问:
if else condition not evaluating in react component
So I'm making a todo list app and to provide alternate colors to new todo items as they are added in the todolist i have used the if else statement in React component but i think it is not evaluating.

Below are the two classes from my css file that i'm using -->

```<code> .bgColorItem1{
    background-color: white;
}

.bgColorItem2{
    background-color:grey;
}
</code>```

Below is the component that accepts arguments item(todo item that will be added to the list) and key(index passed as key) from todolist -->

```<code>  import React from 'react';
    import './App.css';

    const TodoItem=({item,key})=>{
        let settingClass="";

    // *****so the problem is here in the if condn that's not putting settingClass as bgColorItem1*****
        if(key%2===0){
            settingClass="bgColorItem1";
        }else{
        settingClass="bgColorItem2";
    }

    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}</div>
}

export default TodoItem;
</code>```

So what i expect from this code that key which was index in todolist component passed to todo here above should return 0 for even so that settingClass can have alternate values and hence provide alternate colors.But that is not the case.

答:
Your TodoItem component shouldn't have to care about the key prop, but rather a boolean (or a string if you have more than 2 styles) prop like alternateStyle:

```<code>const TodoItem=({item,alternateStyle})=>{
    return <div className={
                 `boxSpace centerAligning ${alternateStyle ? 'bgColorItem2' :
                 'bgColorItem1'}`
           }>
             {item}
           </div>
</code>```

Then you can set the value you need to alternateStyle in the parent component:

```<code><div>
   {items.map((item, index) => <TodoItem item={item} alternateStyle={index % 2 !== 0} />)}
</div>

</code>```

Body:
So I'm making a todo list app and to provide alternate colors to new todo items as they are added in the todolist i have used the if else statement in React component but i think it is not evaluating.

Below are the two classes from my css file that i'm using -->

 .bgColorItem1{
    background-color: white;
}

.bgColorItem2{
    background-color:grey;
}

Below is the component that accepts arguments item(todo item that will be added to the list) and key(index passed as key) from todolist -->

  import React from 'react';
    import './App.css';

    const TodoItem=({item,key})=>{
        let settingClass="";

    // *****so the problem is here in the if condn that's not putting settingClass as bgColorItem1*****
        if(key%2===0){
            settingClass="bgColorItem1";
        }else{
        settingClass="bgColorItem2";
    }

    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}

}

export default TodoItem;

So what i expect from this code that key which was index in todolist component passed to todo here above should return 0 for even so that settingClass can have alternate values and hence provide alternate colors.But that is not the case.

Body:
Your TodoItem component shouldn't have to care about the key prop, but rather a boolean (or a string if you have more than 2 styles) prop like alternateStyle:

const TodoItem=({item,alternateStyle})=>{
    return <div className={
                 `boxSpace centerAligning ${alternateStyle ? 'bgColorItem2' :
                 'bgColorItem1'}`
           }>
             {item}
           </div>

Then you can set the value you need to alternateStyle in the parent component:

<div>
   {items.map((item, index) => <TodoItem item={item} alternateStyle={index % 2 !== 0} />)}
</div>


来源: stackexchange

问:
Difference between the reference types of derived and base classes
Guys i want your help please.

We Have This Code:

```<code>class Program
{

    static void Main(string[] args)
    {
        Animal pig = new Pig();

        Pig pig2 = new Pig();

        List<Animal> Animals = new List<Animal>();
        Animals.Add(pig);
        Animals.Add(pig2);

        foreach(Animal a in Animals)
        {
            Animal.AnimalSound();
        }
    }
}

class Animal
{
    public virtual void AnimalSound()
    {
        Console.WriteLine("AnimalSound");
    }
}

class Pig : Animal
{
    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}
</code>```

My Question is as i instantiate variables pig and pig2 what's the difference Animal pig = new Pig(); and Pig pig2 = new Pig();

Why not declare them both as ReferenceType Pig since Pig is as always Animal????

答:
The difference is, name is not accessible when you do this Animal pig = new Pig();, but name is accessible in this case Pig pig2 = new Pig();. You always inherit from base class because you want to use some ready made behavior from parent, and want to add some child specific behavior in child class. Pig is always an animal, but all animals are not Pig.

```<code>class Pig : Animal
{
    public string name;

    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Guys i want your help please.

We Have This Code:

class Program
{

    static void Main(string[] args)
    {
        Animal pig = new Pig();

        Pig pig2 = new Pig();

        List<Animal> Animals = new List<Animal>();
        Animals.Add(pig);
        Animals.Add(pig2);

        foreach(Animal a in Animals)
        {
            Animal.AnimalSound();
        }
    }
}

class Animal
{
    public virtual void AnimalSound()
    {
        Console.WriteLine("AnimalSound");
    }
}

class Pig : Animal
{
    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}

My Question is as i instantiate variables pig and pig2 what's the difference Animal pig = new Pig(); and Pig pig2 = new Pig();

Why not declare them both as ReferenceType Pig since Pig is as always Animal????

Body:
The difference is, name is not accessible when you do this Animal pig = new Pig();, but name is accessible in this case Pig pig2 = new Pig();. You always inherit from base class because you want to use some ready made behavior from parent, and want to add some child specific behavior in child class. Pig is always an animal, but all animals are not Pig.

class Pig : Animal
{
    public string name;

    public override void AnimalSound()
    {
        Console.WriteLine("wee wee!");
    }
}


问:
Sample code to load & validate an XML file & schema in Saxon under Java
This is for a tool in our system that will verify that it can load an XML file with Saxon, and list any problems. So I want to have Saxon load the file and throw an exception if it can't fully parse it. This test has an option to be given a schema file so it validates against the schema if it exists.

This is for our Java version so need to use the Java API. I tried to port over the C# Validate example (there is no Java validate that I could find) but the API is quite a bit different.

And if possible, get a list of errors it found parsing.

答:
In the download file you should find samples/java/ee/SchemaValidatorExample.java which uses the JAXP interface, and also java/he/S9APIExamples.java which uses the s9api API and includes use cases SchemaA and SchemaB.

These could do with updating, none of them takes advantage of the new interface SchemaValidator.setInvalidityHandler() which allows you either to supply an instance of InvalidityReportGeneratorEE which gives you a Saxon-generated report of all invalidities found, or your own InvalidityReportGenerator or InvalidityHandler to produce your own customized reporting. I suggest you take a tour of the Javadoc for documentation of what these do.

These are very much geared to custom reporting of the invalidities found. Throwing an exception if the file isn't valid is much simpler.


答:
First of all, don't use key's value since it is internal. Secondly, you can achieve like this

```<code>{items.map((item, index) => <TodoItem item={item} index={index} />)}
</code>```

In TodoItem

const TodoItem=({ item, index })=>{
        let settingClass=index % 2 === 0 ? 'bgColorItem1' : 'bgColorItem2';
    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}

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

<p>However, you don't need react to do this, just use css, in your css</p>

```.boxSpace:nth-child(odd) {
  background: red;
}

.boxSpace:nth-child(even) {
  background: blue;
}
```

Title: if else condition not evaluating in react component

Body:
First of all, don't use key's value since it is internal. Secondly, you can achieve like this

{items.map((item, index) => <TodoItem item={item} index={index} />)}

In TodoItem

const TodoItem=({ item, index })=>{
        let settingClass=index % 2 === 0 ? 'bgColorItem1' : 'bgColorItem2';
    return <div className={`boxSpace centerAligning ${settingClass}`}>{item}</div>
}

However, you don't need react to do this, just use css, in your css

.boxSpace:nth-child(odd) {
  background: red;
}

.boxSpace:nth-child(even) {
  background: blue;
}


问:
Xampp control panel is not showing
My Xampp control panel is not showing in the desktop (Windows 10), but can only up the servers through the shortcut (minimized option in the task bar).

As follows:

I have close the application without stopping the servers, will that be the case of this matter?

答:
This doesn't involve modifying, uninstalling, editing, or anything overtly complicated, just hovering:

Start XAMPP.

Hover mouse over XAMPP Window Tab until Window preview pane pops up over the tab.

Right Click over preview pane and click maximize.

Drag down from the sides to resize. Clicking the minimize tab will cause the window to disappear, and you will have to repeat the first three steps.  Drag down from the top to pop the window out of maximized size.

ContentLicense: CC BY-SA 3.0

Title: Xampp control panel is not showing


问:
Mongo query to find documents where any of the field's elements match any of the query param elements
I've scoured the docs and google. Maybe I just need help formulating the question.

I have a field that stores an array of values. We'll call it "tags" for simplicity. I want to be able to search for all documents that match ANY of the multiple tags I search on. Put another way, I want to find all records that are tagged with at least one (not necessarily all) of these tags. Here's an example.

Documents :

```<code>{name: "My Thing 1", tags: ["cool", "important", "anothertag"]},
{name: "My Thing 2", tags: ["cool"]},
{name: "My Thing 3", tags: ["cool", "important"]}
{name: "My Thing 4", tags: ["important", "anothertag"]}
{name: "My Thing 5", tags: []}
{name: "My Thing 6", tags: ["anothertag"]}
</code>```

Query: ["important", "cool"]

Result: documents 1-4 (not 5-6)

答: See comment by whoami. $in does the trick.</p>

Body:
I've scoured the docs and google. Maybe I just need help formulating the question.

I have a field that stores an array of values. We'll call it "tags" for simplicity. I want to be able to search for all documents that match ANY of the multiple tags I search on. Put another way, I want to find all records that are tagged with at least one (not necessarily all) of these tags. Here's an example.

Documents :

{name: "My Thing 1", tags: ["cool", "important", "anothertag"]},
{name: "My Thing 2", tags: ["cool"]},
{name: "My Thing 3", tags: ["cool", "important"]}
{name: "My Thing 4", tags: ["important", "anothertag"]}
{name: "My Thing 5", tags: []}
{name: "My Thing 6", tags: ["anothertag"]}

Query: ["important", "cool"]

Result: documents 1-4 (not 5-6)


问:
Two versions of same npm package in Node application
I'm working on a CLI tool in NodeJS that uses another NodeJs package that we develop, which is an SDK.

The thing is, we just published a V2 version of that SDK, and we want to offer the CLI user a legacy mode, so they can use either the first or second version of our SDK, like so:

```<code>$ cli do-stuff
#execute sdk v2
</code>```

Or

```<code>$ LEGACY_MODE='on' cli do-stuff
#execute sdk v1
</code>```

My problem is that I did not found any clean way to use two versions of the same dependency in my CLI.
I tried to use npm-install-version package. It works well on my local environment, but after publishing my cli and doing npm install -g my-cli, it doesn't work anymore, because it creates a node_modules folder in the current folder, instead of the /usr/local/lib/node_modules/my-cli folder.
I also tried multidep, and I have kind of the same issue.

For now, my package.json do not contain at all my sdk, but I would like to have something like :

```<code>"dependencies": {
  "my-sdk": "2.0.0"
  "my-sdk-legacy": "1.0.0"
}
</code>```

Or

```<code>"dependencies": {
  "my-sdk": ["2.0.0", "1.0.0"]
}
</code>```

I haven't found anything else yet. I'm thinking about publishing the first version of my sdk package with another name, like "my-sdk-legacy", but I would like to avoid that if possible.

Any solution for that ?

答:
Do npm i alias@npm:package_name@package_version

Inside package.json use “alias”: “npm:package_name@package_version”

Body:
I'm working on a CLI tool in NodeJS that uses another NodeJs package that we develop, which is an SDK.

The thing is, we just published a V2 version of that SDK, and we want to offer the CLI user a legacy mode, so they can use either the first or second version of our SDK, like so:

$ cli do-stuff
#execute sdk v2

Or

$ LEGACY_MODE='on' cli do-stuff
#execute sdk v1

My problem is that I did not found any clean way to use two versions of the same dependency in my CLI.
I tried to use npm-install-version package. It works well on my local environment, but after publishing my cli and doing npm install -g my-cli, it doesn't work anymore, because it creates a node_modules folder in the current folder, instead of the /usr/local/lib/node_modules/my-cli folder.
I also tried multidep, and I have kind of the same issue.

For now, my package.json do not contain at all my sdk, but I would like to have something like :

"dependencies": {
  "my-sdk": "2.0.0"
  "my-sdk-legacy": "1.0.0"
}

Or

"dependencies": {
  "my-sdk": ["2.0.0", "1.0.0"]
}

I haven't found anything else yet. I'm thinking about publishing the first version of my sdk package with another name, like "my-sdk-legacy", but I would like to avoid that if possible.

Any solution for that ?


问:
How to programmatically disable page scrolling with jQuery
Using jQuery, I would like to disable scrolling of the body:

My idea is to:

Set body{ overflow: hidden;}

Capture the current scrollTop();/scrollLeft()

Bind to the body scroll event, set scrollTop/scrollLeft to the captured value.

Is there a better way?

Update:

Please see my example, and a reason why, at http://jsbin.com/ikuma4/2/edit

I am aware someone will be thinking "why does he not just use position: fixed on the panel?".

Please do not suggest this as I have other reasons.

答: Can't you just set the body height to 100% and overflow hidden? See http://jsbin.com/ikuma4/13/edit</p>


问:
Using variable in Angular (8) partial class name
I want to create dynamic class names like

```<code><div [ngClass]='color-42'>
<div [ngClass]='color-43'>
</code>```

through using

or variants thereof

but all I get is matching variants of

```<code>Parser Error: Got interpolation ({{}}) where expression was expected at column ...
</code>```

答:
You should not use curly brackets with input attributes.

You should either use one of them:

```<code>[ngClass]="'color-' + variable"
</code>```

Or:

```<code>class="color-{{variable}}"
</code>```

Or:

```<code>[ngClass]="{'color-' + variable: someExpression}"
</code>```

Official docs: https://angular.io/api/common/NgClass#description

Body:
I want to create dynamic class names like

through using

or variants thereof

but all I get is matching variants of

Parser Error: Got interpolation ({{}}) where expression was expected at column ...

Body:
You should not use curly brackets with input attributes.

You should either use one of them:

[ngClass]="'color-' + variable"

Or:

class="color-{{variable}}"

Or:

[ngClass]="{'color-' + variable: someExpression}"

Official docs: https://angular.io/api/common/NgClass#description


问:
how to access wamp server in a system to other system using wifi-hotspot?
I want to access my wamp server from other laptop using wifi hotspot. How can i do it ? . Kindly help me . Thank you for the answer in advance .</p>

答: Click on "Put Online" like this:

Body: Click on "Put Online" like this:


问:
NameError at /test_submit/ name 'item_name' is not defined in Django
Hello Iam new in django and i try to same my form input to database without form.py just from views but iam getting name error please help me to short out the problem

This is my html form code

```<code><form class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin" method="post" action="/test_submit/" id='myForm'>
    {% csrf_token %}

    <div class="w3-row-padding">
      <div class="w3-half">
         <p><label>Item Name</label></p>
         <p><input class="w3-input" type="text" name="item_name" required></p>
      </div>
      <div class="w3-half">
         <p><label>Brand Name</label></p>
         <p><input class="w3-input" type="text" name="brand_name" required></p>
      </div>
    </div>

    <div class="w3-row-padding">
     <div class="w3-half">
      <p><label>Item Size</label></p>
      <p><select class="w3-select" name="item_size" required>
      <option value="" disabled selected>Select Size</option>
      <option value="5k-7k">5k-7k</option>
      <option value="7k-10k">7k-10k</option>
      <option value="11-13">11-13</option>
      <option value="1-3">1-3</option>
      <option value="4-5">4-5</option>
      <option value="6-9">6-9</option>
      <option value="10-11">10-11</option>
      </select></p>
    </div>

    <div class="w3-half">
    <p><label>Item Color</label></p>
     <p><input class="w3-input" type="text" name="item_color" required></p>
   </div>

    <div class="w3-half">
      <p><label>Item Unit</label></p>
     <p><select class="w3-select" name="item_unit" required>
     <option value="" disabled selected>Select Unit</option>
     <option value="Number">Number</option>
     <option value="Number">Number</option>
     <option value="Boxes">Boxes</option>
     </select></p>
    </div>

    <div class="w3-half">
      <p><label>Quantity</label></p>
      <p><input class="w3-input" type="number" name="item_quantity" placeholder="0" required></p>
    </div>

  </div>

  <div class="w3-row-padding">
    <div class="w3-half">
      <p><label>Purchase Price</label></p>
      <p><input class="w3-input" type="number" name="purchase_price" placeholder="0.0" required></p>
    </div>
    <div class="w3-half">
      <p><label>Selling Price</label></p>
      <p><input class="w3-input" type="number" name="selling_price" placeholder="0.0" required></p>
    </div>
    <div class="w3-half">
      <p><label>MRP</label></p>
      <p><input class="w3-input" type="number" name="mrp" placeholder="0.0" required></p>
    </div>
    <div class="w3-half">
      <p><label>Date</label></p>
      <p><input class="w3-input" type="date" name="date" required></p>
    </div>

  </div>
    <div class="w3-bar">
      <button class="w3-btn w3-blue w3-round">Save</button>
      <button class="w3-btn w3-blue w3-round">Save & Generate Barcode</button>
      <button class="w3-btn w3-gray w3-round" onclick="clearFun()">Cancle</button>
    </div>
    <p></p>
</form>
</code>```

This is my views.py code

```<code> from django.shortcuts import render
from .models import Items_Tb
from django.contrib import messages

# Create your views here.
def items_views(request):
    return render(request,'itemapp/items.html')

def items_submit_views(request):
    print('----------------test my submit form-----------------')
    itemname = request.POST[item_name]
    brandname = request.POST[brand_name]
    itemsize = request.POST[item_size]
    itemcolor = request.POST[item_color]
    itemunit = request.POST[item_unit]
    itemquantity = request.POST[item_quantity]
    purchaseprice = request.POST[purchase_price]
    sellingprice = request.POST[selling_price]
    mrp = request.POST[mrp]
    item_date = request.POST[date]

    item_info = Items_Tb(item_name=itemname,brand_name=brandname,item_size=itemsize,
    item_color=itemcolor,item_unit=itemunit,item_quantity=itemquantity,purchase_price=purchaseprice,
    selling_price=sellingprice,mrp=mrp,item_date=item_date)

    item_info.save()
    messages.success(request,'Items save successfully!')

    return render(request,'itemapp/items.html')
</code>```

This is models.py Code

```<code>from django.db import models

# Create your models here.
class Items_Tb(models.Model):
    item_name = models.CharField(max_length=64)
    brand_name = models.CharField(max_length=64)
    item_size =  models.CharField(max_length=64)
    item_color = models.CharField(max_length=64)
    item_unit =  models.CharField(max_length=64)
    item_quantity = models.IntegerField()
    purchase_price = models.FloatField()
    selling_price =  models.FloatField()
    mrp = models.FloatField()
    item_date = models.DateField()

    def __str__(self):#show tabel name on admin
        return self.item_name
</code>```

This is my Urls.py Code

```<code>from django.contrib import admin
from django.urls import path
from dashboardapp import views as d_views
from itemapp import views as i_views
from userapp import views as u_views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('dashboard/', d_views.dash_views),
    path('test/', d_views.test_views),
    path('items/', i_views.items_views, name='items'),
    path('test_submit/', i_views.items_submit_views, name='test_submit'),
    path('users/', u_views.users_views),
]
</code>```

when i sumbit my form iam getting this error
bellowenter image description here

答:
item_name should be in quotes:

```<code>itemname = request.POST["item_name"]
</code>```

Body:
Hello Iam new in django and i try to same my form input to database without form.py just from views but iam getting name error please help me to short out the problem

This is my html form code

<form class="w3-container w3-card-4 w3-light-grey w3-text-black w3-margin" method="post" action="/test_submit/" id='myForm'>
    {% csrf_token %}

Item Name

<input class="w3-input" type="text" name="item_name" required>

Brand Name

<input class="w3-input" type="text" name="brand_name" required>

Item Size

<select class="w3-select" name="item_size" required>
      <option value="" disabled selected>Select Size</option>
      <option value="5k-7k">5k-7k</option>
      <option value="7k-10k">7k-10k</option>
      <option value="11-13">11-13</option>
      <option value="1-3">1-3</option>
      <option value="4-5">4-5</option>
      <option value="6-9">6-9</option>
      <option value="10-11">10-11</option>
      </select>

Item Color

<input class="w3-input" type="text" name="item_color" required>

Item Unit

<select class="w3-select" name="item_unit" required>
     <option value="" disabled selected>Select Unit</option>
     <option value="Number">Number</option>
     <option value="Number">Number</option>
     <option value="Boxes">Boxes</option>
     </select>

Quantity

<input class="w3-input" type="number" name="item_quantity" placeholder="0" required>

Purchase Price

<input class="w3-input" type="number" name="purchase_price" placeholder="0.0" required>

Selling Price

<input class="w3-input" type="number" name="selling_price" placeholder="0.0" required>

MRP

<input class="w3-input" type="number" name="mrp" placeholder="0.0" required>

Date

<input class="w3-input" type="date" name="date" required>

      <button class="w3-btn w3-blue w3-round">Save</button>
      <button class="w3-btn w3-blue w3-round">Save & Generate Barcode</button>
      <button class="w3-btn w3-gray w3-round" onclick="clearFun()">Cancle</button>

</form>

This is my views.py code

 from django.shortcuts import render
from .models import Items_Tb
from django.contrib import messages

# Create your views here.
def items_views(request):
    return render(request,'itemapp/items.html')

def items_submit_views(request):
    print('----------------test my submit form-----------------')
    itemname = request.POST[item_name]
    brandname = request.POST[brand_name]
    itemsize = request.POST[item_size]
    itemcolor = request.POST[item_color]
    itemunit = request.POST[item_unit]
    itemquantity = request.POST[item_quantity]
    purchaseprice = request.POST[purchase_price]
    sellingprice = request.POST[selling_price]
    mrp = request.POST[mrp]
    item_date = request.POST[date]

    item_info = Items_Tb(item_name=itemname,brand_name=brandname,item_size=itemsize,
    item_color=itemcolor,item_unit=itemunit,item_quantity=itemquantity,purchase_price=purchaseprice,
    selling_price=sellingprice,mrp=mrp,item_date=item_date)

    item_info.save()
    messages.success(request,'Items save successfully!')

    return render(request,'itemapp/items.html')

This is models.py Code

from django.db import models

# Create your models here.
class Items_Tb(models.Model):
    item_name = models.CharField(max_length=64)
    brand_name = models.CharField(max_length=64)
    item_size =  models.CharField(max_length=64)
    item_color = models.CharField(max_length=64)
    item_unit =  models.CharField(max_length=64)
    item_quantity = models.IntegerField()
    purchase_price = models.FloatField()
    selling_price =  models.FloatField()
    mrp = models.FloatField()
    item_date = models.DateField()

    def __str__(self):#show tabel name on admin
        return self.item_name

This is my Urls.py Code

from django.contrib import admin
from django.urls import path
from dashboardapp import views as d_views
from itemapp import views as i_views
from userapp import views as u_views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('dashboard/', d_views.dash_views),
    path('test/', d_views.test_views),
    path('items/', i_views.items_views, name='items'),
    path('test_submit/', i_views.items_submit_views, name='test_submit'),
    path('users/', u_views.users_views),
]

when i sumbit my form iam getting this error
bellowenter image description here

Body:
item_name should be in quotes:

itemname = request.POST["item_name"]


问:
How to get Firebase idToken from AuthResult?
Firebase are providing AuthResult on the callback for user sign in using startActivityForSignInWithProvider (in my case the provider is apple on Android platform).
I can't seem to fetch the idToken from it in a proper (synchronous) way.

So far I found two options, both aren't satisfying:

Option 1: casting

```<code>((OAuthCredential)authResult.getCredential()).getIdToken()
</code>```

This works but I'm not sure if it's a safe cast. Plis, I'm thinking, if Firebase would have wanted us to fetch the idToken this way, they would have added it to AuthCredential.

Option 2: fetching it from the user

```<code>authResult.getUser().getIdToken(false).addOnCompleteListener { ... }
</code>```

This seems to be a safe solution, but it's an async method. It doesn't seem to make sense to performing another async method, after the user just manually signed in (this is what i'm doing for an existing user).

答: You should be using the asynchronous listener.  The reason for this is because the ID token will expire every hour, and your listener is how you know the very moment when the token has been refreshed, so you can start using that new token right away.</p>

Body:
Firebase are providing AuthResult on the callback for user sign in using startActivityForSignInWithProvider (in my case the provider is apple on Android platform).
I can't seem to fetch the idToken from it in a proper (synchronous) way.

So far I found two options, both aren't satisfying:

Option 1: casting

((OAuthCredential)authResult.getCredential()).getIdToken()

This works but I'm not sure if it's a safe cast. Plis, I'm thinking, if Firebase would have wanted us to fetch the idToken this way, they would have added it to AuthCredential.

Option 2: fetching it from the user

authResult.getUser().getIdToken(false).addOnCompleteListener { ... }

This seems to be a safe solution, but it's an async method. It doesn't seem to make sense to performing another async method, after the user just manually signed in (this is what i'm doing for an existing user).


问:
Java String to Date Parse
I am trying convert String to Date but getting this error.

```<code>java.text.ParseException: Unparseable date: "Wed Feb 16 20:04:17 EET 2022"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.mycompany.facebookproject.OpenFace.main(OpenFace.java:55)
</code>```

My code is:

```<code>String val= "Wed Feb 16 20:04:19 EET 2022";
expiry=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(val);
</code>```

答:
I guess its a typo:</p>

```<code>String dateSt= "Wed Feb 16 20:04:19 EET 2022";
        Date parse = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateSt);
        System.out.println(parse);
</code>```

Title: Java String to Date Parse

Body:
I am trying convert String to Date but getting this error.

java.text.ParseException: Unparseable date: "Wed Feb 16 20:04:17 EET 2022"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.mycompany.facebookproject.OpenFace.main(OpenFace.java:55)

My code is:

String val= "Wed Feb 16 20:04:19 EET 2022";
expiry=new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(val);

Body:
I guess its a typo:

String dateSt= "Wed Feb 16 20:04:19 EET 2022";
        Date parse = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(dateSt);
        System.out.println(parse);


问:
Django Field Error cannot resolve keyword 'is_staff
```<code>Cannot resolve keyword 'is_staff' into field. Choices are: dob, experience, id,user, user_id
</code>```

I get the above error when adding trainer as a Foreign Key to the Subscription model and then accessing any record for Subscription model from admin panel

```<code>class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)
</code>```

答:
You're trying to access an attribute is_staff, which does not exist on the TrainerProfile model. is_staff is an attribute of User, which you reference in your TrainerProfile model's user field.

In order to access this property, you need to "traverse" the relationship from Subscription -> TrainerProfile -> User. Django allows you to do this by using double-underscore notation, like this: some_fk_field__fk_field_attribute.

In your example, you need to change your limit_choices_to option on trainer to traverse the relationship to the user, like so:

```<code>class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, <b>limit_choices_to={'user__is_staff': True}</b>)
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)
</code>```

Body:
Cannot resolve keyword 'is_staff' into field. Choices are: dob, experience, id,user, user_id

I get the above error when adding trainer as a Foreign Key to the Subscription model and then accessing any record for Subscription model from admin panel

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)

Body:
You're trying to access an attribute is_staff, which does not exist on the TrainerProfile model. is_staff is an attribute of User, which you reference in your TrainerProfile model's user field.

In order to access this property, you need to "traverse" the relationship from Subscription -> TrainerProfile -> User. Django allows you to do this by using double-underscore notation, like this: some_fk_field__fk_field_attribute.

In your example, you need to change your limit_choices_to option on trainer to traverse the relationship to the user, like so:

class Subscription(models.Model):
    client = models.OneToOneField(ClientProfile, on_delete=models.CASCADE)
    trainer = models.ForeignKey(TrainerProfile, null=True, blank=True,
        on_delete=models.SET_NULL, limit_choices_to={'user__is_staff': True})
    plan = models.ForeignKey(Plan, on_delete=models.CASCADE)
    transaction = models.OneToOneField(PaymentHistory, on_delete=models.CASCADE)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

class TrainerProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    dob = models.DateField(null=True)
    experience = models.PositiveIntegerField(default=0)


问:
Unity and Generics
how do i register and resolve a generic object/interface in Unity?  I'm trying to stay away from the config file.

I'm looking for something like

IEnterpriseClient<IInterface1> to resolve to EnterpriseClient<IInterface1>

The class signature is

```<code>class EnterpriseClient<T> : IEnterpriseClient<T> where T : class
</code>```

Thanks!

答:
Look at this question for XML configuration: Unity 2.0 registering generic types via XML

and http://davidhayden.com/blog/dave/archive/2008/03/25/UnityDependencyInjectionOpenGenericTypes.aspx for code configuration.

Title: Unity and Generics

Body:
how do i register and resolve a generic object/interface in Unity?  I'm trying to stay away from the config file.

I'm looking for something like

IEnterpriseClient<IInterface1> to resolve to EnterpriseClient<IInterface1>

The class signature is

class EnterpriseClient<T> : IEnterpriseClient<T> where T : class

Thanks!


问:
how to do a dot product with x1,…,xn and print then in a specific way
I have a basic question. I am trying to make some constraints for an optimization software. could you please help me to do this:

I have a couple of vectors of numbers for example :(1 4 2 3 4 1) , (1 1 2 6 8 9)

I want the first one multiply by x1 the second by x2 and ... . I want the out put be like this:

s.t. a1: 1*x1+4*x2+2*x3+3*x4+4*x5+1*x6>=0;

s.t. a2: 1*x1+1*x2+2*x3+6*x4+8*x5+9*x6>=0;

so I want the term s.t. ai: to be printed in front of i-th constraint and >=0; at the end of each constraint.

Note that I have the vectors of number but not x1,x2,...,xn. Since my vectors are large it is hard for me to make the list of x1,x2,...,xn.

here is what I did :

```<code>y="1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
xx=list(y.split(" "))
x=[]
for i in range(1,42):     #I know it is not correct to define (x1,...,x42) like this, but
          x=xi                #what is the correct way?

def dot(x, y):
    return sum(x_i*y_i for x_i, y_i in zip(x, xx))

print("s.t. a:" dot(x, y) ">=0;")
</code>```

my problem is I can not define x=(x1,...,x42) correctly. and in print I can't print ai

答:
This:

```<code># create vectors:
vector = [1, 4, 2]

# initialize empty equation:
equation = ''

# loop over every point in the vector:
for index, point in enumerate(vector):

    # update the equation for each point in the vector:
    equation += str(point) + '*x_' + str(index+1) + ' + '

# remove the trailing ' + ' from equation:
equation = equation[0:-3]

# add head and tail to equation:
equation = 's.t. a1: ' + equation + ' >=0;'

# print result:
print(equation)
</code>```

Will output this:

```<code>s.t. a1: 1*x_1 + 4*x_2 + 2*x_3 >=0;
</code>```

You can change the vector as needed.

Body:
I have a basic question. I am trying to make some constraints for an optimization software. could you please help me to do this:

I have a couple of vectors of numbers for example :(1 4 2 3 4 1) , (1 1 2 6 8 9)

I want the first one multiply by x1 the second by x2 and ... . I want the out put be like this:

s.t. a1: 1*x1+4*x2+2*x3+3*x4+4*x5+1*x6>=0;

s.t. a2: 1*x1+1*x2+2*x3+6*x4+8*x5+9*x6>=0;

so I want the term s.t. ai: to be printed in front of i-th constraint and >=0; at the end of each constraint.

Note that I have the vectors of number but not x1,x2,...,xn. Since my vectors are large it is hard for me to make the list of x1,x2,...,xn.

here is what I did :

y="1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1"
xx=list(y.split(" "))
x=[]
for i in range(1,42):     #I know it is not correct to define (x1,...,x42) like this, but
          x=xi                #what is the correct way?

def dot(x, y):
    return sum(x_i*y_i for x_i, y_i in zip(x, xx))

print("s.t. a:" dot(x, y) ">=0;")

my problem is I can not define x=(x1,...,x42) correctly. and in print I can't print ai

Body:
This:

# create vectors:
vector = [1, 4, 2]

# initialize empty equation:
equation = ''

# loop over every point in the vector:
for index, point in enumerate(vector):

    # update the equation for each point in the vector:
    equation += str(point) + '*x_' + str(index+1) + ' + '

# remove the trailing ' + ' from equation:
equation = equation[0:-3]

# add head and tail to equation:
equation = 's.t. a1: ' + equation + ' >=0;'

# print result:
print(equation)

Will output this:

s.t. a1: 1*x_1 + 4*x_2 + 2*x_3 >=0;

You can change the vector as needed.


问:
Multiple inheritance and "this" pointer being cast to common base class
Consider the following code:

```<code>class Base {
  //some code
};

class A : public virtual Base{
    //some code
};

class B : public virtual Base{
    //some code
};

class C:  public A, public B {
    //some code
};
</code>```

In other words we have multiple inheritance and all classes inherit from class Base. Now consider that the "this" pointer exists in code in classes A,B,C,Base. I know that in general we cannot assume that the "this" pointer value will be identical in all cases. But what it the "this" pointer is cast to the Base* class inside A,B,C whenever it is used. Is it correct to say that the casted pointer "this" after casting to the common Base* class will contain the same address inside A,B,C? Thanks

答:
But what it the "this" pointer is cast to the Base* class inside A,B,C whenever it is used

Note that there isn't even a need to cast (i.e. convert explicitly). A pointer to derived converts to base pointer implicitly.

Is it correct to say that the casted pointer "this" after casting to the common Base* class will contain the same value inside A,B,C?

A pointer doesn't "contain values" other than the value of the address of an object. The object whose address is stored is the pointed object. A pointer to a base points to the base sub object.

Body:
Consider the following code:

class Base {
  //some code
};

class A : public virtual Base{
    //some code
};

class B : public virtual Base{
    //some code
};

class C:  public A, public B {
    //some code
};

In other words we have multiple inheritance and all classes inherit from class Base. Now consider that the "this" pointer exists in code in classes A,B,C,Base. I know that in general we cannot assume that the "this" pointer value will be identical in all cases. But what it the "this" pointer is cast to the Base* class inside A,B,C whenever it is used. Is it correct to say that the casted pointer "this" after casting to the common Base* class will contain the same address inside A,B,C? Thanks


问:
Filtering google sheets column to show cells ending with one of several values
I need to filter column A to see which cells end with values like .com/,.org/,.co.uk/, etc

Instead of filtering by "text ends with" dozens or hundreds of times, is there a way to combine all of these into one custom formula?

答:
try this custom formula for:

filter view

conditional formatting

data validation

```<code>=REGEXMATCH(A1, ".com/$|.org/$|.co.uk/$")
</code>```

Body:
try this custom formula for:

filter view

conditional formatting

data validation

=REGEXMATCH(A1, ".com/$|.org/$|.co.uk/$")


问:
How to let PHP to create subdomain automatically for each user?
How do I create subdomain like http://user.mywebsite.example? Do I have to access .htaccess somehow? Is it actually simply possible to create it via pure PHP code or I need to use some external script-server side language?

To those who answered: Well, then, should I ask my hosting if they provide some sort of DNS access?

答:
We setup wildcard DNS like they explained above. So the a record is *.yourname.example

Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.

We use the following code:

```<code>$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);
</code>```

This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.

This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).

We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.

OwnerDisplayName: Skuta

LastEditorDisplayName: Skuta

Body:
We setup wildcard DNS like they explained above. So the a record is *.yourname.example

Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.

We use the following code:

$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);

This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.

This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).

We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.

OwnerDisplayName: Gordon


问:
How can I get sqlite working on a shared hosting server?
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

```
-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
<b>ImportError: No module named _sqlite3</b>
```

I think I have everything set up right as far as the directory structure.

```
-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

```

And finally the contents of the sqlite3 directory:

```
-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

```

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !

答:
None of the files listed in the sqlite folder is the _sqlite3.pyd Python shared library. Are you sure you compiled it when compiling Python? What does the build log say? I think there's a configure flag that needs to be passed.

Alternatively, just install pysqlite

Body:
I'm trying to run a python script using python 2.6.4. The hosting company has 2.4 installed so I compiled my own 2.6.4 on a similar server and then moved the files over into ~/opt/python. that part seems to be working fine.

anyhow, when I run the script below, I am getting ImportError: No module named _sqlite3 and I'm not sure what to do to fix this.

Most online threads mention that sqlite / sqlite3 is included in python 2.6 - so I'm not sure why this isn't working.

-jailshell-3.2$ ./pyDropboxValues.py

Traceback (most recent call last):
  File "./pyDropboxValues.py", line 21, in
    import sqlite3
  File "/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py", line 24, in
    from dbapi2 import *
  File "/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in
    from _sqlite3 import *
ImportError: No module named _sqlite3

I think I have everything set up right as far as the directory structure.

-jailshell-3.2$ find `pwd` -type d

/home/myAccount/opt
/home/myAccount/opt/bin
/home/myAccount/opt/include
/home/myAccount/opt/include/python2.6
/home/myAccount/opt/lib
/home/myAccount/opt/lib/python2.6
/home/myAccount/opt/lib/python2.6/distutils
/home/myAccount/opt/lib/python2.6/distutils/command
/home/myAccount/opt/lib/python2.6/distutils/tests
/home/myAccount/opt/lib/python2.6/compiler
/home/myAccount/opt/lib/python2.6/test
/home/myAccount/opt/lib/python2.6/test/decimaltestdata
/home/myAccount/opt/lib/python2.6/config
/home/myAccount/opt/lib/python2.6/json
/home/myAccount/opt/lib/python2.6/json/tests
/home/myAccount/opt/lib/python2.6/email
/home/myAccount/opt/lib/python2.6/email/test
/home/myAccount/opt/lib/python2.6/email/test/data
/home/myAccount/opt/lib/python2.6/email/mime
/home/myAccount/opt/lib/python2.6/lib2to3
/home/myAccount/opt/lib/python2.6/lib2to3/pgen2
/home/myAccount/opt/lib/python2.6/lib2to3/fixes
/home/myAccount/opt/lib/python2.6/lib2to3/tests
/home/myAccount/opt/lib/python2.6/xml
/home/myAccount/opt/lib/python2.6/xml/parsers
/home/myAccount/opt/lib/python2.6/xml/sax
/home/myAccount/opt/lib/python2.6/xml/etree
/home/myAccount/opt/lib/python2.6/xml/dom
/home/myAccount/opt/lib/python2.6/site-packages
/home/myAccount/opt/lib/python2.6/logging
/home/myAccount/opt/lib/python2.6/lib-dynload
/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/test
/home/myAccount/opt/lib/python2.6/encodings
/home/myAccount/opt/lib/python2.6/wsgiref
/home/myAccount/opt/lib/python2.6/multiprocessing
/home/myAccount/opt/lib/python2.6/multiprocessing/dummy
/home/myAccount/opt/lib/python2.6/curses
/home/myAccount/opt/lib/python2.6/bsddb
/home/myAccount/opt/lib/python2.6/bsddb/test
/home/myAccount/opt/lib/python2.6/idlelib
/home/myAccount/opt/lib/python2.6/idlelib/Icons
/home/myAccount/opt/lib/python2.6/tmp
/home/myAccount/opt/lib/python2.6/lib-old
/home/myAccount/opt/lib/python2.6/lib-tk
/home/myAccount/opt/lib/python2.6/hotshot
/home/myAccount/opt/lib/python2.6/plat-linux2
/home/myAccount/opt/lib/python2.6/ctypes
/home/myAccount/opt/lib/python2.6/ctypes/test
/home/myAccount/opt/lib/python2.6/ctypes/macholib
/home/myAccount/opt/share
/home/myAccount/opt/share/man
/home/myAccount/opt/share/man/man1

And finally the contents of the sqlite3 directory:

-jailshell-3.2$ find `pwd`

/home/myAccount/opt/lib/python2.6/sqlite3
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.pyc
/home/myAccount/opt/lib/python2.6/sqlite3/dbapi2.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.pyo
/home/myAccount/opt/lib/python2.6/sqlite3/__init__.py
/home/myAccount/opt/lib/python2.6/sqlite3/dump.py

I feel like I need to add something into the sqlite3 directory - maybe sqlite3.so? But I don't know where to get that.

What am I doing wrong here? Please remember that I'm using a shared host so that means installing / compiling on another server and then copying the files over. Thanks! :)

Update
Just wanted to confirm that the answer from @samplebias did work out very well. I needed to have the dev package installed on the machine I was compiling from to get it to add in sqlite3.so and related files. Also found the link in the answer very helpful. Thanks @samplebias !


问:
sum values in sub array
this is how I store values to array

```<code>$array[$row['name']][] = $row['from'] - $row['to'];
</code>```

and here is result

```<code>Array
(
   [name1] => Array
    (
        [0] => 1
        [1] => 12
        [2] => 10
    )

)

Array
(
   [name2] => Array
    (
        [0] => 0.25
        [1] => 0.55
        [2] => 0.35
        [3] => 5
    )

)
</code>```

i need result like

```<code>echo $sum_of_first_array. "hours" .$name;
</code>```

or:

23 hours name1

6.15 hours name2

...

答:
You could run your values through array_sum using array_map

$array = array_map('array_sum', $array);

All in all, something like -

$rows = [
    ['name' => 'name1', 'from' => 4, 'to' => 3],
    ['name' => 'name1', 'from' => 32, 'to' => 20],
    ['name' => 'name1', 'from' => 999, 'to' => 989],
    ['name' => 'name2', 'from' => 10.25, 'to' => 10],
    ['name' => 'name2', 'from' => 10.55, 'to' => 10],
    ['name' => 'name2', 'from' => 10.35, 'to' => 10],
    ['name' => 'name2', 'from' => 5, 'to' => 0],
];
$array = [];
foreach ($rows as $row) {
    $array[$row['name']][] = $row['from'] - $row['to'];

}

print_r($array); // what you have so far

$array = array_map('array_sum', $array);

print_r($array); // what you want

```

<p>See https://www.tehplayground.com/paAkQ8riS5KwFSfP</p>

<p>Although a better solution would be to add these as you go, like</p>

<pre class="lang-php prettyprint-override"><code>
$array = [];
foreach ($rows as $row) {
    $array[$row['name']] += $row['from'] - $row['to'];

}

print_r($array);
</code>```

See https://www.tehplayground.com/kA2QDWUluJ53Ueia

Title: sum values in sub array

Body:
this is how I store values to array

$array[$row['name']][] = $row['from'] - $row['to'];

and here is result

Array
(
   [name1] => Array
    (
        [0] => 1
        [1] => 12
        [2] => 10
    )

)

Array
(
   [name2] => Array
    (
        [0] => 0.25
        [1] => 0.55
        [2] => 0.35
        [3] => 5
    )

)

i need result like

echo $sum_of_first_array. "hours" .$name;

or:

23 hours name1

6.15 hours name2

...

Body:
You could run your values through array_sum using array_map

$array = array_map('array_sum', $array);

All in all, something like -

$rows = [
    ['name' => 'name1', 'from' => 4, 'to' => 3],
    ['name' => 'name1', 'from' => 32, 'to' => 20],
    ['name' => 'name1', 'from' => 999, 'to' => 989],
    ['name' => 'name2', 'from' => 10.25, 'to' => 10],
    ['name' => 'name2', 'from' => 10.55, 'to' => 10],
    ['name' => 'name2', 'from' => 10.35, 'to' => 10],
    ['name' => 'name2', 'from' => 5, 'to' => 0],
];
$array = [];
foreach ($rows as $row) {
    $array[$row['name']][] = $row['from'] - $row['to'];

}

print_r($array); // what you have so far

$array = array_map('array_sum', $array);

print_r($array); // what you want

See https://www.tehplayground.com/paAkQ8riS5KwFSfP

Although a better solution would be to add these as you go, like

$array = [];
foreach ($rows as $row) {
    $array[$row['name']] += $row['from'] - $row['to'];

}

print_r($array);

See https://www.tehplayground.com/kA2QDWUluJ53Ueia


问:
Linear interpolation among columns in r
I am working with some temperature data where I have temperatures at certain depths e.g. 0.9m, 2.5m and 5m. I would like to interpolate this values so I obtain the temperature each meter, e.g. 1m, 2m and 3m. The original data looks like this:

```<code>df
# A tibble: 5 x 3
  date                d_0.9 d_2.5
  <dttm>              <dbl> <dbl>
1 2004-01-05 03:00:00  7     8
2 2004-01-05 04:00:00  7.5   9
3 2004-01-05 05:00:00  7     8
4 2004-01-05 06:00:00  6.92  NA
</code>```

What I would like to get is something like :

```<code>df_int
# A tibble: 5 x 5
  date                 d_0.9   d_1      d_2      d_2.5
  <dttm>              <dbl>   <dbl>     <dbl>    <dbl>
1 2004-01-05 03:00:00  7       7.0625   7.6875   8
2 2004-01-05 04:00:00  7.5     7.59375  8.53125  9
3 2004-01-05 05:00:00  7       7.0625   7.6875   8
4 2004-01-05 06:00:00  6.92    NA       NA       NA
</code>```

I have to do this for a very large data frame. Is there an efficient way of doing it?

Many thanks in advance

答:
One option is to convert the data to long format, use a join to add rows for the depths we want to interpolate at, and then use approx for the interpolation:

```<code>library(tidyverse)

# Data
df = tibble(date=seq(as.POSIXct("2004-01-05 03:00:00"),
                     as.POSIXct("2004-01-05 06:00:00"),
                     by="1 hour"),
            d_0.9 = c(7,7.5,7,6.92),
            d_2.5 = c(8,NA,8,NA),
            d_5.0 = c(10,10.5,9.4,NA))

# Create a data frame with all of the times and depths we want to interpolate at
depths = sort(unique(c(c(0.9, 2.5, 5), seq(ceiling(0.9), floor(5), 1))))
depths = crossing(date=unique(df$date), depth = depths)

# Convert data to long format, join to add interpolation depths, then interpolate
df.interp = df %>%
  gather(depth, value, -date) %>%
  mutate(depth = as.numeric(gsub("d_", "", depth))) %>%
  full_join(depths) %>%
  arrange(date, depth) %>%
  group_by(date) %>%
  mutate(value.interp = if(length(na.omit(value)) > 1) {
    approx(depth, value, xout=depth)$y
  } else {
    value
  })
</code>```

In the code above, the if statement is inclduded to prevent approx throwing an error when a given date has only one non-missing value.

```<code>df.interp
</code>```

```<code>                  date depth value value.interp
1  2004-01-05 03:00:00   0.9  7.00     7.000000
2  2004-01-05 03:00:00   1.0    NA     7.062500
3  2004-01-05 03:00:00   2.0    NA     7.687500
4  2004-01-05 03:00:00   2.5  8.00     8.000000
5  2004-01-05 03:00:00   3.0    NA     8.400000
6  2004-01-05 03:00:00   4.0    NA     9.200000
7  2004-01-05 03:00:00   5.0 10.00    10.000000
8  2004-01-05 04:00:00   0.9  7.50     7.500000
9  2004-01-05 04:00:00   1.0    NA     7.573171
10 2004-01-05 04:00:00   2.0    NA     8.304878
11 2004-01-05 04:00:00   2.5    NA     8.670732
12 2004-01-05 04:00:00   3.0    NA     9.036585
13 2004-01-05 04:00:00   4.0    NA     9.768293
14 2004-01-05 04:00:00   5.0 10.50    10.500000
15 2004-01-05 05:00:00   0.9  7.00     7.000000
16 2004-01-05 05:00:00   1.0    NA     7.062500
17 2004-01-05 05:00:00   2.0    NA     7.687500
18 2004-01-05 05:00:00   2.5  8.00     8.000000
19 2004-01-05 05:00:00   3.0    NA     8.280000
20 2004-01-05 05:00:00   4.0    NA     8.840000
21 2004-01-05 05:00:00   5.0  9.40     9.400000
22 2004-01-05 06:00:00   0.9  6.92     6.920000
23 2004-01-05 06:00:00   1.0    NA           NA
24 2004-01-05 06:00:00   2.0    NA           NA
25 2004-01-05 06:00:00   2.5    NA           NA
26 2004-01-05 06:00:00   3.0    NA           NA
27 2004-01-05 06:00:00   4.0    NA           NA
28 2004-01-05 06:00:00   5.0    NA           NA
</code>```

Title: Linear interpolation among columns in r

Body:
I am working with some temperature data where I have temperatures at certain depths e.g. 0.9m, 2.5m and 5m. I would like to interpolate this values so I obtain the temperature each meter, e.g. 1m, 2m and 3m. The original data looks like this:

df
# A tibble: 5 x 3
  date                d_0.9 d_2.5
  <dttm>              <dbl> <dbl>
1 2004-01-05 03:00:00  7     8
2 2004-01-05 04:00:00  7.5   9
3 2004-01-05 05:00:00  7     8
4 2004-01-05 06:00:00  6.92  NA

What I would like to get is something like :

df_int
# A tibble: 5 x 5
  date                 d_0.9   d_1      d_2      d_2.5
  <dttm>              <dbl>   <dbl>     <dbl>    <dbl>
1 2004-01-05 03:00:00  7       7.0625   7.6875   8
2 2004-01-05 04:00:00  7.5     7.59375  8.53125  9
3 2004-01-05 05:00:00  7       7.0625   7.6875   8
4 2004-01-05 06:00:00  6.92    NA       NA       NA

I have to do this for a very large data frame. Is there an efficient way of doing it?

Many thanks in advance

Body:
One option is to convert the data to long format, use a join to add rows for the depths we want to interpolate at, and then use approx for the interpolation:

library(tidyverse)

# Data
df = tibble(date=seq(as.POSIXct("2004-01-05 03:00:00"),
                     as.POSIXct("2004-01-05 06:00:00"),
                     by="1 hour"),
            d_0.9 = c(7,7.5,7,6.92),
            d_2.5 = c(8,NA,8,NA),
            d_5.0 = c(10,10.5,9.4,NA))

# Create a data frame with all of the times and depths we want to interpolate at
depths = sort(unique(c(c(0.9, 2.5, 5), seq(ceiling(0.9), floor(5), 1))))
depths = crossing(date=unique(df$date), depth = depths)

# Convert data to long format, join to add interpolation depths, then interpolate
df.interp = df %>%
  gather(depth, value, -date) %>%
  mutate(depth = as.numeric(gsub("d_", "", depth))) %>%
  full_join(depths) %>%
  arrange(date, depth) %>%
  group_by(date) %>%
  mutate(value.interp = if(length(na.omit(value)) > 1) {
    approx(depth, value, xout=depth)$y
  } else {
    value
  })

In the code above, the if statement is inclduded to prevent approx throwing an error when a given date has only one non-missing value.

df.interp

                  date depth value value.interp
1  2004-01-05 03:00:00   0.9  7.00     7.000000
2  2004-01-05 03:00:00   1.0    NA     7.062500
3  2004-01-05 03:00:00   2.0    NA     7.687500
4  2004-01-05 03:00:00   2.5  8.00     8.000000
5  2004-01-05 03:00:00   3.0    NA     8.400000
6  2004-01-05 03:00:00   4.0    NA     9.200000
7  2004-01-05 03:00:00   5.0 10.00    10.000000
8  2004-01-05 04:00:00   0.9  7.50     7.500000
9  2004-01-05 04:00:00   1.0    NA     7.573171
10 2004-01-05 04:00:00   2.0    NA     8.304878
11 2004-01-05 04:00:00   2.5    NA     8.670732
12 2004-01-05 04:00:00   3.0    NA     9.036585
13 2004-01-05 04:00:00   4.0    NA     9.768293
14 2004-01-05 04:00:00   5.0 10.50    10.500000
15 2004-01-05 05:00:00   0.9  7.00     7.000000
16 2004-01-05 05:00:00   1.0    NA     7.062500
17 2004-01-05 05:00:00   2.0    NA     7.687500
18 2004-01-05 05:00:00   2.5  8.00     8.000000
19 2004-01-05 05:00:00   3.0    NA     8.280000
20 2004-01-05 05:00:00   4.0    NA     8.840000
21 2004-01-05 05:00:00   5.0  9.40     9.400000
22 2004-01-05 06:00:00   0.9  6.92     6.920000
23 2004-01-05 06:00:00   1.0    NA           NA
24 2004-01-05 06:00:00   2.0    NA           NA
25 2004-01-05 06:00:00   2.5    NA           NA
26 2004-01-05 06:00:00   3.0    NA           NA
27 2004-01-05 06:00:00   4.0    NA           NA
28 2004-01-05 06:00:00   5.0    NA           NA


问:
Python how to map categorical values into new numeric values without getting the indices must be integer error?
I need to map some categorical values to integers. I tried the solution from this link at In[24]:

```<code>title_mapping = {"Mr": 0, "Miss": 1, "Mrs": 2,
                 "Master": 3, "Dr": 3, "Rev": 3, "Col": 3, "Major": 3, "Mlle": 3,"Countess": 3,
                 "Ms": 3, "Lady": 3, "Jonkheer": 3, "Don": 3, "Dona" : 3, "Mme": 3,"Capt": 3,"Sir": 3 }
for dataset in train_test_data:
    dataset['Title'] = dataset['Title'].map(title_mapping)
</code>```

From my script:

```<code>for dataset in train:
    dataset['Title'] = dataset['Title'].map(title_mapping)
</code>```

And here is the dataframe with the Title field:

I am keep getting the following error:

TypeError: string indices must be integers

答:
The error is probably because you are trying to iterate from your train DataFrame instead of the list of DataFrames train_test_data.

Try simply doing:

```<code>train['Title'] = train['Title'].map(title_mapping)
</code>```

The notebook you are basing on first creates a list of dataframes at [21]:

```<code>train_test_data = [train, test]
</code>```

So when it is iterating at [24] it first goes thru train and then test fully, which it's whats needed when mapping a column.

By the way, if you ever want to iterate row by row from a DataFrame, do like this:

```<code>for index_value, row in df.iterrows():
    print(index_value)
    # you can work for each column from that row:
    print(row['column_name'])

>>> 0
>>> I'm a column value
</code>```

Body:
I need to map some categorical values to integers. I tried the solution from this link at In[24]:

title_mapping = {"Mr": 0, "Miss": 1, "Mrs": 2,
                 "Master": 3, "Dr": 3, "Rev": 3, "Col": 3, "Major": 3, "Mlle": 3,"Countess": 3,
                 "Ms": 3, "Lady": 3, "Jonkheer": 3, "Don": 3, "Dona" : 3, "Mme": 3,"Capt": 3,"Sir": 3 }
for dataset in train_test_data:
    dataset['Title'] = dataset['Title'].map(title_mapping)

From my script:

for dataset in train:
    dataset['Title'] = dataset['Title'].map(title_mapping)

And here is the dataframe with the Title field:

I am keep getting the following error:

TypeError: string indices must be integers

Body:
The error is probably because you are trying to iterate from your train DataFrame instead of the list of DataFrames train_test_data.

Try simply doing:

train['Title'] = train['Title'].map(title_mapping)

The notebook you are basing on first creates a list of dataframes at [21]:

train_test_data = [train, test]

So when it is iterating at [24] it first goes thru train and then test fully, which it's whats needed when mapping a column.

By the way, if you ever want to iterate row by row from a DataFrame, do like this:

for index_value, row in df.iterrows():
    print(index_value)
    # you can work for each column from that row:
    print(row['column_name'])

>>> 0
>>> I'm a column value


问:
calling a template function of a derived class
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

```<code>class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};
</code>```

Usage:

```<code>int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}
</code>```

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir

答: Check this out, it will help you implement the CRTP.</p>

Body:
I'm having a problem in C++ with calling a function of a derived class while having a pointer to the base class.

EDIT:
Some answers referred me to CRTP

but my point is that I need to have a pointer to the "Base*" class not "Base*" because I'm unaware of the type currently being handled (The current instance is created from some sort of a factory).

Classes:

class Base
{
..
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

class Derived1 : public Base
{
...
template<typename T>
func (T arg) { ... };
};

Usage:

int main()
{
   Base* BasePtr = new Derived1();

   // The expected function to be called is Derived1::func<int>()
   BasePtr->func<int>();

   return 0; // :)
}

I can't make func virtual because the language does not support virtual template function.

It is only allowed if only the class is have template arguments but not if the function within it has template arguments.

I have seen a similar problem resolved within Boost.Serialization but couldn't understand the solution.

Thanks,

Koby Meir


问:
perl - matching greater than charater in regex
```<code>$string1="<a href='/channels/folder1'>Alpha-Seeking";
$string2="<a href='/channels/folder2'>No Underlying Index ,";
</code>```

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

```<code>($string1=~ /\'>(.*?)/) {print "got $1";}
</code>```

but this does not seem to work on '>' symbol.

2) Also tried

```<code>if ($string1=~ /(?=>)(.*?)/) {print "got $1";}
</code>```

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

答:
I must start by reiterating that it's incredibly unwise to parse HTML or XML with regexes. Please consider using a proper HTML parser.

Having said that, your problem here is pretty simple to fix. What you call the "standard intuitive approach" works fine with a simple tweak.

Here's what you have:

```<code>if ($string1=~ /\'>(.*?)/) {print "got $1";}
</code>```

And your regex is \'>(.*?). That means "find a literal quote mark, followed by a greater than sign and then capture the minimum amount of anything following that". It's "the minimum amount" that's the problem. The simplest thing that .*? can capture is nothing - the empty string.

Regexes are greedy by default; they match as much as possible. You add the ? to remove that greediness and make them match as little as possible. But you don't want that here. Here, you want their greediness. So just remove that ?.

```<code>use warnings;
use strict;

my @strings = (
 "<a href='/channels/folder1'>Alpha-Seeking",
 "<a href='/channels/folder2'>No Underlying Index ,"
);

for my $string (@strings) {
  if ($string =~ /'>(.*)/) { # Note: No "?" here
    print "got $1\n";
  }
}
</code>```

This displays:

```<code>got Alpha-Seeking
got No Underlying Index ,
</code>```

Body:
$string1="Alpha-Seeking";
$string2="No Underlying Index ,";

I need to extract "Alpha-Seeking" and "No Underlying Index ," from the above 2 strings.
Basically, need everything from ('>) to the last character of the string.

Tried two ways,

1) The standard intuitive

($string1=~ /\'>(.*?)/) {print "got $1";}

but this does not seem to work on '>' symbol.

2) Also tried

if ($string1=~ /(?=>)(.*?)/) {print "got $1";}

based on inputs from Greater than and less than symbol in regular expressions, but it is not working.

Any inputs will be useful.

PS: Also, if the answer can include matching the "less than" symbo ("<"), that will be great!

Thanks

Body:
I must start by reiterating that it's incredibly unwise to parse HTML or XML with regexes. Please consider using a proper HTML parser.

Having said that, your problem here is pretty simple to fix. What you call the "standard intuitive approach" works fine with a simple tweak.

Here's what you have:

if ($string1=~ /\'>(.*?)/) {print "got $1";}

And your regex is \'>(.*?). That means "find a literal quote mark, followed by a greater than sign and then capture the minimum amount of anything following that". It's "the minimum amount" that's the problem. The simplest thing that .*? can capture is nothing - the empty string.

Regexes are greedy by default; they match as much as possible. You add the ? to remove that greediness and make them match as little as possible. But you don't want that here. Here, you want their greediness. So just remove that ?.

use warnings;
use strict;

my @strings = (
 "<a href='/channels/folder1'>Alpha-Seeking",
 "<a href='/channels/folder2'>No Underlying Index ,"
);

for my $string (@strings) {
  if ($string =~ /'>(.*)/) { # Note: No "?" here
    print "got $1\n";
  }
}

This displays:

got Alpha-Seeking
got No Underlying Index ,


问:
Distribute load within chained operators in flink
I have an input kinesis stream with a single shard. I create a simple application with a map function but with an environment level parallelism of 8. Using a thread profiler, when I check the threads created, there is only 1 thread that is active for the map function and source(querying, as mentioned in the documentation). I realise that this is because I'm setting the parallelism at an environment level. Is there anyway to distribute the load amongst all the parallel instances created for the map function after it is consumed?</p>

答:
An easy fix would be to put a rebalance() right after the kinesis consumer. rebalance() does round-trip repartitioning. This will redistribute the events being read from the one shard among the 8 instances of the map that follows it.

Documentation.

The rebalance will cause ser/de and a network shuffle. You'll have to weigh that against the benefit of having 8 active pipelines rather than one.

Given that your job graph looks something like this,

```<code>source -> map -> async -> filter -> keyBy + process function -> sink
</code>```

the keyBy later in your pipeline will cause another network shuffle. If you are very concerned about performance, you might be able to get away with doing the keyBy right after the source (instead of using a rebalance there), and then use reinterpretAsKeyedStream after the async operator to avoid the second network shuffle. The reason this becomes a bit convoluted is that the async operator doesn't know anything about keyed streams -- and this will only work if the same KeySelector makes sense both before and after the async function.

Body:
An easy fix would be to put a rebalance() right after the kinesis consumer. rebalance() does round-trip repartitioning. This will redistribute the events being read from the one shard among the 8 instances of the map that follows it.

Documentation.

The rebalance will cause ser/de and a network shuffle. You'll have to weigh that against the benefit of having 8 active pipelines rather than one.

Given that your job graph looks something like this,

source -> map -> async -> filter -> keyBy + process function -> sink

the keyBy later in your pipeline will cause another network shuffle. If you are very concerned about performance, you might be able to get away with doing the keyBy right after the source (instead of using a rebalance there), and then use reinterpretAsKeyedStream after the async operator to avoid the second network shuffle. The reason this becomes a bit convoluted is that the async operator doesn't know anything about keyed streams -- and this will only work if the same KeySelector makes sense both before and after the async function.


问:
wrong/crazy number display in xpages dynamic view
I have a crazy effect when displaying in view with a number column in a dynamic view panel of an xPage:
Some (not all!) entries are displayed like:
123.40000000000005

the value in the notes doc is 123.4 .

I cannot found any difference between that wrong displayed value and others, which are displayed correctly.
I tried a few number formatting things in the column properties of the notes view: does not improve.

the notes view displayed everything well (for the notes client).

Is it a bug? Or did a forget some format settings for the dyn view control?

Thanks in advance, Uwe

Body:
tmp:=yourfield;
@Round(tmp*100)/100


问:
Rebuild database views
When you create a view, the column structure of the view is created and stored, and thus you can see it in object explorer:

When you alter the source data tables, sometimes things go wacky, because the view may have been built with "Select *" yet the schema created for you has the old information without the additional columns.

Does SQL Server have an easy way to rebuild the view schemas?

答:
Do not use SELECT * in views.  I say this as someone who has spent much too much time (in the past) debugging views that had this "feature".

When you do create a view in a production system, create it with SCHEMABINDING:

SCHEMABINDING

Binds the view to the schema of the underlying table or tables. When SCHEMABINDING is specified, the base table or tables cannot be modified in a way that would affect the view definition. The view definition itself must first be modified or dropped to remove dependencies on the table that is to be modified.

Although this adds an extra step when trying to modify tables, the increased resilience of the system is worth it.

Title: Rebuild database views


问:
XML parsing with Python and regex does not return all results
I am still struggling with regexp:

```<code>import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''

pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>'

print(re.findall(pattern, text, re.S))
</code>```

This returns:

```<code>[('abc', '8')]
</code>```

I would expect it to return:

```<code>[('abc', '4'), ('def', '8')]
</code>```

Why is it so greedy and matches everything until the last closing tag?

This is the regex101 link: https://regex101.com/r/ANO7RA/1

Maybe negative lookahead will solve this. I was not able to fully grasp the concept, though... :-(

答:
you can also check this out :

```<code>import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''
pattern=r'<SW-VARIABLE>\s*<SHORT-NAME>([^<].*?)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>([^<]*?)</VF>\s*</SW-ARRAYSIZE>.*?</SW-VARIABLE>'
print(re.findall(pattern, text, re.S))
</code>```

output :

```<code>[('abc', '4'), ('def', '8')]
</code>```

Body:
I am still struggling with regexp:

import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''

pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>'

print(re.findall(pattern, text, re.S))

This returns:

[('abc', '8')]

I would expect it to return:

[('abc', '4'), ('def', '8')]

Why is it so greedy and matches everything until the last closing tag?

This is the regex101 link: https://regex101.com/r/ANO7RA/1

Maybe negative lookahead will solve this. I was not able to fully grasp the concept, though... :-(

Body:
you can also check this out :

import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''
pattern=r'<SW-VARIABLE>\s*<SHORT-NAME>([^<].*?)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>([^<]*?)</VF>\s*</SW-ARRAYSIZE>.*?</SW-VARIABLE>'
print(re.findall(pattern, text, re.S))

output :

[('abc', '4'), ('def', '8')]


问:
Timber Android in an Android Library project
I am wondering if is there any way to use Timber Android in an Android library project, without initiate it in onCreate() in Application Class ?

答:
So it depends when you want to initialize your library. You can plant a DebugTree for example in your Library init class and if your library is initialized in your Application class or the better way would be to abstract it a little bit and make it possible to give your library a logger instance for example so that in debug builds it would be possible to pass some logger. So it is recommended to plant the tree as early as possible but this is not a must but you may be too late for some important logs

Behavior is added through Tree instances. You can install an instance by calling Timber.plant. Installation of Trees should be done as early as possible. The onCreate of your application is the most logical choice. https://github.com/JakeWharton/timber/blob/master/README.md

So like i already said you need to decide when and how you want to do enable logs for your lib (only debug etc..) and when your library will be instantiated.


问:
What Jekyll syntax to filter key:value pair in Front Matter?
In my Jekyll site, I have a page that stores an array of data in front matter, like this:

```<code>---
layout: page
title: MyTitle
array:
  - key1: value1
  - key2: value2
---
</code>```

What I want to do in my template: given a keyX, obtain valueX from the array.

I figured out a way to access the array:

```<code>{% assign subpage = site.pages | where: 'title', 'MyTitle' %}
{% assign array = subpage[0].array %}
</code>```

Now the query that I need to write is: "from the array, extract the value that matches keyX".

Is there a way to search through the array, without the need for looping? All the examples I can find are based on one-dimensional arrays...

答:
Your array is an array of non standardized objects (they don't have the same keys).

```<code>{{ page.array | inspect }}
</code>```

returns

```<code>[{"key1"=>"value1"}, {"key2"=>"value2"}]
</code>```

Here the only way to search is to loop over all array's items.

If you refactor your array to become an object, you can then get value from a key.

```<code>---
[...]
object:
  key1: value1
  key2: value2
...
</code>```

Example :

```<code>{% assign searched = "key1" %}
{{ page.object[searched] }}
</code>```

Body:
In my Jekyll site, I have a page that stores an array of data in front matter, like this:

---
layout: page
title: MyTitle
array:
  - key1: value1
  - key2: value2
---

What I want to do in my template: given a keyX, obtain valueX from the array.

I figured out a way to access the array:

{% assign subpage = site.pages | where: 'title', 'MyTitle' %}
{% assign array = subpage[0].array %}

Now the query that I need to write is: "from the array, extract the value that matches keyX".

Is there a way to search through the array, without the need for looping? All the examples I can find are based on one-dimensional arrays...

Body:
Your array is an array of non standardized objects (they don't have the same keys).

{{ page.array | inspect }}

returns

[{"key1"=>"value1"}, {"key2"=>"value2"}]

Here the only way to search is to loop over all array's items.

If you refactor your array to become an object, you can then get value from a key.

---
[...]
object:
  key1: value1
  key2: value2
...

Example :

{% assign searched = "key1" %}
{{ page.object[searched] }}


问:
Positioning a button with a tab bar
I am trying to position a button but I have found a problem with it.

When the view loads, the button displays but not in the correct position which is just above the tab bar.

```<code> self.tabBarController?.tabBar.isHidden = false
 loadButton()
</code>```

When the view did appear method

```<code> override func viewDidAppear(_ animated: Bool) {
            if shouldReloadDataOnViewWillAppear {
                // your code for reloading data
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2){
                    self.scaleDownAnimation()
                }
                shouldReloadDataOnViewWillAppear = false

            }
        }
</code>```

/////I then call another few functions to set up the map and markers.

Last line of the function sets the tab bar to be hidden:

```<code>self.tabBarController?.tabBar.isHidden = false
</code>```

then I call the load button function

```<code>func loadButton()
    {
        if  self.tabBarController?.tabBar.isHidden == false{
        button.setBackgroundImage(UIImage(named:"compass.png"), for: .normal)
        button.addTarget(self, action: #selector(btnPressed), for: UIControl.Event.touchUpInside)

        self.view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false
        let widthContraints =  NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40)

        let heightContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40)

        let xContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.bottomMargin, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.bottomMargin, multiplier: 1, constant: -40)

        let yContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -40)

        NSLayoutConstraint.activate([heightContraints,widthContraints,xContraints,yContraints])
        }
    }
</code>```

I think the problem is that the button loads in the correct position but when the tab bar loads it doesn't push up. As you can see below, when the view loads the button is below tab bar and when I segue away from the view it goes to the correct position.

I hope this is a really simple problem to solve!

答:
It would be easier for you to reason about your constraints if you used NSLayoutAnchor instead of manually creating the constraints:

```<code>NSLayoutContstraint.activate(
  [
    button.widthAnchor.constraint(equalTo: 40),
    button.heightAnchor.constraint(equalTo: 40),
    button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40),
    button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40)
  ]
)
</code>```

This removes a whole bunch of noise from your code so you can more easily see the logic instead of a wall of text with the constraint declarations.

As to your problem, you should probably use the view's safe area instead of the view itself:

```<code>button.bottomAnchor.constraint(
  equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40
)
</code>```

Title: Positioning a button with a tab bar

Body:
I am trying to position a button but I have found a problem with it.

When the view loads, the button displays but not in the correct position which is just above the tab bar.

 self.tabBarController?.tabBar.isHidden = false
 loadButton()

When the view did appear method

 override func viewDidAppear(_ animated: Bool) {
            if shouldReloadDataOnViewWillAppear {
                // your code for reloading data
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2){
                    self.scaleDownAnimation()
                }
                shouldReloadDataOnViewWillAppear = false

            }
        }

/////I then call another few functions to set up the map and markers.

Last line of the function sets the tab bar to be hidden:

self.tabBarController?.tabBar.isHidden = false

then I call the load button function

func loadButton()
    {
        if  self.tabBarController?.tabBar.isHidden == false{
        button.setBackgroundImage(UIImage(named:"compass.png"), for: .normal)
        button.addTarget(self, action: #selector(btnPressed), for: UIControl.Event.touchUpInside)

        self.view.addSubview(button)

        button.translatesAutoresizingMaskIntoConstraints = false
        let widthContraints =  NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.width, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40)

        let heightContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 40)

        let xContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.bottomMargin, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.bottomMargin, multiplier: 1, constant: -40)

        let yContraints = NSLayoutConstraint(item: button, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1, constant: -40)

        NSLayoutConstraint.activate([heightContraints,widthContraints,xContraints,yContraints])
        }
    }

I think the problem is that the button loads in the correct position but when the tab bar loads it doesn't push up. As you can see below, when the view loads the button is below tab bar and when I segue away from the view it goes to the correct position.

I hope this is a really simple problem to solve!

Body:
It would be easier for you to reason about your constraints if you used NSLayoutAnchor instead of manually creating the constraints:

NSLayoutContstraint.activate(
  [
    button.widthAnchor.constraint(equalTo: 40),
    button.heightAnchor.constraint(equalTo: 40),
    button.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -40),
    button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -40)
  ]
)

This removes a whole bunch of noise from your code so you can more easily see the logic instead of a wall of text with the constraint declarations.

As to your problem, you should probably use the view's safe area instead of the view itself:

button.bottomAnchor.constraint(
  equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -40
)


问:
Removing a Forward Slash from my Data - Using Replace Function mysql3
I am converting a BLOB file to a CSV file using mysqlite3. Once the conversion is completed I have forward slashes in my date data,  and characters of : in my time data.

Using the replace function i was able to remove the : characters from the Time data but was NOT able to remove the forward slashes.

After much research i have read that using multiple forward slashes should work however this was not the case for me.

The following part of the expression is what i am having trouble with (the date part only)

```<code>select REPLACE(date(eventdate/1000,'unixepoch'), '/' ,' ') as EventDate
       ,REPLACE(Time(eventdate/1000,'unixepoch', ':' ,' ') as EventTime
</code>```

As started above the removal of : is working OK just not the removal of the / characters,  How do i remove the / characters from my date. The date is currently dd/mm/yyyy ?

答:
If the function date() succeeds it will return a date in the format YYYY-MM-DD so it will not contain any forward slashes and the replace() function will do nothing because there is nothing to replace.

If you have dates in the format DD/MM/YYYY and you want to remove the forward slashes then apply replace() to them directly without the use of date().

If you have an integer column eventdate which you want to convert to date and format it like DD MM YYYY then you can do it with strftime():

```<code>strftime('%d %m %Y',date(12345612345/1000,'unixepoch'))
</code>```

Body:
I am converting a BLOB file to a CSV file using mysqlite3. Once the conversion is completed I have forward slashes in my date data,  and characters of : in my time data.

Using the replace function i was able to remove the : characters from the Time data but was NOT able to remove the forward slashes.

After much research i have read that using multiple forward slashes should work however this was not the case for me.

The following part of the expression is what i am having trouble with (the date part only)

select REPLACE(date(eventdate/1000,'unixepoch'), '/' ,' ') as EventDate
       ,REPLACE(Time(eventdate/1000,'unixepoch', ':' ,' ') as EventTime

As started above the removal of : is working OK just not the removal of the / characters,  How do i remove the / characters from my date. The date is currently dd/mm/yyyy ?

Body:
If the function date() succeeds it will return a date in the format YYYY-MM-DD so it will not contain any forward slashes and the replace() function will do nothing because there is nothing to replace.

If you have dates in the format DD/MM/YYYY and you want to remove the forward slashes then apply replace() to them directly without the use of date().

If you have an integer column eventdate which you want to convert to date and format it like DD MM YYYY then you can do it with strftime():

strftime('%d %m %Y',date(12345612345/1000,'unixepoch'))


问:
Create a list of lines representing the difference between two text files
I have two text files. I want to find the percent difference between the two files based on different lines seen in the two files. I can use the number of lines in the list and then the number of lines of the two files to calculate the percent difference (unless there is some builtin python function that does this). For example

File 1:

```<code>apple
ball
cat
dog
</code>```

File 2:

```<code>ball
cat
elephant
</code>```

resulting list:

```<code>[apple, dog, elephant]
</code>```

What would be the easiest and fastest way to do this?

答:
It depends on how you define "difference between two text files". Assuming that order doesn't matter to you and you just want to find lines from the two files that don't appear in the other, here is one possible solution:

```<code>set_1 = {line.strip() for line in open(file_1_path, 'r').readlines()}
set_2 = {line.strip() for line in open(file_2_path, 'r').readlines()}
difference = (set_1 | set_2) - (set_1 & set_2)
</code>```

For sequence matching differences, you can difflib as suggested by wjandrea. You can use it like this:

```<code>import difflib
list_1 = [line.strip() for line in open(file_1_path, 'r').readlines()]
list_2 = [line.strip() for line in open(file_2_path, 'r').readlines()]
difference = [line[2:] for line in difflib.ndiff(list_1, list_2) if line[0] in {'+', '-'}]
</code>```

Body:
I have two text files. I want to find the percent difference between the two files based on different lines seen in the two files. I can use the number of lines in the list and then the number of lines of the two files to calculate the percent difference (unless there is some builtin python function that does this). For example

File 1:

apple
ball
cat
dog

File 2:

ball
cat
elephant

resulting list:

[apple, dog, elephant]

What would be the easiest and fastest way to do this?

Body:
It depends on how you define "difference between two text files". Assuming that order doesn't matter to you and you just want to find lines from the two files that don't appear in the other, here is one possible solution:

set_1 = {line.strip() for line in open(file_1_path, 'r').readlines()}
set_2 = {line.strip() for line in open(file_2_path, 'r').readlines()}
difference = (set_1 | set_2) - (set_1 & set_2)

For sequence matching differences, you can difflib as suggested by wjandrea. You can use it like this:

import difflib
list_1 = [line.strip() for line in open(file_1_path, 'r').readlines()]
list_2 = [line.strip() for line in open(file_2_path, 'r').readlines()]
difference = [line[2:] for line in difflib.ndiff(list_1, list_2) if line[0] in {'+', '-'}]


问:
Multiple inheritance and "this" pointer being cast to common base class
Consider the following code:

```<code>class Base {
  //some code
};

class A : public virtual Base{
    //some code
};

class B : public virtual Base{
    //some code
};

class C:  public A, public B {
    //some code
};
</code>```

In other words we have multiple inheritance and all classes inherit from class Base. Now consider that the "this" pointer exists in code in classes A,B,C,Base. I know that in general we cannot assume that the "this" pointer value will be identical in all cases. But what it the "this" pointer is cast to the Base* class inside A,B,C whenever it is used. Is it correct to say that the casted pointer "this" after casting to the common Base* class will contain the same address inside A,B,C? Thanks

答: Yes. The virtual inheritance means that there is only one base class subobject of type Base, which is simultaneously a subobject of the C and the A and the B. A conversion (implicit or by cast) from pointer to any of those types to Base*, or initializing a reference Base& from lvalue of any of those types will cause the compiler to do the correct logic to find that single Base subobject.

Body:
Consider the following code:

class Base {
  //some code
};

class A : public virtual Base{
    //some code
};

class B : public virtual Base{
    //some code
};

class C:  public A, public B {
    //some code
};

In other words we have multiple inheritance and all classes inherit from class Base. Now consider that the "this" pointer exists in code in classes A,B,C,Base. I know that in general we cannot assume that the "this" pointer value will be identical in all cases. But what it the "this" pointer is cast to the Base* class inside A,B,C whenever it is used. Is it correct to say that the casted pointer "this" after casting to the common Base* class will contain the same address inside A,B,C? Thanks