问:
Python 3 Program to print the Initials of a name and with surname
Program: Input a name and Print the Initials and with surname.

Input:- Ted Vivian Mosby

Output:- T V Mosby

Using Python 3 online compiler:-

https://repl.it/languages/python3

```<code>user = input('Please Enter your name \n')
length = len(user)
value=0

for a in range(0,length-1):
    if a==" ":
      value=a

for b in range(0,value):
    if b==0:
      print(user[0])
    elif user[b]==" ":
      print(user[b+1])

for c in range(value+1,length):
    print(user[c])
</code>```

The output I have is:-

Please Enter your name

 Ted Vivian Mosby

e

d

V

i

v

i

a

n

M

o

s

b

y

答:
Here's a pythonic way to do it. Notice it takes into account all names, no matter how many middle names.</p>

```<code>name = input("Please enter a name: ")
names = name.split()
initials = [x[0] for x in names[:-1]]
print(*initials, names[-1])

"""
Broken down:
name.split() = ['Ted', 'David', 'Vivican', 'Mosby']   Note ive added an extra name for show
name.split()[:-1] = ['Ted', 'David', 'Vivican']
[x[0] for name in ['Ted', 'David', 'Vivican']] = ['T', 'D', 'V']
print(*initials) unpacks each value in the list to the function eg
print(*['T', 'D', 'V']) == print('T', 'D', 'V')
"""
</code>```

Body:
Program: Input a name and Print the Initials and with surname.

Input:- Ted Vivian Mosby

Output:- T V Mosby

Using Python 3 online compiler:-

https://repl.it/languages/python3

user = input('Please Enter your name \n')
length = len(user)
value=0

for a in range(0,length-1):
    if a==" ":
      value=a

for b in range(0,value):
    if b==0:
      print(user[0])
    elif user[b]==" ":
      print(user[b+1])

for c in range(value+1,length):
    print(user[c])

The output I have is:-

Please Enter your name

 Ted Vivian Mosby

e

d

V

i

v

i

a

n

M

o

s

b

y

Body:
Here's a pythonic way to do it. Notice it takes into account all names, no matter how many middle names.

name = input("Please enter a name: ")
names = name.split()
initials = [x[0] for x in names[:-1]]
print(*initials, names[-1])

"""
Broken down:
name.split() = ['Ted', 'David', 'Vivican', 'Mosby']   Note ive added an extra name for show
name.split()[:-1] = ['Ted', 'David', 'Vivican']
[x[0] for name in ['Ted', 'David', 'Vivican']] = ['T', 'D', 'V']
print(*initials) unpacks each value in the list to the function eg
print(*['T', 'D', 'V']) == print('T', 'D', 'V')
"""


来源: stackexchange

问:
How can I update swift from 3.1 to 3.2, but not to 4.0
I have checked the question related to how to find the current Swift version by the command swift --version, but how can I upgrade my Swift version from 3.1 to 3.2? (because the Xcode 9 only supports Swift 4.0 & Swift 3.2)

To build successfully both in Xcode 8 & Xcode 9, it's better to upgrade Swift from 3.1 to 3.2. But how?

My target was to make sure build successfully both in Xcode 8 & Xcode 9, So that publish with Xcode 8 would be OK, and try out the feature of Xcode 9 is OK too. So I will not upgrade code to swift 4.0 yet until Xcode 9.0 official edition is published.

After my test, I can't convert my code from swift 3.1 to 3.2 by Xcode 8.3.3's 'edit->convert' function.

The reason why I try to convert the code to Swift 3.2 is that I will get error of "Module compiled with Swift 3.1 cannot be imported in Swift 4.0" if I build the code with Xcode 9.

答:
You do not have to convert it.

Swift 3.2 is not an actual version. It is how Xcode 9 (and the Swift 4 compiler) calls Swift 3. (I guess to differentiate from Swift 3 built with Xcode 8).

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Compatibility.html

ContentLicense: CC BY-SA 3.0


问:
How can I consume oData from a service in SAP UI5, while not using the Web IDE?
I would like to display data from a oData model in SAP UI5.

```<code>"dataSources": {
            "ZSM_APPLIKATION_SRV": {
                "uri": "/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/",
                "type": "OData",
                "settings": {
                    "odataVersion": "2.0",
                    "localUri": "localService/ZSM_APPLIKATION_SRV/metadata.xml"
                }
            }
        },

"models": {
    "i18n": {
        ...
        }
    },
    "oData": {
        "dataSource": "ZSM_APPLIKATION_SRV"
    }
}
</code>```

As you can see I already added the oData service to the manifest.json and specified the model "oData" to represent this service.

I would now like to display the services data in a table. When adding the property items="{oData>/UserSet}" to the table it works fine when launching the application with the Web IDE and all the data is displayed.
Instead of using the Web IDE I use PhpStorm and a local Apache Web Server to test the UI5 app.
When using the solution, which works with the Web IDE I keep getting an Error in the Chrome console and the data won't be displayed in the table:

```<code>"Failed to load resource: the server responded with a status of 404 (Not Found)"
</code>```

So the Web IDEs webserer seems to find the service without a problem, while both the local apache server and the built-in PhpStorm server won't find it.

I also tried to enter the full service URI in the manifest.json

```<code>"uri": "http://xxx:50020/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/"
</code>```

Doing so will result in getting another error at the chrome console

```<code>XMLHttpRequest cannot load http://xxx:50020/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/$metadata?sap-language=DE. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.
</code>```

Is there any way now to connect to my service and consume data without using the Web IDE? How can I fix this error.

Thanks in advance

答: PhpStorm requires correct deployment setup to be configured (see tutorial) - IDE can't detect path mappings in complex projects so you would have to configure deployment & path mappings for this to work from inside IDE.</p>

Body:
I would like to display data from a oData model in SAP UI5.

"dataSources": {
            "ZSM_APPLIKATION_SRV": {
                "uri": "/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/",
                "type": "OData",
                "settings": {
                    "odataVersion": "2.0",
                    "localUri": "localService/ZSM_APPLIKATION_SRV/metadata.xml"
                }
            }
        },

"models": {
    "i18n": {
        ...
        }
    },
    "oData": {
        "dataSource": "ZSM_APPLIKATION_SRV"
    }
}

As you can see I already added the oData service to the manifest.json and specified the model "oData" to represent this service.

I would now like to display the services data in a table. When adding the property items="{oData>/UserSet}" to the table it works fine when launching the application with the Web IDE and all the data is displayed.
Instead of using the Web IDE I use PhpStorm and a local Apache Web Server to test the UI5 app.
When using the solution, which works with the Web IDE I keep getting an Error in the Chrome console and the data won't be displayed in the table:

"Failed to load resource: the server responded with a status of 404 (Not Found)"

So the Web IDEs webserer seems to find the service without a problem, while both the local apache server and the built-in PhpStorm server won't find it.

I also tried to enter the full service URI in the manifest.json

"uri": "http://xxx:50020/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/"

Doing so will result in getting another error at the chrome console

XMLHttpRequest cannot load http://xxx:50020/sap/opu/odata/SAP/ZSM_APPLIKATION_SRV/$metadata?sap-language=DE. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 401.

Is there any way now to connect to my service and consume data without using the Web IDE? How can I fix this error.

Thanks in advance


问:
Unique pointer to vector and polymorphism
I have problem, I want to create unique pointer to vector of Base objects.
I want keep in this vector subclass of Base (SubClass), but i have problem with initialization, because Base class is virtual.

```<code>std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);
</code>```

答:
A vector of Base doesn't support polymorphism. For this you need references or pointers or even better smart pointers:

```<code>auto baseVector = std::make_unique<std::vector<Base*>>();
auto baseVector = std::make_unique<std::vector<std::unique_ptr<Base>>>();
</code>```

add elements via

```<code>baseVector.push_back(std::make_unique<SubClass>());
</code>```

Body:
I have problem, I want to create unique pointer to vector of Base objects.
I want keep in this vector subclass of Base (SubClass), but i have problem with initialization, because Base class is virtual.

std::unique_ptr<std::vector<Base>> baseVector = std::make_unique<std::vector<Base>>();
SubClass newObject();
baseVector->push_back(newObject);

Body:
A vector of Base doesn't support polymorphism. For this you need references or pointers or even better smart pointers:

auto baseVector = std::make_unique<std::vector<Base*>>();
auto baseVector = std::make_unique<std::vector<std::unique_ptr<Base>>>();

add elements via

baseVector.push_back(std::make_unique<SubClass>());


问:
Symfony 3.3 Update - Argument 5 passed to FrameworkBundle Translator must be of the type array, object given,
I just updated from 3.2.9 to 3.3.2

receiving the following error:

```<code>Catchable Fatal Error: Argument 5 passed to Symfony\Bundle\FrameworkBundle\Translation\Translator::__construct() must be of the type array, object given, called in /dev/shm/appname/cache/dev/appDevDebugProjectContainer.php on line 4100 and defined
</code>```

No idea where to start looking and what files are needed further to help you to investigate my issue. The stracktrace brings me on the trace of dependency injection.. what breaking change in Symfony 3.3 did I miss?

答: Start by removing the lexik translator bundle from the script as it my not be ready for 3.3.x. Then clear cache files again.</p>

Body:
I just updated from 3.2.9 to 3.3.2

receiving the following error:

Catchable Fatal Error: Argument 5 passed to Symfony\Bundle\FrameworkBundle\Translation\Translator::__construct() must be of the type array, object given, called in /dev/shm/appname/cache/dev/appDevDebugProjectContainer.php on line 4100 and defined

No idea where to start looking and what files are needed further to help you to investigate my issue. The stracktrace brings me on the trace of dependency injection.. what breaking change in Symfony 3.3 did I miss?


问:
How to calculate the difference in days for two Date in Swift as days start at 6 a.m. instead of 0
I'm trying to get the difference in two Date objects.
I know how to do it basically, which is like this:

```<code>        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        print(count)
        // print(history[count - 1].value(forKey: "multipleURLs") as! [String])
        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

        let nowDate = calendar.startOfDay(for: date)
        let lastDate = calendar.startOfDay(for: latestDate)

        let diffDateComponent = (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: lastDate, to: nowDate, options: NSCalendar.Options.init(rawValue: 0))

        print("Status Checked" + String(describing: diffDateComponent.day))
</code>```

But I'm trying to get the result as a day start from 6 a.m. in the morning instead of 0.

So I did something like this:

```<code>        let nowDate = calendar.startOfDay(for: date.addingTimeInterval(-3600))
        let lastDate = calendar.startOfDay(for: latestDate.addingTimeInterval(-3600))
</code>```

But it doesn't seem to be working, can anyone help me with this?

答:
This will set each date to 6 AM (in the current locale of the Date):

```<code>import Foundation

// set up dates
let calendar = Calendar.current
let date = Date()
if let latestDate = calendar.date(byAdding: .day, value: -5, to: date) {

  // set each day to 6 AM
  if let nowDate  = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: date      ),
     let lastDate = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: latestDate) {

    print(    date.description(with: .current),
           nowDate.description(with: .current),
          lastDate.description(with: .current),
          separator: "\n")

    // calculate difference in days
    if let days = calendar.dateComponents([.day], from: lastDate, to: nowDate).day {
      print("Days since: \(days)")
    }
  }
}

// Thursday, June 8, 2017 at 7:59:42 AM Eastern Daylight Time
// Thursday, June 8, 2017 at 6:00:00 AM Eastern Daylight Time
// Saturday, June 3, 2017 at 6:00:00 AM Eastern Daylight Time
// Days since: 5
</code>```

Body:
I'm trying to get the difference in two Date objects.
I know how to do it basically, which is like this:

        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.locale = Locale.current

        print(count)
        // print(history[count - 1].value(forKey: "multipleURLs") as! [String])
        let latestDate = history[count - 1].value(forKey: "date") as! Date
        let calendar = Calendar.current

        let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

        let nowDate = calendar.startOfDay(for: date)
        let lastDate = calendar.startOfDay(for: latestDate)

        let diffDateComponent = (calendar as NSCalendar).components([NSCalendar.Unit.year, NSCalendar.Unit.month, NSCalendar.Unit.day], from: lastDate, to: nowDate, options: NSCalendar.Options.init(rawValue: 0))

        print("Status Checked" + String(describing: diffDateComponent.day))

But I'm trying to get the result as a day start from 6 a.m. in the morning instead of 0.

So I did something like this:

        let nowDate = calendar.startOfDay(for: date.addingTimeInterval(-3600))
        let lastDate = calendar.startOfDay(for: latestDate.addingTimeInterval(-3600))

But it doesn't seem to be working, can anyone help me with this?

Body:
This will set each date to 6 AM (in the current locale of the Date):

import Foundation

// set up dates
let calendar = Calendar.current
let date = Date()
if let latestDate = calendar.date(byAdding: .day, value: -5, to: date) {

  // set each day to 6 AM
  if let nowDate  = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: date      ),
     let lastDate = calendar.date(bySettingHour: 6, minute: 0, second: 0, of: latestDate) {

    print(    date.description(with: .current),
           nowDate.description(with: .current),
          lastDate.description(with: .current),
          separator: "\n")

    // calculate difference in days
    if let days = calendar.dateComponents([.day], from: lastDate, to: nowDate).day {
      print("Days since: \(days)")
    }
  }
}

// Thursday, June 8, 2017 at 7:59:42 AM Eastern Daylight Time
// Thursday, June 8, 2017 at 6:00:00 AM Eastern Daylight Time
// Saturday, June 3, 2017 at 6:00:00 AM Eastern Daylight Time
// Days since: 5


问:
Error 404 script not working, if
My error404 script was working perfectly, but then I did this:

I had non-friendly URL's like this:

```<code>localhost/website/user.php?name=UserA
</code>```

Then, I updated my .htaccess

```<code>#Options +FollowSymlinks
RewriteEngine On
RewriteRule    ^([0-9A-Za-z-]+)/?$   user.php?name=$1    [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ErrorDocument 404 /website/error404.html
</code>```

After this, my URL's are friendly URL like this: localhost/website/UserA

But, the error404 script do not work When the page is something like this: localhost/website/dsfdsfsfasfsfsfs

But if the page is something like this: localhost/website/SomeThingHere/sdfsfs

答:
Use:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule    ^([0-9A-Z-]+)/?$   user.php?name=$1    [NC,L]

ErrorDocument 404 /website/error404.html
</code>```

With RewriteCond before RewriteRule

But you rewrite /website/dsfdsfsfasfsfsfs to user.php?name=dsfdsfsfasfsfsfs
You need to change user.php to show 404 error when the user does not exist

Title: Error 404 script not working, if

Body:
My error404 script was working perfectly, but then I did this:

I had non-friendly URL's like this:

localhost/website/user.php?name=UserA

Then, I updated my .htaccess

#Options +FollowSymlinks
RewriteEngine On
RewriteRule    ^([0-9A-Za-z-]+)/?$   user.php?name=$1    [NC,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
ErrorDocument 404 /website/error404.html

After this, my URL's are friendly URL like this: localhost/website/UserA

But, the error404 script do not work When the page is something like this: localhost/website/dsfdsfsfasfsfsfs

But if the page is something like this: localhost/website/SomeThingHere/sdfsfs

Body:
Use:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule    ^([0-9A-Z-]+)/?$   user.php?name=$1    [NC,L]

ErrorDocument 404 /website/error404.html

With RewriteCond before RewriteRule

But you rewrite /website/dsfdsfsfasfsfsfs to user.php?name=dsfdsfsfasfsfsfs
You need to change user.php to show 404 error when the user does not exist


问:
Change State after finishing
Using Flash Builder 4 (with 4.1 flex).
Trying to create a state change after my function has finished running that will change the screen to have a "finished" button that will close the application.  How can I tell the air app to do this?

I found this: protected function setState(newState:String):void for AS3 but won't work on flex 4.  It should change state to Finished after the array of files is done.

```<code>        private function initiate_download(event:MouseEvent):void
        {
            var filearray:Array = new Array();
            filearray[0]="00.jpg";
            filearray[1]="01.jpg";
            filearray[2]="02.jpg";
            for (var i:uint; i < filearray.length; i++) {
                var remoteURL = "http://domain/" + filearray[i];
                var localURL = "C:/dir/" + filearray[i];
                downloadFile(remoteURL, localURL);
            }

            function downloadFile(url, filename) {
                // Create the stream for the data request
                var urlStream = new URLStream();

                // Used to initiate request for remote file
                var request = new URLRequest(url);

                // Create file stream
                var fileStream = new FileStream();

                // Create a reference to a location on disk
                var file = File.desktopDirectory.resolvePath(filename);

                // Called as download progresses
                var writeFile = function()
                {
                    // Write to file
                    if (urlStream.bytesAvailable > 51200)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }
                    return true;
                }

                // Called when download completes
                var finishWriteFile = function()
                {
                    // Write to file
                    if(urlStream.bytesAvailable > 0)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }

                    // Close streams
                    fileStream.close();
                    urlStream.close();

                    return true;
                }

                // Initiate download
                fileStream.openAsync(file, FileMode.WRITE);
                urlStream.load(request);

                // Add event listeners
                urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
                urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
    ]]>
</fx:Script>
<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:states>
    <s:State name="Start"/>
    <s:State name="Finished"/>
</s:states>
<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" includeIn="Start" label="Update" id="download" click="initiate_download(event)" color="#FFFFFF" fontSize="30"/>
<s:Button x="131" y="85" includeIn="Finished" label="Finished" id="closer" click="close_window(event)" color="#FFFFFF" fontSize="30"/>
</code>```

答:
after you close the fileStream and urlStream you can change state doing

```<code>this.currentState = "Finished"
</code>```

and the close button should be visible now.

ContentLicense: CC BY-SA 2.5

Title: Change State after finishing

Body:
Using Flash Builder 4 (with 4.1 flex).
Trying to create a state change after my function has finished running that will change the screen to have a "finished" button that will close the application.  How can I tell the air app to do this?

I found this: protected function setState(newState:String):void for AS3 but won't work on flex 4.  It should change state to Finished after the array of files is done.

        private function initiate_download(event:MouseEvent):void
        {
            var filearray:Array = new Array();
            filearray[0]="00.jpg";
            filearray[1]="01.jpg";
            filearray[2]="02.jpg";
            for (var i:uint; i < filearray.length; i++) {
                var remoteURL = "http://domain/" + filearray[i];
                var localURL = "C:/dir/" + filearray[i];
                downloadFile(remoteURL, localURL);
            }

            function downloadFile(url, filename) {
                // Create the stream for the data request
                var urlStream = new URLStream();

                // Used to initiate request for remote file
                var request = new URLRequest(url);

                // Create file stream
                var fileStream = new FileStream();

                // Create a reference to a location on disk
                var file = File.desktopDirectory.resolvePath(filename);

                // Called as download progresses
                var writeFile = function()
                {
                    // Write to file
                    if (urlStream.bytesAvailable > 51200)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }
                    return true;
                }

                // Called when download completes
                var finishWriteFile = function()
                {
                    // Write to file
                    if(urlStream.bytesAvailable > 0)
                    {
                        var dataBuffer = new ByteArray();
                        urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);
                        fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);
                    }

                    // Close streams
                    fileStream.close();
                    urlStream.close();

                    return true;
                }

                // Initiate download
                fileStream.openAsync(file, FileMode.WRITE);
                urlStream.load(request);

                // Add event listeners
                urlStream.addEventListener(Event.COMPLETE, finishWriteFile);
                urlStream.addEventListener(ProgressEvent.PROGRESS, writeFile);
            }
    ]]>
</fx:Script>
<fx:Declarations>

</fx:Declarations>
<s:states>
    <s:State name="Start"/>
    <s:State name="Finished"/>
</s:states>
<mx:Image x="0" y="0" source="background.jpg"/>
<s:Button x="85" y="85" includeIn="Start" label="Update" id="download" click="initiate_download(event)" color="#FFFFFF" fontSize="30"/>
<s:Button x="131" y="85" includeIn="Finished" label="Finished" id="closer" click="close_window(event)" color="#FFFFFF" fontSize="30"/>

Body:
after you close the fileStream and urlStream you can change state doing

this.currentState = "Finished"

and the close button should be visible now.


问:
How to find the path to tf.exe from MsBuild
I have an MsBuild file which shells out to TFS using tf.exe for a few things. Unfortunately the tf.exe file has been installed to different locations on the developer PCs and the build server.

I could really do with a way of detecting where the tf.exe file is located within my script in the same way you can do $(MSBuildExtensionsPath32) etc. Is this possible?

Thanks as always :)

答:
Seems they changed location again in Visual Studio 2017.
It was not in any of the above locations on my machine.

I found TF.exe instead at:

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

(Some users may find in the Professional folder instead of Enterprise folder: C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\tf.exe)

Apparently the environment variable is no longer set by default in VS 2017.

ContentLicense: CC BY-SA 4.0


问:
Failing to draw points obtained from geoJson on Leaflet map
I have to realize an Android app that shows a map in a WebView with Leaflet and uses data from a JSON to draw some points.

This is the HTML code loaded in the WebView:

```<code><title>Leaflet example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin=""/>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>

<style>
    #map {
        width: 600px;
        height: 400px;
    }
</style>

</head>
<body>

<div id='map'></div>
<script src="file:///android_asset/provaquake.js" type="text/javascript">
</script>
<script src="file:///android_asset/map.js"></script>

</body>
</code>```

This is the javascript file that calls the map with Leaflet and draws a line for testing:

```<code>var map = L.map('map').setView([39.74739, -105], 13);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
        '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
        'Imagery © <a href="http://mapbox.com">Mapbox</a>',
    id: 'mapbox.light'
}).addTo(map);

var myLines = [{
    "type": "LineString",
    "coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];

var myStyle = {
    "color": "#ff7800",
    "weight": 5,
    "opacity": 0.65
};

L.geoJSON(myLines, {
    style: myStyle
}).addTo(map);
</code>```

provaquake.js is a file that contains a variable named "quake" initialized with this geoJson:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson

I wrote this code to add the location of every earthquake to the map:

```<code>L.geoJSON(quake, {
    style: function (feature) {
        return feature.properties && feature.properties.style;
    },
    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, {
            radius: 8,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
        });
    }
}).addTo(map);
</code>```

but it doesn't seem to work.

All the code works well except this last instruction for the points, I'm completely new to Leaflet and I don't know why it doesn't draw them

答:
Here is a working example. The only thing I changed to your code is add the fetch to the quake json and set the map zoom to 3 for the demo.  Double check that your quake variable is correctly populated with the quake FeatureCollection data.

var map = L.map('map').setView([39.74739, -105], 3);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: 'Map data © OpenStreetMap contributors, ' +
    'CC-BY-SA, ' +
    'Imagery © Mapbox',
  id: 'mapbox.light'
}).addTo(map);

var myLines = [{
  "type": "LineString",
  "coordinates": [
    [-105, 40],
    [-110, 45],
    [-115, 55]
  ]
}];

var myStyle = {
  "color": "#ff7800",
  "weight": 5,
  "opacity": 0.65
};

L.geoJSON(myLines, {
  style: myStyle
}).addTo(map);

fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson')
  .then(function(res) {
    if (res.ok === true) {
      return res.json();
    } else {
      alert('Geojson request failed.');
    }
  })
  .then(function(quake) {
    L.geoJSON(quake, {
      style: function(feature) {
        return feature.properties && feature.properties.style;
      },
      pointToLayer: function(feature, latlng) {
        return L.circleMarker(latlng, {
          radius: 8,
          fillColor: "#ff7800",
          color: "#000",
          weight: 1,
          opacity: 1,
          fillOpacity: 0.8
        });
      }
    }).addTo(map);
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><title>Leaflet example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>

<style>
  #map {
    width: 600px;
    height: 400px;
  }
</style>

</head>

<body>

  <div id='map'></div>
  <script src="file:///android_asset/provaquake.js" type="text/javascript">
  </script>
  <script src="file:///android_asset/map.js"></script>

</body></code>```

Body:
I have to realize an Android app that shows a map in a WebView with Leaflet and uses data from a JSON to draw some points.

This is the HTML code loaded in the WebView:

<title>Leaflet example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin=""/>

This is the javascript file that calls the map with Leaflet and draws a line for testing:

var map = L.map('map').setView([39.74739, -105], 13);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
    maxZoom: 18,
    attribution: 'Map data © OpenStreetMap contributors, ' +
        'CC-BY-SA, ' +
        'Imagery © Mapbox',
    id: 'mapbox.light'
}).addTo(map);

var myLines = [{
    "type": "LineString",
    "coordinates": [[-105, 40], [-110, 45], [-115, 55]]
}];

var myStyle = {
    "color": "#ff7800",
    "weight": 5,
    "opacity": 0.65
};

L.geoJSON(myLines, {
    style: myStyle
}).addTo(map);

provaquake.js is a file that contains a variable named "quake" initialized with this geoJson:
https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson

I wrote this code to add the location of every earthquake to the map:

L.geoJSON(quake, {
    style: function (feature) {
        return feature.properties && feature.properties.style;
    },
    pointToLayer: function (feature, latlng) {
        return L.circleMarker(latlng, {
            radius: 8,
            fillColor: "#ff7800",
            color: "#000",
            weight: 1,
            opacity: 1,
            fillOpacity: 0.8
        });
    }
}).addTo(map);

but it doesn't seem to work.

All the code works well except this last instruction for the points, I'm completely new to Leaflet and I don't know why it doesn't draw them

Body:
Here is a working example. The only thing I changed to your code is add the fetch to the quake json and set the map zoom to 3 for the demo.  Double check that your quake variable is correctly populated with the quake FeatureCollection data.

var map = L.map('map').setView([39.74739, -105], 3);

L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
  maxZoom: 18,
  attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' +
    '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
    'Imagery © <a href="http://mapbox.com">Mapbox</a>',
  id: 'mapbox.light'
}).addTo(map);

var myLines = [{
  "type": "LineString",
  "coordinates": [
    [-105, 40],
    [-110, 45],
    [-115, 55]
  ]
}];

var myStyle = {
  "color": "#ff7800",
  "weight": 5,
  "opacity": 0.65
};

L.geoJSON(myLines, {
  style: myStyle
}).addTo(map);

fetch('https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.geojson')
  .then(function(res) {
    if (res.ok === true) {
      return res.json();
    } else {
      alert('Geojson request failed.');
    }
  })
  .then(function(quake) {
    L.geoJSON(quake, {
      style: function(feature) {
        return feature.properties && feature.properties.style;
      },
      pointToLayer: function(feature, latlng) {
        return L.circleMarker(latlng, {
          radius: 8,
          fillColor: "#ff7800",
          color: "#000",
          weight: 1,
          opacity: 1,
          fillOpacity: 0.8
        });
      }
    }).addTo(map);
  });

<title>Leaflet example</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/x-icon" href="docs/images/favicon.ico" />
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.0.3/dist/leaflet.css" integrity="sha512-07I2e+7D8p6he1SIM+1twR5TIrhUQn9+I6yjqD53JQjFiMf8EtC93ty0/5vJTZGF8aAocvHYNEDJajGdNx1IsQ==" crossorigin="" />
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js" integrity="sha512-A7vV8IFfih/D732iSSKi20u/ooOfj/AGehOKq0f4vLT1Zr2Y+RX7C+w8A1gaSasGtRUZpF/NZgzSAu4/Gc41Lg==" crossorigin=""></script>

<style>
  #map {
    width: 600px;
    height: 400px;
  }
</style>

</head>

<body>

  <div id='map'></div>
  <script src="file:///android_asset/provaquake.js" type="text/javascript">
  </script>
  <script src="file:///android_asset/map.js"></script>

</body>


问:
Segmentation fault(core dumped) c++
The following program gives the correct output but gives segmentation fault(core dumped in the end)

```<code>#include <iostream>

using namespace std;

int main()
{
    int a[50],n,i,c[50],b[50];
    cin>>n;
    for(i=1;i<=n;i++)
    cin>>a[i];
    for(i=1;i<=100;i++)
        b[i]=0;
    for(i=1;i<=n;i++)
    {
        b[a[i]]++;
    }
    for(i=2;i<=100;i++)
    {
        b[i]=b[i]+b[i-1];
    }
    for(i=1;i<=n;i++)
    {
        c[b[a[i]]]=a[i];
        b[a[i]]--;
    }
    for(i=1;i<=n;i++)
        cout<<c[i]<<endl;
    return 0;
}
</code>```

Here is the debugger output
gdb

答:
You are going out of bounds here:

```<code>for(i=2;i<=100;i++)
{
    b[i]=b[i]+b[i-1];
}
</code>```

since b is an array of size 50 and you allow i to reach the value of 100 and index the array. This causes the segmentation fault.

PS: Other loops may also index your arrays out of bounds, depending on the input you receive, since you don't check the input.

Title: Segmentation fault(core dumped) c++

Body:
The following program gives the correct output but gives segmentation fault(core dumped in the end)

#include <iostream>

using namespace std;

int main()
{
    int a[50],n,i,c[50],b[50];
    cin>>n;
    for(i=1;i<=n;i++)
    cin>>a[i];
    for(i=1;i<=100;i++)
        b[i]=0;
    for(i=1;i<=n;i++)
    {
        b[a[i]]++;
    }
    for(i=2;i<=100;i++)
    {
        b[i]=b[i]+b[i-1];
    }
    for(i=1;i<=n;i++)
    {
        c[b[a[i]]]=a[i];
        b[a[i]]--;
    }
    for(i=1;i<=n;i++)
        cout<<c[i]<<endl;
    return 0;
}

Here is the debugger output
gdb

Body:
You are going out of bounds here:

for(i=2;i<=100;i++)
{
    b[i]=b[i]+b[i-1];
}

since b is an array of size 50 and you allow i to reach the value of 100 and index the array. This causes the segmentation fault.

PS: Other loops may also index your arrays out of bounds, depending on the input you receive, since you don't check the input.


问:
2nd normal form violation with lhs of the dependency is composite (prime and non-prime together)
I was studying functional dependencies and normalization and I've come across a question. The original question is below:

"Given the relation R = {v,w,x,y,z} and functional dependency set {v->w,y->z,yz->v,wx->z} find BCNF composition and check if dependency preservation holds."

First I tried to find minimal cover and came up with this:

Minimal Cover:

v -> w

y -> z

y -> v

wx -> z

Then I tried to found candidate keys, came up with only one candidate key:

Candidate Keys:

xy

Then I started to check normal forms:

1st Normal Form: check

2nd Normal Form:

I thought the below dependencies are violating 2nd normal form:

1) y -> z

2) y -> v

3) wx -> z

The first two were easy to solve. However, I've never seen an example of the 3rd where the left-hand side is a composite of prime and non-prime attributes. How do we solve this kind of situation? Do we make a new relation for the 3rd making w and x primary key?

If I solve that part, the 3rd and BC normal forms will be easy I guess.

答:
Whether one considers a FD (functional dependency) to "violate 2NF" depends on one's definition of 2NF. A common definition of 2NF is, no FDs hold where a non-prime attribute is partially functionally dependent on a CK (candidate key). So are the violating FDs the ones where a non-prime attribute is partially functionally dependent on a CK? Or the ones where a non-prime attribute is functionally dependent on a proper subset of a CK, by which the preceding FDs are partial? Or both? And/or others? Or what? The fact is that it isn't individual FDs that violate NFs but the set of all FDs that hold. If you want to talk about individual FDs violating then you need to give a definition for 2NF & then give & justify a definition of violating FD based on how the definition talks about such FDs.

The following uses the 2NF definition above & talks about "bad" FDs explicitly disallowed by that definition, where a non-prime attribute is partially functionally dependent on a CK.

Those three FDs are not bad. A FD is partial when its right hand side is functionally determined by a proper/smaller subset of its left hand side. None of those three FDs are partial dependencies on a CK (candidate key). None of them are even partial, because none has a right hand side that is determined by a subset of the left hand side (determinant). And none of them are even on a CK, because none of them have a CK as their left hand side.

You might consider the first two to "violate 2NF" per a 2NF definition that there are no FDs with left side a proper subset of a CK & right side a non-prime attribute. That definition explicitly disallows those FDs. So we do not have 2NF.

However the FDs xy->z & xy->v are partial, because proper/smaller subsets of xy determine z & v. And they are bad: xy is a CK and Z & v are non-prime attributes so both have a non-prime attribute partially dependent on a CK. So we do not have 2NF.

wx->z isn't bad. And it doesn't "violate 2NF" per a 2NF definition that there are no FDs with left side a proper subset of a CK & right side a non-prime attribute.

It doesn't matter whether "the left-hand side is a composite of prime and non-prime attributes". What matters is what is mentioned in your definitions. (It happens that you will never see such "an example" of a bad or "violating" FD. Because both those require left-hand sides with only CK attributes.)

Read some academic definitions for partial FD & 2NF. (Many textbooks/presentations/courses are free online.) Memorize and apply definitions, theorems and algorithms exactly. You seem to not understand numerous things:

Being in BCNF implies being in all lower NFs. Getting to BCNF does not require going through lower NFs.

Examples of decompositions you have seen are not presentations of decomposition algorithms.

We don't normalize via successive NFs. We use an algorithm for the NF we want. (Going through lower NFs can even mean good higher-NF designs become unavailable.)

When some FDs hold, all the ones implied by them by Armstrong's axioms also hold.

To determine CKs & NFs it's not enough to know that some FDs hold, we need to know what FDs hold & what FDs don't hold. You need to know a closure or cover of FDs.

Each time we decompose we get new relations & sets of FDs & CKs for each.

The FDs that hold in a component are all those of the original whose attributes are in it. (Those of a closure, not just those of a cover.)

A FD is partial when its right hand side is functionally determined by a proper/smaller subset of its left hand side.

A common 2NF definition explicitly disallows partial FDs of non-prime attributes on CKs.

"Violating FD" is not a helpful term, refer to the things that definitions mention.


问:
How can i fix this error?? error is cannot assign to the property "target is a method"
    //This is my custom navigation function

```<code>    func addSlideMenuButton()
</code>```

// This is my custom navigation bar

```<code>      let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width,height: 104))
 let backgroundImage = UIImage(named: "BarBa")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 15, 0, 15), resizingMode: UIImageResizingMode.stretch)
                UINavigationBar.appearance().setBackgroundImage(backgroundImage, for: .default)
    // Create a navigation item with a title

let navigationItem = UINavigationItem()
                let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 90 ))
                imageView.contentMode = .scaleAspectFit
                let image = UIImage(named: "logo.png")
                imageView.image = image
                navigationItem.titleView = imageView

                let button = UIButton.init(type: .custom)
                button.setImage(UIImage.init(named: "sidebar.png"), for: UIControlState.normal)
                button.addTarget(self, action:#selector(NewsTableViewController.callMethod), for: UIControlEvents.touchUpInside)
                button.frame = CGRect.init(x: 0, y: 0, width: 70, height: 80)
                let customBarItem = UIBarButtonItem(customView: button)
                self.navigationItem.leftBarButtonItem = customBarItem;
                navigationBar.items = [navigationItem]

                // Make the navigation bar a subview of the current view controller
                self.view.addSubview(navigationBar)

 //tapping the menu button work
 // Here revealViewController is a objective C class

   if self.revealViewController() != nil {
                button.target = self.revealViewController()
                button.action = #selector(SWRevealViewController.revealToggle(_:)) // in this 2 line i got error cannot assign to the property "target is a method"
                self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
                // for set customiz width
                self.revealViewController().rearViewRevealWidth = 250
            }
            // Assign the navigation item to the navigation bar
            navigationBar.items = [navigationItem]
            self.view.addSubview(navigationBar)
        }
</code>```

答: you are not using a bar button item, SWRevealController action and target work with bar button not simple button</p>

Body:
    //This is my custom navigation function

    func addSlideMenuButton()

// This is my custom navigation bar

      let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.size.width,height: 104))
 let backgroundImage = UIImage(named: "BarBa")?.resizableImage(withCapInsets: UIEdgeInsetsMake(0, 15, 0, 15), resizingMode: UIImageResizingMode.stretch)
                UINavigationBar.appearance().setBackgroundImage(backgroundImage, for: .default)
    // Create a navigation item with a title

let navigationItem = UINavigationItem()
                let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 70, height: 90 ))
                imageView.contentMode = .scaleAspectFit
                let image = UIImage(named: "logo.png")
                imageView.image = image
                navigationItem.titleView = imageView

                let button = UIButton.init(type: .custom)
                button.setImage(UIImage.init(named: "sidebar.png"), for: UIControlState.normal)
                button.addTarget(self, action:#selector(NewsTableViewController.callMethod), for: UIControlEvents.touchUpInside)
                button.frame = CGRect.init(x: 0, y: 0, width: 70, height: 80)
                let customBarItem = UIBarButtonItem(customView: button)
                self.navigationItem.leftBarButtonItem = customBarItem;
                navigationBar.items = [navigationItem]

                // Make the navigation bar a subview of the current view controller
                self.view.addSubview(navigationBar)

 //tapping the menu button work
 // Here revealViewController is a objective C class

   if self.revealViewController() != nil {
                button.target = self.revealViewController()
                button.action = #selector(SWRevealViewController.revealToggle(_:)) // in this 2 line i got error cannot assign to the property "target is a method"
                self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
                // for set customiz width
                self.revealViewController().rearViewRevealWidth = 250
            }
            // Assign the navigation item to the navigation bar
            navigationBar.items = [navigationItem]
            self.view.addSubview(navigationBar)
        }


答:
Apart from other conditions in your program, at least this loop causes a buffer overflow and hence invokes undefined behavior!

```<code>for(i=1;i<=100;i++)
        b[i]=0;
</code>```

That is, because b has only 50 elements, and you're accessing memory waaay beyond that range. Also C arrays a zero-index based.

Note, that you likely cause UB in other statements as well, but this one was the first I noticed skimming over your code.

Title: Segmentation fault(core dumped) c++

Body:
Apart from other conditions in your program, at least this loop causes a buffer overflow and hence invokes undefined behavior!

for(i=1;i<=100;i++)
        b[i]=0;

That is, because b has only 50 elements, and you're accessing memory waaay beyond that range. Also C arrays a zero-index based.

Note, that you likely cause UB in other statements as well, but this one was the first I noticed skimming over your code.


问:
Convert array in json javascript - same key
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)
```

<p>And I'd like my JSON structured like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}
</code>```

I tried using json_encode but this alone doesn't give me what I want.

答:
```<code>let myArray = [
  'teste3.pdf',
  'teste2.pdf',
  'teste.pdf'
];
let obj = {
  Documents: myArray.map( item => ({ NameDoc: item }))
};
let jsonString = JSON.stringify(obj);
</code>```

Body:
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)

And I'd like my JSON structured like this:

{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}

I tried using json_encode but this alone doesn't give me what I want.


问:
Xamarin Forms - calling rest service from viewmodel of pcl
I created a class that connected to the API to retrieve the required data using httpclient. That file was called in the code behind file of the view and worked perfectly. Than I decided to implement the MVVM approach. As a result, I moved the code that initialized the rest service class to the view-model.
After doing that, i stopped getting the data. To investigate, I stated the the debugging session with the breakpoint placed at the line where i initialize the rest service class. Than i executed that line. By doing that, I found out that a huge android mono exception is thrown and the debugging session if stopped. The app exits the debugging session.
This has happened for the first time since i stated developing my app in Xamarin Forms. I have no idea about why it is breaking like that. Your help will be greatly appreciated.

This is the code that was working properly.
In the view code behind file

```<code>[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SubtaskPage : ContentPage
{
    protected override void OnAppearing()
    {
         base.OnAppearing();
         PopulateSubtaskData();
    }
    private async void PopulateSubtaskData()
    {
        lstSubtasks.IsRefreshing = true;
        try
        {
            RestService rs = new RestService();
            SResponse = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
            if (SResponse.Status == 1)
            {
                lstSubtasks.ItemsSource = SResponse.Subtasks;
            }
            else
            {
                await DisplayAlert("Error", SResponse.Message, "Ok");
            }
       }
       catch (Exception E)
       {
           Debug.WriteLine(@"GetSubtasksAsync -> ERROR {0}", E.Message);
       }
       lstSubtasks.IsRefreshing = false;
    }
}
</code>```

The rest service class is as follows
This class is in a separate folder named "Services". ip and url have been changed for security reason.

```<code>class RestService
{
        HttpClient client;
        public List<Ticket> Tickets { get; private set; }
        string Server1 = "server ip";
        string Server2 = "server ip";
        public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
        }
        public async Task<SubtasksResponse> GetSubtasksAsync(int UserId)
        {
            SubtasksResponse SubtaskResponse = new SubtasksResponse();
            string ApiUrl = "URL";
            string Url = "";
            HttpResponseMessage response;
            if (CrossConnectivity.Current.IsConnected)
            {
                Url = await GetActiveServerAsync();
                if (Url != "")
                {
                    var uri = string.Format(Url + ApiUrl, UserId);
                    try
                    {
                        response = await client.GetAsync(uri);
                        if (response.IsSuccessStatusCode)
                        {
                            var content = await response.Content.ReadAsStringAsync();
                            SubtaskResponse.Subtasks = JsonConvert.DeserializeObject<List<Ticket>>(content);
                            SubtaskResponse.Status = 1;
                        }
                        else
                        {
                            SubtaskResponse.Subtasks = null;
                            SubtaskResponse.Status = 0;
                            SubtaskResponse.Message = "Attempt to fetch data from server was unsuccessful. Please try again";
                        }
                    }
                    catch (Exception E)
                    {
                        SubtaskResponse.Subtasks = null;
                        SubtaskResponse.Status = 0;
                        SubtaskResponse.Message = "Error occured while fetching data from the server. Please try again";
                    }
                }
                else
                {
                    SubtaskResponse.Subtasks = null;
                    SubtaskResponse.Status = 0;
                    SubtaskResponse.Message = "Remote Server Not Responding! Please try again later";
                }
            }
            else
            {
                SubtaskResponse.Subtasks = null;
                SubtaskResponse.Status = 0;
                SubtaskResponse.Message = "No Network Connection Found! Please connect to a network and try again";
            }
            return SubtaskResponse;
        }
    }
}
</code>```

This was working fine until I added the view model into the mix.
This is how I am calling the function in the view model.

```<code>async Task<SubtasksResponse> PopulateSubtaskList()
{
    RestService rs = new RestService();
    IsBusy = true;
    _subtaskList = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
    IsBusy = false;
    return _subtaskList;
}
</code>```

"RestService rs = new RestService();" this is the line where the code breaks.

Here is the image of the exception that occurs when the code breaks.

Hope you get the clear picture of the situation. Please let me know if additional information is required.
Thanks

答: Don't do this. If you want to call rest from a mvvm Xamarin Forms app I can advice Refit. All the difficult work is already done for you and abstracted away. With a few lines of code you are up and running.</p>

Body:
I created a class that connected to the API to retrieve the required data using httpclient. That file was called in the code behind file of the view and worked perfectly. Than I decided to implement the MVVM approach. As a result, I moved the code that initialized the rest service class to the view-model.
After doing that, i stopped getting the data. To investigate, I stated the the debugging session with the breakpoint placed at the line where i initialize the rest service class. Than i executed that line. By doing that, I found out that a huge android mono exception is thrown and the debugging session if stopped. The app exits the debugging session.
This has happened for the first time since i stated developing my app in Xamarin Forms. I have no idea about why it is breaking like that. Your help will be greatly appreciated.

This is the code that was working properly.
In the view code behind file

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SubtaskPage : ContentPage
{
    protected override void OnAppearing()
    {
         base.OnAppearing();
         PopulateSubtaskData();
    }
    private async void PopulateSubtaskData()
    {
        lstSubtasks.IsRefreshing = true;
        try
        {
            RestService rs = new RestService();
            SResponse = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
            if (SResponse.Status == 1)
            {
                lstSubtasks.ItemsSource = SResponse.Subtasks;
            }
            else
            {
                await DisplayAlert("Error", SResponse.Message, "Ok");
            }
       }
       catch (Exception E)
       {
           Debug.WriteLine(@"GetSubtasksAsync -> ERROR {0}", E.Message);
       }
       lstSubtasks.IsRefreshing = false;
    }
}

The rest service class is as follows
This class is in a separate folder named "Services". ip and url have been changed for security reason.

class RestService
{
        HttpClient client;
        public List<Ticket> Tickets { get; private set; }
        string Server1 = "server ip";
        string Server2 = "server ip";
        public RestService()
        {
            client = new HttpClient();
            client.MaxResponseContentBufferSize = 256000;
        }
        public async Task<SubtasksResponse> GetSubtasksAsync(int UserId)
        {
            SubtasksResponse SubtaskResponse = new SubtasksResponse();
            string ApiUrl = "URL";
            string Url = "";
            HttpResponseMessage response;
            if (CrossConnectivity.Current.IsConnected)
            {
                Url = await GetActiveServerAsync();
                if (Url != "")
                {
                    var uri = string.Format(Url + ApiUrl, UserId);
                    try
                    {
                        response = await client.GetAsync(uri);
                        if (response.IsSuccessStatusCode)
                        {
                            var content = await response.Content.ReadAsStringAsync();
                            SubtaskResponse.Subtasks = JsonConvert.DeserializeObject<List<Ticket>>(content);
                            SubtaskResponse.Status = 1;
                        }
                        else
                        {
                            SubtaskResponse.Subtasks = null;
                            SubtaskResponse.Status = 0;
                            SubtaskResponse.Message = "Attempt to fetch data from server was unsuccessful. Please try again";
                        }
                    }
                    catch (Exception E)
                    {
                        SubtaskResponse.Subtasks = null;
                        SubtaskResponse.Status = 0;
                        SubtaskResponse.Message = "Error occured while fetching data from the server. Please try again";
                    }
                }
                else
                {
                    SubtaskResponse.Subtasks = null;
                    SubtaskResponse.Status = 0;
                    SubtaskResponse.Message = "Remote Server Not Responding! Please try again later";
                }
            }
            else
            {
                SubtaskResponse.Subtasks = null;
                SubtaskResponse.Status = 0;
                SubtaskResponse.Message = "No Network Connection Found! Please connect to a network and try again";
            }
            return SubtaskResponse;
        }
    }
}

This was working fine until I added the view model into the mix.
This is how I am calling the function in the view model.

async Task<SubtasksResponse> PopulateSubtaskList()
{
    RestService rs = new RestService();
    IsBusy = true;
    _subtaskList = await rs.GetSubtasksAsync(Convert.ToInt32(Application.Current.Properties["UserId"]));
    IsBusy = false;
    return _subtaskList;
}

"RestService rs = new RestService();" this is the line where the code breaks.

Here is the image of the exception that occurs when the code breaks.

Hope you get the clear picture of the situation. Please let me know if additional information is required.
Thanks


问:
Number to text decoding
Can anybody help me come up with an algorithm or way to decode a number to 3 characters when they are encoded in the following manner:

Each element represents 3 alphabetic characters as in the following examples:

DOG -> (3 * 26^2) + (14 * 26) + 6 = 2398

CAT -> (2 * 26^2) + (0 * 26) + 19 = 1371

ZZZ -> (25 * 26^2) + (25 * 26) + 25 = 17575

So say I have 7446 or 3290 how would I go about converting them to text?

答:
Try this to extract the letters in reverse order:

```<code>7446             % 26 = 10
(7446 / 26)      % 26 = 0
(7446 / 26 / 26) % 26 = 11
</code>```

For example:

```<code>1371             % 26 = 19 (T)
(1371 / 26)      % 26 = 0  (A)
(1371 / 26 / 26) % 26 = 2  (C)

CAT
</code>```

The % refers to the modulo operation. x % y gives you the remainder of the division x / y.

Title: Number to text decoding

Body:
Try this to extract the letters in reverse order:

7446             % 26 = 10
(7446 / 26)      % 26 = 0
(7446 / 26 / 26) % 26 = 11

For example:

1371             % 26 = 19 (T)
(1371 / 26)      % 26 = 0  (A)
(1371 / 26 / 26) % 26 = 2  (C)

CAT

The % refers to the modulo operation. x % y gives you the remainder of the division x / y.


问:
How can I fetch values from object array using jquery and javascript
I have this array structure :

```<code>var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };
</code>```

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div

```<code><p id="array"></p>
</code>```

答:
There are different ways. The best suited would be:

Bracket Notation

var prop = object['property_name'];

Dot Notation

var prop = object.property_name;

In your case it would be

var obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

    console.log(obj.sections2.row4.key2);//Dot notation
    console.log(obj['sections2']['row4']['key2']);//Bracket notation
    document.getElementById("array").innerHTML=obj.sections2.row4.key2;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="array"></p></code>```

For more details refer MDN Property Accessors

Hoe it helps :)

Body:
I have this array structure :

var $obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

I want to fetch data from $obj->section2->row4->key2. How can I make it using jquery and javascript both.

UPDATE: I want it to print the value in a paragraph or div

Body:
There are different ways. The best suited would be:

Bracket Notation

var prop = object['property_name'];

Dot Notation

var prop = object.property_name;

In your case it would be

var obj = {
        'sections1' : {
            'row1' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row2' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        },
        'sections2' : {
            'row3' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            },
            'row4' : {
                'key1' : 'input1',
                'key2' : 'inpu2'
            }
        }
    };

    console.log(obj.sections2.row4.key2);//Dot notation
    console.log(obj['sections2']['row4']['key2']);//Bracket notation
    document.getElementById("array").innerHTML=obj.sections2.row4.key2;

<p id="array"></p>

For more details refer MDN Property Accessors

Hoe it helps :)


问:
your content folder is not writable wordpress
Can somebody help me please. I have getting a headache. I recently moved my server. The website run as normal but when I try to add content. My wordpress site shown. "your content folder is not writable"

I have did changing the permission to 777 to recursive folders but it won't work. I also tried to change it from ssh which code

```<code>chmod -R 777 /home/admin/public_html/wp-content/uploads
</code>```

surprisingly, the admin dashboard still show the same error. I really appreciate any helps. Thank you.

答:
That's a server permission problem. According to the WP docs:

Any file that needs write access from WordPress should be owned or
  group-owned by the user account used by the WordPress (which may be
  different than the server account). For example, you may have a user
  account that lets you FTP files back and forth to your server, but
  your server itself may run using a separate user, in a separate
  usergroup, such as dhapache or nobody. If WordPress is running as the
  FTP account, that account needs to have write access, i.e., be the
  owner of the files, or belong to a group that has write access. In the
  latter case, that would mean permissions are set more permissively
  than default (for example, 775 rather than 755 for folders, and 664
  instead of 644).

From http://codex.wordpress.org/Changing_File_Permissions

And, FYI, search first for a common issue like permissions; there are many answers already on WP permissions.

Body:
Can somebody help me please. I have getting a headache. I recently moved my server. The website run as normal but when I try to add content. My wordpress site shown. "your content folder is not writable"

I have did changing the permission to 777 to recursive folders but it won't work. I also tried to change it from ssh which code

chmod -R 777 /home/admin/public_html/wp-content/uploads

surprisingly, the admin dashboard still show the same error. I really appreciate any helps. Thank you.


问:
Android smart-card interface over USB
I need to read/write to a smart-card using a smart-card reader attached to an Android phone by USB.
Is this possible with native APIs or do I have to install other libraries?

Thank you

答: Sadly there is no abstraction layer like PC/SC in the native Android system. But you can utilize Android USB library to talk directly to the USB smart card reader.

Title: Android smart-card interface over USB


问:
PHP- How to display a specific form based on a selection?
I'm new in the word of html and PHP, so I would like to ask a question: in the HTMl code there is a form and inside that there are two options to select: lesson or topic.
I would like to show a form when the user selects "lesson" and another one if the user select "topic".
How can I do it?</p>

```<code><!DOCTYPE html>
<html>
<head>
    <title>Create a lesson</title>
</head>
<body>

    <?php

    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

        if($_POST["argumetOrLesson"] == "topic")
        {
            //form to input a topic
        }
        else
        {
            //form to input a lesson

        }

    ?>

    <form method="post" action= "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
    <label for="argumetOrLesson">Topic or Lesson?</label>
    <select id="argumetOrLesson" name="argumetOrLesson">
      <option value="topic">Topic</option>
      <option value="lesson">Lesson</option>
    </select>
    <input type="submit" value="Submit">
  </form>

</body>
</html>
</code>```

答:
Here is a syntax error in your code. You forgot the closing of first if statement. Replace your php code with this:

```<code>if($_SERVER["REQUEST_METHOD"] == "POST")
{

    if($_POST["argumetOrLesson"] == "topic")
    {
        //form to input a topic
    }
    else
    {
        //form to input a lesson

    }
}
?>
</code>```

Body:
I'm new in the word of html and PHP, so I would like to ask a question: in the HTMl code there is a form and inside that there are two options to select: lesson or topic.
I would like to show a form when the user selects "lesson" and another one if the user select "topic".
How can I do it?

<!DOCTYPE html>

    <title>Create a lesson</title>

    <?php

    if($_SERVER["REQUEST_METHOD"] == "POST")
    {

        if($_POST["argumetOrLesson"] == "topic")
        {
            //form to input a topic
        }
        else
        {
            //form to input a lesson

        }

    ?>

    <form method="post" action= "<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>">
    Topic or Lesson?
    <select id="argumetOrLesson" name="argumetOrLesson">
      <option value="topic">Topic</option>
      <option value="lesson">Lesson</option>
    </select>
    <input type="submit" value="Submit">
  </form>

Body:
Here is a syntax error in your code. You forgot the closing of first if statement. Replace your php code with this:

if($_SERVER["REQUEST_METHOD"] == "POST")
{

    if($_POST["argumetOrLesson"] == "topic")
    {
        //form to input a topic
    }
    else
    {
        //form to input a lesson

    }
}
?>


问:
Get Woocommerce customer order language
I'm developing a complementary plugin for woocommerce.
I have a sql request that gets all the order and customer info, but i need to get the language from the order.

How can i detect the language was using a customer when he made an order? Is it registered somewhere?

In other CMS like prestashop it's stored as id_lang in orders and customer tables.

答:
Finally solved, both solutions are OK.

With WPML plugin you can get the value in the table postmeta with the meta_key = wpml_language

Just added a left join in my SQL query:

```<code>SELECT O.ID as id_order, O.post_date_gmt as date, M.meta_value as email, M2.meta_value as firstname, M3.meta_value as lastname, M4.meta_value as iso_code
    FROM ".$prefix."posts O
    LEFT JOIN ".$prefix."postmeta M ON M.post_id = O.ID AND M.meta_key = '_billing_email'
    LEFT JOIN ".$prefix."postmeta M2 ON M2.post_id = O.ID AND M2.meta_key = '_billing_first_name'
    LEFT JOIN ".$prefix."postmeta M3 ON M3.post_id = O.ID AND M3.meta_key = '_billing_last_name'
    LEFT JOIN ".$prefix."postmeta M4 ON M3.post_id = O.ID AND M4.meta_key = 'wpml_language'
    WHERE O.post_type = 'shop_order' AND O.post_status = 'wc-completed'
</code>```

Title: Get Woocommerce customer order language

Body:
Finally solved, both solutions are OK.

With WPML plugin you can get the value in the table postmeta with the meta_key = wpml_language

Just added a left join in my SQL query:

SELECT O.ID as id_order, O.post_date_gmt as date, M.meta_value as email, M2.meta_value as firstname, M3.meta_value as lastname, M4.meta_value as iso_code
    FROM ".$prefix."posts O
    LEFT JOIN ".$prefix."postmeta M ON M.post_id = O.ID AND M.meta_key = '_billing_email'
    LEFT JOIN ".$prefix."postmeta M2 ON M2.post_id = O.ID AND M2.meta_key = '_billing_first_name'
    LEFT JOIN ".$prefix."postmeta M3 ON M3.post_id = O.ID AND M3.meta_key = '_billing_last_name'
    LEFT JOIN ".$prefix."postmeta M4 ON M3.post_id = O.ID AND M4.meta_key = 'wpml_language'
    WHERE O.post_type = 'shop_order' AND O.post_status = 'wc-completed'


问:
dynamically change the json property name and serialize
i want to change the json property name dynamically and serialize the object.

here is my json for two different entities

For customer

```<code>{
  "userName": "66666",
  "password": "test1234",
  "customersList": [
    {
      "address": "Test Stree2",
      "customerNumber": "US01-000281",
      "city": ""

    }
  ]
}
</code>```

For contact

```<code>{
  "userName": "66666",
  "password": "test1234",
  "contactList": [
    {
      "address": "Test stree1",
      "contactNumber": "US01-000281",
      "city": ""

    }
  ]
}
</code>```

and the model that is holding this data is as follows

```<code>public class URequest<T>
    {

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<T> requestList { get; set; }

    }
</code>```

in above code requestList could contain list of contacts or customer but while sending i want to change the requestList json property name to respective entity name i.e. for customer it will be customerList and for contact it will be contactList after serializing.

答:
using the ContentResolver i have solve the issue

here is the code

```<code>public class UserRequestResolver : DefaultContractResolver
{
    private string propertyName;

    public UserRequestResolver()
    {
    }
    public UserRequestResolver(string name)
    {
        propertyName = name;
    }
    public new static readonly UserRequestResolver Instance = new UserRequestResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (property.PropertyName == "requestList")
        {
            property.PropertyName = propertyName;
        }
        return property;
     }
}
</code>```

once can pass specific property name in the constructor.

```<code>JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new UserRequestResolver("contactList");
</code>```

Body:
i want to change the json property name dynamically and serialize the object.

here is my json for two different entities

For customer

{
  "userName": "66666",
  "password": "test1234",
  "customersList": [
    {
      "address": "Test Stree2",
      "customerNumber": "US01-000281",
      "city": ""

    }
  ]
}

For contact

{
  "userName": "66666",
  "password": "test1234",
  "contactList": [
    {
      "address": "Test stree1",
      "contactNumber": "US01-000281",
      "city": ""

    }
  ]
}

and the model that is holding this data is as follows

public class URequest<T>
    {

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string userName { get; set; }

        [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public string password { get; set; }

       [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
        public IList<T> requestList { get; set; }

    }

in above code requestList could contain list of contacts or customer but while sending i want to change the requestList json property name to respective entity name i.e. for customer it will be customerList and for contact it will be contactList after serializing.

Body:
using the ContentResolver i have solve the issue

here is the code

public class UserRequestResolver : DefaultContractResolver
{
    private string propertyName;

    public UserRequestResolver()
    {
    }
    public UserRequestResolver(string name)
    {
        propertyName = name;
    }
    public new static readonly UserRequestResolver Instance = new UserRequestResolver();

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        if (property.PropertyName == "requestList")
        {
            property.PropertyName = propertyName;
        }
        return property;
     }
}

once can pass specific property name in the constructor.

JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ContractResolver = new UserRequestResolver("contactList");