问:
Pass whole Model through ajax call
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});
</code>```

I have tried with this but it just return a Model that is null:

```<code>$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});
</code>```

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

```<code>public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}
</code>```

答:
You can embed the model properties within a form and then serialize the form and pass it your ajax call.

```<code>$.ajax({
                url: "/Controller/ActionName",
                type: 'POST',
                data: $('#MyFormName').serialize()
            })
                .done(function (response) {
        alert(response.Message);

                    }
                }).fail(function () {
                    alert(Something went wrong);
                });
</code>```

And in the action you can directly access your model as

```<code>public ActionResult ActionName(MyModel modelObj)
    {}
</code>```

Title: Pass whole Model through ajax call

Body:
Is it possible to pass a whole Model through my jQuery's ajax call?
For know I can only get it working if i set one variable at the time.

As the code shows I pass the iVideo_ID through the ajax call. The Video object has a lot of other fields. So instead of writing all the attributes, can i pass the whole existing object (Video Model)?

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/UpdateComment", // Controller/View
    data: { //Passing data
        iVideo_ID: '@(Model.Video.iVideo_ID)'
    }
});

I have tried with this but it just return a Model that is null:

$.ajax({
    type: "POST", //HTTP POST Method
    url: "/Video/NyMetode", // Controller/View
    data: '@(Model)'
});

So how can i pass the whole model? Is it possible?

EDIT:
My View Model I try to pass:

public class CommentViewModel
{
   public List<Comments> Comments { get; set; }
   public List<Tasks> Tasks { get; set; }
   public Videos Video { get; set; }
   public List<VideoTaskScores> VideoTaskScores { get; set; }
}

Body:
You can embed the model properties within a form and then serialize the form and pass it your ajax call.

$.ajax({
                url: "/Controller/ActionName",
                type: 'POST',
                data: $('#MyFormName').serialize()
            })
                .done(function (response) {
        alert(response.Message);

                    }
                }).fail(function () {
                    alert(Something went wrong);
                });

And in the action you can directly access your model as

public ActionResult ActionName(MyModel modelObj)
    {}


来源: stackexchange

问:
Angular 2: getting data from a Class
I've created a class for the default settings of my app. But I have no idea how to get the data from that class and use it in my html. I tried an observable but that's not really working. </p>

<p>My class looks like this: </p>

```<code>export class Instellingen {
  urenTotBehandeling: number = 4;
  toonNaam: boolean = true;
  toonTijd: boolean = true;
  toonType: boolean = true;
  toonSanitair: boolean = true;
  toonKinder: boolean = true;
  toonSalon: boolean = true;
  toonKamerNummer: boolean = true;
  uren = [
    {value: 1, label: '1 uur'},
    {value: 2, label: '2 uren'},
    {value: 3, label: '3 uren'},
    {value: 4, label: '4 uren'}         ];
  hulpKleur:string= "red";
  behandelKleur:string = "orange";
  volKleur:string="green";
  leegKleur:string="white";    }
</code>```

答:
here is an example how you can use it :

```<code>let i: Instellingen=new Instellingen();
console.log(i.urenTotBehandeling); // 4
</code>```

Hope it helps :)

ContentLicense: CC BY-SA 3.0

Title: Angular 2: getting data from a Class

Body:
I've created a class for the default settings of my app. But I have no idea how to get the data from that class and use it in my html. I tried an observable but that's not really working.

My class looks like this:

export class Instellingen {
  urenTotBehandeling: number = 4;
  toonNaam: boolean = true;
  toonTijd: boolean = true;
  toonType: boolean = true;
  toonSanitair: boolean = true;
  toonKinder: boolean = true;
  toonSalon: boolean = true;
  toonKamerNummer: boolean = true;
  uren = [
    {value: 1, label: '1 uur'},
    {value: 2, label: '2 uren'},
    {value: 3, label: '3 uren'},
    {value: 4, label: '4 uren'}         ];
  hulpKleur:string= "red";
  behandelKleur:string = "orange";
  volKleur:string="green";
  leegKleur:string="white";    }

Body:
here is an example how you can use it :

let i: Instellingen=new Instellingen();
console.log(i.urenTotBehandeling); // 4

Hope it helps :)


问:
C# selecting data from a SQL database
Having problems selecting data from my database, any clue as to what is wrong as I've been staring at this for for a solid 2 hours.... (have made a login system to which can write and use data but can't search for it)

答:
The problem is with SQL Query you are trying to execute.

```<code>SELECT * FROM TABLE WHERE "condition";
</code>```

use that query.

Title: C# selecting data from a SQL database

Body:
The problem is with SQL Query you are trying to execute.

SELECT * FROM TABLE WHERE "condition";

use that query.


问:
Time and Date getHour(), getDay() etc... still work on Android 2.3 and 3.0?
these methods are deprecated... but... still work on android 2.3 or 3.0 ?

i'm sure they work on 2.1, cause i tested it on my android phone, but works also in 2.3 or 3.0 ?

答: Those methods are not android-specific, but is in the core java class library and have been deprecated since JDK 1.1 from around 1997. So they remain until there is a non-compatible version of java released.</p>

ContentLicense: CC BY-SA 2.5


问:
SQL Server (T-SQL): Avoid call scalar function multiple times
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

```<code>SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100
</code>```

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

答:
You can achieve this by using derived table concept, In derived table we once called to function dbo.GetNumTravels(Id) only once and used its output in outer query, this may help to gaining performance at some level by avoiding multiple calls to same function.

```<code>SELECT
       Id,
       Name,
       Surname,
       CASE WHEN (NumTravelsID >= 50)  THEN 10  ELSE 99 END as Factor1,
       CASE WHEN (NumTravelsID >= 50)  THEN 15  ELSE -1 END as Factor2,
       CASE WHEN (NumTravelsID >= 50)  THEN 30  ELSE 70 END as Factor3
FROM (
         SELECT
            Id,
            Name,
            Surname,
            dbo.GetNumTravels(Id) as NumTravelsID
         FROM Employees
         WHERE DepartmentId = 100
 )M
</code>```

Body:
I have a stored procedure which does a SELECT to return some rows. Within the SELECT, I need to check a condition in order to return the correct value for some columns. This condition consists on a scalar function. All times scalar function is called with the same parameter for the row being processed, see below:

SELECT
    Id,
    Name,
    Surname,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 10
        ELSE 99
    END as Factor1,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 15
        ELSE -1
    END as Factor2,
    CASE WHEN (dbo.GetNumTravels(Id) >= 50)
        THEN 30
        ELSE 70
    END as Factor3
FROM
    Employees
WHERE
    DepartmentId = 100

I am worried about performance, I mean, I do not like to call scalar function dbo.GetNumTravels multiples times, so how to avoid this and only call it once and then used it all the times I need it?

Body:
You can achieve this by using derived table concept, In derived table we once called to function dbo.GetNumTravels(Id) only once and used its output in outer query, this may help to gaining performance at some level by avoiding multiple calls to same function.

SELECT
       Id,
       Name,
       Surname,
       CASE WHEN (NumTravelsID >= 50)  THEN 10  ELSE 99 END as Factor1,
       CASE WHEN (NumTravelsID >= 50)  THEN 15  ELSE -1 END as Factor2,
       CASE WHEN (NumTravelsID >= 50)  THEN 30  ELSE 70 END as Factor3
FROM (
         SELECT
            Id,
            Name,
            Surname,
            dbo.GetNumTravels(Id) as NumTravelsID
         FROM Employees
         WHERE DepartmentId = 100
 )M


问:
Laravel API expired session
In Laravel 5.4 I created some API on my routes/web.php. These API are called by .NET application.
The first called API is the login, after that, I put in session some datas.
Before to call other API, I check if the datas are in session, but after the first call (login), when I try to call the second one, the session seems to be flushed/expired.

Here my route code:

```<code>// API
Route::group(["prefix" => "api"], function() {
    // Login
    Route::post("login", "APIController@login");

    Route::group(["middleware" => "isNotAuthenticatedAPI"], function() {
        Route::group(["middleware" => "loginDBUser"], function() {
            // Importazioni
            Route::group(["prefix" => "importazioni"], function() {

                // Utenti
                Route::post("utenti", "APIController@importCustomers");
                // Attività (Abbonamenti)
                Route::post("attivita", "APIController@importSubscriptions");
                // Iscrizioni
                Route::post("iscrizioni", "APIController@importCustomersSubscriptions");
            });

            // Richieste
            Route::group(["prefix" => "richieste"], function() {
                // Ultima iscrizione
                Route::post("ultima_iscrizione/{subscription_external_id?}", "APIController@getLastCustomerSubscription");
            });
        });
    });
});
</code>```

Middleware isNotAuthenticatedAPI:

```<code>public function handle($request, Closure $next) {
        $res = [
            "result" => null,
            "errors" => [
            ]
        ];

        if (!$request->session()->get("user.api")) {
            $res["result"] = false;
            $res["errors"][] = [
                "code" => APIController::WARNING_SESSION_EXPIRED,
                "message" => trans("api.w_session_expired")
            ];
            return response()->json($res);
        }

        return $next($request);
    }
</code>```

My config/session.php:

```<code>'lifetime' => 120,

    'expire_on_close' => false,
</code>```

I tried to put the route's code into routes/api.php, but the result doesn't change.

答:
If you want to continue using Session in API, please make sure that the client (your .NET application) store the cookie and include it in later requests.

A simple way to test if your problem is the cookie, try login your api in browser and call other api after that. If everything work well, then it's the cookie problem.

Title: Laravel API expired session

Body:
In Laravel 5.4 I created some API on my routes/web.php. These API are called by .NET application.
The first called API is the login, after that, I put in session some datas.
Before to call other API, I check if the datas are in session, but after the first call (login), when I try to call the second one, the session seems to be flushed/expired.

Here my route code:

// API
Route::group(["prefix" => "api"], function() {
    // Login
    Route::post("login", "APIController@login");

    Route::group(["middleware" => "isNotAuthenticatedAPI"], function() {
        Route::group(["middleware" => "loginDBUser"], function() {
            // Importazioni
            Route::group(["prefix" => "importazioni"], function() {

                // Utenti
                Route::post("utenti", "APIController@importCustomers");
                // Attività (Abbonamenti)
                Route::post("attivita", "APIController@importSubscriptions");
                // Iscrizioni
                Route::post("iscrizioni", "APIController@importCustomersSubscriptions");
            });

            // Richieste
            Route::group(["prefix" => "richieste"], function() {
                // Ultima iscrizione
                Route::post("ultima_iscrizione/{subscription_external_id?}", "APIController@getLastCustomerSubscription");
            });
        });
    });
});

Middleware isNotAuthenticatedAPI:

public function handle($request, Closure $next) {
        $res = [
            "result" => null,
            "errors" => [
            ]
        ];

        if (!$request->session()->get("user.api")) {
            $res["result"] = false;
            $res["errors"][] = [
                "code" => APIController::WARNING_SESSION_EXPIRED,
                "message" => trans("api.w_session_expired")
            ];
            return response()->json($res);
        }

        return $next($request);
    }

My config/session.php:

'lifetime' => 120,

    'expire_on_close' => false,

I tried to put the route's code into routes/api.php, but the result doesn't change.


问:
comparison condition in case statement
I want to have a comparison in case statement in sql statement

```<code>  SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
    THEN (price * revenueShareAmountLocal * o.mfactor *0.08)
</code>```

and  second one is

```<code>SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
    THEN (price * revenueShareAmountLocal * o.mfactor *0.04)
</code>```

I want make a comparison that if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 > bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.01)

Else
if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 < bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.08)

In simple words, I need to put a comparison in the case statement that if one is greater than another then sum this else sum something else.

答:
You could calculate the 2 sums in an sub query.

And then compare the results in the outer query.
Which is probably the most readable method.

Or you could put a case around the sums.

For example:

```<code>-- Using a single table variable for testing reasons
declare @Test table (groupid int, idBillingStatus int, idOperator int, idClub int, price float, revenueShareAmountLocal float, mfactor int);
insert into @Test (groupid, idBillingStatus, idOperator, idClub, price, revenueShareAmountLocal, mfactor) values
(1000,2,5,1,100,20,2),
(1000,2,5,2,100,20,2),
(2000,2,5,2,100,20,2),
(2000,2,5,1,200,20,2),
(2000,2,5,2,100,20,2);

select groupid, idBillingStatus, idOperator, result1, result2,
(case
 when result2 > result1 then result2 * 0.01
 else result2 * 0.08
 end) as finalresult2
from (
    select groupid, idBillingStatus, idOperator,
    SUM(
     case
     when idClub = 1 and idBillingStatus = 2 and idOperator = 5
     then price * revenueShareAmountLocal * mfactor
     end) as result1,
    SUM(
     case
     when idClub = 2 and idBillingStatus = 2 and idOperator = 5
     then price * revenueShareAmountLocal * mfactor
     end) as result2
    from @Test
    group by groupid, idBillingStatus, idOperator
) q;

-- On in 1 select, comparing the sums
select groupid, idBillingStatus, idOperator,
CASE
WHEN SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) >
     SUM(case when idClub = 1 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end)
THEN SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) * 0.01
ELSE SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) * 0.08
END as result
from @Test
group by groupid, idBillingStatus, idOperator;
</code>```

Title: comparison condition in case statement

Body:
I want to have a comparison in case statement in sql statement

  SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
    THEN (price * revenueShareAmountLocal * o.mfactor *0.08)

and  second one is

SUM(CASE
    WHEN bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2
    THEN (price * revenueShareAmountLocal * o.mfactor *0.04)

I want make a comparison that if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 > bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.01)

Else
if bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=2 < bt.idBillingStatus = 2  and o.idOperator = 5 and cs.idClub=1
then (price * revenueShareAmountLocal * o.mfactor *0.08)

In simple words, I need to put a comparison in the case statement that if one is greater than another then sum this else sum something else.

Body:
You could calculate the 2 sums in an sub query.

And then compare the results in the outer query.
Which is probably the most readable method.

Or you could put a case around the sums.

For example:

-- Using a single table variable for testing reasons
declare @Test table (groupid int, idBillingStatus int, idOperator int, idClub int, price float, revenueShareAmountLocal float, mfactor int);
insert into @Test (groupid, idBillingStatus, idOperator, idClub, price, revenueShareAmountLocal, mfactor) values
(1000,2,5,1,100,20,2),
(1000,2,5,2,100,20,2),
(2000,2,5,2,100,20,2),
(2000,2,5,1,200,20,2),
(2000,2,5,2,100,20,2);

select groupid, idBillingStatus, idOperator, result1, result2,
(case
 when result2 > result1 then result2 * 0.01
 else result2 * 0.08
 end) as finalresult2
from (
    select groupid, idBillingStatus, idOperator,
    SUM(
     case
     when idClub = 1 and idBillingStatus = 2 and idOperator = 5
     then price * revenueShareAmountLocal * mfactor
     end) as result1,
    SUM(
     case
     when idClub = 2 and idBillingStatus = 2 and idOperator = 5
     then price * revenueShareAmountLocal * mfactor
     end) as result2
    from @Test
    group by groupid, idBillingStatus, idOperator
) q;

-- On in 1 select, comparing the sums
select groupid, idBillingStatus, idOperator,
CASE
WHEN SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) >
     SUM(case when idClub = 1 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end)
THEN SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) * 0.01
ELSE SUM(case when idClub = 2 and idBillingStatus = 2 and idOperator = 5 then price * revenueShareAmountLocal * mfactor end) * 0.08
END as result
from @Test
group by groupid, idBillingStatus, idOperator;


问:
How handle Entity Framework navigation property CollectionChanged event?
Let's say I have Entity like this:

```<code>public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}
</code>```

My problem is that the Nodes_CollectionChanged function is also called when EF initializes the property for the first use, and not only when the user adds or romoves an item.

My question is how can I respond only when the user adds or removes an item from the list?

答: To avoid the problem completely I would recommend to use entities only as data transport objects. Implement your business logic separately and your are free to do anything you want to. A NodeModel can handle your collection changes and you can control its lifecycle. Just use the Node entity to load / save the data.

Body:
Let's say I have Entity like this:

public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}

My problem is that the Nodes_CollectionChanged function is also called when EF initializes the property for the first use, and not only when the user adds or romoves an item.

My question is how can I respond only when the user adds or removes an item from the list?


问:
Using Groovy-Eclipse plugin to develop in Grails
I am evaluating Groovy/Grails for a new project and I am wondering: Can the free Groovy-Eclipse plugin be used to develop Grails applications, and if so, what are the limitations? I am aware of the SpringSource Tool Suite, which includes full support for Grails in Eclipse, but it also includes a bunch of other stuff I don't care about, so I'm looking for a lighter-weight alternative. </p>

答: STS (SpringSource ToolSOute) offers a lot more support regarding Grails compared to naked Eclipse+GroovyPlugin. Also take a look at IntelliJ.</p>


问:
Sql Server query for Webpage
I'm pretty new to web dev and need to pass arguments from the webpage and use them to query a mssql database. Unfortunately, I'm not very familiar with HTML and am in need of help/reference material. Could anyone help me?</p>

答:
which programming language are you using?

In case of PHP you should look here: http://php.net/manual/de/mysqli.quickstart.prepared-statements.php

In case of Java: https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html

Title: Sql Server query for Webpage


问:
Trying to run batch file as a Windows service
I have created a simple batch file to start my redis node.

```<code>@echo off
start cmd.exe /k "cd C:\Users\cmguser\Desktop\7000 & redis-server ./redis.conf"
</code>```

This batch file is working fine, if I am running it in cmd as administrator. I am creating this bat file as a windows service, through NSSM, but the service is giving following error:
"windows could not start the service on local computer the service did not return an error." Referred this link.

Do I have to mentioned run as administrator in my batch file, or there is any other issue through above mentioned method?

Also I have tried creating service through following command but it threw the 1053 error :

```<code>sc create service_name binpath=C:\Users\user\Desktop\redis_config_7000  start= auto
</code>```

答:
The correct way to install redis as a service in windows:

```<code>redis-server --service-install --service-name "[your desired service name]" "[full path to your redis conf]"
</code>```

As others have suggested the redis.conf must contain at least the minimum  parameters. Try it with the default config and get more specific by including the default config in an instance specific config file per include

Another way is by using the sc create command correctly:

```<code>SC CREATE [your desired service name] binpath= "\"C:\Program Files\Redis\redis-server.exe\" --service-run \"[full path to your config]\""
</code>```

Please note the whitespace after binpath=!

Body:
I have created a simple batch file to start my redis node.

@echo off
start cmd.exe /k "cd C:\Users\cmguser\Desktop\7000 & redis-server ./redis.conf"

This batch file is working fine, if I am running it in cmd as administrator. I am creating this bat file as a windows service, through NSSM, but the service is giving following error:
"windows could not start the service on local computer the service did not return an error." Referred this link.

Do I have to mentioned run as administrator in my batch file, or there is any other issue through above mentioned method?

Also I have tried creating service through following command but it threw the 1053 error :

sc create service_name binpath=C:\Users\user\Desktop\redis_config_7000  start= auto

Body:
The correct way to install redis as a service in windows:

redis-server --service-install --service-name "[your desired service name]" "[full path to your redis conf]"

As others have suggested the redis.conf must contain at least the minimum  parameters. Try it with the default config and get more specific by including the default config in an instance specific config file per include

Another way is by using the sc create command correctly:

SC CREATE [your desired service name] binpath= "\"C:\Program Files\Redis\redis-server.exe\" --service-run \"[full path to your config]\""

Please note the whitespace after binpath=!


问:
Does AWS support weighted load balancing?
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

```<code>upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}
</code>```

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.

答: You could use Route53 weight routing directly to your servers or to multiple ELBs</p>

Body:
Does AWS natively support weighted load balancing?

From what I see, ELB does only support round-robin load balancing (without any configurable weights). I have not found reliable documentation on it, though.

The easiest thing that I can think of is to put a load balancer like Nginx in front of it, for example:

upstream backend  {
  server backend1.example.com weight=1;
  server backend2.example.com weight=2;
  server backend3.example.com weight=4;
}

Here, out of seven requests, one will go to backend1, two to backend2, and four to backend4.

It will work, but it also means you have to setup a server with Nginx just for that. If AWS would directly support weighted load balancing that would be far easier to setup.


答:
The best approach to get the default settings from a class in application will be:

Create a service and add it to the Provider in your AppModule/module

Import that service and inject it in your component's constructor

Use it in your code.

Title: Angular 2: getting data from a Class


问:
Find Text having highest density of words
I have a hash as below:

```<code>{1=>[{content=>"Text of paragraph 1.........."},{content=>"Text of paragraph 2"}]}
</code>```

The above hash is created after parsing a text file . The key "1" represents page 1. It points to an array of hashes , each hash pointing to a paragraph with content key pointing to actual text.

Now I have a word list like [word1,word2,word3]. I have to iterate through all the paragraph content of that page and tell which paragraph has the most occurrence of these words.

I can write my own code where I do regex match for each of the word against the paragraph . But I wanted to know if there is any powerful string matching library that can solve this use case (in C, C++, or even ruby)

Its just not string matching. I need a library that can extract the data that consists the highest density for the words in the word list.

答:
Here is a simple example, in ruby, for counting the frequency of words in a string:

```<code>def count_words(string)
  string
    .scan(/[\w']+/) # Treat strings like "don't" as a single word
    .each_with_object(Hash.new(0)) do |w,h|
      h[w.downcase] += 1
    end
end
</code>```

Usage:

```<code>word_occurrences = count_words("Hello world! Hello, vipul.")
  => {"hello"=>2, "world"=>1, "vipul"=>1}
</code>```

You shouldn't need a third party library to implement something this simple.

To check occurrences of a specific word, just look it up in the hash:

```<code>word_occurrences[word1.downcase]
</code>```

To obtain a list of the "highest density" words, just sort by hash value:

```<code>word_occurrences.sort_by {|_word, occurrences| -occurrences}
# Note the negative to make this descending, not ascending
</code>```

Body:
I have a hash as below:

{1=>[{content=>"Text of paragraph 1.........."},{content=>"Text of paragraph 2"}]}

The above hash is created after parsing a text file . The key "1" represents page 1. It points to an array of hashes , each hash pointing to a paragraph with content key pointing to actual text.

Now I have a word list like [word1,word2,word3]. I have to iterate through all the paragraph content of that page and tell which paragraph has the most occurrence of these words.

I can write my own code where I do regex match for each of the word against the paragraph . But I wanted to know if there is any powerful string matching library that can solve this use case (in C, C++, or even ruby)

Its just not string matching. I need a library that can extract the data that consists the highest density for the words in the word list.

Body:
Here is a simple example, in ruby, for counting the frequency of words in a string:

def count_words(string)
  string
    .scan(/[\w']+/) # Treat strings like "don't" as a single word
    .each_with_object(Hash.new(0)) do |w,h|
      h[w.downcase] += 1
    end
end

Usage:

word_occurrences = count_words("Hello world! Hello, vipul.")
  => {"hello"=>2, "world"=>1, "vipul"=>1}

You shouldn't need a third party library to implement something this simple.

To check occurrences of a specific word, just look it up in the hash:

word_occurrences[word1.downcase]

To obtain a list of the "highest density" words, just sort by hash value:

word_occurrences.sort_by {|_word, occurrences| -occurrences}
# Note the negative to make this descending, not ascending


问:
Spring Boot Config at Git
I am following an blog :

https://github.com/jeroenbellen/blog-manage-and-reload-spring-properties

I am developing the services using spring boot and I want to change the config at run-time without application restart.

I have run the code mentioned in the above github repo.
What I am not able to understand how does the example-service knows about config-service. There is nothing in code which link them together.

Also, there is just one example service but I have 10s of such example service, how do I use just one config service for all example services

答:
The default is http://localhost:8888 which is enough for this example, but might differ from your needs in a productive environment :)

You can configure the config server URI in bootstrap.yml (or bootstrap.properties) using the key spring.cloud.config.uri.

The bootstrap configuration file is evaluated first, so that you can set the actual properties using the config server.

Documentation: https://cloud.spring.io/spring-cloud-config/spring-cloud-config.html#config-first-bootstrap

Title: Spring Boot Config at Git


问:
very slow spark performance
I am a newbie to spark and need some help to debug very slow performance in spark.
I am doing below transformations and its been running for more than 2 hours.

```<code>scala> val hiveContext = new org.apache.spark.sql.hive.HiveContext( sc )
hiveContext: org.apache.spark.sql.hive.HiveContext =      org.apache.spark.sql.hive.HiveContext@2b33f7a0
scala> val t1_df = hiveContext.sql("select * from T1" )

scala> t1_df.registerTempTable( "T1" )
warning: there was one deprecation warning; re-run with -deprecation for details

scala> t1_df.count
17/06/07 07:26:51 WARN util.Utils: Truncated the string representation of a    plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf.
res3: Long = 1732831

scala> val t1_df1 = t1_df.dropDuplicates( Array("c1","c2","c3", "c4" ))

scala> df1.registerTempTable( "ABC" )
warning: there was one deprecation warning; re-run with -deprecation for details

scala> hiveContext.sql( "select * from T1 where c1 not in ( select c1 from ABC )" ).count
[Stage 4:====================================================>    (89 + 8) / 97]
</code>```

I am using spark2.1.0 and reading data from hive.2.1.1 on amazon VMs cluster of 7 nodes each with 250GB RAM and 64 virtual cores. With this massive resource, i am expecting this simple query on 1.7 mil recs to fly but its painfully slow.
Any pointers would be of great help.

UPDATES:
Adding explain plan:

```<code> scala> hiveContext.sql( "select * from T1 where c1 not in ( select c1 from    ABC )" ).explain
    == Physical Plan ==
    BroadcastNestedLoopJoin BuildRight, LeftAnti, (isnull((c1#26 = c1#26#1398))   || (c1#26 = c1#26#1398))
:- FileScan parquet default.t1_pq[cols
 more fields] Batched: false, Format: Parquet, Location: InMemoryFileIndex[hdfs://<hostname>/user/hive/warehouse/atn_load_pq], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<hdr_msg_src:string,hdr_recv_tsmp:timestamp,hdr_desk_id:string,execprc:string,dreg:string,c...
+- BroadcastExchange IdentityBroadcastMode
   +- *HashAggregate(keys=[c1#26, c2#59, c3#60L, c4#82], functions=[])
      +- Exchange hashpartitioning(c1#26, c2#59, c3#60L, c4#82, 200)
         +- *HashAggregate(keys=[c1#26, c2#59, c3#60L, c4#82], functions=[])
            +- *FileScan parquet default.atn_load_pq[c1#26,c2#59,c3#60L,c4#82] Batched: true, Format: Parquet, Location: InMemoryFileIndex[hdfs://<hostname>/user/hive/warehouse/atn_load_pq], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<c1:string,c2:string,c3:bigint,c4:string>
</code>```

答:
Although I think your count will always be 0 in your query, you may try to use an left-anti join, and don't forget to cache t1_df to avoid multiple re-computations</p>

```<code>val t1_df = hiveContext.sql("select * from T1" ).cache

t1_df
   .join(
     t1_df.dropDuplicates( Array("c1","c2","c3", "c4" )),
     Seq("c1"),
     "leftanti"
   )
   .count()
</code>```

Title: very slow spark performance

Body:
I am a newbie to spark and need some help to debug very slow performance in spark.
I am doing below transformations and its been running for more than 2 hours.

scala> val hiveContext = new org.apache.spark.sql.hive.HiveContext( sc )
hiveContext: org.apache.spark.sql.hive.HiveContext =      org.apache.spark.sql.hive.HiveContext@2b33f7a0
scala> val t1_df = hiveContext.sql("select * from T1" )

scala> t1_df.registerTempTable( "T1" )
warning: there was one deprecation warning; re-run with -deprecation for details

scala> t1_df.count
17/06/07 07:26:51 WARN util.Utils: Truncated the string representation of a    plan since it was too large. This behavior can be adjusted by setting 'spark.debug.maxToStringFields' in SparkEnv.conf.
res3: Long = 1732831

scala> val t1_df1 = t1_df.dropDuplicates( Array("c1","c2","c3", "c4" ))

scala> df1.registerTempTable( "ABC" )
warning: there was one deprecation warning; re-run with -deprecation for details

scala> hiveContext.sql( "select * from T1 where c1 not in ( select c1 from ABC )" ).count
[Stage 4:====================================================>    (89 + 8) / 97]

I am using spark2.1.0 and reading data from hive.2.1.1 on amazon VMs cluster of 7 nodes each with 250GB RAM and 64 virtual cores. With this massive resource, i am expecting this simple query on 1.7 mil recs to fly but its painfully slow.
Any pointers would be of great help.

UPDATES:
Adding explain plan:

 scala> hiveContext.sql( "select * from T1 where c1 not in ( select c1 from    ABC )" ).explain
    == Physical Plan ==
    BroadcastNestedLoopJoin BuildRight, LeftAnti, (isnull((c1#26 = c1#26#1398))   || (c1#26 = c1#26#1398))
:- FileScan parquet default.t1_pq[cols
 more fields] Batched: false, Format: Parquet, Location: InMemoryFileIndex[hdfs://<hostname>/user/hive/warehouse/atn_load_pq], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<hdr_msg_src:string,hdr_recv_tsmp:timestamp,hdr_desk_id:string,execprc:string,dreg:string,c...
+- BroadcastExchange IdentityBroadcastMode
   +- *HashAggregate(keys=[c1#26, c2#59, c3#60L, c4#82], functions=[])
      +- Exchange hashpartitioning(c1#26, c2#59, c3#60L, c4#82, 200)
         +- *HashAggregate(keys=[c1#26, c2#59, c3#60L, c4#82], functions=[])
            +- *FileScan parquet default.atn_load_pq[c1#26,c2#59,c3#60L,c4#82] Batched: true, Format: Parquet, Location: InMemoryFileIndex[hdfs://<hostname>/user/hive/warehouse/atn_load_pq], PartitionFilters: [], PushedFilters: [], ReadSchema: struct<c1:string,c2:string,c3:bigint,c4:string>

Body:
Although I think your count will always be 0 in your query, you may try to use an left-anti join, and don't forget to cache t1_df to avoid multiple re-computations

val t1_df = hiveContext.sql("select * from T1" ).cache

t1_df
   .join(
     t1_df.dropDuplicates( Array("c1","c2","c3", "c4" )),
     Seq("c1"),
     "leftanti"
   )
   .count()


问:
Move UITextField up when keyboard is overlapped
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

```<code>ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------
</code>```

I have registered keyboard notification

```<code>    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}
</code>```

答:
Don't get worry when we are in the world with the lots of open libraries.

Use  KeyboardLib  Lib by adding it to code or by the pod.

Just build it. On every Keyboard open that will show option for the Next, previous arrow with the Done button.
Zero line of code with automatic event handling.

May be this one will solve the issue and a solution for the app betterment.

Body:
There is a subView presented on top of ViewA. Please find the screen layout below. When keyboard is shown on selecting UITextField even if its not overlapping with UITextField the view is scrolled up.

ViewA
  -> UIButton

subView
  -> UIScrollView
        -> UITextField
        -> UITextField

   ViewA
 -----------
|           |
|           |
|  Button   |
|           |
|           |
 -----------

   subView
 --------------
|              |
|              |
|  UITextField |
|  UITextField |
|              |
 --------------

I have registered keyboard notification

    - (void) viewWillAppear:(BOOL)animated {

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardDidShow:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillBeHidden:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];
    }

- (void) keyboardDidShow:(NSNotification *)notification {

            NSDictionary* info = [notification userInfo];
            CGRect kbRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];

            UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbRect.size.height, 0.0);
            self.scrollViewIb.contentInset = contentInsets;
            self.scrollViewIb.scrollIndicatorInsets = contentInsets;

            CGRect aRect = self.viewSelf.frame;
            aRect.size.height -= kbRect.size.height;
            CGRect frame = [self.viewSelf convertRect:self.activeField.frame toView:self.viewSelf.superview];
            if (!CGRectContainsPoint(aRect, frame.origin) ) {
                [self.scrollViewIb scrollRectToVisible:self.activeField.frame animated:YES];
            }
    }

- (void) keyboardWillBeHidden:(NSNotification *)notification {

        self.scrollViewIb.scrollEnabled = true;

        UIEdgeInsets contentInsets = UIEdgeInsetsZero;
        self.scrollViewIb.scrollIndicatorInsets = contentInsets;
        [self.scrollViewIb setContentOffset:CGPointZero animated:false];

}


问:
POSIX way to convert user input with utc offset to calendar time
Is there a POSIX way how to convert a user input with UTC offset into time_t? I was hoping for something like

```<code>strptime( buf, "%Y-%m-%d-UTC%O", &input_time );
</code>```

where %O would be the UTC offset.

Unfortunately the tm_gmtoff extention to struct tm doesn't seem to be available on Solaris (10), is it?

答:
The only thing I can think of is to copy the string, search and replace the UTC offset with one of zero, parse both times and take a difference with difftime(...).

There's probably a clever technique out there, but right now I'm short on coffee.

Body:
Is there a POSIX way how to convert a user input with UTC offset into time_t? I was hoping for something like

strptime( buf, "%Y-%m-%d-UTC%O", &input_time );

where %O would be the UTC offset.

Unfortunately the tm_gmtoff extention to struct tm doesn't seem to be available on Solaris (10), is it?


问:
How to pass the video id in main page to another page like youtube?
This is what in the main_page.html:

After clicked this image, the hidden form will be filled and use GET to video.php

```<code> <!-- hidden form -->
    <form id="openVideoPlayerForm" action="player.php" method="get">
        <input id="form-video-id" tpye="text" name="videoID" value="" hidden />
    </form>
</code>```

In video.php, I first make GET data into JSON and call initPage() -> js function to assign the video id attribute in youtube embed.

$video = $_GET['videoID'];

function initPage(){
  var videoID = <?php echo json_encode($videoID) ?>;
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&showinfo=0';
  $('#video-player').attr('src' , videoPath);
}

The question is

1.

this is not work if I use php variable into js function (It is because I am using php 7.1 ?)

var videoID = <?php echo json_encode($videoID) ?>;

2.

I used this method to implement this "clone youtube" is it a best way?

Should I use ajax to implement this function?

If yes how to do.

image for description

答:
Make VideoID a string, add quotes. This is currently invalid :

```<code>var videoID = <?php echo json_encode($videoID) ?>;
</code>```

because it yields :

```<code>var videoID = X3pTXG9a1oQ; // Error : X3pTXG9a1oQ is not defined
</code>```

Here again, open your console, it will tell you what's wrong.

You have to add quotes :

```<code>var videoID = "<?php echo json_encode($videoID) ?>";
</code>```

which will yield :

```<code>var videoID = "X3pTXG9a1oQ"; // Valid
</code>```

Body:
This is what in the main_page.html:

After clicked this image, the hidden form will be filled and use GET to video.php

    <form id="openVideoPlayerForm" action="player.php" method="get">
        <input id="form-video-id" tpye="text" name="videoID" value="" hidden />
    </form>

In video.php, I first make GET data into JSON and call initPage() -> js function to assign the video id attribute in youtube embed.

$video = $_GET['videoID'];

function initPage(){
  var videoID = <?php echo json_encode($videoID) ?>;
  var videoPath = 'https://www.youtube.com/embed/' + videoID + 'rel=0&showinfo=0';
  $('#video-player').attr('src' , videoPath);
}

The question is

1.

this is not work if I use php variable into js function (It is because I am using php 7.1 ?)

var videoID = <?php echo json_encode($videoID) ?>;

2.

I used this method to implement this "clone youtube" is it a best way?

Should I use ajax to implement this function?

If yes how to do.

image for description

Body:
Make VideoID a string, add quotes. This is currently invalid :

var videoID = <?php echo json_encode($videoID) ?>;

because it yields :

var videoID = X3pTXG9a1oQ; // Error : X3pTXG9a1oQ is not defined

Here again, open your console, it will tell you what's wrong.

You have to add quotes :

var videoID = "<?php echo json_encode($videoID) ?>";

which will yield :

var videoID = "X3pTXG9a1oQ"; // Valid


问:
I am trying to compare two dictionaries in Python and return the key for which values changed. But Python throws a invalid Syntax
I am new to Python. I am trying to compare two dictionaries based on the value and return if there are any newly added keys and removed keys. I also want to print the modified keys(if the values are changed).

Basically, i have a directory with multiple sub folders and files in it. I calculate the md5sum of all these and have similar directory on other node, check these both and print the added, removed and modified keys based on checksum.

I have written the code to do these, it works as well in Python 2.7. But sadly, i m suppposed make this work in 2.6 and lesser as well. Here is the code and it throws invalid syntax in

```<code>import os
import sys
from hashlib import md5
import ssl
import json

walk_dir = sys.argv[1]
actual_hash = {}
data = {}

def get_md5sum(file_name):
    """
    Calculate the md5sum of file.
    Returns a valid md5sum if successful, None otherwise.
    """
    md5sum = md5()
    block_size = 128 * md5sum.block_size
    try:
        with open(file_name, 'rb') as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5sum.update(data)
        return md5sum.hexdigest()
    except Exception as e:
        ERROR("Failed to calculate md5sum for %s with %s" %
              (file_name, e))
        return None

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    intersect_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
    same = set(o for o in intersect_keys if d1[o] == d2[o])
    return added, removed, modified, same

with open('../tool/file.json', 'r') as f:
     data = json.load(f)

for root, subdirs, files in os.walk(walk_dir):
for filename in files:
    file_path = os.path.join(root, filename)
    tmp_str = get_md5sum(file_path)
    actual_hash[file_path]= tmp_str

added, removed, modified, same = dict_compare(data, actual_hash)

print "\n\n*******************************"
print "Newly Added Files"
print "*******************************"
if len(added) == 0:
    print "No files are newly added"
else:
    print "\n ".join(str(e) for e in added)

print "\n\n*******************************"
print "Missing Files"
print "*******************************"
if len(removed) == 0:
    print "No files are missing or removed"
else:
    print "\n ".join(str(e) for e in removed)

print "\n\n*******************************"
print "Modified Files"
print "*******************************"
if not modified:
    print "No modified files are found"
else:
    print modified
</code>```

It throws

modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
                                     ^
SyntaxError: invalid syntax

How can i make this work on older versions and also, please suggest improvements on this code. Thanks!

答:
Change this line

```<code>modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
</code>```

to this:

```<code>modified = {}
for o in intersect_keys:
    if d1[o] != d2[o]:
        modified[o] = (d1[o], d2[o])
</code>```

Body:
I am new to Python. I am trying to compare two dictionaries based on the value and return if there are any newly added keys and removed keys. I also want to print the modified keys(if the values are changed).

Basically, i have a directory with multiple sub folders and files in it. I calculate the md5sum of all these and have similar directory on other node, check these both and print the added, removed and modified keys based on checksum.

I have written the code to do these, it works as well in Python 2.7. But sadly, i m suppposed make this work in 2.6 and lesser as well. Here is the code and it throws invalid syntax in

import os
import sys
from hashlib import md5
import ssl
import json

walk_dir = sys.argv[1]
actual_hash = {}
data = {}

def get_md5sum(file_name):
    """
    Calculate the md5sum of file.
    Returns a valid md5sum if successful, None otherwise.
    """
    md5sum = md5()
    block_size = 128 * md5sum.block_size
    try:
        with open(file_name, 'rb') as f:
            while True:
                data = f.read(block_size)
                if not data:
                    break
                md5sum.update(data)
        return md5sum.hexdigest()
    except Exception as e:
        ERROR("Failed to calculate md5sum for %s with %s" %
              (file_name, e))
        return None

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    intersect_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
    same = set(o for o in intersect_keys if d1[o] == d2[o])
    return added, removed, modified, same

with open('../tool/file.json', 'r') as f:
     data = json.load(f)

for root, subdirs, files in os.walk(walk_dir):
for filename in files:
    file_path = os.path.join(root, filename)
    tmp_str = get_md5sum(file_path)
    actual_hash[file_path]= tmp_str

added, removed, modified, same = dict_compare(data, actual_hash)

print "\n\n*******************************"
print "Newly Added Files"
print "*******************************"
if len(added) == 0:
    print "No files are newly added"
else:
    print "\n ".join(str(e) for e in added)

print "\n\n*******************************"
print "Missing Files"
print "*******************************"
if len(removed) == 0:
    print "No files are missing or removed"
else:
    print "\n ".join(str(e) for e in removed)

print "\n\n*******************************"
print "Modified Files"
print "*******************************"
if not modified:
    print "No modified files are found"
else:
    print modified

It throws

modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}
                                     ^
SyntaxError: invalid syntax

How can i make this work on older versions and also, please suggest improvements on this code. Thanks!

Body:
Change this line

modified = {o : (d1[o], d2[o]) for o in intersect_keys if d1[o] != d2[o]}

to this:

modified = {}
for o in intersect_keys:
    if d1[o] != d2[o]:
        modified[o] = (d1[o], d2[o])


问:
Not able to use @Autowired with @Mock while creating unit test cases
I have a service say MainService and it has few managers which are initialised with @Autowired, and it is using some external service which are also @Autowired.

My purpose is to create unit test cases so that I can access the inmemory DB with managers, and want to mock the external service.

Now problem which I am facing is if I use @Autowired in my unit test and use @Mock for external services, then it doesn't use mock methods, Instead it uses the actual implementation. If I do @InjectMocks then it doesn't pick the data from repo as it doesn't find the respective dependencies for managers, and if I use @Autowired and @InjectMocks together it still not being able to use the Mocks.

Something like this

```<code>@Service
public class MainService extends AbstractService
{
  @Autowired
  Manager1 manager1;

  @Autowired
  Manager2 manager2;

  @Autowired
  Manager3 manager3;

@Trace(dispatcher = true)
public void mainMethod(int data)
{
 int data1 = manager1.getData(int xyz);\\ getting data from DAO
 int data2 = manager1.getData(int xyz);\\ getting data from DAO
 int data3 = manager1.getData(int xyz);\\ getting data from
                                        \\External Service
    }

  }
</code>```

Now the test case I am writing is

```<code>@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class TestClass {

  @InjectMocks
  @Autowired
  MainService service;

  @Autowired
  RepoForManager1 repoManager1;

  @Autowired
  RepoForManager2 repoManager2;

  @Mock
  Manager3 manager3;

  @Before
  public void initTest()
  {
      MockitoAnnotations.initMocks(this);
      int dataFirst=1;
      int dataSecond =2;
      int dataThird=3;
      int dataForMethod=4;
      repoManager1.save(dataFirst);
      repoManager2.save(dataSecond);
     }

   @Test
      public void testMethod()
      {

         Mockito.when(manager3.getData(Mockito.anyInt())).thenReturn(dataThird);
         service.mainMethod(dataForMethod);
       }
 }
</code>```

This is a replication of the actual service, when I debug the test I found that the mock is not being used, its using actual implementation, and when I removed @Autowired from MainService then it only execute the mocked method.

答:
If you want to use Mockito, you need Annotate your TestClass with @RunWith(MockitoJUnitRunner.class) instead of @RunWith(SpringRunner.class).

Then for the @AutoWired in the TestClass for repoManager1, repoManger2. Annotate them with @Mock instead of @Autowired, as you want to mock them with Mockito.

I have not used the SpringRunner myself, but from a quick read, I can see that it is used mostly for Integration Test, where you want to load the SpringContext..etc.

Also @ActiveProfiles("test") is mostly used for Integration Test, where you want to load the spring context, with the 'test' profile properties.

Body:
I have a service say MainService and it has few managers which are initialised with @Autowired, and it is using some external service which are also @Autowired.

My purpose is to create unit test cases so that I can access the inmemory DB with managers, and want to mock the external service.

Now problem which I am facing is if I use @Autowired in my unit test and use @Mock for external services, then it doesn't use mock methods, Instead it uses the actual implementation. If I do @InjectMocks then it doesn't pick the data from repo as it doesn't find the respective dependencies for managers, and if I use @Autowired and @InjectMocks together it still not being able to use the Mocks.

Something like this

@Service
public class MainService extends AbstractService
{
  @Autowired
  Manager1 manager1;

  @Autowired
  Manager2 manager2;

  @Autowired
  Manager3 manager3;

@Trace(dispatcher = true)
public void mainMethod(int data)
{
 int data1 = manager1.getData(int xyz);\\ getting data from DAO
 int data2 = manager1.getData(int xyz);\\ getting data from DAO
 int data3 = manager1.getData(int xyz);\\ getting data from
                                        \\External Service
    }

  }

Now the test case I am writing is

@RunWith(SpringRunner.class)
@ActiveProfiles("test")
public class TestClass {

  @InjectMocks
  @Autowired
  MainService service;

  @Autowired
  RepoForManager1 repoManager1;

  @Autowired
  RepoForManager2 repoManager2;

  @Mock
  Manager3 manager3;

  @Before
  public void initTest()
  {
      MockitoAnnotations.initMocks(this);
      int dataFirst=1;
      int dataSecond =2;
      int dataThird=3;
      int dataForMethod=4;
      repoManager1.save(dataFirst);
      repoManager2.save(dataSecond);
     }

   @Test
      public void testMethod()
      {

         Mockito.when(manager3.getData(Mockito.anyInt())).thenReturn(dataThird);
         service.mainMethod(dataForMethod);
       }
 }

This is a replication of the actual service, when I debug the test I found that the mock is not being used, its using actual implementation, and when I removed @Autowired from MainService then it only execute the mocked method.


问:
Catch an error from tar and continue processing
I'm looping through a list of .tar.gz files, untar them and do some analysis with them. So far so good. The problem is, when some of the files are corrupt, untar throws an error and the processing stops.

My code is like that:

```<code>f <- dir(path.to.files, pattern=".tar.gz")
for(k in 1:length(f)){
  # make sure the temporary dir is empty
  file.remove(dir(path = tempdir(), full.names = TRUE)
  untar(f[k], exdir = tempdir())
  # do some analisys with the extracted files
}
</code>```

I would rather catch the error from untar, skip that corrupt file, and simply continue my loop. I already tried to use try and tryCatch but without luck.

Is there a way of telling untar to throw a warning instead of an error?

答:
You can continue the loop by adding next to the finally argument of tryCatch. Consider the following example. The loop runs from 1 to 3 and prints the iteration value. When the value is equal to 2, R tries to untar the file "untitled-3.synctex1.gz", which does not exist in my current working directory

```<code>for(i in 1:3) {
  print(i)
  if(i == 2) tryCatch(untar("untitled-3.synctex1.gz"), finally=next)
}
</code>```

[1] 1

  [1] 2

   Show Traceback

Rerun with Debug
   Error in gzfile(path.expand(tarfile), "rb") : cannot open the connection In addition: Warning message:

  In gzfile(path.expand(tarfile), "rb") :
    cannot open compressed file 'untitled-3.synctex1.gz', probable reason 'No such file or directory'

  [1] 3

We see the error message and the warning, but the loop continues to the next iteration and prints the third value.

Body:
I'm looping through a list of .tar.gz files, untar them and do some analysis with them. So far so good. The problem is, when some of the files are corrupt, untar throws an error and the processing stops.

My code is like that:

f <- dir(path.to.files, pattern=".tar.gz")
for(k in 1:length(f)){
  # make sure the temporary dir is empty
  file.remove(dir(path = tempdir(), full.names = TRUE)
  untar(f[k], exdir = tempdir())
  # do some analisys with the extracted files
}

I would rather catch the error from untar, skip that corrupt file, and simply continue my loop. I already tried to use try and tryCatch but without luck.

Is there a way of telling untar to throw a warning instead of an error?

Body:
You can continue the loop by adding next to the finally argument of tryCatch. Consider the following example. The loop runs from 1 to 3 and prints the iteration value. When the value is equal to 2, R tries to untar the file "untitled-3.synctex1.gz", which does not exist in my current working directory

for(i in 1:3) {
  print(i)
  if(i == 2) tryCatch(untar("untitled-3.synctex1.gz"), finally=next)
}

[1] 1

  [1] 2

   Show Traceback

Rerun with Debug
   Error in gzfile(path.expand(tarfile), "rb") : cannot open the connection In addition: Warning message:

  In gzfile(path.expand(tarfile), "rb") :
    cannot open compressed file 'untitled-3.synctex1.gz', probable reason 'No such file or directory'

  [1] 3

We see the error message and the warning, but the loop continues to the next iteration and prints the third value.


问:
Is it possible to launch another app in iOS 8 using Swift?
Is it possible to launch any app from within another app?

For example, in my application, I want the user to push a button and launch another app (don't close the current app, just open another app and switch to it).

How can I do it in iOS 8 using Swift?

答:
Others have described the right idea already here but with some issues around handling the URL and the function to call. UIApplication.shared.open(_ url:) is deprecated, and replaced with a new version with a completion handler.

As others have mentioned, you need the recipient app to have defined a URL scheme. Provided they have, you can do something like this:

```<code>func launchTwitterApp() {
    guard let url = URL(string: "twitter://user?id=12345") else {
        preconditionFailure("There was something wrong with our url, this shouldn't happen")
    }
    UIApplication.shared.open(url, completion: { success in
        if success {
            print("We opened the Twitter app.")
        }
        else {
            print("Something went wrong. We might not have the necessary app or the right url.")
        }
    })
}
</code>```

Body:
Others have described the right idea already here but with some issues around handling the URL and the function to call. UIApplication.shared.open(_ url:) is deprecated, and replaced with a new version with a completion handler.

As others have mentioned, you need the recipient app to have defined a URL scheme. Provided they have, you can do something like this:

func launchTwitterApp() {
    guard let url = URL(string: "twitter://user?id=12345") else {
        preconditionFailure("There was something wrong with our url, this shouldn't happen")
    }
    UIApplication.shared.open(url, completion: { success in
        if success {
            print("We opened the Twitter app.")
        }
        else {
            print("Something went wrong. We might not have the necessary app or the right url.")
        }
    })
}


问:
From a shell script, determine if firefox has rendered a page
I need to run firefox from a bash script to load a url

Example

firefox -url www.google.ie

The problem is I need to know when firefox has rendered the page on the browser. Does anyone know how this could be done? There doesn't seem to be anything about this in the firefox documentation.

My goal is automated tests, Basically I have a proxy type server that sits between a browser and the web, it performs optimizations on webpages before returning them to the browser (I have a good reason for doing this). Currently I just want to know how long it takes between requesting the page and loading it in the browser.

答: From a plain vanilla install, you can't. Theoretically you could write an extension which would communicate the "page loaded" event - through a file, pipe, or whatever other mechanism you'd choose.</p>


问:
AsyncTask still operating after the method (.cancel)
AsyncTask still runs after calling the method new myTask.cancel(). I call the method when i press the back button, or when i change the fragment with a spinner. I have logged the progress of increments, and even after the myTask.cancel is called, the increments still rises.

My AsyncTask class

```<code> public class myTask extends AsyncTask<Void, Integer, String> {
        private static final String TAG = "myTask";
        private ProgressBar budgetProgressBar=null;
        private TextView textView1;
        double b_val,e_val;
        int position;
        private Context mContext;

        public myTask(){
        }

        public myTask(double b_val ,double e_val,ProgressBar budgetProgressBar, TextView textView1) {
            this.b_val = b_val;
            this.textView1=textView1;
            this.e_val = e_val;
            pStatus = (int) e_val;
            this.budgetProgressBar= budgetProgressBar;
            position = (int) budgetProgressBar.getTag();
            maxBudget = (int) this.b_val;
        }

        int pStatus;
        int maxBudget;

        @Override
        protected void onPreExecute() {
            budgetProgressBar.setMax(maxBudget);
            budgetProgressBar.setVisibility(View.VISIBLE);

               budgetProgressBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    //        }
        }

        @Override
        protected String doInBackground(Void... params) {

            int incrementor =10;

                for (int i = incrementor; i<=pStatus && !isCancelled(); i+=incrementor){

                    if (isCancelled()){
                        Log.d(TAG, "doInBackground: CANCELLED");
                        break;
                    }

                    try {

                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    publishProgress(i);
                }

            return "Complete";
        }

        @Override
        protected void onProgressUpdate(Integer... p) {

            super.onProgressUpdate(p);
            Log.d(TAG, "onProgressUpdate: ");
            if ((int) budgetProgressBar.getTag() == position){
                budgetProgressBar.incrementProgressBy(p[0]);
                budgetProgressBar.setProgress(p[0]);
                textView1.setText(p[0]+"/"+maxBudget);
               // Log.d(TAG, "Setting progress to " + p[0]);

                double calc =(e_val/b_val)*100;
                if (calc>100){
                    calc-=100;
                    textView1.setText("-"+ ((int) calc)+"%");
                }else{
                    textView1.setText(((int) calc)+"%");
                }

            }

        }

    }
</code>```

Cancelling the AsyncTask

```<code>new myTask().cancel(true);
</code>```

答:
please read this document for better understand of AsyncTask in Android
 https://developer.android.com/reference/android/os/AsyncTask.html</p>

Body:
AsyncTask still runs after calling the method new myTask.cancel(). I call the method when i press the back button, or when i change the fragment with a spinner. I have logged the progress of increments, and even after the myTask.cancel is called, the increments still rises.

My AsyncTask class

 public class myTask extends AsyncTask<Void, Integer, String> {
        private static final String TAG = "myTask";
        private ProgressBar budgetProgressBar=null;
        private TextView textView1;
        double b_val,e_val;
        int position;
        private Context mContext;

        public myTask(){
        }

        public myTask(double b_val ,double e_val,ProgressBar budgetProgressBar, TextView textView1) {
            this.b_val = b_val;
            this.textView1=textView1;
            this.e_val = e_val;
            pStatus = (int) e_val;
            this.budgetProgressBar= budgetProgressBar;
            position = (int) budgetProgressBar.getTag();
            maxBudget = (int) this.b_val;
        }

        int pStatus;
        int maxBudget;

        @Override
        protected void onPreExecute() {
            budgetProgressBar.setMax(maxBudget);
            budgetProgressBar.setVisibility(View.VISIBLE);

               budgetProgressBar.getProgressDrawable().setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);
    //        }
        }

        @Override
        protected String doInBackground(Void... params) {

            int incrementor =10;

                for (int i = incrementor; i<=pStatus && !isCancelled(); i+=incrementor){

                    if (isCancelled()){
                        Log.d(TAG, "doInBackground: CANCELLED");
                        break;
                    }

                    try {

                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    publishProgress(i);
                }

            return "Complete";
        }

        @Override
        protected void onProgressUpdate(Integer... p) {

            super.onProgressUpdate(p);
            Log.d(TAG, "onProgressUpdate: ");
            if ((int) budgetProgressBar.getTag() == position){
                budgetProgressBar.incrementProgressBy(p[0]);
                budgetProgressBar.setProgress(p[0]);
                textView1.setText(p[0]+"/"+maxBudget);
               // Log.d(TAG, "Setting progress to " + p[0]);

                double calc =(e_val/b_val)*100;
                if (calc>100){
                    calc-=100;
                    textView1.setText("-"+ ((int) calc)+"%");
                }else{
                    textView1.setText(((int) calc)+"%");
                }

            }

        }

    }

Cancelling the AsyncTask

new myTask().cancel(true);


问:
How handle Entity Framework navigation property CollectionChanged event?
Let's say I have Entity like this:

```<code>public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}
</code>```

My problem is that the Nodes_CollectionChanged function is also called when EF initializes the property for the first use, and not only when the user adds or romoves an item.

My question is how can I respond only when the user adds or removes an item from the list?

答:
You can handle ObjectMaterialized event, when EF added all items to collections and call some method, where you can subscribe:</p>

```<code>public Context()
{
    ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
          (sender, e) => Subscribe(e.Entity as Node);

}
public void Subscribe(Node node)
{
    node?.Subscribe();
}

public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
    }

    public void Subscribe()
    {
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}
</code>```

Body:
Let's say I have Entity like this:

public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}

My problem is that the Nodes_CollectionChanged function is also called when EF initializes the property for the first use, and not only when the user adds or romoves an item.

My question is how can I respond only when the user adds or removes an item from the list?

Body:
You can handle ObjectMaterialized event, when EF added all items to collections and call some method, where you can subscribe:

public Context()
{
    ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
          (sender, e) => Subscribe(e.Entity as Node);

}
public void Subscribe(Node node)
{
    node?.Subscribe();
}

public class Node
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Node Parent { get; set; }

    public virtual ObservableCollection<Node> Nodes { get; set; }

    public Node()
    {
        Nodes = new ObservableCollection<Node>();
    }

    public void Subscribe()
    {
        Nodes.CollectionChanged += Nodes_CollectionChanged;
    }

    private void Nodes_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // do something just if the USER adds or romoves item.
    }
}


问:
Issues Applying css styles conditionally to a twitter-bootstrap table
I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?

my css:

```<code>.found {
    background-color: green;
}
</code>```

my html table and input field:

```<code><table class="table table-striped">
   <thead>
      <tr>
         <th>Description</th>
         <th>Price</th>
         <th>Qty</th>
         <th>Barcode</th>
       </tr>
     </thead>
     <tbody>
        <tr *ngFor="let item of ticket.items" [class.found]="item.Barcode === spotCheckBarcode">
            <td>{{item?.ProductDetail_Name}}</td>
            <td>{{item?.Amount}}</td>
            <td>{{item?.Qty}}</td>
            <td>{{item?.Barcode}}</td>
          </tr>
       </tbody>
   </table>

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"><span class="glyphicon glyphicon-search"></span> Search</button>
    </form>
</code>```

//my ts component function that sets spotCheckBarcode

```<code>spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}
</code>```

答:
your class is not applied to td. you need to be bit more specific with css for table here.</p>

```<code>.found td { background-color: green; }
</code>```

Body:
I have a table containing a list of products.  Below the table I have a text field where a barcode is entered, if the barcode is found the matching row in the table should be highlighted.  i've read through many similar scenarios and as far as I can tell i'm doing everything as I should.  I can see in the  google dev console that the barcode I enter matches the only product currently in my table however for some reason the css doesn't get applied...  Any idea what i'm doing wrong here?/how I can go about fixing it?

my css:

.found {
    background-color: green;
}

my html table and input field:

         Description
         Price
         Qty
         Barcode

            {{item?.ProductDetail_Name}}
            {{item?.Amount}}
            {{item?.Qty}}
            {{item?.Barcode}}

   <form role="form" [formGroup]="spotCheckForm" (ngSubmit)="spotCheck(spotCheckForm.value.itemBarcode)">
        <input class="form-control" type="tel" placeholder="Enter item barcode" [formControl]="spotCheckForm.controls['itemBarcode']">
        <button class="btn btn-block" [disabled]="!spotCheckForm.controls['itemBarcode'].valid && busy"> Search</button>
    </form>

//my ts component function that sets spotCheckBarcode

spotCheck(itemBarcode: number) {
    let found: boolean = false;
     for (var i: number = 0; i < this.ticket.items.length; i++) {
        if (itemBarcode === this.ticket.items[i].Barcode) {
            console.log('found!');
            found = true;
            this.spotCheckBarcode = itemBarcode;
        }
    }
    if (found == false) {
        console.log(`found in if statement: ${found}`);
        this.showError("Item not found on ticket");
    }
}

Body:
your class is not applied to td. you need to be bit more specific with css for table here.

.found td { background-color: green; }


问:
"Percent" Style Formatting in Excel-VBA
Have n sheets which have been selected and I am trying to apply the "percent' style to all for a range of cell selection.
However only the  first sheet gets formatted. Other formatting styles that I am using work perfectly on all sheets. Only "percent" seems to be working only in the first sheet! Is there a specific reason for this? Pasting my Code snippet below: Thanks in advance for your help</p>

```<code>Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
</code>```

答:
all sheets  selected method</p>

```<code>Sub test()
    Dim vName()
    Dim Ws As Worksheet, n As Integer
    For Each Ws In Worksheets
        n = n + 1
        ReDim Preserve vName(1 To n)
        vName(n) = Ws.Name
    Next Ws
    Sheets(vName).Select
    Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
    Selection.Style = "Percent"
    Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
    Selection.Style = "Comma"
    Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
    Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
End Sub
</code>```

Title: "Percent" Style Formatting in Excel-VBA

Body:
Have n sheets which have been selected and I am trying to apply the "percent' style to all for a range of cell selection.
However only the  first sheet gets formatted. Other formatting styles that I am using work perfectly on all sheets. Only "percent" seems to be working only in the first sheet! Is there a specific reason for this? Pasting my Code snippet below: Thanks in advance for your help

Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
Selection.Style = "Percent"
Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
Selection.Style = "Comma"
Selection.numberformat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
Selection.numberformat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"

Body:
all sheets  selected method

Sub test()
    Dim vName()
    Dim Ws As Worksheet, n As Integer
    For Each Ws In Worksheets
        n = n + 1
        ReDim Preserve vName(1 To n)
        vName(n) = Ws.Name
    Next Ws
    Sheets(vName).Select
    Range(Cells(143, 2), Cells(146, MarketRangeColumn + 10)).Select
    Selection.Style = "Percent"
    Range(Cells(100, 2), Cells(142, MarketRangeColumn + 10)).Select
    Selection.Style = "Comma"
    Selection.NumberFormat = "_(* #,##0.0_);_(* (#,##0.0);_(* ""-""??_);_(@_)"
    Selection.NumberFormat = "_(* #,##0_);_(* (#,##0);_(* ""-""??_);_(@_)"
End Sub


问:
Can't center a View in an activity in XML (Android)
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>
</code>```

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

答:
Update EditText Xml

```<code><EditText
        android:id="@+id/edit2"
        android:layout_width="200dip"
        android:layout_height="50dip"
        android:textAlignment="center"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>
</code>```

Body:
I have created a new (second) activity in my android app, and right now there is one view in the content_area_reduction.xml (EditText). The file looks like this:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.company.myname.appname.AreaReductionActivity"
    tools:showIn="@layout/activity_area_reduction">

        <EditText
            android:id="@+id/edit2"
            android:layout_width="200dip"
            android:layout_height="50dip"
            android:textAlignment="center"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"/>

</RelativeLayout>

The problem is, the view appears on the left of the screen instead of center. How do I fix this issue? Will post more code if needed.

Thank you

Body:
Update EditText Xml

<EditText
        android:id="@+id/edit2"
        android:layout_width="200dip"
        android:layout_height="50dip"
        android:textAlignment="center"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>


问:
QSqlTableModel empty result
If I do this:

```<code>QSqlQuery searchQuery(QString("select * from people where id = %1").arg(1));
if (searchQuery.next())
  {
  std::cout << "Name: " << searchQuery.value(1).toString().toStdString() << std::endl;
  }
</code>```

The output is (as expected):

```<code>Name: David
</code>```

However, if I do this:

```<code> QSqlTableModel *model = new QSqlTableModel;
    // Set used table
    model->setTable("people");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
// Set where clause
model->setFilter(QString("id=%1").arg(1));
model->select();

// Read result
QSqlRecord record = model->record();
if (!record.isEmpty())
  {
  std::cout << "Name from model: " << record.value(1).toString().toStdString();
  }
</code>```

The record is not empty, but the output is blank:

```<code>Name from model:
</code>```

Can anyone see what have I done wrong using the QSqlTableModel?

Also, with both methods, I don't understand how you don't have to tell it which database to use (i.e. I instantiate a QSqlDatabase and .open() it, but I never tell the query to operate on the database?)

Thanks,

David

答:
```<code>QSqlRecord record = model->record();
</code>```

You are using QSqlQueryModel::record() which returns a "blank" record, instead of QSqlQueryModel::record(int row). The record you are getting is not empty : you can get the number and name of fields returned by the query from it.

With QSqlQuery or QSqlTableModel, you can specify which database connection to use (see QSqlTableModel or QSqlQuery constructors). If you don't, then the default database connection is used : see QSqlDatabase documentation. If you didn't explicitly gave it a name, the connection you opened is the default connection.

Title: QSqlTableModel empty result

Body:
If I do this:

QSqlQuery searchQuery(QString("select * from people where id = %1").arg(1));
if (searchQuery.next())
  {
  std::cout << "Name: " << searchQuery.value(1).toString().toStdString() << std::endl;
  }

The output is (as expected):

Name: David

However, if I do this:

 QSqlTableModel *model = new QSqlTableModel;
    // Set used table
    model->setTable("people");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
// Set where clause
model->setFilter(QString("id=%1").arg(1));
model->select();

// Read result
QSqlRecord record = model->record();
if (!record.isEmpty())
  {
  std::cout << "Name from model: " << record.value(1).toString().toStdString();
  }

The record is not empty, but the output is blank:

Name from model:

Can anyone see what have I done wrong using the QSqlTableModel?

Also, with both methods, I don't understand how you don't have to tell it which database to use (i.e. I instantiate a QSqlDatabase and .open() it, but I never tell the query to operate on the database?)

Thanks,

David

Body:
QSqlRecord record = model->record();

You are using QSqlQueryModel::record() which returns a "blank" record, instead of QSqlQueryModel::record(int row). The record you are getting is not empty : you can get the number and name of fields returned by the query from it.

With QSqlQuery or QSqlTableModel, you can specify which database connection to use (see QSqlTableModel or QSqlQuery constructors). If you don't, then the default database connection is used : see QSqlDatabase documentation. If you didn't explicitly gave it a name, the connection you opened is the default connection.


问:
React-Native display image without declaring dimensions
In, React-Native, is it possible to display an image without declaring width and height inside style prop ?

I would like the image to take all the space it has or to be rendered at its actual dimensions. (whether resizeMode is set to cover for example.)

I read this article and tried to implement its method but with no success : https://medium.com/the-react-native-log/tips-for-react-native-images-or-saying-goodbye-to-trial-and-error-b2baaf0a1a4d

Here is my code :

```<code>    <View>
      <Image
        source={{ uri: 'https://upload.wikimedia.org/wikipedia/en/c/c8/Marvelwolverine.jpg' }}
        style={{
          flex: 1,
          height: undefined,
          width: undefined,
        }}
      />
    </View>
</code>```

but nothing gets printed unless I specify hard coded width and height.

答:
You could try</p>

```<code><View style={{ flex: 1 }}>
            <Image source={{ uri:'http://...'}}
                style={{
                    alignSelf: 'stretch',
                    flex: 1,
                }}
            />
        </View>
</code>```

Body:
In, React-Native, is it possible to display an image without declaring width and height inside style prop ?

I would like the image to take all the space it has or to be rendered at its actual dimensions. (whether resizeMode is set to cover for example.)

I read this article and tried to implement its method but with no success : https://medium.com/the-react-native-log/tips-for-react-native-images-or-saying-goodbye-to-trial-and-error-b2baaf0a1a4d

Here is my code :

    <View>
      <Image
        source={{ uri: 'https://upload.wikimedia.org/wikipedia/en/c/c8/Marvelwolverine.jpg' }}
        style={{
          flex: 1,
          height: undefined,
          width: undefined,
        }}
      />
    </View>

but nothing gets printed unless I specify hard coded width and height.

Body:
You could try

<View style={{ flex: 1 }}>
            <Image source={{ uri:'http://...'}}
                style={{
                    alignSelf: 'stretch',
                    flex: 1,
                }}
            />
        </View>


问:
Create site collection using CSOM C# get error Value cannot be null. Parameter name: source
I've made some code to create site collection via CSOM C# and the following code worked fine. But recently (1, 2 days back), it give me "ServerException Value cannot be null.\r\nParameter name: source" and i cannot create any more site since then.

```<code>using (var tenantContext = new ClientContext("https://<Tenant>-admin.sharepoint.com"))
            {
                var password = ConvertToSecureString("my admin password");
                tenantContext.Credentials = new SharePointOnlineCredentials("my admin account", password);

                var tenant = new Tenant(tenantContext);
                var siteCreationProperties = new SiteCreationProperties();

                siteCreationProperties.Title = "Site 01";
                siteCreationProperties.Url = "https://<Tenant>.sharepoint.com/sites/site01";
                siteCreationProperties.Owner = "my admin account";

                var spo = tenant.CreateSite(siteCreationProperties);

                tenantContext.Load(spo, i => i.IsComplete);
                tenantContext.ExecuteQuery();
            }
</code>```

And the Exception:

```<code>ex  {"Value cannot be null.\r\nParameter name: source"} System.Exception
</code>```

{Microsoft.SharePoint.Client.ServerException}
Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HResult -2146233088 int
HelpLink    null    string
InnerException  null    System.Exception
Message "Value cannot be null.\r\nParameter name: source"   string
ServerErrorCode -2147467261 int
ServerErrorDetails  null    object
ServerErrorTraceCorrelationId   "3a3ef99d-702c-3000-d2be-2391dc283133"  string
ServerErrorTypeName "System.ArgumentNullException"  string
ServerErrorValue    null    string
ServerStackTrace    ""  string
Source  "Microsoft.SharePoint.Client.Runtime"   string
StackTrace  "   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)\r\n   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()\r\n   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)\r\n   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()\r\n   at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()\r\n   at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()\r\n   at ConsoleApplication1.Program.CreateSite() in....\ConsoleApplication1\Program.cs:line 79"   string

Please help me to find out what is this Exception and how to resolve it.

Many Thanks and Best Regards,

David

答:
we had the same Issue yesterday and did a lot of research to investigate the error. But it was just that our Tenant had Issues. Try to start the site creation on a different Tenant and see if that works. Have also a look inside the Tenant "Admin Portal => Service health" if there are some problems with SharePoint.

Hope that save you some time.

Body:
I've made some code to create site collection via CSOM C# and the following code worked fine. But recently (1, 2 days back), it give me "ServerException Value cannot be null.\r\nParameter name: source" and i cannot create any more site since then.

using (var tenantContext = new ClientContext("https://<Tenant>-admin.sharepoint.com"))
            {
                var password = ConvertToSecureString("my admin password");
                tenantContext.Credentials = new SharePointOnlineCredentials("my admin account", password);

                var tenant = new Tenant(tenantContext);
                var siteCreationProperties = new SiteCreationProperties();

                siteCreationProperties.Title = "Site 01";
                siteCreationProperties.Url = "https://<Tenant>.sharepoint.com/sites/site01";
                siteCreationProperties.Owner = "my admin account";

                var spo = tenant.CreateSite(siteCreationProperties);

                tenantContext.Load(spo, i => i.IsComplete);
                tenantContext.ExecuteQuery();
            }

And the Exception:

ex  {"Value cannot be null.\r\nParameter name: source"} System.Exception

{Microsoft.SharePoint.Client.ServerException}
Data    {System.Collections.ListDictionaryInternal} System.Collections.IDictionary {System.Collections.ListDictionaryInternal}
HResult -2146233088 int
HelpLink    null    string
InnerException  null    System.Exception
Message "Value cannot be null.\r\nParameter name: source"   string
ServerErrorCode -2147467261 int
ServerErrorDetails  null    object
ServerErrorTraceCorrelationId   "3a3ef99d-702c-3000-d2be-2391dc283133"  string
ServerErrorTypeName "System.ArgumentNullException"  string
ServerErrorValue    null    string
ServerStackTrace    ""  string
Source  "Microsoft.SharePoint.Client.Runtime"   string
StackTrace  "   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)\r\n   at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()\r\n   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQueryToServer(ChunkStringBuilder sb)\r\n   at Microsoft.SharePoint.Client.ClientRequest.ExecuteQuery()\r\n   at Microsoft.SharePoint.Client.ClientRuntimeContext.ExecuteQuery()\r\n   at Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()\r\n   at ConsoleApplication1.Program.CreateSite() in....\ConsoleApplication1\Program.cs:line 79"   string

Please help me to find out what is this Exception and how to resolve it.

Many Thanks and Best Regards,

David