问:
C++ Menu Code - Running another Class
OK, so Im close to wrapping up my work on this simple C++ Game and now its just a matter of connecting the classes together so to speak so that when a certain event happens, it would start running code from another class.

However my menu is a particularly stubborn problem. Im trying to set it so when the user enters option "1" as their choice it starts running the map code in another C++ file but its having none of it.

It gives me the following 3 errors whenever I try run the code.

```<code>1   IntelliSense: transfer of control bypasses initialization of:
        variable "A" (declared at line 37)  e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    27  3   Menu_3

2   IntelliSense: class "Map" has no member "standby"   e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    38  6   Menu_3

3   IntelliSense: return value type does not match the function type    e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    46  9   Menu_3
</code>```

This is my menu code:

```<code>#pragma once
#include "Map.h"
#include "Menu.h"
#include <iostream>
#include <string>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::string;

Menu::Menu()
{
}

void menu()
{
    int choice;

    bool gameOn = true;
    while (gameOn != false){
        cout << " 1 - Play\n";
        cout << " 2 - Quit\n";

        cin >> choice;

        switch (choice)
        {
        case 1:
            cout << "Your adventure starts now!\n";
            system("PAUSE");

            cout << "Welcome to ATAG brave adventurer!\n";
            system("PAUSE");

            //Starts the next part of the game, in this case, the map
            Map A;
            A.standby();

        //Ends the game
        case 2:
            system("PAUSE");
            exit(0);
        }
    }
    return 0;
}

Menu::~Menu()
{
}
</code>```

FYI, I'm using Visual Studio 2013 in case that helps.
Anyone got any advice because this is probably the last thing as far as code goes that's stopping me from finishing the project, and I'd be grateful if someone can tell me how to make those 3 errors go away.

答:
Here is a good explanation, why you are having this problem -> Why can't variables be declared in a switch statement?

How to fix - simply enclose case body in curly braces. This limits scope of variable A to those curly braces (not whole switch).

```<code>case 1: {
    cout << "Your adventure starts now!\n";
    system("PAUSE");
    cout << "Welcome to ATAG brave adventurer!\n";
    system("PAUSE");
    Map A;
    A.standby();
} break;
</code>```

Title: C++ Menu Code - Running another Class

Body:
OK, so Im close to wrapping up my work on this simple C++ Game and now its just a matter of connecting the classes together so to speak so that when a certain event happens, it would start running code from another class.

However my menu is a particularly stubborn problem. Im trying to set it so when the user enters option "1" as their choice it starts running the map code in another C++ file but its having none of it.

It gives me the following 3 errors whenever I try run the code.

1   IntelliSense: transfer of control bypasses initialization of:
        variable "A" (declared at line 37)  e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    27  3   Menu_3

2   IntelliSense: class "Map" has no member "standby"   e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    38  6   Menu_3

3   IntelliSense: return value type does not match the function type    e:\C++ - Copy\Menu_3\Menu_3\Menu.cpp    46  9   Menu_3

This is my menu code:

#pragma once
#include "Map.h"
#include "Menu.h"
#include <iostream>
#include <string>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::string;

Menu::Menu()
{
}

void menu()
{
    int choice;

    bool gameOn = true;
    while (gameOn != false){
        cout << " 1 - Play\n";
        cout << " 2 - Quit\n";

        cin >> choice;

        switch (choice)
        {
        case 1:
            cout << "Your adventure starts now!\n";
            system("PAUSE");

            cout << "Welcome to ATAG brave adventurer!\n";
            system("PAUSE");

            //Starts the next part of the game, in this case, the map
            Map A;
            A.standby();

        //Ends the game
        case 2:
            system("PAUSE");
            exit(0);
        }
    }
    return 0;
}

Menu::~Menu()
{
}

FYI, I'm using Visual Studio 2013 in case that helps.
Anyone got any advice because this is probably the last thing as far as code goes that's stopping me from finishing the project, and I'd be grateful if someone can tell me how to make those 3 errors go away.

Body:
Here is a good explanation, why you are having this problem -> Why can't variables be declared in a switch statement?

How to fix - simply enclose case body in curly braces. This limits scope of variable A to those curly braces (not whole switch).

case 1: {
    cout << "Your adventure starts now!\n";
    system("PAUSE");
    cout << "Welcome to ATAG brave adventurer!\n";
    system("PAUSE");
    Map A;
    A.standby();
} break;


来源: stackexchange

问:
SQL OpenQuery variable tablename
I need to transfer data from a linked server to our main SQL server. The issue is, that the table name changes everyday.
I have looked around this site to find out if it is even possible to have a variable database name, which it is, but also to see if it is possible to have variables in a OPENQUERY, which it also is.

But i am struggling to combine those needs, so i have a variable table name in a OPENQUERY.

I need something like this:

```<code>Declare @LinkedServer as varchar(max) = 'LinkedServer'
Declare @TName as varchar(max) = 'TName'+substring(cast(cast(getdate() as date) as
varchar(50)),1,4)+substring(cast(cast(getdate() as date) as
varchar(50)),6,2)+substring(cast(cast(getdate() as date) as
varchar(50)),9,2)

SELECT * FROM OPENQUERY(@LinkedServer, 'SELECT * FROM dbo.@TName')
</code>```

Is there any way i can make a variable table name in a OPENQUERY ?

Thank you for your help.

/Mikkel

答:
The answer i have, is this:

```<code>USE [DataBase]
GO

DROP SYNONYM [dbo].[eCallByCallStat]
GO

declare @tablename varchar(50)

set @tablename = 'Server1..dbo.eCallByCallStat'+substring(cast(cast(getdate()-1 as date) as varchar(50)),1,4)+substring(cast(cast(getdate()-1 as date) as varchar(50)),6,2)+substring(cast(cast(getdate()-1 as date) as varchar(50)),9,2)

declare @sql varchar(500)

set @sql = 'CREATE SYNONYM [dbo].[eCallByCallStat] FOR ' + @tablename

exec (@sql)
</code>```

This will run everymorning updating the table name in the synonym, and then we will insert that data into a prober table so we have all the data.

ContentLicense: CC BY-SA 3.0

Title: SQL OpenQuery variable tablename

Body:
I need to transfer data from a linked server to our main SQL server. The issue is, that the table name changes everyday.
I have looked around this site to find out if it is even possible to have a variable database name, which it is, but also to see if it is possible to have variables in a OPENQUERY, which it also is.

But i am struggling to combine those needs, so i have a variable table name in a OPENQUERY.

I need something like this:

Declare @LinkedServer as varchar(max) = 'LinkedServer'
Declare @TName as varchar(max) = 'TName'+substring(cast(cast(getdate() as date) as
varchar(50)),1,4)+substring(cast(cast(getdate() as date) as
varchar(50)),6,2)+substring(cast(cast(getdate() as date) as
varchar(50)),9,2)

SELECT * FROM OPENQUERY(@LinkedServer, 'SELECT * FROM dbo.@TName')

Is there any way i can make a variable table name in a OPENQUERY ?

Thank you for your help.

/Mikkel

Body:
The answer i have, is this:

USE [DataBase]
GO

DROP SYNONYM [dbo].[eCallByCallStat]
GO

declare @tablename varchar(50)

set @tablename = 'Server1..dbo.eCallByCallStat'+substring(cast(cast(getdate()-1 as date) as varchar(50)),1,4)+substring(cast(cast(getdate()-1 as date) as varchar(50)),6,2)+substring(cast(cast(getdate()-1 as date) as varchar(50)),9,2)

declare @sql varchar(500)

set @sql = 'CREATE SYNONYM [dbo].[eCallByCallStat] FOR ' + @tablename

exec (@sql)

This will run everymorning updating the table name in the synonym, and then we will insert that data into a prober table so we have all the data.


问:
How to convert an html webpage to a picture
How to convert an html webpage to a picture  like google preview.

Is there a Java library permitting this?

Is there a command-line argument to call browsers to make them convert a web page into a picture .png for instance?

答:
http://www.roseindia.net/java/example/java/swing/Print.shtml

Here's a way to do it!

ContentLicense: CC BY-SA 2.5


问:
Trying to understand how Spark Streaming works?
This might be a stupid question, but I can't seem to find any doc clarifying this in pure English (ok, exaggerated), and after reading the official doc and some blogs, I'm still confused about how driver and executors work.

Here is my current understanding:

1) Driver defines the transformation/computation.

2) Once we call SparkContext.start(), the driver will send the defined transformation/computation to all the executors, such that each executor knows how to process the incoming RDD stream data.

OK, here is some confusing questions I have:

1) Does the driver send the defined transformation/computation to all executors only ONCE AND FOR ALL?

If this is the case, we wouldn't have any chance to redefine/change the computation, right?

For example, I do a word-count job similar to this one, however my job is a little complicated, I want to count only words starting with letter J for the first 60s, and then only words starting with letter K for the next 60s, and then only words starting with ......, that goes on.

So how am I supposed to implement this streaming job in the driver?

2) Or does the driver restart/reschedule all the executors after each batch of data is done?

FOLLOWUP

To solve the 1) question, I think I could make use of some external storage media, like redis, I mean I could implement a processing function count_fn in the driver, and each time when this count_fn is called, it will read from redis to get the starting letter, and then count in the RDD stream, is this a right way to go?

答:
Does the driver send the defined transformation/computation to all
  executors only ONCE AND FOR ALL?

No, each Task is serialized and sent to all the workers per batch iteration. Think what happens when you have an instance of a class that is used inside a transformation, Spark has to able to ship that same instance with all it's state to each of the executors to operate on.

If this is the case, we wouldn't have any chance to redefine/change
  the computation, right?

The logic inside the definition of the transformation is constant, but that doesn't mean you can't query a third party which stores information which effects the data inside your transformation.

For example, assume you had some external source which indicates which letters you should filter by. Then you can either call transform on the DStream to fetch data from the driver regarding which letter to filter by.

Or does the driver restart/reschedule all the executors after each
  batch of data is done?

It doesn't restart, it simply starts a new job per batch interval. If you defined your StreamingContext batch duration to be 60 seconds, every 60 seconds a new job (micro batch) will start processing data.

As per your follow up, yes that is the way I'd do it.


问:
How to play audio file of URL link using AVAudioPlayer in iphone objective-c
I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
 testing I am experiencing an error with playing back message I created
 with AVAudioPlayer. The AVAudioplayer just returns a null value.

How do I play an audio file from the URL link with AVAudioPlayer?

```<code>if (!self.audioRecorder.recording) {

        NSURL *url = [NSURL URLWithString:[@"http://.../sound.mp4"]];
        NSLog(@"%@", url);
        NSLog(@"PlayBack");

        NSData *audioData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound1.caf"];
        [audioData writeToFile:filePath atomically:YES];

        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
        if (self.audioPlayer == nil) {
            NSLog(@"%@", [error description]);
            NSLog(@"%@", [self.audioPlayer description]);
        }else
            [self.audioPlayer play];
    }else [self.audioRecorder stop];
</code>```

答:
check this</p>

```<code> NSString* resourcePath = @""; //your url
        NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
        NSError *error;

        app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
        app.audioPlayer.numberOfLoops = 0;
        app.audioPlayer.volume = 4.0f;
        [app.audioPlayer prepareToPlay];

        if (app.audioPlayer == nil)
        NSLog(@"%@", [error description]);
        else
        [app.audioPlayer play];
</code>```

Body:
I am creating a voice communication feature in my application that sends voice notes between users via a web server, however during
 testing I am experiencing an error with playing back message I created
 with AVAudioPlayer. The AVAudioplayer just returns a null value.

How do I play an audio file from the URL link with AVAudioPlayer?

if (!self.audioRecorder.recording) {

        NSURL *url = [NSURL URLWithString:[@"http://.../sound.mp4"]];
        NSLog(@"%@", url);
        NSLog(@"PlayBack");

        NSData *audioData = [NSData dataWithContentsOfURL:url];
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                   NSUserDomainMask, YES) objectAtIndex:0]
                              stringByAppendingPathComponent:@"sound1.caf"];
        [audioData writeToFile:filePath atomically:YES];

        NSError *error;
        NSURL *fileURL = [NSURL fileURLWithPath:filePath];
        self.audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:fileURL error:&error];
        if (self.audioPlayer == nil) {
            NSLog(@"%@", [error description]);
            NSLog(@"%@", [self.audioPlayer description]);
        }else
            [self.audioPlayer play];
    }else [self.audioRecorder stop];

Body:
check this

 NSString* resourcePath = @""; //your url
        NSData *_objectData = [NSData dataWithContentsOfURL:[NSURL URLWithString:resourcePath]];
        NSError *error;

        app.audioPlayer = [[AVAudioPlayer alloc] initWithData:_objectData error:&error];
        app.audioPlayer.numberOfLoops = 0;
        app.audioPlayer.volume = 4.0f;
        [app.audioPlayer prepareToPlay];

        if (app.audioPlayer == nil)
        NSLog(@"%@", [error description]);
        else
        [app.audioPlayer play];


问:
Slim php / Eloquent custom query for hasMany-relation
I'm currently working with Slim php-framework and eloquent-database:
https://www.slimframework.com/docs/cookbook/database-eloquent.html

What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.

Let's say, I have two models "User" and "Entry".

My User.php looks like this

```<code>class User extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'users';

    public function entries() {
        return $this->hasMany('foo\bar\Entry');
    }
</code>```

}

To fetch the entries I use the following code which works as expected.

```<code>$userentries = User::find(1)->entries
</code>```

But, I'd like the entries to be fetched with a custom SQL-query like

```<code>SELECT e.user_id, e.colB, SUM(e.colC - e.colD) as foobar from entries as e where e.user_id = 1 group by e.colB order by foobar DESC;
</code>```

instead of the default SELECT * from entries where user_id = 1; but still keep the Entry-model associated to the User's entries property. Is that possible?

答:
Well, found a clean solution which is a combination of selectRaw() and eloquent local scopes: https://laravel.com/docs/5.4/eloquent#local-scopes

prototype:

I played around with the query()-functions to find out, what's possible and came up with this one

```<code>Entry::query()->selectRaw("SUM(colC - colD) as foobar, colB")->where('user_id', 1)->groupBy('colB')->orderBy('foobar', 'DESC')->get();
</code>```

to use this in a relation:

the Entry.php model looks like this:

```<code>class Entry extends \Illuminate\Database\Eloquent\Model {

    public function scopeCustom($query) {
        return $query->selectRaw("SUM(colC - colD) as foobar, colB")->groupBy('colB')->orderBy('foobar', 'DESC')->get();
    }
}
</code>```

and finally...

I can call it with:

```<code>User::find(1)->entries()->custom();
</code>```

Body:
I'm currently working with Slim php-framework and eloquent-database:
https://www.slimframework.com/docs/cookbook/database-eloquent.html

What I want to do is to use a custom SQL-query to set up a hasMany-relation of two models.

Let's say, I have two models "User" and "Entry".

My User.php looks like this

class User extends \Illuminate\Database\Eloquent\Model {
    protected $table = 'users';

    public function entries() {
        return $this->hasMany('foo\bar\Entry');
    }

}

To fetch the entries I use the following code which works as expected.

$userentries = User::find(1)->entries

But, I'd like the entries to be fetched with a custom SQL-query like

SELECT e.user_id, e.colB, SUM(e.colC - e.colD) as foobar from entries as e where e.user_id = 1 group by e.colB order by foobar DESC;

instead of the default SELECT * from entries where user_id = 1; but still keep the Entry-model associated to the User's entries property. Is that possible?

Body:
Well, found a clean solution which is a combination of selectRaw() and eloquent local scopes: https://laravel.com/docs/5.4/eloquent#local-scopes

prototype:

I played around with the query()-functions to find out, what's possible and came up with this one

Entry::query()->selectRaw("SUM(colC - colD) as foobar, colB")->where('user_id', 1)->groupBy('colB')->orderBy('foobar', 'DESC')->get();

to use this in a relation:

the Entry.php model looks like this:

class Entry extends \Illuminate\Database\Eloquent\Model {

    public function scopeCustom($query) {
        return $query->selectRaw("SUM(colC - colD) as foobar, colB")->groupBy('colB')->orderBy('foobar', 'DESC')->get();
    }
}

and finally...

I can call it with:

User::find(1)->entries()->custom();


问:
javascript - grouping objects by properties
my question is somewhat similar to javascript | Object grouping .

my input obj is

```<code>[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]
</code>```

and my required output is

```<code> [
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  }

]
</code>```

when i tried to implement the answer ,i got

```<code>[[[object Object] {
  group: "Technical detals",
  id: "60",
  name: "Display",
  value: "4"
}, [object Object] {
  group: "Technical detals",
  id: "37",
  name: "OS",
  value: "Apple iOS"
}], [[object Object] {
  group: "Manufacturer",
  id: "58",
  name: "Manufacturer",
  value: "Apple"
}]]
</code>```

i don't want to group my objects with same property into a single array .  i couldn't find out where they are pushing it into array. help me to Fix it :(

答:
Without sorting you may group by the provided property (by) as follows;

function quasiSort(a,by){
  var h = a.reduce((h,e) => h[e[by]] ? (h[e[by]].push(e), h)
                                     : (h[e[by]] = [e], h), {});
  return Object.keys(h).reduce((r,k) => r.concat(h[k]),[]);
}
var data = [{ "name":"Display",
             "group":"Technical detals",
                "id":"60",
             "value":"4"
            },
            { "name":"Manufacturer",
             "group":"Manufacturer",
                "id":"58",
             "value":"Apple"
            },
            { "name":"OS",
             "group":"Technical detals",
                "id":"37",
             "value":"Apple iOS"
            }
           ];

console.log(quasiSort(data,"group"));```

Body:
my question is somewhat similar to javascript | Object grouping .

my input obj is

[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]

and my required output is

 [
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  }

]

when i tried to implement the answer ,i got

[[[object Object] {
  group: "Technical detals",
  id: "60",
  name: "Display",
  value: "4"
}, [object Object] {
  group: "Technical detals",
  id: "37",
  name: "OS",
  value: "Apple iOS"
}], [[object Object] {
  group: "Manufacturer",
  id: "58",
  name: "Manufacturer",
  value: "Apple"
}]]

i don't want to group my objects with same property into a single array .  i couldn't find out where they are pushing it into array. help me to Fix it :(


问:
Sent Email in Google Cloud Service
I have some doubts regarding configuring email in Google Cloud service with existing applications

1.we configured the SMTP using gmail account with port 587 & try to sent mail from our google cloud instance, no email is sent.We try to ping to the port 587, it shows connection refused. Why it is happened?

2.we have seen an option to sent email using SMTP-Relay in Google cloud platform. How can we configure & setup SMTP with Google Apps email/gmail using SMTP-Relay set up?

Is there any option to send emails from google cloud for our existing application like mantis without using third-party partners like SendGrid, Mailgun and Mailjet?

答: You cannot use port 587 since GCP block all outbound traffic from that port, I suggest you use  port 2525 since that's the only smtp port that GCP does not block. </p>

Title: Sent Email in Google Cloud Service


问:
Sort descending based on part of a title in Wordpress?
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

```<code>Sweden 2017
Sweden 2016
Norway 2018
Norway 2019
</code>```

I want to sort above like this: (descending by year and ascending by name)

```<code>Norway 2019
Norway 2018
Sweden 2017
Sweden 2016
</code>```

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

```<code>$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );
</code>```

but then I get this result:

```<code>Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007
</code>```

but it should be:

```<code>Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007
</code>```

答:
First you need to split values of string and number and then convert that number in string format to intger then do order by as you like.</p>

```<code>select * from table_name order by
cast(substring(post_title,-4), INTEGER) desc,
SUBSTRING_INDEX(post_title,' ',1) asc
</code>```

Body:
I'm having an issue how to sort a title in Wordpress. If I just know how I would solve this in MySQL it would be great. (If someone has an answer specific for wordpress that would be a lot easier for me though)

I have a database where the title (one field in the database-table) is called post_title. The title stores name AND year with a space between

eg.

Sweden 2017
Sweden 2016
Norway 2018
Norway 2019

I want to sort above like this: (descending by year and ascending by name)

Norway 2019
Norway 2018
Sweden 2017
Sweden 2016

UPDATE:
I've tried with Wordpress-builtin sorting with WP_Query:

$module_args = array(
                'posts_per_page' => -1,
                'post_type' => 'project',
                'include_children' => false,
                'orderby' => 'title',
                'order' => 'DESC',
                'no_found_rows' => true          //No pagination needed
            );

//Do the filtering and retrieve all projects with current service
$projects = get_posts( $module_args );

but then I get this result:

Yacht 2011
Vasastan 2008
Ulrikagatan 2008
Thailand 2010 (?)
Strandvägen 2007

but it should be:

Yacht 2011
Thailand 2010
Ulrikagatan 2008
Vasastan 2008
Strandvägen 2007

Body:
First you need to split values of string and number and then convert that number in string format to intger then do order by as you like.

select * from table_name order by
cast(substring(post_title,-4), INTEGER) desc,
SUBSTRING_INDEX(post_title,' ',1) asc


问:
How to retrieve data in jquery from mvc list type of model
I have a class like below:

```<code>public class CustomBenefitCommittee
{
    public bool? IsChecked { get; set; }
    public bool PropertyError { get; set; }
}
</code>```

And I am using this class as a list type in MVC model like:

```<code>@model List<CustomBenefitCommittee>
</code>```

I want to retrieve data from this model in jQuery. I am trying right now as

```<code>@{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var json = serializer.Serialize(Model);
}

var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
    $.each(model, function () {
        alert(model.PropertyError );
    });
}
</code>```

This is giving me undefind. Can someone help me out getting the values from this model.

答:
From Server Side:
First you need to add actions in the controller returns JsonResult.

```<code>public JsonResult GetData(int id)
{
    var data = new
    {
      id,
      age = 23
    }
    return Json(data,JsonRequestBehavior.AllowGet);
}
</code>```

From Client Side:
you need ajax call to retrieve the data

```<code>function getData(id){
   var data = {id: id};
   $.get('/Home/GetData/', data,
         function (response) {
             alert(JSON.stringify(response));
             },'json'
    };
}
</code>```

OR
if you are sending data to model and you want to use it in your javascript or jquery code you can use NewtonSoft.Json.

First install the Package in your solution:

```<code>PM> install-package NewtoSoft.Json
</code>```

Second you can make your view like this:

```<code>@model ...
@using Newtonsoft.Json

<script type="text/javascript">

    var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));

</script>
</code>```

than you can use this data like this:

```<code>$.each(model, function(index, item) { alert(item.PropertyError); });
</code>```

And
also you can use one the javascript frameworks like Konockout.js or angularjs

Body:
I have a class like below:

public class CustomBenefitCommittee
{
    public bool? IsChecked { get; set; }
    public bool PropertyError { get; set; }
}

And I am using this class as a list type in MVC model like:

@model List<CustomBenefitCommittee>

I want to retrieve data from this model in jQuery. I am trying right now as

@{
    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    var json = serializer.Serialize(Model);
}

var model = @Html.Raw(json);
if(model != null && @Html.Raw(json) != "undefined")
{
    $.each(model, function () {
        alert(model.PropertyError );
    });
}

This is giving me undefind. Can someone help me out getting the values from this model.

Body:
From Server Side:
First you need to add actions in the controller returns JsonResult.

public JsonResult GetData(int id)
{
    var data = new
    {
      id,
      age = 23
    }
    return Json(data,JsonRequestBehavior.AllowGet);
}

From Client Side:
you need ajax call to retrieve the data

function getData(id){
   var data = {id: id};
   $.get('/Home/GetData/', data,
         function (response) {
             alert(JSON.stringify(response));
             },'json'
    };
}

OR
if you are sending data to model and you want to use it in your javascript or jquery code you can use NewtonSoft.Json.

First install the Package in your solution:

PM> install-package NewtoSoft.Json

Second you can make your view like this:

@model ...
@using Newtonsoft.Json

<script type="text/javascript">

    var data = @Html.Raw(JsonConvert.SerializeObject(this.Model));

</script>

than you can use this data like this:

$.each(model, function(index, item) { alert(item.PropertyError); });

And
also you can use one the javascript frameworks like Konockout.js or angularjs


问:
How do I drop a file from a branch and go back to the trunk version?
I have an SVN branch that has files with committed modifications on it.
We've now decided that some of these modifications are not required.

How do I effectively discard all the changes I've made to these files on the branch and get the branch to go back to using the trunk revision of these particular files?

Edit: I should have added that some of the files were new on the branch, but have subsequently been added to trunk by a completely different branch and now I want to use those. I sorted these ones by SVN Deleting them from the branch then using SVN Copy to copy the versions from the trunk - which seems to have worked.

答:
If you want the whole branch to revert to the trunk revision, I'd just create a new branch from trunk, or delete that branch and re-create it from trunk. If it's just some files you want back to trunk state, just svn copy those files from trunk into the branch.

Edit: You might also want to read The Subversion Book - Undoing Changes for a method of reversing committed changes.


问:
Validating an email address on key-press using javascript & jquery
I'm trying to prevent users from inputting invalid characters when typing-in an email address.  I am NOT trying to validate the entire value as-a-whole (that happens later).

I "thought" this was the correct way to prevent a list of characters (such as # or $):

```<code>/[A-Z0-9a-z@]^[$#<>?]/
</code>```

This part works:

```<code>/[A-Z0-9a-z@]/
</code>```

This part fails:

```<code>/^[$#<>?]/
</code>```

Any thoughts?

答:
FIXED:

The problem was some keynum values collide with undesirable characters.  This fixed it!

```<code>// **********************
// .emailOnly
// Use -
// Makes the element email-only.
//
// Example -
// $('.myElement').emailOnly();
// **********************
(function($) {
    $.fn.extend({
        emailOnly: function() {
            return this.each(function() {
                return $(this).keypress(function(e, text) {

                    var keynum;
                    var keychar;
                    var regEx;
                    var allowedKeyNums = [8, 9, 35, 36, 46]; // Backspace, Tab, End, Home, (Delete & period)

                    if (window.event) // IE
                        keynum = e.keyCode;
                    else if (e.which) // Netscape/Firefox/Opera
                        keynum = e.which;
                    else
                        keynum = e.keyCode

                    keychar = String.fromCharCode(keynum);
                    regEx = /[^$#<>?]/ // Undesirable characters

                    // Test for keynum values that collide with undesirable characters
                    if ($.inArray(keynum, allowedKeyNums) > -1)
                        return regEx.test(keychar);

                    regEx = /[A-Z0-9a-z@]/
                    return regEx.test(keychar);
                });
            });
        }
    });
})(jQuery);
</code>```

Body:
I'm trying to prevent users from inputting invalid characters when typing-in an email address.  I am NOT trying to validate the entire value as-a-whole (that happens later).

I "thought" this was the correct way to prevent a list of characters (such as # or $):

/[A-Z0-9a-z@]^[$#<>?]/

This part works:

/[A-Z0-9a-z@]/

This part fails:

/^[$#<>?]/

Any thoughts?

Body:
FIXED:

The problem was some keynum values collide with undesirable characters.  This fixed it!

// **********************
// .emailOnly
// Use -
// Makes the element email-only.
//
// Example -
// $('.myElement').emailOnly();
// **********************
(function($) {
    $.fn.extend({
        emailOnly: function() {
            return this.each(function() {
                return $(this).keypress(function(e, text) {

                    var keynum;
                    var keychar;
                    var regEx;
                    var allowedKeyNums = [8, 9, 35, 36, 46]; // Backspace, Tab, End, Home, (Delete & period)

                    if (window.event) // IE
                        keynum = e.keyCode;
                    else if (e.which) // Netscape/Firefox/Opera
                        keynum = e.which;
                    else
                        keynum = e.keyCode

                    keychar = String.fromCharCode(keynum);
                    regEx = /[^$#<>?]/ // Undesirable characters

                    // Test for keynum values that collide with undesirable characters
                    if ($.inArray(keynum, allowedKeyNums) > -1)
                        return regEx.test(keychar);

                    regEx = /[A-Z0-9a-z@]/
                    return regEx.test(keychar);
                });
            });
        }
    });
})(jQuery);


问:
SQL date comparision in yyyy/mm/dd
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

```<code>d.date_begin >= DATEADD(day,-7, GETDATE())
</code>```

is not working :), i'm TERRIBLE at convert and data type..

答:
Don't manipulate d.date_begin. Making calculation on a column while comparing can give bad performance. You should manipulate getdate() to get the same format as d.date_begin. In this case it works because the format is yyyy/MM/dd - the comparison will give the same result as if both columns were date columns.</p>

```<code>WHERE
  d.date_begin >= convert(char(10),DATEADD(day,-7, GETDATE()), 111)
</code>```

Title: SQL date comparision in yyyy/mm/dd

Body:
Not being that great at sql, i've reached my limit.
I have a date in the yyyy/mm/dd format and i need to get all records "from a week ago"
I think i need some conversion stuff to be done cause this

d.date_begin >= DATEADD(day,-7, GETDATE())

is not working :), i'm TERRIBLE at convert and data type..

Body:
Don't manipulate d.date_begin. Making calculation on a column while comparing can give bad performance. You should manipulate getdate() to get the same format as d.date_begin. In this case it works because the format is yyyy/MM/dd - the comparison will give the same result as if both columns were date columns.

WHERE
  d.date_begin >= convert(char(10),DATEADD(day,-7, GETDATE()), 111)


问:
AI scripting in Unity. Blocking Y rotation in code
I am creating a game where the world is 3D yet the characters are 2D. This means that my Y rotation must not change or else the 2D sprite rotates. I have a been scripting an AI and while the enemy does attract towards my player, he also rotates by 90 degrees. How can I modify my code to make it so that the sprite follows my player in the X and Z axis but the Y axis rotation stays zero. </p>

<pre class="lang-cs prettyprint-override"><code>//CODE STARTS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AISimple : MonoBehaviour
{
    public Transform player;
    float distancefrom_player;
    public float look_range = 20.0f;
    public float agro_range = 10.0f;
    public float move_speed = 5.0f;
    public float damping = 6.0f;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        distancefrom_player = Vector3.Distance(player.position, transform.position);

        if (distancefrom_player < look_range)
        {
            lookAt();
        }

        if (distancefrom_player < agro_range)

        {
            attack();
        }
    }

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void attack()
    {
        transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
    }

}
</code>```

答: rigidbody has this functionality, if you tick freeze y rotation you'll be fine</p>

Body:
I am creating a game where the world is 3D yet the characters are 2D. This means that my Y rotation must not change or else the 2D sprite rotates. I have a been scripting an AI and while the enemy does attract towards my player, he also rotates by 90 degrees. How can I modify my code to make it so that the sprite follows my player in the X and Z axis but the Y axis rotation stays zero.

//CODE STARTS

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AISimple : MonoBehaviour
{
    public Transform player;
    float distancefrom_player;
    public float look_range = 20.0f;
    public float agro_range = 10.0f;
    public float move_speed = 5.0f;
    public float damping = 6.0f;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        distancefrom_player = Vector3.Distance(player.position, transform.position);

        if (distancefrom_player < look_range)
        {
            lookAt();
        }

        if (distancefrom_player < agro_range)

        {
            attack();
        }
    }

    void lookAt()
    {
        Quaternion rotation = Quaternion.LookRotation(player.position - transform.position);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * damping);
    }

    void attack()
    {
        transform.Translate(Vector3.forward * move_speed * Time.deltaTime);
    }

}


问:
Offline MathML rendring support in android app
I want to render MathML offline inside Android app. I am using leathrum's APK using MathJax. Below is the code for setting up mathjax offline config(http://cs.jsu.edu/~leathrum/mjapp-src/full/MainActivity.java) :

```<code>webview.loadDataWithBaseURL("http://bar/", "<script type='text/x-mathjax-config'>"
                              +"MathJax.Hub.Config({ "
                                +"showMathMenu: false, "
                                +"jax: ['input/TeX','output/HTML-CSS'], " // output/SVG
                                +"extensions: ['tex2jax.js','toMathML.js'], "
                                +"TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
                                  +"'noErrors.js','noUndefined.js'] }, "
                              //+"'SVG' : { blacker: 30, "
                              // +"styles: { path: { 'shape-rendering': 'crispEdges' } } } "
                              +"});</script>"
                              +"<script type='text/javascript' "
                              +"src='file:///android_asset/MathJax/MathJax.js'"
                              +"></script>"
                              +"<script type='text/javascript'>getLiteralMML = function() {"
                              +"math=MathJax.Hub.getAllJax('math')[0];"
                              // below, toMathML() rerurns literal MathML string
                              +"mml=math.root.toMathML(''); return mml;"
                              +"}; getEscapedMML = function() {"
                              +"math=MathJax.Hub.getAllJax('math')[0];"
                              // below, toMathMLquote() applies &-escaping to MathML string input
                              +"mml=math.root.toMathMLquote(getLiteralMML()); return mml;}"
                              +"</script>"
                              +"<span id='math'></span>``````","text/html","utf-8","");
</code>```

Local Mathjax is in assets.It renders Tex Input properly but I am unable to configure it to take MathML as input and show result offline.

答:
To render mathml offline you need to add MathJax library to your asset folder and configure the library with web view</p>

```<code>loadDataWithBaseURL("http://bar",
    "<html><head>" +
    " <meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" />" +
    "</head>" +
    "" +
    "<body style=\"font-size:18px\" >" +
    "<b>Put here your equation</b> </br> " +
    "<script type=\"text/x-mathjax-config\">" +
    "  MathJax.Hub.Config({\n" +
    "  CommonHTML: { linebreaks: { automatic: true },EqnChunk:(MathJax.Hub.Browser.isMobile?10:50) },displayAlign: \"left\",\n" +
    "  \"HTML-CSS\": { linebreaks: { automatic: true } ," +
    "\n" +
    "    preferredFont: \"STIX\"}," +
    "extensions: [\"tex2jax.js\"],messageStyle:\"none\"," +
    "jax: [\"input/TeX\", \"input/MathML\",\"output/HTML-CSS\"]," +
    "tex2jax: {inlineMath: [['$','$'],['\\\\(','\\\\)']]}" +
    "});" +
    "</script>" +
    "<script type=\"text/javascript\" async src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>" +
    "" +
    "</body>" +
    "</html>", "text/html", "utf-8", "");

loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");
</code>```

Body:
I want to render MathML offline inside Android app. I am using leathrum's APK using MathJax. Below is the code for setting up mathjax offline config(http://cs.jsu.edu/~leathrum/mjapp-src/full/MainActivity.java) :

webview.loadDataWithBaseURL("http://bar/", ""
                              +""
                              +""
                              +"

","text/html","utf-8","");

Local Mathjax is in assets.It renders Tex Input properly but I am unable to configure it to take MathML as input and show result offline.

Body:
To render mathml offline you need to add MathJax library to your asset folder and configure the library with web view

loadDataWithBaseURL("http://bar",
    "<html><head>" +
    " <meta name=\"viewport\" content=\"width=device-width, user-scalable=yes\" />" +
    "</head>" +
    "" +
    "<body style=\"font-size:18px\" >" +
    "<b>Put here your equation</b> </br> " +
    "<script type=\"text/x-mathjax-config\">" +
    "  MathJax.Hub.Config({\n" +
    "  CommonHTML: { linebreaks: { automatic: true },EqnChunk:(MathJax.Hub.Browser.isMobile?10:50) },displayAlign: \"left\",\n" +
    "  \"HTML-CSS\": { linebreaks: { automatic: true } ," +
    "\n" +
    "    preferredFont: \"STIX\"}," +
    "extensions: [\"tex2jax.js\"],messageStyle:\"none\"," +
    "jax: [\"input/TeX\", \"input/MathML\",\"output/HTML-CSS\"]," +
    "tex2jax: {inlineMath: [['$','$'],['\\\\(','\\\\)']]}" +
    "});" +
    "</script>" +
    "<script type=\"text/javascript\" async src=\"file:///android_asset/MathJax/MathJax.js?config=TeX-AMS-MML_HTMLorMML\"></script>" +
    "" +
    "</body>" +
    "</html>", "text/html", "utf-8", "");

loadUrl("javascript:MathJax.Hub.Queue(['Typeset',MathJax.Hub]);");


问:
How to replace the following character with an empty space and write in next line?
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

```<code> string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "<br>");
</code>```

and

```<code> if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}
</code>```

But it is writing the whole line with  □....Any suggestion??

答:
It seems to me that you are having problems with Unix newlines.

Try this using this method:

```<code>public static string ConvertToWindowsNewlines(string value)
{
    value = value.Replace("\r\n", "\n");
    value = value.Replace("\n", "\r\n");
    return value;
}
</code>```

EDIT: Found solution in: http://dotnetperls.com/whitespace.

Contains some more tips on C# and char replacement.

Body:
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

 string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "
");

and

 if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}

But it is writing the whole line with  □....Any suggestion??

Body:
It seems to me that you are having problems with Unix newlines.

Try this using this method:

public static string ConvertToWindowsNewlines(string value)
{
    value = value.Replace("\r\n", "\n");
    value = value.Replace("\n", "\r\n");
    return value;
}

EDIT: Found solution in: http://dotnetperls.com/whitespace.

Contains some more tips on C# and char replacement.


问:
Convert long format with only unique comparisons to full square matrix with the diag
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

```<code>Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42
</code>```

I wonder how I can easily convert the input file into the square matrix

```<code>    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100
</code>```

答:
I think you can achieve your goal with matrix subsetting.

```<code># get row/column names of new matrix from columns 1 and 2 of data.frame
myNames <- sort(unique(as.character(unlist(df[1:2]))))

# build matrix of 0s
myMat <- matrix(0, 5, 5, dimnames = list(myNames, myNames))

# fill in upper triangle
myMat[as.matrix(df[c(1,2)])] <- df$values
# fill in the lower triangle
myMat[as.matrix(df[c(2,1)])] <- df$values
# fill in the diagonal
diag(myMat) <- 100
</code>```

which returns

```<code>myMat
    A   B   C   D   E
A 100  58  64  78  32
B  58 100  10  12  54
C  64  10 100  99  84
D  78  12  99 100  42
E  32  54  84  42 100
</code>```

Note

It is also possible to fill in the lower triangle. with

```<code>myMat[lower.tri(myMat)] <- t(myMat)[lower.tri(myMat)]
</code>```

data

```<code>df <-
structure(list(Species_A = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
2L, 3L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"),
    Species_B = structure(c(1L, 2L, 3L, 4L, 2L, 3L, 4L, 3L, 4L,
    4L), .Label = c("B", "C", "D", "E"), class = "factor"), values = c(58L,
    64L, 78L, 32L, 10L, 12L, 54L, 99L, 84L, 42L)), .Names = c("Species_A",
"Species_B", "values"), class = "data.frame", row.names = c(NA,
-10L))
</code>```

Body:
Let's say I have that kind of input data
A file with a data.frame with data in long format, and only uniques comparisons between Species_A and Species_B as follow:

Species_A Species_B values
A B 58
A C 64
A D 78
A E 32
B C 10
B D 12
B E 54
C D 99
C E 84
D E 42

I wonder how I can easily convert the input file into the square matrix

    A   B   C   D   E
A   100 58  64  78  32
B   58  100 10  12  54
C   64  10  100 99  84
D   78  12  99  100 42
E   32  54  84  42  100

Body:
I think you can achieve your goal with matrix subsetting.

# get row/column names of new matrix from columns 1 and 2 of data.frame
myNames <- sort(unique(as.character(unlist(df[1:2]))))

# build matrix of 0s
myMat <- matrix(0, 5, 5, dimnames = list(myNames, myNames))

# fill in upper triangle
myMat[as.matrix(df[c(1,2)])] <- df$values
# fill in the lower triangle
myMat[as.matrix(df[c(2,1)])] <- df$values
# fill in the diagonal
diag(myMat) <- 100

which returns

myMat
    A   B   C   D   E
A 100  58  64  78  32
B  58 100  10  12  54
C  64  10 100  99  84
D  78  12  99 100  42
E  32  54  84  42 100

Note

It is also possible to fill in the lower triangle. with

myMat[lower.tri(myMat)] <- t(myMat)[lower.tri(myMat)]

data

df <-
structure(list(Species_A = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
2L, 3L, 3L, 4L), .Label = c("A", "B", "C", "D"), class = "factor"),
    Species_B = structure(c(1L, 2L, 3L, 4L, 2L, 3L, 4L, 3L, 4L,
    4L), .Label = c("B", "C", "D", "E"), class = "factor"), values = c(58L,
    64L, 78L, 32L, 10L, 12L, 54L, 99L, 84L, 42L)), .Names = c("Species_A",
"Species_B", "values"), class = "data.frame", row.names = c(NA,
-10L))


问:
How to get Notification from standalone class (Swift 3)
I want to call method in a class as soon as observer get Notification in another one. The problem is that I cannot call one class from another, because I will get recursion call then.

1) Controller class with Player instance:

```<code>//  PlayerController.swift
//  player

import UIKit
import MediaPlayer

class NowPlayingController: NSObject {

    var musicPlayer: MPMusicPlayerController {
        if musicPlayer_Lazy == nil {
            musicPlayer_Lazy = MPMusicPlayerController.systemMusicPlayer()
            let center = NotificationCenter.default
            center.addObserver(
                self,
                selector: #selector(self.playingItemDidChange),
                name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange,
                object: musicPlayer_Lazy)
            musicPlayer_Lazy!.beginGeneratingPlaybackNotifications()
        }

        return musicPlayer_Lazy!
    }

    //If song changes
    func playingItemDidChange(notification: NSNotification) {
        //somehow call updateSongInfo() method from 2nd class
    }

    //Get song metadata
    func getSongData() -> (UIImage, String?, String?) {
        let nowPlaying = musicPlayer.nowPlayingItem

        //...some code
        return (albumImage, songName, artistAlbum)
    }

    func updateProgressBar() -> (Int?, Float?){
        let nowPlaying = musicPlayer.nowPlayingItem
        var songDuration: Int?
        var elapsedTime: Float?

        songDuration = nowPlaying?.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? Int
        elapsedTime = Float(musicPlayer.currentPlaybackTime)

        return(songDuration, elapsedTime)
    }
}
</code>```

2) View controller which should be updated when Player Controller get notification

```<code>//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let playerController = PlayerController()
    @IBOutlet weak var albumView: UIImageView!
    @IBOutlet weak var songLabel: UILabel!
    @IBOutlet weak var artistAlbum: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Start updating progress bar
        Timer.scheduledTimer(timeInterval: 0.5,
                         target: self,
                         selector: #selector(MainViewController.updateProgressBar),
                         userInfo: nil,
                         repeats: true)
    }

    private func updateSongInfo(){
        (albumView.image!, songLabel.text, artistAlbum.text) = playerController.getSongData()
    }

    private func updateProgressBar(){
        (progressBar.maximumValue, progressBar.value) = playerController.playingItemProgress()
}
}
</code>```

Solution for Swift 3:

In NowPlayingController:

```<code>let newSongNotifications = NSNotification(name:NSNotification.Name(rawValue: "updateSongNotification"), object: nil, userInfo: nil)

func playingItemDidChange(notification: NSNotification) {
        NotificationCenter.default.post(newSongNotifications as Notification)
}
</code>```

And in other controller:

```<code>override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateSongInfo), name: NSNotification.Name(rawValue: "updateSongNotification"), object: nil)
}
</code>```

答:
You can post a notification from within your custom object where you need it:

```<code>    let notification = NSNotification(name:"doSomethingNotification", object: nil, userInfo: nil)
    NotificationCenter.defaultCenter.postNotification(notification)
</code>```

And then in your other view controller in which you want to execute something in response to this notification, you tell it to observe the notification in viewDidLoad(). The selector you pass in is the method you want to be executed when the notification is received.

```<code>    override func viewDidLoad(){
        super.viewDidLoad()

        NotificationCenter.addObserver(self, selector: #selector(self.doSomething), name: "doSomethingNotification", object: nil)
    }
</code>```

Body:
I want to call method in a class as soon as observer get Notification in another one. The problem is that I cannot call one class from another, because I will get recursion call then.

1) Controller class with Player instance:

//  PlayerController.swift
//  player

import UIKit
import MediaPlayer

class NowPlayingController: NSObject {

    var musicPlayer: MPMusicPlayerController {
        if musicPlayer_Lazy == nil {
            musicPlayer_Lazy = MPMusicPlayerController.systemMusicPlayer()
            let center = NotificationCenter.default
            center.addObserver(
                self,
                selector: #selector(self.playingItemDidChange),
                name: NSNotification.Name.MPMusicPlayerControllerNowPlayingItemDidChange,
                object: musicPlayer_Lazy)
            musicPlayer_Lazy!.beginGeneratingPlaybackNotifications()
        }

        return musicPlayer_Lazy!
    }

    //If song changes
    func playingItemDidChange(notification: NSNotification) {
        //somehow call updateSongInfo() method from 2nd class
    }

    //Get song metadata
    func getSongData() -> (UIImage, String?, String?) {
        let nowPlaying = musicPlayer.nowPlayingItem

        //...some code
        return (albumImage, songName, artistAlbum)
    }

    func updateProgressBar() -> (Int?, Float?){
        let nowPlaying = musicPlayer.nowPlayingItem
        var songDuration: Int?
        var elapsedTime: Float?

        songDuration = nowPlaying?.value(forProperty: MPMediaItemPropertyPlaybackDuration) as? Int
        elapsedTime = Float(musicPlayer.currentPlaybackTime)

        return(songDuration, elapsedTime)
    }
}

2) View controller which should be updated when Player Controller get notification

//  MainViewController.swift
//  player

import UIKit

class MainViewController: UIViewController {

    let playerController = PlayerController()
    @IBOutlet weak var albumView: UIImageView!
    @IBOutlet weak var songLabel: UILabel!
    @IBOutlet weak var artistAlbum: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        //Start updating progress bar
        Timer.scheduledTimer(timeInterval: 0.5,
                         target: self,
                         selector: #selector(MainViewController.updateProgressBar),
                         userInfo: nil,
                         repeats: true)
    }

    private func updateSongInfo(){
        (albumView.image!, songLabel.text, artistAlbum.text) = playerController.getSongData()
    }

    private func updateProgressBar(){
        (progressBar.maximumValue, progressBar.value) = playerController.playingItemProgress()
}
}

Solution for Swift 3:

In NowPlayingController:

let newSongNotifications = NSNotification(name:NSNotification.Name(rawValue: "updateSongNotification"), object: nil, userInfo: nil)

func playingItemDidChange(notification: NSNotification) {
        NotificationCenter.default.post(newSongNotifications as Notification)
}

And in other controller:

override func viewDidLoad() {
    super.viewDidLoad()

    NotificationCenter.default.addObserver(self, selector: #selector(self.updateSongInfo), name: NSNotification.Name(rawValue: "updateSongNotification"), object: nil)
}

Body:
You can post a notification from within your custom object where you need it:

    let notification = NSNotification(name:"doSomethingNotification", object: nil, userInfo: nil)
    NotificationCenter.defaultCenter.postNotification(notification)

And then in your other view controller in which you want to execute something in response to this notification, you tell it to observe the notification in viewDidLoad(). The selector you pass in is the method you want to be executed when the notification is received.

    override func viewDidLoad(){
        super.viewDidLoad()

        NotificationCenter.addObserver(self, selector: #selector(self.doSomething), name: "doSomethingNotification", object: nil)
    }


问:
Laravel pass ID back from controller to view via redirect with errors
How can I pass $id back from controller to the same view when update is failed and error is trigerred.

I have view which prints all items from database and also adds edit button to each of the items which triggers modal popup window.

```<code>@for ($i =0; $i < count($inventory); $i++)

                     <tr>

                       <td> {{ $inventory[$i]->name }} </td>
                        <td>
                        <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal{{ $inventory[$i]->id }}">
                          Edit
                        </button>
</code>```

After editting all the data are passed to route via form

```<code><form action="/updateInventory/{{$inventory[$i]->id}}" method="post">
</code>```

Then it goes to my controller which validates input and then inserts input into database.

```<code>public function update(Request $req,$id)

{
    $this->validate($req, [
        'name'=> 'min:2'
        ]);
    $inventory = inventory::find($id);
    $inventory->name = $req->input('name');
    $response = $inventory->save();

    if($response)
    {
        return redirect()->back()->with(['message'=>'gerai']);
    }

    return redirect()->back()->withErrors(['error'=>'negerai']);
    //return redirect('/inventory');

}
</code>```

But if input doesn't pass validation I'm printing error like that.

```<code>@include ('partials.notice')

                    @if($errors->any())

                    <script>
                        $(function() {
                            $('#myModal{{$id}}').modal('show');
                        });
                        </script>
                    @endif
</code>```

How can I pass $id of element I just edited from controller back to the same view so when @if($errors->any()) triggers I can popup my modal $('#myModal{{$id}}').modal('show'); with element I wanted to edit.

答:
In Laravel you can flash data into the Session. In your example you can do something similar to:

```<code>$request->session()->flash('idOfError', $id);
</code>```

You can access it with :

```<code>               @if($errors->any())

                <script>
                    $(function() {
                        $('#myModal{{session()->get("idOfError")}}').modal('show');
                    });
                    </script>
                @endif
</code>```

You can see more here.

Body:
How can I pass $id back from controller to the same view when update is failed and error is trigerred.

I have view which prints all items from database and also adds edit button to each of the items which triggers modal popup window.

@for ($i =0; $i < count($inventory); $i++)

                        {{ $inventory[$i]->name }}

                        <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal{{ $inventory[$i]->id }}">
                          Edit
                        </button>

After editting all the data are passed to route via form

<form action="/updateInventory/{{$inventory[$i]->id}}" method="post">

Then it goes to my controller which validates input and then inserts input into database.

public function update(Request $req,$id)

{
    $this->validate($req, [
        'name'=> 'min:2'
        ]);
    $inventory = inventory::find($id);
    $inventory->name = $req->input('name');
    $response = $inventory->save();

    if($response)
    {
        return redirect()->back()->with(['message'=>'gerai']);
    }

    return redirect()->back()->withErrors(['error'=>'negerai']);
    //return redirect('/inventory');

}

But if input doesn't pass validation I'm printing error like that.

@include ('partials.notice')

                    @if($errors->any())

                    @endif

How can I pass $id of element I just edited from controller back to the same view so when @if($errors->any()) triggers I can popup my modal $('#myModal{{$id}}').modal('show'); with element I wanted to edit.

Body:
In Laravel you can flash data into the Session. In your example you can do something similar to:

$request->session()->flash('idOfError', $id);

You can access it with :

               @if($errors->any())

                <script>
                    $(function() {
                        $('#myModal{{session()->get("idOfError")}}').modal('show');
                    });
                    </script>
                @endif

You can see more here.


问:
Is there any tag to know type of road/highway/route in OSRM RouteStep Object?
Context : I am querying OSRM to return route between two co-ordinates. It returns me requested route along with parts(steps) with instructions for route ( Array of RouteStep bjects in v5 ).

http://project-osrm.org/docs/v5.6.4/api/#route-object

What I want : I want to know if there is way to know type of road for any particular RouteStep whether it is a motorway, highway, one way etc.

Any lead is appreciated.

答: The Annotation object has OSM node IDs but unfortunately no way IDs. It is possible to retrieve those nodes and determine the way ID(s) they belong to. The way contains the tags you are interested. Unfortunately this is not very feasible since it will require many individual requests.


问:
A potentially dangerous Request.Form value was detected from the client
Every time a user posts something containing < or > in a page in my web application, I get this exception thrown.

I don't want to go into the discussion about the smartness of throwing an exception or crashing an entire web application because somebody entered a character in a text box, but I am looking for an elegant way to handle this.

Trapping the exception and showing

An error has occurred please go back and re-type your entire form again, but this time please do not use <

doesn't seem professional enough to me.

Disabling post validation (validateRequest="false") will definitely avoid this error, but it will leave the page vulnerable to a number of attacks.

Ideally: When a post back occurs containing HTML restricted characters, that posted value in the Form collection will be automatically HTML encoded.
So the .Text property of my text-box will be something & lt; html & gt;

Is there a way I can do this from a handler?

答:
In ASP.NET MVC you need to set requestValidationMode="2.0" and validateRequest="false" in web.config, and apply a ValidateInput attribute to your controller action:

```<code><httpRuntime requestValidationMode="2.0"/>

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>
</code>```

and

```<code>[Post, ValidateInput(false)]
public ActionResult Edit(string message) {
    ...
}
</code>```

Body:
In ASP.NET MVC you need to set requestValidationMode="2.0" and validateRequest="false" in web.config, and apply a ValidateInput attribute to your controller action:

<httpRuntime requestValidationMode="2.0"/>

<configuration>
    <system.web>
        <pages validateRequest="false" />
    </system.web>
</configuration>

and

[Post, ValidateInput(false)]
public ActionResult Edit(string message) {
    ...
}


问:
Angular 2 localization with Gettext ( .po files)
I have old legacy site translated of 4 different languages with Gettext and .po files.

Now I am starting rebuilding of the site, and trying to use those files in new Angular2 site.

Is there any way I could directly use .po files?

I have tried https://github.com/ocombe/ng2-translate with https://www.npmjs.com/package/@biesbjerg/ng2-translate-po-loader
but It's not working properly when passing params to string.

Then I tried some converters, to convert .po to JSON, but they are adding some nulls and arrays...

For example converting:

```<code>msgid "meta:Reporting"
msgstr "Reporting"
</code>```

I get:

```<code>"meta:Reporting": [
    null,
    "Reporting"
]
</code>```

Instead of

```<code>"meta:Reporting" : "Reporting"
</code>```

Is there way to use directly .po files in Angular2?

答: I use ngx-translate together with ngx-translate-po-http-loader. I use them together with ngx-translate-extract to extract text from my .ts-fies to one or more .pot-files

Body:
I have old legacy site translated of 4 different languages with Gettext and .po files.

Now I am starting rebuilding of the site, and trying to use those files in new Angular2 site.

Is there any way I could directly use .po files?

I have tried https://github.com/ocombe/ng2-translate with https://www.npmjs.com/package/@biesbjerg/ng2-translate-po-loader
but It's not working properly when passing params to string.

Then I tried some converters, to convert .po to JSON, but they are adding some nulls and arrays...

For example converting:

msgid "meta:Reporting"
msgstr "Reporting"

I get:

"meta:Reporting": [
    null,
    "Reporting"
]

Instead of

"meta:Reporting" : "Reporting"

Is there way to use directly .po files in Angular2?


问:
MySQL LIKE clause with variables in CodeIgniter
I defined a model and tried to get data from two tables using the UNION keyword. Here I used the LIKE keyword as a constraint. When I use this query without variables (hard-coded variable values), it works. But it doesn't work with variables. Instead it gives an empty array. What's wrong with it?

```<code>function searchProf(){
    //$name=$this->input->post('name');
    $name='du';
    $query=$this->db->query("SELECT name FROM users WHERE  name like '%".$name."%' UNION SELECT name FROM children WHERE name like '%".$name."%' ");
    print_r ($query->result());

}
</code>```

答:
Please use active record base or SQL binding to your SQL queries. Otherwise you have to face for SQL Injections. </p>

<p>`</p>

```<code>function searchProf(){
    $name ='du';
    $sql = "SELECT name FROM users WHERE  name like ? UNION SELECT name FROM children WHERE name like ? ";
    $query = $this->db->query($sql,array('%'.$name.'%','%'.$name.'%'));
    print_r ($query->result());
}
</code>```

Body:
I defined a model and tried to get data from two tables using the UNION keyword. Here I used the LIKE keyword as a constraint. When I use this query without variables (hard-coded variable values), it works. But it doesn't work with variables. Instead it gives an empty array. What's wrong with it?

function searchProf(){
    //$name=$this->input->post('name');
    $name='du';
    $query=$this->db->query("SELECT name FROM users WHERE  name like '%".$name."%' UNION SELECT name FROM children WHERE name like '%".$name."%' ");
    print_r ($query->result());

}

Body:
Please use active record base or SQL binding to your SQL queries. Otherwise you have to face for SQL Injections.

`

function searchProf(){
    $name ='du';
    $sql = "SELECT name FROM users WHERE  name like ? UNION SELECT name FROM children WHERE name like ? ";
    $query = $this->db->query($sql,array('%'.$name.'%','%'.$name.'%'));
    print_r ($query->result());
}


问:
Explode array from mysql and assign to variables PHP
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

```<code>$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>'.$var4;
}while($result = mysql_fetch_assoc($query));
</code>```

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

答:
Your problem it´s how you are trying to get the values from the table and explode.

I use something like this:

```<code>$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)) {
$def_sessions = row(number of yor row);
$eventtype = explode(":", def_sessions);
$val0 = $eventtype[0];
$val1 = $eventtype[1];
...
}
</code>```

Body:
OK so in the database I have a column that contains data like this
:Novice:Intermediate:Advanced
( some columns have more than the 3 listed above )

What I'm trying to do is explode at the : and then assign the exploded values to variables

At most there are 4 bits of data separated by : so a max of 4 variables

Here is the code I have so far

$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysql_fetch_assoc($query);

do{
$eventtype = explode(':',$result['def_sessions']);
list($var1, $var2, $var3, $var4) = $eventtype;
//print_r(explode(":",$result['def_sessions']));
echo $var1.'
'.$var2.'
'.$var3.'
'.$var4;
}while($result = mysql_fetch_assoc($query));

It works ( to an extent )
For example record ID 13 has this in the column
:Novice:Novice/Intermediate:Intermediate/Advanced:Advanced:

The output however does NOT display the final
Advanced

it only displays
Novice
Novice/Intermediate
Intermediate/Advanced

Anyone help me please I am pulling hair out badly here .

I have also tried adding another $var5 but that doesnt help

Body:
Your problem it´s how you are trying to get the values from the table and explode.

I use something like this:

$query = mysql_query("SELECT * FROM venues",$dbc);
$result = mysqli_query($conn, $query);

while($row = mysqli_fetch_assoc($result)) {
$def_sessions = row(number of yor row);
$eventtype = explode(":", def_sessions);
$val0 = $eventtype[0];
$val1 = $eventtype[1];
...
}


问:
Detect support for the @-ms-viewport rule in Edge
Now that Microsoft has decided to move the @-ms-viewport rule in Edge behind an about:config flag, using javascript (not jquery) how do you determine if the user has that flag enabled (or is using an older version of Edge where it was still supported)?

Thread about the withdrawal of the rule here https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7970618/

答:
Maybe something like this? Please see comments in code.

function testSupportMsViewport() {
  let result = false;
  let s = document.createElement('style');
  let test = document.createElement('div');

  // create style rule to make viewport 200px in width
  // if @-ms-viewport is interpreted
  s.innerHTML = '@-ms-viewport { width: 200px; }';
  // hide any overflow hence we do not need to take scrollbars into account
  s.innerHTML += '* { overflow-y: hidden; }';
  // use fixed position, block box sizing and no paddings/margins/borders
  // together with a width of 1% (which is 2px when the viewport is 200px)
  s.innerHTML += '.foo { position: fixed; display: block; padding: 0; border: 0; margin: 0; width: 1%; }';

  test.classList += 'foo';

  // append the style element and the test div to the html element
  // applying the test styles to the div
  // note that we're not appending it to body since there may be
  // styles applied which could disturb calculations
  document.documentElement.appendChild(s);
  document.documentElement.appendChild(test);

  // check width of test div. If the browser interprets the rule,
  // it should be 2 (2px)
  // obviously, this yields a false-positive when the viewport really is just 200px in width. Think about using some other value or add additional checks
  if (parseFloat(window.getComputedStyle(test).width) === 2) {
    result = true;
  }

  // Remove elements since they're not needed anymore
  document.documentElement.removeChild(s);
  document.documentElement.removeChild(test);

  return result;
}```

I was not able to test that snippet in Edge since I'm not using Windows. However, the function returns true if the viewport is 200px in width and false otherwise.

(If you're targeting ES5, you may replace the let by var)

Body:
Maybe something like this? Please see comments in code.

function testSupportMsViewport() {
  let result = false;
  let s = document.createElement('style');
  let test = document.createElement('div');

  // create style rule to make viewport 200px in width
  // if @-ms-viewport is interpreted
  s.innerHTML = '@-ms-viewport { width: 200px; }';
  // hide any overflow hence we do not need to take scrollbars into account
  s.innerHTML += '* { overflow-y: hidden; }';
  // use fixed position, block box sizing and no paddings/margins/borders
  // together with a width of 1% (which is 2px when the viewport is 200px)
  s.innerHTML += '.foo { position: fixed; display: block; padding: 0; border: 0; margin: 0; width: 1%; }';

  test.classList += 'foo';

  // append the style element and the test div to the html element
  // applying the test styles to the div
  // note that we're not appending it to body since there may be
  // styles applied which could disturb calculations
  document.documentElement.appendChild(s);
  document.documentElement.appendChild(test);

  // check width of test div. If the browser interprets the rule,
  // it should be 2 (2px)
  // obviously, this yields a false-positive when the viewport really is just 200px in width. Think about using some other value or add additional checks
  if (parseFloat(window.getComputedStyle(test).width) === 2) {
    result = true;
  }

  // Remove elements since they're not needed anymore
  document.documentElement.removeChild(s);
  document.documentElement.removeChild(test);

  return result;
}

I was not able to test that snippet in Edge since I'm not using Windows. However, the function returns true if the viewport is 200px in width and false otherwise.

(If you're targeting ES5, you may replace the let by var)


问:
How do I strip all javascript out of an HTML document using PHP?
In my email program I use Tidy to clean up the HTML before I send out the emails. A problem is beginning to persist that if I send a mail fetching the html from a url on the web there may exist some javascript in the document.

I want to clean up this html document even more by stripping out all javascript, embedded, referenced and in any form so that the mail exist only of html.

I want to use php's preg_replace() to strip out all javascript from a mail and I need some help with the best regex because it's not my strongest point i must confess.

答:
You can use strip_tags, passing in the tags you wish to allow (whitelist) as the second parameter, but that will not remove inline JS - which might be present in onclick properties and such.

```<code>echo strip_tags($html, '<p><a><small>');
</code>```

Body:
You can use strip_tags, passing in the tags you wish to allow (whitelist) as the second parameter, but that will not remove inline JS - which might be present in onclick properties and such.

echo strip_tags($html, '<p><a><small>');


问:
Multi-line text values in Dyalog APL
How to code a multi-line text value in Dyalog APL?

I want to code something like this:

```<code>query←'
SELECT *
FROM SOME_TABLE
'
</code>```

to be able to copy this text to SQL Developer and back.

I know that I could code it this way:

```<code>query←''
query,←'SELECT * '
query,←'FROM SOME_TABLE '
</code>```

But it would not allow me to copy this text to SQL Developer and back easily.

Is it possible to temporary override the newline character in Dyalog APL function source code?

答: This feature was actually available many years ago on (mainframe) systems based on APL\360, such as Sharp APL (removed around 1980?), STSC APL*Plus, and others.  Among other things, it was no longer possible to go back edit such a line with embedded carriage returns with the normal del editor (full screen editors, as such, did not exist yet).  It was removed as it may have been confusing for users - the system expected a closing quote and just pressing return did not implicitly provide one.</p>

Title: Multi-line text values in Dyalog APL

Body:
How to code a multi-line text value in Dyalog APL?

I want to code something like this:

query←'
SELECT *
FROM SOME_TABLE
'

to be able to copy this text to SQL Developer and back.

I know that I could code it this way:

query←''
query,←'SELECT * '
query,←'FROM SOME_TABLE '

But it would not allow me to copy this text to SQL Developer and back easily.

Is it possible to temporary override the newline character in Dyalog APL function source code?


问:
How can i see the assembly version of a .NET assembly in Windows Vista and newer (WIndows 7, 2008)?
In windows 2003 and windows XP you could right click on an assembly (.dll) go to properties, click on the version tab and then you would see 3 different version numbers: Assembly version, file version and product version.

If you take that same file and look at its properties in windows 2008, you will only see file version and product version.

Is there a way to see the assembly version of a .NET assembly in windows vista and newer (without third part tools)?

答: You can always write a Shell Extension to add a property page to File Properties like it has been done here http://sbytestream.pythonanywhere.com/software/asmprops</p>


问:
Avoid changing font scale of app when changed from system settings on Android 7.0
I am working on LGE Nexus 5x which runs on Android 7.0 & I want to restrict any system font changes to change my application font size.

I have already gone through this question, and also
I have tried this answer which works perfectly upto Marshmallow. But doesn't work on Nougat.

In my Application class I have added these lines;

```<code>@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    adjustFontScale(new Configuration(newConfig));
}

public void adjustFontScale(Configuration configuration) {
    if (configuration != null && configuration.fontScale != 1.0) {
        configuration.fontScale = (float) 1.0;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        metrics.scaledDensity = configuration.fontScale * metrics.density;
        getBaseContext().getResources().updateConfiguration(configuration, metrics);
    }
}
</code>```

In manifest, under application tag I have declared;

```<code>android:configChanges="fontScale"
</code>```

But that doesn't work on Nougat devices even though onConfigurationChanged is called and executed without any exception.

Any help will be appreciated.

答:
I had the same problem. I managed to solve it by overriding onConfigurationChanged in Activity instead of Application class & changing getBaseContext() to

```<code>this.getResources().updateConfiguration(configuration, metrics);
</code>```

Body:
I am working on LGE Nexus 5x which runs on Android 7.0 & I want to restrict any system font changes to change my application font size.

I have already gone through this question, and also
I have tried this answer which works perfectly upto Marshmallow. But doesn't work on Nougat.

In my Application class I have added these lines;

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    adjustFontScale(new Configuration(newConfig));
}

public void adjustFontScale(Configuration configuration) {
    if (configuration != null && configuration.fontScale != 1.0) {
        configuration.fontScale = (float) 1.0;
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(metrics);
        metrics.scaledDensity = configuration.fontScale * metrics.density;
        getBaseContext().getResources().updateConfiguration(configuration, metrics);
    }
}

In manifest, under application tag I have declared;

android:configChanges="fontScale"

But that doesn't work on Nougat devices even though onConfigurationChanged is called and executed without any exception.

Any help will be appreciated.

Body:
I had the same problem. I managed to solve it by overriding onConfigurationChanged in Activity instead of Application class & changing getBaseContext() to

this.getResources().updateConfiguration(configuration, metrics);


问:
Display bytes as images on an .aspx page
I'm using a database to store clients' images as bytes. How can I render these images on an .aspx page?</p>

答:
This can be done easily by converting the Byte Array to a Base64 image.</p>

```<code>public string GetImageAsBase64String(byte[] bin)
{
    if (bin != null)
    {
        return "<img src=\"data:image/jpeg;base64," + Convert.ToBase64String(bin) + "\">";
    }
    else
    {
       return null;
    }
}

//usage, for demo purposes an uploaded image from a FileUpload Control
Label1.Text = GetImageAsBase64String(FileUpload1.FileBytes);
</code>```

Body:
This can be done easily by converting the Byte Array to a Base64 image.

public string GetImageAsBase64String(byte[] bin)
{
    if (bin != null)
    {
        return "<img src=\"data:image/jpeg;base64," + Convert.ToBase64String(bin) + "\">";
    }
    else
    {
       return null;
    }
}

//usage, for demo purposes an uploaded image from a FileUpload Control
Label1.Text = GetImageAsBase64String(FileUpload1.FileBytes);


问:
Draw sample from all groups in a DataFrame
How do I draw a sample (say, 10% randomly or alternatively every nth row) of rows from within each group inside a dataframe ?

e.g. from when grouping by 'name':

```<code>name    a    b
foo     1    1
foo     4    1
foo     3    3
bar     2    1
bar     3    7
bar     4    3
bar     1    2
</code>```

I want to get something like:

```<code>name    a    b
foo     4    1
bar     3    7
bar     1    2
</code>```

many thanks

答:
You can use groupby to group by your name column and then apply sample to randomly get samples from the subgroups.

First, let's see the dummy data:

```<code>print(df)

    name    a   b
0   foo     1   1
1   foo     4   1
2   foo     3   3
3   bar     2   1
4   bar     3   7
5   bar     4   3
6   bar     1   2
</code>```

fraction defines the percentage of random sample. It is set to 0.5 here for your small dummy data set:

```<code>fraction = 0.5
result = df.groupby("name", group_keys=False).apply(lambda x: x.sample(frac=fraction))

print(result)

    name    a   b
3   bar     2   1
6   bar     1   2
0   foo     1   1
2   foo     3   3
</code>```

Body:
How do I draw a sample (say, 10% randomly or alternatively every nth row) of rows from within each group inside a dataframe ?

e.g. from when grouping by 'name':

name    a    b
foo     1    1
foo     4    1
foo     3    3
bar     2    1
bar     3    7
bar     4    3
bar     1    2

I want to get something like:

name    a    b
foo     4    1
bar     3    7
bar     1    2

many thanks

Body:
You can use groupby to group by your name column and then apply sample to randomly get samples from the subgroups.

First, let's see the dummy data:

print(df)

    name    a   b
0   foo     1   1
1   foo     4   1
2   foo     3   3
3   bar     2   1
4   bar     3   7
5   bar     4   3
6   bar     1   2

fraction defines the percentage of random sample. It is set to 0.5 here for your small dummy data set:

fraction = 0.5
result = df.groupby("name", group_keys=False).apply(lambda x: x.sample(frac=fraction))

print(result)

    name    a   b
3   bar     2   1
6   bar     1   2
0   foo     1   1
2   foo     3   3


问:
Can I reuse a Transaction? and how?
I must use a corporate class that re-uses or re-creates a transaction after every Commit() or Rollback(). This class is told to use (or not use) transactions via a Boolean ctor parameter.

I am thinking of wrapping this API to separate the transaction support (to rely explicitly on Transaction objects or the ambient TransactionScope). But this requires a transaction class that is re-usable. Is there any such class in .NET? Or how would I begin to develop my own?

答:
Write a wrapper method like so

```<code>TransactionScope GetTransaction(bool useTransaction)
{
   if (useTransaction)
   {
      return new TransactionScope( /* ... */ );
   }
   return null;
}
</code>```

Using-Blocks will happily work with null-References so you could then write your code like this (where "useTransaction" is the boolean parameter you give to your class):

```<code>using (var scope = GetTransaction(useTransaction))
{
   // Code here (if useTransaction == true will use the ambient Transaction,
   // otherwhise will not run inside a transaction).

   if (scope != null)
   {
      scope.Complete();
   }
}
</code>```

OwnerDisplayName: ajmastrean

Title: Can I reuse a Transaction? and how?

Body:
Write a wrapper method like so

TransactionScope GetTransaction(bool useTransaction)
{
   if (useTransaction)
   {
      return new TransactionScope( /* ... */ );
   }
   return null;
}

Using-Blocks will happily work with null-References so you could then write your code like this (where "useTransaction" is the boolean parameter you give to your class):

using (var scope = GetTransaction(useTransaction))
{
   // Code here (if useTransaction == true will use the ambient Transaction,
   // otherwhise will not run inside a transaction).

   if (scope != null)
   {
      scope.Complete();
   }
}


问:
XML Parsing Error - Yet seems correct
I've been modding 7days to Die, a videogame on Steam as of late and it utilizes a number of XML files. I understand the basics and yet, one of the files is encountering an error despite looking, by all means, to be correct.

I am getting this error.

XML Parsing Error at line 4385
Premature end of data in tag entitygroups line 3

Pertaining to this line

```<code>< /entitygroups>
</code>```

Yes, the file begins with < entitygroups> and is sub-divided within with many < entitygroup> and < /entitygroup> entries.

I do not understand why it has an issue with the ending < /entitygroups>.

Note I had to put a space in the entitygroups brackets otherwise it wouldnt show here on the forum text.

Here is the Pastebin of the entire file if you are curious.
https://pastebin.com/B2fVPPV9

Any help is appreciated.

答: It's not exactly correct - in line #14 tag entitygroup missing end-tag </entitygroup> in #36

Title: XML Parsing Error - Yet seems correct

Body:
I've been modding 7days to Die, a videogame on Steam as of late and it utilizes a number of XML files. I understand the basics and yet, one of the files is encountering an error despite looking, by all means, to be correct.

I am getting this error.

XML Parsing Error at line 4385
Premature end of data in tag entitygroups line 3

Pertaining to this line

< /entitygroups>

Yes, the file begins with < entitygroups> and is sub-divided within with many < entitygroup> and < /entitygroup> entries.

I do not understand why it has an issue with the ending < /entitygroups>.

Note I had to put a space in the entitygroups brackets otherwise it wouldnt show here on the forum text.

Here is the Pastebin of the entire file if you are curious.
https://pastebin.com/B2fVPPV9

Any help is appreciated.


问:
How to remove anchor tags in image in wordpress plugin development?
Please click here to view image

In this image the black dot is another image on background image . I am able to embed that black dot on that post image.

```<code>    $embedCode ='div id="mainCHImage"style="position:relative;height:'.$heightOrg.'px;width:'.$widthOrg.'px;">'.
            '<img style="background:none;border:none;height:'.$heightOrg.'px !important;width:'.$widthOrg.'px !important;"'. "src=\"{$matches[1]}\";>".'

            </div>

<img id="Icon" style="position:relative;left:'.$imgWidth.'px;top: '.$imgHeight.'px;padding-left: 10px;z-index:9999;cursor:pointer;background:none;border:none;" src="/Icon.png" onClick="showProducts(event,'."'{$matches[1]}'".')"></div>
</code>```

This is code i am replacing for an image of post image in order to bring that black dot on that background image.
Now the problem is onclick of black dot i want to run a javascript function but in wordpress it is wrapped under anchor tag with href of background image and hence not getting the click event .But i have disabled the link on images then its working but its not the right way ..Below i m pasting the inspect element response of this code...

```<code><a href="http://localhost/wordpress/wp-content/uploads/2013/04/9.jpg">
  <img id="Icon" style="position:relative;left:130px;top: -30px;padding-left: 10px;z-index:9999;cursor:pointer;background:none;border:none;"
src="/Icon.png" onclick="showProducts(event,'http://localhost/wordpress/wp-content/uploads/2013/04/9.jpg')">
</code>```

I m not getting where that anchor tag is coming from ..I have nt added in my code ..

答:
```<code>    add_filter( 'the_content', 'attachment_image_link_remove_filter' );

    function attachment_image_link_remove_filter( $content ) {

            $content =preg_replace(array('{<a(.*?)(wp-att|wp-content\/uploads)[^>]*><img}','{ wp-image-[0-9]*" /></a>}'),array('<img', '" />'),             $content);

        return $content;
    }

/*place this code in your functions.php*/

/*if you wanna remove anchor tags which has image links, follow below code*/
add_filter( 'the_content', 'attachment_image_link_remove_filter' );

function attachment_image_link_remove_filter( $content ) {
    global $post;
    $exceptional_cjtypes = array("Mashup");
    $cjtype = wp_get_post_terms($post->ID, "cjtype");
    if(!in_array(strtolower($cjtype[0]->name), array_map('strtolower', $exceptional_cjtypes))) {
        $content =preg_replace(
                array('{<a href="(.*?(gif|jpeg|jpg|png))"><img}',
                    '{ wp-image-[0-9]*" /></a>}'),
                array('<img', '" />'),
                $content
            );
    }
    return $content;
}
</code>```

Body:
Please click here to view image

In this image the black dot is another image on background image . I am able to embed that black dot on that post image.

    $embedCode ='div id="mainCHImage"style="position:relative;height:'.$heightOrg.'px;width:'.$widthOrg.'px;">'.
            '".'

This is code i am replacing for an image of post image in order to bring that black dot on that background image.
Now the problem is onclick of black dot i want to run a javascript function but in wordpress it is wrapped under anchor tag with href of background image and hence not getting the click event .But i have disabled the link on images then its working but its not the right way ..Below i m pasting the inspect element response of this code...

I m not getting where that anchor tag is coming from ..I have nt added in my code ..

ContentLicense: CC BY-SA 4.0


问:
Guice injection fails somewhere in injection hierarchy
I am new to Guice and trying to achieve dependency injection in my below family of classes as below:

```<code>class DoSomethingServlet {
    @Inject
    IProvider provider;
}

interface IProvider {

}

@Singleton
class Provider implements IProvider {

    @Inject
    @Named("B")
    IManager manager;
}

interface IManager {

}

class Manager implements IManager {

    @Inject
    @Named("B")
    IDAO dao;

    @Inject
    @Named("B")
    IConverter converter;
}

interface IDAO {

}

class DAO implements IDAO {

}

interface IConverter {

}

class Converter implements IConverter {

}

import com.google.inject.AbstractModule;

class DoSomethingModule extends  AbstractModule {
    @Override
    protected void configure() {
        bind(IProvider.class).to(Provider.class);
        bind(IManager.class).annotatedWith(Names.named("B"))
            .to(Manager.class);
        bind(IDAO.class).annotatedWith(Names.named("B")).to(DAO.class);
        bind(IConverter.class).annotatedWith(Names.named("B"))
            .to(Converter.class);
    }
}
</code>```

However there is some issue due to which my request does not succeed.

If I just replace the two injects in Manager with new as below it works fine.

```<code>IDAO dao = new DAO();
IConverter converter = new Converter();
</code>```

Could you please help me in spotting the problem and also let me know how you debug dependency injection issues in Guice in general?

答:
You need to bind your servlet through guice. For that you need to follow below steps.

Create a Servlet module to add servlet binding.

```<code>public class YourServletModule extends ServletModule {
    @Override
    protected void configureServlets() {
        serve("YOUR SERVLET URL").with(DoSomethingServlet.class);
        bind(DoSomethingServlet.class).in(Singleton.class);
    }
}
</code>```

You can also add servlet mapping to module you have already created if you don't want to create separate module, but then you need to derive your module from ServletModule.

Create Guice listener as below.

```<code>public class YourContextListener extends GuiceServletContextListener{
    @Override
    public Injector getInjector(){
        return Guice.createInjector(new DoSomethingModule(),new YourServletModule());
    }
}
</code>```

Add listener tag in your web.xml.

```<code><listener>
    <listener-class>qualified class name of YourContextListener</listener-class>
</listener>
</code>```

Add guice filter to web.xml to map filter to servlet url pattern.

```<code><filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>YOUR SERVLET URL</url-pattern>
</filter-mapping>
</code>```

Body:
I am new to Guice and trying to achieve dependency injection in my below family of classes as below:

class DoSomethingServlet {
    @Inject
    IProvider provider;
}

interface IProvider {

}

@Singleton
class Provider implements IProvider {

    @Inject
    @Named("B")
    IManager manager;
}

interface IManager {

}

class Manager implements IManager {

    @Inject
    @Named("B")
    IDAO dao;

    @Inject
    @Named("B")
    IConverter converter;
}

interface IDAO {

}

class DAO implements IDAO {

}

interface IConverter {

}

class Converter implements IConverter {

}

import com.google.inject.AbstractModule;

class DoSomethingModule extends  AbstractModule {
    @Override
    protected void configure() {
        bind(IProvider.class).to(Provider.class);
        bind(IManager.class).annotatedWith(Names.named("B"))
            .to(Manager.class);
        bind(IDAO.class).annotatedWith(Names.named("B")).to(DAO.class);
        bind(IConverter.class).annotatedWith(Names.named("B"))
            .to(Converter.class);
    }
}

However there is some issue due to which my request does not succeed.

If I just replace the two injects in Manager with new as below it works fine.

IDAO dao = new DAO();
IConverter converter = new Converter();

Could you please help me in spotting the problem and also let me know how you debug dependency injection issues in Guice in general?

Body:
You need to bind your servlet through guice. For that you need to follow below steps.

Create a Servlet module to add servlet binding.

public class YourServletModule extends ServletModule {
    @Override
    protected void configureServlets() {
        serve("YOUR SERVLET URL").with(DoSomethingServlet.class);
        bind(DoSomethingServlet.class).in(Singleton.class);
    }
}

You can also add servlet mapping to module you have already created if you don't want to create separate module, but then you need to derive your module from ServletModule.

Create Guice listener as below.

public class YourContextListener extends GuiceServletContextListener{
    @Override
    public Injector getInjector(){
        return Guice.createInjector(new DoSomethingModule(),new YourServletModule());
    }
}

Add listener tag in your web.xml.

<listener>
    <listener-class>qualified class name of YourContextListener</listener-class>
</listener>

Add guice filter to web.xml to map filter to servlet url pattern.

<filter>
    <filter-name>guiceFilter</filter-name>
    <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>guiceFilter</filter-name>
    <url-pattern>YOUR SERVLET URL</url-pattern>
</filter-mapping>