问:
Circular progress bar is not showing progress for 10% when it show for 60%
I have a circular progress bar and it is working properly when it show 60%. But it does not show any progress for 10% result.The progress is shown with the help of adapter. Can you please help me?

My code is:

```<code><ProgressBar
     android:id="@+id/progressbar"
     style="?android:attr/progressBarStyleHorizontal"
     android:layout_width="100dp"
     android:layout_height="100dp"
     android:layout_marginTop="10dp"
     android:max="100"
     android:indeterminate="false"
     android:progressBackgroundTint="#D3D3D3"
     android:progress="50"
     android:progressDrawable="@drawable/progressbar"
     android:layout_centerVertical="true" />
</code>```

答:
Try this

```<code><RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_weight="1">

      <ProgressBar
           android:id="@+id/cmll_progrssbar"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="70dp"
           android:layout_height="70dp"
           android:indeterminate="false"
           android:layoutDirection="rtl"
           android:max="100"
           android:progress="100"
           android:progressDrawable="@drawable/circle_progress_uncomplete" />

      <TextView
          android:id="@+id/cmll_completed_per"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignBottom="@id/cmll_progrssbar"
          android:layout_alignLeft="@id/cmll_progrssbar"
          android:layout_alignRight="@id/cmll_progrssbar"
          android:layout_alignTop="@id/cmll_progrssbar"
          android:layout_gravity="center"
          android:gravity="center"
          android:padding="10dp"
          android:text="100%" />

    </RelativeLayout>
</code>```

Now Create @drawable/circle_progress_uncomplete like this

```<code><?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="20.0"
            android:useLevel="false">
            <solid android:color="@color/colorLightOrange" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <rotate
            android:fromDegrees="270"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="270">
            <shape
                android:innerRadiusRatio="3"
                android:shape="ring"
                android:thicknessRatio="20.0"
                android:useLevel="true">
                <solid android:color="@color/colorOrange" />
            </shape>
        </rotate>
    </item>

</layer-list>
</code>```

OUTPUT WITH 10% PROGRESS

OUTPUT WITH 100% PROGRESS

Body:
I have a circular progress bar and it is working properly when it show 60%. But it does not show any progress for 10% result.The progress is shown with the help of adapter. Can you please help me?

My code is:

<ProgressBar
     android:id="@+id/progressbar"
     style="?android:attr/progressBarStyleHorizontal"
     android:layout_width="100dp"
     android:layout_height="100dp"
     android:layout_marginTop="10dp"
     android:max="100"
     android:indeterminate="false"
     android:progressBackgroundTint="#D3D3D3"
     android:progress="50"
     android:progressDrawable="@drawable/progressbar"
     android:layout_centerVertical="true" />

Body:
Try this

<RelativeLayout
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_weight="1">

      <ProgressBar
           android:id="@+id/cmll_progrssbar"
           style="?android:attr/progressBarStyleHorizontal"
           android:layout_width="70dp"
           android:layout_height="70dp"
           android:indeterminate="false"
           android:layoutDirection="rtl"
           android:max="100"
           android:progress="100"
           android:progressDrawable="@drawable/circle_progress_uncomplete" />

      <TextView
          android:id="@+id/cmll_completed_per"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignBottom="@id/cmll_progrssbar"
          android:layout_alignLeft="@id/cmll_progrssbar"
          android:layout_alignRight="@id/cmll_progrssbar"
          android:layout_alignTop="@id/cmll_progrssbar"
          android:layout_gravity="center"
          android:gravity="center"
          android:padding="10dp"
          android:text="100%" />

    </RelativeLayout>

Now Create @drawable/circle_progress_uncomplete like this

<?xml version="1.0" encoding="utf-8"?>

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background">
        <shape
            android:innerRadiusRatio="3"
            android:shape="ring"
            android:thicknessRatio="20.0"
            android:useLevel="false">
            <solid android:color="@color/colorLightOrange" />
        </shape>
    </item>
    <item android:id="@android:id/progress">
        <rotate
            android:fromDegrees="270"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toDegrees="270">
            <shape
                android:innerRadiusRatio="3"
                android:shape="ring"
                android:thicknessRatio="20.0"
                android:useLevel="true">
                <solid android:color="@color/colorOrange" />
            </shape>
        </rotate>
    </item>

</layer-list>

OUTPUT WITH 10% PROGRESS

OUTPUT WITH 100% PROGRESS


来源: stackexchange

问:
redirect function doesnt work properly after submitting the form twice
I did a form validation where server checks submitted data. If data passes validation, then redirect to previous page, if not, a modal box will pop up tells user wrong username/password.

The question is, after user resubmit the form, redierct function doesn't work. It only works when user first time successfully input those fields. Can anyone help me with this please?

The html code:

```<code><div id="formInfo">
    <form method="post" action="<?PHP echo $_SERVER['PHP_SELF'];?>">
        <span class="title">Sign in to urmajesty.net</span><br><br>

        <div id="input_container">
            <input type="text" name="username" placeholder="username"><img src="Images/icons/user.png" id="input_img"><br><br>
        </div>

        <div id="psw_container">
             <input type="password" name="psw" placeholder="password"><img src="Images/icons/key.png" id="key_img"><br><br>
        </div>

        <div id="checkbox">
            <input type="checkbox" name="RememberUsername" value="Yes"><span class="checkboxtxt">Remember my username</span>
        </div><br><br>

        <div id="Forget">
            <a href="#"><span class="forget1">Forget Password</span></a><a href="#"><span class="forget2">Forget Username</span></a>
        </div>

        <input type="submit" class="button" value="SIGN IN"><br><br>

        <div id="hispan"><p class="hip"><span class="hi">New to urmajesty.net?</span></p></div><br>

             <input class='disable_me' name="referer" type="hidden" value="<?php echo urlencode($_SERVER['HTTP_REFERER'])?> " />
             <button type="button" class="button" id="btn">CREATE ACCOUNT</button>
    </form>
</div>

<div id='modal_box'>
    <div class='modal_content'>
         <span class='close'>×</span><p>username/password is wrong. Please try again!</p>
    </div>
</div>
</code>```

The php code:

```<code>if($_SERVER["REQUEST_METHOD"]=="POST"){
    $validation=Login();
    if($validation==false){
        echo"<script>
        var modal_box=document.getElementById('modal_box');
        modal_box.style.display='block';
        modal_box.style.backgroundColor='rgba(0,0,0,0.4)';
        var close=document.getElementsByClassName('close')[0];
        close.onclick=function(){
            modal_box.style.display='none';
        }
        window.onclick=function(event){
            if(event.target==modal_box){
                modal_box.style.display='none';
            }
        }
        </script>";
    }
    else{
        if(!empty($_POST['referer']) && !is_array($_POST['referer'])){
            header("Location: ".urldecode($_POST['referer']));
            exit();
        }
    }
}
?>
</code>```

答:
Use javascript to redirect.</p>

```<code>if(!empty($_POST['referer']) && !is_array($_POST['referer'])){ ?>
    //header("Location: ".urldecode($_POST['referer']));
    <script>
        window.location.href = "<?=$_POST['referer']?>";
    </script>
 <?php
    exit();
 } ?>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I did a form validation where server checks submitted data. If data passes validation, then redirect to previous page, if not, a modal box will pop up tells user wrong username/password.

The question is, after user resubmit the form, redierct function doesn't work. It only works when user first time successfully input those fields. Can anyone help me with this please?

The html code:

    <form method="post" action="<?PHP echo $_SERVER['PHP_SELF'];?>">
        Sign in to urmajesty.net

            <input type="text" name="username" placeholder="username">

             <input type="password" name="psw" placeholder="password">

            <input type="checkbox" name="RememberUsername" value="Yes">Remember my username

            Forget PasswordForget Username

        <input type="submit" class="button" value="SIGN IN">

New to urmajesty.net?

             <input class='disable_me' name="referer" type="hidden" value="<?php echo urlencode($_SERVER['HTTP_REFERER'])?> " />
             <button type="button" class="button" id="btn">CREATE ACCOUNT</button>
    </form>

         ×
username/password is wrong. Please try again!

The php code:

if($_SERVER["REQUEST_METHOD"]=="POST"){
    $validation=Login();
    if($validation==false){
        echo"";
    }
    else{
        if(!empty($_POST['referer']) && !is_array($_POST['referer'])){
            header("Location: ".urldecode($_POST['referer']));
            exit();
        }
    }
}
?>

Body:
Use javascript to redirect.

if(!empty($_POST['referer']) && !is_array($_POST['referer'])){ ?>
    //header("Location: ".urldecode($_POST['referer']));
    <script>
        window.location.href = "<?=$_POST['referer']?>";
    </script>
 <?php
    exit();
 } ?>


问:
a jQuery promise that always succeeds?
I have this code jQuery code fragment:

```<code>$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)
</code>```

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

```<code>let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)
</code>```

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

```<code>let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {
</code>```

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.

答:
You can achieve this by implementing AlwaysSuceeds constructor function. Please see below example.

function AlwaysSucceeds(data) {
  this.data = data;
}

AlwaysSucceeds.prototype.done = function(fn) {
  fn(this.data);
  return this;
}

AlwaysSucceeds.prototype.fail = function(fn) {
  return this;
}

var myData = {
  a: 1
};

(new AlwaysSucceeds(myData)).done(function(data) {
  console.log(data)
}).fail(function(data){

})```

Title: a jQuery promise that always succeeds?

Body:
I have this code jQuery code fragment:

$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.


问:
Error when using presigned url to download from S3
I'm successfully generating presigned GetObject URLs. The generated URL is then pasted onto the browser to download the requested item. So far, I am able to retrieve objects from Virginia and Singapore. But with Ohio, I'm getting the following error.
"The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256."</p>

答:
Amazon has 2 authentication schemes: AWS Signature Version 4 and AWS Signature Version 2. Amazon has decided to support only the newer, V4 version in regions deployed after January 30th, 2014. So facing this issue is expected in some regions.

However, V4 has some changes which you need to know if you want to sign your requests properly and access S3. You can find more details here.


问:
Fractional y-var in ggplot
How can I easily create a fractional y-value when using ggplot?

```<code>t <- as.factor(test=sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T)
p <- data.frame(t,d)
</code>```

My best shot was:

```<code>ggplot(p,aes(x=t,y=prop.table(table(t,d),1)[,1])) + geom_point()
</code>```

However this doesnt work and I guess there is an easier way around this...

答:
scale_y_continuous() accepts a 'formatter' argument which can take a function.  I was having some errors with your example code, but consider the following:</p>

```<code>require(ggplot2)

t <- as.factor(sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T))
p <- data.frame(t,d)

formatFraction <- function(x)
{
    fraction <- paste(x*100, '/100', sep='')
    fraction
}

plot <- ggplot(p, aes(x=prop.table(table(t, d), 1)[,2],
    y=prop.table(table(t, d), 1)[,1])) + geom_point()
plot + scale_y_continuous(formatter=formatFraction)
</code>```

ContentLicense: CC BY-SA 2.5

Title: Fractional y-var in ggplot

Body:
How can I easily create a fractional y-value when using ggplot?

t <- as.factor(test=sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T)
p <- data.frame(t,d)

My best shot was:

ggplot(p,aes(x=t,y=prop.table(table(t,d),1)[,1])) + geom_point()

However this doesnt work and I guess there is an easier way around this...

Body:
scale_y_continuous() accepts a 'formatter' argument which can take a function.  I was having some errors with your example code, but consider the following:

require(ggplot2)

t <- as.factor(sample(seq(0,100,10),1000,rep=T))
d <- as.factor(sample(c(0,1),1000,rep=T))
p <- data.frame(t,d)

formatFraction <- function(x)
{
    fraction <- paste(x*100, '/100', sep='')
    fraction
}

plot <- ggplot(p, aes(x=prop.table(table(t, d), 1)[,2],
    y=prop.table(table(t, d), 1)[,1])) + geom_point()
plot + scale_y_continuous(formatter=formatFraction)


问:
Rails skip initializer on asset precompile
I'd like to skip one of my initializer files during asset precompilation. Is this possible in Rails 4? Seems like initialize_on_precompile was removed.

thanks

答:
There seems to be no way to do this in a rails way. We have done something like below

```<code>if ENV['ASSET_PRECOMPILE'].blank?
  Airbrake.configure do |config|
    config.project_id = ENV['AIRBRAKE_PROJECT_ID']
    config.project_key = ENV['AIRBRAKE_PROJECT_KEY']
    config.ignore_environments = %w(test development)
    config.environment = Rails.env
  end
end
</code>```

and when running the asset:precompile task

```<code>ASSET_PRECOMPILE=1 RAILS_ENV=production bundle exec rake assets:precompile
</code>```

Body:
There seems to be no way to do this in a rails way. We have done something like below

if ENV['ASSET_PRECOMPILE'].blank?
  Airbrake.configure do |config|
    config.project_id = ENV['AIRBRAKE_PROJECT_ID']
    config.project_key = ENV['AIRBRAKE_PROJECT_KEY']
    config.ignore_environments = %w(test development)
    config.environment = Rails.env
  end
end

and when running the asset:precompile task

ASSET_PRECOMPILE=1 RAILS_ENV=production bundle exec rake assets:precompile


问:
most frequent character in 2d array with pointer
i want to find the most frequent character for 5 strings,i thought of this ,i have done it for a specific character,in my ocasion s ,but how can i make it for every character,its only part of my code

Ch is a pointer!!!

```<code>for(i = 0; i < five; i++){
    ch = strchr(cities[i], 's');

    if (ch != NULL){ //if this is true
        ch1++;
        printf("exists in %s\n", cities[i]); //print
    }
    else
    {
        printf ("doesnt exist in %s\n", cities[i]); //print
    }
}
printf("The character 's' appears in %d cities\n", ch1);
</code>```

答:
You can use count sort to achieve this task in O(n) time complexity and O(1) space complexity if your input strictly consists of ASCII characters only.

You keep an array int count[128] = {0}; which keeps track of how many time each character occurred. You use the index of the array as the ASCII value of the character.

```<code>for(int i = 0; i < 5; i++)
    for(int j = 0; cities[i][j] != '\0'; j++)
         count[cities[i][j]]++;
</code>```

If you want to ignore non-graphic characters or you just want to count alphanumeric characters or whatever your requirements maybe, you will have to add an if check with the correct combination of functions (isalpha, isalnum, etc) from ctype.h

You now have to run through the count array and find the largest number. The index at which the largest number was found is the ASCII value of the most common character.

Body:
i want to find the most frequent character for 5 strings,i thought of this ,i have done it for a specific character,in my ocasion s ,but how can i make it for every character,its only part of my code

Ch is a pointer!!!

for(i = 0; i < five; i++){
    ch = strchr(cities[i], 's');

    if (ch != NULL){ //if this is true
        ch1++;
        printf("exists in %s\n", cities[i]); //print
    }
    else
    {
        printf ("doesnt exist in %s\n", cities[i]); //print
    }
}
printf("The character 's' appears in %d cities\n", ch1);

Body:
You can use count sort to achieve this task in O(n) time complexity and O(1) space complexity if your input strictly consists of ASCII characters only.

You keep an array int count[128] = {0}; which keeps track of how many time each character occurred. You use the index of the array as the ASCII value of the character.

for(int i = 0; i < 5; i++)
    for(int j = 0; cities[i][j] != '\0'; j++)
         count[cities[i][j]]++;

If you want to ignore non-graphic characters or you just want to count alphanumeric characters or whatever your requirements maybe, you will have to add an if check with the correct combination of functions (isalpha, isalnum, etc) from ctype.h

You now have to run through the count array and find the largest number. The index at which the largest number was found is the ASCII value of the most common character.


问:
design procedure printString
basically i have a question. got new work book today from college with couple of questions and one is following:

Design a procedure printString to input an integer n and a string s, and print n copies of (the value of) n on the screen, two copies per line (except, possibly, the last line).
If the user enters a negative value for n, the computer should print a complaint.

So my code is this:( also compiles and does whatever the question asked me to do)

```<code>import java.util.*;

public class Question5 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String s = "";
        int n = 0;

        System.out.println("Type in any string");
        s = input.nextLine();

        System.out.println("Type in any integer");
        n = input.nextInt();

        if (n > 0) {
            while (n > 1) {
                System.out.println(s + "\t" + s);
                --n;
                --n;
            }
            if(n == 1){
                System.out.print(s);
                --n;
            }
        } else {
            System.out.println("Please do not use negative value.");
        }
    }
}
</code>```

I wanted to ask what did my teacher have in mind by saying procedure printString? a method?

Thank you!

答:
If you are asking for a printString function than it could be implemented as:</p>

```<code>public static void printString(String s, int n)
{
    if(n<0)
    {
        System.out.println("Please do not use negative value.");
    }
    else
    {
        for(int i=0;i<n;i=i+2)
        {
            System.out.println(s+" "+s);
        }
    }
}
   public static void main(String[] args) {

printString("String",6);
}
</code>```

Title: design procedure printString

Body:
basically i have a question. got new work book today from college with couple of questions and one is following:

Design a procedure printString to input an integer n and a string s, and print n copies of (the value of) n on the screen, two copies per line (except, possibly, the last line).
If the user enters a negative value for n, the computer should print a complaint.

So my code is this:( also compiles and does whatever the question asked me to do)

import java.util.*;

public class Question5 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String s = "";
        int n = 0;

        System.out.println("Type in any string");
        s = input.nextLine();

        System.out.println("Type in any integer");
        n = input.nextInt();

        if (n > 0) {
            while (n > 1) {
                System.out.println(s + "\t" + s);
                --n;
                --n;
            }
            if(n == 1){
                System.out.print(s);
                --n;
            }
        } else {
            System.out.println("Please do not use negative value.");
        }
    }
}

I wanted to ask what did my teacher have in mind by saying procedure printString? a method?

Thank you!

Body:
If you are asking for a printString function than it could be implemented as:

public static void printString(String s, int n)
{
    if(n<0)
    {
        System.out.println("Please do not use negative value.");
    }
    else
    {
        for(int i=0;i<n;i=i+2)
        {
            System.out.println(s+" "+s);
        }
    }
}
   public static void main(String[] args) {

printString("String",6);
}


问:
How to subquery Firebase Web App to Create a table
I'm doing a basic e-commerce web platform, so the user can buy products, and in other page I want to show his product list, and the orders, what I mean is that a user can make one or more orders with 1 or more products.

the UID is the email.
this is my data structure

```<code>{
  "Orders" : {
    "-L-Nor4Ld1NNORxNToPI" : {
      "order" : [ {
        "cant" : "1",
        "product_id" : "1"
      }, {
        "cant" : "2",
        "product_id" : "5"
      }, {
        "cant" : "3",
        "product_id" : "8"
      } ],
      "status" : "pendiente",
      "total" : 795,
      "user_id" : "email@gmail.com"
    },
    "-L-UU03CNGSPd8o0UCHn" : {
      "order" : [ {
        "cant" : "2",
        "product_id" : "2"
      }, {
        "cant" : "1",
        "product_id" : "7"
      } ],
      "status" : "pendiente",
      "total" : 280,
      "user_id" : "email@gmail.com"
    },
    "any" : {
      "order" : {
        "product1" : {
          "cant" : 1,
          "product_id" : 1
        },
        "product2" : {
          "cant" : 1,
          "product_id" : 1
        }
      },
      "status" : "delivered",
      "total" : 100.01,
      "user_id" : "email@example.com"
    }
  },
  "Productos" : {
    "-L-JT-TaL5ctRQ-8u8NR" : {
      "price" : 35,
      "product_id" : 1,
      "product_name" : "Serie 100 luces (foco)",
      "stock" : 20
    },
    "-L-JTIcZ69uFkdUQbs8X" : {
      "price" : 75,
      "product_id" : 2,
      "product_name" : "Serie 100 luces (LED)",
      "stock" : 10
    },
    "-L-JTTi8VcLxkgT3RNuA" : {
      "price" : 70,
      "product_id" : 3,
      "product_name" : "Serie 140 luces musical (foco)",
      "stock" : 10
    },
    "-L-JTb0PwTyS8TiWS5W9" : {
      "price" : 96,
      "product_id" : 4,
      "product_name" : "Serie 140 luces musical (LED)",
      "stock" : 10
    },
    "-L-JUm5tF8fYBmR3BZCU" : {
      "price" : 110,
      "product_id" : 5,
      "product_name" : "Serie 300 luces color",
      "stock" : 10
    },
    "-L-JUzclafELx1xjpuQx" : {
      "price" : 135,
      "product_id" : 6,
      "product_name" : "Serie 300 luces blanca",
      "stock" : 10
    },
    "-L-JVB8diTZMmVS3ay1u" : {
      "price" : 130,
      "product_id" : 7,
      "product_name" : "Cascada 400 Luces",
      "stock" : 10
    },
    "-L-JVIgENEJRdcfLfKWT" : {
      "price" : 180,
      "product_id" : 8,
      "product_name" : "Manguera gel 10 metros",
      "stock" : 10
    }
  }
}
</code>```

And you can see the project by yourself just login with google in  this link
Go To Project
once you have made your order, you can go to this link Order review Page
and you should see whats in your order, but that doesnt happens, I want to do something like this

Get logged user_id then get user_id orders(order_id), then show in (if) multiple tables with

|Product |Price| Quantity| sub(price*quant)

And its products

So as you can see in the code of cart.html im using

```<code>ref.orderBy(X).equalTo(uid).on("child_added",function(data){
    ref.orderBy(Y).equalTo(item).on("child_added",function(data2){
        //dothings create table content
    })
    //close table content
})
//embed table content created.
</code>```

so I want to show a the table but .then() function doesnt work and the same with .done() , i hope you can help me to understand how should I subquery, to get the user orders in a table

答:
My solution was not to get values by inner firebase functions, it was getting all the data, then create the table with the data

The next code suppose that productsObj, and ordersObj are the result objects of my firebase database products and orders.
so the next thing i did was to create dynamically the table with this function.
You cannot create subqueries or something like that on firebase functions like on  child_added, child_removed, etc..

```<code>function productList(){

    if(ordersObj.length != 0 & productsObj.length == 8){
        //console.log("si termino");
        $.each(ordersObj,function(index, data){
            var table =('<table class="table table-hover table-bordered">');
            var tableHead = ("<thead class='thead-dark'><tr><th>Producto</th><th>Precio</th><th>Cantidad</th><th>Importe</th></thead>");
            table+=tableHead;
            //console.log(table);
            var tableBody = ("");
            //console.log(tableBody)
            var total = 0;
            $.each(data.order,function(idx, ord){
                console.log(ord.product_id);
                //console.log("precio:"+productsObj[ord.product_id-1].price);
                var subtotal = ord.cant*productsObj[ord.product_id-1].price;
                //console.log("despues del subtotal")
                var row = ('<tr><td>'+productsObj[ord.product_id-1].product_name+'</td><td>'+productsObj[ord.product_id-1].price+'</td>'+'<td>'+ord.cant+'</td>'+'<td>'+subtotal+'</td></tr>');
                //console.log(row);
                total=data.total;
                tableBody+=(row);
            });
                //console.log(tableBody.html());
                //console.log(tableHead.html());
            tableBody+=("<tr><td colspan='2'>Total</td><td colspan='2'>"+total+"</td></tr><tbody></table>");
            table+=tableBody;
            //console.log(table);
            //table.append(tableHead.html());
            $('#content').append(table);
            $('#content').append("<br>");
        });

    }
    else{
        //productList();
    }

}
</code>```

Body:
I'm doing a basic e-commerce web platform, so the user can buy products, and in other page I want to show his product list, and the orders, what I mean is that a user can make one or more orders with 1 or more products.

the UID is the email.
this is my data structure

{
  "Orders" : {
    "-L-Nor4Ld1NNORxNToPI" : {
      "order" : [ {
        "cant" : "1",
        "product_id" : "1"
      }, {
        "cant" : "2",
        "product_id" : "5"
      }, {
        "cant" : "3",
        "product_id" : "8"
      } ],
      "status" : "pendiente",
      "total" : 795,
      "user_id" : "email@gmail.com"
    },
    "-L-UU03CNGSPd8o0UCHn" : {
      "order" : [ {
        "cant" : "2",
        "product_id" : "2"
      }, {
        "cant" : "1",
        "product_id" : "7"
      } ],
      "status" : "pendiente",
      "total" : 280,
      "user_id" : "email@gmail.com"
    },
    "any" : {
      "order" : {
        "product1" : {
          "cant" : 1,
          "product_id" : 1
        },
        "product2" : {
          "cant" : 1,
          "product_id" : 1
        }
      },
      "status" : "delivered",
      "total" : 100.01,
      "user_id" : "email@example.com"
    }
  },
  "Productos" : {
    "-L-JT-TaL5ctRQ-8u8NR" : {
      "price" : 35,
      "product_id" : 1,
      "product_name" : "Serie 100 luces (foco)",
      "stock" : 20
    },
    "-L-JTIcZ69uFkdUQbs8X" : {
      "price" : 75,
      "product_id" : 2,
      "product_name" : "Serie 100 luces (LED)",
      "stock" : 10
    },
    "-L-JTTi8VcLxkgT3RNuA" : {
      "price" : 70,
      "product_id" : 3,
      "product_name" : "Serie 140 luces musical (foco)",
      "stock" : 10
    },
    "-L-JTb0PwTyS8TiWS5W9" : {
      "price" : 96,
      "product_id" : 4,
      "product_name" : "Serie 140 luces musical (LED)",
      "stock" : 10
    },
    "-L-JUm5tF8fYBmR3BZCU" : {
      "price" : 110,
      "product_id" : 5,
      "product_name" : "Serie 300 luces color",
      "stock" : 10
    },
    "-L-JUzclafELx1xjpuQx" : {
      "price" : 135,
      "product_id" : 6,
      "product_name" : "Serie 300 luces blanca",
      "stock" : 10
    },
    "-L-JVB8diTZMmVS3ay1u" : {
      "price" : 130,
      "product_id" : 7,
      "product_name" : "Cascada 400 Luces",
      "stock" : 10
    },
    "-L-JVIgENEJRdcfLfKWT" : {
      "price" : 180,
      "product_id" : 8,
      "product_name" : "Manguera gel 10 metros",
      "stock" : 10
    }
  }
}

And you can see the project by yourself just login with google in  this link
Go To Project
once you have made your order, you can go to this link Order review Page
and you should see whats in your order, but that doesnt happens, I want to do something like this

Get logged user_id then get user_id orders(order_id), then show in (if) multiple tables with

|Product |Price| Quantity| sub(price*quant)

And its products

So as you can see in the code of cart.html im using

ref.orderBy(X).equalTo(uid).on("child_added",function(data){
    ref.orderBy(Y).equalTo(item).on("child_added",function(data2){
        //dothings create table content
    })
    //close table content
})
//embed table content created.

so I want to show a the table but .then() function doesnt work and the same with .done() , i hope you can help me to understand how should I subquery, to get the user orders in a table

Body:
My solution was not to get values by inner firebase functions, it was getting all the data, then create the table with the data

The next code suppose that productsObj, and ordersObj are the result objects of my firebase database products and orders.
so the next thing i did was to create dynamically the table with this function.
You cannot create subqueries or something like that on firebase functions like on  child_added, child_removed, etc..

function productList(){

    if(ordersObj.length != 0 & productsObj.length == 8){
        //console.log("si termino");
        $.each(ordersObj,function(index, data){
            var table =('<table class="table table-hover table-bordered">');
            var tableHead = ("<thead class='thead-dark'><tr><th>Producto</th><th>Precio</th><th>Cantidad</th><th>Importe</th></thead>");
            table+=tableHead;
            //console.log(table);
            var tableBody = ("");
            //console.log(tableBody)
            var total = 0;
            $.each(data.order,function(idx, ord){
                console.log(ord.product_id);
                //console.log("precio:"+productsObj[ord.product_id-1].price);
                var subtotal = ord.cant*productsObj[ord.product_id-1].price;
                //console.log("despues del subtotal")
                var row = ('<tr><td>'+productsObj[ord.product_id-1].product_name+'</td><td>'+productsObj[ord.product_id-1].price+'</td>'+'<td>'+ord.cant+'</td>'+'<td>'+subtotal+'</td></tr>');
                //console.log(row);
                total=data.total;
                tableBody+=(row);
            });
                //console.log(tableBody.html());
                //console.log(tableHead.html());
            tableBody+=("<tr><td colspan='2'>Total</td><td colspan='2'>"+total+"</td></tr><tbody></table>");
            table+=tableBody;
            //console.log(table);
            //table.append(tableHead.html());
            $('#content').append(table);
            $('#content').append("<br>");
        });

    }
    else{
        //productList();
    }

}


问:
How to create REST endpoint service consume multipart using Spring 4.x?
I am trying to create a REST service that consumes the "multipart/form-data" with text and attachment objects. For files i can use "org.springframework.web.multipart.MultipartFile", but how do i specify the service method for Text objects?

Below is the expected client call to service.

答:
Just create the controller as specified below:

```<code>@RequestMapping(value = "/uploadFiles", headers = ("content-type=multipart/*"), method = RequestMethod.POST)
    public AppDTO uploadFile(UploadFiles uploadFiles, HttpServletRequest request) {
</code>```

Now create a pojo class for what ever things you need to submit along with a multipartfile member where the file will bind to. refer below code for pojo

```<code>class UploadFiles
{
private String cc;
private String to;
private String from;

private MultipartFile attachment;

//create getters and setters

}
</code>```

MultipartFile here used is provided by spring

```<code>import org.springframework.web.multipart.MultipartFile;
</code>```

If you have more than one attachment you can use MultipartFile[] in POJO

Body:
Just create the controller as specified below:

@RequestMapping(value = "/uploadFiles", headers = ("content-type=multipart/*"), method = RequestMethod.POST)
    public AppDTO uploadFile(UploadFiles uploadFiles, HttpServletRequest request) {

Now create a pojo class for what ever things you need to submit along with a multipartfile member where the file will bind to. refer below code for pojo

class UploadFiles
{
private String cc;
private String to;
private String from;

private MultipartFile attachment;

//create getters and setters

}

MultipartFile here used is provided by spring

import org.springframework.web.multipart.MultipartFile;

If you have more than one attachment you can use MultipartFile[] in POJO


问:
Ionic requests return 404 only on android, in Chrome it works fine
So, i have cloned the tutorial app repo from ionic. I ran

```<code>ionic start conference sidemenu
</code>```

and then i added a simple $http.get('myserver')(I tried with ngResources too).

It worked perfect on chrome, I got all the data back but on angular i only got null data and 404 status on any request I tried to do.

Note: I tried with my hosted server and with a local one. Both fail on Android.
Server is a node.js REST API.

Nothing is printed on the console, so the request does not even get to the server.

Has anyone experienced that or could tell me how can I debug Android apps built with Ionic?

EDIT 1: I don`t know why do you need it but here it is

```<code>$http.get('http://server.com/route').success(function (data) {
            //handle success
        }).error(function (data, status) {
            // handle error
        });
</code>```

答:
The local content you should, when cordova compile is a www folder, they are there assets and other folder for you implement the apk or equivalent iOS

i.e

```<code><img src="assets/images/{your-file-name}">
</code>```

Body:
So, i have cloned the tutorial app repo from ionic. I ran

ionic start conference sidemenu

and then i added a simple $http.get('myserver')(I tried with ngResources too).

It worked perfect on chrome, I got all the data back but on angular i only got null data and 404 status on any request I tried to do.

Note: I tried with my hosted server and with a local one. Both fail on Android.
Server is a node.js REST API.

Nothing is printed on the console, so the request does not even get to the server.

Has anyone experienced that or could tell me how can I debug Android apps built with Ionic?

EDIT 1: I don`t know why do you need it but here it is

$http.get('http://server.com/route').success(function (data) {
            //handle success
        }).error(function (data, status) {
            // handle error
        });

Body:
The local content you should, when cordova compile is a www folder, they are there assets and other folder for you implement the apk or equivalent iOS

i.e

<img src="assets/images/{your-file-name}">


问:
Information about remote IP addresses
I want to track all IP addresses with which my computer is communicating. I am using C# and Visual Studio. There is one listBox in which I will put all remote IP address. I am new to network programming so I need some direction about that kind of problem.

My question is how to do this? How to get information about remote IP addresses which which my computer make connections?

答:
Most socket programming applications talk to the TCP socket API that's roughly standardized between operating systems.  If you just want to write a simple server and visualize the clients talking to your server running in your process that's pretty easy.  However, your process can't see the socket connections talking to other processes on your machine with the typical socket API.

If you want to get access to all IPs the entire machine is talking too you'll have to use a lower level API.  That's not standardized between OS.  For Windows I'd look at Winsock API to see if you can find how to look at the tcp/ip stack of the OS.  It gets more complex because TCP connections ride on top of IP packets.  At what level do you want to look at?  Just TCP, or all protocols that also ride on top of IP.  ARP, UDP, TCP, ICMP to name a view standard ones.

If you're just learning then doing just a simple server, and all the connections talking to that server in your process is much simpler.  Going lower is going to be jumping into the deep end quickly.  Not that I'm saying you shouldn't this.  Would you like to keep it simple and stay with the connections your process is talking to, or would you like to go into the deep dark Window's forest?  Choose your adventure.

Edit: Better option for lower level access is WinPcap with a C# wrapper.  That will let you get the raw packet information.  Even let you put your PC in promiscuous mode and sniff all traffic on your subnet not just your PC.

Title: Information about remote IP addresses


问:
How to compare two array and alert the result?
I have two simple arrays:

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.
</code>```

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

```<code>arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)
</code>```

I use $.each but it's only check the array. Not comparing them.

```<code>$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});
</code>```

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

答:
You will have to write a function that does the comparing and stores the difference in an array</p>

```<code>var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var diff = [];
arr_must_exist.forEach(function(value){
   if(arr_created.indexOf(value) < 0) {
     diff.push(value);
    }
});
var str = '';
if(diff.length) {
    var str = 'Your choice must contain ';
    diff.forEach(function(value, index) {
        str += ((index+1 == diff.length) ? ' and ' + value : value)
    });
} else {
    str = 'Your choice is valid';
}
alert(str);
</code>```

Body:
I have two simple arrays:

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"]; //This is varies depend of the array created.

So, if arr_created is like the example there should be an alert like Your choice must contain 1 and 3

Example:

arr_created    = ["2","4","7","8"];
alert(`Your choice must contain 1 and 3`)

arr_created    = ["2","3","7","8"];
alert(`Your choice must contain 1`)

arr_created    = ["4","5","7","8"];
alert(`Your choice must contain 1, 2 and 3`)

arr_created    = ["1","2","9","3"];
alert(`Your choice is valid`)

I use $.each but it's only check the array. Not comparing them.

$.each(arr_is_must_exist , function(index, val_must_exist) {

        $.each(arr_is_exist_in_table , function(index, val_is_exist) {
            if(val_must_exist != val_is_exist){
              alert("Your choice must contain 1,2,3");
            }
        });
});

I look here but there is not accepted answer. I use IE and mozilla (it's for local user)

Body:
You will have to write a function that does the comparing and stores the difference in an array

var arr_must_exist = ["1","2","3"];
var arr_created    = ["2","4","7","8"];
var diff = [];
arr_must_exist.forEach(function(value){
   if(arr_created.indexOf(value) < 0) {
     diff.push(value);
    }
});
var str = '';
if(diff.length) {
    var str = 'Your choice must contain ';
    diff.forEach(function(value, index) {
        str += ((index+1 == diff.length) ? ' and ' + value : value)
    });
} else {
    str = 'Your choice is valid';
}
alert(str);


问:
Error CS0234 when building solution using TFS 2017 BuildAgent
I ran into the following probem, when trying to build using a TFS build definition.

When executing a Build the agent logs following errors:

Error CS0234: The type or namespace name 'VisualStudio' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)

Error CS0246: The type or namespace name 'TestInitializeAttribute' could not be found (are you missing a using directive or an assembly reference?)

Error CS0246: The type or namespace name 'TestCleanupAttribute' could not be found (are you missing a using directive or an assembly reference?)

Error CS0246: The type or namespace name 'TestCleanup' could not be found (are you missing a using directive or an assembly reference?)

Error CS0246: The type or namespace name 'TestMethodAttribute' could not be found (are you missing a using directive or an assembly reference?)

So i understand the message that way, that the buildAgent is unable to find the following .dll

Microsoft.VisualStudio.TestTools.UnitTesting;

I have installed Visual Studio 2017 RC and Visual Studio 2017 Build Tools on the server, that runs TFS and the Buildagents.

I have also installed .net 4.6.1 on that mashine.

This
accepted answer is not a solution for me.

There must be some kind of solution, that does not include to copy that dll into the git trunk and reference it from there.

Update

I am able to locally build the Solution using Visual Studio 2017 RC on that mashine.
But the build agent still throws the same errors.

答: I changed the target framework from 4.7 to 4.6.1 in VS 2017, and it was fixed</p>


问:
Access VBA RunSQL Error
I'm trying to insert into a table the top x records from a query data-set. However I keep getting the run-time error '3061' Too few parameters. Expected 1. I've tried a few things but it doesn't make any difference.

```<code>Private Sub UpdateGA_Click()

Dim dbs As DAO.Database
Dim strSQL As String
Dim rounds As Integer
Dim playerid As Long

Set dbs = CurrentDb

rounds = Me.NoOfScores.Value
playerid = Me.lngPlayerID.Value

strSQL = "INSERT INTO [tbl_TopRounds] ( [lngPlayerID], [lngRoundID],  [dblPlayedTo], [dteRoundDate]) " & _
" SELECT TOP " & Me.NoOfScores.Value & " [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate] FROM qry_LastRounds" & _
" WHERE [lngPlayerID] = " & Me.lngPlayerID.Value & _
" ORDER BY [dblPlayedTo], [dteRoundDate] DESC;"

dbs.Execute strSQL

End Sub
</code>```

I'm expecting that x (based on a form parameter) records will be written to the tbl_TopRounds.

VB Error on executing

Any help would be appreciated.

答: Normally this error means that you made a mistake in field name. Set breakpoint on last command, run the sub, open immediate window and type ?strSQL. Copy received SQL text and try to run it in query builder, it will show column name which doesn't exist in the table. The error may be in the query qry_LastRounds, check it first by opening

Title: Access VBA RunSQL Error

Body:
I'm trying to insert into a table the top x records from a query data-set. However I keep getting the run-time error '3061' Too few parameters. Expected 1. I've tried a few things but it doesn't make any difference.

Private Sub UpdateGA_Click()

Dim dbs As DAO.Database
Dim strSQL As String
Dim rounds As Integer
Dim playerid As Long

Set dbs = CurrentDb

rounds = Me.NoOfScores.Value
playerid = Me.lngPlayerID.Value

strSQL = "INSERT INTO [tbl_TopRounds] ( [lngPlayerID], [lngRoundID],  [dblPlayedTo], [dteRoundDate]) " & _
" SELECT TOP " & Me.NoOfScores.Value & " [lngPlayerID], [lngRoundID], [dblPlayedTo], [dteRoundDate] FROM qry_LastRounds" & _
" WHERE [lngPlayerID] = " & Me.lngPlayerID.Value & _
" ORDER BY [dblPlayedTo], [dteRoundDate] DESC;"

dbs.Execute strSQL

End Sub

I'm expecting that x (based on a form parameter) records will be written to the tbl_TopRounds.

VB Error on executing

Any help would be appreciated.


问:
Google Maps draggable marker not work in collapse class bootstrap
I want to put a Google Maps draggable marker inside a collapse class bootstrap but it doesn't work. If I put the map outside the collapse class everything just working fine, the problem is just happen when I put the map inside the collapse class.

This is the HTML code:

```<code><div class="col-lg-12" >
    <div class="panel-group" id="accordion">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h4 class="panel-title">
                    <a data-toggle="collapse" data-parent="#accordion" href="#collapseThree"> Input Map?</a>
                </h4>
            </div>
            <div id="collapseThree" class="panel-collapse collapse">
                <div class="panel-body">
                    <!--map start-->
                    <div class="col-lg-8" >
                        <div class="form-group">
                            <label>Map</label>
                            <div id="map" class="col-lg-8 tambah-map-canvas"></div>
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <label>Coordinat</label><br/>
                    </div>
                    <div class="col-lg-4">
                        <div class="form-group">
                            <label>Latitude</label>
                            <input type="text" name="lat" id="lat" class="form-control">
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="form-group">
                            <label>Longitude</label>
                            <input type="text" name="lng" id="lng" class="form-control">
                        </div>
                    </div>
                    <div class="col-lg-4">
                        <div class="form-group">
                            <input type="button" id="reset" value="Reset Location">
                            <br/><br/>
                        </div>
                    </div>
                    <!--map end-->
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This is the JavaScript:

```<code><script type="text/javascript">

    function updateMarkerPosition(latLng) {
        document.getElementById('lat').value = [latLng.lat()];
        document.getElementById('lng').value = [latLng.lng()];
    }

    var myOptions = {
      zoom: 7,
    scaleControl: true,
      center:  new google.maps.LatLng(-6.175500045712664,106.8272084918824),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"),
    myOptions);

    var marker1 = new google.maps.Marker({
    position : new google.maps.LatLng(-6.175500045712664,106.8272084918824),
    title : 'lokasi',
    map : map,
    draggable : true
    });

    //updateMarkerPosition(latLng);

    google.maps.event.addListener(marker1, 'drag', function() {
        updateMarkerPosition(marker1.getPosition());
    });
</script>

<script type="text/javascript">
    document.getElementById('reset').onclick= function() {
        var field1= document.getElementById('lng');
        var field2= document.getElementById('lat');
        field1.value= field1.defaultValue;
        field2.value= field2.defaultValue;
    };
</script>
</code>```

Is there anything I miss? What am I doing wrong?
Thanks.

答:
I can't see your CSS on the id of #map but if it's not set to a specific height (i.e. 400px) then when you collapse the div, it really won't show.

So the fastest solution would be to set the height of your map to a fixed amount.

Then, regardless if you have draggable markers or not, the map will load on collapse.

Here's a sample: (also, a jsbin link if needed)

var map;
var center = {
  lat: -34.397,
  lng: 150.644
};

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: center,
    zoom: 8
  });

  var marker = new google.maps.Marker({
    position: center,
    map: map,
    draggable: true
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#map {
  height: 400px; /* Set this to something fixed */
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}</code>```

<!DOCTYPE html>

  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">

      Click to toggle the map

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

```

Hope that helps!

Body:
I want to put a Google Maps draggable marker inside a collapse class bootstrap but it doesn't work. If I put the map outside the collapse class everything just working fine, the problem is just happen when I put the map inside the collapse class.

This is the HTML code:

                     Input Map?

                            Map

                        Coordinat

                            Latitude
                            <input type="text" name="lat" id="lat" class="form-control">

                            Longitude
                            <input type="text" name="lng" id="lng" class="form-control">

                            <input type="button" id="reset" value="Reset Location">

This is the JavaScript:

Is there anything I miss? What am I doing wrong?
Thanks.

Body:
I can't see your CSS on the id of #map but if it's not set to a specific height (i.e. 400px) then when you collapse the div, it really won't show.

So the fastest solution would be to set the height of your map to a fixed amount.

Then, regardless if you have draggable markers or not, the map will load on collapse.

Here's a sample: (also, a jsbin link if needed)

var map;
var center = {
  lat: -34.397,
  lng: 150.644
};

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    center: center,
    zoom: 8
  });

  var marker = new google.maps.Marker({
    position: center,
    map: map,
    draggable: true
  });
}

#map {
  height: 400px; /* Set this to something fixed */
}

/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

<!DOCTYPE html>
<html>

<head>
  <title>Simple Map</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
</head>

<body>
  <div id="exampleAccordion" data-children=".item">
    <div class="item">
      <a data-toggle="collapse" data-parent="#exampleAccordion" href="#exampleAccordion1" aria-expanded="true" aria-controls="exampleAccordion1">
      Click to toggle the map
    </a>
      <div id="exampleAccordion1" class="collapse show" role="tabpanel">
        <div id="map"></div>
      </div>
    </div>
  </div>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCD0rWgXRVBa7PgaTWXVp_gU51pgHGviYY&callback=initMap" async defer></script>
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</body>

</html>

Hope that helps!


问:
Why does this happen when I create goroutine through the loop?
Please help me.
I have block codes, It uses iteration to get the elements of the map, and use this element to create a listener on a port on a Linux machine, But Its execution exceeded my expectations.
code show as below:

```<code>var srvs = map[string]struct {
  id       int
  timezone string
  connCfg  string
  conn     net.Conn
}{"BrazilEastSrv": {id: 1, timezone: "Brazil/East", connCfg: "127.0.0.1:9007"},
  "AustraliaDarwinSrv": {id: 2, timezone: "Australia/Darwin", connCfg: "127.0.0.1:9008"}}

var ch1 = make(chan int, 2)

func main() {
  for k, srv := range srvs {
    go func() {
      if ln, err := net.Listen("tcp", srv.connCfg); err != nil {
        log.Fatal(fmt.Sprintf("%s : %s conn failed,", k, srv.connCfg))
      } else {
        log.Println(fmt.Sprintf("%s:%s created, port:%s listened.", k, srv.connCfg[:9], srv.connCfg[10:]))
        if conn, err := ln.Accept(); err != nil {
          log.Fatal(srv.connCfg, " conn create fatal, errmsg=", err)
        } else {
          srv.conn = conn
          defer srv.conn.Close()
          log.Println("Accepted an access request from cli:", srv.conn.RemoteAddr(), ".")
          handleMsg(srv)
        }
      }
    }()
  }
  var brazilEastSrv, australiaDarwinSrv = <-ch1
  log.Println(brazilEastSrv, australiaDarwinSrv)
}
</code>```

output:

```<code>2017/12/07 11:45:48 AustraliaDarwinSrv:127.0.0.1 created, port:9008 listened.
2017/12/07 11:45:48 AustraliaDarwinSrv : 127.0.0.1:9008 conn failed,
exit status 1
</code>```

Seen from the output content. It uses the last element of the iteration and reuses this element, Why does it have this problem?

But when I make some changes：

```<code>var srvs = map[string]struct {
  id       int
  timezone string
  connCfg  string
  conn     net.Conn
}{"BrazilEastSrv": {id: 1, timezone: "Brazil/East", connCfg: "127.0.0.1:9007"},
  "AustraliaDarwinSrv": {id: 2, timezone: "Australia/Darwin", connCfg: "127.0.0.1:9008"}}

var ch1 = make(chan int, 2)

func main() {
  for k, srv := range srvs {
    go func(srv struct {
      id       int
      timezone string
      connCfg  string
      conn     net.Conn
    }) {
      //go func() {
      if ln, err := net.Listen("tcp", srv.connCfg); err != nil {
        log.Fatal(fmt.Sprintf("%s : %s conn failed,", k, srv.connCfg))
      } else {
        log.Println(fmt.Sprintf("%s:%s created, port:%s listened.", k, srv.connCfg[:9], srv.connCfg[10:]))
        if conn, err := ln.Accept(); err != nil {
          log.Fatal(srv.connCfg, " conn create fatal, errmsg=", err)
        } else {
          srv.conn = conn
          defer srv.conn.Close()
          log.Println("Accepted an access request from cli:", srv.conn.RemoteAddr(), ".")
          handleMsg(srv)
        }
      }
      //}()
    }(srv)
  }
  var brazilEastSrv, australiaDarwinSrv = <-ch1
  log.Println(brazilEastSrv, australiaDarwinSrv)
}
</code>```

It behaves in line with my expectations, what caused that difference? Thank you for your explanation.

答: In the first version, your goroutine uses the variable srv (and k) which changes with each iteration of the loop, so you don't know what value your goroutine will see when it is executing. In the second version, you're passing srv as an argument to the goroutine, so the variable srv within the goroutine is no longer the same variable that is used in the loop.

Body:
Please help me.
I have block codes, It uses iteration to get the elements of the map, and use this element to create a listener on a port on a Linux machine, But Its execution exceeded my expectations.
code show as below:

var srvs = map[string]struct {
  id       int
  timezone string
  connCfg  string
  conn     net.Conn
}{"BrazilEastSrv": {id: 1, timezone: "Brazil/East", connCfg: "127.0.0.1:9007"},
  "AustraliaDarwinSrv": {id: 2, timezone: "Australia/Darwin", connCfg: "127.0.0.1:9008"}}

var ch1 = make(chan int, 2)

func main() {
  for k, srv := range srvs {
    go func() {
      if ln, err := net.Listen("tcp", srv.connCfg); err != nil {
        log.Fatal(fmt.Sprintf("%s : %s conn failed,", k, srv.connCfg))
      } else {
        log.Println(fmt.Sprintf("%s:%s created, port:%s listened.", k, srv.connCfg[:9], srv.connCfg[10:]))
        if conn, err := ln.Accept(); err != nil {
          log.Fatal(srv.connCfg, " conn create fatal, errmsg=", err)
        } else {
          srv.conn = conn
          defer srv.conn.Close()
          log.Println("Accepted an access request from cli:", srv.conn.RemoteAddr(), ".")
          handleMsg(srv)
        }
      }
    }()
  }
  var brazilEastSrv, australiaDarwinSrv = <-ch1
  log.Println(brazilEastSrv, australiaDarwinSrv)
}

output:

2017/12/07 11:45:48 AustraliaDarwinSrv:127.0.0.1 created, port:9008 listened.
2017/12/07 11:45:48 AustraliaDarwinSrv : 127.0.0.1:9008 conn failed,
exit status 1

Seen from the output content. It uses the last element of the iteration and reuses this element, Why does it have this problem?

But when I make some changes：

var srvs = map[string]struct {
  id       int
  timezone string
  connCfg  string
  conn     net.Conn
}{"BrazilEastSrv": {id: 1, timezone: "Brazil/East", connCfg: "127.0.0.1:9007"},
  "AustraliaDarwinSrv": {id: 2, timezone: "Australia/Darwin", connCfg: "127.0.0.1:9008"}}

var ch1 = make(chan int, 2)

func main() {
  for k, srv := range srvs {
    go func(srv struct {
      id       int
      timezone string
      connCfg  string
      conn     net.Conn
    }) {
      //go func() {
      if ln, err := net.Listen("tcp", srv.connCfg); err != nil {
        log.Fatal(fmt.Sprintf("%s : %s conn failed,", k, srv.connCfg))
      } else {
        log.Println(fmt.Sprintf("%s:%s created, port:%s listened.", k, srv.connCfg[:9], srv.connCfg[10:]))
        if conn, err := ln.Accept(); err != nil {
          log.Fatal(srv.connCfg, " conn create fatal, errmsg=", err)
        } else {
          srv.conn = conn
          defer srv.conn.Close()
          log.Println("Accepted an access request from cli:", srv.conn.RemoteAddr(), ".")
          handleMsg(srv)
        }
      }
      //}()
    }(srv)
  }
  var brazilEastSrv, australiaDarwinSrv = <-ch1
  log.Println(brazilEastSrv, australiaDarwinSrv)
}

It behaves in line with my expectations, what caused that difference? Thank you for your explanation.


答:
Apart from using header() to redirect, you can use meta refresh method, or JS window.location method.

```<code>  <script>
     window.location = "<?=$_POST['referer']?>"
  </script>
</code>```

Title: redirect function doesnt work properly after submitting the form twice

Body:
I did a form validation where server checks submitted data. If data passes validation, then redirect to previous page, if not, a modal box will pop up tells user wrong username/password.

The question is, after user resubmit the form, redierct function doesn't work. It only works when user first time successfully input those fields. Can anyone help me with this please?

The html code:

    <form method="post" action="<?PHP echo $_SERVER['PHP_SELF'];?>">
        Sign in to urmajesty.net

            <input type="text" name="username" placeholder="username">

             <input type="password" name="psw" placeholder="password">

            <input type="checkbox" name="RememberUsername" value="Yes">Remember my username

            Forget PasswordForget Username

        <input type="submit" class="button" value="SIGN IN">

New to urmajesty.net?

             <input class='disable_me' name="referer" type="hidden" value="<?php echo urlencode($_SERVER['HTTP_REFERER'])?> " />
             <button type="button" class="button" id="btn">CREATE ACCOUNT</button>
    </form>

         ×
username/password is wrong. Please try again!

The php code:

if($_SERVER["REQUEST_METHOD"]=="POST"){
    $validation=Login();
    if($validation==false){
        echo"";
    }
    else{
        if(!empty($_POST['referer']) && !is_array($_POST['referer'])){
            header("Location: ".urldecode($_POST['referer']));
            exit();
        }
    }
}
?>

Body:
Apart from using header() to redirect, you can use meta refresh method, or JS window.location method.

  <script>
     window.location = "<?=$_POST['referer']?>"
  </script>


答:
Since jQuery Ajax functions just return $.Deferred objects, you can just substitute an immediately-resolved Deferred:

```<code>$.Deferred().resolve(myData).then(...)
</code>```

In this particular case, if you want to make it easy to switch between synchronous and asynchronous code, and you have access to async/await, you can just use those directly:

```<code>try {
    const data = await Promise.resolve($.get('/api/' + currentPage));
    // code in done
} catch (err) {
    // code in fail
}
</code>```

would become

```<code>try {
    const data = myData;
    // code in done
} catch (err) {
    // code in fail (never runs unless other code throws exceptions)
}
</code>```

Title: a jQuery promise that always succeeds?

Body:
I have this code jQuery code fragment:

$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.

Body:
Since jQuery Ajax functions just return $.Deferred objects, you can just substitute an immediately-resolved Deferred:

$.Deferred().resolve(myData).then(...)

In this particular case, if you want to make it easy to switch between synchronous and asynchronous code, and you have access to async/await, you can just use those directly:

try {
    const data = await Promise.resolve($.get('/api/' + currentPage));
    // code in done
} catch (err) {
    // code in fail
}

would become

try {
    const data = myData;
    // code in done
} catch (err) {
    // code in fail (never runs unless other code throws exceptions)
}


问:
Bitwise AND and modulo in a for loop produce unexpected results
```<code>for i in range(10):
    if i&3 == 0 or i%5 == 0:
        print(i)
</code>```

Guess what the outputs are?

0
4
5
8

4 and 8 are not supposed to be the output. Why does this happen?

Body:
for i in range(10):
    if i&3 == 0 or i%5 == 0:
        print(i)

Guess what the outputs are?

0
4
5
8

4 and 8 are not supposed to be the output. Why does this happen?

Body:
In [1]: bin(3)
Out[1]: '0b11'

In [2]: bin(5)
Out[2]: '0b101'

In [3]: for i in range(10):
...:     print i, bin(i), i&3, bin(i&3), i&5, bin(i&5)
...:
0 0b0 0 0b0 0 0b0
1 0b1 1 0b1 1 0b1
2 0b10 2 0b10 0 0b0
3 0b11 3 0b11 1 0b1
4 0b100 0 0b0 4 0b100
5 0b101 1 0b1 5 0b101
6 0b110 2 0b10 4 0b100
7 0b111 3 0b11 5 0b101
8 0b1000 0 0b0 0 0b0
9 0b1001 1 0b1 1 0b1

the reason those numbers are showing up is because either the last two bits are off '00' (i&3), or the last three bits are either '000' or '010'


问:
How to set '/*' rout in codeigniter 3.x
I want to rout all the request to one function

```<code>eg : $route['products/*'] = 'catalog/product_lookup';
</code>```

so if I request

```<code>products/abc
</code>```

or

```<code>products/xyz/akj/
</code>```

or

```<code>products/1027/01/12
</code>```

or

```<code>products/.....
</code>```

all this case I need to trigger "catalog/product_lookup"

inside product_lookup I need to get the routs after products

Any idea ?

答:
```<code>$route[‘products/(.*)’] = “products/product_lookup”;
</code>```

Here I assume that you request domain.com/products/product-name and it will map in products which is a controller, product_lookup which is a function and rest all will be parameters

For more details: http://naveedramzan.com/codeigniter-url-rewriting/

Title: How to set '/*' rout in codeigniter 3.x

Body:
I want to rout all the request to one function

eg : $route['products/*'] = 'catalog/product_lookup';

so if I request

products/abc

or

products/xyz/akj/

or

products/1027/01/12

or

products/.....

all this case I need to trigger "catalog/product_lookup"

inside product_lookup I need to get the routs after products

Any idea ?

Body:
$route[‘products/(.*)’] = “products/product_lookup”;

Here I assume that you request domain.com/products/product-name and it will map in products which is a controller, product_lookup which is a function and rest all will be parameters

For more details: http://naveedramzan.com/codeigniter-url-rewriting/


问:
extract numbers from dates in C
I got an assignment to convert numbers from a date.

we get the dates as a char string like 18.2.2014 for example, and I need to extract the integers 18, 2, 2014.

my way is not perfect...

what is the best way in your opinion?

```<code>void luckChoice(char a[]){

    int month=10*(a[3]-'0')+(a[4]-'0');
    int day=(a[0]-'0')*10+(a[1]-'0');
    int year=(a[9]-'0')+(a[8]-'0')*10+(a[7]-'0')*100+(a[6]-'0')*1000;
</code>```

答:
There are many ways to solve this.  A simple question is how much code should be used to detect invalid input?

Staying with the C standard library, code can process the string multiple times and catch many errors.

```<code>// Expand the f() signature
// void luckChoice(char a[]){
int luckChoice(const char a[], int *year, int *month, int *day) {
</code>```

Check format. "%n" saves the offset of the scan if it got that far.  "%*2[0-9]" matches 1 or 2 digits, yet does not save the result.  This is unlike "%d" which allows leadins spaces and '+' or '-'.

```<code>  int n = 0;
  sscanf(a, "%*2[0-9].%*2[0-9].%*4[0-9]%n", &n);
</code>```

If n is non-zero that the scan was completely successful.  So if that is the end of the string, then - oh happy day!

```<code>  if (n > 0 && a[n] == '\0') {
    sscanf(a, "%d.%d.%d", day, mon, year);
    // check ranges if desired
    if (*day < 1 || *day > 31) return 0;
    if (*mon < 1 || *mon > 12) return 0;

    // additional checks
    TDB_Code();

    return 1; // success
  }
  return 0; // failure
}
</code>```

Title: extract numbers from dates in C

Body:
I got an assignment to convert numbers from a date.

we get the dates as a char string like 18.2.2014 for example, and I need to extract the integers 18, 2, 2014.

my way is not perfect...

what is the best way in your opinion?

void luckChoice(char a[]){

    int month=10*(a[3]-'0')+(a[4]-'0');
    int day=(a[0]-'0')*10+(a[1]-'0');
    int year=(a[9]-'0')+(a[8]-'0')*10+(a[7]-'0')*100+(a[6]-'0')*1000;

Body:
There are many ways to solve this.  A simple question is how much code should be used to detect invalid input?

Staying with the C standard library, code can process the string multiple times and catch many errors.

// Expand the f() signature
// void luckChoice(char a[]){
int luckChoice(const char a[], int *year, int *month, int *day) {

Check format. "%n" saves the offset of the scan if it got that far.  "%*2[0-9]" matches 1 or 2 digits, yet does not save the result.  This is unlike "%d" which allows leadins spaces and '+' or '-'.

  int n = 0;
  sscanf(a, "%*2[0-9].%*2[0-9].%*4[0-9]%n", &n);

If n is non-zero that the scan was completely successful.  So if that is the end of the string, then - oh happy day!

  if (n > 0 && a[n] == '\0') {
    sscanf(a, "%d.%d.%d", day, mon, year);
    // check ranges if desired
    if (*day < 1 || *day > 31) return 0;
    if (*mon < 1 || *mon > 12) return 0;

    // additional checks
    TDB_Code();

    return 1; // success
  }
  return 0; // failure
}


问:
How i delete list in json file in python?
i have some code and json file like this

```<code>import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    for a in data:
       del a[param2]
with open('data/'+param1+'.json','w','utf-8') as f:
     json.dump(data, f, sort_keys=True, indent=4,ensure_ascii=False)
</code>```

json data

```<code>[
    "11111111111111",
    "22222222222222",
    "33333333333333"
]
</code>```

i want to delete the "11111111111111" and save in data/'+param1+'.json, but it say TypeError: 'unicode' object does not support item deletion

any solution for this?

答:
Use a.remove(value).

```<code>import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    for a in data:
       a.remove(param2)
with open('data/'+param1+'.json','w','utf-8') as f:
     json.dump(data, f, sort_keys=True, indent=4,ensure_ascii=False)
</code>```

Note that this will only remove the first occurrence of value from the list a. If you need to remove all occurrences I suggest a nested list comprehension.

```<code>with open('data/'+param1+'.json') as json_data:
        data = json.load(json_data)
        data = [[i for i in a if i != param2] for a in data]
</code>```

Body:
i have some code and json file like this

import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    for a in data:
       del a[param2]
with open('data/'+param1+'.json','w','utf-8') as f:
     json.dump(data, f, sort_keys=True, indent=4,ensure_ascii=False)

json data

[
    "11111111111111",
    "22222222222222",
    "33333333333333"
]

i want to delete the "11111111111111" and save in data/'+param1+'.json, but it say TypeError: 'unicode' object does not support item deletion

any solution for this?

Body:
Use a.remove(value).

import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    for a in data:
       a.remove(param2)
with open('data/'+param1+'.json','w','utf-8') as f:
     json.dump(data, f, sort_keys=True, indent=4,ensure_ascii=False)

Note that this will only remove the first occurrence of value from the list a. If you need to remove all occurrences I suggest a nested list comprehension.

with open('data/'+param1+'.json') as json_data:
        data = json.load(json_data)
        data = [[i for i in a if i != param2] for a in data]


答:
Your data is a list.  When you iterate over it, a is a Unicode string.  Instead of:

```<code>for a in data:
   del a[param2]
</code>```

Just remove the item from the list:

```<code>data.remove(param2)
</code>```

Whole code (Python 2):

```<code>import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    data.remove(param2)

# Python 2 doesn't take an encoding parameter.
with open('data/'+param1+'.json','w') as f:
     json.dump(data, f, sort_keys=True, indent=4, ensure_ascii=False)
</code>```

Result:

```<code>[
    "22222222222222",
    "33333333333333"
]
</code>```

Title: How i delete list in json file in python?

Body:
Your data is a list.  When you iterate over it, a is a Unicode string.  Instead of:

for a in data:
   del a[param2]

Just remove the item from the list:

data.remove(param2)

Whole code (Python 2):

import json

param1 = "xxxxxx"
param2 = "11111111111111"
param3 = "333333333"

with open('data/'+param1+'.json') as json_data:
    data = json.load(json_data)
    data.remove(param2)

# Python 2 doesn't take an encoding parameter.
with open('data/'+param1+'.json','w') as f:
     json.dump(data, f, sort_keys=True, indent=4, ensure_ascii=False)

Result:

[
    "22222222222222",
    "33333333333333"
]


问:
Select elements of html table and change contents using jquery

Hello Professionals

I have a table in my asp.net page

Search Results : 25

          No.
          Album Name
          Year
          Artist

          1

             Al Muallim

          2003
          Sami Yusuf

          2

             Barakah

          2017
          Sami Yusuf

```
</div>
</div>
</p>

<p><br />
the table you see is an html template, it has 25 rows as you see in the <code><span></code> in the <code><h4></code> . <br /><br />
I get data of Albums by ajax and I want by jQuery to assign the values in there palces in the table. <br />
I am using a loop on the 25 rows, and for every row I must reach the <code><img></code> in the second <code><td></code> to change its <code>src</code> , same for the <code><spane></code> beside it to change the text inside it which is the album name.<br />
In the third <code><td></code> also to change the year in it .<br />
In the forth <code><td></code> I need to change the <code>href</code> of <code><a></code> and the text of <code><a></code> which is the name of the artist. <br />
Do you see that <code>id="a"</code> in the first <code><div></code>, this is because I have like this table for every letter in the alphabet, where the letter is the <code>id</code> for that table, <br /> and there is an A-ZList of the letters where a click on a letter wil make request to bring the albums with names start with the clicked letter, and assing them from the <code>XmlHttpRequest.responseText</code> to the table. <br />
Thats why I use <code>letter</code> variable in this jQuery code to pass the <code>id</code> of the first <code><div></code> to assign the values into the table , because there is another <code><div id="b"></code> and so on <br /></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // keep calling until i is 25
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(1).children().eq(0).children().eq(0).attr("src", albumPhotoPath);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(2).text(albumYear);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(3).children().eq(0).text(artistName);
  }
}</code>```

by the this code I can assing the albumYear in the third  and artistName in thr fourth ,
 but could not change in the second  the albumPhotoPath in  src and the albumName in the

Can I extend the question

This page as you see from the explanation, is a search page

And I have all the information of the album except the songs of the album, so how can I pass these information to a page called Single.aspx dedcated to show an album information and its songs after clicking the  in the second , and in the Single.aspx I only need by ajax to request the songs of the album not all the information again.

I think the passing will be as a QueryString in the href of  in the second , is there another way?

I thank you so much so much

答:
The question looks like it's all over the place so here's what I think you are asking:

How do you display data in a HTML table?

Details commented in Demo

Demo

// Reference to section "N"
var char = document.querySelector('section').id;
console.log(char);
// Counter
var index = 0;
// Object of arrays
var data = {
  url0: ['https://en.wikipedia.org/wiki/Nevermind', 'https://en.wikipedia.org/wiki/Tragic_Kingdom'],
  img: ['https://upload.wikimedia.org/wikipedia/en/b/b7/NirvanaNevermindalbumcover.jpg', 'https://upload.wikimedia.org/wikipedia/en/9/9d/No_Doubt_-_Tragic_Kingdom.png'],
  album: ['NeverMind', 'Tragic Kingdom'],
  year: ['1991', '1995'],
  url1: ['https://en.wikipedia.org/wiki/Nirvana_(band)', 'https://en.wikipedia.org/wiki/No_Doubt'],
  artist: ['Nirvana', 'No Doubt']
};
// Pass data
function DisplayAlbum(data) {
  // Reference the counter
  this.idx = index;
  // Object data property values by index
  this.url0 = data['url0'][index];
  this.img = data['img'][index];
  this.album = data['album'][index];
  this.year = data['year'][index];
  this.url1 = data['url1'][index];
  this.artist = data['artist'][index];
  /* Row is a Template Literal with all of
  || object data's values interpolated
  */
  this.row = `

  ${idx+1}

  ${album}

  ${year}

  ${artist}

`;
  index++;
  return this.row;
}
/* On button click append the return of
|| DisplayAlbum()
*/
$('#' + char + ' .btn').on('click', function() {
  $('#' + char + ' .table').append(DisplayAlbum(data));
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
  font: 100 10px/1 Consolas;
}

img {
  width: 64px;
  height: 64px;
  display: block;
  margin: 0 auto;
}

button {
  font: inherit
}

td {
  text-align: center
}

.as-console-wrapper {
  width: 30%;
  margin-left: 70%;
}</code>```

Search Results:
        <output class='hits'></output>

      <button class='btn'>Add Row</button>

          No.
          Album
          Year
          Artist

```

Body:
Hello Professionals

I have a table in my asp.net page

Search Results : 25

          No.
          Album Name
          Year
          Artist

          1

             Al Muallim

          2003
          Sami Yusuf

          2

             Barakah

          2017
          Sami Yusuf

the table you see is an html template, it has 25 rows as you see in the  in the
 .

I get data of Albums by ajax and I want by jQuery to assign the values in there palces in the table.

I am using a loop on the 25 rows, and for every row I must reach the  in the second  to change its src , same for the <spane> beside it to change the text inside it which is the album name.

In the third  also to change the year in it .

In the forth  I need to change the href of  and the text of  which is the name of the artist.

Do you see that id="a" in the first
, this is because I have like this table for every letter in the alphabet, where the letter is the id for that table,
 and there is an A-ZList of the letters where a click on a letter wil make request to bring the albums with names start with the clicked letter, and assing them from the XmlHttpRequest.responseText to the table.

Thats why I use letter variable in this jQuery code to pass the id of the first
 to assign the values into the table , because there is another
 and so on

function AssignAlbumIntoDOM(albumName, albumYear, albumPhotoPath, artistName, albumsCount, i, letter) {
  if (i < 25 && i >= 0) { // keep calling until i is 25
    jQuery("#" + letter + " h4 span").text(albumsCount);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(1).children().eq(0).children().eq(0).attr("src", albumPhotoPath);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(2).text(albumYear);
    jQuery("#" + letter + " table tbody").children().eq(i).children().eq(3).children().eq(0).text(artistName);
  }
}

by the this code I can assing the albumYear in the third  and artistName in thr fourth ,
 but could not change in the second  the albumPhotoPath in  src and the albumName in the

Can I extend the question

This page as you see from the explanation, is a search page

And I have all the information of the album except the songs of the album, so how can I pass these information to a page called Single.aspx dedcated to show an album information and its songs after clicking the  in the second , and in the Single.aspx I only need by ajax to request the songs of the album not all the information again.

I think the passing will be as a QueryString in the href of  in the second , is there another way?

I thank you so much so much

Body:
The question looks like it's all over the place so here's what I think you are asking:

How do you display data in a HTML table?

Details commented in Demo

Demo

// Reference to section "N"
var char = document.querySelector('section').id;
console.log(char);
// Counter
var index = 0;
// Object of arrays
var data = {
  url0: ['https://en.wikipedia.org/wiki/Nevermind', 'https://en.wikipedia.org/wiki/Tragic_Kingdom'],
  img: ['https://upload.wikimedia.org/wikipedia/en/b/b7/NirvanaNevermindalbumcover.jpg', 'https://upload.wikimedia.org/wikipedia/en/9/9d/No_Doubt_-_Tragic_Kingdom.png'],
  album: ['NeverMind', 'Tragic Kingdom'],
  year: ['1991', '1995'],
  url1: ['https://en.wikipedia.org/wiki/Nirvana_(band)', 'https://en.wikipedia.org/wiki/No_Doubt'],
  artist: ['Nirvana', 'No Doubt']
};
// Pass data
function DisplayAlbum(data) {
  // Reference the counter
  this.idx = index;
  // Object data property values by index
  this.url0 = data['url0'][index];
  this.img = data['img'][index];
  this.album = data['album'][index];
  this.year = data['year'][index];
  this.url1 = data['url1'][index];
  this.artist = data['artist'][index];
  /* Row is a Template Literal with all of
  || object data's values interpolated
  */
  this.row = `
  <tr>
  <td>${idx+1}</td>
  <td><a href="${url0}">
  <img src="${img}">
  ${album}</a>
  </td>
  <td>${year}</td>
  <td><a href="${url1}">
  ${artist}</a>
  </td>
  </tr>`;
  index++;
  return this.row;
}
/* On button click append the return of
|| DisplayAlbum()
*/
$('#' + char + ' .btn').on('click', function() {
  $('#' + char + ' .table').append(DisplayAlbum(data));
});

html {
  font: 100 10px/1 Consolas;
}

img {
  width: 64px;
  height: 64px;
  display: block;
  margin: 0 auto;
}

button {
  font: inherit
}

td {
  text-align: center
}

.as-console-wrapper {
  width: 30%;
  margin-left: 70%;
}

<section id="N" class='a-z'>
  <div>
    <header>
      <h4>Search Results:
        <output class='hits'></output>
      </h4>
      <button class='btn'>Add Row</button>
    </header>
    <table class="table">
      <thead>
        <tr>
          <th>No.</th>
          <th>Album</th>
          <th>Year</th>
          <th>Artist</th>
        </tr>
      </thead>
      <tbody>

      </tbody>
    </table>
  </div>
</section>

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


问:
authentication problem or bug
There are 3 web apps.

Site A and B are both ASP.NET Web Application with FormsAuthentications configurations, and there is a protected folder in site B which also configured correctly in the web.config. Site C is a classic ASP web which keep authentication status with Session.

Now please consider the following steps:

1, There is a link with target="_blank" property on a page of site A and link to the protected folder of site B;

2, Click this link you should open the site B in a new browser window and redirect to the log in page;

3, Log in with your credentials then redirect to the protected page normally, now you can browse that page of site B of course;

4, Now close the browser window which shows the protected page of site B, you can click the close button of browser or press Alt+F4;

5, Then click the link on site A again, now you can access the protected page of site B without logging in again.

6, There is another link also with target="_blank" on a page of site A and link to the protected page of site C, site C is an ASP site;

7, First open the protected page of site C, log in is required exactly;

8, Logging in the site C and you can view the protected page of course, then close the browser;

9, Click the link to site C again, you can find yourself already authenticated on site C.

Oops. there are 10 steps already, I think these are boring but they are really make me confused for few days.

Anybody know about this issue?
Great Thanks.

答:
Use session.abandoned on window.close event for example.

Create function which will be loaded in header and catch event window.close.
Do not forget to verify if previous page is from the same domain/IP.
Because your user can forgot to logoff and go to some other website and then click back button...

OwnerDisplayName: Shiny

Title: authentication problem or bug

LastEditorDisplayName: Shiny


问:
Cookie management using Okta authentication api
In my app I have called authentication api and below is code for same

```<code>NSMutableDictionary* paraDict = [[NSMutableDictionary alloc] init];
[paraDict setObject:@"userid" forKey:@"username"];
[paraDict setObject:@"password" forKey:@"password"];

NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"https://my.oktapreview.com/api/v1/authn"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:paraDict options:0 error:&error];
[request setHTTPBody:postData];

[request setHTTPShouldHandleCookies:YES];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if ([(NSHTTPURLResponse*)response statusCode] == 200) {
        aBlock(YES);
    }
}];

[postDataTask resume];
</code>```

After this I am getting success response, but not able to get all cookies associated with ( When checked with PostMan with same request, have received around 12 cookies with response )

For reading cookie, I am using

```<code>for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
    NSLog(@"name: '%@'\n",   [cookie name]);
    NSLog(@"value: '%@'\n",  [cookie value]);
    NSLog(@"domain: '%@'\n", [cookie domain]);
    NSLog(@"path: '%@'\n",   [cookie path]);
}
</code>```

is there way to set cookie acceptance policy.

答:
Perhaps you can extract the returned cookies from the response using NSHTTPCookie's -cookiesWithResponseHeaderFields:forURL: method passing in the response your data task receives.

Like so

```<code>task = [session dataTaskWithRequest:... completionHandler:^(...) {
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[(NSHTTPURLResponse *)response allHeaderFields] forURL:request.URL];
    // Use cookies
}];
</code>```

Body:
In my app I have called authentication api and below is code for same

NSMutableDictionary* paraDict = [[NSMutableDictionary alloc] init];
[paraDict setObject:@"userid" forKey:@"username"];
[paraDict setObject:@"password" forKey:@"password"];

NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:@"https://my.oktapreview.com/api/v1/authn"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                   timeoutInterval:60.0];

[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
NSData *postData = [NSJSONSerialization dataWithJSONObject:paraDict options:0 error:&error];
[request setHTTPBody:postData];

[request setHTTPShouldHandleCookies:YES];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if ([(NSHTTPURLResponse*)response statusCode] == 200) {
        aBlock(YES);
    }
}];

[postDataTask resume];

After this I am getting success response, but not able to get all cookies associated with ( When checked with PostMan with same request, have received around 12 cookies with response )

For reading cookie, I am using

for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies])
{
    NSLog(@"name: '%@'\n",   [cookie name]);
    NSLog(@"value: '%@'\n",  [cookie value]);
    NSLog(@"domain: '%@'\n", [cookie domain]);
    NSLog(@"path: '%@'\n",   [cookie path]);
}

is there way to set cookie acceptance policy.

Body:
Perhaps you can extract the returned cookies from the response using NSHTTPCookie's -cookiesWithResponseHeaderFields:forURL: method passing in the response your data task receives.

Like so

task = [session dataTaskWithRequest:... completionHandler:^(...) {
    NSArray<NSHTTPCookie *> *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[(NSHTTPURLResponse *)response allHeaderFields] forURL:request.URL];
    // Use cookies
}];


问:
Creating incremental df file from 2 different df files
Is there a method to create an incremental .df file from 2 different .df files? Or do I have to load both files into 2 blank databases and then use the create incremental .df file feature from Data Administration tool?

I'm using Openedge 10.2B08

答:
Loading them both in a blank database then dumping one solid DF remains the best solutions in my opinion.

Of course you could shaves a couple of minutes by appending one file to the other, I think you can even remove the footer and not bother, it should work.

As with everything it depends on the critical aspect of the situation. Are you looking at important downtime on a production database? Usually there shouldn't be much compromise on whatever will be applied to production. A solid DF is better than a "hacked 99.9% safe" one. That's the difference between a good and bad Dba. The good one may seems to work a bit slower over a decade. But once in that decade the bad one will eventually provoke some critical  downtime to a business...totally offsetting the silly productivity advantage he may looks like to have.

I fixed countless mistakes all around for the past 15 years, I made one. It's not a fun feeling. Being waked up early Monday by a panicked helpdesk guy that describes the issue. Quickly realising it's related to the previous night maintenance I made. Replying to get all users out, country wide going to an halt while I'm trying to figure what's wrong and how to fix it. 2500 employees were being paid but wasn't able to work... With customers in front of them with money to spend and no time to lose.

Took me 3 hours. It wasn't a lazy mistake... Just a mistake with no easy way to notice while doing the usual post-update quick tests to make sure it runs fine. We had Gui code running code against a training database while the usual business logic was being executed on Unix and production.

Don't need a math genius to compute that a silly DBA mistake was costing more than his annual salary every few minutes.

Mistakes happens but folks, if a few minutes of added work is the root cause of one, time to leave the seat to someone else I'm afraid.  No shame there, it's simply a job that requires that mindset and some people needs decades to eventually get caught off-guard and realize it. Nothing is very fun about spending precious time triple checking a 99.9% safe update...nobody will notice the added effort next Monday as it will work regardless as usual. Everybody will yell if it's not working, your fault or not.

My mutli-million mistake never ever got mentioned once it was solved. Everyone knew very well that I can count lost cash and that I've never cut corners for any reason during my whole career. It's still only money... I could now go with the mistake that almost killed 2 youngs workers lifes a few years later.

Stress and way too many hours, it can le
ad to a reflex F1 and kill mechanics working in some automation device.

Stay safe with that keyboard guys, it's serious business  ;)


问:
a jQuery promise that always succeeds?
I have this code jQuery code fragment:

```<code>$.get('/api/' + currentPage).done(function(data) { ... })
                            .fail(...)
</code>```

I want to replace $.get('/api/'+currentPage) with a promise that always succeeds and returns a specific value for data. Something like:

```<code>let myData = { ... }  // value of data I want to pass to the done function

(new AlwaysSucceeds(myData)).done(function(data) { ... })
                            .fail(...)
</code>```

I could cobble up a dummy object, or I could extract out the done function but I want to keep changes to the code to a minimum.

Is there a way to do this?

UPDATE: To help clarify what's going, the code I am working with is (here). Normally this app is served from a nodejs server which implements the /api/... call, but I am converting it to be served
from a static page server. I know what is going to be returned from
the $.get call. To keep changes to the code clean I simply want to
change that line to:

```<code>let myData = {...}

// $.get('/api/' + currentPage) -- comment out the $.get call
(SOMETHINGHERE(myData)).done(function(data) {
</code>```

The SOMETHINGHERE expression needs to implement .done(f)
which will call the function f with myData and then return
some object which implements .fail(...) which does nothing.

答:
You can just replace $.get(...) with a function that returns a promise that is already resolved with the data you already have.  And, the shortest way to get an already resolved jQuery promise, resolved with a particular value, is this:

```<code>$.when(myData).done(...)
</code>```

The more text book way to do it in jQuery is:

```<code>$.Deferred().resolve(myData).done(...)
</code>```

And, if you care to switch your logic to the the ES6 standard (instead of the non-standard jQuery promise behaviors), then you could use this:

```<code>Promise.resolve(myData).then(...).catch(...)
</code>```

Title: a jQuery promise that always succeeds?

Body:
You can just replace $.get(...) with a function that returns a promise that is already resolved with the data you already have.  And, the shortest way to get an already resolved jQuery promise, resolved with a particular value, is this:

$.when(myData).done(...)

The more text book way to do it in jQuery is:

$.Deferred().resolve(myData).done(...)

And, if you care to switch your logic to the the ES6 standard (instead of the non-standard jQuery promise behaviors), then you could use this:

Promise.resolve(myData).then(...).catch(...)