问:
Insert value referencing another field
After creating a table like this:

```<code>CREATE TABLE T1 (
    C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
    C2 INTEGER);
</code>```

I would like to insert in C2 the same value of C1:

```<code>INSERT INTO T1(C1, C2) VALUES (DEFAULT, C1)
</code>```

I could only do something that resembles this by introducing a sequence, is there a more straightforward way?

答:
I don't have a solution for this, as at the time the insert is happening, the auto generated value might not even be available yet.  But, one workaround at the data layer which you could use might be to just insert NULL values into C2 whenever you want them to just reflect the value in C1.  That is, use this insert for these cases:

```<code>INSERT INTO T1 (C2)
VALUES (NULL);
</code>```

Then, when you select, use COALESCE to report the C1 value for C2:

```<code>SELECT C1, COALESCE(C2, C1) AS C2
FROM T1;
</code>```

Title: Insert value referencing another field

Body:
After creating a table like this:

CREATE TABLE T1 (
    C1 INTEGER GENERATED ALWAYS AS IDENTITY (START WITH 1) PRIMARY KEY,
    C2 INTEGER);

I would like to insert in C2 the same value of C1:

INSERT INTO T1(C1, C2) VALUES (DEFAULT, C1)

I could only do something that resembles this by introducing a sequence, is there a more straightforward way?

Body:
I don't have a solution for this, as at the time the insert is happening, the auto generated value might not even be available yet.  But, one workaround at the data layer which you could use might be to just insert NULL values into C2 whenever you want them to just reflect the value in C1.  That is, use this insert for these cases:

INSERT INTO T1 (C2)
VALUES (NULL);

Then, when you select, use COALESCE to report the C1 value for C2:

SELECT C1, COALESCE(C2, C1) AS C2
FROM T1;


来源: stackexchange

问:
How to store meta data about a collection in Firestore?
I see it quite often I come across this problem about storing some meta additional information about a collection.

Is there any way on Firestore to save some meta information in a collection? Like what this collection is maintained for or some other custom properties.

For example : When saving leaderboard scores, if we need to know if the scores need to be sorted ascending or descending when queried, its good if we store this info in the collection.

Else, we need to go for extra reads when ever we need the to sort the scores. Can any one suggest?

答:
As explained in the documentation:

Following Cloud Firestore's NoSQL data model, you store data in
  documents that contain fields mapping to values. These documents are
  stored in collections, which are containers for your documents that
  you can use to organize your data and build queries.

In other words, the "data container" in Firestore is the Document. Collections are only Document containers and cannot hold data (i.e. "fields mapping to values").

So if you want to store extra information on a specific Collection (i.e. metadata) you will have to do that in a Document. And yes, it will require an extra read to query the Document containing these metadata.

ContentLicense: CC BY-SA 4.0


问:
Why does Thread.Sleep(0) fix my problems, and how to avoid it?
I'm working on a client server application.  At certain times, on certain machines, when there's more than 5 clients requesting data, it seems to reach a deadlock.  If I step in to debug the problem, then the program appears to be processing.  Simply setting a break point where I know the program is executing, and causing it to hit the breakpoint a few times causes it to finish. If I insert Thread.Sleep(0) at certain points in the code, mostly around some cpu intensive loops, it seems to pretty much totally resolve the problem.  The one problem that I have now is that if I call Thread.Sleep(0) too much, it can slow down the code.  If I don't call it enough, the code seems to be in deadlock.  Although I can verify that it isn't in deadlock because if I step into the code, it causes the problem to disappear, simply because I'm pausing a thread.

Is there a good way to track down exactly what is causing this.  It seems that it only happens on my laptop which is running Vista, but not on my desktop which is running Windows XP.  However, it's impossible to debug, because simply stepping into the code causes the problem to go away.  I've read comments that calling Thread.Sleep(0) is a bad practice, and shouldn't be necessary, and I don't like putting witchcraft type code into my applications that I don't understand why it has to be there.  Any pointers would be greatly appreciated.

[EDIT]
I can also verify that the code is still running when it is "deadlocked" because if I leave it long enough, it will finish, only the amount of time it takes is many orders of magnitude higher.  I mean like it's actually at least 100 times slower when it's in this "deadlocked" mode.  The CPU is pegged at 80-95%, so it is working, altough what it is doing is beyond me, because it's taking forever to complete the task.

[More Info]
Just because everybody here is insistent that it's a deadlock, I removed all the code that did any locking. There was only a couple lines of code that did any locking whatsoever. The threads work completely independantly for the most part, so it wasn't much work to remove the locking completely.  Still the problem persists.  There is no more synclocks in my code, no more mutex's no more stuff that I see see that would cause a deadlock, but the problem is still there.  And it's not deadlocked.  It runs, albeit very slowly, even though it's eating up all the processor resources.

答:
How many simultaneous threads are running when it bogs down?
If you have too many threads, the CPU could be spending all of its time doing context switching.  Plus, you would be chewing through 1+ MB of memory per thread.</p>

OwnerDisplayName: Kibbee

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Kibbee


问:
In a layered architecture using Entity Framework, should I return POCO classes from the BLL? (Architecture guidance needed)
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

```<code>public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}
</code>```

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.

答:
Answers to your questions may depend on the size and complexity of your application. So I am afraid there will be valid arguments to answer your questions with Yes and No as well.

Personally I will answer your two main questions both with Yes:

Is it acceptable practice to use POCO (Domain) classes in the UI layer?

I guess with "UI layer" you don't actually mean the View part of the MVVM pattern but the ViewModels. (Most MVVM specialists would argue against letting a View directly reference the Model at all, I believe.)

It is not unusual to wrap a POCO from your Domain project as a property into a ViewModel and to bind this wrapped POCO directly to the View. The big Pro is: It's easy. You don't need additional ViewModel classes or replicated properties in a ViewModel and then copy those properties between the objects.

However, if you are using WPF you must take into account that the binding engine will directly write into your POCO properties if you bind them to a View. This might not always be what you want, especially if you are working with attached and change-tracked entities in a WPF form. You have to think about cancellation scenarios or how you restore properties after a cancellation which have been changed by the binding engine.

In my current project I am working with detached entities: I load the POCO from the data layer, detach it from context, dispose the context and then work with that copy in the ViewModel and bind it to the View. Updating in the data layer happens by creating a new context, loading the original entity from the DB by ID and then updating the properties from the changed POCO which was bound to the View. So the problem of unwished changes of an attached entity disappears with this approach. But there are also downsides to work with detached entites (updating is more complex for instance).

Is it okay if I implement the IDataErrorInfo interface on the generated POCO class?

If you bind your POCO entities to a View (through a wrapping ViewModel) it is not only OK but you even must implement IDataErrorInfo on the POCO class if you want to leverage the built-in property validation of the WPF binding engine. Although this interface is mainly used together with UI technologies it is part of System.ComponentModel namespace and therefore not directly tied to any UI namespaces. Basically IDataErrorInfo is only a simple contract which supports reporting of the object's state which also might be useful outside of a UI context.

The same is true for the INotifyPropertyChanged interface which you also would need to implement on your POCO classes if you bind them directly to a View.

I often see opinions which would disagree with me for several architectural reasons. But none of those opinions argue that another approach is easier. If you strictly would want to avoid to have POCO model classes in your ViewModel layer, you need to add another mapping layer with additional complexity and programming and maintenance effort. So I would vote: Keep it simple as long as you do not have a convincing reason and clear benefit to make your architecture more complex.

ContentLicense: CC BY-SA 3.0

Body:
I've been reading too much probably and am suffering from some information overload. So I would appreciate some explicit guidance.

From what I've gathered, I can use VS2010's T4 template thingy to generate POCO classes that aren't tied directly to the EF. I would place these in their own project while my DAL would have an ObjectContext-derived class, right?

Once I have these classes, is it acceptable practice to use them in the UI layer? That is, say one of the generated classes is BookInfo that holds stuff about books for a public library (Title, edition, pages, summary etc.).

My BLL would contain a class BooksBLL for example like so:

public class BooksBLL
{
    ObjectContext _context;

    public void AddBook(BookInfo book) { ... }
    public void DeleteBook(int bookID) { ... }
    public void UpdateBook(int bookID, BookInfo newBook) { ... }

    //Advanced search taking possibly all fields into consideration
    public List<BookInfo> ResolveSearch(Func<BookInfo, bool> filter) { ... }

    //etc...
}

So, my ViewModels in my MVVM UI app will be communicating with the above BLL class and exchanging BookInfo instances. Is that okay?

Furthermore, MVVM posts on the Web suggest implementing IDataErrorInfo for validation purposes. Is it okay if I implement said interface on the generated POCO class? I see from samples that those generated POCO classes contain all virtual properties and stuf and I hope adding my own logic would be okay?

If it makes any difference, at present, my app does not use WCF (or any networking stuff).

Also, if you see something terribly wrong with the way I'm trying to build my BLL, please feel free to offer help in that area too.

Update (Additional info as requested):

I'm trying to create a library automation application. It is not network based at present.

I am thinking about having layers as follows:

A project consisting of generated POCO classes (BookInfo, Author, Member, Publisher,  Contact etc.)

A project with the ObjectContext-derived class (DAL?)

A Business Logic Layer with classes like the one I mentioned above (BooksBLL, AuthorsBLL etc)

A WPF UI layer using the MVVM pattern. (Hence my sub-question about IDataErrorInfo implementation).

So I'm wondering about stuff like using an instance of BooksBLL in a ViewModel class, calling ResolveSearch() on it to obtain a List<BookInfo> and presenting it... that is, using the POCO classes everywhere.

Or should I have additional classes that mirror the POCO classes exposed from my BLL?

If any more detail is needed, please ask.


问:
Trying to calculate user whos spent the most and the least - Excel
I have a spreadsheet of user transactions and naturally some users will have one or more transactions. My objective is to add up the total(spent) of each user ( not necessary display it  )and display the user whos spent the most and spent the least.

I cannot use a pivot table and if you can show me the formula with the simple table below that would be very helpful.

I have tried the max and averageIF functions, but I can't get the code to work. This is just a sample table but concept will apply.

UserID      |  Amount

```<code>1     |      122
2     |      400
3     |      122
1     |      300
4     |      400
5     |      100
2     |      50
1     |      600
3     |      400
2     |      320
</code>```

So the end result will be User with Max spend  = 1 and Min spend = 5

答:
This works for me in Excel 2013. They are array formulas so you have to press ctrl+shift+enter to input them. This assumes column A is your ID and column B is your amount.</p>

```<code>=INDEX($A$1:$A$10,MATCH(MAX(SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10)),SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10),0))

=INDEX($A$1:$A$10,MATCH(MIN(SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10)),SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10),0))
</code>```

Body:
I have a spreadsheet of user transactions and naturally some users will have one or more transactions. My objective is to add up the total(spent) of each user ( not necessary display it  )and display the user whos spent the most and spent the least.

I cannot use a pivot table and if you can show me the formula with the simple table below that would be very helpful.

I have tried the max and averageIF functions, but I can't get the code to work. This is just a sample table but concept will apply.

UserID      |  Amount

1     |      122
2     |      400
3     |      122
1     |      300
4     |      400
5     |      100
2     |      50
1     |      600
3     |      400
2     |      320

So the end result will be User with Max spend  = 1 and Min spend = 5

Body:
This works for me in Excel 2013. They are array formulas so you have to press ctrl+shift+enter to input them. This assumes column A is your ID and column B is your amount.

=INDEX($A$1:$A$10,MATCH(MAX(SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10)),SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10),0))

=INDEX($A$1:$A$10,MATCH(MIN(SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10)),SUMIF($A$1:$A$10,A1:A10,$B$1:$B$10),0))


问:
Fastest way to compute a function on the patches of two images
I have two equal sized images and I want to compute a function lets suppose f on the patches of the images and calculate one number at each image location

The patch extraction is easy

```<code>   patches1 = image.extract_patches_2d(img1,(5,5))
   patches2 = image.extract_patches_2d(img2,(5,5))
</code>```

Now applying the function could be something like as follows

```<code>   result = numpy.zeros((image1.shape[0], img1.shape[1]))
   for i in range(len(image1.shape[0])):
       for j in range(len(image1.shape[1])):
           result[i,j] = f(patches1[i], patches1[j])
</code>```

But this is very slow!!!

I am wondering that what could be the best possible way to calculate it fast and get rid of the loops.

Thanks

EDIT1:

The implementation of f is

```<code>    def f (patch1, patch2):
        return np.sqrt(patch1^2 + patch2^2)
</code>```

答:
You can make it fast using multiprocessing:

```<code>from concurrent import futures
import itertools
import numpy as np

patches1 = image.extract_patches_2d(img1,(5,5))
H = image.shape[0]; W = image.shape[1]
results = np.zeros(H*W)
with futures.ProcessPoolExecutor(max_workers=8) as exe:
    procs = {exe.submit(f, patches1[i], patches1[j]): i*W+j for (i,j) in itertools.product(range(H), range(W))}
    for r in futures.as_completed(procs):
        ids = procs[r]
        val = r.result()
        results[ids] = val
results = np.reshape(results,(H,W))
</code>```

There may be a smarter way to do this by optimizing f to work on whole image instead of patches1. Here I show an engineering way only.

Body:
I have two equal sized images and I want to compute a function lets suppose f on the patches of the images and calculate one number at each image location

The patch extraction is easy

   patches1 = image.extract_patches_2d(img1,(5,5))
   patches2 = image.extract_patches_2d(img2,(5,5))

Now applying the function could be something like as follows

   result = numpy.zeros((image1.shape[0], img1.shape[1]))
   for i in range(len(image1.shape[0])):
       for j in range(len(image1.shape[1])):
           result[i,j] = f(patches1[i], patches1[j])

But this is very slow!!!

I am wondering that what could be the best possible way to calculate it fast and get rid of the loops.

Thanks

EDIT1:

The implementation of f is

    def f (patch1, patch2):
        return np.sqrt(patch1^2 + patch2^2)

Body:
You can make it fast using multiprocessing:

from concurrent import futures
import itertools
import numpy as np

patches1 = image.extract_patches_2d(img1,(5,5))
H = image.shape[0]; W = image.shape[1]
results = np.zeros(H*W)
with futures.ProcessPoolExecutor(max_workers=8) as exe:
    procs = {exe.submit(f, patches1[i], patches1[j]): i*W+j for (i,j) in itertools.product(range(H), range(W))}
    for r in futures.as_completed(procs):
        ids = procs[r]
        val = r.result()
        results[ids] = val
results = np.reshape(results,(H,W))

There may be a smarter way to do this by optimizing f to work on whole image instead of patches1. Here I show an engineering way only.


问:
Reflection using generics
I'd like to return the properties of a series of DbSet objects I have saved to a class using reflection, but in order to access this data in a single method I'd need to pass a variable as an accessor to return the properties of that object.

Currently I've managed to return the properties of all of the DbSet objects, but the code looks very DRY.

```<code>public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}

public List<string> GetPropertiesFoo()
{
    DbContext client = new DbContext();
    return client.Foo.GetType().GetProperties().Select(e => e.Name).ToList();
}
public List<string> GetPropertiesBar()
{
    DbContext client = new DbContext();
    return client.Bar.GetType().GetProperties().Select(e => e.Name).ToList();
}
</code>```

My intention is to refactor this so that it accepts a DbSet name as an argument and returns a single list of properties, rather than a list of all properties.

答:
You are looking for something like this to do it all in one hit. Note this code is quite verbose so that each step can be explained:

```<code>// Make the method generic so we can use it on any context
public List<string> GetProperties<TContext>(string dbSetName = "")
    where TContext : DbContext // Make sure we have a Dbcontext
{
    var propertyNames = typeof(TContext)

        // Get all properties of context
        .GetProperties()

         // Filter out so we only have DbSet<> types
        .Where(pi => pi.PropertyType.IsGenericType &&
                     typeof(DbSet<>).IsAssignableFrom(pi.PropertyType.GetGenericTypeDefinition()))

        // If a DbSet name has been specified, filter it out
        .Where(pi => string.IsNullOrEmpty(dbSetName) || pi.Name == dbSetName)

        // Get the generic type e.g. Foo
        .Select(pi => pi.PropertyType.GetGenericArguments()[0])

        // Get the individual properties of the entity types
        .Select(t => t.GetProperties())

        // Get all of the property names
        .SelectMany(x => x.Select(pi => pi.Name));

    return propertyNames.ToList();
}
</code>```

And use it like this:

```<code>// All properties for all sets
var allProperties = GetProperties<MyContext>();

// Only properties for the Foo set
var fooProperties = GetProperties<MyContext>("Foo");
</code>```

Title: Reflection using generics

Body:
I'd like to return the properties of a series of DbSet objects I have saved to a class using reflection, but in order to access this data in a single method I'd need to pass a variable as an accessor to return the properties of that object.

Currently I've managed to return the properties of all of the DbSet objects, but the code looks very DRY.

public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}

public List<string> GetPropertiesFoo()
{
    DbContext client = new DbContext();
    return client.Foo.GetType().GetProperties().Select(e => e.Name).ToList();
}
public List<string> GetPropertiesBar()
{
    DbContext client = new DbContext();
    return client.Bar.GetType().GetProperties().Select(e => e.Name).ToList();
}

My intention is to refactor this so that it accepts a DbSet name as an argument and returns a single list of properties, rather than a list of all properties.

Body:
You are looking for something like this to do it all in one hit. Note this code is quite verbose so that each step can be explained:

// Make the method generic so we can use it on any context
public List<string> GetProperties<TContext>(string dbSetName = "")
    where TContext : DbContext // Make sure we have a Dbcontext
{
    var propertyNames = typeof(TContext)

        // Get all properties of context
        .GetProperties()

         // Filter out so we only have DbSet<> types
        .Where(pi => pi.PropertyType.IsGenericType &&
                     typeof(DbSet<>).IsAssignableFrom(pi.PropertyType.GetGenericTypeDefinition()))

        // If a DbSet name has been specified, filter it out
        .Where(pi => string.IsNullOrEmpty(dbSetName) || pi.Name == dbSetName)

        // Get the generic type e.g. Foo
        .Select(pi => pi.PropertyType.GetGenericArguments()[0])

        // Get the individual properties of the entity types
        .Select(t => t.GetProperties())

        // Get all of the property names
        .SelectMany(x => x.Select(pi => pi.Name));

    return propertyNames.ToList();
}

And use it like this:

// All properties for all sets
var allProperties = GetProperties<MyContext>();

// Only properties for the Foo set
var fooProperties = GetProperties<MyContext>("Foo");


问:
Cloud run failed to start because of invalid SQL Cloud configuration
I followed the documentation to enable SQL Cloud from a Cloud run.  But according to the documentation:

Your container instances are now able to connect to Cloud SQL via the Cloud SQL proxy that is automatically activated and configured. In your code, you can connect to the Cloud SQL instance using the /cloudsql/[CONNECTION NAME] unix socket.

What does mean the last phrase?.
Do I need to connect using the usual connection string like:
jdbc:postgresql://localhost:5432/${DATABASE_NAME}

In my case this is what prevent the container to start.
org.postgresql.util.PSQLException: Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

Also I use the following command to "add" SQL cloud:
gcloud beta run deploy --image gcr.io/[PROJECT_ID/[IMAGE_NAME]:[TAG] --add-cloudsql-instances [CONNECTION_NAME]

答:
An example of connection statement is this one:

```<code>import pymysql
connection = pymysql.connect(unix_socket='/cloudsql/' + <INSTANCE_CONNECTION_NAME>,
                             user='<USER>',
                             password='<PASSWORD>',
                             db='<DATABASE>')
</code>```

You can find more information about this in Google's documentation about connecting to Cloud SQL from external application which uses the Cloud Proxy also.

If you are using the Java.  The documentation for the UNIX socket connection can be found here : Cloud SQL Socket Factory for JDBC drivers

Body:
An example of connection statement is this one:

import pymysql
connection = pymysql.connect(unix_socket='/cloudsql/' + <INSTANCE_CONNECTION_NAME>,
                             user='<USER>',
                             password='<PASSWORD>',
                             db='<DATABASE>')

You can find more information about this in Google's documentation about connecting to Cloud SQL from external application which uses the Cloud Proxy also.

If you are using the Java.  The documentation for the UNIX socket connection can be found here : Cloud SQL Socket Factory for JDBC drivers


问:
Batch insert in Yii
I need to insert multiple ActiveRecord object in Yii,if all of them inserted

```<code>$transaction = Yii::app()->db->beginTransaction();
for ($i = 0;$i < 10;$i++){
    $model = new Mymodel();
    $model->x = $i;
    if (!$model->save()){
        $transaction->rollback();
        break;
    }
}
if ($transaction->active)
    $transaction->commit();
</code>```

Now I need to insert all of them in one query,How can I do it during using active record?

答:
Update for the Bulk Insert / Batch Insert for YII

```<code>class CDbMultiInsertCommand extends CDbCommand{

/** @var CActiveRecord $class */
private $class;

/** @var string $insert_template */
private $insert_template = "insert into %s(%s) ";

/** @var string $value_template */
private $value_template = "(%s)";

/** @var string $query */
public $query;

/** @var CDbColumnSchema[] $columns */
private $columns;

/** @var boolean $fresh */
private $fresh;

/** @var CDbConnection $db */
private $db;

/** @param CActiveRecord $class
 *  @param CDbConnection $db
 */
public function __construct($class, $db = null){

    $this->class = $class;
    $this->createTemplate();
    if(is_null($db)){
        $this->db = Yii::app()->db;
    }
    else{
        $this->db = $db;
    }

    parent::__construct($this->getConnection());
}
private function createTemplate(){
    $this->fresh = true;
    $value_template = "";
    $columns_string = "";
    $this->columns = $this->class->getMetaData()->tableSchema->columns;

    $counter = 0;
    foreach($this->columns as $keyColumnName => $column){
        /** @var CDbColumnSchema $column */
        if($column->autoIncrement){
            unset($this->columns[$keyColumnName]);
            continue;
            // $value_template .= "0";
        }
        else if($column->type == "integer" || $column->type == "boolean" || $column->type == "float" || $column->type == "double") {
            $value_template .= "%d";
        }
        else{
            $value_template .= "\"%s\"";
        }
        $columns_string .= '"'.$column->name.'"';
        $counter ++;
        if($counter != sizeof($this->columns)){
            $columns_string .= ", ";
            $value_template .= ", ";
        }
    }
    $this->insert_template = sprintf($this->insert_template, $this->class->tableName(), $columns_string);
    $this->value_template = sprintf($this->value_template, $value_template);
}

/** @param boolean $validate
 *  @param CActiveRecord $record
 */
public function add($record, $validate = true){
    $values = array();
    if($validate){
        if(!$record->validate()){
            return false;
        }
    }
    $counter = 0;
    foreach($this->columns as $column){
        if($column->autoIncrement){
            continue;
        }
        $values[$counter] = $record->{$column->name};
        $counter ++;
    }
    if(!$this->fresh){
        $this->query .= ",";
    }
    else{
        $this->query = "values";
    }
    $this->fresh = false;
    $this->query .= vsprintf($this->value_template, $values);
    $this->query = str_replace('"', "'", $this->query);

    return true;
}

public function getConnection(){
    return $this->db;
}

public function execute($params=array()){
    if(!$this->query)
        return;

    $this->setText($this->insert_template." ".$this->query);

    return parent::execute();
}
</code>```

}

I was facing problem with 3 things with the earlier code.

Auto increment column where in earlier code it was set as 0

Query statement which had double quotes.

execute function should be similar to parent execute function with parameter.

I guess the first 2 points are related to database I am using postgresql, hope the updated code works for all database systems.

Title: Batch insert in Yii

Body:
I need to insert multiple ActiveRecord object in Yii,if all of them inserted

$transaction = Yii::app()->db->beginTransaction();
for ($i = 0;$i < 10;$i++){
    $model = new Mymodel();
    $model->x = $i;
    if (!$model->save()){
        $transaction->rollback();
        break;
    }
}
if ($transaction->active)
    $transaction->commit();

Now I need to insert all of them in one query,How can I do it during using active record?

Body:
Update for the Bulk Insert / Batch Insert for YII

class CDbMultiInsertCommand extends CDbCommand{

/** @var CActiveRecord $class */
private $class;

/** @var string $insert_template */
private $insert_template = "insert into %s(%s) ";

/** @var string $value_template */
private $value_template = "(%s)";

/** @var string $query */
public $query;

/** @var CDbColumnSchema[] $columns */
private $columns;

/** @var boolean $fresh */
private $fresh;

/** @var CDbConnection $db */
private $db;

/** @param CActiveRecord $class
 *  @param CDbConnection $db
 */
public function __construct($class, $db = null){

    $this->class = $class;
    $this->createTemplate();
    if(is_null($db)){
        $this->db = Yii::app()->db;
    }
    else{
        $this->db = $db;
    }

    parent::__construct($this->getConnection());
}
private function createTemplate(){
    $this->fresh = true;
    $value_template = "";
    $columns_string = "";
    $this->columns = $this->class->getMetaData()->tableSchema->columns;

    $counter = 0;
    foreach($this->columns as $keyColumnName => $column){
        /** @var CDbColumnSchema $column */
        if($column->autoIncrement){
            unset($this->columns[$keyColumnName]);
            continue;
            // $value_template .= "0";
        }
        else if($column->type == "integer" || $column->type == "boolean" || $column->type == "float" || $column->type == "double") {
            $value_template .= "%d";
        }
        else{
            $value_template .= "\"%s\"";
        }
        $columns_string .= '"'.$column->name.'"';
        $counter ++;
        if($counter != sizeof($this->columns)){
            $columns_string .= ", ";
            $value_template .= ", ";
        }
    }
    $this->insert_template = sprintf($this->insert_template, $this->class->tableName(), $columns_string);
    $this->value_template = sprintf($this->value_template, $value_template);
}

/** @param boolean $validate
 *  @param CActiveRecord $record
 */
public function add($record, $validate = true){
    $values = array();
    if($validate){
        if(!$record->validate()){
            return false;
        }
    }
    $counter = 0;
    foreach($this->columns as $column){
        if($column->autoIncrement){
            continue;
        }
        $values[$counter] = $record->{$column->name};
        $counter ++;
    }
    if(!$this->fresh){
        $this->query .= ",";
    }
    else{
        $this->query = "values";
    }
    $this->fresh = false;
    $this->query .= vsprintf($this->value_template, $values);
    $this->query = str_replace('"', "'", $this->query);

    return true;
}

public function getConnection(){
    return $this->db;
}

public function execute($params=array()){
    if(!$this->query)
        return;

    $this->setText($this->insert_template." ".$this->query);

    return parent::execute();
}

}

I was facing problem with 3 things with the earlier code.

Auto increment column where in earlier code it was set as 0

Query statement which had double quotes.

execute function should be similar to parent execute function with parameter.

I guess the first 2 points are related to database I am using postgresql, hope the updated code works for all database systems.


问:
How to Fix ''Level None not found' Error in pandas?
Facing following error when running code

Level None not found

```<code>pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = True)
pt = pt.sort_values('Score', ascending = False)
</code>```

I want to take the average value of Threat Score & Score, also count of the user name.  Then sort by Threat Score high to low.

答:
```<code>pt = df.pivot_table(index = 'User Agent', values = ['Threat Score', 'Score','Source IP'] ,
                    aggfunc = {"Source IP" : 'count',
                               'Threat Score':np.mean,
                               'Score': np.mean})

pt = pt.sort_values('Threat Score', ascending = False)
new_cols = ['Avg_Score', 'Count', 'Avg_ThreatScore']
pt.columns = new_cols
pt.to_csv(Path3 + '\\AllUserAgent.csv')
</code>```

Body:
Facing following error when running code

Level None not found

pt = df.pivot_table(index = 'User Name',values = ['Threat Score', 'Score'],
        aggfunc = {
                   'Threat Score': np.mean,
                   'Score' :[np.mean, lambda x: len(x.dropna())]
                  },
        margins = True)
pt = pt.sort_values('Score', ascending = False)

I want to take the average value of Threat Score & Score, also count of the user name.  Then sort by Threat Score high to low.


问:
How to sort dictionary by object property vbscript
I am trying to sort a dictionary with a function that I found online by an object property which is the Id but on this For Each i In dict line I am getting this error message Microsoft VBScript runtime error: Object doesn't support this property or method. I have tried For Each i In dict.Items but I get the same error message with 'dict.Items' I am using a older version of VBScript so it does not have features like dict.Count

VBScript Class:

```<code>Class TestClass
    Public ID
    Public TestText
    Private Sub Class_Initialize
            TestText  = ""
    End Sub
End Class

Set gDic = CreateObject("Scripting.Dictionary")

For i = 1 to 5
    Set temp = new TestClass
    temp.ID = i
    temp.TestText = "Test" & i

    gDic.Add i,temp
Next

Set NewDic = SortDict(gDic)
msgbox NewDic.Items()(1).TestText
</code>```

Sort function:

```<code>Function SortDict(ByVal dict)
    Dim i, j, temp
    For Each i In dict
        For Each j In dict
            If(dict.Item(i) <= dict.Item(j)) Then
                temp = dict.Item(i)
                dict.Item(i) = dict.Item(j)
                dict.Item(j) = temp
            End If
        Next
    Next
    Set SortDict = dict
End Function
</code>```

答:
If you need to do a single pass along the dictionary you could use a disconnected recordset to sort the keys, then retrieve the values from the dictionary in the order to get the keys from the recordset.</p>

```<code>dim rs 'the recordset used to sort keys  must be global
Set D = CreateObject("Scripting.Dictionary")
for i=1 to 10
d.add right("0000"&Cint(rnd*10000),4), i
next

'
for each j in d.keys
   wscript.echo j & " " & d(j)
next
wscript.echo ""

i=0
do
  b= DicNextItem(d,i)
  wscript.echo b(0)&" "&b(1)
loop until i=-1

'---------------------------------------------

Function DicNextItem(dic,i)
'returns successive items from dictionary ordered by keys
'arguments  dic: the dictionary
'         i: 0 must be passed at fist call,
'                 returns 1 if there are more items
'                 returns-1 if no more items
'returns array with the key in index 0 and the value and value in index 1
'requires rs as global variable (no static in vbs)
'it supposes the key is a string
      const advarchar=200
      const adopenstatic=3
      dim a(2)
      if i=0 then
        Set rs = CreateObject("ADODB.RECORDSET")
        with rs
        .fields.append "Key", adVarChar, 100
        .CursorType = adOpenStatic
        .open
        'add all keys to the disconnected recordset
        for each i in Dic.keys
          .AddNew
          rs("Key").Value = i
          .Update
        next
        .Sort= " Key ASC"
        .MoveFirst
        end with
        i=1
       end if
       if rs.EOF then
         a=array(nul,nul)
       else
         a(0)=rs(0)
     a(1)=dic(a(0))
         rs.movenext
       end if
       if rs.EOF then i=-1:set rs=nothing
       DicNextItem=a
end function
</code>```

Body:
I am trying to sort a dictionary with a function that I found online by an object property which is the Id but on this For Each i In dict line I am getting this error message Microsoft VBScript runtime error: Object doesn't support this property or method. I have tried For Each i In dict.Items but I get the same error message with 'dict.Items' I am using a older version of VBScript so it does not have features like dict.Count

VBScript Class:

Class TestClass
    Public ID
    Public TestText
    Private Sub Class_Initialize
            TestText  = ""
    End Sub
End Class

Set gDic = CreateObject("Scripting.Dictionary")

For i = 1 to 5
    Set temp = new TestClass
    temp.ID = i
    temp.TestText = "Test" & i

    gDic.Add i,temp
Next

Set NewDic = SortDict(gDic)
msgbox NewDic.Items()(1).TestText

Sort function:

Function SortDict(ByVal dict)
    Dim i, j, temp
    For Each i In dict
        For Each j In dict
            If(dict.Item(i) <= dict.Item(j)) Then
                temp = dict.Item(i)
                dict.Item(i) = dict.Item(j)
                dict.Item(j) = temp
            End If
        Next
    Next
    Set SortDict = dict
End Function

Body:
If you need to do a single pass along the dictionary you could use a disconnected recordset to sort the keys, then retrieve the values from the dictionary in the order to get the keys from the recordset.

dim rs 'the recordset used to sort keys  must be global
Set D = CreateObject("Scripting.Dictionary")
for i=1 to 10
d.add right("0000"&Cint(rnd*10000),4), i
next

'
for each j in d.keys
   wscript.echo j & " " & d(j)
next
wscript.echo ""

i=0
do
  b= DicNextItem(d,i)
  wscript.echo b(0)&" "&b(1)
loop until i=-1

'---------------------------------------------

Function DicNextItem(dic,i)
'returns successive items from dictionary ordered by keys
'arguments  dic: the dictionary
'         i: 0 must be passed at fist call,
'                 returns 1 if there are more items
'                 returns-1 if no more items
'returns array with the key in index 0 and the value and value in index 1
'requires rs as global variable (no static in vbs)
'it supposes the key is a string
      const advarchar=200
      const adopenstatic=3
      dim a(2)
      if i=0 then
        Set rs = CreateObject("ADODB.RECORDSET")
        with rs
        .fields.append "Key", adVarChar, 100
        .CursorType = adOpenStatic
        .open
        'add all keys to the disconnected recordset
        for each i in Dic.keys
          .AddNew
          rs("Key").Value = i
          .Update
        next
        .Sort= " Key ASC"
        .MoveFirst
        end with
        i=1
       end if
       if rs.EOF then
         a=array(nul,nul)
       else
         a(0)=rs(0)
     a(1)=dic(a(0))
         rs.movenext
       end if
       if rs.EOF then i=-1:set rs=nothing
       DicNextItem=a
end function


问:
Android | What is the best way to retrieve a contact's photo by phone number?
I have an application that needs to get the photo of a given contact. I have the phone number of the contact, so is there a way to retrieve the photo of the contact if it exists by phone number via ContentResolver or any other form? I've been searching, but found no answers.

I would really like to stress the importance of using the phone number to get the contact photo if it exists. Thank you.

答:
I do not think there's an easy way to do this. But I guess you can go through the Contacts on the phone and check each number if it's the one your are trying to match.

As the numbers are unordered anyway, there's no way to make it more efficient. Search in unordered list is performed by traversing them, as I suggest you should do with this problem. Unless Android keeps all numbers in an ordered list that I don't know about.

You can traverse through the Contacts by doing something like this:

```<code>Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
   String contactId = cursor.getString(cursor.getColumnIndex(
   ContactsContract.Contacts._ID));
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
   if (Boolean.parseBoolean(hasPhone)) {
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
      while (phones.moveToNext()) {
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
      }
   phones.close();
}
cursor.close();
</code>```

This is not the complete solution to your task, but by modifying the code above I think you'll get through. :-)

Body:
I do not think there's an easy way to do this. But I guess you can go through the Contacts on the phone and check each number if it's the one your are trying to match.

As the numbers are unordered anyway, there's no way to make it more efficient. Search in unordered list is performed by traversing them, as I suggest you should do with this problem. Unless Android keeps all numbers in an ordered list that I don't know about.

You can traverse through the Contacts by doing something like this:

Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
   String contactId = cursor.getString(cursor.getColumnIndex(
   ContactsContract.Contacts._ID));
   String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
   if (Boolean.parseBoolean(hasPhone)) {
      // You know it has a number so now query it like this
      Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
      while (phones.moveToNext()) {
         String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
      }
   phones.close();
}
cursor.close();

This is not the complete solution to your task, but by modifying the code above I think you'll get through. :-)


问:
Git server hooks, check if code is formated
I am trying to create a git server hook so that unformatted code would not be pushed. In my scenario I want to use clang format to check if the code is formatted correctly. if not the user will receive a message stating they need to format the code before pushing. </p>

<p>we are trying to implement a must format policy at work and this will simply be a safety net. </p>

答:
Summary

It took me quite a while to piece together from the sparse examples I was able to find, so I figure I'll share what I've come up with as well.

Basically here's what you need to do:

use an update hook (similar to pre-receive)

inspect the branch and commit

checkout the bare repo to a temp folder

run the formatter (Prettier, in this case) on the temp folder

exit non-zero if files are / would be changed

(either from the tool's output or a git status --work-tree=... --git-dir=...)

Example: Prettier + 'update' Hook

Although the pre-receive hook is much more googleable, I find that the update hook is both easier to use and more flexible. I'm using Prettier in this example, but I tried to write to be easy to adapt to any linter / vetter / formatter.

In my case my git user's home directory is /srv/git-repositories and the hooks for the project I've set up are at:

```<code>/srv/git-repositories/my-project.git/hooks/update
</code>```

I've actually tested this, so I know that it works, although it's a bit watered down from what I'm really using.

That said, it covers the basics:

```<code>ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi
</code>```

Although I typically use gitea for git hosting, I've tested this particular hook with a simple automated git deploy with ssh, and it should work just as well with GitLab, Gogs, and the like.

More Info

I offer a little more detail in the blog post I wrote on the matter:

Reject Ugly Commits with Server-Side Git Hooks

Even more...

You may also benefit from some of these other resources:

Git Hooks Documentation

Practical Git Secrets Example

GitHub Platform Git Hook Samples

pre-receive hook for clang-format (already linked above)

Body:
I am trying to create a git server hook so that unformatted code would not be pushed. In my scenario I want to use clang format to check if the code is formatted correctly. if not the user will receive a message stating they need to format the code before pushing.

we are trying to implement a must format policy at work and this will simply be a safety net.

Body:
Summary

It took me quite a while to piece together from the sparse examples I was able to find, so I figure I'll share what I've come up with as well.

Basically here's what you need to do:

use an update hook (similar to pre-receive)

inspect the branch and commit

checkout the bare repo to a temp folder

run the formatter (Prettier, in this case) on the temp folder

exit non-zero if files are / would be changed

(either from the tool's output or a git status --work-tree=... --git-dir=...)

Example: Prettier + 'update' Hook

Although the pre-receive hook is much more googleable, I find that the update hook is both easier to use and more flexible. I'm using Prettier in this example, but I tried to write to be easy to adapt to any linter / vetter / formatter.

In my case my git user's home directory is /srv/git-repositories and the hooks for the project I've set up are at:

/srv/git-repositories/my-project.git/hooks/update

I've actually tested this, so I know that it works, although it's a bit watered down from what I'm really using.

That said, it covers the basics:

ref_name=$1
new_rev=$3

# only check branches, not tags or bare commits
if [ -z $(echo $ref_name | grep "refs/heads/") ]; then
  exit 0
fi

# don't check empty branches
if [ "$(expr "${new_rev}" : '0*$')" -ne 0 ]; then
  exit 0
fi

# Checkout a copy of the branch (but also changes HEAD)
my_work_tree=$(mktemp -d -t git-work-tree.XXXXXXXX) 2>/dev/null
git --work-tree="${my_work_tree}" --git-dir="." checkout $new_rev -f >/dev/null

# Do the formatter check
echo "Checking code formatting..."
pushd ${my_work_tree} >/dev/null
prettier './**/*.{js,css,html,json,md}' --list-different
my_status=$?
popd >/dev/null

# reset HEAD to master, and cleanup
git --work-tree="${my_work_tree}" --git-dir="." checkout master -f >/dev/null
rm -rf "${my_work_tree}"

# handle error, if any
if [ "0" != "$my_status" ]; then
  echo "Please format the files listed above and re-commit."
  echo "(and don't forget your .prettierrc, if you have one)"
  exit 1
fi

Although I typically use gitea for git hosting, I've tested this particular hook with a simple automated git deploy with ssh, and it should work just as well with GitLab, Gogs, and the like.

More Info

I offer a little more detail in the blog post I wrote on the matter:

Reject Ugly Commits with Server-Side Git Hooks

Even more...

You may also benefit from some of these other resources:

Git Hooks Documentation

Practical Git Secrets Example

GitHub Platform Git Hook Samples

pre-receive hook for clang-format (already linked above)


问:
cscope/ctags navigation in Intellij Idea vim plugin
I am used to navigating code in vim using cscope/ctags style Ctrl + [ for function definition and Ctrl + t to go back. With Intellij Idea's vim plugin enabled, I am still able to do that. However, other cscope commands like Ctrl + \ s don't seem to work.

I could try adding .ideavim to add my own mapping, but I am looking for something that does not require this step.

答:
cscope is not one of the emulated plugins. You can use IntelliJ IDEA navigation to reach that.

Also, you can map keys to standard idea actions.

For example, to get all callers of the method you can execute Call Hierarchy action. You can map this action to ctrl-\ s as follows:

Search for actions with hierarchy pattern: :actionlist hierarchy

Place map <C-\>s :action CallHierarchy<CR> to your .ideavimrc

If you want this behavior to be the default, you can create a feature request.


问:
TS2740 Type is missing the following properties from ReadOnly<MyInterface> error in React Native with TypeScript app
Since StatelessComponent is deprecated, I am trying to turn all the components into classes.

I have an interface, for example:

```<code>interface MyInterface{
    prop1: number;
    prop2: boolean;
}
</code>```

And I use it in the class:

```<code>class MyComponent extends React.Component<MyInterface> {
   ...
   public render(){...}
}
</code>```

And when I try to use MyComponent like this:

```<code><MyComponent
    prop1={3}
    prop2={false}
/>
</code>```

I get this error:

TS2740: Type {prop1: 3, prop2: false} is missing the following properties from type ReadOnly: render, context, setState, forceUpdate, and 3 more.

Is there any workaround to this?

答:
To fix this issue without explicitly typing the class, simply move the state out of the constructor as shown below:

```<code>class MyComponent extends React.Component<any> {
    state = {
        key1: value1,
        key2: value2
    }
    render(){
        return(
           <div>Hello World</div>
        )
    }
}
</code>```

This approach is useful when you have a function that set the state of form inputs like this:

```<code>handleInputChange = (event)=>{
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }
</code>```

So the code below will just fine especially when you are using typescript:

```<code>class MyComponent extends React.Component<any> {

      state = {
          key1: value1,
          key2: value2
      }

      handleInputChange = (event: React.ChangeEvent<HTMLInputElement>)=>{
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
          [name]: value // no typing error
        });
      }

      render(){
         return(
            <div>Hello World</div>
         )
      }
    }
</code>```

Body:
Since StatelessComponent is deprecated, I am trying to turn all the components into classes.

I have an interface, for example:

interface MyInterface{
    prop1: number;
    prop2: boolean;
}

And I use it in the class:

class MyComponent extends React.Component<MyInterface> {
   ...
   public render(){...}
}

And when I try to use MyComponent like this:

<MyComponent
    prop1={3}
    prop2={false}
/>

I get this error:

TS2740: Type {prop1: 3, prop2: false} is missing the following properties from type ReadOnly: render, context, setState, forceUpdate, and 3 more.

Is there any workaround to this?

Body:
To fix this issue without explicitly typing the class, simply move the state out of the constructor as shown below:

class MyComponent extends React.Component<any> {
    state = {
        key1: value1,
        key2: value2
    }
    render(){
        return(
           <div>Hello World</div>
        )
    }
}

This approach is useful when you have a function that set the state of form inputs like this:

handleInputChange = (event)=>{
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

So the code below will just fine especially when you are using typescript:

class MyComponent extends React.Component<any> {

      state = {
          key1: value1,
          key2: value2
      }

      handleInputChange = (event: React.ChangeEvent<HTMLInputElement>)=>{
        const target = event.target;
        const value = target.type === 'checkbox' ? target.checked : target.value;
        const name = target.name;

        this.setState({
          [name]: value // no typing error
        });
      }

      render(){
         return(
            <div>Hello World</div>
         )
      }
    }


问:
How to use for in loop and query data from firebase
I have a query that gets all keys of users in my firebase database. Those keys er saved into an array. I would then like to loop through the array and inside the loop query for the users name. The problem is that it stops when the first name is loaded - the loop does not query through even though there are 1000 keys inside the array?

```<code>var i;

for (i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    return firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}

</code>```

I get no errors but the loop just stops after the first name is retrieved.

答:
You are using a return in your loop, which stops the loop.

If you remove that return, it should work the way you expect it to work.

```<code>for (var i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}
</code>```

Body:
I have a query that gets all keys of users in my firebase database. Those keys er saved into an array. I would then like to loop through the array and inside the loop query for the users name. The problem is that it stops when the first name is loaded - the loop does not query through even though there are 1000 keys inside the array?

var i;

for (i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    return firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}

I get no errors but the loop just stops after the first name is retrieved.

Body:
You are using a return in your loop, which stops the loop.

If you remove that return, it should work the way you expect it to work.

for (var i = 0; i < emailArray.length; i++) {
    userIDgotten = emailArray[i];

    console.log(userIDgotten);

    firebase.database().ref('/users/' + userIDgotten).once('value').then(function(snapshotUser) {
        const name = snapshotUser.val().name;

        console.log("NAME: " + name);

        allTicketEmailsFromUsers = allTicketEmailsFromUsers + ", " + name;

        console.log(allTicketEmailsFromUsers);
    });
}


问:
how to fix xamarin form listview lag when itemsource are image
how to fix xamarin form listview lag when itemsource are image.
Image are come for folder path i am using FFimageloading for image display</p>

```<code>
 <ffimageloading:CachedImage Aspect="AspectFill"
                             HorizontalOptions="FillAndExpand"
                             VerticalOptions="FillAndExpand"
                             BitmapOptimizations="True"
                             DownsampleToViewSize="True"
                             DownsampleUseDipUnits="True"
                             CacheDuration="80"
                             CacheType="Memory"
                             LoadingPlaceholder="ic_timer"
                             ErrorPlaceholder="ic_spare_active"
                             Source="{Binding DocumentUrl}">

<ffimageloading:CachedImage.Triggers>
      <DataTrigger Binding="{Binding IsAddDocumentItem}"
                   TargetType="ffimageloading:CachedImage"
                   Value="True">

       <Setter Property="IsVisible" Value="False"/>

      </DataTrigger>

</ffimageloading:CachedImage.Triggers>

</ffimageloading:CachedImage>
</code>```

答:
If you enable downsampling, please make sure you set correct values for DownsampleWidth or DownsampleHeight. FFImageLoading uses only one of these, preserving correct aspect ratio.

Add and CachingStrategy="RecycleElement" to ListView

Check more samples here

https://github.com/luberda-molinet/FFImageLoading/tree/master/samples/ImageLoading.Forms.Sample/Shared/Pages

Body:
how to fix xamarin form listview lag when itemsource are image.
Image are come for folder path i am using FFimageloading for image display

 <ffimageloading:CachedImage Aspect="AspectFill"
                             HorizontalOptions="FillAndExpand"
                             VerticalOptions="FillAndExpand"
                             BitmapOptimizations="True"
                             DownsampleToViewSize="True"
                             DownsampleUseDipUnits="True"
                             CacheDuration="80"
                             CacheType="Memory"
                             LoadingPlaceholder="ic_timer"
                             ErrorPlaceholder="ic_spare_active"
                             Source="{Binding DocumentUrl}">

<ffimageloading:CachedImage.Triggers>
      <DataTrigger Binding="{Binding IsAddDocumentItem}"
                   TargetType="ffimageloading:CachedImage"
                   Value="True">

       <Setter Property="IsVisible" Value="False"/>

      </DataTrigger>

</ffimageloading:CachedImage.Triggers>

</ffimageloading:CachedImage>


问:
setInterval argumet is undefined in the second function call
I'm generating a file from an API, and need to keep making a request until the file is ready,so I used the setInterval to invoke the ajax call repeatedly but in the second call the URL becomes undefined.

```<code>$( "#campaign-list-table form").submit(function(event) {

        event.preventDefault();
        let exportOption = $(this).children("option:selected").val();
        let postUrl = $(this).attr('action');

        setInterval(ajaxd(postUrl), 5000);

    });

    /**
     *
     * @param postUrl
     */
    let ajaxd = function (postUrl) {
        $.ajax({
            method: 'POST',
            url: postUrl,
            contentType: "application/xml",
            complete: function (data) {

                //let $xmlObject = parseXML(data);
                console.log(postUrl);
                    ajaxd();

            }
        });
    }
</code>```

I expect the output of the URL to be 'api/export/2988475 , but the second output is undefined.

答:
You are not passing a function to setInterval, but rather calling the function ajaxd and passing its result as the first argument to setInterval.

Wrap your call to ajaxd in an anonymous function:

```<code>setInterval(function () {
    ajaxd(postUrl)
}, 5000);
</code>```

Body:
I'm generating a file from an API, and need to keep making a request until the file is ready,so I used the setInterval to invoke the ajax call repeatedly but in the second call the URL becomes undefined.

$( "#campaign-list-table form").submit(function(event) {

        event.preventDefault();
        let exportOption = $(this).children("option:selected").val();
        let postUrl = $(this).attr('action');

        setInterval(ajaxd(postUrl), 5000);

    });

    /**
     *
     * @param postUrl
     */
    let ajaxd = function (postUrl) {
        $.ajax({
            method: 'POST',
            url: postUrl,
            contentType: "application/xml",
            complete: function (data) {

                //let $xmlObject = parseXML(data);
                console.log(postUrl);
                    ajaxd();

            }
        });
    }

I expect the output of the URL to be 'api/export/2988475 , but the second output is undefined.

Body:
You are not passing a function to setInterval, but rather calling the function ajaxd and passing its result as the first argument to setInterval.

Wrap your call to ajaxd in an anonymous function:

setInterval(function () {
    ajaxd(postUrl)
}, 5000);


问:
"Encountered unsupported property Type" Error in Cloudformation with Route53
When attempting to build a AWS::Route53::RecordSet using cloudformation, I get "Encountered unsupported property Type" error. I am assuming this means it does not recognize "Type": "A" in my JSON. However, that is a valid property of AWS::Route53::RecordSet and is even in the example AWS gives in the documentation. (I understand this is for RecordSetGroup, but the example at the bottom builds a RecordSet).

I have also tried copying and pasting the exact example Amazon gives and subbing out their values for mine. Still no luck.

Here is my code:

```<code>"DNS" : {
      "Type": "AWS::Route53::RecordSet",
      "Properties": {
        "HostedZoneName": {
          "Ref": "HostedZoneName"
        },
        "Comment": "DNS name for my instance.",
        "Name": {
          "Fn::Join": [
            "",
            [
              {
                "Ref": "ComponentDNSName"
              },
              {
                "Ref": "HostedZoneName"
              }
            ]
          ]
        },
        "Type": "A",
        "TTL": "900",
        "ResourceRecords": [
          {
            "Fn::GetAtt": [
              {
                "Fn::GetAtt": [
                  "Ec2Instance",
                  "PrivateIp"
                ]
              }
            ]
          }
        ]
      }
    }
</code>```

I thought it might be brackets in the wrong places, but I have double checked that and other resources in my stack (alarms, EC2Instance) build fine.

Thank you for any help.

答:
The issue is with ResourceRecords I think. Replace the current one with

```<code>   "ResourceRecords": [
      {
        "Fn::GetAtt": [
            "Ec2Instance",
            "PrivateIp"
        ]
      }
    ]
</code>```

If you have multiple inputs to be added to ResourceRecords, it will become

```<code>   "ResourceRecords": [
      {
        "Fn::GetAtt": [
            "name1",
            "resource1"
        ]
      },
      {
        "Fn::GetAtt": [
            "name2",
            "resource2"
        ]
      }
    ]
</code>```

Hope this helps.

Body:
When attempting to build a AWS::Route53::RecordSet using cloudformation, I get "Encountered unsupported property Type" error. I am assuming this means it does not recognize "Type": "A" in my JSON. However, that is a valid property of AWS::Route53::RecordSet and is even in the example AWS gives in the documentation. (I understand this is for RecordSetGroup, but the example at the bottom builds a RecordSet).

I have also tried copying and pasting the exact example Amazon gives and subbing out their values for mine. Still no luck.

Here is my code:

"DNS" : {
      "Type": "AWS::Route53::RecordSet",
      "Properties": {
        "HostedZoneName": {
          "Ref": "HostedZoneName"
        },
        "Comment": "DNS name for my instance.",
        "Name": {
          "Fn::Join": [
            "",
            [
              {
                "Ref": "ComponentDNSName"
              },
              {
                "Ref": "HostedZoneName"
              }
            ]
          ]
        },
        "Type": "A",
        "TTL": "900",
        "ResourceRecords": [
          {
            "Fn::GetAtt": [
              {
                "Fn::GetAtt": [
                  "Ec2Instance",
                  "PrivateIp"
                ]
              }
            ]
          }
        ]
      }
    }

I thought it might be brackets in the wrong places, but I have double checked that and other resources in my stack (alarms, EC2Instance) build fine.

Thank you for any help.

Body:
The issue is with ResourceRecords I think. Replace the current one with

   "ResourceRecords": [
      {
        "Fn::GetAtt": [
            "Ec2Instance",
            "PrivateIp"
        ]
      }
    ]

If you have multiple inputs to be added to ResourceRecords, it will become

   "ResourceRecords": [
      {
        "Fn::GetAtt": [
            "name1",
            "resource1"
        ]
      },
      {
        "Fn::GetAtt": [
            "name2",
            "resource2"
        ]
      }
    ]

Hope this helps.


问:
What should the return type be?
```<code>ABRecordCopyValue(thisPerson, kABPersonAddressProperty);
</code>```

thisPerson is ABRecordRef

Thanks

答: According to the documentation, the return type is CFTypeRef

Title: What should the return type be?

Body:
ABRecordCopyValue(thisPerson, kABPersonAddressProperty);

thisPerson is ABRecordRef

Thanks


问:
Is there a way to assign a percentile value to a variable?
I am setting up dynamic threshold values (upper and lower bound). These values are from a SQL statement (e.g. select percentile("value",80) from apc where metrics="temperature")

Instead of:
var upperbound = 16

How can we assign the upperbound variable to the output of the SQL statement?

答:
You cannot do this with InfluxQL. You have two options:

Subqueries. You can use multiple subqueries in your main query to fetch the upper and lower bounds

Try our new query language, Flux

https://docs.influxdata.com/flux/v0.24/

It can be enabled on InfluxDB 1.7 and 2.0-alpha


问:
Can't authenticate block with key A after writing the sector trailer
I can't authenticate the sector with "key A" after I write new content to the sector trailer block.

My tag is MIFARE Classic 1K and I use "MF_API.dll".

I do this:

On a new tag with default config, I authenticate with "key A" and value "FFFFFFFFFFFF", and the result is success.

Then, I write AAAAAAAAAAAA078069BBBBBBBBBBBB to the sector trailer.

When I then try to authenticate with "key A" and value "AAAAAAAAAAAA", it fails. The same thing happens when I try to authenticate with "key B" and value "BBBBBBBBBBBB".

Where is my mistake?

And my second question:
Is there any free software for writing and reading on MIFARE Classic 1K tags?

答:
The value that you write to the sector trailer seems to miss one byte (the value is only 15 bytes long, but the trailer block is 16 bytes long). See Changing authentication key of a sector in MIFARE Classic for the format of the sector trailer block.

Moreover, the access bits (078069) that you have in your trailer block don't seem to be valid since this would be

```
C1 = 0x8 and nC1 = 7 (-> check okay)
C2 = 0x9 but nC2 = 0 (-> check not okay, since not(C2) would be 0x6)
C3 = 0x6 but nC3 = 0 (-> check not okay, since not(C3) would be 0x9)
```

As a result, if you managed to write this to the sector trailer, the sector will be permanently blocked (due to the checksum mismatch in the access bits), see Can I recover a MIFARE Classic card?.

Based on the values you used, I would guess that you actually wanted to write this to the sector trailer:

```
AAAAAAAAAAAA<b>FF</b>078069BBBBBBBBBBBB
```

Note that these permissions mean that you can authenticate to that sector with key A only, Key B is readable with those permissions and, consequently, cannot be used for authentication.

Regarding your second question: I would not recommend any specific software. Also, please be aware that this type of question is off-topic here.

Body:
The value that you write to the sector trailer seems to miss one byte (the value is only 15 bytes long, but the trailer block is 16 bytes long). See Changing authentication key of a sector in MIFARE Classic for the format of the sector trailer block.

Moreover, the access bits (078069) that you have in your trailer block don't seem to be valid since this would be

C1 = 0x8 and nC1 = 7 (-> check okay)
C2 = 0x9 but nC2 = 0 (-> check not okay, since not(C2) would be 0x6)
C3 = 0x6 but nC3 = 0 (-> check not okay, since not(C3) would be 0x9)

As a result, if you managed to write this to the sector trailer, the sector will be permanently blocked (due to the checksum mismatch in the access bits), see Can I recover a MIFARE Classic card?.

Based on the values you used, I would guess that you actually wanted to write this to the sector trailer:

AAAAAAAAAAAAFF078069BBBBBBBBBBBB

Note that these permissions mean that you can authenticate to that sector with key A only, Key B is readable with those permissions and, consequently, cannot be used for authentication.

Regarding your second question: I would not recommend any specific software. Also, please be aware that this type of question is off-topic here.


问:
Git in Visual Studio 2017 is extremely slow
I did the basic checks like not having folders on network drives, changing certain git config settings, using a different repo, anti virus scan ect.

So far I know the problem isn't tied to my Windows account. On another device it only takes a few seconds to switch branches, not a minute. We noticed a lot more network traffic on the slow PC.

When I run Visual Studio in safe mode,

```<code>devenv.exe /SafeMode
</code>```

I immediately see the following errors in the Team Explorer:

```<code>System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(Int32 hr, Int32[] expectedHRFailure)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsurePackageLoaded(IServiceProvider serviceProvider, Guid packageGuid)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsureSccAndTfPackagesLoaded(IServiceProvider serviceProvider)
   at Microsoft.TeamFoundation.Git.Provider.Repositories.GitTeamProjectExtendedInfoProvider.set_ServiceProvider(IServiceProvider value)
   at Microsoft.VisualStudio.TeamFoundation.TeamExplorer.ConnectPage.ConnectPageVS.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerPageHost.Initialize(TeamExplorerPageContext context)
</code>```

As suggested on msdn, the first thing I tried was:

```<code>devenv.exe /updateConfiguration
</code>```

but this did not fix the problem. Then I ran:

```<code>devenv.exe /setup
</code>```

It gives the following error message:

The operation could not be completed. The requested operation requires
  elevation.

```<code>devenv.exe /SafeMode /log D:\temp
</code>```

The errors I see in the log are:

```<code>Error loading UI library for package WebEditorPackage. HrLoadNativeUILibrary failed with 0x800a006f.
Error loading UI library for package Microsoft.VsSDK.ExtensibilityProjectFlavor.ExtensibilityProjectFlavorPackage. HrLoadNativeUILibrary failed with 0x800a006f.
Failed to find CTMENU resource '#1000' in loaded UI library.
</code>```

I ran Visual Studio as administrator. The problem persists but I don't have any error lines in the log anymore when running as user in safemode afterwards.

I see one error and many warnings on a regular startup:

```<code>ERROR Encountered an ArgumentException when trying to look up the key binding information for ({ef254ccf-cee3-43e9-a22c-3ae3ab08e7fe},256) in the scope {5efc7975-14bc-11cf-9b2b-00aa00573819}.
Unexpected system error mode before loading package [Microsoft.VisualStudio.Services.Promotions.PromotionsPackage]
Unexpected system error mode before loading package [InstallerPackage]
About to block on async service creation because the service was requested via GetService. This has the potential to deadlock. Async initializing services should be retrieved via GetServiceAsync.

PkgDef syntax or I/O error at line 1: Section header: additional characters after closing bracket
      [$RootKey$\Setup\[ProductName]]  80004005 - E_FAIL
PkgDef syntax or I/O error at line 3: Section header: additional characters after closing bracket
      "SrcPath"="[SourceDir]"  80004005 - E_FAIL
Could not process PkgDef file
      C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\Community\Detection_Keys_Reg.pkgdef
</code>```

A Visual Studio repair did not fix the problem either. I'm using Visual Studio 15.6.5.

I ran sfc to check Windows system files.

```<code>sfc /scannow

Beginning system scan.  This process will take some time.

Beginning verification phase of system scan.
Verification 100% complete.

Windows Resource Protection found corrupt files but was unable to fix some
of them. Details are included in the CBS.Log windir\Logs\CBS\CBS.log. For
example C:\Windows\Logs\CBS\CBS.log. Note that logging is currently not
supported in offline servicing scenarios.
</code>```

There are many errors like these:

```<code>CSI    000010f2 [DIRSD OWNER WARNING] Directory [l:48 ml:49]'\??\C:\Program Files\Windows Identity Foundation' is not owned but specifies SDDL in component c2wtsres, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f3 [DIRSD OWNER WARNING] Directory [l:53 ml:54]'\??\C:\Program Files\Windows Identity Foundation\v3.5' is not owned but specifies SDDL in component c2wtsres, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f4 Error - Overlap: Duplicate ownership for directory \??\C:\Program Files\Windows Identity Foundation in component c2wtsres, version 10.0.14393.0, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f5 Error - Overlap: Duplicate ownership for directory \??\C:\Program Files\Windows Identity Foundation\v3.5 in component c2wtsres, version 10.0.14393.0, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
</code>```

The Process Monitor logs show switching between Git and VS. The disk operations itself are fast, but after git.exe FileCloses C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\bin\git.exe it takes almost exactly a second before it closes C:\Windows. And almost a second after a QueryNameInformationFile event from git.exe, it does CloseFile on C:\Windows\System32\conhost.exe.

I made Wireshark captures when there is nothing special going on. I see a lot of traffic between my PC and webdefence.cluster-x.websense.net, the company proxy. The traffic is exceptionally more than what my colleagues have and they don't see errors.

The problem stays the same when using the wired, wireless or at home with the VPN connection.

I'm suspecting it is a problem with NTFS permissions?

I tried running SFCFix to no avail.

```<code>SFCFix Has Crashed

Something has gone horribly wrong and SFCFix has crashed. Would you like SFCFix
to submit a crash report to the developer so that this problem can be fixed?
Type "y" for yes or "n" for no and press enter to continue:
</code>```

The other tools I tried weren't successful yet either.

```<code>System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(Int32 hr, Int32[] expectedHRFailure)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsurePackageLoaded(IServiceProvider serviceProvider, Guid packageGuid)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsureSccAndTfPackagesLoaded(IServiceProvider serviceProvider)
   at Microsoft.TeamFoundation.Git.Provider.Repositories.GitTeamProjectExtendedInfoProvider.set_ServiceProvider(IServiceProvider value)
   at Microsoft.VisualStudio.TeamFoundation.TeamExplorer.ConnectPage.ConnectPageVS.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerPageHost.Initialize(TeamExplorerPageContext context)
</code>```0

Tweaking.com - Windows Repair 2018 was not able to fix the file permissions either.

答:
delete "Git" folder in this directory and restart VS

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer

that folder overrides your normal Git executions.

PS: if you are using not "Community" version then modify accordingly.
Cheers

Body:
I did the basic checks like not having folders on network drives, changing certain git config settings, using a different repo, anti virus scan ect.

So far I know the problem isn't tied to my Windows account. On another device it only takes a few seconds to switch branches, not a minute. We noticed a lot more network traffic on the slow PC.

When I run Visual Studio in safe mode,

devenv.exe /SafeMode

I immediately see the following errors in the Team Explorer:

System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
   at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
   at Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(Int32 hr, Int32[] expectedHRFailure)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsurePackageLoaded(IServiceProvider serviceProvider, Guid packageGuid)
   at Microsoft.TeamFoundation.Git.Provider.ServiceProviderExtensionMethods.EnsureSccAndTfPackagesLoaded(IServiceProvider serviceProvider)
   at Microsoft.TeamFoundation.Git.Provider.Repositories.GitTeamProjectExtendedInfoProvider.set_ServiceProvider(IServiceProvider value)
   at Microsoft.VisualStudio.TeamFoundation.TeamExplorer.ConnectPage.ConnectPageVS.Initialize(Object sender, PageInitializeEventArgs e)
   at Microsoft.TeamFoundation.Controls.WPF.TeamExplorer.Framework.TeamExplorerPageHost.Initialize(TeamExplorerPageContext context)

As suggested on msdn, the first thing I tried was:

devenv.exe /updateConfiguration

but this did not fix the problem. Then I ran:

devenv.exe /setup

It gives the following error message:

The operation could not be completed. The requested operation requires
  elevation.

devenv.exe /SafeMode /log D:\temp

The errors I see in the log are:

Error loading UI library for package WebEditorPackage. HrLoadNativeUILibrary failed with 0x800a006f.
Error loading UI library for package Microsoft.VsSDK.ExtensibilityProjectFlavor.ExtensibilityProjectFlavorPackage. HrLoadNativeUILibrary failed with 0x800a006f.
Failed to find CTMENU resource '#1000' in loaded UI library.

I ran Visual Studio as administrator. The problem persists but I don't have any error lines in the log anymore when running as user in safemode afterwards.

I see one error and many warnings on a regular startup:

ERROR Encountered an ArgumentException when trying to look up the key binding information for ({ef254ccf-cee3-43e9-a22c-3ae3ab08e7fe},256) in the scope {5efc7975-14bc-11cf-9b2b-00aa00573819}.
Unexpected system error mode before loading package [Microsoft.VisualStudio.Services.Promotions.PromotionsPackage]
Unexpected system error mode before loading package [InstallerPackage]
About to block on async service creation because the service was requested via GetService. This has the potential to deadlock. Async initializing services should be retrieved via GetServiceAsync.

PkgDef syntax or I/O error at line 1: Section header: additional characters after closing bracket
      [$RootKey$\Setup\[ProductName]]  80004005 - E_FAIL
PkgDef syntax or I/O error at line 3: Section header: additional characters after closing bracket
      "SrcPath"="[SourceDir]"  80004005 - E_FAIL
Could not process PkgDef file
      C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\Extensions\Community\Detection_Keys_Reg.pkgdef

A Visual Studio repair did not fix the problem either. I'm using Visual Studio 15.6.5.

I ran sfc to check Windows system files.

sfc /scannow

Beginning system scan.  This process will take some time.

Beginning verification phase of system scan.
Verification 100% complete.

Windows Resource Protection found corrupt files but was unable to fix some
of them. Details are included in the CBS.Log windir\Logs\CBS\CBS.log. For
example C:\Windows\Logs\CBS\CBS.log. Note that logging is currently not
supported in offline servicing scenarios.

There are many errors like these:

CSI    000010f2 [DIRSD OWNER WARNING] Directory [l:48 ml:49]'\??\C:\Program Files\Windows Identity Foundation' is not owned but specifies SDDL in component c2wtsres, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f3 [DIRSD OWNER WARNING] Directory [l:53 ml:54]'\??\C:\Program Files\Windows Identity Foundation\v3.5' is not owned but specifies SDDL in component c2wtsres, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f4 Error - Overlap: Duplicate ownership for directory \??\C:\Program Files\Windows Identity Foundation in component c2wtsres, version 10.0.14393.0, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}
CSI    000010f5 Error - Overlap: Duplicate ownership for directory \??\C:\Program Files\Windows Identity Foundation\v3.5 in component c2wtsres, version 10.0.14393.0, arch amd64, nonSxS, pkt {l:8 b:31bf3856ad364e35}

The Process Monitor logs show switching between Git and VS. The disk operations itself are fast, but after git.exe FileCloses C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\Git\mingw32\bin\git.exe it takes almost exactly a second before it closes C:\Windows. And almost a second after a QueryNameInformationFile event from git.exe, it does CloseFile on C:\Windows\System32\conhost.exe.

I made Wireshark captures when there is nothing special going on. I see a lot of traffic between my PC and webdefence.cluster-x.websense.net, the company proxy. The traffic is exceptionally more than what my colleagues have and they don't see errors.

The problem stays the same when using the wired, wireless or at home with the VPN connection.

I'm suspecting it is a problem with NTFS permissions?

I tried running SFCFix to no avail.

SFCFix Has Crashed

Something has gone horribly wrong and SFCFix has crashed. Would you like SFCFix
to submit a crash report to the developer so that this problem can be fixed?
Type "y" for yes or "n" for no and press enter to continue:

The other tools I tried weren't successful yet either.

D:\Tools>DISM /Online /Cleanup-Image /StartComponentCleanup /ResetBase

Deployment Image Servicing and Management tool
Version: 10.0.14393.0

Image Version: 10.0.14393.0

[===========                20.0%                          ]
The operation completed successfully.

D:\Tools>Dism /Online /Cleanup-Image /RestoreHealth

Deployment Image Servicing and Management tool
Version: 10.0.14393.0

Image Version: 10.0.14393.0

[==========================100.0%==========================]
Error: 0x800f081f

The source files could not be found.
Use the "Source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see http://go.microsoft.com/fwlink/?LinkId=243077.

The DISM log file can be found at C:\WINDOWS\Logs\DISM\dism.log

Tweaking.com - Windows Repair 2018 was not able to fix the file permissions either.


问:
How do I properly make images for a website?
I know this seems like a simple question, but I'm really stuck. I am developing a website and Firefox is altering the image colors for the site.  The issue is stemming from Firefox's use of ICC color profiles (I think).

I've done tons of research on the topic, and most of it boils down to sRGB when saving in Photoshop, but the color profiles are already set to sRGB.

These are the color settings I use when I save:
http://i.stack.imgur.com/jLJ5g.png

http://i.stack.imgur.com/OAx88.png - How it looks in Firefox 3, Chrome, and IE

http://i.stack.imgur.com/B7bcC.png - How it looks in Firefox 4

I can disable Firefox 4's color management through

about:config / gfx.color_management.enabled = 0,

but that is not a correct solution.

Wat do?

URL: http://development.smgwebdesign.com/riley

Thanks guys.

答:
This is a bit out of my depth because I haven't been a Photoshop user for a long time, but the general solution to this is not to  embed a ICC colour profile in the first place. </p>

<p>You should have a check box for that in your export dialog. Is that already turned off? </p>

Body:
This is a bit out of my depth because I haven't been a Photoshop user for a long time, but the general solution to this is not to  embed a ICC colour profile in the first place.

You should have a check box for that in your export dialog. Is that already turned off?


问:
Tracking progress of joblib.Parallel execution
Is there a simple way to track the overall progress of a joblib.Parallel execution?

I have a long-running execution composed of thousands of jobs, which I want to track and record in a database. However, to do that, whenever Parallel finishes a task, I need it to execute a callback, reporting how many remaining jobs are left.

I've accomplished a similar task before with Python's stdlib multiprocessing.Pool, by launching a thread that records the number of pending jobs in Pool's job list.

Looking at the code, Parallel inherits Pool, so I thought I could pull off the same trick, but it doesn't seem to use these that list, and I haven't been able to figure out how else to "read" it's internal status any other way.

答:
In Jupyter tqdm starts a new line in the output each time it outputs.
So for Jupyter Notebook it will be:

For use in Jupyter notebook.
No sleeps:

```<code>from joblib import Parallel, delayed
from datetime import datetime
from tqdm import notebook

def myfun(x):
    return x**2

results = Parallel(n_jobs=8)(delayed(myfun)(i) for i in notebook.tqdm(range(1000)))
</code>```

100% 1000/1000 [00:06<00:00, 143.70it/s]

With time.sleep:

```<code>from joblib import Parallel, delayed
from datetime import datetime
from tqdm import notebook
from random import randint
import time

def myfun(x):
    time.sleep(randint(1, 5))
    return x**2

results = Parallel(n_jobs=7)(delayed(myfun)(i) for i in notebook.tqdm(range(100)))
</code>```

What I'm currently using instead of joblib.Parallel:

```<code>import concurrent.futures
from tqdm import notebook
from random import randint
import time

iterable = [i for i in range(50)]

def myfun(x):
    time.sleep(randint(1, 5))
    return x**2

def run(func, iterable, max_workers=8):
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        results = list(notebook.tqdm(executor.map(func, iterable), total=len(iterable)))
    return results

run(myfun, iterable)
</code>```

Body:
In Jupyter tqdm starts a new line in the output each time it outputs.
So for Jupyter Notebook it will be:

For use in Jupyter notebook.
No sleeps:

from joblib import Parallel, delayed
from datetime import datetime
from tqdm import notebook

def myfun(x):
    return x**2

results = Parallel(n_jobs=8)(delayed(myfun)(i) for i in notebook.tqdm(range(1000)))

100% 1000/1000 [00:06<00:00, 143.70it/s]

With time.sleep:

from joblib import Parallel, delayed
from datetime import datetime
from tqdm import notebook
from random import randint
import time

def myfun(x):
    time.sleep(randint(1, 5))
    return x**2

results = Parallel(n_jobs=7)(delayed(myfun)(i) for i in notebook.tqdm(range(100)))

What I'm currently using instead of joblib.Parallel:

import concurrent.futures
from tqdm import notebook
from random import randint
import time

iterable = [i for i in range(50)]

def myfun(x):
    time.sleep(randint(1, 5))
    return x**2

def run(func, iterable, max_workers=8):
    with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
        results = list(notebook.tqdm(executor.map(func, iterable), total=len(iterable)))
    return results

run(myfun, iterable)


答:
This is a possible way to go, just adapt it to your case:</p>

```<code>df<-c('33','429:301:255:38','450692,450693,450694,450695')
df[1]<-paste('[',shQuote(df[1]),']')
df[2]<-paste(' = {[',shQuote(df[2]),']')
df[3]<-paste(', [',shQuote(df[3]),']}')
dff<-paste(df[1],df[2],df[3])
library("openxlsx")
setwd("C:\\temp")
wb<-createWorkbook()
addWorksheet(wb, sheetName = "test")
writeData(wb,dff,sheet = "test", rowNames = FALSE)
name <- paste("mydata_",Sys.Date(),".xlsx", sep="")
saveWorkbook(wb,name, overwrite = TRUE)
</code>```

Title: How do I merge rows based on column and modify layout code in R?

Body:
I have a .csv file that contains this:

84,62,175,235,374,221,292,375,430,497,0,0,736,0,0,0
85,62,298,337,149,181,247,424,228,383,0,0,1657,0,0,0
87,62,198,181,347,355,423,479,403,494,0,0,261,0,0,0
88,62,289,202,422,310,388,430,498,604,0,0,259,0,0,0
122,41,276,231,247,294,402,463,383,461,0,0,87,0,0,0

I have another .csv file that contains this:

10848,0,0,0,272826,84
10849,0,0,0,272806,85
10850,0,1,0,272812,85
10851,1,0,0,440831,85
10870,0,0,0,271567,122
10871,0,1,0,438415,122

Using R, how can I merge these together (by first column in first table and last column in second) and add quotes to make it look nicer.

Many thanks.

Body:
This is a possible way to go, just adapt it to your case:

df<-c('33','429:301:255:38','450692,450693,450694,450695')
df[1]<-paste('[',shQuote(df[1]),']')
df[2]<-paste(' = {[',shQuote(df[2]),']')
df[3]<-paste(', [',shQuote(df[3]),']}')
dff<-paste(df[1],df[2],df[3])
library("openxlsx")
setwd("C:\\temp")
wb<-createWorkbook()
addWorksheet(wb, sheetName = "test")
writeData(wb,dff,sheet = "test", rowNames = FALSE)
name <- paste("mydata_",Sys.Date(),".xlsx", sep="")
saveWorkbook(wb,name, overwrite = TRUE)


问:
How can I sort LinkedHashMap<Integer, HtmlTagValues> where HtmlTagValues is a class with various values?
I am relatively new to Java, and trying to sort LinkedHashMap<Integer, HtmlTagValues> newHtmlTagValues where HtmlTagValues is a public class which has numerous values from a HTML page. I want to sort on the Top values.

```<code>public class HtmlTagValues {
    public String Top;
    public String Height;
    public String Width;
    public String Left;
    ....
}
</code>```

The values are stored in the following way.

```<code>HtmlTagValues v = new HtmlTagValues();
v.Top = topValue;
v.Left = leftValue;
hHtmlTagValues.put(nPage + ElementID, v);
</code>```

答:
I presume there is a constructor in HtmlTagValues class for all the properties

```<code>public HtmlTagValues(String top, String height, String width, String left) {
    this.top = top;
    this.height = height;
    this.width = width;
    this.left = left;
}
</code>```

Note: I also presume that you have getters/setters for each property.

Now let's say we have the following map

```<code>Map<Integer, HtmlTagValues> map = new LinkedHashMap<>();

map.put(1, new HtmlTagValues("Z", "10", "768", "100"));
map.put(2, new HtmlTagValues("A", "10", "768", "100"));
map.put(3, new HtmlTagValues("B", "10", "768", "100"));
map.put(4, new HtmlTagValues("D", "10", "768", "100"));
map.put(5, new HtmlTagValues("C", "10", "768", "100"));
</code>```

Here is how we can sort our map by value, by the property 'Top'

```<code>Map<Integer, HtmlTagValues> sortedMap = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Comparator.comparing(HtmlTagValues::getTop)))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));
</code>```

Your sorted map will look like this

```<code>2,HtmlTagValues("A", "10", "768", "100")
3,HtmlTagValues("B", "10", "768", "100")
5,HtmlTagValues("C", "10", "768", "100")
4,HtmlTagValues("D", "10", "768", "100")
1,HtmlTagValues("Z", "10", "768", "100")
</code>```

Fully working example:

https://gist.github.com/mackatozis/8aa81597bc33d885635cb3a9935e5cd5

Body:
I am relatively new to Java, and trying to sort LinkedHashMap<Integer, HtmlTagValues> newHtmlTagValues where HtmlTagValues is a public class which has numerous values from a HTML page. I want to sort on the Top values.

public class HtmlTagValues {
    public String Top;
    public String Height;
    public String Width;
    public String Left;
    ....
}

The values are stored in the following way.

HtmlTagValues v = new HtmlTagValues();
v.Top = topValue;
v.Left = leftValue;
hHtmlTagValues.put(nPage + ElementID, v);

Body:
I presume there is a constructor in HtmlTagValues class for all the properties

public HtmlTagValues(String top, String height, String width, String left) {
    this.top = top;
    this.height = height;
    this.width = width;
    this.left = left;
}

Note: I also presume that you have getters/setters for each property.

Now let's say we have the following map

Map<Integer, HtmlTagValues> map = new LinkedHashMap<>();

map.put(1, new HtmlTagValues("Z", "10", "768", "100"));
map.put(2, new HtmlTagValues("A", "10", "768", "100"));
map.put(3, new HtmlTagValues("B", "10", "768", "100"));
map.put(4, new HtmlTagValues("D", "10", "768", "100"));
map.put(5, new HtmlTagValues("C", "10", "768", "100"));

Here is how we can sort our map by value, by the property 'Top'

Map<Integer, HtmlTagValues> sortedMap = map.entrySet()
        .stream()
        .sorted(Map.Entry.comparingByValue(Comparator.comparing(HtmlTagValues::getTop)))
        .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldValue, newValue) -> oldValue, LinkedHashMap::new));

Your sorted map will look like this

2,HtmlTagValues("A", "10", "768", "100")
3,HtmlTagValues("B", "10", "768", "100")
5,HtmlTagValues("C", "10", "768", "100")
4,HtmlTagValues("D", "10", "768", "100")
1,HtmlTagValues("Z", "10", "768", "100")

Fully working example:

https://gist.github.com/mackatozis/8aa81597bc33d885635cb3a9935e5cd5