问:
htaccess rewrite trouble with "fake" folder
Before I ask my question, let me start off by saying that I have a working htaccess rule that is:

```<code>#1.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /good/$1 [L,R=301]
</code>```

and, like I said, this works well.

But, when I try to do this:

```<code>#2.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /funfolder/good/$1 [L,R=301]
</code>```

this doesn't work anymore.

So here comes my question.

If I want to rewrite the following:

```<code>#3.
http://www.mydomain/funfolder/folder2/sheet to
http://www.mydomain/funfolder/fakefolder3/sheet
</code>```

when I write:

```<code>#4.
RewriteRule ^funfolder/folder2/sheet$ /funfolder/fakefolder3/sheet?&%{QUERY_STRING}
</code>```

or

```<code>#5.
RewriteCond %{THE_REQUEST} ^GET\ /funfolder/folder2/
RewriteRule ^funfolder/folder2/(.*) /funfolder/fakefolder3/$1 [L,R=301]
</code>```

it is not working.  I do not see the content i want to see.

If I

```<code>#6.
Redirect 301 /funfolder/folder2  http://www.mydomain/funfolder/fakefolder3
</code>```

The redirect works but not the content.

I don't know if it helps but funfolder isn't a real folder.  Neither are folder2 or fakefolder3.  The CMS (joomla), however, generates the folder2 and funfolder.  but I want to add the fakefolder3.

I also though of moving the order of the above rules since there are other rewrite rules.  But, it did not produce any difference.

what I don't understand, is why the #1 works and the #2 doesn't.  I'm thinking that if I can understand the reason, it might also give me the answer to how to do #3. with a slithly altered #4 or altered a #5

Then I can always add a #6 if I need to.

this make any sence?  anyone know why I can't get #2 to work (and thus, my real problem), how to get #3 to work trough #4 or #5?

答:
I have part of an answer to my question, although it is not totally what I intended.  I wanted an answer with htaccess, which I did not find, but I found a solution within the CMS.

I created an invisible menu pointing to the working link and then I used that new invisible menu item and pointed a new visible menu item on it.  That had the results I wanted/needed.  The new visible link (alias) was made to fit the need.

I'm still looking for a solution with pure htaccess..... but till I find it, at least I have somehting that works.

Body:
Before I ask my question, let me start off by saying that I have a working htaccess rule that is:

#1.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /good/$1 [L,R=301]

and, like I said, this works well.

But, when I try to do this:

#2.
RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /funfolder/good/$1 [L,R=301]

this doesn't work anymore.

So here comes my question.

If I want to rewrite the following:

#3.
http://www.mydomain/funfolder/folder2/sheet to
http://www.mydomain/funfolder/fakefolder3/sheet

when I write:

#4.
RewriteRule ^funfolder/folder2/sheet$ /funfolder/fakefolder3/sheet?&%{QUERY_STRING}

or

#5.
RewriteCond %{THE_REQUEST} ^GET\ /funfolder/folder2/
RewriteRule ^funfolder/folder2/(.*) /funfolder/fakefolder3/$1 [L,R=301]

it is not working.  I do not see the content i want to see.

If I

#6.
Redirect 301 /funfolder/folder2  http://www.mydomain/funfolder/fakefolder3

The redirect works but not the content.

I don't know if it helps but funfolder isn't a real folder.  Neither are folder2 or fakefolder3.  The CMS (joomla), however, generates the folder2 and funfolder.  but I want to add the fakefolder3.

I also though of moving the order of the above rules since there are other rewrite rules.  But, it did not produce any difference.

what I don't understand, is why the #1 works and the #2 doesn't.  I'm thinking that if I can understand the reason, it might also give me the answer to how to do #3. with a slithly altered #4 or altered a #5

Then I can always add a #6 if I need to.

this make any sence?  anyone know why I can't get #2 to work (and thus, my real problem), how to get #3 to work trough #4 or #5?


来源: stackexchange

问:
PHP and MySQLi - Upload Multiple Image
I am planning to make an image galary using PHP with MySQL as a database.

I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.

Here is my code :

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
    if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
    }

    $connect->close();}
?>

</body>
</html>
</code>```

Can someone help me ? Thanks for ur feedback :)

答:
Move the header location redirect outside the for loop.
Also Refer Upload multiple images and store their path in database.

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (`file`,`path`,`type`) VALUES ('$filename','$filepath','$filetype')";
    $connect->query($sql);

    }
if($connect->query($sql) === TRUE) {
header("Location: a.php");
exit; // always add exit after header Location:
} else {
header("Location: a.php");
exit;  // always add exit after header Location:
}
    $connect->close();}
?>

</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP and MySQLi - Upload Multiple Image

Body:
I am planning to make an image galary using PHP with MySQL as a database.

I already make a multiple upload images using PHP but I got a problem. When I uploaded 8 images in database only show 1 row data. But in folder there are 8 images that I have upload.

Here is my code :

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (file,path,type) VALUES ('$filename','$filepath','$filetype')";
    if($connect->query($sql) === TRUE) {
header("Location: a.php");
} else {
header("Location: a.php");
}
    }

    $connect->close();}
?>

Can someone help me ? Thanks for ur feedback :)

Body:
Move the header location redirect outside the for loop.
Also Refer Upload multiple images and store their path in database.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>

<form action="a.php" method="post" enctype="multipart/form-data">
<input type="file" name="file_img[]" multiple>
<input type="submit" name="btn_upload" value="Upload">
</form>

<?php
include_once 'koneksi.php';
if(isset($_POST['btn_upload']))
{
    for($i = 0; $i < count($_FILES['file_img']['name']); $i++)
    {
        $filetmp = $_FILES["file_img"]["tmp_name"][$i];
        $filename = $_FILES["file_img"]["name"][$i];
        $filetype = $_FILES["file_img"]["type"][$i];
        $filepath = "uploads/".$filename;

    move_uploaded_file($filetmp,$filepath);

    $sql = "INSERT INTO files (`file`,`path`,`type`) VALUES ('$filename','$filepath','$filetype')";
    $connect->query($sql);

    }
if($connect->query($sql) === TRUE) {
header("Location: a.php");
exit; // always add exit after header Location:
} else {
header("Location: a.php");
exit;  // always add exit after header Location:
}
    $connect->close();}
?>

</body>
</html>


问:
Rails: custom wrapper for submit button in simple_form?
I am using simple_form gem with bootstrap 3.
I want to have a wrapper for submit button

Now it shows HTML as

```<code><form id="new_order" ...>
    ...

   <input class="btn btn-primary" type="submit" value="Save" name="commit">
</form>
</code>```

I want to write a wrapper so the HTML would be:

```<code><form id="new_order" ...>
  ...

  <div class="form-group">
     <div class="col-sm-offset-2 col-sm-10">
        <input class="btn btn-primary" type="submit" value="Save" name="commit">
     </div>
 </div>
</code>```

I got this so far:

app/initializers/simple_form_bootstrap.rb:

```<code>options[:wrapper] = :horizontal_form
options[:wrapper_mappings] = {
  check_boxes: :horizontal_radio_and_checkboxes,
  radio_buttons: :horizontal_radio_and_checkboxes,
  file: :horizontal_file_input,
  boolean: :horizontal_boolean,

 # what to write here??
 # submit: :horizontal_submit_button

}
</code>```

and this is my wrapper:

```<code>  config.wrappers :horizontal_submit_button, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
     b.use :html5
     b.use :placeholder

     b.wrapper tag: 'div', class: 'col-sm-offset-2 col-sm-10' do |ba|
       ba.use :input
       # some coe goes here, maybe
     end
  end
</code>```

Which input type to use in wrapper_mappings for submit button? How to write that wrapper?

答:
Apparently it is not possible to have a wrapper for buttons using simple_form. I wanted to do the same thing and the solution I found was to replace

```<code>config.button_class = 'btn'
</code>```

with

```<code>config.button_class = 'myclass1 myclass2'
</code>```

in the config/initializers/simple_form.rb file. The problem is that it will be the default for all form buttons.

Body:
I am using simple_form gem with bootstrap 3.
I want to have a wrapper for submit button

Now it shows HTML as

<form id="new_order" ...>
    ...

   <input class="btn btn-primary" type="submit" value="Save" name="commit">
</form>

I want to write a wrapper so the HTML would be:

<form id="new_order" ...>
  ...

        <input class="btn btn-primary" type="submit" value="Save" name="commit">

I got this so far:

app/initializers/simple_form_bootstrap.rb:

options[:wrapper] = :horizontal_form
options[:wrapper_mappings] = {
  check_boxes: :horizontal_radio_and_checkboxes,
  radio_buttons: :horizontal_radio_and_checkboxes,
  file: :horizontal_file_input,
  boolean: :horizontal_boolean,

 # what to write here??
 # submit: :horizontal_submit_button

}

and this is my wrapper:

  config.wrappers :horizontal_submit_button, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
     b.use :html5
     b.use :placeholder

     b.wrapper tag: 'div', class: 'col-sm-offset-2 col-sm-10' do |ba|
       ba.use :input
       # some coe goes here, maybe
     end
  end

Which input type to use in wrapper_mappings for submit button? How to write that wrapper?

Body:
Apparently it is not possible to have a wrapper for buttons using simple_form. I wanted to do the same thing and the solution I found was to replace

config.button_class = 'btn'

with

config.button_class = 'myclass1 myclass2'

in the config/initializers/simple_form.rb file. The problem is that it will be the default for all form buttons.


问:
if a number is divisible by all the entries of a list then
This came up while attempting Problem 5 of Project Euler, I'm sorry if this is vague or obvious I am new to programming.

Suppose I have a list of integers

v = range(1,n) = [1, ..., n]

What I want to do is this:

if m is divisible by all the entries of v then I want to set

m/v[i]  for i starting at 2 and iterating up

then I want to keep repeating this process until I eventually get something which is not divisible by all the entries of v.

Here is a specific example:

let v=[1,2,3,4] and m = 24

m is divisible by 1, 2, 3, and 4, so we divide m by 2 giving us

m=12 which is divisible by 1, 2, 3, and 4 , so we divide by 3

giving us m=4 which is not divisible by 1, 2, 3, and 4. So we stop here.

Is there a way to do this in python using a combination of loops?

答:
I think this code will solve your problem:</p>

```<code>i=1
while(True):
    w=[x for x in v if (m%x)==0]
    if(w==v):
        m/=v[i]
        i+=1
        continue
    elif(m!=v):
        break
</code>```

Body:
I think this code will solve your problem:

i=1
while(True):
    w=[x for x in v if (m%x)==0]
    if(w==v):
        m/=v[i]
        i+=1
        continue
    elif(m!=v):
        break


问:
node js, browser cache and 304 response
I am designing a single page app with a normal html layout like so:

```<code><html>
  <head>
    <title>...</title>
    <link rel="stylesheet" media="all" type="text/css" href="css/main.css">
    ...more meta tags
  </head>
  <body>
    <!--body generated with templates-->
    <script src="js/main.js"></script>
  </body>
</html>
</code>```

On the node.js server:

```<code>route.get(req, function(url, type, hdr) {
  if (type === 'error') {
    //response 404
  }else if (type === 'page') {
    console.log(url);
    fileSys.stat(url, function(err, stat) {
      if (err) {
        res.statusCode = 404;
        res.setHeader("Content-Type","text/plain");
        res.write("404 Not Found");
        res.end();
      }else {
        var file,
        headers = {},
        modif = req.headers['if-modified-since'];
        if (modif && new Date(modif).getTime() === stat.mtime.getTime()) { //STATUS 304
          headers = {
            'Last-Modified': stat.mtime.toUTCString(),
            'Date': new Date().toUTCString()
          };
          res.writeHead(304, headers);
          res.end();
        }else { //STATUS 200
          if (path.extname(url) === '.jpg' || path.extname(url) === '.png')
            file = fileSys.readFileSync(url);
          else {
            if (fileSys.statSync(url).isDirectory())
              url += '/index.html';
            file = fileSys.readFileSync(url, 'binary');
          }
          headers = {
            'Last-Modified': stat.mtime.toUTCString(),
            'Content-Length': stat.size,
            'Cache-Control': 'public, max-age=31536000',
            'ETag': url+'_'+stat.mtime.getTime(),
            'Date': new Date().toUTCString()
          };
          var contentType = contentExtens[path.extname(url)];
          if (contentType)
            headers['Content-Type'] = contentType;
          res.writeHeader(200, headers);
          res.end(file);
        }
      }
    });
  }
});
</code>```

I'm handling the routing without Express and the problem I'm running into is after clearing my Chrome cache, I refresh my index page and server side I'm logging all of the requests which logs the index page, css, js, favicon and all of the images.  But when I reload the index page another time, the only request which comes in is for the index page without its resources.  And in the browser console everything is 304 and loaded from cache.  Is this normal behavior?  If I make some changes to the images or any resource files, I can't compare the mtime since those requests are not being sent.

Also I noticed on Safari all of the resources ARE being sent even after setting the cache, last modified and etag headers.  Am I not understanding how this should work, is this a browser thing or amd I doing something wrong?

答:
I didn't quite understand how caching on the browser works until I read this article and it opened my eyes to the fact that I'm caching everything for a year.  The main page gets requested every time but the page's resources are cached for a year and they will not be requested until the cache is cleared by the user or a year goes by.  So the solution is to either set the Cache Control to no-cache and still set ETag to some value.  In that case a request for each resource will be sent and it's up to you to decide whether anything has been modified.  Or continue to cache for a long period of time but anytime you modify a resource, append some value to it inside the index.html page (ex: main.V4.js or mycss.x845.css).  The browser will encounter this new file name and send a new request for it.

Hope this helps someone, please add something if I got anything wrong!

Title: node js, browser cache and 304 response

Body:
I am designing a single page app with a normal html layout like so:

    <title>...</title>
    <link rel="stylesheet" media="all" type="text/css" href="css/main.css">
    ...more meta tags

On the node.js server:

route.get(req, function(url, type, hdr) {
  if (type === 'error') {
    //response 404
  }else if (type === 'page') {
    console.log(url);
    fileSys.stat(url, function(err, stat) {
      if (err) {
        res.statusCode = 404;
        res.setHeader("Content-Type","text/plain");
        res.write("404 Not Found");
        res.end();
      }else {
        var file,
        headers = {},
        modif = req.headers['if-modified-since'];
        if (modif && new Date(modif).getTime() === stat.mtime.getTime()) { //STATUS 304
          headers = {
            'Last-Modified': stat.mtime.toUTCString(),
            'Date': new Date().toUTCString()
          };
          res.writeHead(304, headers);
          res.end();
        }else { //STATUS 200
          if (path.extname(url) === '.jpg' || path.extname(url) === '.png')
            file = fileSys.readFileSync(url);
          else {
            if (fileSys.statSync(url).isDirectory())
              url += '/index.html';
            file = fileSys.readFileSync(url, 'binary');
          }
          headers = {
            'Last-Modified': stat.mtime.toUTCString(),
            'Content-Length': stat.size,
            'Cache-Control': 'public, max-age=31536000',
            'ETag': url+'_'+stat.mtime.getTime(),
            'Date': new Date().toUTCString()
          };
          var contentType = contentExtens[path.extname(url)];
          if (contentType)
            headers['Content-Type'] = contentType;
          res.writeHeader(200, headers);
          res.end(file);
        }
      }
    });
  }
});

I'm handling the routing without Express and the problem I'm running into is after clearing my Chrome cache, I refresh my index page and server side I'm logging all of the requests which logs the index page, css, js, favicon and all of the images.  But when I reload the index page another time, the only request which comes in is for the index page without its resources.  And in the browser console everything is 304 and loaded from cache.  Is this normal behavior?  If I make some changes to the images or any resource files, I can't compare the mtime since those requests are not being sent.

Also I noticed on Safari all of the resources ARE being sent even after setting the cache, last modified and etag headers.  Am I not understanding how this should work, is this a browser thing or amd I doing something wrong?


问:
Python: appending egrep output into a file
In a Python script, I'm trying to count the number of times {H9,H10...C21,H11} appear in a group of files. I don't need counts for each individual phrase in the set, just a single sum. The filenames are contained in an array named "legend" and are sorted numerically by name.
My best attempt is below:

```<code>for nitem in sorted(legend, key=numericalSort):
    with open(nitem, 'a+') as f:
        with open('block.txt', 'a+') as myfile:
            var5 = 'egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" <%s> %s' %(nitem,myfile)
            os.system(var5)
</code>```

When I run this, I get the following error for each file contained in legend (only one error message included below):

```<code>sh: -c: line 0: syntax error near unexpected token `<'
sh: -c: line 0: `egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" <file00.dat> <open file 'block.txt', mode 'a+' at 0x7f71196ec660>'
</code>```

All I want is to append with egrep within python, but cannot do so.

答:
I found a way: </p>

```<code>for nitem in sorted(legend, key=numericalSort):
    with open(nitem, 'a+') as f:
        var5 = '''egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" %s >> filename.txt''' %(nitem)
        os.system(var5)
</code>```

<p>Using triple quotes and not confusing python append for UNIX append seemed to do the trick. </p>

Body:
In a Python script, I'm trying to count the number of times {H9,H10...C21,H11} appear in a group of files. I don't need counts for each individual phrase in the set, just a single sum. The filenames are contained in an array named "legend" and are sorted numerically by name.
My best attempt is below:

for nitem in sorted(legend, key=numericalSort):
    with open(nitem, 'a+') as f:
        with open('block.txt', 'a+') as myfile:
            var5 = 'egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" <%s> %s' %(nitem,myfile)
            os.system(var5)

When I run this, I get the following error for each file contained in legend (only one error message included below):

sh: -c: line 0: syntax error near unexpected token `<'
sh: -c: line 0: `egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" <file00.dat> <open file 'block.txt', mode 'a+' at 0x7f71196ec660>'

All I want is to append with egrep within python, but cannot do so.

Body:
I found a way:

for nitem in sorted(legend, key=numericalSort):
    with open(nitem, 'a+') as f:
        var5 = '''egrep -c "H9|H10|N71|N61|H32|C81|N91|C51|C61|C41|N11|N31|C21|H11" %s >> filename.txt''' %(nitem)
        os.system(var5)

Using triple quotes and not confusing python append for UNIX append seemed to do the trick.


问:
How do you reference a bitmap on the stage in actionscript?
How do you reference a bitmap on the stage in flash using actionscript 3?

I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.

```<code>layer 5 : mask2:MovieClip
layer 4 : img2:Bitmap
layer 3 : mask1:MovieClip
layer 2 : img1:Bitmap
layer 1 : background:Bitmap
</code>```

at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.

but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?

The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.

Any help would be appreciated.

EDIT:

@81bronco , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what vanhornRF suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.

答:
I would probably do something like this in your document class

```<code>for(var i:int=0; i<numChildren; i++){
    trace(getChildAt(i),"This is the child at position "+i);
}
</code>```

I do this because I still code in the flash IDE and its debugger is so very painful to get working most of the time it's easier to just trace variables out, so you can either use that for loop to print the object names of the items currently on your stage, or use a debugger program to find the objects as well.

Now that you have the children and at what index they actually are at within the stage, you can reference them by calling getChildAt(int), you can removeChildAt(int), you can addChildAt(displayObject, int) and swapChildrenAt(int, int). The int in these arguments would represent the index position that was returned by your trace statement and the displayObject would obviously just represent anything you wanted to add to the stage or parent DisplayObject.

Using those 4 commands you should be able to freely re-arrange any movieclips you have on stage so that they will appear to transition seamlessly.

@81bronco One should definitely name your assets on stage if you want to uniquely reference them specifically to avoid any confusion if there ends up being a lot of items on stage

Body:
How do you reference a bitmap on the stage in flash using actionscript 3?

I have a bitmap on the stage in flash and at the end of the movie I would like to swap it out for the next in the sequence before the movie loops. in my library i have 3 images, exported for actionscript, with the class name img1/img2/img3. here is how my layers in flash are set out.

layer 5 : mask2:MovieClip
layer 4 : img2:Bitmap
layer 3 : mask1:MovieClip
layer 2 : img1:Bitmap
layer 1 : background:Bitmap

at the end of the movie I would like to swap img1 with img2, so the movie loops seamlessly, then ideally swap img2 (on layer 4) with img3 and so on until I get to the end of my images.

but I can not find out how to reference the images that have already been put on the stage (in design time), any one have any idea of how to do this?

The end movie will hopefully load images dynamically from the web server (I have the code for this bit) and display them as well as img1/img2/img3.

Any help would be appreciated.

EDIT:

@81bronco , I tried this but the instance name is greyed out for graphics, it will only allow me to do it with movieclips and buttons. I half got it to work by turning them into moveclips, and clearing the images in the moveclip out before adding a new one (using something simpler to what vanhornRF suggested), but for some odd reason when the mask kicks in the images I cleared out come back for the mask animation.

Body:
I would probably do something like this in your document class

for(var i:int=0; i<numChildren; i++){
    trace(getChildAt(i),"This is the child at position "+i);
}

I do this because I still code in the flash IDE and its debugger is so very painful to get working most of the time it's easier to just trace variables out, so you can either use that for loop to print the object names of the items currently on your stage, or use a debugger program to find the objects as well.

Now that you have the children and at what index they actually are at within the stage, you can reference them by calling getChildAt(int), you can removeChildAt(int), you can addChildAt(displayObject, int) and swapChildrenAt(int, int). The int in these arguments would represent the index position that was returned by your trace statement and the displayObject would obviously just represent anything you wanted to add to the stage or parent DisplayObject.

Using those 4 commands you should be able to freely re-arrange any movieclips you have on stage so that they will appear to transition seamlessly.

@81bronco One should definitely name your assets on stage if you want to uniquely reference them specifically to avoid any confusion if there ends up being a lot of items on stage

OwnerDisplayName: vanhornRF

ContentLicense: CC BY-SA 2.5


问:
Why are string in .net case sensitive by default?
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

```<code>"John Smith" == "JOHN SMITH"
</code>```

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords

答:
your case is not necessarily the most common case, a very common case is to match words in a document against grammar conditions, in that case case sensitivity is an absolute must.

Note matching in a case in-sensitive fashion is trivially easy. In fact the equals method of a string has an overload specifically for specifying how to compare.

Body:
Most times I want to do string comparisons I want them to be case insensitive.

So why are string in .net case sensitive by default?

EDIT 1: To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.

"John Smith" == "JOHN SMITH"

EDIT 2: I can think of many more examples of things that should be case insensitive

Examples of things that should be case insensitive

Usernames

Urls

File extensions / File names / Directory names / Paths

Machine / servernames

State / Country / Location etc

FirstName / LastName / Initials

Guids

Month / Day names

Examples of things that should be case sensitive

Passwords


问:
save google charts as image on php server
I had created a google chart which fetches data from MySQL. I would like to save it as image to my PHP server automatically whenever the chart renders. I had been through some code which prints chart as png image .But I don't know how to save it in PHP server .Can anyone help me out?

Here is my code which renders chart from MYSQL:

```<code><html>
<head>
<title>Google Charts </title>
        <script src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">

 google.charts.load('current', {packages: ['corechart']});
    google.charts.setOnLoadCallback(drawChart);

<?php
$sql = mysql_connect("localhost","root","");
if(!$sql)
{
    echo "Connection Not Created";
}
$con = mysql_select_db("PRJ");
if(!$sql)
{
    echo "Database Not Connected";
}
$sql = "select * from LF";
$result = mysql_query($sql);

$count=0;
while($row = mysql_fetch_array($result))
{
$a[]=$row['x'];
$b[]=$row['y'];
$count++;
 }

$tot=0;
$toty=0;
$xsqtot=0;
$ysqtot=0;
$xytot=0;

for($i=0;$i<$count;$i++)
{
$tot=$tot+$a[$i];
$toty=$toty+$b[$i];
$xpow[]=$a[$i]*$a[$i];
$ypow[]=$b[$i]*$b[$i];
$xsqtot=$xsqtot+$xpow[$i];
$ysqtot=$ysqtot+$ypow[$i];
$product[]=$a[$i]*$b[$i];
$xytot=$xytot+$product[$i];
}
$p=(($tot*$toty)-($count*$xytot))/(($tot*$tot)-($count*$xsqtot));
$q=(($xytot*$tot)-($xsqtot*$toty))/(($tot*$tot)-($count*$xsqtot));

for($i=0;$i<$count;$i++)
{
$cfy[]=($p*$a[$i])+$q;
}
$ct=sizeof($a);

?>

var x=new Array();
<?php

for($i=0;$i<$count;$i++){

                     echo "x[$i]=".$a[$i].";\n";}

             ?>
var y=new Array();
<?php

for($i=0;$i<$count;$i++){

                     echo "y[$i]=".$b[$i].";\n";}

             ?>
var z=new Array();
<?php

for($i=0;$i<$count;$i++){

                     echo "z[$i]=".$cfy[$i].";\n";}

             ?>
function drawChart()
{
   var data = new google.visualization.DataTable();
   data.addColumn('number', 'independent');
   data.addColumn('number', 'dependent');
   data.addColumn('number', 'TRENDLINE');

for(var i=0;i<x.length;i++)
{
   data.addRows([[x[i],y[i],z[i]]]);
}

     var options = {'title':'LAT VS LONG ',
 vAxis: {title: 'X'},
      hAxis: {title: 'Y'},
      'width':550,
      'height':400,
seriesType:'scatter',
 series: {1: {type: 'line'}},
};

   var curve_chart = document.getElementById('curve_chart');
var chart=new google.visualization.ColumnChart(curve_chart);
google.visualization.events.addListener(chart, 'ready', function () {
        curve_chart.innerHTML = '<img src="' + chart.getImageURI() + '">';
        console.log(curve_chart.innerHTML);
      });
   chart.draw(data, options);
}

</script>

</head>
<body>
    <div id="curve_chart" style="width: 900px; height: 500px;"></div>
 </body>
</html>
</code>```

答:
inside the 'ready' event, post the image string back to the server...

```<code>google.visualization.events.addListener(chart, 'ready', function () {
  $.ajax({
    type: 'POST',
    url: 'saveImage.php',
    data: {
      // send image string as data
      imgStr: chart.getImageURI()
    },
  }).success(function(response) {
    console.log('image saved');
  });
});
</code>```

then in php, get the image string from the post and save it...

```<code>$imgStr = $_POST['imgStr'];
</code>```

the post field name needs to match the key used when sending the data

js

```<code>imgStr: chart.getImageURI()  // <-- imgStr
</code>```

php

```<code>$imgStr = $_POST['imgStr'];  // <-- post field name 'imgStr'
</code>```

Body:
I had created a google chart which fetches data from MySQL. I would like to save it as image to my PHP server automatically whenever the chart renders. I had been through some code which prints chart as png image .But I don't know how to save it in PHP server .Can anyone help me out?

Here is my code which renders chart from MYSQL:

<title>Google Charts </title>

Body:
inside the 'ready' event, post the image string back to the server...

google.visualization.events.addListener(chart, 'ready', function () {
  $.ajax({
    type: 'POST',
    url: 'saveImage.php',
    data: {
      // send image string as data
      imgStr: chart.getImageURI()
    },
  }).success(function(response) {
    console.log('image saved');
  });
});

then in php, get the image string from the post and save it...

$imgStr = $_POST['imgStr'];

the post field name needs to match the key used when sending the data

js

imgStr: chart.getImageURI()  // <-- imgStr

php

$imgStr = $_POST['imgStr'];  // <-- post field name 'imgStr'


问:
Change 1px border color to custom color instead of accent color in Windows 10
Windows 10 draws this 1px border in the accent color around most windows including the window of our WPF app or as seen here cmd.exe:

But Visual Studio (which is also WPF) has changed that to fit its status bar color:

We would like to do the same, but I found nothing on how we can do this for WPF.

Does anybody know how this can be done?

答: I believe you would need to add a window proc function to your window and handle the WM_NCPAINT message. This is similar to what's done in this code project article: Class for drawing a flat color border though he's doing it on child controls, the principle is the same for top-level windows. </p>


问:
Html - Get value from database
So I want to get the titlefor that image in the database. How do I do it? It's showing Describe your post... for all images instead of the actual title of the image in the database

https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

View:

```<code>    @foreach (var image in Model.Images)
{
    <h2>@Html.LabelFor(m => m.title)</h2>
    <div class="row">
        <div class="col-md-8 portfolio-item">
            <img class="portrait" src="@Url.Content(image)" alt="Hejsan" />
        </div>
    </div>

}
</code>```

Model

```<code> [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}
</code>```

答:
Remove the display attribute.

```<code>[Required]
public string title { get; set; }
</code>```

Also, LabelFor() is not the right thing. You may want to use Display/DisplayFor() to render the value.

Title: Html - Get value from database

Body:
So I want to get the titlefor that image in the database. How do I do it? It's showing Describe your post... for all images instead of the actual title of the image in the database

https://i.gyazo.com/17828889116a77983f70fd8c8a4c2ebf.png

View:

    @foreach (var image in Model.Images)
{

@Html.LabelFor(m => m.title)

}

Model

 [Table("MemeImages")]
public class UploadFileModel
{
    [Key]
    [DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
    public int id { get; set; }

    public string location { get; set; }

    public IEnumerable<string> Images { get; set; }

    public int contentLength { get; set; }
    public string contentType { get; set; }

    public string userID { get; set; }

    [Required]
    [Display(Name = "Describe your post...")]
    public string title { get; set; }

    public void SavetoDatabase(UploadFileModel file)
    {
        ApplicationDbContext db = new ApplicationDbContext();
        db.uploadedFiles.Add(file);
        db.SaveChanges();
    }
}

Body:
Remove the display attribute.

[Required]
public string title { get; set; }

Also, LabelFor() is not the right thing. You may want to use Display/DisplayFor() to render the value.


问:
React / Material UI - <CardHeader> css
Using React & Material UI I'm trying to layout 3 divs within a <Card> <CardHeader/> such that it has a left, center and right alignment respectively as shown below.

The change is trivial, I need to remove the padding and change to display: inherit but it seems this
 exists between the exposed style & titleStyle for <CardHeader> and <CardHeader title={someElement}/>

The hierarchy looks like:

...

<myTitleElement>...

Being so new to React and styles, I'm unsure how to get to it.
Some representative code follows.

Thanks for help.

```<code>// @flow
import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';

const style = {
  paper: {
    height: 250,
    width: 200,
    margin: 20,
  },
  card: {
    header: {
      container: {
        display: 'flex',               /* establish flex container */
        justifyContent: 'space-between',
        backgroundColor: 'lightblue'
      },
      padding: 1,
      height: 26
    }
  }
};

const POCardTitle = () => (
  <div className="myContainer" style={style.card.header.container}>
    <div style={{ width: 25, height: 26, border: '2px dashed red' }}> - </div>
    <div style={{ width: 25, height: 26, border: '2px dashed blue' }}> - </div>
    <div style={{ width: 25, height: 26, border: '2px dashed green' }}> - </div>
  </div>
);

export default class POCard extends Component {

  render() {
    return (
      <div>
        <Paper style={style.paper} zDepth={2} >
          <Card >
            <CardHeader className="myCardHeader"
              style={style.card.header}
              titleStyle={{ paddingRight: 0, display: 'inline' }}
              title={<POCardTitle />}
            />
          </Card>
        </Paper>
      </div>
    );
  }
}
</code>```

答:
I managed to get there courtesy of https://www.styled-components.com

and the following:

```<code>const StyledHeader = styled(CardHeader) `
  padding: 0px !important;
  height: 26px !important;
  > div {
    display: inherit !important;
    padding-right: 0px !important;
  }
`;
</code>```

I could find no other way to get to the "first div" after the component through regular CSS...

Title: React / Material UI - <CardHeader> css

Body:
Using React & Material UI I'm trying to layout 3 divs within a <Card> <CardHeader/> such that it has a left, center and right alignment respectively as shown below.

The change is trivial, I need to remove the padding and change to display: inherit but it seems this
 exists between the exposed style & titleStyle for <CardHeader> and <CardHeader title={someElement}/>

The hierarchy looks like:

...

<myTitleElement>...

Being so new to React and styles, I'm unsure how to get to it.
Some representative code follows.

Thanks for help.

// @flow
import React, { Component } from 'react';
import Paper from 'material-ui/Paper';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';

const style = {
  paper: {
    height: 250,
    width: 200,
    margin: 20,
  },
  card: {
    header: {
      container: {
        display: 'flex',               /* establish flex container */
        justifyContent: 'space-between',
        backgroundColor: 'lightblue'
      },
      padding: 1,
      height: 26
    }
  }
};

const POCardTitle = () => (

 -

 -

 -

);

export default class POCard extends Component {

  render() {
    return (

        <Paper style={style.paper} zDepth={2} >
          <Card >
            <CardHeader className="myCardHeader"
              style={style.card.header}
              titleStyle={{ paddingRight: 0, display: 'inline' }}
              title={<POCardTitle />}
            />
          </Card>
        </Paper>

    );
  }
}

Body:
I managed to get there courtesy of https://www.styled-components.com

and the following:

const StyledHeader = styled(CardHeader) `
  padding: 0px !important;
  height: 26px !important;
  > div {
    display: inherit !important;
    padding-right: 0px !important;
  }
`;

I could find no other way to get to the "first div" after the component through regular CSS...


问:
Using gdb info malloc command within xcode (iphone dev)
I'm playing with gdb within xcode debugging an iphone app.

Supposedly, I should be able to use the following command:

```<code>info malloc <0xaddress>
</code>```

see
http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/
 and strange GDB error unable to trace

I have env vars MallocStackLoggingNoCompact = 1 and NSZombieEnabled = YES set (via the executable in xcode).

However, I am getting this:

```<code>2010-10-03 21:29:01.366 memleaktest[10881:307] *** -[one release]: message sent to deallocated instance 0x1646b0
(gdb) info malloc 0x1646b0
Undefined info command: "malloc 0x1646b0".  Try "help info".
</code>```

What am I missing to run this command? (xcode 3.2.4 and iphone SDK 4.1)

答:
In Xcode go to Run -> Enable Guard Malloc

Set environment variable MallocStackLoggingNoCompact to YES (as you already did)

to make sure the logs are being written, in the debugger console you should see this message:

```<code>malloc: stack logs being written into /tmp/stack-logs.xxxx.MyApp.xxxxxx.index
</code>```

Now you should be able to:

```<code>(gdb) info malloc 0x1646b0
</code>```

Body:
I'm playing with gdb within xcode debugging an iphone app.

Supposedly, I should be able to use the following command:

info malloc <0xaddress>

see
http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/
 and strange GDB error unable to trace

I have env vars MallocStackLoggingNoCompact = 1 and NSZombieEnabled = YES set (via the executable in xcode).

However, I am getting this:

2010-10-03 21:29:01.366 memleaktest[10881:307] *** -[one release]: message sent to deallocated instance 0x1646b0
(gdb) info malloc 0x1646b0
Undefined info command: "malloc 0x1646b0".  Try "help info".

What am I missing to run this command? (xcode 3.2.4 and iphone SDK 4.1)

Body:
In Xcode go to Run -> Enable Guard Malloc

Set environment variable MallocStackLoggingNoCompact to YES (as you already did)

to make sure the logs are being written, in the debugger console you should see this message:

malloc: stack logs being written into /tmp/stack-logs.xxxx.MyApp.xxxxxx.index

Now you should be able to:

(gdb) info malloc 0x1646b0


问:
Change drawer gap between header group and first item menu
I need change the space between header group and first item menu, here's an example:

I have seen a lot of examples and posts but only be can change the space for all items, and I just need to change only for header group.

Any idea?

答: In my experience, the best way to handle nav drawer is to have it display a full Fragment. This allows you to have a total control of its layout and behavior.


问:
Including and excluding files with lftp mirror
I have an ftp server and I would like to only download the files matching a certain pattern. These files are in a nested directory tree. This is what I did:

```<code>lftp -c 'open -e "mirror --parallel=8 -i .*abc\.zip . localmirrordir" http://site.ftp.com/'
</code>```

This command downloads in the localmirrordir only the files matching the regex. But the issue is that this commandline does a full scan of the all the directories on the server every time it is run.

I was hoping to cut down on that time and my hope was to only inspect those paths on the server that match the regex. How can I do that ?

Additionally can you tell me why this command fails to fetch anything from the server at all:

```<code>lftp -c 'open -e "mirror --parallel=8 -x .* -x .*/ -i .*abc\.zip . localmirrordir" http://site.ftp.com/'
</code>```

答: You can explicitly exclude directories you don't want to scan. When the first pattern is including, then lftp excludes all files first, but includes all directories. Last matching pattern provides the resolution about each file or directory. Directories are matched with a slash appended. </p>

Body:
I have an ftp server and I would like to only download the files matching a certain pattern. These files are in a nested directory tree. This is what I did:

lftp -c 'open -e "mirror --parallel=8 -i .*abc\.zip . localmirrordir" http://site.ftp.com/'

This command downloads in the localmirrordir only the files matching the regex. But the issue is that this commandline does a full scan of the all the directories on the server every time it is run.

I was hoping to cut down on that time and my hope was to only inspect those paths on the server that match the regex. How can I do that ?

Additionally can you tell me why this command fails to fetch anything from the server at all:

lftp -c 'open -e "mirror --parallel=8 -x .* -x .*/ -i .*abc\.zip . localmirrordir" http://site.ftp.com/'


问:
Reversing an audio file
I'm using AVAssetReader and AVAssetWriter to reverse an audio file. However, the resulting reversed audio is very jerky.

What's the best practice for reversing an audio file?

Any help is much appreciated.

```<code>-(void)reverseAudio:(NSURL *)videoURL andVideoAsset:(AVURLAsset *)videoAsset{

AVAssetReader *video2AssetReader = [[AVAssetReader alloc] initWithAsset:videoAsset error:nil];
video2AssetReader.timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, [videoAsset duration]);

NSArray *audioTracks = [videoAsset tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack* audioTrack = [audioTracks objectAtIndex:0];

NSDictionary *outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                                    [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved,
                                    nil];

AVAssetReaderTrackOutput *readerAudioTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:outputSettingsDict];
[video2AssetReader addOutput:readerAudioTrackOutput];

[video2AssetReader startReading];

// read in the samples
NSMutableArray *audioSamples = [[NSMutableArray alloc] init];

CMSampleBufferRef audioSample;

while((audioSample = [readerAudioTrackOutput copyNextSampleBuffer])){
    [audioSamples addObject:(__bridge id)audioSample];

    CFRelease(audioSample);
}

videoReverseProcess3TotalFrames = audioSamples.count;
NSLog(@"AUDIO SAMPLES COUNT = %f", videoReverseProcess3TotalFrames);

[video2AssetReader cancelReading];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *videoPath = [documentsDirectory stringByAppendingPathComponent:@"videoReverseAudioFile.m4a"];
NSError *error = nil;
if([[NSFileManager defaultManager] fileExistsAtPath:videoPath]){
    [[NSFileManager defaultManager] removeItemAtPath:videoPath error:&error];
    if(error){
        NSLog(@"VIDEO DELETE FAILED");
    }
    else{
        NSLog(@"VIDEO DELETED");

    }
}

NSURL *audioExportURL = [[NSURL alloc] initFileURLWithPath:videoPath];

AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:audioExportURL fileType:AVFileTypeAppleM4A error:&error];

AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
NSDictionary *audioCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                          [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                          [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                          [NSNumber numberWithInt:128000], AVEncoderBitRateKey,
                                          [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey, nil];

AVAssetWriterInput *writerAudioInput;

writerAudioInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio outputSettings:audioCompressionSettings];
writerAudioInput.expectsMediaDataInRealTime = NO;

if([writer canAddInput:writerAudioInput]){
    [writer addInput:writerAudioInput];
}
else{
    NSLog(@"ERROR ADDING AUDIO");
}

[writer startWriting];

CMTime timeStamp = CMSampleBufferGetPresentationTimeStamp((__bridge CMSampleBufferRef)audioSamples[0]);
[writer startSessionAtSourceTime:timeStamp];

while(audioSamples.count > 0){
    if(writer && writerAudioInput.readyForMoreMediaData){
        CMSampleBufferRef audioBufferRef = (__bridge CMSampleBufferRef)audioSamples[audioSamples.count - 1];

        [writerAudioInput appendSampleBuffer:audioBufferRef];

        [audioSamples removeObjectAtIndex:audioSamples.count - 1];
    }
    else{
        [NSThread sleepForTimeInterval:0.2];
    }
}

if(writer.status != AVAssetWriterStatusCancelled){
    [writerAudioInput markAsFinished];
    [writer finishWritingWithCompletionHandler:^{

    }];
}
</code>```

}

答:
You are not reversing audio, you just reversing audio fragments (buffers) order.

So you have this input: S1, S2, S3, S4 and you produce following output: S4, S3, S2, S1. But inside this fragments you still have original order of frames.

You need to reverse buffer data too.

Update #1

Here is example how you can do this.

```<code>- (void)reverseAudio:(AVURLAsset *)videoAsset {

    AVAssetReader *video2AssetReader = [[AVAssetReader alloc] initWithAsset:videoAsset error:nil];
    video2AssetReader.timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, [videoAsset duration]);

    NSArray *audioTracks = [videoAsset tracksWithMediaType:AVMediaTypeAudio];
    AVAssetTrack* audioTrack = [audioTracks objectAtIndex:0];

    NSDictionary *outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                                        [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved,
                                        nil];

    AVAssetReaderTrackOutput *readerAudioTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:outputSettingsDict];
    [video2AssetReader addOutput:readerAudioTrackOutput];

    [video2AssetReader startReading];

    // read in the samples
    CMTime timeStamp = kCMTimeInvalid;

    NSMutableArray *audioSamples = [[NSMutableArray alloc] init];
    CMSampleBufferRef audioSample;
    while ((audioSample = [readerAudioTrackOutput copyNextSampleBuffer])) {
        [audioSamples addObject:(__bridge id)[self reverseSampleBuffer:audioSample]];

        if (CMTIME_IS_INVALID(timeStamp)) {
            timeStamp = CMSampleBufferGetPresentationTimeStamp(audioSample);
        }

        CFRelease(audioSample);
    }

    NSLog(@"AUDIO SAMPLES COUNT = %d", (int)audioSamples.count);

    [video2AssetReader cancelReading];

    // rest of the code
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *videoPath = [documentsDirectory stringByAppendingPathComponent:@"videoReverseAudioFile.m4a"];
    NSError *error = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:videoPath error:&error];
        if (error) {
            NSLog(@"VIDEO DELETE FAILED");
        } else {
            NSLog(@"VIDEO DELETED");
        }
    }

    NSURL *audioExportURL = [[NSURL alloc] initFileURLWithPath:videoPath];

    AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:audioExportURL fileType:AVFileTypeAppleM4A error:&error];

    AudioChannelLayout channelLayout;
    memset(&channelLayout, 0, sizeof(AudioChannelLayout));
    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
    NSDictionary *audioCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                              [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                              [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                              [NSNumber numberWithInt:128000], AVEncoderBitRateKey,
                                              [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey, nil];

    AVAssetWriterInput *writerAudioInput;

    writerAudioInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio outputSettings:audioCompressionSettings];
    writerAudioInput.expectsMediaDataInRealTime = NO;

    if ([writer canAddInput:writerAudioInput]) {
        [writer addInput:writerAudioInput];
    } else {
        NSLog(@"ERROR ADDING AUDIO");
    }

    [writer startWriting];

    [writer startSessionAtSourceTime:timeStamp];

    while (audioSamples.count > 0) {
        if(writer && writerAudioInput.readyForMoreMediaData) {
            CMSampleBufferRef audioBufferRef = (__bridge CMSampleBufferRef)audioSamples[audioSamples.count - 1];

            [writerAudioInput appendSampleBuffer:audioBufferRef];

            [audioSamples removeObjectAtIndex:audioSamples.count - 1];
        } else {
            [NSThread sleepForTimeInterval:0.2];
        }
    }

    if (writer.status != AVAssetWriterStatusCancelled) {
        [writerAudioInput markAsFinished];
        [writer finishWritingWithCompletionHandler:^{

        }];
    }
}

- (CMSampleBufferRef)reverseSampleBuffer:(CMSampleBufferRef)buffer {
    AudioBufferList list;
    CMBlockBufferRef dataBuffer = NULL;
    // TODO check result code
    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(buffer,
                                                            NULL,
                                                            &list,
                                                            sizeof(list),
                                                            NULL,
                                                            NULL,
                                                            kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
                                                            &dataBuffer);

    CMItemCount numberOfSamples = CMSampleBufferGetNumSamples(buffer);
    for (int i = 0; i < list.mNumberBuffers; i++) {
        SInt16 *samples = (SInt16 *)list.mBuffers[i].mData;
        for (int j = 0; j < numberOfSamples / 2; j++) {
            SInt16 t = samples[j];
            samples[j] = samples[numberOfSamples - 1 - j];
            samples[numberOfSamples - 1 - j] = t;
        }
    }

    CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(buffer);
    CMSampleBufferRef result = NULL;
    // TODO check result code
    CMSampleBufferCreate(kCFAllocatorDefault, dataBuffer, true, NULL, NULL, format, 0, 0, NULL, 0, NULL, &result);

    return result;
}
</code>```

Title: Reversing an audio file

Body:
I'm using AVAssetReader and AVAssetWriter to reverse an audio file. However, the resulting reversed audio is very jerky.

What's the best practice for reversing an audio file?

Any help is much appreciated.

-(void)reverseAudio:(NSURL *)videoURL andVideoAsset:(AVURLAsset *)videoAsset{

AVAssetReader *video2AssetReader = [[AVAssetReader alloc] initWithAsset:videoAsset error:nil];
video2AssetReader.timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, [videoAsset duration]);

NSArray *audioTracks = [videoAsset tracksWithMediaType:AVMediaTypeAudio];
AVAssetTrack* audioTrack = [audioTracks objectAtIndex:0];

NSDictionary *outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                                    [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                                    [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved,
                                    nil];

AVAssetReaderTrackOutput *readerAudioTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:outputSettingsDict];
[video2AssetReader addOutput:readerAudioTrackOutput];

[video2AssetReader startReading];

// read in the samples
NSMutableArray *audioSamples = [[NSMutableArray alloc] init];

CMSampleBufferRef audioSample;

while((audioSample = [readerAudioTrackOutput copyNextSampleBuffer])){
    [audioSamples addObject:(__bridge id)audioSample];

    CFRelease(audioSample);
}

videoReverseProcess3TotalFrames = audioSamples.count;
NSLog(@"AUDIO SAMPLES COUNT = %f", videoReverseProcess3TotalFrames);

[video2AssetReader cancelReading];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *videoPath = [documentsDirectory stringByAppendingPathComponent:@"videoReverseAudioFile.m4a"];
NSError *error = nil;
if([[NSFileManager defaultManager] fileExistsAtPath:videoPath]){
    [[NSFileManager defaultManager] removeItemAtPath:videoPath error:&error];
    if(error){
        NSLog(@"VIDEO DELETE FAILED");
    }
    else{
        NSLog(@"VIDEO DELETED");

    }
}

NSURL *audioExportURL = [[NSURL alloc] initFileURLWithPath:videoPath];

AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:audioExportURL fileType:AVFileTypeAppleM4A error:&error];

AudioChannelLayout channelLayout;
memset(&channelLayout, 0, sizeof(AudioChannelLayout));
channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
NSDictionary *audioCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,
                                          [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                          [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                          [NSNumber numberWithInt:128000], AVEncoderBitRateKey,
                                          [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey, nil];

AVAssetWriterInput *writerAudioInput;

writerAudioInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio outputSettings:audioCompressionSettings];
writerAudioInput.expectsMediaDataInRealTime = NO;

if([writer canAddInput:writerAudioInput]){
    [writer addInput:writerAudioInput];
}
else{
    NSLog(@"ERROR ADDING AUDIO");
}

[writer startWriting];

CMTime timeStamp = CMSampleBufferGetPresentationTimeStamp((__bridge CMSampleBufferRef)audioSamples[0]);
[writer startSessionAtSourceTime:timeStamp];

while(audioSamples.count > 0){
    if(writer && writerAudioInput.readyForMoreMediaData){
        CMSampleBufferRef audioBufferRef = (__bridge CMSampleBufferRef)audioSamples[audioSamples.count - 1];

        [writerAudioInput appendSampleBuffer:audioBufferRef];

        [audioSamples removeObjectAtIndex:audioSamples.count - 1];
    }
    else{
        [NSThread sleepForTimeInterval:0.2];
    }
}

if(writer.status != AVAssetWriterStatusCancelled){
    [writerAudioInput markAsFinished];
    [writer finishWritingWithCompletionHandler:^{

    }];
}

}

Body:
You are not reversing audio, you just reversing audio fragments (buffers) order.

So you have this input: S1, S2, S3, S4 and you produce following output: S4, S3, S2, S1. But inside this fragments you still have original order of frames.

You need to reverse buffer data too.

Update #1

Here is example how you can do this.

- (void)reverseAudio:(AVURLAsset *)videoAsset {

    AVAssetReader *video2AssetReader = [[AVAssetReader alloc] initWithAsset:videoAsset error:nil];
    video2AssetReader.timeRange = CMTimeRangeFromTimeToTime(kCMTimeZero, [videoAsset duration]);

    NSArray *audioTracks = [videoAsset tracksWithMediaType:AVMediaTypeAudio];
    AVAssetTrack* audioTrack = [audioTracks objectAtIndex:0];

    NSDictionary *outputSettingsDict = [[NSDictionary alloc] initWithObjectsAndKeys:
                                        [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                                        [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                                        [NSNumber numberWithBool:NO],AVLinearPCMIsNonInterleaved,
                                        nil];

    AVAssetReaderTrackOutput *readerAudioTrackOutput = [AVAssetReaderTrackOutput assetReaderTrackOutputWithTrack:audioTrack outputSettings:outputSettingsDict];
    [video2AssetReader addOutput:readerAudioTrackOutput];

    [video2AssetReader startReading];

    // read in the samples
    CMTime timeStamp = kCMTimeInvalid;

    NSMutableArray *audioSamples = [[NSMutableArray alloc] init];
    CMSampleBufferRef audioSample;
    while ((audioSample = [readerAudioTrackOutput copyNextSampleBuffer])) {
        [audioSamples addObject:(__bridge id)[self reverseSampleBuffer:audioSample]];

        if (CMTIME_IS_INVALID(timeStamp)) {
            timeStamp = CMSampleBufferGetPresentationTimeStamp(audioSample);
        }

        CFRelease(audioSample);
    }

    NSLog(@"AUDIO SAMPLES COUNT = %d", (int)audioSamples.count);

    [video2AssetReader cancelReading];

    // rest of the code
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *videoPath = [documentsDirectory stringByAppendingPathComponent:@"videoReverseAudioFile.m4a"];
    NSError *error = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:videoPath]) {
        [[NSFileManager defaultManager] removeItemAtPath:videoPath error:&error];
        if (error) {
            NSLog(@"VIDEO DELETE FAILED");
        } else {
            NSLog(@"VIDEO DELETED");
        }
    }

    NSURL *audioExportURL = [[NSURL alloc] initFileURLWithPath:videoPath];

    AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:audioExportURL fileType:AVFileTypeAppleM4A error:&error];

    AudioChannelLayout channelLayout;
    memset(&channelLayout, 0, sizeof(AudioChannelLayout));
    channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
    NSDictionary *audioCompressionSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:kAudioFormatMPEG4AAC], AVFormatIDKey,
                                              [NSNumber numberWithFloat:44100.0], AVSampleRateKey,
                                              [NSNumber numberWithInt:2], AVNumberOfChannelsKey,
                                              [NSNumber numberWithInt:128000], AVEncoderBitRateKey,
                                              [NSData dataWithBytes:&channelLayout length:sizeof(AudioChannelLayout)], AVChannelLayoutKey, nil];

    AVAssetWriterInput *writerAudioInput;

    writerAudioInput = [[AVAssetWriterInput alloc] initWithMediaType:AVMediaTypeAudio outputSettings:audioCompressionSettings];
    writerAudioInput.expectsMediaDataInRealTime = NO;

    if ([writer canAddInput:writerAudioInput]) {
        [writer addInput:writerAudioInput];
    } else {
        NSLog(@"ERROR ADDING AUDIO");
    }

    [writer startWriting];

    [writer startSessionAtSourceTime:timeStamp];

    while (audioSamples.count > 0) {
        if(writer && writerAudioInput.readyForMoreMediaData) {
            CMSampleBufferRef audioBufferRef = (__bridge CMSampleBufferRef)audioSamples[audioSamples.count - 1];

            [writerAudioInput appendSampleBuffer:audioBufferRef];

            [audioSamples removeObjectAtIndex:audioSamples.count - 1];
        } else {
            [NSThread sleepForTimeInterval:0.2];
        }
    }

    if (writer.status != AVAssetWriterStatusCancelled) {
        [writerAudioInput markAsFinished];
        [writer finishWritingWithCompletionHandler:^{

        }];
    }
}

- (CMSampleBufferRef)reverseSampleBuffer:(CMSampleBufferRef)buffer {
    AudioBufferList list;
    CMBlockBufferRef dataBuffer = NULL;
    // TODO check result code
    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(buffer,
                                                            NULL,
                                                            &list,
                                                            sizeof(list),
                                                            NULL,
                                                            NULL,
                                                            kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment,
                                                            &dataBuffer);

    CMItemCount numberOfSamples = CMSampleBufferGetNumSamples(buffer);
    for (int i = 0; i < list.mNumberBuffers; i++) {
        SInt16 *samples = (SInt16 *)list.mBuffers[i].mData;
        for (int j = 0; j < numberOfSamples / 2; j++) {
            SInt16 t = samples[j];
            samples[j] = samples[numberOfSamples - 1 - j];
            samples[numberOfSamples - 1 - j] = t;
        }
    }

    CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(buffer);
    CMSampleBufferRef result = NULL;
    // TODO check result code
    CMSampleBufferCreate(kCFAllocatorDefault, dataBuffer, true, NULL, NULL, format, 0, 0, NULL, 0, NULL, &result);

    return result;
}


问:
Using a database to store configuration rather than a configuration file
Unfortunately searching for this kind of material produces a lot of noise for me so I was wondering if anyone here knew of a good resource for anyone wishing to learn how to use a database to store site configuration info rather than a file.

I guess some points I'm interested in are:
1) How to store the data. One array like e107? Separate row for each configurable?
2) How to get the configuration data. Global array?

答:
Consider the following:

SOME configuration will have to be stored in a config file unless you hard code it, notably, how to connect to the database

Databases are bad at storing some types of config data - highly structured stuff, or things with unpredictable or variable structure - and you may end up with a schema which doesn't make a lot of sense

It is much easier to store config files in a SCM system

You can simply replace a config file upon upgrade, you can roll it back if you need to go back. Try doing this with database tables? Even in a best-case scenario, it's harder.

I would generally go for a config file, for small web applications.

Once you get as far as having an infrastructure involving web & non-web servers, putting the config in a centrally-accessible place becomes an advantage though. This doesn't have to be a SQL database, some people use LDAP or even DNS.


问:
How can I get queries in a SQL Server stored procedure text using antrl4 lexer and parser?
I want to get queries in a SQL Server stored procedure text using antrl4 lexer and parser. For example, I have procedure text as follows:

```<code>ALTER PROCEDURE [dbo].[BookUpdate]
    @Name nvarchar(max),
    @BookId int,
    @PublishingHouse nvarchar(255),
    @PublicationYear smallint,
    @Authors nvarchar(255),
    @Description nvarchar(max),
    @BookShelf int,
    @UserId int,
    @Cover varbinary(max),
    @Id int OUT
AS
BEGIN
    DECLARE @haveDouble int = 0
    DECLARE @haveUser int = 1

    SELECT @haveDouble = Id
    FROM dbo.Books
    WHERE Name = @Name
      AND Authors = @Authors
      AND PublicationYear = @PublicationYear
      AND Id != @BookId

    IF @UserId > 0
    BEGIN
        SELECT @haveUser = UserId
        FROM dbo.Users
        WHERE UserId = @UserId
    END

    SET @Id = 0

    IF @haveDouble = 0 AND @haveUser > 0
    BEGIN
        UPDATE dbo.Books
        SET [Name] = @Name,
            [PublishingHouse] = @PublishingHouse,
            [PublicationYear] = @PublicationYear,
            [Authors] = @Authors,
            [Description] = @Description,
            [BookShelf] = @BookShelf,
            [Cover] = @Cover,
            [UserId] = @UserId
        WHERE
            Id = @BookId

        SET @Id = @BookId
    END
END
</code>```

I want to get positions of queries "DECLARE @haveDouble int = 0", "DECLARE @haveUser int = 1" and others. How can I do that?

答:
[1] SQL Server comes with a dedicated API for parsing T-SQL source coude, API included within Microsoft.SqlServer.TransactSql.ScriptDom namespace. This namespace include parsers for every SQL Server version starting with SQL Server 2000 (= TSql80Parser).

[2] Download

[3] You have to find all TSqlStatements having DeclareVariableStatement type (see DeclareVariableStatement Class). This class has following properties (among other properties): StartLine, StartColumn, StartOffset, FirstTokenIndex.

[4] Example:

```<code>using Microsoft.SqlServer.TransactSql.ScriptDom;
....

TSql120Parser SqlParser = new TSql120Parser(false);

IList<ParseError> parseErrors;
TSqlFragment result = SqlParser.Parse(new StringReader(SqlTextBox.Text),
                                      out parseErrors);

TSqlScript SqlScript = result as TSqlScript;

foreach (TSqlBatch sqlBatch in SqlScript.Batches)
{
   foreach (TSqlStatement sqlStatement in sqlBatch.Statements)
   {
      ProcessViewStatementBody(sqlStatement);
   }
}
</code>```

Source: http://www.andriescu.nl/sql/sql-how-to-parse-microsoft-transact-sql-statements-in-c_sharp_view_column_binding/

Body:
I want to get queries in a SQL Server stored procedure text using antrl4 lexer and parser. For example, I have procedure text as follows:

ALTER PROCEDURE [dbo].[BookUpdate]
    @Name nvarchar(max),
    @BookId int,
    @PublishingHouse nvarchar(255),
    @PublicationYear smallint,
    @Authors nvarchar(255),
    @Description nvarchar(max),
    @BookShelf int,
    @UserId int,
    @Cover varbinary(max),
    @Id int OUT
AS
BEGIN
    DECLARE @haveDouble int = 0
    DECLARE @haveUser int = 1

    SELECT @haveDouble = Id
    FROM dbo.Books
    WHERE Name = @Name
      AND Authors = @Authors
      AND PublicationYear = @PublicationYear
      AND Id != @BookId

    IF @UserId > 0
    BEGIN
        SELECT @haveUser = UserId
        FROM dbo.Users
        WHERE UserId = @UserId
    END

    SET @Id = 0

    IF @haveDouble = 0 AND @haveUser > 0
    BEGIN
        UPDATE dbo.Books
        SET [Name] = @Name,
            [PublishingHouse] = @PublishingHouse,
            [PublicationYear] = @PublicationYear,
            [Authors] = @Authors,
            [Description] = @Description,
            [BookShelf] = @BookShelf,
            [Cover] = @Cover,
            [UserId] = @UserId
        WHERE
            Id = @BookId

        SET @Id = @BookId
    END
END

I want to get positions of queries "DECLARE @haveDouble int = 0", "DECLARE @haveUser int = 1" and others. How can I do that?

Body:
[1] SQL Server comes with a dedicated API for parsing T-SQL source coude, API included within Microsoft.SqlServer.TransactSql.ScriptDom namespace. This namespace include parsers for every SQL Server version starting with SQL Server 2000 (= TSql80Parser).

[2] Download

[3] You have to find all TSqlStatements having DeclareVariableStatement type (see DeclareVariableStatement Class). This class has following properties (among other properties): StartLine, StartColumn, StartOffset, FirstTokenIndex.

[4] Example:

using Microsoft.SqlServer.TransactSql.ScriptDom;
....

TSql120Parser SqlParser = new TSql120Parser(false);

IList<ParseError> parseErrors;
TSqlFragment result = SqlParser.Parse(new StringReader(SqlTextBox.Text),
                                      out parseErrors);

TSqlScript SqlScript = result as TSqlScript;

foreach (TSqlBatch sqlBatch in SqlScript.Batches)
{
   foreach (TSqlStatement sqlStatement in sqlBatch.Statements)
   {
      ProcessViewStatementBody(sqlStatement);
   }
}

Source: http://www.andriescu.nl/sql/sql-how-to-parse-microsoft-transact-sql-statements-in-c_sharp_view_column_binding/


问:
Workflow engine for php?
Who knows about a "mature" workflow engine for php?.

I am looking forward to use it from an application made using symphony framework.

Thanks !

答:
If you need a state machine you can use Symfony's one

https://symfony.com/doc/current/workflow/usage.html

If you need a workflow look at https://github.com/formapro/pvm.

Title: Workflow engine for php?


问:
Store many numbers as a single unique number
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

```<code>a = 2
b = 3
c = 5
d = 7
e = 13
</code>```

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?

答:
Ok so you want to store "a,b,c" or "a,b" or "a,b,c,d" or "a" etc. (thanks @FlorianK)

in such case just could use bitwise operators and powers of two

```<code>$a = 1 << 0; // 1
$b = 1 << 1; // 2
$c = 1 << 2; // 4
$d = 1 << 3; // 8
.. etc
</code>```

let's say $flag has $a and $c

```<code>$flag = $a | $c; // $flag is integer here
</code>```

now check it

```<code>$ok = ($flag & $a) && ($flag & $c); // true
$ok = ($flag & $a) && ($flag & $b); // false
</code>```

so in 64 bit system/language/os you can use up to 64 flags which gives you a 2^64 combinations

there is no really other option. prime numbers are much worse for this as you skip many numbers in-between while binary system uses every single number.

I see you are using database and you want to store this in DB.

I really think we are dealing here with XY Problem and you should reconsider your application instead of making such workarounds.

Body:
I have the necessity to store many numbers (i can decide which numbers) as a single unique number from which i should be able to retrieve the original number.

I already know 2 ways to do this:

1) Fundamental theorem of arithmetic (Prime Numbers)

Say i have 5 values, i assign a prime number other than 1 to each value

a = 2
b = 3
c = 5
d = 7
e = 13

If i want to store a, b and c i can multiply them 2*3*5=30 and i know no other product of primes can be 30. Then to check if a value contains, for example, b, all i need to do is 30 % b == 0

2) Bitmask
Just like Linux permissions, use powers of 2 and sum each value

But these 2 methods grow up fast (1st way faster than 2nd), and using prime numbers requires me to have a lot of primes.

Is there any other method to do this efficiently when you have, for example, a thousand values?

Body:
Ok so you want to store "a,b,c" or "a,b" or "a,b,c,d" or "a" etc. (thanks @FlorianK)

in such case just could use bitwise operators and powers of two

$a = 1 << 0; // 1
$b = 1 << 1; // 2
$c = 1 << 2; // 4
$d = 1 << 3; // 8
.. etc

let's say $flag has $a and $c

$flag = $a | $c; // $flag is integer here

now check it

$ok = ($flag & $a) && ($flag & $c); // true
$ok = ($flag & $a) && ($flag & $b); // false

so in 64 bit system/language/os you can use up to 64 flags which gives you a 2^64 combinations

there is no really other option. prime numbers are much worse for this as you skip many numbers in-between while binary system uses every single number.

I see you are using database and you want to store this in DB.

I really think we are dealing here with XY Problem and you should reconsider your application instead of making such workarounds.


问:
Fiddlers Jscript JSON.JsonDecode
This is what I have:

public static var users=Fiddler.WebFormats.JSON.JsonDecode('[{key:"20048039", value:"Some Name"}, {key:"204130"...);

This is what I want:

users.JSONObject[0].key or users.JSONObject[0].value

This what I use for investigation:

FiddlerApplication.Log.LogFormat('output: {0}', users.JSONObject[0]);

output: System.Collections.Hashtable

I know c#, but in FiddlerScript I need some help to read these values inside users.

What shall I do here ?

thanks.

答:
ok, I found the solution by myself(ArrayList,Hashtable):

users.JSONObject[0]["key"])

Title: Fiddlers Jscript JSON.JsonDecode