问:
I can't create a simple dataBase in EntityFramework Core
I'm a realy newbie in EntityFramework and Core.

I want to create a simple DataBase in EntityFramework Core 2.0. The project is a ConsoleApplication that I included it a Microsoft.AspNetCore.All by Nuget package. This is a code:

```<code>namespace TestEF
{
class Program
{
    static void Main(string[] args)
    {
        string connStr = "Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connStr).Options);
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet<Student> Students { get; set; }
}
}
</code>```

I'm loggin into a intranet as username "gmiranda". When I run the project I get the following message error:

System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Cannot open database "SchoolDataBase" requested by the login. The login failed.
Login failed for user 'domain\gmiranda'.

What is I doing wrong ?
Thanks !

答:
You should try this code:

```<code>class Program
{
    static void Main(string[] args)
    {
        string connStr = "Data Source=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext();
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext() : base()
    {

    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true");
    }
    public DbSet<Student> Students { get; set; }
}
</code>```

Then open Package Manager Console  and use command Add-Migration FirstMigrarion.
Its add migration to your database with name FirsMigration.
Then use command Update-Database.
Then run your program.

Try use this tutorial: https://learn.microsoft.com/en-us/ef/core/get-started/full-dotnet/new-db

Body:
I'm a realy newbie in EntityFramework and Core.

I want to create a simple DataBase in EntityFramework Core 2.0. The project is a ConsoleApplication that I included it a Microsoft.AspNetCore.All by Nuget package. This is a code:

namespace TestEF
{
class Program
{
    static void Main(string[] args)
    {
        string connStr = "Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext(SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), connStr).Options);
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions options) : base(options)
    {
    }
    public DbSet<Student> Students { get; set; }
}
}

I'm loggin into a intranet as username "gmiranda". When I run the project I get the following message error:

System.Data.SqlClient.SqlException occurred
  HResult=0x80131904
  Message=Cannot open database "SchoolDataBase" requested by the login. The login failed.
Login failed for user 'domain\gmiranda'.

What is I doing wrong ?
Thanks !

Body:
You should try this code:

class Program
{
    static void Main(string[] args)
    {
        string connStr = "Data Source=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true";

        var db = new SchoolContext();
        db.Students.Add(
            new Student()
            {
                LastName = "Miranda",
                EnrollmentDate = DateTime.Now,
                FirstMidName = "Guillermo"
            });
        db.SaveChanges();

        Console.WriteLine("Hello World!");
        Console.ReadLine();
    }
}

public class Student
{
    public int ID { get; set; }
    public string LastName { get; set; }
    public string FirstMidName { get; set; }
    public DateTime EnrollmentDate { get; set; }
}

public class SchoolContext : DbContext
{
    public SchoolContext() : base()
    {

    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=SchoolDataBase;Trusted_Connection=True;MultipleActiveResultSets=true");
    }
    public DbSet<Student> Students { get; set; }
}

Then open Package Manager Console  and use command Add-Migration FirstMigrarion.
Its add migration to your database with name FirsMigration.
Then use command Update-Database.
Then run your program.

Try use this tutorial: https://learn.microsoft.com/en-us/ef/core/get-started/full-dotnet/new-db


来源: stackexchange

问:
Oracle SQL, IF statements
I’m running a query from a table that has info on account numbers, settled charges , the write off figure, and the reason for the write off; so the table is called group_write_off and the table headings, account_id, charge_settled_date, total_charge_amount, amount_written_off, write_off_reason. What I want to do, is pull everything through, so

Select * from
group_write_off

but for any case where the write_off_reason includes the word ‘Audit’, I want amount_written_off to show as 0 (zero), for all others i want the original amount_written_off to show.

Many thanks.

答:
Use CASE expression.

```<code>SELECT CASE WHEN write_off_reason='Audit' THEN 0 ELSE amount_written_off END
FROM group_write_off
</code>```

Also try below for checking if Audit word is present in column write_off_reason by using INSTR() function

```<code>SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0 ELSE amount_written_off END
FROM group_write_off
</code>```

If you want more words

```<code>SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0
       WHEN INSTR(write_off_reason,'admin') = 0 THEN 0
       ELSE amount_written_off END
FROM group_write_off
</code>```

ContentLicense: CC BY-SA 3.0

Title: Oracle SQL, IF statements

Body:
Use CASE expression.

SELECT CASE WHEN write_off_reason='Audit' THEN 0 ELSE amount_written_off END
FROM group_write_off

Also try below for checking if Audit word is present in column write_off_reason by using INSTR() function

SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0 ELSE amount_written_off END
FROM group_write_off

If you want more words

SELECT CASE WHEN INSTR(write_off_reason,'Audit') = 0 THEN 0
       WHEN INSTR(write_off_reason,'admin') = 0 THEN 0
       ELSE amount_written_off END
FROM group_write_off


问:
Fixed point multiply/divide for 15.16 numbers
I am looking for an algorithm to multiply and divide fixed point 15.16 numbers.

I already have addition and subtraction. Those were easy - simple 32-bit add and subtract. With multiply and divide, I can also add many trigonometric and exponential/log functions. And I think I can deal with just multiply, as my library has a reciprocal function and I can use that to implement division: a * (1/b) = a / b. But a 32-bit multiply does not work as it ignores the radix point.

I am working on a 16-bit microcontroller, so I would like to avoid anything more than 32-bit multiply, which takes about 4 cycles on my processor. It's not crucial though, I'm just trying to replace floating point math.

I have heard I need to shift or rotate the result, but I am not sure how this would help or specifically how to shift it. Any suggestions or help appreciated!

答: The multiplication is easily done with 64-bit multiply: (a * b) >> 16. Division, similarly, is easily done with 64 bits: (a << 16) / b. Depending on your rounding / error requirements, you might want to complicate that slightly in order to get the last bit of the output correct.

ContentLicense: CC BY-SA 2.5


问:
How can we deal with different HTTP response from error?
I'm working on simple authentication with my backend.

My action can't handle try-catch and I have no idea why it's not working as I expected because it worked a month ago.

```<code>export const doAuthLogin = ( username, password ) => async dispatch => {
  console.log('passing action'); <- print 'passing action'
  let response = await axios.post(`${ROOT_URL}/rest-auth/login/`, {
    username,
    password,
  }); <- shows 400 error on console (Expo)

  console.log(response.status); <- print nothing // well 200 can prints status here
  console.log('doesn't work); <- print nothing

  if (response.status === 200) { <- doesn't execute
</code>```

答:
You are using a try-catch block for a async operation (post). That's not correct. The operation runs and before there is a response (the "async" response) your code continues to run and end.

Your async operation must have a callback function parameter that deals with the response.

Body:
I'm working on simple authentication with my backend.

My action can't handle try-catch and I have no idea why it's not working as I expected because it worked a month ago.

export const doAuthLogin = ( username, password ) => async dispatch => {
  console.log('passing action'); <- print 'passing action'
  let response = await axios.post(`${ROOT_URL}/rest-auth/login/`, {
    username,
    password,
  }); <- shows 400 error on console (Expo)

  console.log(response.status); <- print nothing // well 200 can prints status here
  console.log('doesn't work); <- print nothing

  if (response.status === 200) { <- doesn't execute


问:
how do i add a edit, delete, details and create new icon in @html.actionLink in mvc
This is html of mvc and this is my format on html:</p>

```<code> 1. @*@Html.ActionLink("Delete", "Delete", new { id=item.ActivityDepreciationTypeId })*@

 2. @*@Html.ActionLink("Details", "Details", new { id=item.ActivityDepreciationTypeId })*@

 3.@*@Html.ActionLink("Edit", "Edit", new { id=item.ActivityDepreciationTypeId }) |*@

 4. @*@Html.ActionLink("Create New", "Create")*@
</code>```

答:
lets say that for example

@Html.ActionLink(" Login", "Index", new { @class = "glyphicon glyphicon-log-in" })

Body:
This is html of mvc and this is my format on html:

 1. @*@Html.ActionLink("Delete", "Delete", new { id=item.ActivityDepreciationTypeId })*@

 2. @*@Html.ActionLink("Details", "Details", new { id=item.ActivityDepreciationTypeId })*@

 3.@*@Html.ActionLink("Edit", "Edit", new { id=item.ActivityDepreciationTypeId }) |*@

 4. @*@Html.ActionLink("Create New", "Create")*@


问:
Some way to get Scope from angular.element with debugInfo turned off
There is some way to get $scope from angular.element() when the debugInfoEnabled is Disable.

```<code>angular.element(document.querySelector('some-cool-element')).scope() // Undefined
</code>```

答:
angular.element($0).scope()

This is a duplicate question for this one

How do I access the $scope variable in browser's console using AngularJS?

Body:
There is some way to get $scope from angular.element() when the debugInfoEnabled is Disable.

angular.element(document.querySelector('some-cool-element')).scope() // Undefined


问:
Printing an array of ascii values to the console as a string in assembly language 8086?
I'm new to assembly language coding and there's this program I'm trying to work out where I initialize an array of letters (in ascii), loop through it, and print it to the console window as a concatenated string. This is what I have so far:

```<code>.MODEL flat

.DATA

    name1 DB 4Ah, 69h, 6Dh, 6Dh, 79h

.CODE

main        PROC

            mov ecx, 0
            mov esi, offset name1

loop1:

            mov dl, [esi]
            mov ah, 2
            inc esi
            inc ecx
            cmp ecx, 5
            jne loop1

endlp:

            mov eax, 4c00h
            ret

main        ENDP

END
</code>```

I'm pretty lost. Some of what I have here is from others trying to help me, so sorry if it looks messy.

答:
Everything about your question cries DOS. I would suggest you use the tiny model for these simple demonstration programs.

In the 16-bit environment it's natural to use 16-bit registers.

To execute DOS api services you place the requested parameters in selected registers and store the function number in the AH register. Then you issue an int 21h call.

A more efficient loop will count downward. Often you can avoid the need to compare before looping back because the flags have been set by the dec instruction.

If you place the data of your program below the code that exits to DOS, you avoid mistakenly executing it.

You can write an array of ASCII codes easier as a string. See the 3rd example.

```<code> ORG 256            ;This asks for the tiny model

 mov  cx, 5
 mov  si, offset array
again:
 mov  dl, [si]
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 dec  cx
 jnz  again

 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 4Ah, 69h, 6Dh, 6Dh, 79h
</code>```

An alternative program doesn't use the CX counter at all. It suffices to stop when the pointer SI is pointing beyond the last character.

```<code> ORG  256            ;This asks for the tiny model

 mov  si, offset array
again:
 mov  dl, [si]
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 cmp  si, offset array+5
 jb   again

 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 4Ah, 69h, 6Dh, 6Dh, 79h
</code>```

Another alternative program uses a zero delimiter on the array. To see if the delimiter was reached, you can write cmp dl, 0 je exit but a bit better is to write test dl, dl jz exit.

```<code> ORG  256            ;This asks for the tiny model

 mov  si, offset array
again:
 mov  dl, [si]
 test dl, dl         ;Test for zero delimiter
 jz   exit
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 jmp  again
exit:
 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 'Jimmy', 0
</code>```

Body:
I'm new to assembly language coding and there's this program I'm trying to work out where I initialize an array of letters (in ascii), loop through it, and print it to the console window as a concatenated string. This is what I have so far:

.MODEL flat

.DATA

    name1 DB 4Ah, 69h, 6Dh, 6Dh, 79h

.CODE

main        PROC

            mov ecx, 0
            mov esi, offset name1

loop1:

            mov dl, [esi]
            mov ah, 2
            inc esi
            inc ecx
            cmp ecx, 5
            jne loop1

endlp:

            mov eax, 4c00h
            ret

main        ENDP

END

I'm pretty lost. Some of what I have here is from others trying to help me, so sorry if it looks messy.

Body:
Everything about your question cries DOS. I would suggest you use the tiny model for these simple demonstration programs.

In the 16-bit environment it's natural to use 16-bit registers.

To execute DOS api services you place the requested parameters in selected registers and store the function number in the AH register. Then you issue an int 21h call.

A more efficient loop will count downward. Often you can avoid the need to compare before looping back because the flags have been set by the dec instruction.

If you place the data of your program below the code that exits to DOS, you avoid mistakenly executing it.

You can write an array of ASCII codes easier as a string. See the 3rd example.

 ORG 256            ;This asks for the tiny model

 mov  cx, 5
 mov  si, offset array
again:
 mov  dl, [si]
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 dec  cx
 jnz  again

 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 4Ah, 69h, 6Dh, 6Dh, 79h

An alternative program doesn't use the CX counter at all. It suffices to stop when the pointer SI is pointing beyond the last character.

 ORG  256            ;This asks for the tiny model

 mov  si, offset array
again:
 mov  dl, [si]
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 cmp  si, offset array+5
 jb   again

 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 4Ah, 69h, 6Dh, 6Dh, 79h

Another alternative program uses a zero delimiter on the array. To see if the delimiter was reached, you can write cmp dl, 0 je exit but a bit better is to write test dl, dl jz exit.

 ORG  256            ;This asks for the tiny model

 mov  si, offset array
again:
 mov  dl, [si]
 test dl, dl         ;Test for zero delimiter
 jz   exit
 mov  ah, 02h
 int  21h            ;Display character
 inc  si
 jmp  again
exit:
 mov  ax, 4C00h
 int  21h            ;Exit the program

array db 'Jimmy', 0


问:
Codename One - Show number of unread messages in the app icon
Please look at the Signal icon in this screenshot:

My question is how to obtain the same result in a Codename One app. Suppose that my app has a variable like "int unreadMdg", how can I show the number of unread message in the app icon?

答:
This is for IOS

Use this to make it displays a specific number

// Objective-C

```<code> [UIApplication sharedApplication].applicationIconBadgeNumber = number;
</code>```

// Swift

```<code>  UIApplication.shared.applicationIconBadgeNumber = number
</code>```

Body:
This is for IOS

Use this to make it displays a specific number

// Objective-C

 [UIApplication sharedApplication].applicationIconBadgeNumber = number;

// Swift

  UIApplication.shared.applicationIconBadgeNumber = number


问:
Can we use egit in another RCP app?
I have an app that manages some files. I want to integrate git to this. Can I use EGit in this case? Or I must use JGit?

I'm trying to build egit but not yet successful. I just want to know if I can integrate EGit to my RCP app. Thank you!

答:
Jgit is basically the library which includes java implementation of git, Egit on the other hand, includes the UI part and the Jgit for the core git operations.

You can simply add the Egit plugin to your required plugins and it should work, if only your app is 3.X RCP based, I don't think it'll work in a pure RCP-4 application.

Title: Can we use egit in another RCP app?


问:
str.join() adds backslashes to my variable
I am using Python 3.5 and PyCharm 2017.3

My code appears as following:

```<code>var1 = 'ASD'
var2 = 'ASDPO'
qryPwr = ''.join(['select DATE as "DATE"'
                       ' from Table1 where MKT = ', "'", var1, "'",
                       ' and COMP = ', "'", var2, "'",
                       ' and ppow_vdays = 0'
                       ' and PPOW_SETTLE = ', "'", 'S', "'"])
</code>```

I get the following for qryPqr:

```<code>qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''
</code>```

So, I have two questions:

(1) Why are there backslashes everywhere?

(2) How do I get rid of them or make my join statement better?

Edit:
I want to remove the backslashes from the print statement as when I do the database query using qryPwr it tries to run the query with backslashes and hence errors out.

答:
There are no backslashes in the variable, they are just in the printed output.

The shell does not print the variable directly, but calls repr() on it. This function

makes an attempt to return a string that would yield an object with the same value when passed to eval()

Usually, repr just wraps strings in quotes:

```<code>>>> "abc" # actually calls repr("abc")
'abc'
</code>```

If your string contains one kind of quotes, it uses the other kind:

```<code>>>> "ab'c"
"ab'c"
>>> 'ab"c'
'ab"c'
</code>```

But your string contains both kinds of quotes. If you would want to specify that in your code, you could either join string literals which each only have one kind (like you did), or escape one kind:

```<code>>>> "a\"b'c"
'a"b\'c'
>>> 'a"b\'c'
'a"b\'c'
</code>```

This escaping is exactly what repr does when you output a string representation of the variable to the command line.

One side note: You are building a SQL query by concatenating fixed parts and (user supplied?) variables. Please don't do that. Please use at least prepared statements, or better a wrapper library like SQLAlchemy. This does not only make it easier to handle database connections, but also much more secure.

Body:
I am using Python 3.5 and PyCharm 2017.3

My code appears as following:

var1 = 'ASD'
var2 = 'ASDPO'
qryPwr = ''.join(['select DATE as "DATE"'
                       ' from Table1 where MKT = ', "'", var1, "'",
                       ' and COMP = ', "'", var2, "'",
                       ' and ppow_vdays = 0'
                       ' and PPOW_SETTLE = ', "'", 'S', "'"])

I get the following for qryPqr:

qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''

So, I have two questions:

(1) Why are there backslashes everywhere?

(2) How do I get rid of them or make my join statement better?

Edit:
I want to remove the backslashes from the print statement as when I do the database query using qryPwr it tries to run the query with backslashes and hence errors out.

Body:
There are no backslashes in the variable, they are just in the printed output.

The shell does not print the variable directly, but calls repr() on it. This function

makes an attempt to return a string that would yield an object with the same value when passed to eval()

Usually, repr just wraps strings in quotes:

>>> "abc" # actually calls repr("abc")
'abc'

If your string contains one kind of quotes, it uses the other kind:

>>> "ab'c"
"ab'c"
>>> 'ab"c'
'ab"c'

But your string contains both kinds of quotes. If you would want to specify that in your code, you could either join string literals which each only have one kind (like you did), or escape one kind:

>>> "a\"b'c"
'a"b\'c'
>>> 'a"b\'c'
'a"b\'c'

This escaping is exactly what repr does when you output a string representation of the variable to the command line.

One side note: You are building a SQL query by concatenating fixed parts and (user supplied?) variables. Please don't do that. Please use at least prepared statements, or better a wrapper library like SQLAlchemy. This does not only make it easier to handle database connections, but also much more secure.


问:
Convert Array of Dictionary to custom object swift
I have:

```<code>    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]
</code>```

I want to add all this array of dictionary to my custom object like

```<code>let country:[Country] = countries
</code>```

My custom object looks like this:

```<code>class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }
</code>```

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

答:
You can use flatMap method of a list to produce the result:

```<code>countries.flatMap { (v: [String: Any]) -> Country? in
    if let name = v["name"] as? String,
       let dial = v["dial_code"] as? String,
       let code = v["code"] as? String {
        return Country(name: name, dial_code: dial, code: code)
    } else {
        return nil
    }
}
</code>```

A full example would be:

```<code>//: Playground - noun: a place where people can play

import UIKit

let countries : [[String : Any]] = [
    [
        "name" : "Afghanistan",
        "dial_code": "+93",
        "code": "AF"
    ],
    [
        "name": "Aland Islands",
        "dial_code": "+358",
        "code": "AX"
    ],
    [
        "name": "Albania",
        "dial_code": "+355",
        "code": "AL"
    ],
    [
        "name": "Algeria",
        "dial_code": "+213",
        "code": "DZ"
    ]
]

class Country: NSObject {
    let name: String
    let dial_code : String
    let code: String

    init(name: String, dial_code: String, code: String) {
        self.name = name
        self.dial_code = dial_code
        self.code = code
    }
}

let cnt = countries.flatMap { (v: [String: Any]) -> Country? in
    if let name = v["name"] as? String, let dial = v["dial_code"] as? String, let code = v["code"] as? String {
        return Country(name: name, dial_code: dial, code: code)
    } else {
        return nil
    }
}

print (cnt)
</code>```

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
You can use flatMap method of a list to produce the result:

countries.flatMap { (v: [String: Any]) -> Country? in
    if let name = v["name"] as? String,
       let dial = v["dial_code"] as? String,
       let code = v["code"] as? String {
        return Country(name: name, dial_code: dial, code: code)
    } else {
        return nil
    }
}

A full example would be:

//: Playground - noun: a place where people can play

import UIKit

let countries : [[String : Any]] = [
    [
        "name" : "Afghanistan",
        "dial_code": "+93",
        "code": "AF"
    ],
    [
        "name": "Aland Islands",
        "dial_code": "+358",
        "code": "AX"
    ],
    [
        "name": "Albania",
        "dial_code": "+355",
        "code": "AL"
    ],
    [
        "name": "Algeria",
        "dial_code": "+213",
        "code": "DZ"
    ]
]

class Country: NSObject {
    let name: String
    let dial_code : String
    let code: String

    init(name: String, dial_code: String, code: String) {
        self.name = name
        self.dial_code = dial_code
        self.code = code
    }
}

let cnt = countries.flatMap { (v: [String: Any]) -> Country? in
    if let name = v["name"] as? String, let dial = v["dial_code"] as? String, let code = v["code"] as? String {
        return Country(name: name, dial_code: dial, code: code)
    } else {
        return nil
    }
}

print (cnt)


答:
```<code>df.value = df.value.interpolate(method='nearest')
</code>```

Title: Fill missing values in a data frame with the nearest row

Body:
I have the following data frame:

df = pd.DataFrame({'id': {3002: 10001,
  3003: 10002,
  3004: 10003,
  3005: 10004,
  3006: 10005,
  3007: 10006,
  3008: 10007,
  3009: 10008,
  3010: 10009,
  3011: 10010,
  3012: 10011,
  3013: 10012,
  3014: 10013,
  3015: 10014,
  3016: 10015,
  3017: 10016,
  3018: 10017,
  3019: 10018,
  3020: 10019,
  3021: 10020},
 'value': {3002: 1669.0,
  3003: 1264.0,
  3004: nan,
  3005: 1411.0,
  3006: 1224.0,
  3007: 1316.0,
  3008: 1736.0,
  3009: nan,
  3010: 1276.0,
  3011: nan,
  3012: nan,
  3013: nan,
  3014: nan,
  3015: 1790.0,
  3016: nan,
  3017: nan,
  3018: nan,
  3019: 1726.0,
  3020: nan,
  3021: nan}})

And I want to fill the missing values with the one in the nearest id, in case of two values at the same distance then I want to use the average.

E.G.

id 10008 is NaN, then I want to fill the cell with the average of  10009 and 10007: (1736.0 + 1276.0)/2

for id 10015 the nearest value is at 10014 so I'll use that value directly: 1790.0

How can I accomplish this efficiently?


问:
Trimming 0x00 in received DatagramPacket
In my Java app I receive DatagramPacket(s) through DatagramSocket. I know the maximum number of bytes which packet could contain, but actually every packet length varies (not exceeding max length).

Let's assume that MAX_PACKET_LENGTH = 1024 (bytes). So every time DatagramPacket is received it is 1024 bytes long, but not always all bytes contains information. It may happen that packet has 10 bytes of useful data, and the rest of 1014 bytes is filled with 0x00.

I am wondering if there is any elegant way to trim this 0x00 (unused) bytes in order to pass to the other layer only useful data? (maybe some java native methods? going in a loop and analysing what packet contains is not desired solution :))

Thanks for all hints.
Piotr

答: You can call getLength on the DatagramPacket to return the ACTUAL length of the packet, which may be less than MAX_PACKET_LENGTH.</p>


问:
Customized strikethrough on title
I'm creating a website to school project and i want to put a strikethrough behind my title like in this image. I want that green lines behind text

I am working with HTML and CSS , someone know the code to get that beautiful strikethrough?

答:
This is an example , adjust as you wish, but you get the idea.

h2 {
    font: 33px sans-serif;
    margin-top: 30px;
    text-align: center;
    text-transform: uppercase;
    color: red;
}

h2.background {
    position: relative;
    z-index: 1;
    }

h2.background:before {
        border-top: 2px solid #000;
        content:"";
        margin: 0 auto; /* this centers the line to the full width specified */
        position: absolute; /* positioning must be absolute here, and relative positioning must be applied to the parent */
        top: 50%; left: 0; right: 0; bottom: 0;
        width: 95%;
        z-index: -1;
}
    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2 class="background">Random Title</h2></code>```

Title: Customized strikethrough on title

Body:
This is an example , adjust as you wish, but you get the idea.

h2 {
    font: 33px sans-serif;
    margin-top: 30px;
    text-align: center;
    text-transform: uppercase;
    color: red;
}

h2.background {
    position: relative;
    z-index: 1;
    }

h2.background:before {
        border-top: 2px solid #000;
        content:"";
        margin: 0 auto; /* this centers the line to the full width specified */
        position: absolute; /* positioning must be absolute here, and relative positioning must be applied to the parent */
        top: 50%; left: 0; right: 0; bottom: 0;
        width: 95%;
        z-index: -1;
}

<h2 class="background">Random Title</h2>


问:
What is the most accurate way to retrieve a user's correct IP address in PHP?
I know there are a plethora of $_SERVER variables headers available for IP address retrieval. I was wondering if there is a general consensus as to how to most accurately retrieve a user's real IP address (well knowing no method is perfect) using said variables?

I spent some time trying to find an in depth solution and came up with the following code based on a number of sources. I would love it if somebody could please poke holes in the answer or shed some light on something perhaps more accurate.

edit includes optimizations from @Alix

```<code> /**
  * Retrieves the best guess of the client's actual IP address.
  * Takes into account numerous HTTP proxy headers due to variations
  * in how different ISPs handle IP addresses in headers between hops.
  */
 public function get_ip_address() {
  // Check for shared internet/ISP IP
  if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
   return $_SERVER['HTTP_CLIENT_IP'];

  // Check for IPs passing through proxies
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
   // Check if multiple IP addresses exist in var
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    foreach ($iplist as $ip) {
     if ($this->validate_ip($ip))
      return $ip;
    }
   }
  }
  if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
   return $_SERVER['HTTP_X_FORWARDED'];
  if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
   return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
  if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
   return $_SERVER['HTTP_FORWARDED_FOR'];
  if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
   return $_SERVER['HTTP_FORWARDED'];

  // Return unreliable IP address since all else failed
  return $_SERVER['REMOTE_ADDR'];
 }

 /**
  * Ensures an IP address is both a valid IP address and does not fall within
  * a private network range.
  *
  * @access public
  * @param string $ip
  */
 public function validate_ip($ip) {
     if (filter_var($ip, FILTER_VALIDATE_IP,
                         FILTER_FLAG_IPV4 |
                         FILTER_FLAG_IPV6 |
                         FILTER_FLAG_NO_PRIV_RANGE |
                         FILTER_FLAG_NO_RES_RANGE) === false)
         return false;
     self::$ip = $ip;
     return true;
 }
</code>```

Words of Warning (update)

REMOTE_ADDR still represents the most reliable source of an IP address. The other $_SERVER variables mentioned here can be spoofed by a remote client very easily. The purpose of this solution is to attempt to determine the IP address of a client sitting behind a proxy. For your general purposes, you might consider using this in combination with the IP address returned directly from $_SERVER['REMOTE_ADDR'] and storing both.

For 99.9% of users this solution will suit your needs perfectly. It will not protect you from the 0.1% of malicious users looking to abuse your system by injecting their own request headers. If relying on IP addresses for something mission critical, resort to REMOTE_ADDR and don't bother catering to those behind a proxy.

答:
My answer is basically just a polished, fully-validated, and fully-packaged, version of @AlixAxel's answer:

```<code><?php

/* Get the 'best known' client IP. */

if (!function_exists('getClientIP'))
    {
        function getClientIP()
            {
                if (isset($_SERVER["HTTP_CF_CONNECTING_IP"]))
                    {
                        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                    };

                foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
                    {
                        if (array_key_exists($key, $_SERVER))
                            {
                                foreach (explode(',', $_SERVER[$key]) as $ip)
                                    {
                                        $ip = trim($ip);

                                        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
                                            {
                                                return $ip;
                                            };
                                    };
                            };
                    };

                return false;
            };
    };

$best_known_ip = getClientIP();

if(!empty($best_known_ip))
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip;
    }
else
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip = '';
    };

?>
</code>```

Changes:

It simplifies the function name (with 'camelCase' formatting style).

It includes a check to make sure the function isn't already declared in another part of your code.

It takes into account 'CloudFlare' compatibility.

It initializes multiple "IP-related" variable names to the returned value, of the 'getClientIP' function.

It ensures that if the function doesn't return a valid IP address, all the variables are set to a empty string, instead of null.

It's only (45) lines of code.

Body:
I know there are a plethora of $_SERVER variables headers available for IP address retrieval. I was wondering if there is a general consensus as to how to most accurately retrieve a user's real IP address (well knowing no method is perfect) using said variables?

I spent some time trying to find an in depth solution and came up with the following code based on a number of sources. I would love it if somebody could please poke holes in the answer or shed some light on something perhaps more accurate.

edit includes optimizations from @Alix

 /**
  * Retrieves the best guess of the client's actual IP address.
  * Takes into account numerous HTTP proxy headers due to variations
  * in how different ISPs handle IP addresses in headers between hops.
  */
 public function get_ip_address() {
  // Check for shared internet/ISP IP
  if (!empty($_SERVER['HTTP_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_CLIENT_IP']))
   return $_SERVER['HTTP_CLIENT_IP'];

  // Check for IPs passing through proxies
  if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
   // Check if multiple IP addresses exist in var
    $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
    foreach ($iplist as $ip) {
     if ($this->validate_ip($ip))
      return $ip;
    }
   }
  }
  if (!empty($_SERVER['HTTP_X_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_X_FORWARDED']))
   return $_SERVER['HTTP_X_FORWARDED'];
  if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && $this->validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
   return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
  if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && $this->validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
   return $_SERVER['HTTP_FORWARDED_FOR'];
  if (!empty($_SERVER['HTTP_FORWARDED']) && $this->validate_ip($_SERVER['HTTP_FORWARDED']))
   return $_SERVER['HTTP_FORWARDED'];

  // Return unreliable IP address since all else failed
  return $_SERVER['REMOTE_ADDR'];
 }

 /**
  * Ensures an IP address is both a valid IP address and does not fall within
  * a private network range.
  *
  * @access public
  * @param string $ip
  */
 public function validate_ip($ip) {
     if (filter_var($ip, FILTER_VALIDATE_IP,
                         FILTER_FLAG_IPV4 |
                         FILTER_FLAG_IPV6 |
                         FILTER_FLAG_NO_PRIV_RANGE |
                         FILTER_FLAG_NO_RES_RANGE) === false)
         return false;
     self::$ip = $ip;
     return true;
 }

Words of Warning (update)

REMOTE_ADDR still represents the most reliable source of an IP address. The other $_SERVER variables mentioned here can be spoofed by a remote client very easily. The purpose of this solution is to attempt to determine the IP address of a client sitting behind a proxy. For your general purposes, you might consider using this in combination with the IP address returned directly from $_SERVER['REMOTE_ADDR'] and storing both.

For 99.9% of users this solution will suit your needs perfectly. It will not protect you from the 0.1% of malicious users looking to abuse your system by injecting their own request headers. If relying on IP addresses for something mission critical, resort to REMOTE_ADDR and don't bother catering to those behind a proxy.

Body:
My answer is basically just a polished, fully-validated, and fully-packaged, version of @AlixAxel's answer:

<?php

/* Get the 'best known' client IP. */

if (!function_exists('getClientIP'))
    {
        function getClientIP()
            {
                if (isset($_SERVER["HTTP_CF_CONNECTING_IP"]))
                    {
                        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                    };

                foreach (array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $key)
                    {
                        if (array_key_exists($key, $_SERVER))
                            {
                                foreach (explode(',', $_SERVER[$key]) as $ip)
                                    {
                                        $ip = trim($ip);

                                        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false)
                                            {
                                                return $ip;
                                            };
                                    };
                            };
                    };

                return false;
            };
    };

$best_known_ip = getClientIP();

if(!empty($best_known_ip))
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip;
    }
else
    {
        $ip = $clients_ip = $client_ip = $client_IP = $best_known_ip = '';
    };

?>

Changes:

It simplifies the function name (with 'camelCase' formatting style).

It includes a check to make sure the function isn't already declared in another part of your code.

It takes into account 'CloudFlare' compatibility.

It initializes multiple "IP-related" variable names to the returned value, of the 'getClientIP' function.

It ensures that if the function doesn't return a valid IP address, all the variables are set to a empty string, instead of null.

It's only (45) lines of code.


问:
How to run virus scanner script from host machine from Docker container
I've got a java program where user can upload photos etc. It is running on docker container in Linux. I can have a plenty of containers and I don't want to pay many licenses to Mcafee, so is there a good solution for executing uvscan on host machine and scan uploaded files and buy only one license instead of 30?</p>

答: I don't know if it's the best practice but you can mount all your photos folder and scan on the host.</p>


问:
How to set CSS properties with JQuery with slow motion?
I want to get fading effect in JQuery using .css(). I'm able to do this with the statement:

```<code>$("p").fadeTo("slow", 0.0);
</code>```

A similar effect I'm able to get with the statement:

```<code>$("p").css("visibility", "hidden");
</code>```

When using fadeTo(), I am able to specify the timing (like "slow", "fast", milliseconds) but I don't know how to specify the timing with .css()

Please let me know how can I achieve this. I am comfortable with CSS, I want to achieve this with .css()

答:
Multiple ways to do this.  Following are 3 examples in 1 snippet so you can see them animate together visually.

jQuery only using .animate()

CSS only using css-animate and keyframes

CSS transition with the aid of jQuery.

Personally I prefer doing this with CSS alone, but since you asked for jQuery I provided a couple ways you can do this.

Browser support for CSS versions:

https://caniuse.com/#search=css%20animation

https://caniuse.com/#search=css3%20transition

To achieve your 'slow motion':

In these cases you'll just increase the duration:

jQuery animate() takes a number or string. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. Source.

css-animate takes a duration in seconds as the second argument after the name of the animation. This is the animation-duration property when not using shorthand. Source.

transition takes a duration in seconds as the second argument after the property/properties being transitioned.  This is the transition-duration property when not using shorthand. Source.

$(function() {
    // Using .animate() only:
    $('.jquery-animate').css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1}, 5000);

    // Using jQuery to apply CSS transition by adding a class on load:
    $('.css-transition-with-jquery').addClass('active');

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* CSS Animate method */
@-webkit-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-moz-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-o-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
.css-animate {
  -webkit-animation: fadeIn 5s ;
  -moz-animation:    fadeIn 5s ;
  -o-animation:      fadeIn 5s ;
  animation:         fadeIn 5s ;
  animation-timing-function: ease-in;
}

/* CSS and jQuery Method */
.css-transition-with-jquery {
  visibility: visible;
  opacity: 0;
  transition: opacity 5s;
  transition-timing-function: ease-in;

}
.css-transition-with-jquery.active {
  opacity: 1;
}</code>```

jQuery only with .animate(). Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.

CSS only using css-animate. Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.

CSS transition with jQuery Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.

```

Body:
I want to get fading effect in JQuery using .css(). I'm able to do this with the statement:

$("p").fadeTo("slow", 0.0);

A similar effect I'm able to get with the statement:

$("p").css("visibility", "hidden");

When using fadeTo(), I am able to specify the timing (like "slow", "fast", milliseconds) but I don't know how to specify the timing with .css()

Please let me know how can I achieve this. I am comfortable with CSS, I want to achieve this with .css()

Body:
Multiple ways to do this.  Following are 3 examples in 1 snippet so you can see them animate together visually.

jQuery only using .animate()

CSS only using css-animate and keyframes

CSS transition with the aid of jQuery.

Personally I prefer doing this with CSS alone, but since you asked for jQuery I provided a couple ways you can do this.

Browser support for CSS versions:

https://caniuse.com/#search=css%20animation

https://caniuse.com/#search=css3%20transition

To achieve your 'slow motion':

In these cases you'll just increase the duration:

jQuery animate() takes a number or string. Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The default duration is 400 milliseconds. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. Source.

css-animate takes a duration in seconds as the second argument after the name of the animation. This is the animation-duration property when not using shorthand. Source.

transition takes a duration in seconds as the second argument after the property/properties being transitioned.  This is the transition-duration property when not using shorthand. Source.

$(function() {
    // Using .animate() only:
    $('.jquery-animate').css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1}, 5000);

    // Using jQuery to apply CSS transition by adding a class on load:
    $('.css-transition-with-jquery').addClass('active');

});

/* CSS Animate method */
@-webkit-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-moz-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-o-keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes fadeIn {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
.css-animate {
  -webkit-animation: fadeIn 5s ;
  -moz-animation:    fadeIn 5s ;
  -o-animation:      fadeIn 5s ;
  animation:         fadeIn 5s ;
  animation-timing-function: ease-in;
}

/* CSS and jQuery Method */
.css-transition-with-jquery {
  visibility: visible;
  opacity: 0;
  transition: opacity 5s;
  transition-timing-function: ease-in;

}
.css-transition-with-jquery.active {
  opacity: 1;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="jquery-animate">
<strong>jQuery only with .animate()</strong>. Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.
</p>

<hr/>

<p class="css-animate">
<strong>CSS only using css-animate.</strong> Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.
</p>

<hr/>

<p class="css-transition-with-jquery">
<strong>CSS transition with jQuery</strong> Aliquam fringilla lacus erat, in tempus lorem egestas sagittis. Suspendisse in maximus est. Ut elementum ultricies mi, at dictum enim ullamcorper vel. Suspendisse sodales feugiat leo, vel sollicitudin felis eleifend quis. Nullam venenatis viverra ultricies. Nulla vel lorem sem. Praesent vestibulum maximus elit, non consectetur urna eleifend eu. Donec vel feugiat ex.
</p>


问:
codeigniter pagination - how to keep on same page after deleting row
I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can  redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:

```<code>  public function update_att(){

      if(isset($_POST['update'])){
        $u_id = $_POST['at_id'];

        if($_POST['status']=="Present"){

            $data = array(
                  'status'=>"Absent"
            );
            $this->db->where('at_id', $u_id);
            $this->db->update('attendence', $data);
        }elseif ($_POST['status']=="Absent") {
            $data = array(
                  'status'=>"Present"
            );
            $this->db->where('at_id', $u_id);
            $this->db->update('attendence', $data);
        }

    redirect("usr/att_list", "refresh");
   }
}

 public function delete_att(){

     if (isset($_POST['delete'])) {
        $at_id = $_POST['at_id'];
        $this->db->where('at_id', $at_id);
        $this->db->delete('attendence');
      }
      redirect("usr/att_list" );
 }
</code>```

Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.

答:
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.

Keep in mind you need to populate $current_page with something like

```<code>    $current_page = ''; // empty means first page
    if( isset($_REQUEST['current_page'] ){
       $current_page = $_REQUEST['current_page'];
    }
</code>```

Then based on your sample you just modifiy the redirect path as follows (for both your functions):

```<code>public function delete_att(){

     if (isset($_POST['delete'])) {
        $at_id = $_POST['at_id'];
        $this->db->where('at_id', $at_id);
        $this->db->delete('attendence');
      }
      redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
 }
</code>```

Note:

Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the  data you wish to output based on $_GET['current_page']

Edit based on your link:

```<code>    public function att_list($id = ""){
         /**
          * Keep your data in array
          */
         $this->data = array();

         /**
          * Add the page number ($id) to the array
          * Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
          */
         $this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);

         /**
          * This is your 'keep on the same page' line
          * $this->data['current_page'] will act as an offset in your query
          * You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
          * $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
          */
         $this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);

         /**
          * Pass the whole array into your view
          */
         $this->load->view('path/to/view', $this->data);

      }
</code>```

Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />

Body:
I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can  redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:

  public function update_att(){

      if(isset($_POST['update'])){
        $u_id = $_POST['at_id'];

        if($_POST['status']=="Present"){

            $data = array(
                  'status'=>"Absent"
            );
            $this->db->where('at_id', $u_id);
            $this->db->update('attendence', $data);
        }elseif ($_POST['status']=="Absent") {
            $data = array(
                  'status'=>"Present"
            );
            $this->db->where('at_id', $u_id);
            $this->db->update('attendence', $data);
        }

    redirect("usr/att_list", "refresh");
   }
}

 public function delete_att(){

     if (isset($_POST['delete'])) {
        $at_id = $_POST['at_id'];
        $this->db->where('at_id', $at_id);
        $this->db->delete('attendence');
      }
      redirect("usr/att_list" );
 }

Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.

Body:
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.

Keep in mind you need to populate $current_page with something like

    $current_page = ''; // empty means first page
    if( isset($_REQUEST['current_page'] ){
       $current_page = $_REQUEST['current_page'];
    }

Then based on your sample you just modifiy the redirect path as follows (for both your functions):

public function delete_att(){

     if (isset($_POST['delete'])) {
        $at_id = $_POST['at_id'];
        $this->db->where('at_id', $at_id);
        $this->db->delete('attendence');
      }
      redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
 }

Note:

Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the  data you wish to output based on $_GET['current_page']

Edit based on your link:

    public function att_list($id = ""){
         /**
          * Keep your data in array
          */
         $this->data = array();

         /**
          * Add the page number ($id) to the array
          * Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
          */
         $this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);

         /**
          * This is your 'keep on the same page' line
          * $this->data['current_page'] will act as an offset in your query
          * You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
          * $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
          */
         $this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);

         /**
          * Pass the whole array into your view
          */
         $this->load->view('path/to/view', $this->data);

      }

Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />


问:
Returning reference to locally dereferenced pointer
Is the behavior of this code well-defined? Will the returned reference always be correct? Will the Bar::method() call always go well?</p>

```<code>struct Bar
{
    void method() {...};
};

struct Foo
{
    static unique_ptr<Bar> bar_ptr;
    static Bar& get_reference()
    {
        return *bar_ptr;
    }
};

unique_ptr<Bar> Foo::bar_ptr = nullptr;

int main()
{
    Foo::bar_ptr = make_unique<Bar>();
    Foo::get_reference().method();

    return 0;
}
</code>```

答:
Is the behavior of this code well-defined?

Yes it is.

The instance of struct Bar will go out of scope, thus destroyed, after main() terminates.

Body:
Is the behavior of this code well-defined? Will the returned reference always be correct? Will the Bar::method() call always go well?

struct Bar
{
    void method() {...};
};

struct Foo
{
    static unique_ptr<Bar> bar_ptr;
    static Bar& get_reference()
    {
        return *bar_ptr;
    }
};

unique_ptr<Bar> Foo::bar_ptr = nullptr;

int main()
{
    Foo::bar_ptr = make_unique<Bar>();
    Foo::get_reference().method();

    return 0;
}


问:
MYSQL and phpmyadmin not allowing me to create user table
im trying to create a table using mysql and phpmyadmin with the w

```<code>CREATE DATABASE android_api

USE 'android_api'
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
unique_id VARCHAR(23) NOT NULL UNIQUE,
NAME VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
encrypted_password VARCHAR(80) NOT NULL,
salt VARCHAR(10) NOT NULL,
created_at DATETIME,
updated_at DATETIME NULL
);
</code>```

but i keep recieving an error :

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'USE 'android_api'
      CREATE TABLE users(
      id INT(11) PRIMARY KEY AUTO_INCREMEN' at line 3

i was wondering if anybody could help me

NOTE - i have tried putting '' around the database name and id, unique_id and so on.

答:
Try this:

```<code>CREATE DATABASE android_api;

USE android_api;

CREATE TABLE users(
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    unique_id VARCHAR(23) NOT NULL UNIQUE,
    NAME VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    encrypted_password VARCHAR(80) NOT NULL,
    salt VARCHAR(10) NOT NULL,
    created_at DATETIME,
    updated_at DATETIME NULL
);
</code>```

Separate three statements with ;

Body:
im trying to create a table using mysql and phpmyadmin with the w

CREATE DATABASE android_api

USE 'android_api'
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
unique_id VARCHAR(23) NOT NULL UNIQUE,
NAME VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
encrypted_password VARCHAR(80) NOT NULL,
salt VARCHAR(10) NOT NULL,
created_at DATETIME,
updated_at DATETIME NULL
);

but i keep recieving an error :

1064 - You have an error in your SQL syntax; check the manual that
  corresponds to your MySQL server version for the right syntax to use
  near 'USE 'android_api'
      CREATE TABLE users(
      id INT(11) PRIMARY KEY AUTO_INCREMEN' at line 3

i was wondering if anybody could help me

NOTE - i have tried putting '' around the database name and id, unique_id and so on.

Body:
Try this:

CREATE DATABASE android_api;

USE android_api;

CREATE TABLE users(
    id INT(11) PRIMARY KEY AUTO_INCREMENT,
    unique_id VARCHAR(23) NOT NULL UNIQUE,
    NAME VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL UNIQUE,
    encrypted_password VARCHAR(80) NOT NULL,
    salt VARCHAR(10) NOT NULL,
    created_at DATETIME,
    updated_at DATETIME NULL
);

Separate three statements with ;


问:
Angular http post request content type from 'text/plain' to 'application/json'
Im trying to get data from a service using POST request. But I cant change the headers (TS wont compile) or content type. I get this error in console:

status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain' not supported"

Below is my component code.

import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  searchValue: any = '';

  constructor(private http: HttpClient) { }

  getData() {

    this.http.post('MY URL',
    JSON.stringify({
      "q": "Achmea"
    }))
    .subscribe(
    data => {
      alert('ok');
      console.log(data);
    }
    )```

NB: Used the code snippet because the formatting wouldnt let me post as pre.

Using latest angular 4 version.
Also server should be correctly configured, accepting only json data.
I tried the examples from Angular docs but none of them worked.

Anyone have any idea how to get it working??
Thanks in advance.

答:
In your example (and also in the comments) the two different http implementations which are provided by angular are mixed up. Since angular 4 HttpClient from '@angular/common/http' is available and is the recommended way to go. Since angular 5 the older Http from '@angular/http' is even marked as deprecated.

In order to prevent the exception message from your backend you have to set your headers in the following way:

```<code>const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url), body, {headers: headers})
...
</code>```

Please remove all dependencies from '@angular/http' in your code. As long as you are using objects from this modul you will have issues with your code.

Body:
Im trying to get data from a service using POST request. But I cant change the headers (TS wont compile) or content type. I get this error in console:

status":415,"error":"Unsupported Media Type","exception":"org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'text/plain' not supported"

Below is my component code.

import { Component, OnInit } from '@angular/core';
import { Http, Headers, Response, URLSearchParams } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {

  searchValue: any = '';

  constructor(private http: HttpClient) { }

  getData() {

    this.http.post('MY URL',
    JSON.stringify({
      "q": "Achmea"
    }))
    .subscribe(
    data => {
      alert('ok');
      console.log(data);
    }
    )

NB: Used the code snippet because the formatting wouldnt let me post as pre.

Using latest angular 4 version.
Also server should be correctly configured, accepting only json data.
I tried the examples from Angular docs but none of them worked.

Anyone have any idea how to get it working??
Thanks in advance.

Body:
In your example (and also in the comments) the two different http implementations which are provided by angular are mixed up. Since angular 4 HttpClient from '@angular/common/http' is available and is the recommended way to go. Since angular 5 the older Http from '@angular/http' is even marked as deprecated.

In order to prevent the exception message from your backend you have to set your headers in the following way:

const headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-8');
return this.httpClient.post<T>(this.httpUtilService.prepareUrlForRequest(url), body, {headers: headers})
...

Please remove all dependencies from '@angular/http' in your code. As long as you are using objects from this modul you will have issues with your code.


问:
Wrap a method into a func
I want to create a generic wrapper around Polly framework so that can have single implementation. In order to achieve it I have written below code

```<code>    private Policy GetPolicy(EType eType)
    {
        var policy = default(Polly.Policy);

        switch (eType)
        {

            case EType.T:
                policy = Policy.Handle<SomeException>().Retry(n, x => new TimeSpan(0, 0, x));
                break;
        }
        return policy;
    }
</code>```

And I am using the above method in one of my wrapper methods

```<code>   public TOutput Execute<TOutput>(Func<TOutput> func, EType eType)
    {
        var policy = GetPolicy(eType);

        return policy.Execute(() => func());
    }
</code>```

Now in order to consume it I have written a sample method

```<code>       var handleError = new HandleError();
        var connection = handleError.Execute(() => factory.CreateConnection(), ExceptionType.Transient);
</code>```

Till above all works fine, but as soon as I start calling the same in a method which takes parameter, then it throws error as

```<code>     var handleError = new HandleError();
        handleError.Execute(() => channel.ExchangeDeclare(queueDetail.ExchangeName, ExchangeType.Fanout), ExceptionType.Transient);

     The type arguments for method 'HandleError.Execute<TOutput>(Func<TOutput>, ExceptionType)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
</code>```

答:
You need two Execute overloads, one for functions that return value and another for those which do not:

```<code>public TOutput Execute<TOutput>(Func<TOutput> func, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    return policy.Execute(func);
}

public void Execute(Action action, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    policy.Execute(action);
}
</code>```

Then you can pass anything there, including functions with parameters:

```<code>// calls first overload
Execute(() => ImReturningValue(parameter1));
// calls second
Execute(() => IDoNot(parameter1));
</code>```

Policy.Execute method also has the same overloads (one for Func, one for Action) - so you will have no problems to pass either one to it.

Title: Wrap a method into a func

Body:
I want to create a generic wrapper around Polly framework so that can have single implementation. In order to achieve it I have written below code

    private Policy GetPolicy(EType eType)
    {
        var policy = default(Polly.Policy);

        switch (eType)
        {

            case EType.T:
                policy = Policy.Handle<SomeException>().Retry(n, x => new TimeSpan(0, 0, x));
                break;
        }
        return policy;
    }

And I am using the above method in one of my wrapper methods

   public TOutput Execute<TOutput>(Func<TOutput> func, EType eType)
    {
        var policy = GetPolicy(eType);

        return policy.Execute(() => func());
    }

Now in order to consume it I have written a sample method

       var handleError = new HandleError();
        var connection = handleError.Execute(() => factory.CreateConnection(), ExceptionType.Transient);

Till above all works fine, but as soon as I start calling the same in a method which takes parameter, then it throws error as

     var handleError = new HandleError();
        handleError.Execute(() => channel.ExchangeDeclare(queueDetail.ExchangeName, ExchangeType.Fanout), ExceptionType.Transient);

     The type arguments for method 'HandleError.Execute<TOutput>(Func<TOutput>, ExceptionType)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Body:
You need two Execute overloads, one for functions that return value and another for those which do not:

public TOutput Execute<TOutput>(Func<TOutput> func, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    return policy.Execute(func);
}

public void Execute(Action action, ExceptionType exceptionType)
{
    var policy = GetPolicyFromExceptionType(exceptionType);
    policy.Execute(action);
}

Then you can pass anything there, including functions with parameters:

// calls first overload
Execute(() => ImReturningValue(parameter1));
// calls second
Execute(() => IDoNot(parameter1));

Policy.Execute method also has the same overloads (one for Func, one for Action) - so you will have no problems to pass either one to it.


问:
Python, Stop a Thread
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

```<code>class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]
</code>```

答:
thanks for @zwer for the lead.
Here's my complete code ( changes are marked )</p>

```<code>class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4
        self.event = threading.Event() # <---- Added

    def run(self):
        while not self.event.is_set(): # <---- Added
            self.start_ping()
            self.event.wait(self.ping_rate) # <---- Added ( Time to repeat moved in here )

    def stop(self):       # <---- Added ( ease of use )
        self.event.set()  # <---- Added ( set to False and causes to stop )

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        # While loop ##--- > Deleted. now it loops in run method #####
        ping_result = os.system('ping %s -n 1 >Null' % self.address)
        self.ping_vector.append(ping_result)

        if self.last_ping != ping_result:
            text = ['Reachable', 'Lost']
            print(str(self.timestamp)[:-4], self.address, text[ping_result])

        round_time_qouta = datetime.datetime.now() - self.timestamp
        self.timestamp = datetime.datetime.now()
        self.update_time_counter(ping_result, round_time_qouta)

        self.last_ping = ping_result
        #### time.sleep (self.ping_rate)  # <---- deleted

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

    def get_status(self):
        return self.last_status

c = Pinger('127.0.0.1', 5)
c.start()
time.sleep(10)
c.stop()
</code>```

Title: Python, Stop a Thread

Body:
I'm trying to create a class that pings an ip address and keeps a record for connected/ not connected times.

Since this class is a part of a GUI, I wish to stop this thread when asked by user.

Found some Q&As regrading this issue, but neither one actually causes thread to stop.

I'm trying to make a method, a part of this class that will stop self.run()

Here's my Pinger class:

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4

    def run(self):
            self.start_ping()

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        while True:
            ping_result = os.system('ping %s -n 1 >Null' % self.address)
            self.ping_vector.append(ping_result)

            if self.last_ping != ping_result:
                text = ['Reachable', 'Lost']
                print(str(self.timestamp)[:-4], self.address, text[ping_result])

            round_time_qouta = datetime.datetime.now() - self.timestamp
            self.timestamp = datetime.datetime.now()
            self.update_time_counter(ping_result, round_time_qouta)

            self.last_ping = ping_result
            time.sleep(self.ping_rate)

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

Body:
thanks for @zwer for the lead.
Here's my complete code ( changes are marked )

class Pinger(threading.Thread):
    def __init__(self, address='', rate=1):
        threading.Thread.__init__(self)

        self.address = address
        self.ping_rate = rate
        self.ping_vector, self.last_ping = [], -1
        self.start_time, self.last_status = datetime.datetime.now(), []
        self.timestamp, self.time_vector = 0, [datetime.timedelta(0)] * 4
        self.event = threading.Event() # <---- Added

    def run(self):
        while not self.event.is_set(): # <---- Added
            self.start_ping()
            self.event.wait(self.ping_rate) # <---- Added ( Time to repeat moved in here )

    def stop(self):       # <---- Added ( ease of use )
        self.event.set()  # <---- Added ( set to False and causes to stop )

    def start_ping(self):
        self.timestamp = datetime.datetime.now()
        # While loop ##--- > Deleted. now it loops in run method #####
        ping_result = os.system('ping %s -n 1 >Null' % self.address)
        self.ping_vector.append(ping_result)

        if self.last_ping != ping_result:
            text = ['Reachable', 'Lost']
            print(str(self.timestamp)[:-4], self.address, text[ping_result])

        round_time_qouta = datetime.datetime.now() - self.timestamp
        self.timestamp = datetime.datetime.now()
        self.update_time_counter(ping_result, round_time_qouta)

        self.last_ping = ping_result
        #### time.sleep (self.ping_rate)  # <---- deleted

    def update_time_counter(self, ping_result=0, time_quota=datetime.timedelta(0)):
        """self.time_vector = [[cons.succ ping time],[cons.not_succ ping time],
        [max accum succ ping time],[max accum not_succ ping time] """

        p_vec = [0, 1]

        self.time_vector[p_vec[ping_result]] += time_quota
        if self.time_vector[p_vec[ping_result]].total_seconds() > self.time_vector[
            p_vec[ping_result] + 2].total_seconds():
            self.time_vector[p_vec[ping_result] + 2] = self.time_vector[p_vec[ping_result]]

        self.time_vector[p_vec[ping_result - 1]] = datetime.timedelta(0)

        self.last_status = [ping_result, self.chop_milisecond(self.time_vector[ping_result]),
                            self.chop_milisecond(self.time_vector[ping_result + 2]),
                            self.chop_milisecond(datetime.datetime.now() - self.start_time)]

        print(str(self.timestamp)[:-4], "State: " + ['Received', 'Lost'][ping_result],
              " Duration: " + self.last_status[1], " Max Duration: " + self.last_status[2],
              "Total time: " + self.last_status[3])

    def chop_milisecond(self, time):
        return str(time).split('.')[0]

    def get_status(self):
        return self.last_status

c = Pinger('127.0.0.1', 5)
c.start()
time.sleep(10)
c.stop()


答:
Very simple and clear solution:

Create custom initializer with param json [String : Any] in your class Country.

Init all variables of class using loop in custom initializer.

Try this code:

```<code>class Country: NSObject {
    var name: String = ""
    var dial_code: String = ""
    var code: String = ""

    // Sol: 1
    init(json: [String : Any]) {
        if let name = json["name"] as? String, let dial_code = json["dial_code"] as? String, let code = json["name"] as? String {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

    // or Sol: 2
    init(name: String, dial_code: String, code: String) {
        self.name = name
        self.dial_code = dial_code
        self.code = code
    }
}
</code>```

Create an instance of class Countries using element of array countries and collect the same in separate array arrayOfCountries

Try this code:

```<code>let countries : [[String : Any]] = [
    [
        "name" : "Afghanistan",
        "dial_code": "+93",
        "code": "AF"
    ],
    [
        "name": "Aland Islands",
        "dial_code": "+358",
        "code": "AX"
    ],
    [
        "name": "Albania",
        "dial_code": "+355",
        "code": "AL"
    ],
    [
        "name": "Algeria",
        "dial_code": "+213",
        "code": "DZ"
    ]
]

var arrayOfCountries = [Country]()

// Sol: 1
for json in countries {
    let country = Country(json: json)
    print("country name - \(country.name)")
    arrayOfCountries.append(country)
}

// Sol: 2
for json in countries {

    if let name = json["name"] as? String, let dial_code = json["dial_code"] as? String, let code = json["name"] as? String {
        let country = Country(name: name, dial_code: dial_code, code: code)
        print("country name - \(country.name)")
        arrayOfCountries.append(country)
    }

}
</code>```

Title: Convert Array of Dictionary to custom object swift

Body:
I have:

    let countries : [[String : Any]] = [
            [
                "name" : "Afghanistan",
                "dial_code": "+93",
                "code": "AF"
            ],
            [
                "name": "Aland Islands",
                "dial_code": "+358",
                "code": "AX"
            ],
            [
                "name": "Albania",
                "dial_code": "+355",
                "code": "AL"
            ],
            [
                "name": "Algeria",
                "dial_code": "+213",
                "code": "DZ"
            ]
]

I want to add all this array of dictionary to my custom object like

let country:[Country] = countries

My custom object looks like this:

class Country: NSObject {
        let name: String
        let dial_code : String
        let code: String

        init(name: String, dial_code: String, code: String) {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

I understand that I need a loop thru the array but idk what is the next step. Would be great to have an example.

Body:
Very simple and clear solution:

Create custom initializer with param json [String : Any] in your class Country.

Init all variables of class using loop in custom initializer.

Try this code:

class Country: NSObject {
    var name: String = ""
    var dial_code: String = ""
    var code: String = ""

    // Sol: 1
    init(json: [String : Any]) {
        if let name = json["name"] as? String, let dial_code = json["dial_code"] as? String, let code = json["name"] as? String {
            self.name = name
            self.dial_code = dial_code
            self.code = code
        }
    }

    // or Sol: 2
    init(name: String, dial_code: String, code: String) {
        self.name = name
        self.dial_code = dial_code
        self.code = code
    }
}

Create an instance of class Countries using element of array countries and collect the same in separate array arrayOfCountries

Try this code:

let countries : [[String : Any]] = [
    [
        "name" : "Afghanistan",
        "dial_code": "+93",
        "code": "AF"
    ],
    [
        "name": "Aland Islands",
        "dial_code": "+358",
        "code": "AX"
    ],
    [
        "name": "Albania",
        "dial_code": "+355",
        "code": "AL"
    ],
    [
        "name": "Algeria",
        "dial_code": "+213",
        "code": "DZ"
    ]
]

var arrayOfCountries = [Country]()

// Sol: 1
for json in countries {
    let country = Country(json: json)
    print("country name - \(country.name)")
    arrayOfCountries.append(country)
}

// Sol: 2
for json in countries {

    if let name = json["name"] as? String, let dial_code = json["dial_code"] as? String, let code = json["name"] as? String {
        let country = Country(name: name, dial_code: dial_code, code: code)
        print("country name - \(country.name)")
        arrayOfCountries.append(country)
    }

}


问:
Java read Properties file that is in same package as the class
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

```<code>try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

another is:

```<code>try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }
</code>```

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

答:
(Not enough reputation to comment)

Have you tried with this?

```<code>InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
    properties.load(input);
</code>```

Body:
I'm stuck in this for almost an hour so please help me.

I'm using netbeans and under my Sources Packages I have a package called com.cmsv1.properties. Inside this package I have 1 java class and .properties file. Called config.java and config.properties.

I've tried so many solutions I got from the internet but nothing works. I always get nullPointerException.

The following are the solutions i've tried:

try
          {
              Properties prop = new Properties();
              InputStream is = config.class.getResourceAsStream("config.properties");
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

another is:

try
          {
              Properties prop = new Properties();
              InputStream input = config.class.getClassLoader().getResourceAsStream("config.properties");
              prop.load(input);
          }
        catch (Exception e)
          {
              System.out.println("got error");
          }

And a couple more solutions. Please tell me how can I do this. Remember both of my java class and .properties file are in the same package. Thanks in advance.

Body:
(Not enough reputation to comment)

Have you tried with this?

InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesFile);
    properties.load(input);


问:
It sould be so obvious, but why does this fail?
Been coding .net for years now yet I feel like a n00b. Why is the following code failing?

```<code>byte[] a = Guid.NewGuid().ToByteArray(); // 16 bytes in array
string b = new UTF8Encoding().GetString(a);
byte[] c = new UTF8Encoding().GetBytes(b);
Guid d = new Guid(c);    // Throws exception (32 bytes recived from c)
</code>```

Update

Approved the answer from CodeInChaos. Reason for the 16 bytes becomming 32 bytes can be read in his answer. Also stated in the answer:

the default constructor of
  UTF8Encoding has error checking
  disabled

IMHO the UTF8 encoder should throw exception when trying to encode a byte array to string that contains invalid bytes. To make the .net framework behave properly the code should have been written as follows

```<code> byte[] a = Guid.NewGuid().ToByteArray();
 string b = new UTF8Encoding(false, true).GetString(a);  // Throws exception as expected
 byte[] c = new UTF8Encoding(false, true).GetBytes(b);
 Guid d = new Guid(c);
</code>```

答:
Not every sequence of bytes is a valid UTF-8 encoded string.

The GUID can contain almost any sequence of bytes. But UTF-8 as specific rules for which byte sequences are allowed if the value is >127. And a Guid will quite often not follow these rules.

Then when you encode the corrupted string back to a byte array you get a byte array longer than 16 bytes, which the constructor of Guid doesn't accept.

The documentation on UTF8Encoding.GetString states:

With error detection, an invalid sequence causes this method to throw a ArgumentException. Without error detection, invalid sequences are ignored, and no exception is thrown.

and the default constructor of UTF8Encoding has error checking disabled(don't ask me why).

This constructor creates an instance that does not provide a Unicode byte order mark and does not throw an exception when an invalid encoding is detected.

  Note

  For security reasons, your applications are recommended to enable error detection by using the constructor that accepts a throwOnInvalidBytes parameter and setting that parameter to true.

You might want to use Base64 encoding instead of UTF-8. That way you can map any valid byte sequence into a string and back.

Body:
Been coding .net for years now yet I feel like a n00b. Why is the following code failing?

byte[] a = Guid.NewGuid().ToByteArray(); // 16 bytes in array
string b = new UTF8Encoding().GetString(a);
byte[] c = new UTF8Encoding().GetBytes(b);
Guid d = new Guid(c);    // Throws exception (32 bytes recived from c)

Update

Approved the answer from CodeInChaos. Reason for the 16 bytes becomming 32 bytes can be read in his answer. Also stated in the answer:

the default constructor of
  UTF8Encoding has error checking
  disabled

IMHO the UTF8 encoder should throw exception when trying to encode a byte array to string that contains invalid bytes. To make the .net framework behave properly the code should have been written as follows

 byte[] a = Guid.NewGuid().ToByteArray();
 string b = new UTF8Encoding(false, true).GetString(a);  // Throws exception as expected
 byte[] c = new UTF8Encoding(false, true).GetBytes(b);
 Guid d = new Guid(c);


问:
Neo4j create new admin user from console
Is there any way to add neo4j admin user from console?
I found how to change default password for native user neo4j https://neo4j.com/docs/operations-manual/current/configuration/set-initial-password/ but didn't found how to add new admin user.

答:
It's not possible with the neo4j-admin tool, but directly with the cypher-shell by running those queries (so you need to have a running database):

```<code>CALL dbms.security.createUser('root', 'password');
CALL dbms.security.addRoleToUser('admin', 'root');
</code>```

You will find the description of all security's procedures here : https://neo4j.com/docs/operations-manual/current/security/authentication-authorization/native-user-role-management/procedures/

Body:
It's not possible with the neo4j-admin tool, but directly with the cypher-shell by running those queries (so you need to have a running database):

CALL dbms.security.createUser('root', 'password');
CALL dbms.security.addRoleToUser('admin', 'root');

You will find the description of all security's procedures here : https://neo4j.com/docs/operations-manual/current/security/authentication-authorization/native-user-role-management/procedures/


问:
Datomic: on a Peer, does Connection.db() read your writes after Connection.transact()
Consider the following operations, occuring in a Datomic Peer:

```<code>(require '[datomic.api :as d])

(let [;; running a transaction and awaiting completion
      tx-res @(d/transact-async conn tx-data)
      ;; reading the current database value
      db1 (d/db conn)]
  ,,,)
</code>```

In the consistency model of Datomic, can I expect the changes made by tx-res to be visible in db1?

(I know about both :db-after (d/sync conn t), but it can be practical to rely on reading your writes on the Connection, e.g for doing successive writes on a connection without having to carry along database values).

答:
Val,

Yes, db1 would include the changes made in the transaction. However, this approach is considered bad practice, as you're reading the same value twice (tx-res already has the value of the resulting db). Further, you're not guaranteed that db1 is the same database value as the :db-after from the transaction.

We highly recommend using the :db-after as returned from the transaction for a subsequent read.

-Marshall

Body:
Consider the following operations, occuring in a Datomic Peer:

(require '[datomic.api :as d])

(let [;; running a transaction and awaiting completion
      tx-res @(d/transact-async conn tx-data)
      ;; reading the current database value
      db1 (d/db conn)]
  ,,,)

In the consistency model of Datomic, can I expect the changes made by tx-res to be visible in db1?

(I know about both :db-after (d/sync conn t), but it can be practical to rely on reading your writes on the Connection, e.g for doing successive writes on a connection without having to carry along database values).


问:
str.join() adds backslashes to my variable
I am using Python 3.5 and PyCharm 2017.3

My code appears as following:

```<code>var1 = 'ASD'
var2 = 'ASDPO'
qryPwr = ''.join(['select DATE as "DATE"'
                       ' from Table1 where MKT = ', "'", var1, "'",
                       ' and COMP = ', "'", var2, "'",
                       ' and ppow_vdays = 0'
                       ' and PPOW_SETTLE = ', "'", 'S', "'"])
</code>```

I get the following for qryPqr:

```<code>qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''
</code>```

So, I have two questions:

(1) Why are there backslashes everywhere?

(2) How do I get rid of them or make my join statement better?

Edit:
I want to remove the backslashes from the print statement as when I do the database query using qryPwr it tries to run the query with backslashes and hence errors out.

答:
The backslashes are in the displayed output, but not in the variable itself, if you print your qryPwr you will see this

```<code>>>> qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''

>>> print(qryPwr)
select DATE as "DATE", from Table1 where MKT = 'ASD' and COMP = 'ASDPO' and ppow_vdays = 0 and PPOW_SETTLE = 'S'
</code>```

You will get this if your actual str contains both ' and " characters. For a simpler example:

```<code>>>> s = 'a "b" \'c\''
>>>
>>> s
'a "b" \'c\''
>>>
>>> print(s)
a "b" 'c'
>>> len(s) # as expected, \ characters aren't actually there.
9
</code>```

Body:
I am using Python 3.5 and PyCharm 2017.3

My code appears as following:

var1 = 'ASD'
var2 = 'ASDPO'
qryPwr = ''.join(['select DATE as "DATE"'
                       ' from Table1 where MKT = ', "'", var1, "'",
                       ' and COMP = ', "'", var2, "'",
                       ' and ppow_vdays = 0'
                       ' and PPOW_SETTLE = ', "'", 'S', "'"])

I get the following for qryPqr:

qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''

So, I have two questions:

(1) Why are there backslashes everywhere?

(2) How do I get rid of them or make my join statement better?

Edit:
I want to remove the backslashes from the print statement as when I do the database query using qryPwr it tries to run the query with backslashes and hence errors out.

Body:
The backslashes are in the displayed output, but not in the variable itself, if you print your qryPwr you will see this

>>> qryPwr
'select DATE as "DATE", from Table1 where MKT = \'ASD\' and COMP = \'ASDPO\' and ppow_vdays = 0 and PPOW_SETTLE = \'S\''

>>> print(qryPwr)
select DATE as "DATE", from Table1 where MKT = 'ASD' and COMP = 'ASDPO' and ppow_vdays = 0 and PPOW_SETTLE = 'S'

You will get this if your actual str contains both ' and " characters. For a simpler example:

>>> s = 'a "b" \'c\''
>>>
>>> s
'a "b" \'c\''
>>>
>>> print(s)
a "b" 'c'
>>> len(s) # as expected, \ characters aren't actually there.
9