答:
Like so?
You need flex-wrap: wrap; In order to wrap the items need to be wide enough (100%). Since 100% flex item is always justified to the full width, you need text-align, not align-items which is the wrong property in the first place.

align-items is the alignment at the cross axis, not the main axis which would be justify-content

.flex-row {
  min-height: 400px;
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}

.flex-item {
  flex-basis: 100%;
}
.flex-item:nth-child(2) {
  text-align: center;
}

.flex-item:last-child {
  text-align: right;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
</div></code>```

Title: How to align the flex items in three different ways?

Body:
Like so?
You need flex-wrap: wrap; In order to wrap the items need to be wide enough (100%). Since 100% flex item is always justified to the full width, you need text-align, not align-items which is the wrong property in the first place.

align-items is the alignment at the cross axis, not the main axis which would be justify-content

.flex-row {
  min-height: 400px;
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
}

.flex-item {
  flex-basis: 100%;
}
.flex-item:nth-child(2) {
  text-align: center;
}

.flex-item:last-child {
  text-align: right;
}

<div class="flex-row">
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
  <div class="flex-item">
    <img src="/default.png" width="100" height="50">
  </div>
</div>


来源: stackexchange

问:
Server hub connection from asp.net core 2.2 signalr console app
I have a server running .net 4.5.1 with SignalR (IIS)

I want to connect to the server using a console client app on .net core 2,2.  I have installed the below Nuget package on the client

Microsoft.AspNetCore.SignalR.Client;

and have followed

https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2

I keep getting the below error

"There was an error opening the connection:System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

The name of my Hub on the server is correct so I'm not sure of the problem

I have also tried

```<code>.WithUrl("http://172.10.0.20:81/client/?hub=myHub")
</code>```

please help

```<code>connection = new HubConnectionBuilder()

//.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

.WithUrl("http://172.10.0.20:81/myHub")

.Build();

connection.StartAsync().ContinueWith(task => {

if (task.IsFaulted)

{Console.WriteLine("There was an error opening the connection:{0}",

task.Exception.GetBaseException());}

else

{Console.WriteLine("Connected");}}).Wait();

connection.StartAsync();
</code>```

答:
I can't reproduce your problem . But since your server is hosted on .net 4.5.1 , please make sure that you are using same version of SignalR both on server side and client side .

That means that you you cannot use the ASP.NET CORE SignalR (Hub or Client) with the ASP.NET SignalR (Hub or Client). You can't mix them. You can click here for more info .

ContentLicense: CC BY-SA 4.0

Body:
I have a server running .net 4.5.1 with SignalR (IIS)

I want to connect to the server using a console client app on .net core 2,2.  I have installed the below Nuget package on the client

Microsoft.AspNetCore.SignalR.Client;

and have followed

https://learn.microsoft.com/en-us/aspnet/core/signalr/dotnet-client?view=aspnetcore-2.2

I keep getting the below error

"There was an error opening the connection:System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found)."

The name of my Hub on the server is correct so I'm not sure of the problem

I have also tried

.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

please help

connection = new HubConnectionBuilder()

//.WithUrl("http://172.10.0.20:81/client/?hub=myHub")

.WithUrl("http://172.10.0.20:81/myHub")

.Build();

connection.StartAsync().ContinueWith(task => {

if (task.IsFaulted)

{Console.WriteLine("There was an error opening the connection:{0}",

task.Exception.GetBaseException());}

else

{Console.WriteLine("Connected");}}).Wait();

connection.StartAsync();


问:
Problem in getting values in Numpy Polynomial
```<code>import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Chebyshev as T
X=np.array([1,2,4,5,6,7,8,9,10,11,12,13])
data=np.array([2.312,4.563,6.765,7.897,12.456,7.568,6.543,3.453,6.654,9.678,11.453,19.567])
p=T.fit(X,data,6)
plt.plot(X,data)
plt.plot(*p.linspace(60))
</code>```

I generated a data for which i am doing fitting using numpy polynomial chebyshev. the chebyshev is fitting the data but i dont know how am i going to get the the fitted data values from this code?
Is there any way to get the fitted values or do i have to change the whole code?

Body:
import numpy as np
import matplotlib.pyplot as plt
from numpy.polynomial import Chebyshev as T
X=np.array([1,2,4,5,6,7,8,9,10,11,12,13])
data=np.array([2.312,4.563,6.765,7.897,12.456,7.568,6.543,3.453,6.654,9.678,11.453,19.567])
p=T.fit(X,data,6)
plt.plot(X,data)
plt.plot(*p.linspace(60))

I generated a data for which i am doing fitting using numpy polynomial chebyshev. the chebyshev is fitting the data but i dont know how am i going to get the the fitted data values from this code?
Is there any way to get the fitted values or do i have to change the whole code?

Body:
At the end of your code, the Chebyshev data structure p holds what is needed to get any fitted value. For example, the expression

list(zip(*p.linspace(60)))

gives a list of 60 points, where each x coordinate is a value betwee 1 and 13, which were the bounds you gave for x values. The corresponding y value is the fitted value for the x value. You can then just choose which of the points you want.

Here is the result for that expression after running your code:

[(1.0, 2.541204853676799),
 (1.2033898305084745, 2.808340815346975),
 (1.4067796610169492, 3.0743429556868413),
 (1.6101694915254239, 3.348688496878723),
 (1.8135593220338984, 3.637978305373278),
 (2.016949152542373, 3.9462679999194794),
 (2.2203389830508478, 4.27538454719654),
 (2.4237288135593222, 4.625228345047772),
 (2.6271186440677967, 4.994060793316362),
 (2.830508474576271, 5.3787773522831195),
 (3.0338983050847457, 5.775166088706113),
 (3.2372881355932206, 6.178151709462269),
 (3.440677966101695, 6.582025082790894),
 (3.6440677966101696, 6.980658247139146),
 (3.8474576271186445, 7.367704907609403),
 (4.050847457627119, 7.736786420008617),
 (4.254237288135593, 8.081663262499552),
 (4.4576271186440675, 8.396391994853994),
 (4.661016949152542, 8.675467705307872),
 (4.864406779661017, 8.913951945018319),
 (5.067796610169491, 9.107586150122668),
 (5.271186440677966, 9.252890551399389),
 (5.474576271186441, 9.347248571530947),
 (5.677966101694915, 9.388976709968594),
 (5.88135593220339, 9.37737991539911),
 (6.084745762711865, 9.312792445813466),
 (6.288135593220339, 9.196604216177416),
 (6.491525423728814, 9.031272633704036),
 (6.694915254237289, 8.820319920728197),
 (6.898305084745763, 8.568315925182945),
 (7.101694915254238, 8.280846418677859),
 (7.305084745762712, 7.964466882179304),
 (7.508474576271187, 7.626641779292636),
 (7.711864406779662, 7.275669317146346),
 (7.915254237288136, 6.920591694878116),
 (8.11864406779661, 6.5710908397228325),
 (8.322033898305085, 6.237369630702523),
 (8.52542372881356, 5.930018609918223),
 (8.728813559322035, 5.6598681814437874),
 (8.932203389830509, 5.437826297821619),
 (9.135593220338983, 5.274701634160355),
 (9.338983050847459, 5.1810122498344615),
 (9.542372881355933, 5.166779737785785),
 (9.745762711864407, 5.241308861427015),
 (9.949152542372882, 5.412952679147101),
 (10.152542372881356, 5.68886315641859),
 (10.35593220338983, 6.074727265506907),
 (10.559322033898306, 6.574488572781565),
 (10.76271186440678, 7.190054313629292),
 (10.966101694915254, 7.920987954969137),
 (11.16949152542373, 8.764187245369472),
 (11.372881355932204, 9.713547752766893),
 (11.576271186440678, 10.75961188978718),
 (11.779661016949154, 11.889203426668058),
 (11.983050847457628, 13.08504749178393),
 (12.186440677966102, 14.325376059772596),
 (12.389830508474578, 15.583518927263885),
 (12.593220338983052, 16.827480176210102),
 (12.796610169491526, 18.019500124818624),
 (13.0, 19.115602766086262)]


问:
How to align the flex items in three different ways?

So, I want to align items inside flex-box like in the above picture.

I have html as follows:

```<code><div class="flex-row">
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
  <div class="flex-item">
    <img src="/default.png">
  </div>
</div>
</code>```

css as

```<code>   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }
</code>```

答:
Use align-self not align-items

.flex-row {
  min-height: 300px;
  display: flex;
  width: 90%;
  margin: 1em auto;
  border: 1px solid red;
  justify-content: space-between;
}

.flex-item {
  height: 50px;
  background: lightblue;
  width: 100px;
}

.flex-item:nth-child(2) {
  align-self: center;
}

.flex-item:last-child {
  align-self: flex-end;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container flex-row">
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
</div></code>```

Body:
So, I want to align items inside flex-box like in the above picture.

I have html as follows:

css as

   .flex-row {
      min-height: 400px;
      display: flex;
      align-items: flex-start;
   }

   .flex-item:nth-child(2) {
     align-items: center;
   }

   .flex-item:last-child {
      align-items: flex-end;
   }

Body:
Use align-self not align-items

.flex-row {
  min-height: 300px;
  display: flex;
  width: 90%;
  margin: 1em auto;
  border: 1px solid red;
  justify-content: space-between;
}

.flex-item {
  height: 50px;
  background: lightblue;
  width: 100px;
}

.flex-item:nth-child(2) {
  align-self: center;
}

.flex-item:last-child {
  align-self: flex-end;
}

<div class="container flex-row">
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
</div>


问:
Having trouble adding a hyperlink to a datatable
I have a Django app that uses jQuery DataTables for a list view of items. Now I am trying to add a hyperlink to the first element of the table which is the primary key for the model I am displaying. The intent is for the link to take you to a detail view for the model instance. I have what I think should work but it is giving me "undefined" for each item in the datatable and throws an error when you click on it. I think it just isn't picking up the ID of the model instance.

I've tried any variation of the render function that I can think of but I'm new to javascript so I'm a bit lost. I am pretty confident that my app will work once I get this sorted out.

Here is my html:

```<code>{% extends "app/layout.html" %}
{% block content %}

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Part Requests</title>

</head>

<body>

    <h1>Part Orders</h1>
    <a class="btn btn-info" style="float:right" href="{% url 'New_Order' %}">  New Part Order  </a>
    <br /><br />
    <div class="table-responsive">
        <table id="PartOrders" class="table table-hover">
            <thead>
                <tr>
                    <th>Order #</th>
                    <th>Priority</th>
                    <th>Part Number</th>
                    <th>Part Description</th>
                    <th>Quantity</th>
                    <th>Order Date</th>
                    <th>Unit Name</th>
                    <th>UIC</th>
                    <th>End Item</th>
                    <th>Reason For Order</th>
                </tr>
            </thead>
        </table>
    </div>

<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">

<script>
    $(document).ready(function() {
        $.get('/api/Order',
            function(data) {
                $('#PartOrders').DataTable( {
                    "data": data,
                    "columns": [
                        { 'data': 'id', 'name': 'id',
                                "render": function(data, type, full) {
                                return '<a href="/order/'+ full.path + '">' + data.id +' </a>';
                            }
                        },
                        { 'data': 'Priority', 'name': 'Priority' },
                        { 'data': 'PartNumber', 'name': 'Part Number' },
                        { 'data': 'PartDescription', 'name': 'Nomenclature' },
                        { 'data': 'Quantity', 'name': 'Quantity' },
                        { 'data': 'OrderDate', 'name': 'Order Date' },
                        { 'data': 'UnitName', 'name': 'Unit Name' },
                        { 'data': 'UIC', 'name': 'UIC' },
                        { 'data': 'EndItem', 'name': 'Aircraft' },
                        { 'data': 'ReasonForOrder', 'name': 'Reason For Order' }

                    ]
                });
            });
        });

</script>
</body>
</html>

{% endblock %}

{% block js %}
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/pdfmake.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.36/vfs_fonts.js"></script>

{% endblock js %}
</code>```

and here is my models in case that helps:

```<code>class PartOrder(models.Model):
    id = models.AutoField(primary_key=True)
    Priority = models.CharField(max_length=20, choices=(('AOG','AOG'),('Rush','Rush'),('Planned','Planned')))
    PartNumber = models.CharField(max_length=35)
    PartDescription = models.CharField(max_length=200)
    SerialNumber = models.CharField(max_length=35)
    UnitOfMeasure = models.CharField(max_length=35)
    Quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)])
    OrderDate = models.DateTimeField(auto_now=True)
    UnitName = models.CharField(max_length=35)
    UIC = models.CharField(max_length=6)
    ShippingAddress = models.CharField(max_length=200)
    TimeSinceNew = models.CharField(max_length=35)
    EndItem = models.CharField(max_length=20, choices=(('UH-72A','UH-72A'),('44301-10-7 Hoist','44301-10-7 Hoist')))
    AircraftSN = models.CharField(max_length=7)
    AircrafTime = models.DecimalField(max_digits=5, decimal_places=2)
    Engine1SN = models.CharField(max_length=12)
    Engine1_TSN = models.DecimalField(max_digits=5, decimal_places=2)
    Engine2SN = models.CharField(max_length=12)
    Engine2_TSN = models.DecimalField(max_digits=5, decimal_places=2)
    ReasonForOrder = models.CharField(max_length=200)
    RequestedBy = models.CharField(max_length=35)

    class Meta:
            ordering = ['Priority']

</code>```

答:
I think, you should refer to the first argument of render callback:

```<code>render: function (data, type, full) => `<a href="/order/${data.path}">${data.id}</a>`
</code>```

Other than that, I would recommend to use DataTables option ajax rather than wrapping your code with your own $.get() success callback - it would give you more flexibility and better integration with DataTables API;

DataTables/jQuery files are normally included in  section of the page;

Plain table header appearing before all the necessary files are loaded may look annoying, so you may set DataTables initialization target node as simple as:

```<code><table id="PartOrders" class="table table-hover"></table>
</code>```

DataTables will populate that for you (including header, you simply need to change columns.name option for columns.title)

Body:
I have a Django app that uses jQuery DataTables for a list view of items. Now I am trying to add a hyperlink to the first element of the table which is the primary key for the model I am displaying. The intent is for the link to take you to a detail view for the model instance. I have what I think should work but it is giving me "undefined" for each item in the datatable and throws an error when you click on it. I think it just isn't picking up the ID of the model instance.

I've tried any variation of the render function that I can think of but I'm new to javascript so I'm a bit lost. I am pretty confident that my app will work once I get this sorted out.

Here is my html:

{% extends "app/layout.html" %}
{% block content %}

    <meta charset="utf-8" />
    <title>Part Requests</title>

Part Orders

      New Part Order

                    Order #
                    Priority
                    Part Number
                    Part Description
                    Quantity
                    Order Date
                    Unit Name
                    UIC
                    End Item
                    Reason For Order

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="sha384-gfdkjb5BdAXd+lj+gudLWI+BXq4IuLW5IT+brZEZsLFm++aCMlF1V92rMkPaX4PP" crossorigin="anonymous">

{% endblock %}

{% block js %}

{% endblock js %}

and here is my models in case that helps:

class PartOrder(models.Model):
    id = models.AutoField(primary_key=True)
    Priority = models.CharField(max_length=20, choices=(('AOG','AOG'),('Rush','Rush'),('Planned','Planned')))
    PartNumber = models.CharField(max_length=35)
    PartDescription = models.CharField(max_length=200)
    SerialNumber = models.CharField(max_length=35)
    UnitOfMeasure = models.CharField(max_length=35)
    Quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)])
    OrderDate = models.DateTimeField(auto_now=True)
    UnitName = models.CharField(max_length=35)
    UIC = models.CharField(max_length=6)
    ShippingAddress = models.CharField(max_length=200)
    TimeSinceNew = models.CharField(max_length=35)
    EndItem = models.CharField(max_length=20, choices=(('UH-72A','UH-72A'),('44301-10-7 Hoist','44301-10-7 Hoist')))
    AircraftSN = models.CharField(max_length=7)
    AircrafTime = models.DecimalField(max_digits=5, decimal_places=2)
    Engine1SN = models.CharField(max_length=12)
    Engine1_TSN = models.DecimalField(max_digits=5, decimal_places=2)
    Engine2SN = models.CharField(max_length=12)
    Engine2_TSN = models.DecimalField(max_digits=5, decimal_places=2)
    ReasonForOrder = models.CharField(max_length=200)
    RequestedBy = models.CharField(max_length=35)

    class Meta:
            ordering = ['Priority']

Body:
I think, you should refer to the first argument of render callback:

render: function (data, type, full) => `<a href="/order/${data.path}">${data.id}</a>`

Other than that, I would recommend to use DataTables option ajax rather than wrapping your code with your own $.get() success callback - it would give you more flexibility and better integration with DataTables API;

DataTables/jQuery files are normally included in <head> section of the page;

Plain table header appearing before all the necessary files are loaded may look annoying, so you may set DataTables initialization target node as simple as:

<table id="PartOrders" class="table table-hover"></table>

DataTables will populate that for you (including header, you simply need to change columns.name option for columns.title)


问:
UNDERSTANDING how to count trailing zeros for a number using bitwise operators in C
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

```<code>unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
</code>```

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?

答:
The code first transforms v is such a way that is is entirely null, except the left most one that remains. Then, it determines the position of this first one.

First let's see how we suppress all ones but the left most one.

Assume that k is the position of the left most one in v. v=(vn-1,vn-2,..vk+1,1,0,..0).

-v is the number that added to v will give 0 (actually it gives 2^n, but bit 2^n is ignored if we only keep the n less significant bits).

What must the value of bits in -v so that v+-v=0?

obviously bits k-1..0 of -k must be at 0 so that added to the trailing zeros in v they give a zero.

bit k must be at 1. Added to the one in vk, it will give a zero and a carry at one at order k+1

bit k+1 of -v will be added to vk+1 and to the carry generated at step k. It must be the logical complement of vk+1. So whatever the value of vk+1, we will have 1+0+1 if vk+1=0 (or 1+1+0 if vk+1=1) and result will be 0 at order k+1 with a carry generated at order k+2.

This is similar for bits n-1..k+2 and they must all be the logical complement of the corresponding bit in v.

Hence, we get the well-known result that to get -v, one must

leave unchanged all trailing zeros of v

leave unchanged the left most one of v

complement all the other bits.

If we compute v&-v, we have

```<code> v      vn-1  vn-2    ...  vk+1  1   0   0  ... 0
-v   & ~vn-1 ~vn-2    ... ~vk+1  1   0   0  ... 0
v&-v      0     0     ...    0   1   0   0  ... 0
</code>```

So v&-v only keeps the left most one in v.

To find the location of first one, look at the code:

```<code>if (v) c--;  // no 1 in result? -> 32 trailing zeros.
             // Otherwise it will be in range c..0=31..0
if (v & 0x0000FFFF) c -= 16; // If there is a one in left most part of v  the range
                             //   of possible values for the location of this one
                             //   will be 15..0.
                             // Otherwise, range must 31..16
                             // remaining range is c..c-15
if (v & 0x00FF00FF) c -= 8;  // if there is one in either byte 0 (c=15) or byte 2 (c=31),
                             // the one is in the lower part of range.
                             // So we must substract 8 to boundaries of range.
                             // Other wise, the one is in the upper part.
                             // Possible range of positions of v is now c..c-7
if (v & 0x0F0F0F0F) c -= 4;  // do the same for the other bits.
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;
</code>```

Body:
Note - This is NOT a duplicate of this question - Count the consecutive zero bits (trailing) on the right in parallel: an explanation? . The linked question has a different context, it only asks the purpose of signed() being use. DO NOT mark this question as duplicate.

I've been finding a way to acquire the number of trailing zeros in a number. I found a bit twiddling Stanford University Write up HERE here that gives the following explanation.

unsigned int v;      // 32-bit word input to count zero bits on right
unsigned int c = 32; // c will be the number of zero bits on the right
v &= -signed(v);
if (v) c--;
if (v & 0x0000FFFF) c -= 16;
if (v & 0x00FF00FF) c -= 8;
if (v & 0x0F0F0F0F) c -= 4;
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;

Why does this end up working ? I have an understanding of how Hex numbers are represented as binary and bitwise operators, but I am unable to figure out the intuition behind this working ? What is the working mechanism ?

Body:
The code first transforms v is such a way that is is entirely null, except the left most one that remains. Then, it determines the position of this first one.

First let's see how we suppress all ones but the left most one.

Assume that k is the position of the left most one in v. v=(vn-1,vn-2,..vk+1,1,0,..0).

-v is the number that added to v will give 0 (actually it gives 2^n, but bit 2^n is ignored if we only keep the n less significant bits).

What must the value of bits in -v so that v+-v=0?

obviously bits k-1..0 of -k must be at 0 so that added to the trailing zeros in v they give a zero.

bit k must be at 1. Added to the one in vk, it will give a zero and a carry at one at order k+1

bit k+1 of -v will be added to vk+1 and to the carry generated at step k. It must be the logical complement of vk+1. So whatever the value of vk+1, we will have 1+0+1 if vk+1=0 (or 1+1+0 if vk+1=1) and result will be 0 at order k+1 with a carry generated at order k+2.

This is similar for bits n-1..k+2 and they must all be the logical complement of the corresponding bit in v.

Hence, we get the well-known result that to get -v, one must

leave unchanged all trailing zeros of v

leave unchanged the left most one of v

complement all the other bits.

If we compute v&-v, we have

 v      vn-1  vn-2    ...  vk+1  1   0   0  ... 0
-v   & ~vn-1 ~vn-2    ... ~vk+1  1   0   0  ... 0
v&-v      0     0     ...    0   1   0   0  ... 0

So v&-v only keeps the left most one in v.

To find the location of first one, look at the code:

if (v) c--;  // no 1 in result? -> 32 trailing zeros.
             // Otherwise it will be in range c..0=31..0
if (v & 0x0000FFFF) c -= 16; // If there is a one in left most part of v  the range
                             //   of possible values for the location of this one
                             //   will be 15..0.
                             // Otherwise, range must 31..16
                             // remaining range is c..c-15
if (v & 0x00FF00FF) c -= 8;  // if there is one in either byte 0 (c=15) or byte 2 (c=31),
                             // the one is in the lower part of range.
                             // So we must substract 8 to boundaries of range.
                             // Other wise, the one is in the upper part.
                             // Possible range of positions of v is now c..c-7
if (v & 0x0F0F0F0F) c -= 4;  // do the same for the other bits.
if (v & 0x33333333) c -= 2;
if (v & 0x55555555) c -= 1;


问:
LINQ side effects
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

```<code>List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);
</code>```

To:

```<code>List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);
</code>```

答:
There is no Linq equivalent of foreach, although it is fairly easy to implement one yourself.

Eric Lippert gives a good description here of why this was not implemented in Linq itself.

However, if your collection is a List (which it appears to be in your example), you can use List.ForEach:

```<code>myList.ForEach(item => Console.WriteLine(item));
</code>```

ContentLicense: CC BY-SA 3.0

Title: LINQ side effects

Body:
is it possible to substitute a foreach loop with a lambda expression in LINQ (.Select))?

List<int> l = {1, 2, 3, 4, 5};
foreach (int i in l)
    Console.WriteLine(i);

To:

List<int> l = {1, 2, 3, 4, 5};
l.Select(/* print to console */);

Body:
There is no Linq equivalent of foreach, although it is fairly easy to implement one yourself.

Eric Lippert gives a good description here of why this was not implemented in Linq itself.

However, if your collection is a List (which it appears to be in your example), you can use List.ForEach:

myList.ForEach(item => Console.WriteLine(item));


问:
try Google API Buckets: testIamPermissions for a specific service account
I can use Buckets: testIamPermissions to test the permissions on a bucket for the logged in user.

Is there a way in which I can test it for a service account.

Any help will be appreciated. Thanks...

答:
After taking another look on your question, I found a way to use Buckets: testIamPermissions with a Service Account:

You have to download the service account’s key.json file in your environment (with gcloud set up) and create an environment variable with:

```<code>GOOGLE_APPLICATION_CREDENTIALS=[key.json]
</code>```

Then, you can get a token of this service account via:

```<code>gcloud auth application-default print-access-token
</code>```

Finally, you can curl the testIamPermissions URL and pass that token as authorization header:

```<code>curl 'https://www.googleapis.com/storage/v1/b/[BUCKET]/iam/testPermissions?permissions=[PERMISSION]'   -H 'Authorization: Bearer [TOKEN]’
</code>```

Body:
After taking another look on your question, I found a way to use Buckets: testIamPermissions with a Service Account:

You have to download the service account’s key.json file in your environment (with gcloud set up) and create an environment variable with:

GOOGLE_APPLICATION_CREDENTIALS=[key.json]

Then, you can get a token of this service account via:

gcloud auth application-default print-access-token

Finally, you can curl the testIamPermissions URL and pass that token as authorization header:

curl 'https://www.googleapis.com/storage/v1/b/[BUCKET]/iam/testPermissions?permissions=[PERMISSION]'   -H 'Authorization: Bearer [TOKEN]’


问:
Get MAC address using shell script
Currently all the solution mentioned for getting the MAC address always use eth0.
But what if instead of eth0 my interfaces start with eth1. Also on OS X the interface names are different.

Also the interface eth0 may be present but is unused. i.e. not active, it doesn't have an IP.

So is there a way I could get the MAC address for the first available interface that is Active.(i.e. it has an inet address, I even don't want one having inet6).

For E.g

```<code>eth0      Link encap:Ethernet  HWaddr <some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

eth1      Link encap:Ethernet  HWaddr <some addr>
          inet addr:<some addr>  Bcast:<some addr>  Mask:<some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:123 Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000
</code>```

NOTE : I have changed the values of the output.

So in this case I want the HWaddr for eth1 and not eth0.
How do I find it ? Also it should work on all the Linux flavours.

答:
I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:

```<code>ip link show eth0 | grep link/ether | awk '{print $2}'
</code>```

Have a nice day!

Title: Get MAC address using shell script

Body:
Currently all the solution mentioned for getting the MAC address always use eth0.
But what if instead of eth0 my interfaces start with eth1. Also on OS X the interface names are different.

Also the interface eth0 may be present but is unused. i.e. not active, it doesn't have an IP.

So is there a way I could get the MAC address for the first available interface that is Active.(i.e. it has an inet address, I even don't want one having inet6).

For E.g

eth0      Link encap:Ethernet  HWaddr <some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

eth1      Link encap:Ethernet  HWaddr <some addr>
          inet addr:<some addr>  Bcast:<some addr>  Mask:<some addr>
          inet6 addr: <some addr> Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:123 Metric:123
          RX packets:123 errors:123 dropped:123 overruns:123 frame:123
          TX packets:123 errors:123 dropped:123 overruns:123 carrier:123
          collisions:123 txqueuelen:123
          RX bytes:123 (123 MB)  TX bytes:123 (123 KB)
          Interrupt:123 Memory:00000000-00000000

NOTE : I have changed the values of the output.

So in this case I want the HWaddr for eth1 and not eth0.
How do I find it ? Also it should work on all the Linux flavours.

Body:
I know that is a little bit dated, but with basic commands, we can take the mac address of an interface:

ip link show eth0 | grep link/ether | awk '{print $2}'

Have a nice day!


问:
Implementing partial recursive function in C#
I am having trouble with somwhow implementing a partial recursive function (at least in my mind though).

for any given p and arbitrary maxsteps = 100, calculate L:

答:
There I left you the code for the recursive approach:

```<code>class Program
{
    static void Main(string[] args)
    {
        double recursiveL = CalculateL(100, 100);
        double notRecursiveLWrong = NotRecursiveCalculateLWrong(100, 100);
        double notRecursiveLRight = NotRecursiveCalculateLRight(100, 100);
    }

    private static double CalculateL(double p, int maxSteps)
    {
        if (maxSteps == 0)
        {
            return (1 / (p + 1));
        }
        else
        {
            return (1 / (p + CalculateL(p, maxSteps - 1)));
        }
    }

    private static double NotRecursiveCalculateLWrong(double p, int maxSteps)
    {
        double result = 0;
        for (int i = 0; i < maxSteps; i++)
        {
            result = (1 / (p + result));
        }
        return result;
    }

    private static double NotRecursiveCalculateLRight(double p, int maxSteps)
    {
        double result = 1 / (p + 1);
        for (int i = 0; i < maxSteps; i++)
        {
            result = (1 / (p + result));
        }
        return result;
    }
}
</code>```

While making it I was thinking about the fact that for this problem, recursion isn't needed and now I can see that I'm not the only one.

I added my not recursive approach.

Edit:

If you try my code you will see that every method returns the same value, WATCHOUT, this is cause of the low precision in floating points.

The correct approach is NotRecursiveCalculateLRight which is stated in @John 's answer.

Body:
There I left you the code for the recursive approach:

class Program
{
    static void Main(string[] args)
    {
        double recursiveL = CalculateL(100, 100);
        double notRecursiveLWrong = NotRecursiveCalculateLWrong(100, 100);
        double notRecursiveLRight = NotRecursiveCalculateLRight(100, 100);
    }

    private static double CalculateL(double p, int maxSteps)
    {
        if (maxSteps == 0)
        {
            return (1 / (p + 1));
        }
        else
        {
            return (1 / (p + CalculateL(p, maxSteps - 1)));
        }
    }

    private static double NotRecursiveCalculateLWrong(double p, int maxSteps)
    {
        double result = 0;
        for (int i = 0; i < maxSteps; i++)
        {
            result = (1 / (p + result));
        }
        return result;
    }

    private static double NotRecursiveCalculateLRight(double p, int maxSteps)
    {
        double result = 1 / (p + 1);
        for (int i = 0; i < maxSteps; i++)
        {
            result = (1 / (p + result));
        }
        return result;
    }
}

While making it I was thinking about the fact that for this problem, recursion isn't needed and now I can see that I'm not the only one.

I added my not recursive approach.

Edit:

If you try my code you will see that every method returns the same value, WATCHOUT, this is cause of the low precision in floating points.

The correct approach is NotRecursiveCalculateLRight which is stated in @John 's answer.


问:
GOOGLE_APPLICATION_CREDENTIALS cannot be found on kubeflow
I follow the tutorial for building kubeflow on GCP.

At the last step, I got stuck at "Check the permissions for your training component".

After setting these secretName and secretMountPath.

```<code>kustomize edit add configmap mnist-map-training --from-literal=secretName=user-gcp-sa
kustomize edit add configmap mnist-map-training --from-literal=secretMountPath=/var/secrets
</code>```

and run

```<code>kustomize build . |kubectl apply -f -
</code>```

I got the error:

Error: field specified in var '{GOOGLE_APPLICATION_CREDENTIALS ~G_v1_ConfigMap {data.GOOGLE_APPLICATION_CREDENTIALS}}' not found in
  corresponding resource
      error: no objects passed to apply

I cannot find my GOOGLE_APPLICATION_CREDENTIALS at /var/secrets in my local machine, but I think kubeflow will automatic create for me based on this document.

Or maybe because I use "Authenticating with username and password" for authenticating kubeflow?

答:
I found the solution at here.

```<code>kustomize edit add configmap mnist-map-monitoring --from-literal=GOOGLE_APPLICATION_CREDENTIALS=/var/secrets/user-gcp-sa.json
</code>```

In original tutorial, lacking of this.

Body:
I follow the tutorial for building kubeflow on GCP.

At the last step, I got stuck at "Check the permissions for your training component".

After setting these secretName and secretMountPath.

kustomize edit add configmap mnist-map-training --from-literal=secretName=user-gcp-sa
kustomize edit add configmap mnist-map-training --from-literal=secretMountPath=/var/secrets

and run

kustomize build . |kubectl apply -f -

I got the error:

Error: field specified in var '{GOOGLE_APPLICATION_CREDENTIALS ~G_v1_ConfigMap {data.GOOGLE_APPLICATION_CREDENTIALS}}' not found in
  corresponding resource
      error: no objects passed to apply

I cannot find my GOOGLE_APPLICATION_CREDENTIALS at /var/secrets in my local machine, but I think kubeflow will automatic create for me based on this document.

Or maybe because I use "Authenticating with username and password" for authenticating kubeflow?

Body:
I found the solution at here.

kustomize edit add configmap mnist-map-monitoring --from-literal=GOOGLE_APPLICATION_CREDENTIALS=/var/secrets/user-gcp-sa.json

In original tutorial, lacking of this.


问:
doSignInWithEmailAndPassword() is missing from firebase.auth()
I want to use React Context to provide a firebase instance to my React Application. Firebase class that I wrote is as below:

```<code>import firebase from "firebase/app";
import "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DB_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
};

class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
    this.auth = firebase.auth();
  }

  // *** AUTH API ***

  doCreateUserWithEmailAndPassword = (email, password) => {
    this.auth.createUserWithEmailAndPassword(email, password);
  };

  doSignInWithEmailAndPassword = (email, password) => {
    this.auth.doSignInWithEmailAndPassword(email, password);
  };

  doSignOut = () => this.auth.signOut();

  doPasswordReset = email => this.auth.sendPasswordResetEmail(email);

  doPasswordUpdate = password => this.auth.currentUser.updatePassword(password);
}

export default Firebase;
</code>```

When I try to do sign in with Email and Password, I got the following error:

```<code>TypeError: this.auth.doSignInWithEmailAndPassword is not a function
    at Firebase.doSignInWithEmailAndPassword (firebase.js:27)
    at SignInFormBase.onSubmit (SignIn.jsx:26)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
    at executeDispatch (react-dom.development.js:571)
    at executeDispatchesInOrder (react-dom.development.js:596)
    at executeDispatchesAndRelease (react-dom.development.js:695)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:704)
    at forEachAccumulated (react-dom.development.js:676)
    at runEventsInBatch (react-dom.development.js:844)
    at runExtractedEventsInBatch (react-dom.development.js:852)
    at handleTopLevel (react-dom.development.js:5030)
    at batchedUpdates$1 (react-dom.development.js:21469)
    at batchedUpdates (react-dom.development.js:2247)
    at dispatchEvent (react-dom.development.js:5110)
    at react-dom.development.js:21526
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at interactiveUpdates$1 (react-dom.development.js:21525)
    at interactiveUpdates (react-dom.development.js:2268)
    at dispatchInteractiveEvent (react-dom.development.js:5086)
</code>```

Anyone could help me figure out what went wrong?

答:
It should be

```<code>  doSignInWithEmailAndPassword = (email, password) => {
    this.auth.signInWithEmailAndPassword(email, password);
  };
</code>```

See the reference here: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html?authuser=0#signinwithemailandpassword

Body:
I want to use React Context to provide a firebase instance to my React Application. Firebase class that I wrote is as below:

import firebase from "firebase/app";
import "firebase/auth";

const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DB_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID
};

class Firebase {
  constructor() {
    firebase.initializeApp(firebaseConfig);
    this.auth = firebase.auth();
  }

  // *** AUTH API ***

  doCreateUserWithEmailAndPassword = (email, password) => {
    this.auth.createUserWithEmailAndPassword(email, password);
  };

  doSignInWithEmailAndPassword = (email, password) => {
    this.auth.doSignInWithEmailAndPassword(email, password);
  };

  doSignOut = () => this.auth.signOut();

  doPasswordReset = email => this.auth.sendPasswordResetEmail(email);

  doPasswordUpdate = password => this.auth.currentUser.updatePassword(password);
}

export default Firebase;

When I try to do sign in with Email and Password, I got the following error:

TypeError: this.auth.doSignInWithEmailAndPassword is not a function
    at Firebase.doSignInWithEmailAndPassword (firebase.js:27)
    at SignInFormBase.onSubmit (SignIn.jsx:26)
    at HTMLUnknownElement.callCallback (react-dom.development.js:147)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:196)
    at invokeGuardedCallback (react-dom.development.js:250)
    at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:265)
    at executeDispatch (react-dom.development.js:571)
    at executeDispatchesInOrder (react-dom.development.js:596)
    at executeDispatchesAndRelease (react-dom.development.js:695)
    at executeDispatchesAndReleaseTopLevel (react-dom.development.js:704)
    at forEachAccumulated (react-dom.development.js:676)
    at runEventsInBatch (react-dom.development.js:844)
    at runExtractedEventsInBatch (react-dom.development.js:852)
    at handleTopLevel (react-dom.development.js:5030)
    at batchedUpdates$1 (react-dom.development.js:21469)
    at batchedUpdates (react-dom.development.js:2247)
    at dispatchEvent (react-dom.development.js:5110)
    at react-dom.development.js:21526
    at Object.unstable_runWithPriority (scheduler.development.js:255)
    at interactiveUpdates$1 (react-dom.development.js:21525)
    at interactiveUpdates (react-dom.development.js:2268)
    at dispatchInteractiveEvent (react-dom.development.js:5086)

Anyone could help me figure out what went wrong?

Body:
It should be

  doSignInWithEmailAndPassword = (email, password) => {
    this.auth.signInWithEmailAndPassword(email, password);
  };

See the reference here: https://firebase.google.com/docs/reference/js/firebase.auth.Auth.html?authuser=0#signinwithemailandpassword


问:
how to use session ids for authentication purpose
I am using just session variables $_SESSION['user_id'] and $_SESSION['passwd'] to store the id and password of user once when he logs in.

I am just checking these two variables with database each time the user moves to a new php page for authentication. Actually I didnt know about session_id() .

I dont think what i am doing for authentication is the right way. I feel that there is something to be done with session_id for security stuff.

and one more doubt- can these session variables be easily hacked when I use the session variables by the way i mentioned

What should I do?

答:
For basic authentication your approach of storing the user id is fine.
However, you don't need to store the password while the user is authenticated.</p>


问:
CSS - Horizontally splitting a page in half
I'm trying to have a page divided in half, horizontally. I want to accomplish it just by HTML/CSS and I'd prefer not to use JS.
What am I doing wrong?

Thanks

CSS

```<code>#container {
min-height:100%;
}

#top_div {
height:50%;
width:100%;
background-color:#009900;
margin:auto;
text-align:center;
}

#bottom_div {
height:50%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}
</code>```

HTML

```<code><div id="container">

<div id="top_div">top</div>
<div id="bottom_div">bottom</div>

</div>
</code>```

答:
Viewport units! Yes, viewport units. Supported by all browsers since IE9, doesn't require you to set height: 100% to every parent container.

Adding the property height: 50vh; will simply size it to 50% of the viewport height.

.top {
  height: 50vh;
  background-color: tomato;
}

.bottom {
  height: 50vh;
  background-color: brown;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='top'></div>
<div class='bottom'></div></code>```

Body:
I'm trying to have a page divided in half, horizontally. I want to accomplish it just by HTML/CSS and I'd prefer not to use JS.
What am I doing wrong?

Thanks

CSS

#container {
min-height:100%;
}

#top_div {
height:50%;
width:100%;
background-color:#009900;
margin:auto;
text-align:center;
}

#bottom_div {
height:50%;
width:100%;
background-color:#990000;
margin:auto;
text-align:center;
color:#FFFFFF;
}

HTML

top

bottom

Body:
Viewport units! Yes, viewport units. Supported by all browsers since IE9, doesn't require you to set height: 100% to every parent container.

Adding the property height: 50vh; will simply size it to 50% of the viewport height.

.top {
  height: 50vh;
  background-color: tomato;
}

.bottom {
  height: 50vh;
  background-color: brown;
}

<div class='top'></div>
<div class='bottom'></div>


问:
How to save DB username and password Spring boot project
Where should I keep Database username, password and url, to keep safe and secure as I trying to create secure production environment for my Java project,
currently I am using application properties to save DB credential kindly suggest some good and secure way to keep DB credentials.

application.properties

```<code># This should be used only for credentials and other local-only config.
spring.datasource.url = jdbc:postgresql://localhost/database
spring.datasource.username = root
spring.datasource.password = root@123
</code>```

Where should I keep for secure and production Spring boot project

答:
As you are using Spring Boot, you may pass the Database connection parameters at the startup of the application.

E.g. java -jar your-spring-boot-app.jar -Dspring.datasource.url=jdbc:postgresql://localhost/database ...

You can also set them as system environment variable:

export SPRING_DATASOURCE_URL="jdbc:postgresql://localhost/database"
and then simply start your app as usual.

That way you only store the connection parameters on the server, where you actually use them and prevent accidentaly checking them into you code versioning system.

see https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

To increase security you could use the https://projects.spring.io/spring-vault/ or an external configuration server https://spring.io/projects/spring-cloud-config

Body:
Where should I keep Database username, password and url, to keep safe and secure as I trying to create secure production environment for my Java project,
currently I am using application properties to save DB credential kindly suggest some good and secure way to keep DB credentials.

application.properties

# This should be used only for credentials and other local-only config.
spring.datasource.url = jdbc:postgresql://localhost/database
spring.datasource.username = root
spring.datasource.password = root@123

Where should I keep for secure and production Spring boot project


问:
How to select a subset of rows from a subset of columns in pandas
Consider this is my pandas data frame

```<code>df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
                    'num_wings': [2, 0, 0, 0],
                    'num_specimen_seen': [10, 2, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])

>>> df
        num_legs  num_specimen_seen  num_wings
falcon         2                 10          2
dog            4                  2          0
spider         8                  1          0
fish           0                  8          0
</code>```

and these are the rows I need to select row_index=[1,3]. For a single column I can use this way

```<code>>>> df.num_wings[row_index]
dog     0
fish    0
</code>```

But I want to do this in a subset of columns and not the whole dataframe like this

```<code>df[['num_legs','num_wings']][row_index]
</code>```

which gives KeyError: '[1 3] not in index'. How can we select a subset of rows from a subset of columns in pandas dataframe?

答:
Use DataFrame.iloc with positions by columns by names with Index.get_indexer:

```<code>a = df.iloc[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
print (a)
      num_legs  num_wings
dog          4          0
fish         0          0
</code>```

If need fancy indexing convert values to numpy array:

```<code>#0.24+
a = df.to_numpy()[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
#pandas below
a = df.values[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
print (a)
[4 0]
</code>```

Body:
Consider this is my pandas data frame

df = pd.DataFrame({'num_legs': [2, 4, 8, 0],
                    'num_wings': [2, 0, 0, 0],
                    'num_specimen_seen': [10, 2, 1, 8]},
                   index=['falcon', 'dog', 'spider', 'fish'])

>>> df
        num_legs  num_specimen_seen  num_wings
falcon         2                 10          2
dog            4                  2          0
spider         8                  1          0
fish           0                  8          0

and these are the rows I need to select row_index=[1,3]. For a single column I can use this way

>>> df.num_wings[row_index]
dog     0
fish    0

But I want to do this in a subset of columns and not the whole dataframe like this

df[['num_legs','num_wings']][row_index]

which gives KeyError: '[1 3] not in index'. How can we select a subset of rows from a subset of columns in pandas dataframe?

Body:
Use DataFrame.iloc with positions by columns by names with Index.get_indexer:

a = df.iloc[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
print (a)
      num_legs  num_wings
dog          4          0
fish         0          0

If need fancy indexing convert values to numpy array:

#0.24+
a = df.to_numpy()[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
#pandas below
a = df.values[row_index, df.columns.get_indexer(['num_legs','num_wings'])]
print (a)
[4 0]


问:
The connection with the client was abnormally terminated during the network communication between the server and the client
The connection with the client was abnormally terminated during the network communication between the server and the client. What should I do in this situation? I do not know which exception to handle.</p>

答:
I would say that the information given is very minimal, but I would suggest you to check the followings to start with

Try pinging the client/server from each other and confirm network connectivity.

Is there a firewall causing network connection to disrupt, you may need to open some ports in that case.

Look into client and server log files - if at all they are there.

Did server process crashed? do ulimit -c unlimited before starting the process.

Did client process crashed? do ulimit -c unlimited before starting the process.

Try doing the connect/send/receive in try-catch blocks, and put proper prints in catch block. There can be a broken pipe exception.

I would say check the buffer size that you are sending or receiving, both client and server should be able to handle the size.

In case you find core files in #2 or #3, load the core and see where it is crashing, it will give you the best hint.

If you are on Linux, try digging out information from system logs - e.g. /var/log/messages etc., if not on Linux find equivalent files.

I can provide more details once the incidence is clear, e.g. what you are trying to send, is it happening every time or some of the times? What is the message printed in catch block?


问:
How to increase hit area of Android button without scaling background?
I have a button with a custom drawable.

```<code><Button
    android:layout_width="22dip"
    android:layout_height="23dip"
    android:background="@drawable/triangle" />
</code>```

The drawable is a triangle with transparent background.

```<code>|\
| \
|__\
</code>```

I find this button hard to tap. First, it's relatively small. Second, the transparent pixels are not tappable. I would like to keep the drawable the same size, but make the hit area a square shape twice the size of the triangle.

```<code>_____________
|            |
|    |\      |
|    | \     |
|    |__\    |
|____________|
</code>```

答:
I think the correct answer should be using ImageButton instead of Button.
Set the triangle drawable as the "src" of the ImageButton, and set the size (layout_width & layout_height) as you want for easier touch and set the ScaleType to center to retain the triangle size.</p>

Body:
I have a button with a custom drawable.

<Button
    android:layout_width="22dip"
    android:layout_height="23dip"
    android:background="@drawable/triangle" />

The drawable is a triangle with transparent background.

|\
| \
|__\

I find this button hard to tap. First, it's relatively small. Second, the transparent pixels are not tappable. I would like to keep the drawable the same size, but make the hit area a square shape twice the size of the triangle.

_____________
|            |
|    |\      |
|    | \     |
|    |__\    |
|____________|


问:
Does tensorflow.data.experimental.CsvDataset read from the file over and over?
I am struggling with long training times with tf.data.Dataset, and am beginning to wonder if reading the CSV file may be a bottleneck. Does tensorflow.data.experimental.CsvDataset read from the file over and over?

I consider trying to first import the whole dataset and put it in a numpy array, and then create a new TF Dataset from tensors. But such a change will take time, and I don't want to waste time if SO could have told me beforehand that it makes no difference.

答: I do not know exactly why I got so long training times with CsvDataset, but modifying my code to first import the data to a numpy array and then import it using tf.data.Dataset.from_tensor_slices made the training about 10-100 times faster. One more, prehaps relevant, change that followed by this, was that the dataset was no longer nested throughout the handling. In the old version, each batch was a tuple of column tensors, whereas in the new version, each batch is simply a tensor. (Further speedups may be achieved by removing transforms tailored to the nested structure, which are now applied to one tensor only.)


问:
How to move a button Pyside2
I don't know why but i can't move a button using Pyside2.

I named a button Lina and i tried to move it using :

```<code>self.__ButtonLina.move(400,400)
</code>```

but it doesn't work, maybe i place this line in the wrong place in the code ?

Here is the code: (Lina's button is in the last tab)

```<code># -*- coding: utf-8 -*-

import sys
from PySide2 import QtCore, QtGui
from PySide2.QtWidgets import *
from PySide2.QtGui import *

# orange Continental rgb(255, 128, 0)

class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self,parent)
        # Les champs
        self.__champTexteNomAuteur = QLineEdit("")
        self.__champTextePrenomAuteur = QLineEdit("")
        self.__champDateNaissanceAuteur = QDateEdit()
        self.__champDateNaissanceAuteur.setCalendarPopup(True)
        self.__champTexteTitreLivre = QLineEdit("")
        self.__champDatePublication = QDateEdit()
        self.__champDatePublication.setCalendarPopup(True)
        self.__ButtonLina = QPushButton("Lina")
        self.__ButtonLina.setMaximumWidth(145)
        self.__ButtonLina.move(400,400)#------<----here is the problem
        self.__ButtonLina.setStyleSheet("background-color: rgb(255, 128, 0);")
        # Les widgets
        self.__widgetAuteur = QWidget()
        self.__widgetLivre = QWidget()
        self.__widget1 = QWidget()
        self.__widget2 = QWidget()
        self.__Tools = QWidget()
        self.__widget1.setStyleSheet("background-color: black;");
        # Les layouts des onglets

        self.__layoutTools = QFormLayout()
        self.__layoutTools.addRow(self.__ButtonLina)
        self.__Tools.setLayout(self.__layoutTools)

        self.__layoutAuteur = QFormLayout()
        self.__widgetAuteur.setLayout(self.__layoutAuteur)
        # La boîte à onglets
        self.__tabWidget = QTabWidget()
        self.__tabWidget.addTab(self.__widgetAuteur, "                  Single Simulation                   ")
        self.__tabWidget.addTab(self.__widgetLivre, "                  Batch Simulation                   ")
        self.__tabWidget.addTab(self.__widget1, "            Vehicule Simulation Tool                ")
        self.__tabWidget.addTab(self.__widget2, "                     Simulation                     ")
        self.__tabWidget.addTab(self.__Tools, "                       Tools                        ")
        # Le layout final
        self.__mainLayout = QVBoxLayout()
        self.__mainLayout.addWidget(self.__tabWidget)
        self.setLayout(self.__mainLayout)
        self.resize(1200,800)
        self.setWindowTitle('VSS Vehicule Simulation Suite')
        self.setStyleSheet("color: black;"
                        "background-color: black");
app = QApplication(sys.argv)
dialog = Dialog()
dialog.exec_()
</code>```

if you have any idea it could be cool !

答:
The layouts are used to manage the position and size of the widgets that it handles, in your case the position of the __ButtonLina is handled by __layoutTools, therefore the position you set manually is not applied. So if you want to establish a fixed position you should not use a layout.

In this case the solution is to remove the layout and set __ButtonLina to __Tools as parent of __ButtonLina to __Tools

# ...
self.__widget1.setStyleSheet("background-color: black;");

# Set as parent of__ButtonLina to __Tools
# so that the position of __ButtonLina is relative to __Tools
self.__ButtonLina.setParent(self.__Tools)

# remove layout
# Les layouts des onglets
# self.__layoutTools = QFormLayout()
# self.__layoutTools.addRow(self.__ButtonLina)
# self.__ButtonLina.clicked.connect(Lina)
# self.__Tools.setLayout(self.__layoutTools)

self.__layoutAuteur = QFormLayout()
# ...
```

Title: How to move a button Pyside2

Body:
I don't know why but i can't move a button using Pyside2.

I named a button Lina and i tried to move it using :

self.__ButtonLina.move(400,400)

but it doesn't work, maybe i place this line in the wrong place in the code ?

Here is the code: (Lina's button is in the last tab)

# -*- coding: utf-8 -*-

import sys
from PySide2 import QtCore, QtGui
from PySide2.QtWidgets import *
from PySide2.QtGui import *

# orange Continental rgb(255, 128, 0)

class Dialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self,parent)
        # Les champs
        self.__champTexteNomAuteur = QLineEdit("")
        self.__champTextePrenomAuteur = QLineEdit("")
        self.__champDateNaissanceAuteur = QDateEdit()
        self.__champDateNaissanceAuteur.setCalendarPopup(True)
        self.__champTexteTitreLivre = QLineEdit("")
        self.__champDatePublication = QDateEdit()
        self.__champDatePublication.setCalendarPopup(True)
        self.__ButtonLina = QPushButton("Lina")
        self.__ButtonLina.setMaximumWidth(145)
        self.__ButtonLina.move(400,400)#------<----here is the problem
        self.__ButtonLina.setStyleSheet("background-color: rgb(255, 128, 0);")
        # Les widgets
        self.__widgetAuteur = QWidget()
        self.__widgetLivre = QWidget()
        self.__widget1 = QWidget()
        self.__widget2 = QWidget()
        self.__Tools = QWidget()
        self.__widget1.setStyleSheet("background-color: black;");
        # Les layouts des onglets

        self.__layoutTools = QFormLayout()
        self.__layoutTools.addRow(self.__ButtonLina)
        self.__Tools.setLayout(self.__layoutTools)

        self.__layoutAuteur = QFormLayout()
        self.__widgetAuteur.setLayout(self.__layoutAuteur)
        # La boîte à onglets
        self.__tabWidget = QTabWidget()
        self.__tabWidget.addTab(self.__widgetAuteur, "                  Single Simulation                   ")
        self.__tabWidget.addTab(self.__widgetLivre, "                  Batch Simulation                   ")
        self.__tabWidget.addTab(self.__widget1, "            Vehicule Simulation Tool                ")
        self.__tabWidget.addTab(self.__widget2, "                     Simulation                     ")
        self.__tabWidget.addTab(self.__Tools, "                       Tools                        ")
        # Le layout final
        self.__mainLayout = QVBoxLayout()
        self.__mainLayout.addWidget(self.__tabWidget)
        self.setLayout(self.__mainLayout)
        self.resize(1200,800)
        self.setWindowTitle('VSS Vehicule Simulation Suite')
        self.setStyleSheet("color: black;"
                        "background-color: black");
app = QApplication(sys.argv)
dialog = Dialog()
dialog.exec_()

if you have any idea it could be cool !


问:
Understanding problem Doctrine 2 ORM Query Builder in Symfony 4
I hope there are a few helpful and prefer German Symfony experts. For many years I have been working with PHP and now I tryed in a framework. I chose Symfony now because I like the components the most. The QueryBuilder and I stand on a war foot - I just do not understand it. Storing values works very well so far, though I doubt that I'm doing this in the sense of the framework. I'm really helpless. Currently  I managing it by chasing everything in raw format but I'm not really happy with it.

How I can implement the following with Doctrine?

```<code>use App\Entity\Questions;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class QuestionsController extends AbstractController
{
/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion()
{
    $entityManager = $this->getDoctrine()->getManager();

    $RAW_QUERY = 'SELECT COUNT(*) AS c FROM questions WHERE questToID = '.$_POST['u'].' AND  questFrom = '.$this->getUser()->getId().';';

    $statement = $entityManager->getConnection()->prepare($RAW_QUERY);
    $statement->execute();

    $total = $statement->fetchAll();

    if($total[0]['c'] >= 3)
    {
        return new Response('error|Du kannst der selben Person maximal drei Fragen stellen.');
    }
 [...]
</code>```

I have already tried to implement this, and many other things (no avail):
Count Rows in Doctrine QueryBuilder

Since I speak bad English, I very much hope that you understand me…

答:
so getting the value with $_POST['u'] is not recommended her you can either pass the value with the route an retrieve it as a parameter for the function:

```<code>/**
 * @Route("/addquestion/{u}", methods={"POST","HEAD"})
 */
public function addQuestion($u)
</code>```

or you can get it out from the request it self:

```<code>/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion(Request $request)
</code>```

if you want to use the query builder the best practice would be to create a repository for you entity and make you the query there:

```<code>namespace App\Repository;

use App\Entity\Questions;
use Doctrine\ORM\EntityRepository;

class QuestionsRepository extends EntityRepository
{
    public function findUserQuestions($user, $u)
    {
          $queryBuilder = $this->createQueryBuilder('c')
            ->where('c.questToID = :questToID')
            ->andWhere('c.questFrom = :questFrom')
            ->setParameters(['questToID'=>$u,'questFrom'=>$user]);
            return $queryBuilder->getQuery()->getResult();
    }
</code>```

and in you controller you can get the result:

```<code>$userQuestions = $this->getDoctrine()->getRepository(Questions::class)->findUserQuestions($this->getUser(), $u);

count($userQuestions);
</code>```

i hope this will be useful in your case and explain you a bit how its done in symfony

Body:
I hope there are a few helpful and prefer German Symfony experts. For many years I have been working with PHP and now I tryed in a framework. I chose Symfony now because I like the components the most. The QueryBuilder and I stand on a war foot - I just do not understand it. Storing values works very well so far, though I doubt that I'm doing this in the sense of the framework. I'm really helpless. Currently  I managing it by chasing everything in raw format but I'm not really happy with it.

How I can implement the following with Doctrine?

use App\Entity\Questions;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;

class QuestionsController extends AbstractController
{
/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion()
{
    $entityManager = $this->getDoctrine()->getManager();

    $RAW_QUERY = 'SELECT COUNT(*) AS c FROM questions WHERE questToID = '.$_POST['u'].' AND  questFrom = '.$this->getUser()->getId().';';

    $statement = $entityManager->getConnection()->prepare($RAW_QUERY);
    $statement->execute();

    $total = $statement->fetchAll();

    if($total[0]['c'] >= 3)
    {
        return new Response('error|Du kannst der selben Person maximal drei Fragen stellen.');
    }
 [...]

I have already tried to implement this, and many other things (no avail):
Count Rows in Doctrine QueryBuilder

Since I speak bad English, I very much hope that you understand me…

Body:
so getting the value with $_POST['u'] is not recommended her you can either pass the value with the route an retrieve it as a parameter for the function:

/**
 * @Route("/addquestion/{u}", methods={"POST","HEAD"})
 */
public function addQuestion($u)

or you can get it out from the request it self:

/**
 * @Route("/addquestion", methods={"POST","HEAD"})
 */
public function addQuestion(Request $request)

if you want to use the query builder the best practice would be to create a repository for you entity and make you the query there:

namespace App\Repository;

use App\Entity\Questions;
use Doctrine\ORM\EntityRepository;

class QuestionsRepository extends EntityRepository
{
    public function findUserQuestions($user, $u)
    {
          $queryBuilder = $this->createQueryBuilder('c')
            ->where('c.questToID = :questToID')
            ->andWhere('c.questFrom = :questFrom')
            ->setParameters(['questToID'=>$u,'questFrom'=>$user]);
            return $queryBuilder->getQuery()->getResult();
    }

and in you controller you can get the result:

$userQuestions = $this->getDoctrine()->getRepository(Questions::class)->findUserQuestions($this->getUser(), $u);

count($userQuestions);

i hope this will be useful in your case and explain you a bit how its done in symfony


问:
Introducing FOREIGN KEY constraint 'FK_Product_User_UserId' on table 'Product' may cause cycles or multiple cascade paths
i cannot create database with ef core
error : Introducing FOREIGN KEY constraint 'FK_Product_User_UserId' on table 'Product' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

this is my product class

```<code>   {
       public Product()
       {
       }

       public Guid UserId { get; set; }
       public Guid CategoryId { get; set; }
       public string Name { get; set; }
       public string Description { get; set; }
       public string PhotoPath { get; set; }
       public decimal Price { get; set; }

       public Category Category { get; set; }
       public User User { get; set; }
   }
</code>```

and
this is my user class

```<code>    {
        public User()
        {
            Payments = new HashSet<Payment>();
            Categories = new HashSet<Category>();
            Products = new HashSet<Product>();
        }

        public string Username { get; set; }
        public Guid Password { get; set; }

        public ICollection<Payment> Payments { get; set; }
        public ICollection<Category> Categories { get; set; }
        public ICollection<Product> Products { get; set; }
    }
</code>```

its mapping class

```<code>    {
        public ProductMap()
        {
        }

        public void Configure(EntityTypeBuilder<Product> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.UserId).IsRequired();
            builder.Property(x => x.CreatedDate).IsRequired();
            builder.Property(x => x.Description).HasMaxLength(500);
            builder.Property(x => x.IsActive).IsRequired();
            builder.Property(x => x.Name).HasMaxLength(500).IsRequired();
            builder.Property(x => x.PhotoPath).HasMaxLength(4000);
            builder.Property(x => x.Price).HasColumnType("decimal(10,3)").IsRequired();

            builder.HasOne(x => x.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
            builder.HasOne(x => x.User).WithMany(x => x.Products).HasForeignKey(x => x.UserId);

        }
    }
</code>```

and i cannot create database cause error like this posts title.
what can i do?
Thanks.

答:
You are saying that each user has many Categories and each Category has many Products so you have to remove this line from the User class since it causing cycle path

```<code>public ICollection<Product> Products { get; set; }
</code>```

And also fix the last line of the Configure method:

```<code>builder.HasOne(x => x.User).WithMany(x => x.Categories).HasForeignKey(x => x.UserId);
</code>```

Body:
i cannot create database with ef core
error : Introducing FOREIGN KEY constraint 'FK_Product_User_UserId' on table 'Product' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

this is my product class

   {
       public Product()
       {
       }

       public Guid UserId { get; set; }
       public Guid CategoryId { get; set; }
       public string Name { get; set; }
       public string Description { get; set; }
       public string PhotoPath { get; set; }
       public decimal Price { get; set; }

       public Category Category { get; set; }
       public User User { get; set; }
   }

and
this is my user class

    {
        public User()
        {
            Payments = new HashSet<Payment>();
            Categories = new HashSet<Category>();
            Products = new HashSet<Product>();
        }

        public string Username { get; set; }
        public Guid Password { get; set; }

        public ICollection<Payment> Payments { get; set; }
        public ICollection<Category> Categories { get; set; }
        public ICollection<Product> Products { get; set; }
    }

its mapping class

    {
        public ProductMap()
        {
        }

        public void Configure(EntityTypeBuilder<Product> builder)
        {
            builder.HasKey(x => x.Id);
            builder.Property(x => x.UserId).IsRequired();
            builder.Property(x => x.CreatedDate).IsRequired();
            builder.Property(x => x.Description).HasMaxLength(500);
            builder.Property(x => x.IsActive).IsRequired();
            builder.Property(x => x.Name).HasMaxLength(500).IsRequired();
            builder.Property(x => x.PhotoPath).HasMaxLength(4000);
            builder.Property(x => x.Price).HasColumnType("decimal(10,3)").IsRequired();

            builder.HasOne(x => x.Category).WithMany(x => x.Products).HasForeignKey(x => x.CategoryId);
            builder.HasOne(x => x.User).WithMany(x => x.Products).HasForeignKey(x => x.UserId);

        }
    }

and i cannot create database cause error like this posts title.
what can i do?
Thanks.

Body:
You are saying that each user has many Categories and each Category has many Products so you have to remove this line from the User class since it causing cycle path

public ICollection<Product> Products { get; set; }

And also fix the last line of the Configure method:

builder.HasOne(x => x.User).WithMany(x => x.Categories).HasForeignKey(x => x.UserId);


问:
Sorting in stackbar and/or cross table with TOP 10 and "Other"
I made a cross table and an stackbar, with a Top 10 rankging and a group over 10, withe the following expression:

```<code>If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,[Countries],"Other") as [Countries]
</code>```

This works very fine in both results. But now I have the problem, that "Other" should be shown after the TOP 10 result and at the end of the stackbar. At the moment I have only the possiblity to sort it by Country Name or Balance.

Do you have an answer for my question?

Kind regards,

Kai

Tibco Spotfire Analyst 7.14.0

```<code>If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,[Countries],"Other") as [Countries]
</code>```

I need the correct ranking: 1-10 and then "Other" for the last stack and row.

答:
I have encountered a problem like this in the past. I found that adding a leading space to the country name 'cheats' the sort order.</p>

```<code>If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,Concatenate(" ",[Countries]),"Other") as [Countries]
</code>```

Body:
I made a cross table and an stackbar, with a Top 10 rankging and a group over 10, withe the following expression:

If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,[Countries],"Other") as [Countries]

This works very fine in both results. But now I have the problem, that "Other" should be shown after the TOP 10 result and at the end of the stackbar. At the moment I have only the possiblity to sort it by Country Name or Balance.

Do you have an answer for my question?

Kind regards,

Kai

Tibco Spotfire Analyst 7.14.0

If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,[Countries],"Other") as [Countries]

I need the correct ranking: 1-10 and then "Other" for the last stack and row.

Body:
I have encountered a problem like this in the past. I found that adding a leading space to the country name 'cheats' the sort order.

If(DenseRank(Sum([Balance]) OVER ([Countries]),"desc")<=10,Concatenate(" ",[Countries]),"Other") as [Countries]


问:
Oracle INSTR replacement in SQLite
I'm currently porting part of an application from an Oracle to a SQLite backend (Java, using plain JDBC). One Oracle-specific feature often being used is the INSTR function with three arguments:

INSTR(<string>, <search-string>, <position>)

This function searches within a string for a search string starting from a certain position. The third parameter can either be positive or negative. If it's negative, the search works backwards starting at the end of the string.

This function isn't available in SQLite and the best I could come up with is an alternative by nesting some other functions:

If <position> is positive:

LENGTH(<string>) - LENGTH(SUBSTR(SUBSTR(<string>,
  <position>), STRPOS(SUBSTR(<string>, <position>),
  <search-string>) + 1))

If <position> is negative (in our case -1 is the only negative value being used):

LENGTH(<string>) - LENGTH(REPLACE(<string>,
  RTRIM(<string>, REPLACE(<string>, <search-string>,
  '')), ''))

This seems to be giving the desired result, but you can see why I'm not really in favor of this approach. Certainly because in the original syntax the INSTR is used a lot and is being nested as well. It becomes a disaster for maintenance afterwards.

Is there a more elegant approach or could I be missing some other native solution for what seems to be a rather trivial task?

答:
Actually, SQLite does support an INSTR function.  But, it does not have a third parameter, which means, it always searches from the very beginning of the string.

But, we can workaround this by passing a substring to INSTR, and then offsetting the position found by adding the amount of the offset of the substring.

So, as an example, Oracle's call:

```<code>INSTR('catsondogsonhats', 'on', 7)
</code>```

which would return 11, would become:

```<code>INSTR(SUBSTR('catsondogsonhats', 7), 'on') + 6
</code>```

Title: Oracle INSTR replacement in SQLite

Body:
Actually, SQLite does support an INSTR function.  But, it does not have a third parameter, which means, it always searches from the very beginning of the string.

But, we can workaround this by passing a substring to INSTR, and then offsetting the position found by adding the amount of the offset of the substring.

So, as an example, Oracle's call:

INSTR('catsondogsonhats', 'on', 7)

which would return 11, would become:

INSTR(SUBSTR('catsondogsonhats', 7), 'on') + 6


问:
How to write very small text in HTML
I would like to have a font smaller than an Arial 9px text.

I've tried to find other font name but I did not succeed to get a very small text. Is there a way to achieve this easily using css ?

EDIT :
I can't go under 9px using Arial
I have tried font-size, small, transform, scale, other fonts... everything as I am an experienced web developper.

答:
If adding css styles don't work then maybe it has something to do with your browser auto adjustment of the font size.

Try this to stop auto adjustment of font size:

```<code>* {
    -webkit-text-size-adjust: none; //For chrome browser
}
</code>```

Title: How to write very small text in HTML

Body:
If adding css styles don't work then maybe it has something to do with your browser auto adjustment of the font size.

Try this to stop auto adjustment of font size:

* {
    -webkit-text-size-adjust: none; //For chrome browser
}


问:
Camel: Process files, split and aggregate
I've got a situation on my hands where I need to read from a directory and process all XML files there. The files are then processed and split according to some rule which results in N new messages/files. I would like to aggregate all the new documents into an index file with one line per file. Once the batch has been processed I will call a webservice and tell it to fetch the index file.

The problem I'm facing is that Camel doesn't see the delivery of the files as one job and my aggregation gets called multiple times, resulting in multiple index files instead of one. I have tried using the Exchange.BATCH_SIZE property and multiplying it by Exchange.SPLIT_SIZE for the aggregration completionSize

Pseudo-Code:

```<code>          from("file://" + SOURCE_FOLDER)
             .threads(10)
             .convertBodyTo(Data.class)
             .process(myProcessor)
             .split(xpath(MAIN_NODE))
             .parallelProcessing()
             .to(MyRouter.ENDPOINT)
             .setProperty(TOTAL)
               .spel(String.format("%s * %s", Exchange.SPLIT_SIZE, FileRouter.NUM_FILES))
             .aggregate(constant(true), myAggregator)
....

</code>```

So the question is: How can I define the boundaries of the exchange / group it? I know that there will only be 1 file delivery at a time but how can I tell Camel that?

I have tried working with only 1 thread but it seems to me it has no effect on this matter.

I have the option of the delivery arriving as tar.gz - would that be easier? To me it seems I'd have the same issue.

```<code> from("file://" + SOURCE_FOLDER + "/tar.gz?consumer.delay=1000&noop=true")
                .streamCaching()
                .unmarshal()
                .gzip()
                .split(new TarSplitter())
                ....<SAME ISSUE>
</code>```

I'm using the Camel 3 Preview though I have tried with latest 2.x version as well.

Thanks in advance and best,

答:
When I understand you correctly, your problem is that you are not able to create an aggregated index per input file.

Well, the Camel Splitter EIP can be combined with an aggregation strategy.

If you do this, the Splitter re-aggregates all parts of a previously splitted message to a new aggregate.

```<code>// a Splitter with an AggregationStrategy
.split([yourSplitCriteria], new MyAggregationStrategy())
    // you can do whatever you want in here with the message parts
    // for example each splitted message part is sent to this bean
    .to("bean:PartProcessor")
    // end the split to re-aggregate the message parts
.end()
// here, after the split-ending you get the re-aggregated messages
</code>```

Body:
I've got a situation on my hands where I need to read from a directory and process all XML files there. The files are then processed and split according to some rule which results in N new messages/files. I would like to aggregate all the new documents into an index file with one line per file. Once the batch has been processed I will call a webservice and tell it to fetch the index file.

The problem I'm facing is that Camel doesn't see the delivery of the files as one job and my aggregation gets called multiple times, resulting in multiple index files instead of one. I have tried using the Exchange.BATCH_SIZE property and multiplying it by Exchange.SPLIT_SIZE for the aggregration completionSize

Pseudo-Code:

          from("file://" + SOURCE_FOLDER)
             .threads(10)
             .convertBodyTo(Data.class)
             .process(myProcessor)
             .split(xpath(MAIN_NODE))
             .parallelProcessing()
             .to(MyRouter.ENDPOINT)
             .setProperty(TOTAL)
               .spel(String.format("%s * %s", Exchange.SPLIT_SIZE, FileRouter.NUM_FILES))
             .aggregate(constant(true), myAggregator)
....

So the question is: How can I define the boundaries of the exchange / group it? I know that there will only be 1 file delivery at a time but how can I tell Camel that?

I have tried working with only 1 thread but it seems to me it has no effect on this matter.

I have the option of the delivery arriving as tar.gz - would that be easier? To me it seems I'd have the same issue.

 from("file://" + SOURCE_FOLDER + "/tar.gz?consumer.delay=1000&noop=true")
                .streamCaching()
                .unmarshal()
                .gzip()
                .split(new TarSplitter())
                ....<SAME ISSUE>

I'm using the Camel 3 Preview though I have tried with latest 2.x version as well.

Thanks in advance and best,

Body:
When I understand you correctly, your problem is that you are not able to create an aggregated index per input file.

Well, the Camel Splitter EIP can be combined with an aggregation strategy.

If you do this, the Splitter re-aggregates all parts of a previously splitted message to a new aggregate.

// a Splitter with an AggregationStrategy
.split([yourSplitCriteria], new MyAggregationStrategy())
    // you can do whatever you want in here with the message parts
    // for example each splitted message part is sent to this bean
    .to("bean:PartProcessor")
    // end the split to re-aggregate the message parts
.end()
// here, after the split-ending you get the re-aggregated messages


问:
Selenium TouchEvent does not work in device emulation
Need to use mobile device emulation on a desktop browser to automate testing.

If enable emulation via ChromeOptions (), the emulation of the touch screen does not work (the button responds to the cursor, etc.). That's why I use java.awt.Robot (F12 > Ctrl + Shift + M > iPad) to turn on device emulation. But touch doesn't work.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.touch.TouchActions;

//Set browser type and platform
DriverSettings.newSettings("https://staging.myev.com", DriverType.CHROME, EmulationType.MOBILE);
WebDriver driver = DriverSettings.getDriver();

driver.get("https://google.com");
WebElement element = driver.findElement(By.xpath("//a[@class='gb_x gb_Ub']"));
TouchActions touchActions = new TouchActions(driver);
touchActions.singleTap(element).perform();
```

The button is not pressed and there are no errors - "Process finished with exit code 0"

Maybe there is another way to enable mobile emulation or use TouchActions?

答:
As per specifications from the official website: http://chromedriver.chromium.org/mobile-emulation, to correctly use the mobile emulation with ChromeDriver you should use:

```<code>Map<String, String> mobileEmulation = new HashMap<>();

mobileEmulation.put("deviceName", "Nexus 5");

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);

WebDriver driver = new ChromeDriver(chromeOptions)
</code>```

*The emulated devices can also be made custom, for this you will need to declare a custom session storage with the stored custom devices properties. This needs to be done because if you dont declare a chrome session storage specifically, each time you will start a new test session, there will be created a temporary session with default settings.

Here you will find a useful lis of commands to start up the chromedriver:
https://peter.sh/experiments/chromium-command-line-switches/#user-data-dir

Body:
Need to use mobile device emulation on a desktop browser to automate testing.

If enable emulation via ChromeOptions (), the emulation of the touch screen does not work (the button responds to the cursor, etc.). That's why I use java.awt.Robot (F12 > Ctrl + Shift + M > iPad) to turn on device emulation. But touch doesn't work.

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.touch.TouchActions;

//Set browser type and platform
DriverSettings.newSettings("https://staging.myev.com", DriverType.CHROME, EmulationType.MOBILE);
WebDriver driver = DriverSettings.getDriver();

driver.get("https://google.com");
WebElement element = driver.findElement(By.xpath("//a[@class='gb_x gb_Ub']"));
TouchActions touchActions = new TouchActions(driver);
touchActions.singleTap(element).perform();

The button is not pressed and there are no errors - "Process finished with exit code 0"

Maybe there is another way to enable mobile emulation or use TouchActions?

Body:
As per specifications from the official website: http://chromedriver.chromium.org/mobile-emulation, to correctly use the mobile emulation with ChromeDriver you should use:

Map<String, String> mobileEmulation = new HashMap<>();

mobileEmulation.put("deviceName", "Nexus 5");

ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.setExperimentalOption("mobileEmulation", mobileEmulation);

WebDriver driver = new ChromeDriver(chromeOptions)

*The emulated devices can also be made custom, for this you will need to declare a custom session storage with the stored custom devices properties. This needs to be done because if you dont declare a chrome session storage specifically, each time you will start a new test session, there will be created a temporary session with default settings.

Here you will find a useful lis of commands to start up the chromedriver:
https://peter.sh/experiments/chromium-command-line-switches/#user-data-dir


问:
Print function on jQuery SimpleModal
I'm using the Basic Modal Dialog from here http://www.ericmmartin.com/projects/simplemodal-demos/ and inside of this dialog, I have an image which I would like to add a Print button below it.

I've tried using jqPrint but it doesn't work. Is there something that I've missed?

My popup dialog

```<code><div id="popup_name" class="popup_block">
<div class="map"><img src="images/map.png"></div>
<br><a href="#" id="print"><img src="images/print.png"></a>
</div>
</code>```

jqPrint

```<code>$("#print").click( function() {
$('.map').jqprint();
});
</script>
</code>```

答:
IMP: jqprint() is a plug-in, add proper reference to your file.
Try putting your click function in document.ready, it should work fine then.

```<code>$(document).ready(function () {
$("#print").click( function() {
$('.map').jqprint();
});
});
</code>```

I have tested this, it works fine.

Title: Print function on jQuery SimpleModal

Body:
I'm using the Basic Modal Dialog from here http://www.ericmmartin.com/projects/simplemodal-demos/ and inside of this dialog, I have an image which I would like to add a Print button below it.

I've tried using jqPrint but it doesn't work. Is there something that I've missed?

My popup dialog

jqPrint

$("#print").click( function() {
$('.map').jqprint();
});
</script>

Body:
IMP: jqprint() is a plug-in, add proper reference to your file.
Try putting your click function in document.ready, it should work fine then.

$(document).ready(function () {
$("#print").click( function() {
$('.map').jqprint();
});
});

I have tested this, it works fine.


问:
How to send a ref to a function as a parameter in React Native?
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

```<code>render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent = component} />
    </View>
  )
}
</code>```

Then, I've created another function to access the state of my custom component. I wrote it like this.

```<code>myFunction = (ref) => {
  ref.setState({ myState: myValue })
}
</code>```

Then, I called that function like this.

```<code>this.myFunction(this.myComponent)
</code>```

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

```<code>this.myComponent.setState({ myState: myValue })
</code>```

Can you please help me to solve this problem?

答:
To use setState, just use your component's context (this keyword). The context also have your ref in it, so you don't need to pass it as an argument if you are inside one component(not forwarding down to children)

```<code>myFunction = (event) => {
 this.myComponent  // -> points to your ref, DOM element
 this.setState() // use your setState like that
}
</code>```

Don't forget to bind your context in parent component if you want to pass the handler to the child components. Refer to this useful topic

EDIT: Based on your comment, I guess you want to update the parent state by calling a handler in some other component. To do that, you need to create a handler in your parent component, bind the context and pass it as a property to the child component. Next up, you need to assign this handler in your child component. You cannot pass a context with setState method via argument or ref, this is just not how it works in javascript and in react.

Example:

```<code>// ParentComponent.js
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 1,
    };
    this.onChangeHandler = this.onChangeHandler.bind(this);
  }

  onChangeHandler(event) {
    this.setState({
      value: someNewValue // will update state on parent component
    })
  }

  render() {
    return (
      <View>
        <SomeComponent>{this.state.value}</SomeComponent>
        <ChildrenComponent onChangeHandler={this.onChangeHandler} />
      </View>
    );
  }
}

// ChildrenComponent.js
const ChildrenComponent = (props) => (
  <View>
    <Button
      onPress={props.onChangeHandler}
      title="click me to change parent state"
    />
  </View>
);
</code>```

Hopefully, this is what you need :)

Body:
I've imported a custom component into my screen and rendered it in the render() function. Then, created a ref to that custom component. Now, the render() function simply looks like this.

render() {
  return (
    <View>
      <MyComponent ref={component => this.myComponent = component} />
    </View>
  )
}

Then, I've created another function to access the state of my custom component. I wrote it like this.

myFunction = (ref) => {
  ref.setState({ myState: myValue })
}

Then, I called that function like this.

this.myFunction(this.myComponent)

But, it does not work. It gives me the following error.

null is not an object (evaluating 'ref.setState')

Actually what I need this myFunction to do is,

this.myComponent.setState({ myState: myValue })

Can you please help me to solve this problem?

Body:
To use setState, just use your component's context (this keyword). The context also have your ref in it, so you don't need to pass it as an argument if you are inside one component(not forwarding down to children)

myFunction = (event) => {
 this.myComponent  // -> points to your ref, DOM element
 this.setState() // use your setState like that
}

Don't forget to bind your context in parent component if you want to pass the handler to the child components. Refer to this useful topic

EDIT: Based on your comment, I guess you want to update the parent state by calling a handler in some other component. To do that, you need to create a handler in your parent component, bind the context and pass it as a property to the child component. Next up, you need to assign this handler in your child component. You cannot pass a context with setState method via argument or ref, this is just not how it works in javascript and in react.

Example:

// ParentComponent.js
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 1,
    };
    this.onChangeHandler = this.onChangeHandler.bind(this);
  }

  onChangeHandler(event) {
    this.setState({
      value: someNewValue // will update state on parent component
    })
  }

  render() {
    return (
      <View>
        <SomeComponent>{this.state.value}</SomeComponent>
        <ChildrenComponent onChangeHandler={this.onChangeHandler} />
      </View>
    );
  }
}

// ChildrenComponent.js
const ChildrenComponent = (props) => (
  <View>
    <Button
      onPress={props.onChangeHandler}
      title="click me to change parent state"
    />
  </View>
);

Hopefully, this is what you need :)