问:
Using results from the loops for another one
I have to say sorry because I know that this is kind of a silly question (I just started learning java) but how can I use a "while" loop result for another loop? I need to prepare a program that will add digits from two given numbers. First of all I need to add digits from number1 then number2 and at the end sum digits of both. sum1 and sum2 are working pretty nice but its ending at this point, sum3, and operations in loop nr3 are invisible for my machine.

I think I should combine it somehow into one loop but I got no idea how (I'm learning from Horstmann and Cadenhead books and there is no good answer)

Thank you for answer and I will be glad if it's not going to be a straight code upgrade but maybe some kind of hint where or what I should search! Thank You :)
I have got something like this:

```<code>public static void main(String[] args) {
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    while (l1 > 0) {
        sum1 += l1 % 10;
        l1 /= 10;
    }
    //System.out.println(sum1);
    while (l2 > 0) {
        sum2 += l2 % 10;
        l2 /= 10;
    }
    //System.out.println(sum2);
    while (sum1+sum2>0) {
        sum3 +=(sum1+sum2) %10;
        (sum1+sum2) /=10;
    }

}
</code>```

答:
the main problem is that result of /= operator should be stored somewhere, result of sum1+sum2 does not provide such storage.

to make this code work, you need to store sum1+sum2 into some temp variable, so replace

```<code>while (sum1+sum2>0) {
    sum3 +=(sum1+sum2) %10;
    (sum1+sum2) /=10;
}
</code>```

with something like:

```<code>int tempsum = sum1 + sum2;
while (tempsum > 0) {
    sum3 += tempsum % 10;
    tempsum /= 10;
}
</code>```

Body:
I have to say sorry because I know that this is kind of a silly question (I just started learning java) but how can I use a "while" loop result for another loop? I need to prepare a program that will add digits from two given numbers. First of all I need to add digits from number1 then number2 and at the end sum digits of both. sum1 and sum2 are working pretty nice but its ending at this point, sum3, and operations in loop nr3 are invisible for my machine.

I think I should combine it somehow into one loop but I got no idea how (I'm learning from Horstmann and Cadenhead books and there is no good answer)

Thank you for answer and I will be glad if it's not going to be a straight code upgrade but maybe some kind of hint where or what I should search! Thank You :)
I have got something like this:

public static void main(String[] args) {
    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    while (l1 > 0) {
        sum1 += l1 % 10;
        l1 /= 10;
    }
    //System.out.println(sum1);
    while (l2 > 0) {
        sum2 += l2 % 10;
        l2 /= 10;
    }
    //System.out.println(sum2);
    while (sum1+sum2>0) {
        sum3 +=(sum1+sum2) %10;
        (sum1+sum2) /=10;
    }

}

Body:
the main problem is that result of /= operator should be stored somewhere, result of sum1+sum2 does not provide such storage.

to make this code work, you need to store sum1+sum2 into some temp variable, so replace

while (sum1+sum2>0) {
    sum3 +=(sum1+sum2) %10;
    (sum1+sum2) /=10;
}

with something like:

int tempsum = sum1 + sum2;
while (tempsum > 0) {
    sum3 += tempsum % 10;
    tempsum /= 10;
}


来源: stackexchange

问:
Owned types collection is never updated in EF Core
I have an aggregate defined like this:

```<code>public class Product {
    public int LocalId { get; private set; }
    public Something Something { get; private set; }
    public ICollection<Price> Prices { get; private set; }
}

public class Something {
    public string Name { get; set; }
}

public class Price {
    public int Type { get; set; }
    public decimal Value { get; set; }
}
</code>```

And a schema defined like this:

```<code>private void DefineProduct(ModelBuilder builder) =>
    builder
        .Entity<Product>(builder =>
        {
            builder.HasKey(p => p.LocalId);
            builder
                .OwnsOne(p => p.Something, smth =>
                {
                    smth.ToTable("somethings");
                })
                .OwnsMany(p => p.Prices, pp =>
                {
                    pp.ToTable("prices");
                });
        });
</code>```

When a price change is requested, I do this (inside the product method not included here for brevity):

```<code>Prices.First(p => p.Type == type).Value = newValue;
</code>```

And then I try to save the product like this:

```<code>public async Task UpdateProperties(Product product, IEnumerable<object> props)
{
    _context.Attach(product);
    _context.Update(product);

    foreach (var prop in props)
    {
        _context.Update(prop);
    }

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Who the hell allowed such a bug to go into a production release?");
    }
}
</code>```

Now I should mention that the product comes in from an initial query whose results were not tracked (via AsNoTracking() call), that's why I'm calling the Attach method in the first line of the method body. The problem is that I'm hitting that catch statement with an exception message saying:

Database operation expected to affect 1 row(s) but actually affected 0
  row(s). Data may have been modified or deleted since entities were
  loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for
  information on understanding and handling optimistic concurrency
  exceptions."}

The thing is that I'm not updating the same product anywhere else and that's the only place touching it. Also I use AsNoTracking as the default. If I comment out the line with _context.Update(prop);, then there's no exception raised, but the price is not being updated. Also, if I don't update that prices collection but the Something property, everything goes well. What. The. Hell.

答:
EF Core documentation for Collections of owned types explicitly states that you have to define the owned entity PK (as opposed to OwnsOne where the shadow FK is normally used as PK).

Hence you need to either define its own PK (like Id you did), or composite PK - for instance, if Price.Type is unique inside the owner, then you can use something like

```<code>pp.HasKey("LocalId", "Type");
</code>```

and avoid the additional Id column.

ContentLicense: CC BY-SA 4.0

Body:
I have an aggregate defined like this:

public class Product {
    public int LocalId { get; private set; }
    public Something Something { get; private set; }
    public ICollection<Price> Prices { get; private set; }
}

public class Something {
    public string Name { get; set; }
}

public class Price {
    public int Type { get; set; }
    public decimal Value { get; set; }
}

And a schema defined like this:

private void DefineProduct(ModelBuilder builder) =>
    builder
        .Entity<Product>(builder =>
        {
            builder.HasKey(p => p.LocalId);
            builder
                .OwnsOne(p => p.Something, smth =>
                {
                    smth.ToTable("somethings");
                })
                .OwnsMany(p => p.Prices, pp =>
                {
                    pp.ToTable("prices");
                });
        });

When a price change is requested, I do this (inside the product method not included here for brevity):

Prices.First(p => p.Type == type).Value = newValue;

And then I try to save the product like this:

public async Task UpdateProperties(Product product, IEnumerable<object> props)
{
    _context.Attach(product);
    _context.Update(product);

    foreach (var prop in props)
    {
        _context.Update(prop);
    }

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (Exception ex)
    {
        Console.WriteLine("Who the hell allowed such a bug to go into a production release?");
    }
}

Now I should mention that the product comes in from an initial query whose results were not tracked (via AsNoTracking() call), that's why I'm calling the Attach method in the first line of the method body. The problem is that I'm hitting that catch statement with an exception message saying:

Database operation expected to affect 1 row(s) but actually affected 0
  row(s). Data may have been modified or deleted since entities were
  loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for
  information on understanding and handling optimistic concurrency
  exceptions."}

The thing is that I'm not updating the same product anywhere else and that's the only place touching it. Also I use AsNoTracking as the default. If I comment out the line with _context.Update(prop);, then there's no exception raised, but the price is not being updated. Also, if I don't update that prices collection but the Something property, everything goes well. What. The. Hell.

Body:
EF Core documentation for Collections of owned types explicitly states that you have to define the owned entity PK (as opposed to OwnsOne where the shadow FK is normally used as PK).

Hence you need to either define its own PK (like Id you did), or composite PK - for instance, if Price.Type is unique inside the owner, then you can use something like

pp.HasKey("LocalId", "Type");

and avoid the additional Id column.


问:
Call bootstrap alert with jquery
I'm trying to call a bootstrap alert with jQuery while meeting some if statements.

Here is my code in HTML:

Attention

You haven't select the metrial you need

Are you going to check next step anyway?

    <button type="button" class="btn btn-primary">Yes</button>
    <button type="button" class="btn btn-secondary">No</button>

```

<p>here is my code for jQuery:</p>

<pre class="lang-js prettyprint-override"><code>if ($("#checkbox1").prop('checked')==false){
    $(".alert").addClass('in');
    return false;
}
</code>```

I want to call this alert while one specific checkbox is not checked as I wrote above.

I also want to mention: I used $(".alert").hide(); to hide my alert when the page is loaded – not sure if that's correct.

I want to know how to call this alert when specific conditions are met and how to hide it properly.

Thanks

答:
You can do this via toggling the CSS display attribute as below:

$("#triggerAlert").change(function() {
  if (this.checked) {
    $('#myAlert').css('display', 'none');
  } else {
    $('#myAlert').css('display', 'block');
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

Hide alert: <input type='checkbox' id='triggerAlert' />

<div class="alert alert-warning fade show" role="alert" id="myAlert">
  <h4 class="alert-heading">Attention</h4>
  <p>You haven't select the metrial you need</p>
  <hr>
  <p class="mb-0">Are you going to check next step anyway?</p>
  <button type="button" class="btn btn-primary">Yes</button>
  <button type="button" class="btn btn-secondary">No</button>
</div>
<p>something after</p></code>```

Title: Call bootstrap alert with jquery

Body:
I'm trying to call a bootstrap alert with jQuery while meeting some if statements.

Here is my code in HTML:

Attention

You haven't select the metrial you need

Are you going to check next step anyway?

    <button type="button" class="btn btn-primary">Yes</button>
    <button type="button" class="btn btn-secondary">No</button>

here is my code for jQuery:

if ($("#checkbox1").prop('checked')==false){
    $(".alert").addClass('in');
    return false;
}

I want to call this alert while one specific checkbox is not checked as I wrote above.

I also want to mention: I used $(".alert").hide(); to hide my alert when the page is loaded – not sure if that's correct.

I want to know how to call this alert when specific conditions are met and how to hide it properly.

Thanks

Body:
You can do this via toggling the CSS display attribute as below:

$("#triggerAlert").change(function() {
  if (this.checked) {
    $('#myAlert').css('display', 'none');
  } else {
    $('#myAlert').css('display', 'block');
  }
})

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

Hide alert: <input type='checkbox' id='triggerAlert' />

<div class="alert alert-warning fade show" role="alert" id="myAlert">
  <h4 class="alert-heading">Attention</h4>
  <p>You haven't select the metrial you need</p>
  <hr>
  <p class="mb-0">Are you going to check next step anyway?</p>
  <button type="button" class="btn btn-primary">Yes</button>
  <button type="button" class="btn btn-secondary">No</button>
</div>
<p>something after</p>


问:
Huge delay in CompletableFuture join() method
So I'm working on an application that has to make 20+ HTTP calls at a time. Each one of them takes 2-3 seconds to get a response.  It's pretty slow to make these calls one at a time (40 seconds at best), so I am trying to send them asynchronously via CompletableFutures. This should allow me to make calls while I'm waiting for the response of others, in theory reducing the total time to maybe 4-5 seconds instead of 40.

I made a very similar setup to this tutorial I found at https://www.codepedia.org/ama/how-to-make-parallel-calls-in-java-with-completablefuture-example.

```<code>import org.codingpedia.example;

import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ParallelCallsDemoService {

    @Inject
    RestApiClient restApiClient;

    private ExecutorService es = Executors.newFixedThreadPool(20);

    public List<ToDo> getToDos(List<String> ids){

        List<CompletableFuture<ToDo>> futures =
                ids.stream()
                          .map(id -> getToDoAsync(id))
                          .collect(Collectors.toList());

        List<ToDo> result =
                futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList());

        return result;
    }

    CompletableFuture<ToDo> getToDoAsync(String id){

        CompletableFuture<ToDo> future = CompletableFuture.supplyAsync(() -> {
            return restApiClient.makeSomeHttpCall(id);
        }, es);

        return future;
    }

}
</code>```

By all accounts it seems to be working - the calls all get sent at roughly the same time, and they all return in a couple seconds. But then I'm experiencing a huge delay of 30-40 seconds on this part:

```<code>        List<ToDo> result =
                futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList());
</code>```

This makes it take roughly the same time as sending serially, which baffles me.  How can it be that I'm getting all responses in a couple seconds but then there's a 30 second delay on joining them? It's almost as if (despite appearances) they're still being made serially. Why does the join take so long?

答: Finally figured this out! Thanks everyone for your suggestions. Turns out it was nothing to do with my implementation of CompletableFutures.  When I receive a response from the service, I use JAXB to convert the java object to an XML string for logging purposes. I started looking at thread dumps when it was hanging, and realized it was actually the JAXB string conversion that the threads were waiting for (the response object is quite large). I took out that part, and the performance immediately improved to what it should have been.</p>

Body:
So I'm working on an application that has to make 20+ HTTP calls at a time. Each one of them takes 2-3 seconds to get a response.  It's pretty slow to make these calls one at a time (40 seconds at best), so I am trying to send them asynchronously via CompletableFutures. This should allow me to make calls while I'm waiting for the response of others, in theory reducing the total time to maybe 4-5 seconds instead of 40.

I made a very similar setup to this tutorial I found at https://www.codepedia.org/ama/how-to-make-parallel-calls-in-java-with-completablefuture-example.

import org.codingpedia.example;

import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class ParallelCallsDemoService {

    @Inject
    RestApiClient restApiClient;

    private ExecutorService es = Executors.newFixedThreadPool(20);

    public List<ToDo> getToDos(List<String> ids){

        List<CompletableFuture<ToDo>> futures =
                ids.stream()
                          .map(id -> getToDoAsync(id))
                          .collect(Collectors.toList());

        List<ToDo> result =
                futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList());

        return result;
    }

    CompletableFuture<ToDo> getToDoAsync(String id){

        CompletableFuture<ToDo> future = CompletableFuture.supplyAsync(() -> {
            return restApiClient.makeSomeHttpCall(id);
        }, es);

        return future;
    }

}

By all accounts it seems to be working - the calls all get sent at roughly the same time, and they all return in a couple seconds. But then I'm experiencing a huge delay of 30-40 seconds on this part:

        List<ToDo> result =
                futures.stream()
                        .map(CompletableFuture::join)
                        .collect(Collectors.toList());

This makes it take roughly the same time as sending serially, which baffles me.  How can it be that I'm getting all responses in a couple seconds but then there's a 30 second delay on joining them? It's almost as if (despite appearances) they're still being made serially. Why does the join take so long?


问:
why if statement not working as expected with multiple conditions when calling crystal reports asp.net?
I am printing result report in medical laboratory system , and i have IF statement with multiple conditions with && and || , then i call crystal report depending on that condition and I am using stored procedure and passing parameters when run the report.
IF statement not working and not passing parameters to the report .
I am using this code when click print link and in page load :

```<code>    protected void Page_Load(object sender, EventArgs e)
{

            if (!IsPostBack)
            {

                TXTORDERID.Text = Request.QueryString["order_id"].ToString();
                TXTDEPTID.Text = Request.QueryString["DEPT ID"].ToString();

    if (Convert.ToInt32(Session["custid"]) > 1 && Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4 )
                        {
                            paramField.Name = "@ORDER_ID";
                            paramDiscreteValue.Value = TXTORDERID.Text.ToString();
                            paramField.CurrentValues.Add(paramDiscreteValue);
                            paramFields.Add(paramField);

                            paramField = new ParameterField();
                            paramDiscreteValue = new ParameterDiscreteValue();
                            paramField.Name = "@deptid";
                            paramDiscreteValue1.Value = TXTDEPTID.Text.ToString();
                            paramField.CurrentValues.Add(paramDiscreteValue1);
                            paramFields.Add(paramField);

                            CrystalReportViewer1.ParameterFieldInfo = paramFields;
                            CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
                            CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
                            reportDocument.Load(Server.MapPath("~/RPT/RPT_RESULTS.rpt"));
                            CrystalReportViewer1.ReportSource = reportDocument;
}
</code>```

now when i use the IF statement like this code its not passing the parameters direct to the report and ask for report parameters order_id and dept_id

```<code>if (Convert.ToInt32(Session["custid"]) > 1 && Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4 )
</code>```

and when i use IF statement like this code with () after && its not ask for parameter and run empty report

```<code>if (Convert.ToInt32(Session["custid"]) > 1 && (Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4) )
</code>```

how to update IF statement to run the report without ask for report parameter value @order_id and @deptid ?

答:
I know its an old post, but if it's of some help to somebody else

Essentially your 2 if statements summarizes as below

if( boolean1 &&  boolean2 || boolean3 || boolean4 || boolean5)

The expression evaluates boolean1 and boolean2 if true then checks the remaining

if(boolean1 && (boolean2 || boolean3 || boolean4 || boolean5))

The expression evaulates boolean1 && the result of boolean in the paranthesis

You can read about Conditional logical operators and its short-circuit behavior
 here

Body:
I am printing result report in medical laboratory system , and i have IF statement with multiple conditions with && and || , then i call crystal report depending on that condition and I am using stored procedure and passing parameters when run the report.
IF statement not working and not passing parameters to the report .
I am using this code when click print link and in page load :

    protected void Page_Load(object sender, EventArgs e)
{

            if (!IsPostBack)
            {

                TXTORDERID.Text = Request.QueryString["order_id"].ToString();
                TXTDEPTID.Text = Request.QueryString["DEPT ID"].ToString();

    if (Convert.ToInt32(Session["custid"]) > 1 && Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4 )
                        {
                            paramField.Name = "@ORDER_ID";
                            paramDiscreteValue.Value = TXTORDERID.Text.ToString();
                            paramField.CurrentValues.Add(paramDiscreteValue);
                            paramFields.Add(paramField);

                            paramField = new ParameterField();
                            paramDiscreteValue = new ParameterDiscreteValue();
                            paramField.Name = "@deptid";
                            paramDiscreteValue1.Value = TXTDEPTID.Text.ToString();
                            paramField.CurrentValues.Add(paramDiscreteValue1);
                            paramFields.Add(paramField);

                            CrystalReportViewer1.ParameterFieldInfo = paramFields;
                            CrystalReportViewer1.ReuseParameterValuesOnRefresh = true;
                            CrystalReportViewer1.ToolPanelView = CrystalDecisions.Web.ToolPanelViewType.None;
                            reportDocument.Load(Server.MapPath("~/RPT/RPT_RESULTS.rpt"));
                            CrystalReportViewer1.ReportSource = reportDocument;
}

now when i use the IF statement like this code its not passing the parameters direct to the report and ask for report parameters order_id and dept_id

if (Convert.ToInt32(Session["custid"]) > 1 && Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4 )

and when i use IF statement like this code with () after && its not ask for parameter and run empty report

if (Convert.ToInt32(Session["custid"]) > 1 && (Convert.ToInt32(TXTDEPTID.Text) == 1 || Convert.ToInt32(TXTDEPTID.Text) == 2 || Convert.ToInt32(TXTDEPTID.Text) == 3 || Convert.ToInt32(TXTDEPTID.Text) == 4) )

how to update IF statement to run the report without ask for report parameter value @order_id and @deptid ?


问:
How would i leave out the name jones but display people with the same deptno
```<code>SQL> select empno, ename, deptno
  2  from empcopy
  3  where deptno =
  4      (select deptno
  5       from empcopy
  6       where ename like 'JONES');

 EMPNO ENAME          DEPTNO
------ ---------- ----------
  7369 SMITH              20
  7566 JONES              20
  7788 SCOTT              20
  7876 ADAMS              20
  7902 FORD               20
</code>```

答:
Yet another option:</p>

```<code>SQL> with jones as
  2    (select ename, deptno
  3     from emp
  4     where ename = 'JONES'
  5    )
  6  select e.empno, e.ename, e.deptno
  7  from emp e join jones j on e.deptno = j.deptno and e.ename <> j.ename;

     EMPNO ENAME          DEPTNO
---------- ---------- ----------
      7369 SMITH              20
      7788 SCOTT              20
      7876 ADAMS              20
      7902 FORD               20

SQL>
</code>```

Body:
Yet another option:

SQL> with jones as
  2    (select ename, deptno
  3     from emp
  4     where ename = 'JONES'
  5    )
  6  select e.empno, e.ename, e.deptno
  7  from emp e join jones j on e.deptno = j.deptno and e.ename <> j.ename;

     EMPNO ENAME          DEPTNO
---------- ---------- ----------
      7369 SMITH              20
      7788 SCOTT              20
      7876 ADAMS              20
      7902 FORD               20

SQL>


问:
Unnecessary rerenders with useContext
In this example

```<code>function App() {
  const [value1, dispatch1] = useReducer(reducer, initialState1);
  const [value2, dispatch2] = useReducer(reducer, initialState2);

  return (
    <React.Fragment>
      <button
        onClick={() => {
          dispatch1({ type: "setFirstName", firstName: "nick" });
        }}
      >
        change1
      </button>
      <button
        onClick={() => {
          dispatch2({ type: "setFamilyName", familyName: "fname" });
        }}
      >
        change2
      </button>
      <JediContext1.Provider value={value1}>
        <Display1 />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <Display2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}
</code>```

I used two context per recommendation from here. But I might have misunderstood and maybe github issue is referring to another case? Because it doesn't seem to solve my problem.

The problem with above code is if I click change1 button, which changes value1, component Display2 is also rerendered which doesn't even consume value1.

Actually this makes sense to me because I changed state in App, hence it would rerender all its children. But then I don't understand the use of recommendation from the github link, because it didn't solve my problem here?

This maybe problematic performance wise if you have large app and root context provider say.

答:
Try memoizing both components so they only render when their local state changes:

```<code>const MemoDisplay = React.memo(Display1);
const MemoDisplay2 = React.memo(Display2);

function App() {
  ...
  return (
    <React.Fragment>
      ...
      <JediContext1.Provider value={value1}>
        <MemoDisplay />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <MemoDisplay2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}
</code>```

Notice the logs, there is no unnecessary renders afterward.

Title: Unnecessary rerenders with useContext

Body:
In this example

function App() {
  const [value1, dispatch1] = useReducer(reducer, initialState1);
  const [value2, dispatch2] = useReducer(reducer, initialState2);

  return (
    <React.Fragment>
      <button
        onClick={() => {
          dispatch1({ type: "setFirstName", firstName: "nick" });
        }}
      >
        change1
      </button>
      <button
        onClick={() => {
          dispatch2({ type: "setFamilyName", familyName: "fname" });
        }}
      >
        change2
      </button>
      <JediContext1.Provider value={value1}>
        <Display1 />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <Display2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}

I used two context per recommendation from here. But I might have misunderstood and maybe github issue is referring to another case? Because it doesn't seem to solve my problem.

The problem with above code is if I click change1 button, which changes value1, component Display2 is also rerendered which doesn't even consume value1.

Actually this makes sense to me because I changed state in App, hence it would rerender all its children. But then I don't understand the use of recommendation from the github link, because it didn't solve my problem here?

This maybe problematic performance wise if you have large app and root context provider say.

Body:
Try memoizing both components so they only render when their local state changes:

const MemoDisplay = React.memo(Display1);
const MemoDisplay2 = React.memo(Display2);

function App() {
  ...
  return (
    <React.Fragment>
      ...
      <JediContext1.Provider value={value1}>
        <MemoDisplay />
      </JediContext1.Provider>
      <JediContext2.Provider value={value2}>
        <MemoDisplay2 />
      </JediContext2.Provider>
    </React.Fragment>
  );
}

Notice the logs, there is no unnecessary renders afterward.


问:
How to hide blanks in a matrix visualization with hierarchical rows
I've built a table of data following this helpful guide:
https://www.daxpatterns.com/parent-child-hierarchies/

I'm following it exactly but I'll still explain things here so you don't have to go through the whole article if you don't want to. I have a table of Names with corresponding keys, and ParentKeys forming hierarchies.
I added a column for the path, columns for each level of the path, depth of hierarchy and an IsLeaf column:

If I want to make a matrix and include City (from another table), all hierarchies will expand to the maximum length, and blanks are filled in with the "parent's" name:

The DAX Patterns website explains how to get around this. First add these two measures:

```<code>BrowseDepth = ISFILTERED (Nodes[Level1]) + ISFILTERED (Nodes[Level2]) + ISFILTERED (Nodes[Level3])
</code>```

```<code>MaxNodeDepth = MAX (Nodes[HierarchyDepth])
</code>```

And then you can factor that into calculations with this measure:

```<code>Sales Amount Simple =
IF (
    Nodes[BrowseDepth] > Nodes[MaxNodeDepth],
    BLANK (),
    SUM (Transactions[Amount])
)
</code>```

If this is the only value on a matrix visual, it turns out fine:

But if I add any other values, I get expanded hierarchies and blanks again:

My problem would be solved if I could filter out blank values, but that filters out the entire hierarchy. Do I have to make a measure using the Sales Amount format above for every value I want to include? I'm trying to add things like addresses that can't be aggregated.

答: Basiacally yes, you have to re do the measure. However you can embed existing into this patern which makes it a little easier.</p>

Body:
I've built a table of data following this helpful guide:
https://www.daxpatterns.com/parent-child-hierarchies/

I'm following it exactly but I'll still explain things here so you don't have to go through the whole article if you don't want to. I have a table of Names with corresponding keys, and ParentKeys forming hierarchies.
I added a column for the path, columns for each level of the path, depth of hierarchy and an IsLeaf column:

If I want to make a matrix and include City (from another table), all hierarchies will expand to the maximum length, and blanks are filled in with the "parent's" name:

The DAX Patterns website explains how to get around this. First add these two measures:

BrowseDepth = ISFILTERED (Nodes[Level1]) + ISFILTERED (Nodes[Level2]) + ISFILTERED (Nodes[Level3])

MaxNodeDepth = MAX (Nodes[HierarchyDepth])

And then you can factor that into calculations with this measure:

Sales Amount Simple =
IF (
    Nodes[BrowseDepth] > Nodes[MaxNodeDepth],
    BLANK (),
    SUM (Transactions[Amount])
)

If this is the only value on a matrix visual, it turns out fine:

But if I add any other values, I get expanded hierarchies and blanks again:

My problem would be solved if I could filter out blank values, but that filters out the entire hierarchy. Do I have to make a measure using the Sales Amount format above for every value I want to include? I'm trying to add things like addresses that can't be aggregated.


答:
the best way is to use a method for that purpose and reuse it:</p>

```<code>public static void main(String[] args) {
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    sum3 = addDigit(addDigit(l1)+addDigit(l2))

}

private static int addDigit(int number){
    int sum = 0;
    while (number > 0) {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}
</code>```

Title: Using results from the loops for another one

Body:
the best way is to use a method for that purpose and reuse it:

public static void main(String[] args) {
    int sum3 = 0;
    Scanner scn = new Scanner(System.in);
    System.out.println("1 : ");
    int l1 = scn.nextInt();
    System.out.println("2 : ");
    int l2 = scn.nextInt();
    System.out.println((0 > l1 || 0 > l2 ? "ERROR-NEGATIVE NUMBER" : "OK"));
    sum3 = addDigit(addDigit(l1)+addDigit(l2))

}

private static int addDigit(int number){
    int sum = 0;
    while (number > 0) {
        sum += number % 10;
        number /= 10;
    }
    return sum;
}


问:
Building GCC: Is there a way to only build cpp?
I am attempting to build GCC however what I really want is only c pre-processor.

Is there a way to build c pre processor on its own?

答:
It seems that CPP is not a separate program all it does is execv cc1 as captured with the following strace command

```<code>execve("/usr/lib/gcc/x86_64-linux-gnu/9/cc1", ["/usr/lib/gcc/x86_64-linux-gnu/9/"..., "-E", "-quiet", "-imultiarch", "x86_64-linux-gnu", "-", "-mtune=generic", "-march=x86-64", "-fasynchronous-unwind-tables", "-fstack-protector-strong", "-Wformat", "-Wformat-security", "-fstack-clash-protection", "-fcf-protection"]

# Which results into the following command line
/usr/lib/gcc/x86_64-linux-gnu/9/cc1 -E -quiet -imultiarch x86_64-linux-gnu --mtune=generic -march=x86-64 -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection
</code>```

This is confirmed using from the following link:

https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture

Program cc1 includes both the preprocessor and C compiler. It compiles
  a C source file and generates an assembly (.S) file.

Body:
It seems that CPP is not a separate program all it does is execv cc1 as captured with the following strace command

execve("/usr/lib/gcc/x86_64-linux-gnu/9/cc1", ["/usr/lib/gcc/x86_64-linux-gnu/9/"..., "-E", "-quiet", "-imultiarch", "x86_64-linux-gnu", "-", "-mtune=generic", "-march=x86-64", "-fasynchronous-unwind-tables", "-fstack-protector-strong", "-Wformat", "-Wformat-security", "-fstack-clash-protection", "-fcf-protection"]

# Which results into the following command line
/usr/lib/gcc/x86_64-linux-gnu/9/cc1 -E -quiet -imultiarch x86_64-linux-gnu --mtune=generic -march=x86-64 -fasynchronous-unwind-tables -fstack-protector-strong -Wformat -Wformat-security -fstack-clash-protection -fcf-protection

This is confirmed using from the following link:

https://en.wikibooks.org/wiki/GNU_C_Compiler_Internals/GNU_C_Compiler_Architecture

Program cc1 includes both the preprocessor and C compiler. It compiles
  a C source file and generates an assembly (.S) file.


问:
How do you balance fun feature creep with time constraints?
I enjoy programming, usually.  Tedious stuff is easy to get done as quickly and correctly as possible so I can get through it and not have to see it again.

But a lot of my coding is fun and when I get in the 'zone' I just really enjoy myself.

Which is where I make the mistake of spending too much time, perhaps adding features, perhaps writing it in a cool or elegant manner, or just doing neat prototypes.

How do you recognize this is happening before it exceeds your time frame?

What do you do before starting a potentially fun piece of code, or during, to get back on track?

When is it ok to let yourself go "hog wild" and just enjoy it without worrying about consequences?

-Adam

答:
Always have a working release (snapshot) ready. Treat it like the way SQL server implement snapshot isolation. :)

Continue adding new cool stuffs to a separate copy of the project. Once it is stable, overwrite your release folder and that is your new snapshot. Whenever somebody ask for a demo or release, that way you can always switch to the stable application and will have something to show anytime.

OwnerDisplayName: Adam Davis

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dF

OwnerDisplayName: Gulzar

LastEditorDisplayName: Gulzar


问:
Using the g++ C++ compiler from cygwin
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

```<code>#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}
</code>```

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
</code>```

And here is what I get when I try to compile the program in the cygwin shell:

```<code>hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
</code>```

答:
As others have mentioned, it's probably a path issue, so you need to look at the environment variable PATH.  To do this, right click on My Computer and click "Properties".  Go to the "Advanced" tab and click the "Evironment Variables" button.  From here, see if the paths you mentioned are included in the PATH variable.  If not, add them using the same syntax you see there to separate paths (I think it's a semi-colon or a colon between paths.)

Edit: Ah, I see you've already done this (beat my post by mere seconds.)  I think all you need to do now is reboot.

Title: Using the g++ C++ compiler from cygwin

Body:
I am trying to execute my first "Hello World!" in C++. I am using Windows XP, and I have installed cygwin, in which the g++ C++ compiler is installed. I have written a small hello-world program, and saved it in hello.cpp. From the command prompt I write:

g++ hello.cpp

But I get:

'g++' is not recognized as an internal or external command, operable program or batch file.

I have installed cygwin in my D:\programs\cygwin. I have made another directory with my hello-world file in D:\cpp. Something with my installation or my paths seems to be not Ok, but I cannot figure what. I have run the exe file of cygwin, and in the installation directory I have got all necessary files, I think: bin folder, lib, Cygwin.bat, etc.

I have read that in case of such error message I should check whether the cygwin1.dll file is copied into the main folder of Windows. Is this the C:\WINDOWS directory? I have looked there, and I don't have such a file there. I have cygwin1.dll in the bin folder of cygwin: D:\programs\cygwin\bin.
Also, how do I check whether the bin folder (D:\programs\cygwin\bin) is considered in the search path of commands?

I think that the hello-world program shouldn't contain any syntax errors, I have just copied it. Also, when I write

g++ -v

I get the same error message: that the command is not recognized.
I would appreciate if someone give me a hint what should I look at. Thank you.

Here is the code of the hello-world program:

#include <iostream>
using namespace std;

int main() {
  cout <<"Hello World!"<<endl;
  return 0;
}

I have installed g++, and now when I type g++ -v, I get: Reading specs from: \d\cygnus\cygwin-b20\H-i586-cygwin32\bin..\lib\gcc-lib\i586-cygwin32\egcs-2.91.57\specs gcc version egcs-2.91.57 19980901 (egcs-1.1 release)

In the bin directory I have both g++.exe, and gcc.exe. I don't understand why I get "gcc" above and not "g++". I don't know how important this is, but I receive an error message when I try to compile the program in the DOS command prompt:

g++ hello.cpp

I get:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)

And here is what I get when I try to compile the program in the cygwin shell:

hello.cpp:1: parse error before character 0357
hello.cpp: In function 'int main()':
hello.cpp:'cout' undeclared (first use this function)
hello.cpp: (Each undeclared identifier is reported only once
hello.cpp: for each function it appears in.)
hello.cpp: 'endl' undeclared (first use this function)
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files
g++.exe: hello.cpp: No such file or directory
g++.exe: No input files

LastEditorDisplayName: Rich B

OwnerDisplayName: Scottie T


问:
Regular expression troubles, escaped quotes
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

```<code>"Hello\" World" "Hello Universe" Hi
</code>```

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

```<code>public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}
</code>```

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind

答:
To recap, you want to split on whitespace, except when surrounded by double quotes, which are not preceded by a backslash.

Step 1: tokenize the input: /([ \t]+)|(\\")|(")|([^ \t"]+)/

This gives you a sequence of SPACE, ESCAPED_QUOTE, QUOTE and TEXT tokens.

Step 2: build a finite state machine matching and reacting to the tokens:

State: START

SPACE -> return empty string

ESCAPED_QUOTE -> Error (?)

QUOTE -> State := WITHIN_QUOTES

TEXT -> return text

State: WITHIN_QUOTES

SPACE -> add value to accumulator

ESCAPED_QUOTE -> add quote to accumulator

QUOTE -> return and clear accumulator; State := START

TEXT -> add text to accumulator

Step 3: Profit!!

ContentLicense: CC BY-SA 3.0

Body:
Basically, I'm being passed a string and I need to tokenise it in much the same manner as command line options are tokenised by a *nix shell

Say I have the following string

"Hello\" World" "Hello Universe" Hi

How could I turn it into a 3 element list

Hello" World

Hello Universe

Hi

The following is my first attempt, but it's got a number of problems

It leaves the quote characters

It doesn't catch the escaped quote

Code:

public void test() {
    String str = "\"Hello\\\" World\" \"Hello Universe\" Hi";
    List<String> list = split(str);
}

public static List<String> split(String str) {
    Pattern pattern = Pattern.compile(
        "\"[^\"]*\"" + /* double quoted token*/
        "|'[^']*'" + /*single quoted token*/
        "|[A-Za-z']+" /*everything else*/
    );

    List<String> opts = new ArrayList<String>();
    Scanner scanner = new Scanner(str).useDelimiter(pattern);

    String token;
    while ((token = scanner.findInLine(pattern)) != null) {
        opts.add(token);
    }
    return opts;
}

So the incorrect output of the following code is

"Hello\"

World

" "

Hello

Universe

Hi

EDIT I'm totally open to a non regex solution.  It's just the first solution that came to mind


问:
Ruby undefined method '**'
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

```<code>def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)
</code>```

I keep getting this error:

```<code>Traceback (most recent call last):
        3: from task2.rb:21:in `<main>'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)
</code>```

答:
#each is just a simple iteration, it's doesn't modify the array.
Instead of:

```<code>a = Array.new(50)
a.each { |x| x = rand(10..100) }
</code>```

you can simply do this:

```<code>a = Array.new(50) { rand(10..100) }
</code>```

Title: Ruby undefined method '**'

Body:
I'm attempting to write a function that uses array methods to do a variety of things. I need to use the each method to print the cube of each element in the array. Here's my code.

def foo(a)

    a.each { |x| puts x ** 3 }

    a.each_slice(3) { |x| puts x }
    a.select do |x|

        if x%5 == 0
            puts x
        end
    end

    a.map { |x| x ** 3 }
    aa.inject(0) { |x, y| x * y }

end

a = Array.new(50)
a.each { |x| x = rand(10..100) }

foo(a)

I keep getting this error:

Traceback (most recent call last):
        3: from task2.rb:21:in `'
        2: from task2.rb:3:in `foo'
        1: from task2.rb:3:in `each'
task2.rb:3:in `block in foo': undefined method `**' for nil:NilClass (NoMethodError)

Body:
#each is just a simple iteration, it's doesn't modify the array.
Instead of:

a = Array.new(50)
a.each { |x| x = rand(10..100) }

you can simply do this:

a = Array.new(50) { rand(10..100) }


问:
Why I can't assign values to a emtpy array with a For cicle?
I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

```<code>var i = 0 , j = 0;
var arr = [[],[]];

for( i = 0; i < 8; i++){

  for( j = 0; j < 8; j++){

     arr[i][j] = 7;
     alert(arr[i][j]);

  }

   alert(arr[i][j]);

}
</code>```

答:
This should do what you are looking for.</p>

```<code>var ar = new Array(10)
for(i = 0; i < 10; i++) {
    ar[i] = new Array(10)
}
for(i = 0; i < 10; i++){
    for(j = 0; j< 10; j++) {
        ar[i][j] = 1
    }
}
console.log(ar)
</code>```

Body:
I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

var i = 0 , j = 0;
var arr = [[],[]];

for( i = 0; i < 8; i++){

  for( j = 0; j < 8; j++){

     arr[i][j] = 7;
     alert(arr[i][j]);

  }

   alert(arr[i][j]);

}

Body:
This should do what you are looking for.

var ar = new Array(10)
for(i = 0; i < 10; i++) {
    ar[i] = new Array(10)
}
for(i = 0; i < 10; i++){
    for(j = 0; j< 10; j++) {
        ar[i][j] = 1
    }
}
console.log(ar)


问:
Why does 'if statement' ignores conditions or reads them as if they are not true when they actually are?
I stumbled upon something that is causing me real hard time and I can't figure it out so, please take a look at my situation and help me out...

I am writing a code that is supposed to prevent some of the website users from accessing a specific part of the website called orders.php

Each user has a previously assigned role and I am trying to achieve this restriction by allowing only a few of the roles to access it so if you don't have some of the specific roles that are allowed to visit the website assigned to you, you get redirected to the homepage.

These is one of the ways that I've tried

```<code>    if( $userrole !== 'Administrator' OR
        $userrole !== 'Manager' OR
        $userrole !== 'Product Hunter' OR
        $userrole !== 'Product Selector' OR
        $userrole !== 'Analytic' OR
        $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    else{
     //code here
    }
</code>```

I tried using || instead of OR but it is not working either

I also tried using elseif statement for each role like this:

```<code>if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Hunter'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Selector'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Analytic'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
   else{
    //code goes here
   }
</code>```

As far as I understand, the code shall continue to execute the else statement the moment it reads your role name, for an example if you are an Administrator, then it shall execute the else statement because it is said that if you are not some of the specified roles then you will be redirected and since you are one of the specified roles then the code shall execute for you but for some odd reason it is redirecting you to the homepage no matter if you are an Administrator, Manager or a Visitor...

The only way the code allows you to visit the website instead of redirecting you to the homepage is when you have only one role specified, for an example:

```<code>    if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }else{
     //code goes here
    }
</code>```

This way, if you are an Administrator, then you are allowed to visit the page, and if you have any different role then you get redirected.

The reason I use !== is because I want the code to define if this user can visit this part of the website at the beginning instead of telling it to show the code to the users with these few specific roles and redirect everyone else.

$userrole is previously set to equal a $_SESSION variable which contains the value of the actual role of the user and is defined at login, if I echo it, it prints the name of the role so that is not causing the problem for sure.

I've found some posts suggesting using switch statements but I haven't tried them yet since I prefer doing it this way if possible.

Thanks in advance!

答:
You need to use and operator. You redirect to dashboard if user has neither of these roles

```<code>if( $userrole !== 'Administrator' &&
    $userrole !== 'Manager' &&
    $userrole !== 'Product Hunter' &&
    $userrole !== 'Product Selector' &&
    $userrole !== 'Analytic' &&
    $userrole !== 'Order Manager'
){
    header('Location: ../dashboard.php');
    die;
}
else{
    //code here
}
</code>```

Body:
I stumbled upon something that is causing me real hard time and I can't figure it out so, please take a look at my situation and help me out...

I am writing a code that is supposed to prevent some of the website users from accessing a specific part of the website called orders.php

Each user has a previously assigned role and I am trying to achieve this restriction by allowing only a few of the roles to access it so if you don't have some of the specific roles that are allowed to visit the website assigned to you, you get redirected to the homepage.

These is one of the ways that I've tried

    if( $userrole !== 'Administrator' OR
        $userrole !== 'Manager' OR
        $userrole !== 'Product Hunter' OR
        $userrole !== 'Product Selector' OR
        $userrole !== 'Analytic' OR
        $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    else{
     //code here
    }

I tried using || instead of OR but it is not working either

I also tried using elseif statement for each role like this:

if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Manager'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Hunter'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Product Selector'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Analytic'){
        header('Location: ../dashboard.php');
        die;
    }
    elseif( $userrole !== 'Order Manager'){
        header('Location: ../dashboard.php');
        die;
    }
   else{
    //code goes here
   }

As far as I understand, the code shall continue to execute the else statement the moment it reads your role name, for an example if you are an Administrator, then it shall execute the else statement because it is said that if you are not some of the specified roles then you will be redirected and since you are one of the specified roles then the code shall execute for you but for some odd reason it is redirecting you to the homepage no matter if you are an Administrator, Manager or a Visitor...

The only way the code allows you to visit the website instead of redirecting you to the homepage is when you have only one role specified, for an example:

    if( $userrole !== 'Administrator'){
        header('Location: ../dashboard.php');
        die;
    }else{
     //code goes here
    }

This way, if you are an Administrator, then you are allowed to visit the page, and if you have any different role then you get redirected.

The reason I use !== is because I want the code to define if this user can visit this part of the website at the beginning instead of telling it to show the code to the users with these few specific roles and redirect everyone else.

$userrole is previously set to equal a $_SESSION variable which contains the value of the actual role of the user and is defined at login, if I echo it, it prints the name of the role so that is not causing the problem for sure.

I've found some posts suggesting using switch statements but I haven't tried them yet since I prefer doing it this way if possible.

Thanks in advance!

Body:
You need to use and operator. You redirect to dashboard if user has neither of these roles

if( $userrole !== 'Administrator' &&
    $userrole !== 'Manager' &&
    $userrole !== 'Product Hunter' &&
    $userrole !== 'Product Selector' &&
    $userrole !== 'Analytic' &&
    $userrole !== 'Order Manager'
){
    header('Location: ../dashboard.php');
    die;
}
else{
    //code here
}


问:
System blocked when delayed work is schedulated
i'm working on an accademic project and i have to understand the usage of linux's workqueue.
For this reason i've developed a small module that simply schedule the execution of a work on a custom workqueue after 1000 jiffies.
However, when the timeout expires, the system is blocked, i need to restart the VM and i can't collect any info for debug.

These are the portions of the code i'm using:

```<code>static void enqueue_message(struct work_struct *work){

    printk("%s: Step 2\n", MODULE_NAME);
    return;
}

int init_module(void){

    struct workqueue_struct *workqueue;
    struct delayed_work deferred_write;
    workqueue = alloc_workqueue("pending_writes",WQ_MEM_RECLAIM, 0);
    INIT_DELAYED_WORK(&deferred_write, enqueue_message);
    queue_delayed_work(workqueue, &deferred_write, 1000);
    printk("%s: Step 1\n", MODULE_NAME);
    return 0;
}
</code>```

If i quickly (before timer expiration) ask for 'dmesg' on shell, i can read 'the Step 1' print but then i can't use the system.
I know probably there is a beginner bug in the code but i can't individuate it.
Thanks everybody for the help.

答:
Like many other functions in the Linux kernel, queue_delayed_work expects its argument to exist until the work will be triggered.

However, you pass the function a local variable (deferred_write) - which has been destroyed when init_module function returns.

Use global variable instead.

Body:
i'm working on an accademic project and i have to understand the usage of linux's workqueue.
For this reason i've developed a small module that simply schedule the execution of a work on a custom workqueue after 1000 jiffies.
However, when the timeout expires, the system is blocked, i need to restart the VM and i can't collect any info for debug.

These are the portions of the code i'm using:

static void enqueue_message(struct work_struct *work){

    printk("%s: Step 2\n", MODULE_NAME);
    return;
}

int init_module(void){

    struct workqueue_struct *workqueue;
    struct delayed_work deferred_write;
    workqueue = alloc_workqueue("pending_writes",WQ_MEM_RECLAIM, 0);
    INIT_DELAYED_WORK(&deferred_write, enqueue_message);
    queue_delayed_work(workqueue, &deferred_write, 1000);
    printk("%s: Step 1\n", MODULE_NAME);
    return 0;
}

If i quickly (before timer expiration) ask for 'dmesg' on shell, i can read 'the Step 1' print but then i can't use the system.
I know probably there is a beginner bug in the code but i can't individuate it.
Thanks everybody for the help.


问:
Firebase App Distribution get registered tester's UDID
Is there any way to get registered tester's UDID. We deleted wrongly mail which comes from Firebase accidentally. Before Firebase App Distribution, we can find it in Fabric Beta. But now we can not access directly to UDID.</p>

答: Chintan from Firebase. We don't expose that currently in the dashboard. The tester could find their UDID in the App Distribution webclip's settings and email that back to you (we show it on the "Manage account" page). Or you can delete the tester and re-add them to your app. Then the tester would have to accept the invite again, consent their device, then register their profile and you'd receive the email again.</p>


问:
How can I return a JavaScript string from a WebAssembly function
How can I return a JavaScript string from a WebAssembly function?

Can the following module be written in C(++) ?

```<code>export function foo() {
  return 'Hello World!';
}
</code>```

Also: Can I pass this to the JS engine to be garbage collected?

答:
Given:

mem, the WebAssembly.Memory object (from the module exports)

p, the address of the first character of the string

len, the length of the string (in bytes),

you can read the string using:

```<code>let str = (new TextDecoder()).decode(new Uint8Array(mem.buffer, p, len));
</code>```

This assumes the string is UTF-8 encoded.

Body:
How can I return a JavaScript string from a WebAssembly function?

Can the following module be written in C(++) ?

export function foo() {
  return 'Hello World!';
}

Also: Can I pass this to the JS engine to be garbage collected?

Body:
Given:

mem, the WebAssembly.Memory object (from the module exports)

p, the address of the first character of the string

len, the length of the string (in bytes),

you can read the string using:

let str = (new TextDecoder()).decode(new Uint8Array(mem.buffer, p, len));

This assumes the string is UTF-8 encoded.


问:
ReactJS - use iframe to silently renew token
My SPA has this working component that fetches an access token that will be encrypted and passed to other components via props. This is it:

```<code>import React, { Component } from 'react';
//import { Redirect } from 'react-router-dom';
import axios from 'axios';
import Credentials from './spotify-auth.js'
import './Spotify.css'

class SpotifyAuth extends Component {
  constructor (props) {
    super(props);
    this.state = {
      isAuthenticatedWithSpotify: false,
    };
    this.state.handleRedirect = this.handleRedirect.bind(this);
  };

  generateRandomString(length) {
    let text = '';
    const possible =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
    }

  getHashParams() {
    const hashParams = {};
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    let e = r.exec(q);
    while (e) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
      e = r.exec(q);
    }
    return hashParams;
  }

  componentDidMount() {
    //if (this.props.isAuthenticated) {
    const params = this.getHashParams();

    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem(Credentials.stateKey);
    localStorage.setItem('spotifyAuthToken', access_token);
    localStorage.getItem('spotifyAuthToken');

    if (window.localStorage.getItem('authToken')) {
      this.setState({ isAuthenticatedWithSpotify: true });
    };
    if (access_token && (state == null || state !== storedState)) {
      alert('Click "ok" to finish authentication with Spotify');
    } else {
      localStorage.removeItem(Credentials.stateKey);
    }
    // DO STUFF WITH ACCEES TOKEN HERE
    this.props.onConnectWithSpotify(access_token);
  };

  handleRedirect(event) {
    event.preventDefault()
    this.props.createMessage('You linked your Spotify account!', 'success');
    // get client features at authenticating
    const params = this.getHashParams();
    const access_token = params.access_token;
    console.log(access_token);

    const state = this.generateRandomString(16);
    localStorage.setItem(Credentials.stateKey, state);

    let url = 'https://accounts.spotify.com/authorize';
    url += '?response_type=token';
    url += '&client_id=' + encodeURIComponent(Credentials.client_id);
    url += '&scope=' + encodeURIComponent(Credentials.scope);
    url += '&redirect_uri=' + encodeURIComponent(Credentials.redirect_uri);
    url += '&state=' + encodeURIComponent(state);
    window.location = url;
  };

  render() {
      return (
        <div className="button_container">
        <h1 className="title is-3"><font color="#C86428">{"Welcome"}</font></h1>
            <div className="Line" /><br/>
              <button className="sp_button" onClick={(event) => this.handleRedirect(event)}>
                <strong>LINK YOUR SPOTIFY ACCOUNT</strong>
              </button>
        </div>
      )
  }
}
export default SpotifyAuth;
</code>```

This token credentials last for 60 minutes.

I've learned that the standard option for SPAs is to use iframes to silently renew tokens and not use refresh tokens at all.

How do one spin up an iframe and silently get a new access token every hour in a React component like the one above? I have looked everywhere for this and haven't found anything.

答:
You can do the following:

Create some watcher function, which checks the expiration time of the access token. If the token is about to expire, it is time to renew it.

Render an iframe tag, the src should be the same URL which you are using for redirecting to the Auth server, with one difference: change the return URL to a static file, let's call it redirect.html. The server should know about the user calling this URL, from the stored cookie, so it should just simply redirect you to the redirect.html file, now with a fresh access token.

In this redirect.html write a short script, which takes out the token from the URL and override it with the one you already have in local storage.

Destroy the iframe.

This is about it, the token is renewd. Keep the watcher going and renew it everytime its about to expire (do it like 5 minutes before it expire).

An example implementation for the AccessToken component in React, most parts of the code will actually work, but you need to replace the constants with your stuff. Also, some functions like extractTokenFromUrl are missing, but that should be easy enough to make:

```<code>import React, { Component } from 'react'

export class SilentTokenRenew extends Component {
  constructor(props) {
    super(props)

    this.state = { renewing: false }
    this.currentAttempt = 0
    this.maxNumberOfAttempts = 20
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.state.renewing !== nextState.renewing
  }

  componentDidMount() {
    this.timeInterval = setInterval(this.handleCheckToken, 20000)
  }

  componentWillUnmount() {
    clearInterval(this.timeInterval)
  }

  willTokenExpire = () => {
    const token = YOUR_ACCESS_TOKEN_OBJECT // { accessToken, expirationTime }
    const threshold = 300 // 300s = 5 minute threshold for token expiration

    const hasToken = token && token.accessToken
    const now = (Date.now() / 1000) + threshold

    return !hasToken || (now > token.accessToken.expirationTime)
  }

  handleCheckToken = () => {
    if (this.willTokenExpire()) {
      this.setState({ renewing: true })
      clearInterval(this.timeInterval)
    }
  }

  silentRenew = () => {
    return new Promise((resolve, reject) => {
      const checkRedirect = () => {
        // This can be e
        const redirectUrl = localStorage[YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE] // /redirect.html#access_token=......
        if (!redirectUrl) {
          this.currentAttempt += 1
          if (this.currentAttempt > this.maxNumberOfAttempts) {
            reject({
              message: 'Silent renew failed after maximum number of attempts.',
              short: 'max_number_of_attempts_reached',
            })
            return
          }
          setTimeout(() => checkRedirect(), 500)
          return
        }

        // Clean up your localStorage for the next silent renewal
        localStorage.removeItem(YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE)

        // Put some more error handlers here

        // Silent renew worked as expected, lets update the access token
        const session = extractTokenFromUrl(redirectUrl) // write some function to get out the access token from the URL
        // Following your code you provided, here is the time to set
        // the extracted access token back to your localStorage under a key Credentials.stateKey
        localStorage.setItem(Credentials.stateKey, JSON.stringify(session))
        resolve(session)
      }

      checkRedirect()
    })
  }

  handleOnLoad = () => {
    this.silentRenew()
      .then(() => {
        this.setState({ renewing: false })
        this.currentAttempt = 0
        this.timeInterval = setInterval(this.handleCheckToken, 60000)
        // Access token renewed silently.
      })
      .catch(error => {
        this.setState({ renewing: false })
        // handle the errors
      })
  }

  renderIframe = () => {
    const url = new URL(YOUR_AUTHORIZE_URL_TO_TH_AUTH_SERVER)
    url.searchParams.set('redirect_uri', 'http://localhost:3000/redirect.html') // the redirect.html file location
    url.searchParams.set('prompt', 'none')

    return (
      <iframe
        style={{ width: 0, height: 0, position: 'absolute', left: 0, top: 0, display: 'none', visibility: 'hidden' }}
        width={0}
        height={0}
        title="silent-token-renew"
        src={url.href}
        onLoad={this.handleOnLoad}
      />
    )
  }

  render() {
    const { renewing } = this.state

    return renewing ? this.renderIframe() : null
  }
}
</code>```

Sample code fore the redirect.html file:

```<code><!DOCTYPE html>
<html>

<head>
    <title>OAuth - Redirect</title>
</head>

<body>
<p>Renewing...</p>
<script>
  // Get name of window which was set by the parent to be the unique request key
  // or if no parameter was specified, we have a silent renew from iframe
  const requestKey = YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE;
  // Update corresponding entry with the redirected url which should contain either access token or failure reason in the query parameter / hash
  window.localStorage.setItem(requestKey, window.location.href);
  window.close();
</script>
</body>

</html>
</code>```

Body:
My SPA has this working component that fetches an access token that will be encrypted and passed to other components via props. This is it:

import React, { Component } from 'react';
//import { Redirect } from 'react-router-dom';
import axios from 'axios';
import Credentials from './spotify-auth.js'
import './Spotify.css'

class SpotifyAuth extends Component {
  constructor (props) {
    super(props);
    this.state = {
      isAuthenticatedWithSpotify: false,
    };
    this.state.handleRedirect = this.handleRedirect.bind(this);
  };

  generateRandomString(length) {
    let text = '';
    const possible =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < length; i++) {
      text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
    }

  getHashParams() {
    const hashParams = {};
    const r = /([^&;=]+)=?([^&;]*)/g;
    const q = window.location.hash.substring(1);
    let e = r.exec(q);
    while (e) {
      hashParams[e[1]] = decodeURIComponent(e[2]);
      e = r.exec(q);
    }
    return hashParams;
  }

  componentDidMount() {
    //if (this.props.isAuthenticated) {
    const params = this.getHashParams();

    const access_token = params.access_token;
    const state = params.state;
    const storedState = localStorage.getItem(Credentials.stateKey);
    localStorage.setItem('spotifyAuthToken', access_token);
    localStorage.getItem('spotifyAuthToken');

    if (window.localStorage.getItem('authToken')) {
      this.setState({ isAuthenticatedWithSpotify: true });
    };
    if (access_token && (state == null || state !== storedState)) {
      alert('Click "ok" to finish authentication with Spotify');
    } else {
      localStorage.removeItem(Credentials.stateKey);
    }
    // DO STUFF WITH ACCEES TOKEN HERE
    this.props.onConnectWithSpotify(access_token);
  };

  handleRedirect(event) {
    event.preventDefault()
    this.props.createMessage('You linked your Spotify account!', 'success');
    // get client features at authenticating
    const params = this.getHashParams();
    const access_token = params.access_token;
    console.log(access_token);

    const state = this.generateRandomString(16);
    localStorage.setItem(Credentials.stateKey, state);

    let url = 'https://accounts.spotify.com/authorize';
    url += '?response_type=token';
    url += '&client_id=' + encodeURIComponent(Credentials.client_id);
    url += '&scope=' + encodeURIComponent(Credentials.scope);
    url += '&redirect_uri=' + encodeURIComponent(Credentials.redirect_uri);
    url += '&state=' + encodeURIComponent(state);
    window.location = url;
  };

  render() {
      return (

{"Welcome"}

              <button className="sp_button" onClick={(event) => this.handleRedirect(event)}>
                LINK YOUR SPOTIFY ACCOUNT
              </button>

      )
  }
}
export default SpotifyAuth;

This token credentials last for 60 minutes.

I've learned that the standard option for SPAs is to use iframes to silently renew tokens and not use refresh tokens at all.

How do one spin up an iframe and silently get a new access token every hour in a React component like the one above? I have looked everywhere for this and haven't found anything.

Body:
You can do the following:

Create some watcher function, which checks the expiration time of the access token. If the token is about to expire, it is time to renew it.

Render an iframe tag, the src should be the same URL which you are using for redirecting to the Auth server, with one difference: change the return URL to a static file, let's call it redirect.html. The server should know about the user calling this URL, from the stored cookie, so it should just simply redirect you to the redirect.html file, now with a fresh access token.

In this redirect.html write a short script, which takes out the token from the URL and override it with the one you already have in local storage.

Destroy the iframe.

This is about it, the token is renewd. Keep the watcher going and renew it everytime its about to expire (do it like 5 minutes before it expire).

An example implementation for the AccessToken component in React, most parts of the code will actually work, but you need to replace the constants with your stuff. Also, some functions like extractTokenFromUrl are missing, but that should be easy enough to make:

import React, { Component } from 'react'

export class SilentTokenRenew extends Component {
  constructor(props) {
    super(props)

    this.state = { renewing: false }
    this.currentAttempt = 0
    this.maxNumberOfAttempts = 20
  }

  shouldComponentUpdate(nextProps, nextState) {
    return this.state.renewing !== nextState.renewing
  }

  componentDidMount() {
    this.timeInterval = setInterval(this.handleCheckToken, 20000)
  }

  componentWillUnmount() {
    clearInterval(this.timeInterval)
  }

  willTokenExpire = () => {
    const token = YOUR_ACCESS_TOKEN_OBJECT // { accessToken, expirationTime }
    const threshold = 300 // 300s = 5 minute threshold for token expiration

    const hasToken = token && token.accessToken
    const now = (Date.now() / 1000) + threshold

    return !hasToken || (now > token.accessToken.expirationTime)
  }

  handleCheckToken = () => {
    if (this.willTokenExpire()) {
      this.setState({ renewing: true })
      clearInterval(this.timeInterval)
    }
  }

  silentRenew = () => {
    return new Promise((resolve, reject) => {
      const checkRedirect = () => {
        // This can be e
        const redirectUrl = localStorage[YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE] // /redirect.html#access_token=......
        if (!redirectUrl) {
          this.currentAttempt += 1
          if (this.currentAttempt > this.maxNumberOfAttempts) {
            reject({
              message: 'Silent renew failed after maximum number of attempts.',
              short: 'max_number_of_attempts_reached',
            })
            return
          }
          setTimeout(() => checkRedirect(), 500)
          return
        }

        // Clean up your localStorage for the next silent renewal
        localStorage.removeItem(YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE)

        // Put some more error handlers here

        // Silent renew worked as expected, lets update the access token
        const session = extractTokenFromUrl(redirectUrl) // write some function to get out the access token from the URL
        // Following your code you provided, here is the time to set
        // the extracted access token back to your localStorage under a key Credentials.stateKey
        localStorage.setItem(Credentials.stateKey, JSON.stringify(session))
        resolve(session)
      }

      checkRedirect()
    })
  }

  handleOnLoad = () => {
    this.silentRenew()
      .then(() => {
        this.setState({ renewing: false })
        this.currentAttempt = 0
        this.timeInterval = setInterval(this.handleCheckToken, 60000)
        // Access token renewed silently.
      })
      .catch(error => {
        this.setState({ renewing: false })
        // handle the errors
      })
  }

  renderIframe = () => {
    const url = new URL(YOUR_AUTHORIZE_URL_TO_TH_AUTH_SERVER)
    url.searchParams.set('redirect_uri', 'http://localhost:3000/redirect.html') // the redirect.html file location
    url.searchParams.set('prompt', 'none')

    return (
      <iframe
        style={{ width: 0, height: 0, position: 'absolute', left: 0, top: 0, display: 'none', visibility: 'hidden' }}
        width={0}
        height={0}
        title="silent-token-renew"
        src={url.href}
        onLoad={this.handleOnLoad}
      />
    )
  }

  render() {
    const { renewing } = this.state

    return renewing ? this.renderIframe() : null
  }
}

Sample code fore the redirect.html file:

<!DOCTYPE html>
<html>

<head>
    <title>OAuth - Redirect</title>
</head>

<body>
<p>Renewing...</p>
<script>
  // Get name of window which was set by the parent to be the unique request key
  // or if no parameter was specified, we have a silent renew from iframe
  const requestKey = YOUR_REDIRECT_URL_FROM_THE_REDIRECT_HTML_FILE;
  // Update corresponding entry with the redirected url which should contain either access token or failure reason in the query parameter / hash
  window.localStorage.setItem(requestKey, window.location.href);
  window.close();
</script>
</body>

</html>


问:
Create lines of string where the number of lines is equal to the number of elements in a list
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello
```

<p>Or if <code>len(x) = 3</code></p>

<pre class="lang-py prettyprint-override"><code>Hello
Hello
Hello
</code>```

How could I code this for any length, which is bigger than 0?

Thanks in advance!

答:
First, we have some list (input data). You said that you need a function, so we'll then define it. Then the ('for') loop executes when position i is included in the list (in our example: 3 places (note that Python starts counting at 0)). This happens 4 times (0, 1, 2, 3). Then we just execute the function and we are done. Also look at the comments, which explain everything.

# Define our list:
exampleList = [1, 2, 3, 4]

# Define our function:
def function():
    for i in exampleList:
        print('Hello')

# Execute our function:
function()
# --------------------------------------
# Result:
# Hello
# Hello
# Hello
# Hello
```

<p>You can also do this with the while loop.</p>

<pre class="lang-py prettyprint-override"><code>exampleList = [1, 2, 3, 4]
def function():
    i = 0
    while i < len(exampleList):
        print('Hello')
        i += 1
function()
</code>```

Just don't stop asking the questions and don't forget to add 'i += 1' at the end of the while loop ...

Body:
I am trying to create a function where it takes the length of a list and can produce lines of string where the number of lines is equal to the number of elements in said list.

For example, if for list x, len(x) = 2, and I want to produce:

Hello
Hello

Or if len(x) = 3

Hello
Hello
Hello

How could I code this for any length, which is bigger than 0?

Thanks in advance!

Body:
First, we have some list (input data). You said that you need a function, so we'll then define it. Then the ('for') loop executes when position i is included in the list (in our example: 3 places (note that Python starts counting at 0)). This happens 4 times (0, 1, 2, 3). Then we just execute the function and we are done. Also look at the comments, which explain everything.

# Define our list:
exampleList = [1, 2, 3, 4]

# Define our function:
def function():
    for i in exampleList:
        print('Hello')

# Execute our function:
function()
# --------------------------------------
# Result:
# Hello
# Hello
# Hello
# Hello

You can also do this with the while loop.

exampleList = [1, 2, 3, 4]
def function():
    i = 0
    while i < len(exampleList):
        print('Hello')
        i += 1
function()

Just don't stop asking the questions and don't forget to add 'i += 1' at the end of the while loop ...


问:
Add a query to Retrofit only if value exist
I'm trying to make an endpoint which can call to:

```<code>...retailer/home
</code>```

or

```<code>...retailer/home?uid=123123123
</code>```

I use the next source code to generate de call:

```<code>@GET("retailer/home")
fun retrieveHomeContent(@Query("uid") uid: String? = null): Single<HomeContentEntity>
</code>```

But when I test this, the result is:

```<code>retailer/home?uid=
</code>```

So, I don't know how to makes retrofit to ignores the Query when the value is null. Any advice?

答: @Query params support optional fields. Simply pass null if you don't want to pass a value.</p>

Body:
I'm trying to make an endpoint which can call to:

...retailer/home

or

...retailer/home?uid=123123123

I use the next source code to generate de call:

@GET("retailer/home")
fun retrieveHomeContent(@Query("uid") uid: String? = null): Single<HomeContentEntity>

But when I test this, the result is:

retailer/home?uid=

So, I don't know how to makes retrofit to ignores the Query when the value is null. Any advice?


问:
What is more efficient? Storing a split string in an array, or calling the split method everytime you need it
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

```<code>String main = "1,2,3,4,5,6";
String[] array = main.split(",");
</code>```

vs

```<code>main.split(",");
</code>```

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

```<code>for (int i = main.length - 1; i >= 0; i--){}
</code>```

vs

```<code>for (int i = main.split(",") - 1; i >= 0; i--){}
</code>```

答:
I would prefer to split once and keep the tokens around regardless of the size of the array.  If the resulting array is large, it will be more expensive to split each time.  If it is small, the resultant storage is probably not going to be a factor.

If your worried about storage for a large array, then the last time you split should also be a concern.  To mitigate that, simply assign null to the array when your done and let the garbage collector do its thing.

If I were going to iterate thru an array of tokens, I would probably do it like this.

```<code>for (String token : main.split(",")) {
    // do some stuff.
}
</code>```

which creates the array once.

Body:
What is going to be faster, storing a split string into an array and using this array within my program, or could I call the .split() method on the string whenever I needed an array to iterate through?

String main = "1,2,3,4,5,6";
String[] array = main.split(",");

vs

main.split(",");

whenever I need to use the input values?

I realise it will be way more readable if I were to store the string in an array. I'd just like to know if the .split() takes more computing time than using an array. Since the split method returns an array containing the split strings.

A simple example(?) loop to go with the question:

for (int i = main.length - 1; i >= 0; i--){}

vs

for (int i = main.split(",") - 1; i >= 0; i--){}

Body:
I would prefer to split once and keep the tokens around regardless of the size of the array.  If the resulting array is large, it will be more expensive to split each time.  If it is small, the resultant storage is probably not going to be a factor.

If your worried about storage for a large array, then the last time you split should also be a concern.  To mitigate that, simply assign null to the array when your done and let the garbage collector do its thing.

If I were going to iterate thru an array of tokens, I would probably do it like this.

for (String token : main.split(",")) {
    // do some stuff.
}

which creates the array once.


问:
Mount vfat image win linux using C
I'm trying to mount a vfat disk image from DOS, using .C

```<code>if( mount( "/mypath/disk.img", "/mypath/img/", "vfat", MS_DIRSYNC | MS_SYNCHRONOUS, "utf8" ) ) {
  printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
}
</code>```

I get all the times the error "Block device required". Should i add some parameter or flag?

Note:I can mount from the bash the same file in the same target without any error.

UPDATE:
I had some good result using the function to mount an ISO. When I run the program, it remains stacked on the call ioctl(loop_device_fd, LOOP_CLR_FD, 0);. When I exit from the program (ctrl-c), the image is mounted. Is  LOOP_CLR_FD necessary to complete all the steps? In additional,it is mounted in read only and seems not possible to change it in read/write.

```<code>const auto loop_control = std::fopen( "/dev/loop-control", "r" );
const auto loop_control_fd = fileno(loop_control);
const auto devnr = ioctl(loop_control_fd, LOOP_CTL_GET_FREE);
std::stringstream loopname;
loopname << "/dev/loop" << devnr;
const auto loop_device_name = loopname.str();
const auto loop_device = std::fopen(loop_device_name.c_str(), "r");
const auto loop_device_fd = fileno(loop_device);
const auto image = std::fopen( dst.c_str(), "r" );
const auto image_fd = fileno(image);
//Associate the loop device with the open file whose file descriptor is passed as the (third) ioctl(2) argument.
ioctl(loop_device_fd, LOOP_SET_FD, image_fd);
const auto result = mount(loop_device_name.c_str(), dst_path_img.c_str(), "vfat", MS_RDONLY, NULL);
if( result ) {
printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
return;
}
ioctl(loop_device_fd, LOOP_CLR_FD, 0);
</code>```

答:
The example code from the link above seems to mount your image quite fine, with minor modifications to retrieve free loop device (I'm assuming it is Dos3.3 diskette image from allbootdisks.com):

#include <sys/mount.h>
#include <linux/loop.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main()
{
    int control_fd, file_fd, device_fd;
    char loop_device[16];

    control_fd = open("/dev/loop-control", O_RDWR);
    if (control_fd < 0) {
        perror("open loop control device failed");
        return 1;
    }

    int loop_id = ioctl(control_fd, LOOP_CTL_GET_FREE);
    sprintf(loop_device, "/dev/loop%d", loop_id);
    close(control_fd);

    printf("using loop device: %s\n", loop_device);

    file_fd = open("./Dos3.3.img", O_RDWR);
    if (file_fd < 0) {
        perror("open backing file failed");
        return 1;
    }

    device_fd = open(loop_device, O_RDWR);
    if (device_fd < 0) {
        perror("open loop device failed");
        close(file_fd);
        return 1;
    }

    if (ioctl(device_fd, LOOP_SET_FD, file_fd) < 0) {
        perror("ioctl LOOP_SET_FD failed");
        close(file_fd);
        close(device_fd);
        return 1;
    }

    close(file_fd);

    if (mount(loop_device, "./mnt/", "vfat", MS_DIRSYNC | MS_SYNCHRONOUS, "") < 0) {
        perror("mount failed");
    } else {
        printf("mount successful\n");
    }

    // always free loop device in the end
    ioctl(device_fd, LOOP_CLR_FD, 0);
    close(device_fd);
}
```

Title: Mount vfat image win linux using C

Body:
I'm trying to mount a vfat disk image from DOS, using .C

if( mount( "/mypath/disk.img", "/mypath/img/", "vfat", MS_DIRSYNC | MS_SYNCHRONOUS, "utf8" ) ) {
  printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
}

I get all the times the error "Block device required". Should i add some parameter or flag?

Note:I can mount from the bash the same file in the same target without any error.

UPDATE:
I had some good result using the function to mount an ISO. When I run the program, it remains stacked on the call ioctl(loop_device_fd, LOOP_CLR_FD, 0);. When I exit from the program (ctrl-c), the image is mounted. Is  LOOP_CLR_FD necessary to complete all the steps? In additional,it is mounted in read only and seems not possible to change it in read/write.

const auto loop_control = std::fopen( "/dev/loop-control", "r" );
const auto loop_control_fd = fileno(loop_control);
const auto devnr = ioctl(loop_control_fd, LOOP_CTL_GET_FREE);
std::stringstream loopname;
loopname << "/dev/loop" << devnr;
const auto loop_device_name = loopname.str();
const auto loop_device = std::fopen(loop_device_name.c_str(), "r");
const auto loop_device_fd = fileno(loop_device);
const auto image = std::fopen( dst.c_str(), "r" );
const auto image_fd = fileno(image);
//Associate the loop device with the open file whose file descriptor is passed as the (third) ioctl(2) argument.
ioctl(loop_device_fd, LOOP_SET_FD, image_fd);
const auto result = mount(loop_device_name.c_str(), dst_path_img.c_str(), "vfat", MS_RDONLY, NULL);
if( result ) {
printf( "Error mount %s errno=%d %s\n", dst.c_str(), errno, strerror( errno ) );
return;
}
ioctl(loop_device_fd, LOOP_CLR_FD, 0);


问:
CSV File: counting how many times the word "life" appears in a column
```<code>with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)
</code>```

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

答:
You have your if and else logic backwards    </p>

```<code>with open("billboard_songs.csv") as data:
    song_count = 0
    for line in data:
        line_strip = line.split(",")
        if "life" in line_strip[1]:
            print(line)
            song_count += 1
        else:
            continue
</code>```

Body:
with open("billboard_songs.csv") as data:
for line in data:
    line_strip = line.split(",")
    if "life" in line[1]:
        continue
    else:
        print(line)

What I want to accomplish is to count how many times the word "life" comes up in song titles. The CSV file is as follow: rank, song, artist, year, lyrics, source and it is split by commas (obviously). So we are looking in location [1] with song.

What am I doing wrong? My output gives me a list of songs but none have the word "life" in them.

Body:
You have your if and else logic backwards

with open("billboard_songs.csv") as data:
    song_count = 0
    for line in data:
        line_strip = line.split(",")
        if "life" in line_strip[1]:
            print(line)
            song_count += 1
        else:
            continue


问:
How to remove invalid database connection from pool
I am using connection pooling of tomcat with oracle database. It is working fine, but when i use my application after a long time it is giving error that "connection reset". I am getting this error because of physical connection at oracle server closed before logical connection closed at tomcat datasource. So before getting the connection from datasource i am checking the connection validity with isValid(0) method of connection object which gives false if the physical connection was closed. But i don't know how to remove that invalid connection object from the pool.

答:
This could be because on the db server, there is a timeout to not allow connections to live beyond a set time, or to die if it does not receive something saying it is still valid. One way to fix this is to turn on keepalives. These basically ping the db server saying that they are still valid connections.

This is a pretty good link on Tomcats DBCP configurations. Take a look at the section titled "Preventing dB connection pool leaks". That looks like it may be a good place to start.


答:
Check if the element that you want to use exists, if not, create it</p>

```<code>var i = 0;
var j = 0;
var arr = [];

for( i = 0; i < 8; i++) {
  for( j = 0; j < 8; j++) {
    arr[i] = arr[i] || []; // Create array if needed
    arr[i][j] = 'value';
  }
}
</code>```

Title: Why I can't assign values to a emtpy array with a For cicle?

Body:
I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

I am learning to use Javascript. I tried to fill an empty matrix, through a For cycle. I think that the sentence I declare has logic, and it should work, I have something intrigued. Anyone know the reason why Javascript does not work with this code?

var i = 0 , j = 0;
var arr = [[],[]];

for( i = 0; i < 8; i++){

  for( j = 0; j < 8; j++){

     arr[i][j] = 7;
     alert(arr[i][j]);

  }

   alert(arr[i][j]);

}

Body:
Check if the element that you want to use exists, if not, create it

var i = 0;
var j = 0;
var arr = [];

for( i = 0; i < 8; i++) {
  for( j = 0; j < 8; j++) {
    arr[i] = arr[i] || []; // Create array if needed
    arr[i][j] = 'value';
  }
}