问:
Does Realm support SELECT FOR UPDATE style read locking
I've spent a fair amount of time looking into the Realm database mechanics and I can't figure out if Realm is using row level read locks under the hood for data selected during write transactions.

As a basic example, imagine the following "queue" logic

assume the queue has an arbitrary number of jobs (we'll say 5 jobs)

```<code> async getNextJob() {

    let nextJob = null;

    this.realm.write(() => {

      let jobs = this.realm.objects('Job')
        .filtered('active == FALSE')
        .sorted([['priority', true], ['created', false]]);

      if (jobs.length) {
        nextJob = jobs[0];
        nextJob.active = true;
      }

    });

    return nextJob;

  }
</code>```

If I call getNextJob() 2 times concurrently, if row level read blocking isn't occurring, there's a chance that nextJob will return the same job object when we query for jobs.

Furthermore, if I have outside logic that relies on up-to-date data in read logic (ie job.active == false when it actually is true at current time) I need the read to block until update transactions complete. MVCC reads getting stale data do not work in this situation.

If read locks are being set in write transactions, I could make sure I'm always reading the latest data like so

```<code>let active = null;
this.realm.write(() => {

  const job = this.realm.pseudoQueryToGetJobByPrimaryKey();
  active = job.active;

});

// Assuming the above write transaction blocked the read until
// any concurrent updates touching the same job committed
// the value for active can be trusted at this point in time.
if (active === false) {
  // code to start job here
}
</code>```

So basically, TL;DR does Realm support SELECT FOR UPDATE?

Postgresql

https://www.postgresql.org/docs/9.1/static/explicit-locking.html

MySql

https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html

答:
So basically, TL;DR does Realm support SELECT FOR UPDATE?

Well if I understand the question correctly, the answer is slightly trickier than that.

If there is no Realm Object Server involved, then realm.write(() => disallows any other writes at the same time, and updates the Realm to its latest version when the transaction is opened.

If there is Realm Object Server involved, then I think this still stands locally, but the Realm Sync manages the updates from remote, in which case the conflict resolution rules apply for remote data changes.

Body:
I've spent a fair amount of time looking into the Realm database mechanics and I can't figure out if Realm is using row level read locks under the hood for data selected during write transactions.

As a basic example, imagine the following "queue" logic

assume the queue has an arbitrary number of jobs (we'll say 5 jobs)

 async getNextJob() {

    let nextJob = null;

    this.realm.write(() => {

      let jobs = this.realm.objects('Job')
        .filtered('active == FALSE')
        .sorted([['priority', true], ['created', false]]);

      if (jobs.length) {
        nextJob = jobs[0];
        nextJob.active = true;
      }

    });

    return nextJob;

  }

If I call getNextJob() 2 times concurrently, if row level read blocking isn't occurring, there's a chance that nextJob will return the same job object when we query for jobs.

Furthermore, if I have outside logic that relies on up-to-date data in read logic (ie job.active == false when it actually is true at current time) I need the read to block until update transactions complete. MVCC reads getting stale data do not work in this situation.

If read locks are being set in write transactions, I could make sure I'm always reading the latest data like so

let active = null;
this.realm.write(() => {

  const job = this.realm.pseudoQueryToGetJobByPrimaryKey();
  active = job.active;

});

// Assuming the above write transaction blocked the read until
// any concurrent updates touching the same job committed
// the value for active can be trusted at this point in time.
if (active === false) {
  // code to start job here
}

So basically, TL;DR does Realm support SELECT FOR UPDATE?

Postgresql

https://www.postgresql.org/docs/9.1/static/explicit-locking.html

MySql

https://dev.mysql.com/doc/refman/5.7/en/innodb-locking-reads.html


来源: stackexchange

问:
When I define functions, in what order should I put the parameters?
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

```<code>def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

could easily be:

```<code>def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)
</code>```

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.

答: I believe the convention is, left to right, most vital to least vital.  so for your example I would do (needle, haystack, exclude_value).  needle is the most vital in this case because its the defining info of the call.  the same haystack could be used in another call with a different needle. Exclude_value seems like it could be optional.</p>

ContentLicense: CC BY-SA 2.5

Body:
I often find it hard to decide and am inconsistent. Are there some rules I could follow?

For example:

def remove_except(haystack, needle, exclude_value):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

could easily be:

def remove_except(needle, exclude_value, haystack):
    for key in hackstack:
        if key in needle and haystack[key] != exclude_value:
            hackstack.pop(key)

Not a perfect example because I tend to put the variable being modified as the first parameter, e.g. haystack, and that might even be a convention but apart from that I'm unsure what to do.

I'm interested for more languages than just Python.


问:
How to get DOM element Xpath in Firefox
It might be just me but I can't find any way to get DOM element's XPATH in Firefox.

That was possible in Firebug, but now it's deprecated in favor of Firefox Developer Tools, and the recommendation is not to use it any longer.

So, is there any way to get XPATH in Firefox and its Developer Tools?

答:
Even if there is no extension available for Firbug in Firfox V57/Quantum. Still we can performed same operation which we performed earlier with the help of firebug, in Firefox dev tool now. Firefox dev tool has more advanced function than normal browser. So It will be helpful for UIDesigner or any Developer.

Features in Developer Tool-Features in Developer Tool

To install & Download Firefox Developer Tool- Firefox Developer Tool

For XPath: Select any element by right click on it and choose Inspect Element(Q) then element/tag gets highlighted under inspector developer tool. Then Right Click on tag and select Copy=>Xpath or CssPath.

but the xpath or Css provided by above option will not be correct always if application is dynamic or having dynamic ids etc...
So better to use console option/ select console option (Press F12) write allow paste and enter.

For Xpath =>we have to use ($x)  example: >>$x("//p") It will gives all p tag.

For Css path=> we have to use ($$) Example: >>$$("p") then Enter It will gives all p tag.

ContentLicense: CC BY-SA 3.0

Title: How to get DOM element Xpath in Firefox


问:
Why is visibility not working on a div?
Here is my html:

```<code><div class="form3">
<form>
    <input type="text" name="search" placeholder="Search Text Here...">
    <button><i class="fa fa-search" aria-hidden="true"></i></button>
</form>
</code>```

Here is the CSS:

```<code>.form3 { visibility: hidden; }
</code>```

I tried to remove div and apply class directly to the form element, but that didn't work either.

答:
Your code is good enough to work. Make sure that you have included the css file correctly. If you have, you might have overwritten .form3 class somewhere which is causing this problem.

Try using :

```<code>.form3 { visibility: hidden !important; }
</code>```

If this doesn't work either, try clearing your browsers cache and reload again.

Title: Why is visibility not working on a div?

Body:
Here is my html:

<form>
    <input type="text" name="search" placeholder="Search Text Here...">
    <button></button>
</form>

Here is the CSS:

.form3 { visibility: hidden; }

I tried to remove div and apply class directly to the form element, but that didn't work either.

Body:
Your code is good enough to work. Make sure that you have included the css file correctly. If you have, you might have overwritten .form3 class somewhere which is causing this problem.

Try using :

.form3 { visibility: hidden !important; }

If this doesn't work either, try clearing your browsers cache and reload again.


问:
In javascript, when to use object literal and when to use array?
Here's a sample. My concern is both seem to do the job. which of them to prefer?

```<code>var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}
</code>```

Also, the following seems to be not valid, Any way of avoiding array notation.

```<code>var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};
</code>```

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

```<code>var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};
</code>```

Thanks again and in advance to those who help me with the query.

答:
The sample doesn't really compare objects and arrays. You're just adding a needless layer by putting an object in the first element of an array.

Use an object when you have to refer to something by name.

```<code>var obj = {}
</code>```

//3 ways of doing the same thing:

```<code>var obj.newName = 'bob';

var obj['newName'] = 'bob';

var name = 'newName';
var obj[name] = 'bob';
</code>```

The 2nd style isn't really necessary and might actually be a touch slower to access than the 1st but it helps you understand how the 3rd can be useful. Or you could have done the following outright:

```<code>var obj = { newName:'bob' }
</code>```

If you want a bunch of names in an object, it would get a bit silly:

```<code>var obj = { newName:'bob', anotherNewName:'sue', yetAnotherNewName:'billy' }

obj.newName === 'bob'
obj.anotherNewName === 'sue'
//etc...
</code>```

That's what arrays are for.

```<code>var listOfNewNames = ['bob','sue','billy']
listOfNewNames[0] === 'bob'
listOfNewNames[1] === 'sue'
//etc...
</code>```

Of course, nothing prevents you from assigning an array to an object property:

```<code>obj { listOfNewNames:['bob','sue','billy'] }

obj.listOfNewNames[0] === 'bob'
</code>```

Or, as demonstrated above, multiple objects in an array:

```<code>var listOfMonsters = [
    { monsterName:'Grarrr',eats:'people' },
    { monsterName:'Wadsworth',eats:'other monsters'}
];

listOfMonsters[1].monsterName === 'Wadsworth'
</code>```

Objects are typically more about keeping groups of related values and methods together for ease of reference. Arrays are just a list of stuff that all can typically be assumed to apply to or derive from the same thing.

Body:
Here's a sample. My concern is both seem to do the job. which of them to prefer?

var fooArr = [{ "bar": {"blah": 9 } }];

for(var i in fooArr) {
    var value = fooArr[i].bar.blah;
console.log(value); //checking in firebug console
}

var fooObj = { "bar": {"blah": 9 } };
for(var i in fooObj) {
    var value = fooObj[i].blah;
console.log(value); //checking in firebug console
}

Also, the following seems to be not valid, Any way of avoiding array notation.

var fooObj1 = {
    { "bar": { "blah": 9 } },
    { "bar": { "blah": 4 } },
    { "bar": { "blah":12} }
};

So I had to modify the above code to something like below which works. Is it too too bad to be too much sticky with Object literals

var fooObj1 = {
    1:{ "bar": { "blah": 9 } },
    2:{ "bar": { "blah": 4 } },
    3:{ "bar": { "blah":12} }
};

Thanks again and in advance to those who help me with the query.

Body:
The sample doesn't really compare objects and arrays. You're just adding a needless layer by putting an object in the first element of an array.

Use an object when you have to refer to something by name.

var obj = {}

//3 ways of doing the same thing:

var obj.newName = 'bob';

var obj['newName'] = 'bob';

var name = 'newName';
var obj[name] = 'bob';

The 2nd style isn't really necessary and might actually be a touch slower to access than the 1st but it helps you understand how the 3rd can be useful. Or you could have done the following outright:

var obj = { newName:'bob' }

If you want a bunch of names in an object, it would get a bit silly:

var obj = { newName:'bob', anotherNewName:'sue', yetAnotherNewName:'billy' }

obj.newName === 'bob'
obj.anotherNewName === 'sue'
//etc...

That's what arrays are for.

var listOfNewNames = ['bob','sue','billy']
listOfNewNames[0] === 'bob'
listOfNewNames[1] === 'sue'
//etc...

Of course, nothing prevents you from assigning an array to an object property:

obj { listOfNewNames:['bob','sue','billy'] }

obj.listOfNewNames[0] === 'bob'

Or, as demonstrated above, multiple objects in an array:

var listOfMonsters = [
    { monsterName:'Grarrr',eats:'people' },
    { monsterName:'Wadsworth',eats:'other monsters'}
];

listOfMonsters[1].monsterName === 'Wadsworth'

Objects are typically more about keeping groups of related values and methods together for ease of reference. Arrays are just a list of stuff that all can typically be assumed to apply to or derive from the same thing.


问:
array to string conversion in php error anyone can help me with this code
```<code><?php

    include('db.php');

    $query = "SELECT * FROM Student";
    $result = mysqli_query ( $conn, $query );

    if (mysqli_num_rows($result)>0)
    {
        while( $row = mysqli_fetch_assoc($result) )
        {
            echo $row = ["id"] . " " . $row = ["name"] . " " . $row = ["email"] . "</br>";
        }
    }
    else
    {
        echo "No Data";
    }

mysqli_close($conn);
?>
</code>```

答:
You should remove = . it work like you are assigning the value.

change your code from

```<code>echo $row = ["id"] . " " . $row = ["name"] . " " . $row = ["email"] . "</br>";
</code>```

to

```<code>echo $row ["id"] . " " . $row ["name"] . " " . $row["email"] . "</br>";
</code>```

Body:
<?php

    include('db.php');

    $query = "SELECT * FROM Student";
    $result = mysqli_query ( $conn, $query );

    if (mysqli_num_rows($result)>0)
    {
        while( $row = mysqli_fetch_assoc($result) )
        {
            echo $row = ["id"] . " " . $row = ["name"] . " " . $row = ["email"] . "
";
        }
    }
    else
    {
        echo "No Data";
    }

mysqli_close($conn);
?>

Body:
You should remove = . it work like you are assigning the value.

change your code from

echo $row = ["id"] . " " . $row = ["name"] . " " . $row = ["email"] . "</br>";

to

echo $row ["id"] . " " . $row ["name"] . " " . $row["email"] . "</br>";


问:
Error: Package 'Microsoft SQL Management Studio Package' failed to load. In SQL Server Management Studio
I had installed SQL Server 2008 R2, the installation was succesful. But I can't open the Management Studio because this error is shown:

```<code>Package 'Microsoft SQL Management Studio Package' failed to load.
</code>```

Any idea? Thanks.

答:
This error due to managment studio did not detect dot net framework hence uninstall dot net 4 and reinstall it.
I tried that , it's working.</p>

Body:
I had installed SQL Server 2008 R2, the installation was succesful. But I can't open the Management Studio because this error is shown:

Package 'Microsoft SQL Management Studio Package' failed to load.

Any idea? Thanks.


问:
Xamarin.Forms: Forms.Context is obsolete
The new obsolete warning in Xamarin.Forms 2.5 really puzzled me.
What context should I be using in Dependency Services, for example, to call GetSystemService()?

Should I store in a static field the context of activity the xamarin forms were initialized against?

Should I override the android Application class and use its Context?

Should I call GetSystemService at activity create and save it somewhere?

答:
I was having the same issue with several Dependency Services

The simplest solution

In a lot of cases for Single Activity Applications

```<code>Xamarin.Forms.Forms.Context
</code>```

Can be replaced with

```<code>Android.App.Application.Context
</code>```

The Background in more detail

Android.App.Application.Context returns the global Application Context of the current process tied to the lifecycle of the Application, as apposed to an Activity context.

A typical example of using the Application context is for starting an Activity e.g.

```<code>Android.App.Application.Context.StartActivity(myIntent);
</code>```

The general rule of thumb is to use the current Activity Context, unless you need
  to save a reference to a context from an object that lives beyond your
  Activity. In which case use the Application context

Why did Forms.Context go obsolete?

Xmarin.Forms 2.5 introduced a new "Forms embedding" feature, which can embed Forms pages into Xamarin.iOS / Xamarin.Android apps. However, since Xamarin.Android apps can use multiple Activities, seemingly there was a danger of Xamarin.Android users calling Forms.Context and in turn getting a reference to the MainActivity, which has the potential cause problems.

The work around

Inside a Renderer you now get a reference to the view’s context which is passed into the constructor.

With any other class you are faced with the issue of how to get the Activity Context. In a single Activity application (in most cases) the Application.Context will work just fine.

However to get the current Activity Context in a Multiple Activity Application you will need to hold a reference to it. The easiest and most reliable way to do this is via a class that implements the  Application.IActivityLifecycleCallbacks Interface.

The main idea is to keep a reference of the Context when an Activity
  is created, started, or resumed.

```<code>[Application]
public partial class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
   internal static Context ActivityContext { get; private set; }

   public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }

   public override void OnCreate()
   {
      base.OnCreate();
      RegisterActivityLifecycleCallbacks(this);
   }

   public override void OnTerminate()
   {
      base.OnTerminate();
      UnregisterActivityLifecycleCallbacks(this);
   }

   public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
   {
      ActivityContext = activity;
   }

   public void OnActivityResumed(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityStarted(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityDestroyed(Activity activity) { }
   public void OnActivityPaused(Activity activity) { }
   public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
   public void OnActivityStopped(Activity activity) { }
}
</code>```

With the above approach, single Activity Applications and multiple Activity Applications can now always have access to the Current/Local Activity Context. e.g instead of relying on the global context

```<code>Android.App.Application.Context

// or previously

Xamarin.Forms.Forms.Context
</code>```

Can now be replaced with

```<code>MainApplication.ActivityContext
</code>```

Example call in a Dependency Service

```<code>if (MainApplication.ActivityContext!= null)
{
    versionNumber = MainApplication.ActivityContext
                       .PackageManager
                       .GetPackageInfo(MainApplication.ActivityContext.PackageName, 0)
                       .VersionName;
}
</code>```

Additional Resources

Android.App.Application.IActivityLifecycleCallbacks

registerActivityLifecycleCallbacks

Body:
I was having the same issue with several Dependency Services

The simplest solution

In a lot of cases for Single Activity Applications

Xamarin.Forms.Forms.Context

Can be replaced with

Android.App.Application.Context

The Background in more detail

Android.App.Application.Context returns the global Application Context of the current process tied to the lifecycle of the Application, as apposed to an Activity context.

A typical example of using the Application context is for starting an Activity e.g.

Android.App.Application.Context.StartActivity(myIntent);

The general rule of thumb is to use the current Activity Context, unless you need
  to save a reference to a context from an object that lives beyond your
  Activity. In which case use the Application context

Why did Forms.Context go obsolete?

Xmarin.Forms 2.5 introduced a new "Forms embedding" feature, which can embed Forms pages into Xamarin.iOS / Xamarin.Android apps. However, since Xamarin.Android apps can use multiple Activities, seemingly there was a danger of Xamarin.Android users calling Forms.Context and in turn getting a reference to the MainActivity, which has the potential cause problems.

The work around

Inside a Renderer you now get a reference to the view’s context which is passed into the constructor.

With any other class you are faced with the issue of how to get the Activity Context. In a single Activity application (in most cases) the Application.Context will work just fine.

However to get the current Activity Context in a Multiple Activity Application you will need to hold a reference to it. The easiest and most reliable way to do this is via a class that implements the  Application.IActivityLifecycleCallbacks Interface.

The main idea is to keep a reference of the Context when an Activity
  is created, started, or resumed.

[Application]
public partial class MainApplication : Application, Application.IActivityLifecycleCallbacks
{
   internal static Context ActivityContext { get; private set; }

   public MainApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { }

   public override void OnCreate()
   {
      base.OnCreate();
      RegisterActivityLifecycleCallbacks(this);
   }

   public override void OnTerminate()
   {
      base.OnTerminate();
      UnregisterActivityLifecycleCallbacks(this);
   }

   public void OnActivityCreated(Activity activity, Bundle savedInstanceState)
   {
      ActivityContext = activity;
   }

   public void OnActivityResumed(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityStarted(Activity activity)
   {
      ActivityContext = activity;
   }

   public void OnActivityDestroyed(Activity activity) { }
   public void OnActivityPaused(Activity activity) { }
   public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { }
   public void OnActivityStopped(Activity activity) { }
}

With the above approach, single Activity Applications and multiple Activity Applications can now always have access to the Current/Local Activity Context. e.g instead of relying on the global context

Android.App.Application.Context

// or previously

Xamarin.Forms.Forms.Context

Can now be replaced with

MainApplication.ActivityContext

Example call in a Dependency Service

if (MainApplication.ActivityContext!= null)
{
    versionNumber = MainApplication.ActivityContext
                       .PackageManager
                       .GetPackageInfo(MainApplication.ActivityContext.PackageName, 0)
                       .VersionName;
}

Additional Resources

Android.App.Application.IActivityLifecycleCallbacks

registerActivityLifecycleCallbacks

ContentLicense: CC BY-SA 4.0


问:
Inability to load objects exported from Blender into three.js?
I've been playing around with Blender for quite a bit longer than I've been coding, and was really excited when I learned that you could load and manipulate a blend in the browser using three.js. I looked up a tutorial, exported a simple icosphere, and plugged in my .json file. Alas, after looking at numerous different pages and examples, I still can't seem to get it to appear in the browser, despite not being able to find any visible errors in my code. I made a codepen project out of it (it was the only way I could find to get the json file online).

```<code>https://codepen.io/redheadedmandy/project/editor/ZjNEQG#0
</code>```

Here's the snippet of code to call the .json file:

```<code>function initMesh() {
    function addModelToScene(geometry, materials) {
        var material = new THREE.MeshFaceMaterial(materials);
        model = new THREE.Mesh(geometry, material);
        model.scale.set(1, 1, 1);
        model.position.set(50, 0, 0);
        scene.add(model);

        var loader = new THREE.JSONLoader();
        loader.load("casvusnion.json", addModelToScene);
    }
}
</code>```

If anyone can spot a problem, or has a suggestion for what the issue might be, I would much appreciate the help!

答:
Try this:

```<code>function initMesh() {

    var loader = new THREE.JSONLoader();
    loader.load("casvusnion.json", addModelToScene);

    function addModelToScene(geometry, materials) {

        var material = new THREE.MeshFaceMaterial(materials);
        model = new THREE.Mesh(geometry, material);
        model.scale.set(1, 1, 1);
        model.position.set(50, 0, 0);
        scene.add(model);

    }

}
</code>```

And check your browser's console log for warnings and error messages.

Also, your camera

```<code>camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
camera.position.set(0, 3.5, 5);
camera.lookAt(scene.position);
</code>```

and your model

```<code>model.position.set(50, 0, 0);
</code>```

It looks like that the model's position is way far from camera's view.

And finally, your project is read-only, so it's impossible for the others to change something there.

Body:
I've been playing around with Blender for quite a bit longer than I've been coding, and was really excited when I learned that you could load and manipulate a blend in the browser using three.js. I looked up a tutorial, exported a simple icosphere, and plugged in my .json file. Alas, after looking at numerous different pages and examples, I still can't seem to get it to appear in the browser, despite not being able to find any visible errors in my code. I made a codepen project out of it (it was the only way I could find to get the json file online).

https://codepen.io/redheadedmandy/project/editor/ZjNEQG#0

Here's the snippet of code to call the .json file:

function initMesh() {
    function addModelToScene(geometry, materials) {
        var material = new THREE.MeshFaceMaterial(materials);
        model = new THREE.Mesh(geometry, material);
        model.scale.set(1, 1, 1);
        model.position.set(50, 0, 0);
        scene.add(model);

        var loader = new THREE.JSONLoader();
        loader.load("casvusnion.json", addModelToScene);
    }
}

If anyone can spot a problem, or has a suggestion for what the issue might be, I would much appreciate the help!

Body:
Try this:

function initMesh() {

    var loader = new THREE.JSONLoader();
    loader.load("casvusnion.json", addModelToScene);

    function addModelToScene(geometry, materials) {

        var material = new THREE.MeshFaceMaterial(materials);
        model = new THREE.Mesh(geometry, material);
        model.scale.set(1, 1, 1);
        model.position.set(50, 0, 0);
        scene.add(model);

    }

}

And check your browser's console log for warnings and error messages.

Also, your camera

camera = new THREE.PerspectiveCamera(70, WIDTH / HEIGHT, 1, 10);
camera.position.set(0, 3.5, 5);
camera.lookAt(scene.position);

and your model

model.position.set(50, 0, 0);

It looks like that the model's position is way far from camera's view.

And finally, your project is read-only, so it's impossible for the others to change something there.


问:
How to select next column when previous column meets certain condition using SQL
I'm using SQL on Impala

The table I'm querying on looks like

customer name   shop1   shop1number shop2   shop2number shop3   shop3number

TOM AB  111 AA  231 AC  321

AMY AC  121 AB  213 AD  231

Franck  AD  123 AE  233 AB  234

enter image description here
here, the numbers are customer loyalty number and the challenge is if I'm looking for the loyalty number of shop 1 (AB), I have no idea which column it falls in as when customer fills in their loyalty number, it's their choice to put in the number at whatever order they profile

答:
```<code>declare @shop varchar(10)
set @shop='AB'
select cname,
case when  shop1=@shop then shop1
when shop2=@shop then shop2
when shop3=@shop then shop3
end
as shop,
shop1number as shopnumber
from tblcus
</code>```


问:
Array Index merge of the same array
I have faced a problem. I have an array looks like this

```<code>print_r($log_ret_val);
Array ( [0] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
      )
        [1] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
      )
        [2] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:03:33 ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:00:31 ) )
     )
)
</code>```

And this is what I write for that value

```<code>$log_val        = array();
foreach ($log_ret_val as $key => $valuee) {
    foreach ($valuee as $key => $val) {
        array_push($log_val,$val);
    }
}
print_r($log_val);

Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
        [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
        [2] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
        [3] => Array ( [TestingLogDevice] => Array ( [Tempin] => 28 ) )
        [4] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:24:45 ) )
        [5] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:21:43 ) )
)
</code>```

But my desired output looks like this

```<code>Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO [Tempin] => 29 [Date_time] => 18.11.2017 11:24:45 ) )
        [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO [Tempin] => 28 [Date_time] => 18.11.2017 11:21:43 ) )
)
</code>```

So what can I do meet up my desired output. For your kind suggestion or help please

答:
Loop through $log_ret_val extract it key and use array_merge_recursive to create new array

```<code>$log_ret_val = Array ( "0" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Siteid" => "Mirpur_CO" ) ) ,
                       "1" => Array ( "TestingLogDevice" => Array ( "Siteid" => "Mirpur_CO" ) ) ,
  ) ,
        "1" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Tempin" => 29 ) ) ,
                      "1" => Array ( "TestingLogDevice" => Array ( "Tempin" => 29 ) ) ,
  ) ,
        "2" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Date_time" => "18.11.2017 11:03:33" ) ) ,
                       "1" => Array ( "TestingLogDevice" => Array ( "Date_time" => "18.11.2017 11:00:31" ) )
  )
  );
$log_val = array();
foreach ($log_ret_val as $key => $value) {
    foreach ($value as $key1 => $value1) {
        if(isset($log_val[$key1]))
            $log_val[$key1] = array_merge_recursive($log_val[$key1],$value1);
        else
            $log_val[$key1] = array_merge_recursive($value1);
    }
}
print_r($log_val);
</code>```

DEMO

Title: Array Index merge of the same array

Body:
I have faced a problem. I have an array looks like this

print_r($log_ret_val);
Array ( [0] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
      )
        [1] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
      )
        [2] => Array ( [0] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:03:33 ) )
                       [1] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:00:31 ) )
     )
)

And this is what I write for that value

$log_val        = array();
foreach ($log_ret_val as $key => $valuee) {
    foreach ($valuee as $key => $val) {
        array_push($log_val,$val);
    }
}
print_r($log_val);

Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
        [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO ) )
        [2] => Array ( [TestingLogDevice] => Array ( [Tempin] => 29 ) )
        [3] => Array ( [TestingLogDevice] => Array ( [Tempin] => 28 ) )
        [4] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:24:45 ) )
        [5] => Array ( [TestingLogDevice] => Array ( [Date_time] => 18.11.2017 11:21:43 ) )
)

But my desired output looks like this

Array ( [0] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO [Tempin] => 29 [Date_time] => 18.11.2017 11:24:45 ) )
        [1] => Array ( [TestingLogDevice] => Array ( [Siteid] => Mirpur_CO [Tempin] => 28 [Date_time] => 18.11.2017 11:21:43 ) )
)

So what can I do meet up my desired output. For your kind suggestion or help please

Body:
Loop through $log_ret_val extract it key and use array_merge_recursive to create new array

$log_ret_val = Array ( "0" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Siteid" => "Mirpur_CO" ) ) ,
                       "1" => Array ( "TestingLogDevice" => Array ( "Siteid" => "Mirpur_CO" ) ) ,
  ) ,
        "1" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Tempin" => 29 ) ) ,
                      "1" => Array ( "TestingLogDevice" => Array ( "Tempin" => 29 ) ) ,
  ) ,
        "2" => Array ( "0" => Array ( "TestingLogDevice" => Array ( "Date_time" => "18.11.2017 11:03:33" ) ) ,
                       "1" => Array ( "TestingLogDevice" => Array ( "Date_time" => "18.11.2017 11:00:31" ) )
  )
  );
$log_val = array();
foreach ($log_ret_val as $key => $value) {
    foreach ($value as $key1 => $value1) {
        if(isset($log_val[$key1]))
            $log_val[$key1] = array_merge_recursive($log_val[$key1],$value1);
        else
            $log_val[$key1] = array_merge_recursive($value1);
    }
}
print_r($log_val);

DEMO


问:
Outlook for Mac 15.40 broke our Angular add-in
We have a side-loaded Outlook add-in written in AngularJS 1.5 that uses hash path parameters, for example:

```<code>https://our.domain.com/ouraddin/index.html?brand=x#/settings
</code>```

After updating Outlook 2016 for Mac to version 15.40 the add-in stopped working. We are getting an error that only occurs if $routeParams.id is not set.

Is anyone else seeing the same problem with 15.40? Everything was working fine in Outlook 2016 for Mac before the update.

Update: It looks like Outlook 2016 for Mac 15.40 is now messing up the URLs from the add-in manifest by encoding the # as %23. The URL above becomes:

```<code>https://our.domain.com/ouraddin/index.html?brand=x&_hostInfo=Outlook$Mac$16.01$en-US%23/settings
</code>```

答: This is a known issue that has been fixed. It will reflect in a future update, in Build 15.40 (171018) and above.</p>

Body:
We have a side-loaded Outlook add-in written in AngularJS 1.5 that uses hash path parameters, for example:

https://our.domain.com/ouraddin/index.html?brand=x#/settings

After updating Outlook 2016 for Mac to version 15.40 the add-in stopped working. We are getting an error that only occurs if $routeParams.id is not set.

Is anyone else seeing the same problem with 15.40? Everything was working fine in Outlook 2016 for Mac before the update.

Update: It looks like Outlook 2016 for Mac 15.40 is now messing up the URLs from the add-in manifest by encoding the # as %23. The URL above becomes:

https://our.domain.com/ouraddin/index.html?brand=x&_hostInfo=Outlook$Mac$16.01$en-US%23/settings


问:
Postgresql schema povider
I have a ASP.NET project that is used MS SQL db. DB access code is generated using CodeSmith .netTiers. Now, project will be merged with another and should use PostgreSQL db. I am looking for PostgreSQL Schema Provider for CodeSmith. But found only next topic on CodeSmith comunity: http://community.codesmithtools.com/nettiers/f/16/t/4463.aspx?PageIndex=2

Can be used PostgreSQL with .netTiers ?

答:
Yes it can be used with .netTiers but there may be some work needed. I'll try and get his patches. Please use the PostgreSQLSchemaProvider that ships with CodeSmith Generator. We have recently rewrote the entire provider and have been doing a lot of testing on it. Please contact support for a nightly build of CodeSmith Generator which contains two extra PostgreSQLSchemaProvider bug fixes. Please let us know if you have any questions.

Thanks
-Blake Niemyjski

Title: Postgresql schema povider


问:
Aesthetic error while plotting multiple labels on x axis in histogram using ggplot
I have a data in the below format

```<code>occupation,how_many_happy, how_many_not_happy
Teacher, 50, 30
</code>```

I am trying to plot a histogram by using both how_many_happy, how_many_not_happy on the x axis for each occupation separatly using ggplot as below

```<code>ggplot(Occupations_vs_parties,
       aes(x = c(Occupations_vs_parties$How_many_happy,
                 Occupations_vs_parties$How_many_not_happy))) +
       facet_wrap(~Occupation, nrow = 4)
</code>```

However I am getting the error as below

```<code>Error: Aesthetics must be either length 1 or the same as the data (17): x
</code>```

Can you please help me with the way forward. Please let me know if any inputs are needed

Thanks,
Surya

答:
There are quite a few mistakes in your code. Most fundamentally, I would recommend reading up on (1) converting data from wide to long format, and (2) general ggplot syntax, especially the use of geom_histogram and geom_bar (for example you don't actually specify how you want to plot your data).

With the sample data that you give, there is also no point in facet wrapping occupation. So your example data might not be a representative minimal example.

Here is an simple barplot based on your sample data.

```<code># Sample data
df <- read.csv(text =
    "occupation,how_many_happy,how_many_not_happy
    Teacher,50,30", sep = ",");

# Convert wide to long dataframe
library(reshape2);
df.long <- melt(df);

# (gg)plot
require(ggplot2);
ggplot(df.long, aes(x = variable, y = value)) + geom_bar(stat = "identity"),
</code>```

If you do have different occupation levels, you can add ... + facet_wrap(~ occuptation) to your ggplot command.

Body:
I have a data in the below format

occupation,how_many_happy, how_many_not_happy
Teacher, 50, 30

I am trying to plot a histogram by using both how_many_happy, how_many_not_happy on the x axis for each occupation separatly using ggplot as below

ggplot(Occupations_vs_parties,
       aes(x = c(Occupations_vs_parties$How_many_happy,
                 Occupations_vs_parties$How_many_not_happy))) +
       facet_wrap(~Occupation, nrow = 4)

However I am getting the error as below

Error: Aesthetics must be either length 1 or the same as the data (17): x

Can you please help me with the way forward. Please let me know if any inputs are needed

Thanks,
Surya

Body:
There are quite a few mistakes in your code. Most fundamentally, I would recommend reading up on (1) converting data from wide to long format, and (2) general ggplot syntax, especially the use of geom_histogram and geom_bar (for example you don't actually specify how you want to plot your data).

With the sample data that you give, there is also no point in facet wrapping occupation. So your example data might not be a representative minimal example.

Here is an simple barplot based on your sample data.

# Sample data
df <- read.csv(text =
    "occupation,how_many_happy,how_many_not_happy
    Teacher,50,30", sep = ",");

# Convert wide to long dataframe
library(reshape2);
df.long <- melt(df);

# (gg)plot
require(ggplot2);
ggplot(df.long, aes(x = variable, y = value)) + geom_bar(stat = "identity"),

If you do have different occupation levels, you can add ... + facet_wrap(~ occuptation) to your ggplot command.


问:
C++ reference to function crashes in a call
I use a templated reference to capture a function by reference-to-function-type but it crashes when I try to call by param() (with Apple LLVM version 9.0.0 (clang-900.0.38), x86_64-apple-darwin17.2.0)

```<code>#include <iostream>
#include <typeinfo>

int doit(int a, int b) {
    return a+b;
}

template <typename T>
void test(T & param) {
    std::cout << typeid(T).name() << " ";
    std::cout << typeid(param).name() << " ";
    std::cout << param(3,5);
}

int main()
{
    test(doit);
}
</code>```

But according to Scott Meyers book "Function types can decay into function pointers":

```<code>void someFunc(int, double); // someFunc is a function; type is void(int, double)

template<typename T>
void f1(T param);       // in f1, param passed by value

template<typename T>
void f2(T& param);      // in f2, param passed by ref

f1(someFunc);       // param deduced as ptr-to-func; type is void (*)(int, double)
f2(someFunc);       // param deduced as ref-to-func; type is void (&)(int, double)
</code>```

So I expect the param to be a reference-to-function-type and call by it.
Whats wrong?

UPDATE: Looks like this is a Clang optimizer bug!
FIX: Evaluation of param's value BEFORE calling by it - fixes the situation!

```<code>std::cout << param << " - " << (*param)(3,5);
</code>```

答:
It seems to be a Clang optimizer bug!
FIX: Evaluation of param's value BEFORE calling by it - fixes the situation!</p>

```<code>std::cout << param << " - " << (*param)(3,5);
</code>```

Body:
I use a templated reference to capture a function by reference-to-function-type but it crashes when I try to call by param() (with Apple LLVM version 9.0.0 (clang-900.0.38), x86_64-apple-darwin17.2.0)

#include <iostream>
#include <typeinfo>

int doit(int a, int b) {
    return a+b;
}

template <typename T>
void test(T & param) {
    std::cout << typeid(T).name() << " ";
    std::cout << typeid(param).name() << " ";
    std::cout << param(3,5);
}

int main()
{
    test(doit);
}

But according to Scott Meyers book "Function types can decay into function pointers":

void someFunc(int, double); // someFunc is a function; type is void(int, double)

template<typename T>
void f1(T param);       // in f1, param passed by value

template<typename T>
void f2(T& param);      // in f2, param passed by ref

f1(someFunc);       // param deduced as ptr-to-func; type is void (*)(int, double)
f2(someFunc);       // param deduced as ref-to-func; type is void (&)(int, double)

So I expect the param to be a reference-to-function-type and call by it.
Whats wrong?

UPDATE: Looks like this is a Clang optimizer bug!
FIX: Evaluation of param's value BEFORE calling by it - fixes the situation!

std::cout << param << " - " << (*param)(3,5);

Body:
It seems to be a Clang optimizer bug!
FIX: Evaluation of param's value BEFORE calling by it - fixes the situation!

std::cout << param << " - " << (*param)(3,5);


问:
Unity framework DependencyAttribute only works for public properties?
I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties that I didn't really want exposed outside my DLLs to internal.  Then I started getting exceptions.

So it seems that using the [Dependency] attribute in Unity only works for public properties. I suppose that makes sense since the internal and private props wouldnt be visible to the Unity assembly, but feels really dirty to have a bunch of public properties that you never want anyone to set or be able to set, other than Unity.

Is there a way to let unity set internal or private properties too?

Here is the unit test I'd like to see pass. Currently only the public prop test passes:

```<code>    [TestFixture]
public class UnityFixture
{
    [Test]
    public void UnityCanSetPublicDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasPublicDep, HasPublicDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasPublicDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.dep);
    }

    [Test]
    public void UnityCanSetInternalDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasInternalDep, HasInternalDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasInternalDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.dep);
    }

    [Test]
    public void UnityCanSetPrivateDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasPrivateDep, HasPrivateDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasPrivateDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.depExposed);
    }
}

public class HasPublicDep
{
    [Dependency]
    public TheDep dep { get; set; }
}

public class HasInternalDep
{
    [Dependency]
    internal TheDep dep { get; set; }
}

public class HasPrivateDep
{
    [Dependency]
    private TheDep dep { get; set; }

    public TheDep depExposed
    {
        get { return this.dep; }
    }
}

public class TheDep
{
}
</code>```

Updated:

I noticed the call stack to set the property passed from:

```<code>UnityCanSetPublicDependency()
--> Microsoft.Practices.Unity.dll
--> Microsoft.Practices.ObjectBuilder2.dll
--> HasPublicDep.TheDep.set()
</code>```

So in an attempt to at least make the internal version work, I added these to my assembly's properties:

```<code>[assembly: InternalsVisibleTo("Microsoft.Practices.Unity")]
[assembly: InternalsVisibleTo("Microsoft.Practices.Unity.Configuration")]
[assembly: InternalsVisibleTo("Microsoft.Practices.ObjectBuilder2")]
</code>```

However, no change. Unity/ObjectBuilder still won't set the internal property

答:
If the property is get-only, it makes more sense to use contructor injection rather than property injection.

If Unity did use reflection to set private or internal members, it would be subjected to code access security constraints. Specifically, it wouldn't work in a low-trust environment.

Body:
I was trying to clean up some accessability stuff in my code, and inadvertently broke Unity dependency injection. After a while I realized that I marked some public properties that I didn't really want exposed outside my DLLs to internal.  Then I started getting exceptions.

So it seems that using the [Dependency] attribute in Unity only works for public properties. I suppose that makes sense since the internal and private props wouldnt be visible to the Unity assembly, but feels really dirty to have a bunch of public properties that you never want anyone to set or be able to set, other than Unity.

Is there a way to let unity set internal or private properties too?

Here is the unit test I'd like to see pass. Currently only the public prop test passes:

    [TestFixture]
public class UnityFixture
{
    [Test]
    public void UnityCanSetPublicDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasPublicDep, HasPublicDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasPublicDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.dep);
    }

    [Test]
    public void UnityCanSetInternalDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasInternalDep, HasInternalDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasInternalDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.dep);
    }

    [Test]
    public void UnityCanSetPrivateDependency()
    {
        UnityContainer container = new UnityContainer();
        container.RegisterType<HasPrivateDep, HasPrivateDep>();
        container.RegisterType<TheDep, TheDep>();

        var i = container.Resolve<HasPrivateDep>();
        Assert.IsNotNull(i);
        Assert.IsNotNull(i.depExposed);
    }
}

public class HasPublicDep
{
    [Dependency]
    public TheDep dep { get; set; }
}

public class HasInternalDep
{
    [Dependency]
    internal TheDep dep { get; set; }
}

public class HasPrivateDep
{
    [Dependency]
    private TheDep dep { get; set; }

    public TheDep depExposed
    {
        get { return this.dep; }
    }
}

public class TheDep
{
}

Updated:

I noticed the call stack to set the property passed from:

UnityCanSetPublicDependency()
--> Microsoft.Practices.Unity.dll
--> Microsoft.Practices.ObjectBuilder2.dll
--> HasPublicDep.TheDep.set()

So in an attempt to at least make the internal version work, I added these to my assembly's properties:

[assembly: InternalsVisibleTo("Microsoft.Practices.Unity")]
[assembly: InternalsVisibleTo("Microsoft.Practices.Unity.Configuration")]
[assembly: InternalsVisibleTo("Microsoft.Practices.ObjectBuilder2")]

However, no change. Unity/ObjectBuilder still won't set the internal property

OwnerDisplayName: Kent Boogaart

LastEditorDisplayName: Kent Boogaart


问:
declare myvar int(11); in mysql routine returns syntax error
I had a very long routine that used to work on a previous server.
I migrated it to a new server and I started having sql syntax error.

So I did a test:

```<code>create procedure test()
begin

declare myvar int(11);

select myvar;

end
</code>```

By running this in mysql or in Mysql Workbench you should have a syntax error at 11) just before the ;

What's going on!

I've looked at mysql references on the subject they say declare [variablename] [datatype]

I've tried with other data types just to make sure I still get the same problem.

thanks in advance for your help.

答:
When you declare variables you don't give them display lengths. Those numbers are meant for table column definitions only.

Just do

```<code>DECLARE myvar INT;
</code>```

Body:
I had a very long routine that used to work on a previous server.
I migrated it to a new server and I started having sql syntax error.

So I did a test:

create procedure test()
begin

declare myvar int(11);

select myvar;

end

By running this in mysql or in Mysql Workbench you should have a syntax error at 11) just before the ;

What's going on!

I've looked at mysql references on the subject they say declare [variablename] [datatype]

I've tried with other data types just to make sure I still get the same problem.

thanks in advance for your help.

Body:
When you declare variables you don't give them display lengths. Those numbers are meant for table column definitions only.

Just do

DECLARE myvar INT;


问:
cannot locate symbol __isnanf referenced by libsupportjni.so
When i run my application on devices with api 17 i see this exception:

```<code>Cannot load library: soinfo_relocate(linker.cpp:975): cannot locate symbol __isnanf referenced by libsupportjni.so

java.lang.ExceptionInInitializerError: at android.app.Application.<init>(Application.java:15)
</code>```

while this exception doesn't occur in higher api versions

答:
i found it.

this issue was an "advanced profiling" related problem.

i disabled it and it works!

Go to

Run -> Edit Configurations -> Profiling

, and uncheck "Enable advanced profiling"

Body:
When i run my application on devices with api 17 i see this exception:

Cannot load library: soinfo_relocate(linker.cpp:975): cannot locate symbol __isnanf referenced by libsupportjni.so

java.lang.ExceptionInInitializerError: at android.app.Application.<init>(Application.java:15)

while this exception doesn't occur in higher api versions


问:
How to change navigation page back button in xamarin forms
I am trying to change back arrow image in navigation page. For this in android app i created navigation page renderer and then using method toolbar.SetNavigationIcon and its not working, but when i use toolbar.SetLogo its working fine.

```<code>    protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
    {

        base.OnElementChanged(e);
        toolbar.SetNavigationIcon(Resource.Drawable.arrow);
        toolbar.SetLogo(Resource.Drawable.arrow);
    }
    public override void OnViewAdded(Android.Views.View child)
    {
        base.OnViewAdded(child);
        if (child.GetType() == typeof(Android.Support.V7.Widget.Toolbar))
        {
            toolbar = (Android.Support.V7.Widget.Toolbar)child;
            toolbar.ChildViewAdded += Toolbar_ChildViewAdded;
        }
    }
</code>```

I also tried add image to app:navigationIcon in toolbar.axml, and it shows great in designer
my arrow

But, when i starting my app i have the same standart arrow icon
enter image description here

答:
If your MainActivity is FormsApplicationActivity, you could refer to this example :

https://github.com/jessejiang0214/ChangeBackIconInXF/tree/master/Droid

If your MainActivity type is FormsAppCompatActivity, you could custom a PageRenderer and change the Toolbar's  NavigationIcon.

For example  :

```<code>[assembly: ExportRenderer(typeof(ContentPage), typeof(NavigationPageRendererDroid))]
...
public class NavigationPageRendererDroid : PageRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
    {
        base.OnElementChanged(e);

        var context = (Activity)Xamarin.Forms.Forms.Context;
        var toolbar = context.FindViewById<Android.Support.V7.Widget.Toolbar>(Droid.Resource.Id.toolbar);

        toolbar.NavigationIcon = Android.Support.V4.Content.ContextCompat.GetDrawable(context, Resource.Drawable.Back);
    }
}
</code>```

Usage :

```<code>MainPage = new NavigationPage(new MainPage());
...
//When click a button in MainPage, navigate to another page
private async void Button_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new TestPage());
}
</code>```

Effect.

Update :

When you use Navigation.PushAsync() method navigate to another page, the system will automatically update the Toolbar's icon, you could find in the source code :

```<code>protected virtual Task<bool> OnPushAsync(Page view, bool animated)
{
    return SwitchContentAsync(view, animated);
}

Task<bool> SwitchContentAsync(Page page, bool animated, bool removed = false, bool popToRoot = false)
{
    ...
    UpdateToolbar();
    ...
}

void UpdateToolbar()
{
    ...
    bool isNavigated = ((INavigationPageController)Element).StackDepth > 1;
    if (isNavigated)
    {
        ...
        if (NavigationPage.GetHasBackButton(Element.CurrentPage))
        {
             //Set the navigation back  icon < =================== !!! =-=
             var icon = new DrawerArrowDrawable(activity.SupportActionBar.ThemedContext);
             icon.Progress = 1;
             bar.NavigationIcon = icon;
        }
    }
    ...
}
</code>```

Solution :

So we have no choice but to custom a NavigationPageRenderer, override the OnPushAsync method to set the Toolbar's icon.

```<code>using AToolbar = Android.Support.V7.Widget.Toolbar;
[assembly: ExportRenderer(typeof(CustomNavigationPage), typeof(NavigationPageRendererDroid))] // APPCOMP
...
public class NavigationPageRendererDroid : Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer // APPCOMP
{
    public AToolbar toolbar;
    public Activity context;

    protected override Task<bool> OnPushAsync(Page view, bool animated)
    {
        var retVal = base.OnPushAsync(view, animated);

        context = (Activity)Xamarin.Forms.Forms.Context;
        toolbar = context.FindViewById<Android.Support.V7.Widget.Toolbar>(Droid.Resource.Id.toolbar);

        if (toolbar != null)
        {
            if (toolbar.NavigationIcon != null)
            {
                toolbar.NavigationIcon = Android.Support.V4.Content.ContextCompat.GetDrawable(context, Resource.Drawable.Back);
                //toolbar.SetNavigationIcon(Resource.Drawable.Back);
            }
        }
        return retVal;
    }
}
</code>```

The CustomNavigationPage are defined in PCL :

```<code>public class CustomNavigationPage : NavigationPage
{
    public CustomNavigationPage(Page startupPage) : base(startupPage)
    {
    }
}
</code>```

Usage :

```<code>public App()
{
    InitializeComponent();

    MainPage = new CustomNavigationPage(new MainPage());
}
...
// In MainPage
private async void Button_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new TestPage());
}
</code>```

Body:
I am trying to change back arrow image in navigation page. For this in android app i created navigation page renderer and then using method toolbar.SetNavigationIcon and its not working, but when i use toolbar.SetLogo its working fine.

    protected override void OnElementChanged(ElementChangedEventArgs<NavigationPage> e)
    {

        base.OnElementChanged(e);
        toolbar.SetNavigationIcon(Resource.Drawable.arrow);
        toolbar.SetLogo(Resource.Drawable.arrow);
    }
    public override void OnViewAdded(Android.Views.View child)
    {
        base.OnViewAdded(child);
        if (child.GetType() == typeof(Android.Support.V7.Widget.Toolbar))
        {
            toolbar = (Android.Support.V7.Widget.Toolbar)child;
            toolbar.ChildViewAdded += Toolbar_ChildViewAdded;
        }
    }

I also tried add image to app:navigationIcon in toolbar.axml, and it shows great in designer
my arrow

But, when i starting my app i have the same standart arrow icon
enter image description here

Body:
If your MainActivity is FormsApplicationActivity, you could refer to this example :

https://github.com/jessejiang0214/ChangeBackIconInXF/tree/master/Droid

If your MainActivity type is FormsAppCompatActivity, you could custom a PageRenderer and change the Toolbar's  NavigationIcon.

For example  :

[assembly: ExportRenderer(typeof(ContentPage), typeof(NavigationPageRendererDroid))]
...
public class NavigationPageRendererDroid : PageRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
    {
        base.OnElementChanged(e);

        var context = (Activity)Xamarin.Forms.Forms.Context;
        var toolbar = context.FindViewById<Android.Support.V7.Widget.Toolbar>(Droid.Resource.Id.toolbar);

        toolbar.NavigationIcon = Android.Support.V4.Content.ContextCompat.GetDrawable(context, Resource.Drawable.Back);
    }
}

Usage :

MainPage = new NavigationPage(new MainPage());
...
//When click a button in MainPage, navigate to another page
private async void Button_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new TestPage());
}

Effect.

Update :

When you use Navigation.PushAsync() method navigate to another page, the system will automatically update the Toolbar's icon, you could find in the source code :

protected virtual Task<bool> OnPushAsync(Page view, bool animated)
{
    return SwitchContentAsync(view, animated);
}

Task<bool> SwitchContentAsync(Page page, bool animated, bool removed = false, bool popToRoot = false)
{
    ...
    UpdateToolbar();
    ...
}

void UpdateToolbar()
{
    ...
    bool isNavigated = ((INavigationPageController)Element).StackDepth > 1;
    if (isNavigated)
    {
        ...
        if (NavigationPage.GetHasBackButton(Element.CurrentPage))
        {
             //Set the navigation back  icon < =================== !!! =-=
             var icon = new DrawerArrowDrawable(activity.SupportActionBar.ThemedContext);
             icon.Progress = 1;
             bar.NavigationIcon = icon;
        }
    }
    ...
}

Solution :

So we have no choice but to custom a NavigationPageRenderer, override the OnPushAsync method to set the Toolbar's icon.

using AToolbar = Android.Support.V7.Widget.Toolbar;
[assembly: ExportRenderer(typeof(CustomNavigationPage), typeof(NavigationPageRendererDroid))] // APPCOMP
...
public class NavigationPageRendererDroid : Xamarin.Forms.Platform.Android.AppCompat.NavigationPageRenderer // APPCOMP
{
    public AToolbar toolbar;
    public Activity context;

    protected override Task<bool> OnPushAsync(Page view, bool animated)
    {
        var retVal = base.OnPushAsync(view, animated);

        context = (Activity)Xamarin.Forms.Forms.Context;
        toolbar = context.FindViewById<Android.Support.V7.Widget.Toolbar>(Droid.Resource.Id.toolbar);

        if (toolbar != null)
        {
            if (toolbar.NavigationIcon != null)
            {
                toolbar.NavigationIcon = Android.Support.V4.Content.ContextCompat.GetDrawable(context, Resource.Drawable.Back);
                //toolbar.SetNavigationIcon(Resource.Drawable.Back);
            }
        }
        return retVal;
    }
}

The CustomNavigationPage are defined in PCL :

public class CustomNavigationPage : NavigationPage
{
    public CustomNavigationPage(Page startupPage) : base(startupPage)
    {
    }
}

Usage :

public App()
{
    InitializeComponent();

    MainPage = new CustomNavigationPage(new MainPage());
}
...
// In MainPage
private async void Button_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new TestPage());
}


问:
Form validation error message is overriding in javascript (only )

Hope, you all doing well.

I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.

I'm wondering why? Can anyone shed me some light please?

Here is my code:

// Predefined validator function to check if input is empty or not

var validator = {};
validator.isEmpty = function(input) {
    // Stop execution if input isn't string
    if (typeof input !== 'string') return false;

    if (input.length !== 0) {
        for (var i = 0; i < input.length; i++) {
            if (input[i] !== " ") {
                return false;
            }
            return true;
        }
    }
    return true;
};
validator.isEmpty(null); // returns false

// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName =  document.getElementById("fName");
var suButton = document.getElementById("subMit");

// Submit button on the function
suButton.addEventListener('click', function(event) {
    isNameValid(fName);
});

signUp.addEventListener('submit', function(event) {
     event.preventDefault();
});

function isNameValid(char) {
    var val = char.value;

    if (validator.isEmpty(val)) {
        if (val.length < 2) {
            // Display a message if input length is less than 2
            char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
            char.style.borderColor = "red";
        }

        if(!isNaN(val)) {
            char.setCustomValidity("Please, enter only characters");
            char.style.borderColor = "red";
        }

    } else {
        char.setCustomValidity("");
        char.style.borderColor = "green";
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="signUp">
    <input type="text" id="fName" name="firstname" placeholder="First name">
    <input type="checkbox" name="result"  required  autofocus> Agree our conditions
    <input type="submit" id='subMit' value="SUBMIT">
</form></code>```

答:
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.

```<code><script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
  var fNameValue = fNameElement.value;
  if(fNameValue.length < 2){
    msg = "We expect your input should contain at least 2 characters, darling !";
  }
  else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
    msg = "Please, enter only characters";
  }
  else{
    formValid = true;
  }
  if(formValid){
    fNameElement.style.borderColor="green";
    //do something
  }
  else{
    fNameElement.style.borderColor="red";
    alert(msg); // or show it in a div
  }
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
    <input type="text" id="fName" name="firstname" placeholder="First name">
    <input type="checkbox" name="result"  required  autofocus> Agree our conditions
    <input type="submit" id='subMit' value="SUBMIT">
 </form>
</code>```

Fiddle: https://jsfiddle.net/fxumcL3d/3/

Body:
Hope, you all doing well.

I am trying to validate firstname input field of a form with Javascript. For some reason, error messages doesn't display in order. Some of them override others, only just one error message is displaying, the rest is not.

I'm wondering why? Can anyone shed me some light please?

Here is my code:

// Predefined validator function to check if input is empty or not

var validator = {};
validator.isEmpty = function(input) {
    // Stop execution if input isn't string
    if (typeof input !== 'string') return false;

    if (input.length !== 0) {
        for (var i = 0; i < input.length; i++) {
            if (input[i] !== " ") {
                return false;
            }
            return true;
        }
    }
    return true;
};
validator.isEmpty(null); // returns false

// Main part to get inputs and apply validation
window.onload = function() {
var signUp = document.getElementById("signUp");
var fName =  document.getElementById("fName");
var suButton = document.getElementById("subMit");

// Submit button on the function
suButton.addEventListener('click', function(event) {
    isNameValid(fName);
});

signUp.addEventListener('submit', function(event) {
     event.preventDefault();
});

function isNameValid(char) {
    var val = char.value;

    if (validator.isEmpty(val)) {
        if (val.length < 2) {
            // Display a message if input length is less than 2
            char.setCustomValidity("We expect your input should contain at least 2 characters, darling !");
            char.style.borderColor = "red";
        }

        if(!isNaN(val)) {
            char.setCustomValidity("Please, enter only characters");
            char.style.borderColor = "red";
        }

    } else {
        char.setCustomValidity("");
        char.style.borderColor = "green";
    }
}

<form id="signUp">
    <input type="text" id="fName" name="firstname" placeholder="First name">
    <input type="checkbox" name="result"  required  autofocus> Agree our conditions
    <input type="submit" id='subMit' value="SUBMIT">
</form>

Body:
It took me a while but I hope following works for you. Let me know if you need help understanding anything. I felt your code was a bit complex so I simplified it.

<script>
function submitForm(){
var formValid = false;
var msg = "";
var fNameElement = document.getElementById("fName");
if(fNameElement){
  var fNameValue = fNameElement.value;
  if(fNameValue.length < 2){
    msg = "We expect your input should contain at least 2 characters, darling !";
  }
  else if(!(/^[a-zA-Z]+$/.test(fNameValue))){
    msg = "Please, enter only characters";
  }
  else{
    formValid = true;
  }
  if(formValid){
    fNameElement.style.borderColor="green";
    //do something
  }
  else{
    fNameElement.style.borderColor="red";
    alert(msg); // or show it in a div
  }
}
}
</script>
<form id="signUp" action="javascript:submitForm()">
    <input type="text" id="fName" name="firstname" placeholder="First name">
    <input type="checkbox" name="result"  required  autofocus> Agree our conditions
    <input type="submit" id='subMit' value="SUBMIT">
 </form>

Fiddle: https://jsfiddle.net/fxumcL3d/3/


问:
Multiple gridviews to single pdf using iTextsharp
I am trying to export multiple gridviews into single pdf using iTextSharp. I am looping through the gridviews and then looping through the rows of the gridview. The looping is going ok. But after pdf download, only the last gridview can be seen. It seems the gridviews are overwriting each other and only last one remains. Here is my code. What am I doing wrong?</p>

```<code>protected void btnExportToPDF_Click(object sender, EventArgs e)
        {
            GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

            for (int i = 0; i < gvExcel.Length; i++)
            {
                if (gvExcel[i].Visible)
                {

                    PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);

                    foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
                    {
                        Font font = new Font();
                        font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                        PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
                        pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                        pdfTbl.AddCell(pdfCell);
                    }

                    foreach (GridViewRow gvRow in gvExcel[i].Rows)
                    {
                        foreach (TableCell tblCell in gvRow.Cells)
                        {
                            Font font = new Font();
                            font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                            PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
                            pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                            pdfTbl.AddCell(pdfCell);
                        }
                    }

                    //Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                    pdfDoc.Open();
                    pdfDoc.Add(pdfTbl);
                }
            }

            pdfDoc.Close();

            //Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
            Response.Write(pdfDoc);
            Response.Flush();
            Response.End();
        }
</code>```

答:
One of your errors is not an iText error; it's is a simple logical error that can be solved with common sense. The other error is weird. You aren't using the Response correctly.

```<code>protected void btnExportToPDF_Click(object sender, EventArgs e)
    {
        GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
        MemoryStream ms = new MemoryStream();
        PdfWriter.GetInstance(pdfDoc, ms);
        pdfDoc.Open();

        for (int i = 0; i < gvExcel.Length; i++)
        {
            if (gvExcel[i].Visible)
            {

                PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);
                pdfTbl.SpacingAfter = 20f;

                foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
                {
                    Font font = new Font();
                    font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                    PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
                    pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                    pdfTbl.AddCell(pdfCell);
                }

                foreach (GridViewRow gvRow in gvExcel[i].Rows)
                {
                    foreach (TableCell tblCell in gvRow.Cells)
                    {
                        Font font = new Font();
                        font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                        PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
                        pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                        pdfTbl.AddCell(pdfCell);
                    }
                }
                pdfDoc.Add(pdfTbl);
            }
        }

        pdfDoc.Close();

        byte[] content = ms.ToArray();
        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
        Response.BinaryWrite(content);
        Response.Flush();
        Response.End();
    }
</code>```

There might be some other issues, but I hope you understand the logical error:

You created a new PDF file with PdfWriter every time you entered the loop. You should only create one PdfWriter instance if you only want to create one PDF.

It's better to create the PDF in a MemoryStream, and then write the content of that stream to the Response object as a binary stream. I really didn't understand what you were doing there (and why you tried to do it that way).

I also introduced a SpacingAfter of 20 user units, otherwise it will look as if all tables all glued together into one big table.

There may still be some errors in the way you send the file to the Response, but this should already get you on your way. (Why aren't you sending the file size to the browser? You know that size, don't you? It's the number of bytes in the content object.)

Body:
I am trying to export multiple gridviews into single pdf using iTextSharp. I am looping through the gridviews and then looping through the rows of the gridview. The looping is going ok. But after pdf download, only the last gridview can be seen. It seems the gridviews are overwriting each other and only last one remains. Here is my code. What am I doing wrong?

protected void btnExportToPDF_Click(object sender, EventArgs e)
        {
            GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);

            for (int i = 0; i < gvExcel.Length; i++)
            {
                if (gvExcel[i].Visible)
                {

                    PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);

                    foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
                    {
                        Font font = new Font();
                        font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                        PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
                        pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                        pdfTbl.AddCell(pdfCell);
                    }

                    foreach (GridViewRow gvRow in gvExcel[i].Rows)
                    {
                        foreach (TableCell tblCell in gvRow.Cells)
                        {
                            Font font = new Font();
                            font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                            PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
                            pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                            pdfTbl.AddCell(pdfCell);
                        }
                    }

                    //Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
                    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                    pdfDoc.Open();
                    pdfDoc.Add(pdfTbl);
                }
            }

            pdfDoc.Close();

            //Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
            Response.Write(pdfDoc);
            Response.Flush();
            Response.End();
        }

Body:
One of your errors is not an iText error; it's is a simple logical error that can be solved with common sense. The other error is weird. You aren't using the Response correctly.

protected void btnExportToPDF_Click(object sender, EventArgs e)
    {
        GridView[] gvExcel = new GridView[] { gridvw1,gridvw2,gridvw3 };
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
        MemoryStream ms = new MemoryStream();
        PdfWriter.GetInstance(pdfDoc, ms);
        pdfDoc.Open();

        for (int i = 0; i < gvExcel.Length; i++)
        {
            if (gvExcel[i].Visible)
            {

                PdfPTable pdfTbl = new PdfPTable(gvExcel[i].HeaderRow.Cells.Count);
                pdfTbl.SpacingAfter = 20f;

                foreach (TableCell headerTblCell in gvExcel[i].HeaderRow.Cells)
                {
                    Font font = new Font();
                    font.Color = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                    PdfPCell pdfCell = new PdfPCell(new Phrase(headerTblCell.Text));
                    pdfCell.BackgroundColor = new BaseColor(gvExcel[i].HeaderStyle.ForeColor);
                    pdfTbl.AddCell(pdfCell);
                }

                foreach (GridViewRow gvRow in gvExcel[i].Rows)
                {
                    foreach (TableCell tblCell in gvRow.Cells)
                    {
                        Font font = new Font();
                        font.Color = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                        PdfPCell pdfCell = new PdfPCell(new Phrase(tblCell.Text));
                        pdfCell.BackgroundColor = new BaseColor(gvExcel[i].RowStyle.ForeColor);
                        pdfTbl.AddCell(pdfCell);
                    }
                }
                pdfDoc.Add(pdfTbl);
            }
        }

        pdfDoc.Close();

        byte[] content = ms.ToArray();
        Response.ContentType = "application/pdf";
        Response.AppendHeader("content-disposition", "attachment;filename=report_" + startDate + "-" + endDate + ".pdf");
        Response.BinaryWrite(content);
        Response.Flush();
        Response.End();
    }

There might be some other issues, but I hope you understand the logical error:

You created a new PDF file with PdfWriter every time you entered the loop. You should only create one PdfWriter instance if you only want to create one PDF.

It's better to create the PDF in a MemoryStream, and then write the content of that stream to the Response object as a binary stream. I really didn't understand what you were doing there (and why you tried to do it that way).

I also introduced a SpacingAfter of 20 user units, otherwise it will look as if all tables all glued together into one big table.

There may still be some errors in the way you send the file to the Response, but this should already get you on your way. (Why aren't you sending the file size to the browser? You know that size, don't you? It's the number of bytes in the content object.)


问:
Can I instantiate TypeScript classes via proxy?
Note: I have updated the question to hopefully make things clearer.

I am trying to instantiate classes through a proxy object called elemTypes. This object is a list of references to classes that I want to use to programmatically build objects based on a DOM-like tree structure. I am very new to TypeScript, so I'm hoping that I am just missing something simple here?

Here is the code:

```<code>type elemDef = {
    type: string,
    name: string,
    childNodes: object[]
}

class Elem {
    childNodes: object[]
    constructor (childNodes: object[]) {
        this.childNodes = childNodes
    }
}

class Div extends Elem {
    constructor (childNodes: object[]) {
        super(childNodes)
    }
}

class Form extends Elem {
    constructor (childNodes: object[]) {
        super(childNodes)
    }
}

class Input extends Elem {
    name: string
    constructor (childNodes: object[], nodeDef: elemDef) {
        super(childNodes)
        this.name = nodeDef.name
    }
}

const div = {
    type: 'Div',
    childNodes: [
        {
            type: 'Form',
            childNodes: [
                {
                    type: 'Input',
                    name: 'username',
                    childNodes: []
                },
                {
                    type: 'Input',
                    name: 'password',
                    childNodes: []
                },
            ]
        }
    ]
}

// I expect that I am doing this part wrong:
const elemTypes = {
    Div,
    Form,
    Input
}

const makeElem = (nodeDef: elemDef) => {
    const childNodes:object[] = []

    nodeDef.childNodes.forEach((childNodeDef: object): void => {
        const element = new elemTypes[childNodeDef.type](childNodeDef)
        childNodes.push(element)
    })

    const element = new elemTypes[nodeDef.type](nodeDef)

    return element
}

// This line just demonstrates that the code is working:
console.log(JSON.stringify(makeElem(div), null, 2))
</code>```

The output of the line above is:

```<code>{
  "childNodes": {
    "type": "Div",
    "childNodes": [
      {
        "type": "Form",
        "childNodes": [
          {
            "type": "Input",
            "name": "username",
            "childNodes": []
          },
          {
            "type": "Input",
            "name": "password",
            "childNodes": []
          }
        ]
      }
    ]
  }
}
</code>```

The issue I am having, is that SublimeText 3 is giving me this error:

```<code>Element implicity has a type 'any' type because the type
'{ Div: typeof Div; Form: typeof Form; Input: typeof Input };
 has no index signature;
</code>```

I have tried figuring this out by reading the TypeScript documentation and looking at some StackOverflow answers on similar questions, but I can not seem to find out what I am doing wrong here.

But does anyone know if there is a way to define the meta object that will stop be having this implicit any error in my IDE? (Note: I do not want to turn implicit errors off in my .ts-config.js file.)

I do not want to turn off implicit any rule in my ts-config.

Any ideas appreciated.

答:
Not entirely sure, but maybe you can try something like this and see if it helps?</p>

```<code>const proxy: {person: Being} = {
    person: Being
}
</code>```

Body:
Note: I have updated the question to hopefully make things clearer.

I am trying to instantiate classes through a proxy object called elemTypes. This object is a list of references to classes that I want to use to programmatically build objects based on a DOM-like tree structure. I am very new to TypeScript, so I'm hoping that I am just missing something simple here?

Here is the code:

type elemDef = {
    type: string,
    name: string,
    childNodes: object[]
}

class Elem {
    childNodes: object[]
    constructor (childNodes: object[]) {
        this.childNodes = childNodes
    }
}

class Div extends Elem {
    constructor (childNodes: object[]) {
        super(childNodes)
    }
}

class Form extends Elem {
    constructor (childNodes: object[]) {
        super(childNodes)
    }
}

class Input extends Elem {
    name: string
    constructor (childNodes: object[], nodeDef: elemDef) {
        super(childNodes)
        this.name = nodeDef.name
    }
}

const div = {
    type: 'Div',
    childNodes: [
        {
            type: 'Form',
            childNodes: [
                {
                    type: 'Input',
                    name: 'username',
                    childNodes: []
                },
                {
                    type: 'Input',
                    name: 'password',
                    childNodes: []
                },
            ]
        }
    ]
}

// I expect that I am doing this part wrong:
const elemTypes = {
    Div,
    Form,
    Input
}

const makeElem = (nodeDef: elemDef) => {
    const childNodes:object[] = []

    nodeDef.childNodes.forEach((childNodeDef: object): void => {
        const element = new elemTypes[childNodeDef.type](childNodeDef)
        childNodes.push(element)
    })

    const element = new elemTypes[nodeDef.type](nodeDef)

    return element
}

// This line just demonstrates that the code is working:
console.log(JSON.stringify(makeElem(div), null, 2))

The output of the line above is:

{
  "childNodes": {
    "type": "Div",
    "childNodes": [
      {
        "type": "Form",
        "childNodes": [
          {
            "type": "Input",
            "name": "username",
            "childNodes": []
          },
          {
            "type": "Input",
            "name": "password",
            "childNodes": []
          }
        ]
      }
    ]
  }
}

The issue I am having, is that SublimeText 3 is giving me this error:

Element implicity has a type 'any' type because the type
'{ Div: typeof Div; Form: typeof Form; Input: typeof Input };
 has no index signature;

I have tried figuring this out by reading the TypeScript documentation and looking at some StackOverflow answers on similar questions, but I can not seem to find out what I am doing wrong here.

But does anyone know if there is a way to define the meta object that will stop be having this implicit any error in my IDE? (Note: I do not want to turn implicit errors off in my .ts-config.js file.)

I do not want to turn off implicit any rule in my ts-config.

Any ideas appreciated.

Body:
Not entirely sure, but maybe you can try something like this and see if it helps?

const proxy: {person: Being} = {
    person: Being
}


问:
How to change the displayed title of a soft keyboard in iOS?
Here's how my soft keyboard's title is currently displayed among the keyboard choices in iOS:

I'd prefer for it to be displayed like the Gboard example above it, simply as "ASETNIOP" on the top line and "Multiple languages" below, as shown in the mockup here:

I can change the lowercased prefix if I modify the extension's "Display Name" in Target->General->Identity, but I can't eliminate it (or the associated dash) entirely:

And (although I don't actually need to do this) it doesn't look like it's possible to change the main application's Display Name at all - it's grayed out:

Can anyone let me know where I need to go to make these changes, and where I need to go to change the Language designation as well?

答:
The name of the keyboard application extension (or appex) iOS displays in the menu under "Globe" button is taken from the Keyboard appex's metadata. In your case this is asentitop target. So, check/apply the following for this target:

Go to the target's Info.plist and change the following keys.

```<code><key>CFBundleDisplayName</key>
    <string>ASETNIOP</string>
<key>CFBundleName</key>
    <string>ASETNIOP</string>
</code>```

Advanced setup would employ localization for your custom keyboard extension display name.

Go to your Xcode project and select your keyboard extension target

Go to General tab and set Display Name to ${PRODUCT_NAME}

Go to Info tab and set CFBundleName to ${PRODUCT_NAME}

Make sure CFBundleDisplayName is set to ${PRODUCT_NAME}

Now, this setup allows you to set the Keyboard appex's name from a single place -- Build Settings tab

Go to Build Settings tab and search for PRODUCT_NAME. Edit Product Name to be ASETNIOP

Localize Info.plist and add these keys to respective localizations:

```<code>"CFBundleDisplayName" ="ASETNIOP";
"CFBundleName" = "ASETNIOP";
</code>```

Body:
The name of the keyboard application extension (or appex) iOS displays in the menu under "Globe" button is taken from the Keyboard appex's metadata. In your case this is asentitop target. So, check/apply the following for this target:

Go to the target's Info.plist and change the following keys.

<key>CFBundleDisplayName</key>
    <string>ASETNIOP</string>
<key>CFBundleName</key>
    <string>ASETNIOP</string>

Advanced setup would employ localization for your custom keyboard extension display name.

Go to your Xcode project and select your keyboard extension target

Go to General tab and set Display Name to ${PRODUCT_NAME}

Go to Info tab and set CFBundleName to ${PRODUCT_NAME}

Make sure CFBundleDisplayName is set to ${PRODUCT_NAME}

Now, this setup allows you to set the Keyboard appex's name from a single place -- Build Settings tab

Go to Build Settings tab and search for PRODUCT_NAME. Edit Product Name to be ASETNIOP

Localize Info.plist and add these keys to respective localizations:

"CFBundleDisplayName" ="ASETNIOP";
"CFBundleName" = "ASETNIOP";


问:
Vectorizing Array of Values indexing another array
I am trying to vectorize the code below.

```<code> for x in range (0, 500):
      S = rand.choice(np.unique(Y))
      A = rand.choice(np.unique(X[Y==S]))
</code>```

Y and X are arrays where the values in the indices need to match.

Currently I modified S to be

```<code> S = np.random.choice(np.unique(Y),size=500)
</code>```

However, I'm not able to figure out how to index through X with an array of values S

An example for size = 5 could be

```<code> Y = [0,0,2,3,2,4]
 X = [1,2,1,3,4,2]

 S = [0,2,0,3,2]
 X[Y==S] => ([1,2],[1,4],[1,2],[3],[1,4])  <=  Not sure how to get this
 A = [2,4,1,3,1]
</code>```

Is there a simple way to do this?

答:
A little clumsy, but if you can use Pandas, combine isin() with a list comprehension:

```<code>import numpy as np
import pandas as pd

Y = pd.Series([0,0,2,3,2,4])
X = pd.Series([1,2,1,3,4,2])
S = pd.Series([0,2,0,3,2])

[np.random.choice(X[Y.isin([s])].values) for s in S]
</code>```

You can get X[Y==S] with: [X[Y.isin([s])].values for s in S]

Body:
I am trying to vectorize the code below.

 for x in range (0, 500):
      S = rand.choice(np.unique(Y))
      A = rand.choice(np.unique(X[Y==S]))

Y and X are arrays where the values in the indices need to match.

Currently I modified S to be

 S = np.random.choice(np.unique(Y),size=500)

However, I'm not able to figure out how to index through X with an array of values S

An example for size = 5 could be

 Y = [0,0,2,3,2,4]
 X = [1,2,1,3,4,2]

 S = [0,2,0,3,2]
 X[Y==S] => ([1,2],[1,4],[1,2],[3],[1,4])  <=  Not sure how to get this
 A = [2,4,1,3,1]

Is there a simple way to do this?

Body:
A little clumsy, but if you can use Pandas, combine isin() with a list comprehension:

import numpy as np
import pandas as pd

Y = pd.Series([0,0,2,3,2,4])
X = pd.Series([1,2,1,3,4,2])
S = pd.Series([0,2,0,3,2])

[np.random.choice(X[Y.isin([s])].values) for s in S]

You can get X[Y==S] with: [X[Y.isin([s])].values for s in S]


问:
How to expand this floating elements to auto-fill the clearfix div
In an assignment, I'm trying to replicate this picture given by the teacher with html and css, but only got this picture  despite trying my best.

How can I make the aside auot-fill the space nicely?

My html:

```<code><div class="clearfix">
  <section>...</section>
  <aside>...</aside>
</div>
</code>```

My CSS:

```<code>section, aside {
  float: left;
}

section {
  width: 55%;
}

aside {
  ?
}
</code>```

答:
Is this what you're trying to achieve? Apologies if I missed something. All I did was manually adjust the height, so

```<code>        #aside {
            width: 43%;
            float: right;
            height: 222px;
        }
</code>```

See my attempt

Body:
In an assignment, I'm trying to replicate this picture given by the teacher with html and css, but only got this picture  despite trying my best.

How can I make the aside auot-fill the space nicely?

My html:

...

  ...

My CSS:

section, aside {
  float: left;
}

section {
  width: 55%;
}

aside {
  ?
}

Body:
Is this what you're trying to achieve? Apologies if I missed something. All I did was manually adjust the height, so

        #aside {
            width: 43%;
            float: right;
            height: 222px;
        }

See my attempt