问:
Need help my android app (http request) is working in an emulator but not on a physical galaxy S5
The app works in android studio with the emulator and an xampp server on the same machine but when I try running it on the Galaxy S5 connected via usb and using my data package on the sim I get the following error in the logcat: (HTTPLog)-Static: isSBSettingEnabled false, from what I can tell there is some kind of connection error and the array returned is a null set, this causes the app to crash. I tried the following connection urls and none worked: http://190.xxx.xx.xx/abcd/search.php, 190.xxx.xx.xx/abcd/search.php, http://190.xxx.xx.xx:80/abcd/search.php, 190.xxx.xx.xx:80/abcd/search.php</p>

```<code>       protected String doInBackground(String... params) {
        String type = params[0];

        // Note Android reserved loopback address is 10.0.2.2
        // Testing server
        //String login_url = "http://10.0.2.2/ttsrp/search.php";
        // Live server
        String login_url = "http://190.xxx.xx.xx/abcd/search.php";
        Log.i("URL set:",login_url);

        if (type.equals("search")){
            try {
                Log.i("Branch :","Search String Accepted.");
                String search_key = params[1];
                //String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("search_key", "UTF-8")+"="+
                        URLEncoder.encode(search_key, "UTF-8");
                bufferedWriter.write(post_data);

                //Buffer Writer cleanup
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bufferedReader.readLine())!= null)
                bufferedReader.close();{
                    result += line;
                }
                inputStream.close();
                httpURLConnection.disconnect();
                Log.i("Information : ","Close Connection");
                return result;

            } catch (MalformedURLException e) {
                Log.e("ERROR: ","Wrong or malformed URL.");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        //alertDialog.setMessage(result);
        //alertDialog.show();

        ListView listView=(ListView)findViewById(R.id.fp_list);

        if (result==null){
            Log.e("ERROR : ", "Null Dataset returned.");
        }else{
            Log.d("Result:", result);
        }

        JSONArray jarr = null;
        JSONObject jobj = null;
        try {
            jarr = new JSONArray(result);

            for (int i=0; i<(jarr.length()); i++){
                jobj = jarr.getJSONObject(i);

                int id = jobj.getInt("id");
                String off = jobj.getString("off");
                String act = jobj.getString("act");
                String ena = jobj.getString("ena");
                int fine = jobj.getInt("fine");
                int dem = jobj.getInt("dem");

                String lab = "acb " + act + " " + ena + " " +"123 " + dem;
                arrayList.add(lab);
                arrayList.add(off);
            }
            //Create Adapter
            ArrayAdapter arrayAdapter=new ArrayAdapter(FixedPenalty.this,android.R.layout.simple_list_item_1, arrayList);
            //assign adapter to listview
            listView.setAdapter(arrayAdapter);
         } catch (JSONException e) {
            e.printStackTrace();
        }
</code>```

答:
I found the issue, a low battery in a wireless mouse caused this code to accidentally move, closing the bufferreader prematurely.

```<code> while((line = bufferedReader.readLine())!= null)
            bufferedReader.close();{
                result += line;
            }
</code>```

should be

```<code>while((line = bufferedReader.readLine())!= null){
                    result += line;
                }
bufferedReader.close();
</code>```

Still dont know why it still worked in the emulator though.

Body:
The app works in android studio with the emulator and an xampp server on the same machine but when I try running it on the Galaxy S5 connected via usb and using my data package on the sim I get the following error in the logcat: (HTTPLog)-Static: isSBSettingEnabled false, from what I can tell there is some kind of connection error and the array returned is a null set, this causes the app to crash. I tried the following connection urls and none worked: http://190.xxx.xx.xx/abcd/search.php, 190.xxx.xx.xx/abcd/search.php, http://190.xxx.xx.xx:80/abcd/search.php, 190.xxx.xx.xx:80/abcd/search.php

       protected String doInBackground(String... params) {
        String type = params[0];

        // Note Android reserved loopback address is 10.0.2.2
        // Testing server
        //String login_url = "http://10.0.2.2/ttsrp/search.php";
        // Live server
        String login_url = "http://190.xxx.xx.xx/abcd/search.php";
        Log.i("URL set:",login_url);

        if (type.equals("search")){
            try {
                Log.i("Branch :","Search String Accepted.");
                String search_key = params[1];
                //String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("search_key", "UTF-8")+"="+
                        URLEncoder.encode(search_key, "UTF-8");
                bufferedWriter.write(post_data);

                //Buffer Writer cleanup
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                String result = "";
                String line = "";
                while((line = bufferedReader.readLine())!= null)
                bufferedReader.close();{
                    result += line;
                }
                inputStream.close();
                httpURLConnection.disconnect();
                Log.i("Information : ","Close Connection");
                return result;

            } catch (MalformedURLException e) {
                Log.e("ERROR: ","Wrong or malformed URL.");
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        //alertDialog.setMessage(result);
        //alertDialog.show();

        ListView listView=(ListView)findViewById(R.id.fp_list);

        if (result==null){
            Log.e("ERROR : ", "Null Dataset returned.");
        }else{
            Log.d("Result:", result);
        }

        JSONArray jarr = null;
        JSONObject jobj = null;
        try {
            jarr = new JSONArray(result);

            for (int i=0; i<(jarr.length()); i++){
                jobj = jarr.getJSONObject(i);

                int id = jobj.getInt("id");
                String off = jobj.getString("off");
                String act = jobj.getString("act");
                String ena = jobj.getString("ena");
                int fine = jobj.getInt("fine");
                int dem = jobj.getInt("dem");

                String lab = "acb " + act + " " + ena + " " +"123 " + dem;
                arrayList.add(lab);
                arrayList.add(off);
            }
            //Create Adapter
            ArrayAdapter arrayAdapter=new ArrayAdapter(FixedPenalty.this,android.R.layout.simple_list_item_1, arrayList);
            //assign adapter to listview
            listView.setAdapter(arrayAdapter);
         } catch (JSONException e) {
            e.printStackTrace();
        }

Body:
I found the issue, a low battery in a wireless mouse caused this code to accidentally move, closing the bufferreader prematurely.

 while((line = bufferedReader.readLine())!= null)
            bufferedReader.close();{
                result += line;
            }

should be

while((line = bufferedReader.readLine())!= null){
                    result += line;
                }
bufferedReader.close();

Still dont know why it still worked in the emulator though.


来源: stackexchange

问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

ContentLicense: CC BY-SA 4.0

Body:
for i,x in enumerate(a[:-1]):
    output.append((a[i+1][1]-a[i][1],a[i+1][2]-a[i][2]))


问:
How can I set badge count of iOS app from its today extension?
I'm looking for a way to update the badge count of iOS app icon from its iOS8 today extension. Today extension has a button and by touching that button, user can increase or decrease badge count of iOS app. Can anyone help me with this?

PS: I need to update the badge count without reopening the app even when the app is terminated.

答: As you already have created group, you can keep a file in the group folder and add a filewatcher in extension, update the file from app, and filewatcher will catch the change, and your work is done.</p>


问:
Will structure like std::list<std::pair<string, string>> be copied when returned?
I have a function that is expected to extract a list of key values from a given string, where each key/value pair is represented by a std::pair, the function has the signature like below:

```<code>std::list<std::pair<string, string>> extract(const string &s)
</code>```

If my implementation looks like:

```<code>list<pair<...>> kv_pairs;
for (....) {
  kv_pairs.push_back(make_pair(k, v));
}
return kv_pairs;
</code>```

1) I don't want any copy to happen and I wonder if RVO/NRVO will be applied for the pairs inside the list and the list holding them.

2) If copy will happen in this case, what could be an alternative data structure implementing this without copying? I can think of a solution using unique_ptr<unorder_map<>>, but in my case, I only need to support iteration of the pairs in the list and don't need to support looking up value by their keys so I would like to avoid unnecessary hash calculation during insertion.

3) I know RVO/NRVO is compiler dependent behavior, is there any approach I can verify if these behavior happens or not easily?

Will RVO happen when returning std::pair?

What are copy elision and return value optimization?

答:
If you are compiling targeting at least C++11, there are really only two possible outcomes:

Without RVO, the returned temporary will be used to move-construct the object to which the return value is assigned.  This is basically just shuffling a few pointers around, and will take exactly the same amount of time (which is negligible) no matter how many items are in the list.

With RVO, the move-construction is elided.

Both outcomes are very fast and will not involve copying of the list structure.

Body:
I have a function that is expected to extract a list of key values from a given string, where each key/value pair is represented by a std::pair, the function has the signature like below:

std::list<std::pair<string, string>> extract(const string &s)

If my implementation looks like:

list<pair<...>> kv_pairs;
for (....) {
  kv_pairs.push_back(make_pair(k, v));
}
return kv_pairs;

1) I don't want any copy to happen and I wonder if RVO/NRVO will be applied for the pairs inside the list and the list holding them.

2) If copy will happen in this case, what could be an alternative data structure implementing this without copying? I can think of a solution using unique_ptr<unorder_map<>>, but in my case, I only need to support iteration of the pairs in the list and don't need to support looking up value by their keys so I would like to avoid unnecessary hash calculation during insertion.

3) I know RVO/NRVO is compiler dependent behavior, is there any approach I can verify if these behavior happens or not easily?

Will RVO happen when returning std::pair?

What are copy elision and return value optimization?


问:
3D object detection for custom objects; dataset creation
How can I create a custom dataset for 3D object detection, I want to use the "Stanford3dDataset" or "Scannet" as baseline and add my object of interest in the dataset. I have the PCD files captured from the 3D camera [Realsense] and for 3D object detection, I am using the Pointnet model.  </p>

<p>I see the dataset has the text file as input instead of PCD or PLY format, how do I convert PLY/PCD files to text files.       </p>

答: You can refer to this repository on github for reading a ply file https://github.com/HuguesTHOMAS/KPConv/blob/master/utils/ply.py  after reading the contents from the ply file you can simply use numpy.savetxt() to convert the ply file to text file</p>

Body:
How can I create a custom dataset for 3D object detection, I want to use the "Stanford3dDataset" or "Scannet" as baseline and add my object of interest in the dataset. I have the PCD files captured from the 3D camera [Realsense] and for 3D object detection, I am using the Pointnet model.

I see the dataset has the text file as input instead of PCD or PLY format, how do I convert PLY/PCD files to text files.


问:
Is there a better way of doing class_eval() to extract class variables, in Ruby?
I personally don't have anything against this, apart from the fact that's is long, but what really bothers me is the word eval.

I do a lot of stuff in JavaScript and I run from anything resembling eval like it's the devil, I also don't fancy the fact that the parameter is a string (again, probably because it's eval).

I know I could write my own method to fix the method-name-length problem, my 'method name issue' and the parameter-being-a-string thingy, but what I really want to know is: Is there a better, shorter, fancier, yet native, way of doing class_eval to extract class variables?

Side note: I know about the existence of class_variable_get() and class_variables(), but they don't really look appealing to me; horribly long, aren't they?

EDIT: Updated the question to be more specific.

Thanks!

答:
Use class_variable_get, but only if you must

class_variable_get is the better way, other than the fact that it is not "appealing" to you. If you are reaching inside a class and breaking encapsulation, perhaps it is appropriate to have this extra barrier to indicate that you're doing something wrong.

Create accessor methods for the variables you want to access

If these are your classes, and accessing the variables doesn't break encapsulation, then you should create class accessor methods for them to make it easier and prettier:

```<code>class Foo
  def self.bar
    @@bar
  end
end
p Foo.bar
</code>```

If this is your class, however, are you sure that you need class variables? If you don't understand the implications (see below), you may actually be wanting instance variables of the class itself:

```<code>class Foo
  class << self
    attr_accessor :bar
  end
end

Foo.bar = 42
p Foo.bar
</code>```

The behavior of class variables

Class variables appear to newcomers like the right way to store information at a class level, mostly because of the name. They are also convenient because you can use the same syntax to read and write them whether you are in a method of the class or an instance method. However, class variables are shared between a class and all its subclasses.

For example, consider the following code:

```<code>class Rectangle
  def self.instances
    @@instances ||= []
  end
  def initialize
    (@@instances ||= []) << self
  end
end

class Square < Rectangle
  def initialize
    super
  end
end

2.times{ Rectangle.new }
p Rectangle.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>]

Square.new
p Square.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>, #<Square:0x25c76d0>]
</code>```

Ack! Rectangles are not squares! Here's a better way to do the same thing:

```<code>class Rectangle
  def self.instances
    @instances ||= []
  end
  def initialize
    self.class.instances << self
  end
end

class Square < Rectangle
  def initialize
    super
  end
end

2.times{ Rectangle.new }
p Rectangle.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>]

2.times{ Square.new }
p Square.instances
#=> [#<Square:0x25c76d0>, #<Square:0x25c76b8>]
</code>```

By creating an instance variable and accesor methods on the class itself—which happens to be an instance of the Class class, similar to MyClass = Class.new—all instances of the class (and outsiders) have a common, clean location to read/write information that is not shared between other classes.

Note that explicitly tracking every instance created will prevent garbage collection on 'unused' instances. Use code like the above carefully.

Using class_eval in a cleaner manner

Finally, if you're going to use class_eval, note that it also has a block form that doesn't have to parse and lex the string to evaluate it:

```<code>Foo.class_eval('@@bar') # ugh
Foo.class_eval{ @@bar } # yum
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Use class_variable_get, but only if you must

class_variable_get is the better way, other than the fact that it is not "appealing" to you. If you are reaching inside a class and breaking encapsulation, perhaps it is appropriate to have this extra barrier to indicate that you're doing something wrong.

Create accessor methods for the variables you want to access

If these are your classes, and accessing the variables doesn't break encapsulation, then you should create class accessor methods for them to make it easier and prettier:

class Foo
  def self.bar
    @@bar
  end
end
p Foo.bar

If this is your class, however, are you sure that you need class variables? If you don't understand the implications (see below), you may actually be wanting instance variables of the class itself:

class Foo
  class << self
    attr_accessor :bar
  end
end

Foo.bar = 42
p Foo.bar

The behavior of class variables

Class variables appear to newcomers like the right way to store information at a class level, mostly because of the name. They are also convenient because you can use the same syntax to read and write them whether you are in a method of the class or an instance method. However, class variables are shared between a class and all its subclasses.

For example, consider the following code:

class Rectangle
  def self.instances
    @@instances ||= []
  end
  def initialize
    (@@instances ||= []) << self
  end
end

class Square < Rectangle
  def initialize
    super
  end
end

2.times{ Rectangle.new }
p Rectangle.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>]

Square.new
p Square.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>, #<Square:0x25c76d0>]

Ack! Rectangles are not squares! Here's a better way to do the same thing:

class Rectangle
  def self.instances
    @instances ||= []
  end
  def initialize
    self.class.instances << self
  end
end

class Square < Rectangle
  def initialize
    super
  end
end

2.times{ Rectangle.new }
p Rectangle.instances
#=> [#<Rectangle:0x25c7808>, #<Rectangle:0x25c77d8>]

2.times{ Square.new }
p Square.instances
#=> [#<Square:0x25c76d0>, #<Square:0x25c76b8>]

By creating an instance variable and accesor methods on the class itself—which happens to be an instance of the Class class, similar to MyClass = Class.new—all instances of the class (and outsiders) have a common, clean location to read/write information that is not shared between other classes.

Note that explicitly tracking every instance created will prevent garbage collection on 'unused' instances. Use code like the above carefully.

Using class_eval in a cleaner manner

Finally, if you're going to use class_eval, note that it also has a block form that doesn't have to parse and lex the string to evaluate it:

Foo.class_eval('@@bar') # ugh
Foo.class_eval{ @@bar } # yum


问:
Error while i am trying to deploy the function
I am trying to deploy my code but I am getting error

My index code is:

```<code>'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification =
functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;

console.log('We have a notification to send to :' , receiver_user_id);

if (!data.after.val())
{
    console.log('A notification has been deleted :' , notification_id);
    return null;
}

const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

return DeviceToken.then(result =>
{
    const token_id = result.val();

    const payload =
    {
        notification:
        {
            title: "New Chat Request",
            body: `you have a new Chat Request, Please Check.`,
            icon: "default"
        }
    };

    return admin.messaging().sendToDevice(token_id, payload)
    .then(response =>
        {
            console.log('This was a notification feature.');
        });
});
});
</code>```

Error shown is this:

```<code>npm ERR! code ELIFECYCLE  npm ERR! errno 1

npm ERR! functions@ lint: `eslint .`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the functions@ lint script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-06-02T11_48_47_185Z-debug.log
events.js:287
      throw er; // Unhandled 'error' event
      ^
}

Error: functions predeploy error: Command terminated with non-zero exit code1

The error shown in C:\Users\Admin\AppData\Roaming\npm-cache_logs\2020-06-02T11_48_47_185Z-debug.log :

 error code ELIFECYCLE

 error errno 1

 error functions@ lint: `eslint .`

 error Exit status 1

 error Failed at the functions@ lint script.

 error This is probably not a problem with npm. There is likely additional logging output above.

 verbose exit [ 1, true ]
</code>```

答:
You need the catch the error here:

then(response =>
        {
            console.log('This was a notification feature.');
        }).catch(error => handle error here)

```

Body:
I am trying to deploy my code but I am getting error

My index code is:

'use strict'

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.sendNotification =
functions.database.ref('/Notifications/{receiver_user_id}/{notification_id}')
.onWrite((data, context) =>
{
const receiver_user_id = context.params.receiver_user_id;
const notification_id = context.params.notification_id;

console.log('We have a notification to send to :' , receiver_user_id);

if (!data.after.val())
{
    console.log('A notification has been deleted :' , notification_id);
    return null;
}

const DeviceToken = admin.database().ref(`/Users/${receiver_user_id}/device_token`).once('value');

return DeviceToken.then(result =>
{
    const token_id = result.val();

    const payload =
    {
        notification:
        {
            title: "New Chat Request",
            body: `you have a new Chat Request, Please Check.`,
            icon: "default"
        }
    };

    return admin.messaging().sendToDevice(token_id, payload)
    .then(response =>
        {
            console.log('This was a notification feature.');
        });
});
});

Error shown is this:

npm ERR! code ELIFECYCLE  npm ERR! errno 1

npm ERR! functions@ lint: `eslint .`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the functions@ lint script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     C:\Users\Admin\AppData\Roaming\npm-cache\_logs\2020-06-02T11_48_47_185Z-debug.log
events.js:287
      throw er; // Unhandled 'error' event
      ^
}

Error: functions predeploy error: Command terminated with non-zero exit code1

The error shown in C:\Users\Admin\AppData\Roaming\npm-cache_logs\2020-06-02T11_48_47_185Z-debug.log :

 error code ELIFECYCLE

 error errno 1

 error functions@ lint: `eslint .`

 error Exit status 1

 error Failed at the functions@ lint script.

 error This is probably not a problem with npm. There is likely additional logging output above.

 verbose exit [ 1, true ]


问:
Multiple submit buttons php different actions
I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:

```<code><form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">
</code>```

and then I use:

```<code>if (!isset($_POST['submit'])){
Do actions, display calculations}
</code>```

Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?

答:
Another approach is that You can create and Use some session variable to achieve it easily.

E.g. $_SESSION['validate'].

HTML and PHP Code for buttons

```<code><button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>
</code>```

jquery and ajax Script

```<code><script>
    $(document).ready(function(){

        $("#form").on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'handler-file.php',
                data:  new FormData(this),
                dataType: "json",
                enctype: 'multipart/form-data',
                contentType: false,
                cache: false,
                processData:false,
                error:function(error){
                    //your required code or alert
                    alert(error.responseText);
                },
                success: function(response){
                    if(response.status=='1')
                    {
                        //your required code or alert
                        $('#first_submit').hide();
                        $('#second_submit').show();
                    }
                    else if(response.status=='2')
                    {
                        //your required code or alert
                        $('#first_submit').show();
                        $('#second_submit').hide();
                    }
                    else
                    {
                        //your required code or alert
                    }
                }
            });
        });

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

Handler PHP File

```<code><?php
session_start();

$result['status']='0';
$result['error']='';

if(!isset($_SESSION['validate']))
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-02 file missing!]';
    }
    else
    {
        //your other code
        $_SESSION['validate'] = true;
        $result['status']='1';
    }
}
else if($_SESSION['validate']==true)
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-03 Validation file missing!]';
    }
    else
    {
        //your other code
        unset($_SESSION['validate']);
        $result['status']='2';
    }
}
else
{
    $result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);
</code>```

?>

It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.

Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.

Hope it helps!

Body:
I have a website started where I want to have 2 separate submit buttons, one of which will take data entered and do some calculations to it to display on the same screen. I've got this successfully working with:

<form id="form1" name="form1" method="post" onsubmit="" onreset="" action="programname.php">
<input type="submit" name="calc" value="Find Angle">

and then I use:

if (!isset($_POST['submit'])){
Do actions, display calculations}

Now I want a second submit button that still grabs the data they entered but then goes to a different address. Is there an elegant way to do this?

Body:
Another approach is that You can create and Use some session variable to achieve it easily.

E.g. $_SESSION['validate'].

HTML and PHP Code for buttons

<button type="submit" id="first_submit" style="<?php echo isset($_SESSION['validate'])?'display:none':'';?>">first submit</button>
<button type="submit" id="second_submit" style="<?php echo isset($_SESSION['validate'])?'':'display:none';?>">second submit</button>

jquery and ajax Script

<script>
    $(document).ready(function(){

        $("#form").on('submit', function(e){
            e.preventDefault();
            $.ajax({
                type: 'POST',
                url: 'handler-file.php',
                data:  new FormData(this),
                dataType: "json",
                enctype: 'multipart/form-data',
                contentType: false,
                cache: false,
                processData:false,
                error:function(error){
                    //your required code or alert
                    alert(error.responseText);
                },
                success: function(response){
                    if(response.status=='1')
                    {
                        //your required code or alert
                        $('#first_submit').hide();
                        $('#second_submit').show();
                    }
                    else if(response.status=='2')
                    {
                        //your required code or alert
                        $('#first_submit').show();
                        $('#second_submit').hide();
                    }
                    else
                    {
                        //your required code or alert
                    }
                }
            });
        });

    });
    </script>

Handler PHP File

<?php
session_start();

$result['status']='0';
$result['error']='';

if(!isset($_SESSION['validate']))
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-02 file missing!]';
    }
    else
    {
        //your other code
        $_SESSION['validate'] = true;
        $result['status']='1';
    }
}
else if($_SESSION['validate']==true)
{
    if(!isset($_FILES['file']))
    {
        $result['error'].='[Er-03 Validation file missing!]';
    }
    else
    {
        //your other code
        unset($_SESSION['validate']);
        $result['status']='2';
    }
}
else
{
    $result['error'].='[Er-01 Invalid source!]';
}
echo json_encode($result);

?>

It may not be the optimal or efficient solution. My level of experience is not too much, so I came up with this solution what served my purpose best after all the solutions available but with their limitations. This was not anywhere so thought to write it here.

Note: You may notice it includes some other parts like response, success and error handling between presentation, script and backend file.

Hope it helps!


问:
Using async-await not returning the values
I use the following code which works! I was able to fetch the data in the spread (then) , http200

```<code>Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });
</code>```

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

```<code>const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}
</code>```

Now I’ve created function to call it and get the tokens

```<code>async function main() {

    let val = await FetchData();
    console.log(val)

}
</code>```

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?

答:
You need to change the position of your return statement:

Updated code with changes:

```<code>const FetchData = (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
// Return the promise here

return Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];

      // This return is for getting the data once the promise is resolved either with then or await
      return {
         run: aToken ,
         app: bToken
      };
    }).catch(function(error: any) {
       console.log("Error: " + error);
       return error;
    });

)}
</code>```

As you are returning the value before the promise is resolved so you are not getting any data.
You need to return promise and inside then you need to return the required data, to get once the promise is resolved in invoking function.

Body:
I use the following code which works! I was able to fetch the data in the spread (then) , http200

Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      const aToken = responses[0];
      const bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

Now I want to wrap it with async function which return two response (responses[0], responses[1] )

I’ve created this function

const FetchData = async (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];
    }).catch(function(error: any) {
      console.log("Error: " + error);
    });

// add this return
return {
    run: aToken ,
    app: bToken
};

)}

Now I’ve created function to call it and get the tokens

async function main() {

    let val = await FetchData();
    console.log(val)

}

The problem is that I got empty value in the val property, while put a breakpoint inside main function
I see that I got into the console, before I actually get the values from the ).then(axios.spread(( ,
Any idea how to adopt the code to return the value from the spread operator and then call to the console?

Body:
You need to change the position of your return statement:

Updated code with changes:

const FetchData = (): Promise<{ run: string; app: string }> => {

let aToken:string;
let bToken:string;
// Return the promise here

return Promise.all([
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'run:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    }),
    axios({
      method: 'post',
      url: 'https://oauth2.-arch.mand.com/oauth2/token',
      data: qs.stringify({
        'grant_type': 'client_credentials'
      }, {
        'scope': 'exe:crud'
      }),
      headers: {
        'Accept': 'application/json',
        'Authorization': 'Basic NTgwNjgtMDhhZTczOGNl',
        'Content-Type': 'application/x-www-form-urlencoded',
      }
    })
  ]).then(axios.spread((...responses: AxiosResponse[]) => {
      aToken = responses[0];
      bToken = responses[1];

      // This return is for getting the data once the promise is resolved either with then or await
      return {
         run: aToken ,
         app: bToken
      };
    }).catch(function(error: any) {
       console.log("Error: " + error);
       return error;
    });

)}

As you are returning the value before the promise is resolved so you are not getting any data.
You need to return promise and inside then you need to return the required data, to get once the promise is resolved in invoking function.


问:
C++ Program works when using int with cin but not a string
I wrote this simple program to more or less "warm up" in using C++ and when asking for a string input, the program stops working as intended.

Here it is asking for an int, which works as intended:

```<code>#include <iostream>

using namespace std;

int main() {
    cout << "enter something\n";
    int usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
}
</code>```

Output is as follows:

```<code>Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
enter something
12.5
12 is a number.
PS C:\Users\fortm\Documents\CPPPrac\MainPrac>
</code>```

However, when changing code to use a string instead, the program skips over "enter something" and the cin lines and jumps to a new line (for commands and etc.) instead.

Non-working code:

```<code>#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "enter something\n";
    string usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
}
</code>```

Output log:

```<code>Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> 12
12
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> hu
hu : The term 'hu' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ hu
+ ~~
    + CategoryInfo          : ObjectNotFound: (hu:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\fortm\Documents\CPPPrac\MainPrac>

</code>```

I've tried compiling with both MinGW and CygWin to no avail and am running the program with coderunner (run in terminal is checked) in Visual Studio code.

答:
It worked fine when i did it..

Code:

```<code>#include <iostream>
#include<string>
using namespace std;

int main() {
    cout << "enter something\n";
    string usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
    return 0;
}
</code>```

Output:

```<code>enter something
25
25 is a number.
</code>```

Body:
I wrote this simple program to more or less "warm up" in using C++ and when asking for a string input, the program stops working as intended.

Here it is asking for an int, which works as intended:

#include <iostream>

using namespace std;

int main() {
    cout << "enter something\n";
    int usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
}

Output is as follows:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
enter something
12.5
12 is a number.
PS C:\Users\fortm\Documents\CPPPrac\MainPrac>

However, when changing code to use a string instead, the program skips over "enter something" and the cin lines and jumps to a new line (for commands and etc.) instead.

Non-working code:

#include <iostream>
#include <string>

using namespace std;

int main() {
    cout << "enter something\n";
    string usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
}

Output log:

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Try the new cross-platform PowerShell https://aka.ms/pscore6

PS C:\Users\fortm\Documents\CPPPrac> cd "c:\Users\fortm\Documents\CPPPrac\MainPrac\" ; if ($?) { g++ Main.cpp -o Main } ; if ($?) { .\Main }
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> 12
12
PS C:\Users\fortm\Documents\CPPPrac\MainPrac> hu
hu : The term 'hu' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ hu
+ ~~
    + CategoryInfo          : ObjectNotFound: (hu:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

PS C:\Users\fortm\Documents\CPPPrac\MainPrac>

I've tried compiling with both MinGW and CygWin to no avail and am running the program with coderunner (run in terminal is checked) in Visual Studio code.

Body:
It worked fine when i did it..

Code:

#include <iostream>
#include<string>
using namespace std;

int main() {
    cout << "enter something\n";
    string usertypestuff;
    cin >> usertypestuff;
    cout << usertypestuff << " is a number.";
    return 0;
}

Output:

enter something
25
25 is a number.


答:
You can use std::to_string() function to convert usertypestuff to string,

string str = to_string(usertypestuff);
```

Title: C++ Program works when using int with cin but not a string


问:
HAXM device is not found in Windows 7
I am trying to develop a mobile application using Android Studio but I am always getting a pop message with below message.

Intel HAXM is required to run this AVD.
HAXM device is not found.

Enable VT-x in your BIOS security settings, ensure that HAXM is installed properly. Try disabling 3rd party security software if the problem still occurs.

Things I have tried:

Installed the HAXM installer on SDK Manager

Went to Extras -> Intel -> Hardware_Accelerated_Execution_Manager and run the file named "intelhaxm-android.exe". But getting error message as "Failed to configure driver: unknown error. Failed to open driver."

I am using:
Android Studio 3.5 on Windows 7.

Could you kindly let me know that Windows 7 supports Android application development using Android Studio?

Could you kindly let me how this issue can be addressed?

答:
For me this problem was solved by disabling Hyper-V on Windows 10.

The below are the steps to disable Hyper-V:

In "Control Panel", select "Programs and Features".

Select "Turn Windows features on or off".

Expand "Hyper-V", expand "Hyper-V Platform", and then clear the "Hyper-V Hypervisor" check box.

Title: HAXM device is not found in Windows 7


问:
How do I correctly return values from a web service?
I'm not familiar with the web services. I created a Email Service using web service.

My questions is:

How to make a Email Sending with have a MsgBox "Sent" and " sent Failed"?

答:
try to add a

return "Sent"

on  your code..


问:
Find top parent in hierarchy
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

```<code>CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End
</code>```

This is the result I want:

```<code>Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310
</code>```

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.

答:
This problem is similar to traversing a tree using sql language. I think you might need to use stored procedures to solve this problem.
First, query all records. When traversing a record, the top parent is found through the while loop.
However, illegal data needs to be considered. For example, ('1', '2'), ('2', '3'), and ('3', '1') cause the while loop to become an infinite loop.</p>

Title: Find top parent in hierarchy

Body:
I have a SQL table with different project codes. A project can consist of multiple levels (sub-projects). I want to find the top level (top parent) for each of the project codes using SQL coding.

My table looks like this:

CREATE TABLE #Temp
(
    Child nvarchar(100),
    Parent nvarchar(100)

)

insert into #Temp (Child,Parent)
values
('17210',Null),
('17210-100','17210'),
('17210-100-100','17210-100'),
('1310',Null),
('1310-100','1310'),
('1310-100-100','1310-100')
;

select * from #Temp

If(OBJECT_ID('tempdb..#temp') Is Not Null)
Begin
    Drop Table #Temp
End

This is the result I want:

Child           Parent      TopParent
17210           NULL        17210
17210-100       17210       17210
17210-100-100   17210-100   17210
1310            NULL        1310
1310-100        1310        1310
1310-100-100    1310-100    1310

How do I find the top parent for each project number (child)? I have an idea that using recursive CTE's might be the solution, but I am not sure if this is the right approach.

Any help is much appreciated.


问:
How to disable click events of mat-list-item enable click of only maticon
Hi I am working on angular 5.I want to disable click event of mat-list-item want to enable only click action of mat-icon.

```<code>  <mat-nav-list>
            <mat-list-item
              *ngFor="
                let item of (speciality_list | listFilter: { name: searchText })
              "
              [class.disabled]="!item.status"
              [ngClass]="item.id == specialityActiveId ? 'active' : ''"
              (click)="onRowClick(item, 'speciality')"
            >
              <div matLine>
                <div fxLayout="row">
                  <div fxFlex="80">{{ item.name }}</div>
                  <div fxFlex="12" >
                    <button class="cursor-default"
                      mat-icon-button
                      (click)="edit($event, 'speciality', item)"
                    >
                      <mat-icon class="mat-17">edit</mat-icon>
                    </button>
                  </div>

                    <div fxFlex="8">
                      <button mat-icon-button mat-icon-button>
                        <mat-icon class="mat-17">arrow_forward_ios</mat-icon>
                      </button>
                    </div>

                </div>
              </div>
            </mat-list-item>
          </mat-nav-list>
</code>```

Thank you,

答:
You can stop immediate propagation by doing this:

edit(event){
    event.preventDefault();
    // EDIT: Looks like you also have to include Event#stopImmediatePropagation as well
    event.stopImmediatePropagation();
}

I referred to the following link for my solution.
mat-nav-list with secondary buttons

Body:
Hi I am working on angular 5.I want to disable click event of mat-list-item want to enable only click action of mat-icon.

  <mat-nav-list>
            <mat-list-item
              *ngFor="
                let item of (speciality_list | listFilter: { name: searchText })
              "
              [class.disabled]="!item.status"
              [ngClass]="item.id == specialityActiveId ? 'active' : ''"
              (click)="onRowClick(item, 'speciality')"
            >

{{ item.name }}

                    <button class="cursor-default"
                      mat-icon-button
                      (click)="edit($event, 'speciality', item)"
                    >
                      <mat-icon class="mat-17">edit</mat-icon>
                    </button>

                      <button mat-icon-button mat-icon-button>
                        <mat-icon class="mat-17">arrow_forward_ios</mat-icon>
                      </button>

            </mat-list-item>
          </mat-nav-list>

Thank you,


问:
How to resolve dependency in asp.net mvc when can only access Interfaces and don't have access to implementation classes of them
I have injected(AccountAccessInterface) interface in the constructor when I run API I can't resolve its dependency as this interface I am getting from .dll and don't have access to its implementation. So I need some way so that I can resolve dependency   inside controller in any way Please as without having implementation(hidden implementation) class of interface I face error in APIs of dependency resolver

```<code>public class AdminController : ApiController
{
    private readonly AccountAccessInterface _accountAccessInterface;

    public AdminController(AccountAccessInterface accountAccessInterface)
    {
        _accountAccessInterface = accountAccessInterface;
    }

    // to get account if by user id
   [Route("api/admin/ProcessTrsanctionAndSave")]
   [HttpGet]
    public void ProcessTrsanctionAndSave()
    {

        BankDB.BankDB bankDB = new BankDB.BankDB();
        bankDB.ProcessAllTransactions();
        bankDB.SaveToDisk();
    }
}
</code>```

答:
I have solved the problem by doing the Following work.
When we don't have access to implementation class it means interfaces are returning from any class as a method.so if we do

TransactionAccessInterface is interface here and Models.Globoclass.myBank.GetTransactionInterface() is the base class from interface returning as method.

```<code> public object SelectTransaction(uint TransactionID)
    {
        TransactionAccessInterface myint = Models.Globoclass.myBank.GetTransactionInterface();
        myint.SelectTransaction(TransactionID);
        Transaction_Details transaction_Details = new Transaction_Details();
        transaction_Details.amount = myint.GetAmount();
        transaction_Details.recvrAccount = myint.GetRecvrAcct();
        transaction_Details.sendrAmount = myint.GetSendrAcct();

        return transaction_Details;
    }
</code>```

Body:
I have injected(AccountAccessInterface) interface in the constructor when I run API I can't resolve its dependency as this interface I am getting from .dll and don't have access to its implementation. So I need some way so that I can resolve dependency   inside controller in any way Please as without having implementation(hidden implementation) class of interface I face error in APIs of dependency resolver

public class AdminController : ApiController
{
    private readonly AccountAccessInterface _accountAccessInterface;

    public AdminController(AccountAccessInterface accountAccessInterface)
    {
        _accountAccessInterface = accountAccessInterface;
    }

    // to get account if by user id
   [Route("api/admin/ProcessTrsanctionAndSave")]
   [HttpGet]
    public void ProcessTrsanctionAndSave()
    {

        BankDB.BankDB bankDB = new BankDB.BankDB();
        bankDB.ProcessAllTransactions();
        bankDB.SaveToDisk();
    }
}

Body:
I have solved the problem by doing the Following work.
When we don't have access to implementation class it means interfaces are returning from any class as a method.so if we do

TransactionAccessInterface is interface here and Models.Globoclass.myBank.GetTransactionInterface() is the base class from interface returning as method.

 public object SelectTransaction(uint TransactionID)
    {
        TransactionAccessInterface myint = Models.Globoclass.myBank.GetTransactionInterface();
        myint.SelectTransaction(TransactionID);
        Transaction_Details transaction_Details = new Transaction_Details();
        transaction_Details.amount = myint.GetAmount();
        transaction_Details.recvrAccount = myint.GetRecvrAcct();
        transaction_Details.sendrAmount = myint.GetSendrAcct();

        return transaction_Details;
    }


问:
Defeating the Array<T> and IObservableArray<T> incompatibility
Assume I have some property in my store that is being array of some type MyType and decorated with observable:

```<code>class MyStore {
    @observable array
}
</code>```

I know that in normal world this should be an Array<MyType>. But when I'm declaring it in this way,

```<code>class MyStore {
    @observable array: Array<MyType>
}
</code>```

then I lose the method .remove(item: MyType). On the other hand, if I'm declaring it with IObservableArray<MyType>,

```<code>class MyStore {
    @observable array: IObservableArray<MyType>
}
</code>```

then I lose a possibility to legally assign an Array<MyType> values to this prop (under legally I mean assigning without construction ... as IObservableArray<MyType> - disadvantages of this method are too obvious: a lot of unnecessary code, the type should be imported whenever it used, etc.)

I also tried to use union and intersection types:

Intersection (Array<MyType> & IObservableArray<MyType>) produces an error during assigning an Array<MyType> value to this prop: Property 'spliceWithArray' is missing in type MyType.

Union (Array<MyType> | IObservableArray<MyType>) still causes lost of method .remove(item: MyType).

Am I missing or misunderstanding something? Is there any legal way to defeat it? Thank you all in advance!

By the way, the mobx version I'm using is 4, because it is necessary for me to support old iPads, unfortunately

答:
You need to use the next syntax, this won't generate any TS errors. And you can safely use methods of both Array and IObservableArray

class MyStore {
  readonly array = observable<MyType>([])

  @action
  getItems() {
    api.getItems<MyType[]>().then((response) => this.array.replace(response.data));
  }

  @action
  removeItem(item: MyType) {
    this.array.remove(item);
  }
}
```

readonly - as you are mostly not intended to do an assignment for array property, like this.array = itemsFromServer

replace, remove - methods of IObservableArray

Body:
Assume I have some property in my store that is being array of some type MyType and decorated with observable:

class MyStore {
    @observable array
}

I know that in normal world this should be an Array<MyType>. But when I'm declaring it in this way,

class MyStore {
    @observable array: Array<MyType>
}

then I lose the method .remove(item: MyType). On the other hand, if I'm declaring it with IObservableArray<MyType>,

class MyStore {
    @observable array: IObservableArray<MyType>
}

then I lose a possibility to legally assign an Array<MyType> values to this prop (under legally I mean assigning without construction ... as IObservableArray<MyType> - disadvantages of this method are too obvious: a lot of unnecessary code, the type should be imported whenever it used, etc.)

I also tried to use union and intersection types:

Intersection (Array<MyType> & IObservableArray<MyType>) produces an error during assigning an Array<MyType> value to this prop: Property 'spliceWithArray' is missing in type MyType.

Union (Array<MyType> | IObservableArray<MyType>) still causes lost of method .remove(item: MyType).

Am I missing or misunderstanding something? Is there any legal way to defeat it? Thank you all in advance!

By the way, the mobx version I'm using is 4, because it is necessary for me to support old iPads, unfortunately

Body:
You need to use the next syntax, this won't generate any TS errors. And you can safely use methods of both Array and IObservableArray

class MyStore {
  readonly array = observable<MyType>([])

  @action
  getItems() {
    api.getItems<MyType[]>().then((response) => this.array.replace(response.data));
  }

  @action
  removeItem(item: MyType) {
    this.array.remove(item);
  }
}

readonly - as you are mostly not intended to do an assignment for array property, like this.array = itemsFromServer

replace, remove - methods of IObservableArray


问:
Lazy loading function in Javascript
In our code sometimes we need a function to load after some time the page is loaded, for stuff like caching the articles of website which is not needed while the page load is happening.

I was wondering if we can write or use some syntax which can lazy load that particular function.

Example:

lazyload funnction xyz(){
    // put your code here
}
```

If there is any way to do this or something similar approach, It is fine if you point me to any patterns, frameworks etc.

答:
You can add a script dynamically using JavaScript:

let script = document.createElement('script');
script.src = "/caching.js";
document.body.append(script);
```

<p>The script will start loading once it's been added to the document.</p>

<p>Dynamically loaded scripts behave like <code>async</code> by default, but you can change the order from “First Loaded – First Executed” to the order in which they are appended into the document by explicitly setting the <code>async</code> property to <code>false</code>:
</p>

```let script = document.createElement('script');
script.src = "caching.js";

script.async = false;

document.body.append(script);
```

Title: Lazy loading function in Javascript

Body:
In our code sometimes we need a function to load after some time the page is loaded, for stuff like caching the articles of website which is not needed while the page load is happening.

I was wondering if we can write or use some syntax which can lazy load that particular function.

Example:

lazyload funnction xyz(){
    // put your code here
}

If there is any way to do this or something similar approach, It is fine if you point me to any patterns, frameworks etc.

Body:
You can add a script dynamically using JavaScript:

let script = document.createElement('script');
script.src = "/caching.js";
document.body.append(script);

The script will start loading once it's been added to the document.

Dynamically loaded scripts behave like async by default, but you can change the order from “First Loaded – First Executed” to the order in which they are appended into the document by explicitly setting the async property to false:

let script = document.createElement('script');
script.src = "caching.js";

script.async = false;

document.body.append(script);


问:
Express JS passing middleware through controller function
I wanted to know if it is possible to pass middleware in the controller function
routes.js

```<code>const router = require('express').Router();
router.get('/home', home.get);

</code>```

home.js

```<code>module.exports.get = (req, res) => {
  res.send("Welcome to HOME");
};

</code>```

I want to pass middleware in the get function of home.js, one method I know is to call the middleware function and then pass the controller function as next callback

```<code>module.exports.get = (req, res) => {
   authCheckMiddleware(req, res, () => {
       res.send("Welcome to HOME");
   })
};
</code>```

If there any approach? to pass the middleware in the function defination or something for home.js

答:
You can do it by adding your middleware function as an argument preceding the actual controller:</p>

```<code>router.get('/home', authCheckMiddleware, home.get);
</code>```

Body:
I wanted to know if it is possible to pass middleware in the controller function
routes.js

const router = require('express').Router();
router.get('/home', home.get);

home.js

module.exports.get = (req, res) => {
  res.send("Welcome to HOME");
};

I want to pass middleware in the get function of home.js, one method I know is to call the middleware function and then pass the controller function as next callback

module.exports.get = (req, res) => {
   authCheckMiddleware(req, res, () => {
       res.send("Welcome to HOME");
   })
};

If there any approach? to pass the middleware in the function defination or something for home.js

Body:
You can do it by adding your middleware function as an argument preceding the actual controller:

router.get('/home', authCheckMiddleware, home.get);


问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

答:
A possible solution using list comprehension could be:

```<code>a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
output = [ (a[i+1][1] - a[i][1], a[i+1][2] - a[i][2]) for i in range(len(a)-1) ]
print(output)
</code>```

Body:
A possible solution using list comprehension could be:

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
output = [ (a[i+1][1] - a[i][1], a[i+1][2] - a[i][2]) for i in range(len(a)-1) ]
print(output)


问:
Angular 9 How to import HTML file as a string with TypeScript?
I'm using  Angular 9.1.3 and Typescript 3.8.3.

I want to import html file as a raw string.

For the case:

```<code>import * as template from "./projects.page.html";
console.log("Template: ", template);
</code>```

I'm getting error:

```<code>ERROR in src/app/features/projects/projects.page.ts:41:27 - error TS2307: Cannot find module './projects.page.html'.

41 import * as template from "./projects.page.html";
</code>```

If I add html.d.ts file:

```<code>declare module "*.html" {
    const content: string;
    export default content;
}
</code>```

I'm getting error:

```<code>ERROR in ./src/app/features/projects/projects.page.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
> <div style="height: calc(100vh - 64px)">
</code>```

答:
I had the same problem and I fixed it using the html template inside a typescript file.

You could create a template.ts file like this:

```<code>const template = `
  <div> Your template here! </div>
`;

export default template;

</code>```

And you could simply import the file in this way :

```<code>import template from "./template";
</code>```

Body:
I'm using  Angular 9.1.3 and Typescript 3.8.3.

I want to import html file as a raw string.

For the case:

import * as template from "./projects.page.html";
console.log("Template: ", template);

I'm getting error:

ERROR in src/app/features/projects/projects.page.ts:41:27 - error TS2307: Cannot find module './projects.page.html'.

41 import * as template from "./projects.page.html";

If I add html.d.ts file:

declare module "*.html" {
    const content: string;
    export default content;
}

I'm getting error:

ERROR in ./src/app/features/projects/projects.page.html 1:0
Module parse failed: Unexpected token (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
>

Body:
I had the same problem and I fixed it using the html template inside a typescript file.

You could create a template.ts file like this:

const template = `
  <div> Your template here! </div>
`;

export default template;

And you could simply import the file in this way :

import template from "./template";


问:
How to tokenize python code using the Tokenize module?
Consider that I have a string that contains the python code.

```<code>input = "import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"
</code>```

How can I tokenize the code? I found the tokenize module (https://docs.python.org/3/library/tokenize.html). However, it is not clear to me how to use the module. It has tokenize.tokenize(readline) but the parameter takes a generator, not a string.

答:
import tokenize
import io

inp = """import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"""

for token in tokenize.generate_tokens(io.StringIO(inp).readline):
 print(token)
```

tokenize.tokenize takes a method not a string. The method should be a readline method from an IO object.
In addition, tokenize.tokenize expects the readline method to return bytes, you can use tokenize.generate_tokens instead to use a readline method that returns strings.

Your input should also be in a docstring, as it is multiple lines long.

See io.TextIOBase, tokenize.generate_tokens for more info.

Body:
Consider that I have a string that contains the python code.

input = "import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"

How can I tokenize the code? I found the tokenize module (https://docs.python.org/3/library/tokenize.html). However, it is not clear to me how to use the module. It has tokenize.tokenize(readline) but the parameter takes a generator, not a string.

Body:
import tokenize
import io

inp = """import nltk
 from nltk.stem import PorterStemmer
 porter_stemmer=PorterStemmer()
 words=["connect","connected","connection","connections","connects"]
 stemmed_words=[porter_stemmer.stem(word) for word in words]
 stemmed_words"""

for token in tokenize.generate_tokens(io.StringIO(inp).readline):
 print(token)

tokenize.tokenize takes a method not a string. The method should be a readline method from an IO object.
In addition, tokenize.tokenize expects the readline method to return bytes, you can use tokenize.generate_tokens instead to use a readline method that returns strings.

Your input should also be in a docstring, as it is multiple lines long.

See io.TextIOBase, tokenize.generate_tokens for more info.


问:
Error 'tunneling socket' while executing npm install
I'm getting the error shown below while trying to execute 'npm install' command.

Error: tunneling socket could not be established, cause=connect ECONNREFUSED 10.232.207.137:8080

What do I miss?

答:
```<code>npm config set registry http://registry.npmjs.org/
</code>```

above code solved my issue :)

Body:
npm config set registry http://registry.npmjs.org/

above code solved my issue :)


问:
ORA-06553: PLS-801:Internal Error [55018]
I want to make a function call like SELECT URUN_GETIR('test1') FROM DUAL; but i got ORA-06553: PLS-801: Internal Error [55018].

I tried ORA-06553: PLS-801: internal error [55018] when testing function returning ROWTYPE this like for ex URUN_GETIR('test1').KULUSERNAME but getting same error. It didn't work for me.Thanks in advance.

My db table :

My plsql function code :

```<code>create or replace FUNCTION URUN_GETIR(KULADI VARCHAR2)
RETURN URUN%ROWTYPE
AS
URUN_TABLO URUN%ROWTYPE;
BEGIN
SELECT * INTO URUN_TABLO FROM URUN ur WHERE ur.kulusername = KULADI;
RETURN URUN_TABLO;
END;
</code>```

答:
You can achieve your goal with using  table functions. Other than that you can not call directly your function like you wanted. Here is another choice for you Use Stackoverflow Wisely</p>

```<code>CREATE TABLE URUN
(
   CREATED_BY     VARCHAR2 (50 CHAR),
   CREATED_DATE   DATE,
   UPDATED_BY     VARCHAR2 (50 CHAR),
   KULUSERNAME    VARCHAR2 (50 CHAR),
   ID             NUMBER (10)
);

INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST1',TO_DATE('19000101','YYYYMMDD') ,'TTEST1','USER1',1);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST2',TO_DATE('19000102','YYYYMMDD') ,'TTEST2','USER2',2);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST3',TO_DATE('19000103','YYYYMMDD') ,'TTEST3','USER3',3);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST4',TO_DATE('19000104','YYYYMMDD') ,'TTEST4','USER4',4);COMMIT;

CREATE OR REPLACE TYPE URUN_OBJ AS OBJECT
(
   CREATED_BY VARCHAR2 (50 CHAR),
   CREATED_DATE DATE,
   UPDATED_BY VARCHAR2 (50 CHAR),
   KULUSERNAME VARCHAR2 (50 CHAR),
   ID NUMBER (10)
);

CREATE OR REPLACE TYPE URUN_OBJ_TAB AS TABLE OF URUN_OBJ;

CREATE OR REPLACE FUNCTION URUN_GETIR (KULADI IN VARCHAR2)
   RETURN URUN_OBJ_TAB
   PIPELINED
AS
   REC_OBJ   URUN_OBJ;

   CURSOR DATA
   IS
      SELECT *
        FROM URUN UR
       WHERE UR.KULUSERNAME = KULADI;
BEGIN
   FOR REC IN DATA
   LOOP
      REC_OBJ :=
         URUN_OBJ (REC.CREATED_BY,
                   REC.CREATED_DATE,
                   REC.UPDATED_BY,
                   REC.KULUSERNAME,
                   REC.ID);
      PIPE ROW (REC_OBJ);
   END LOOP;

   RETURN;
END;
/

SELECT * FROM   TABLE(URUN_GETIR('USER1'));

CREATED_BY  CREATED_DATE    UPDATED_BY  KULUSERNAME ID
TEST1   1.01.1900   TTEST1  USER1   1
</code>```

Body:
I want to make a function call like SELECT URUN_GETIR('test1') FROM DUAL; but i got ORA-06553: PLS-801: Internal Error [55018].

I tried ORA-06553: PLS-801: internal error [55018] when testing function returning ROWTYPE this like for ex URUN_GETIR('test1').KULUSERNAME but getting same error. It didn't work for me.Thanks in advance.

My db table :

My plsql function code :

create or replace FUNCTION URUN_GETIR(KULADI VARCHAR2)
RETURN URUN%ROWTYPE
AS
URUN_TABLO URUN%ROWTYPE;
BEGIN
SELECT * INTO URUN_TABLO FROM URUN ur WHERE ur.kulusername = KULADI;
RETURN URUN_TABLO;
END;

Body:
You can achieve your goal with using  table functions. Other than that you can not call directly your function like you wanted. Here is another choice for you Use Stackoverflow Wisely

CREATE TABLE URUN
(
   CREATED_BY     VARCHAR2 (50 CHAR),
   CREATED_DATE   DATE,
   UPDATED_BY     VARCHAR2 (50 CHAR),
   KULUSERNAME    VARCHAR2 (50 CHAR),
   ID             NUMBER (10)
);

INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST1',TO_DATE('19000101','YYYYMMDD') ,'TTEST1','USER1',1);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST2',TO_DATE('19000102','YYYYMMDD') ,'TTEST2','USER2',2);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST3',TO_DATE('19000103','YYYYMMDD') ,'TTEST3','USER3',3);COMMIT;
INSERT INTO URUN (CREATED_BY, CREATED_DATE, UPDATED_BY, KULUSERNAME, ID) VALUES('TEST4',TO_DATE('19000104','YYYYMMDD') ,'TTEST4','USER4',4);COMMIT;

CREATE OR REPLACE TYPE URUN_OBJ AS OBJECT
(
   CREATED_BY VARCHAR2 (50 CHAR),
   CREATED_DATE DATE,
   UPDATED_BY VARCHAR2 (50 CHAR),
   KULUSERNAME VARCHAR2 (50 CHAR),
   ID NUMBER (10)
);

CREATE OR REPLACE TYPE URUN_OBJ_TAB AS TABLE OF URUN_OBJ;

CREATE OR REPLACE FUNCTION URUN_GETIR (KULADI IN VARCHAR2)
   RETURN URUN_OBJ_TAB
   PIPELINED
AS
   REC_OBJ   URUN_OBJ;

   CURSOR DATA
   IS
      SELECT *
        FROM URUN UR
       WHERE UR.KULUSERNAME = KULADI;
BEGIN
   FOR REC IN DATA
   LOOP
      REC_OBJ :=
         URUN_OBJ (REC.CREATED_BY,
                   REC.CREATED_DATE,
                   REC.UPDATED_BY,
                   REC.KULUSERNAME,
                   REC.ID);
      PIPE ROW (REC_OBJ);
   END LOOP;

   RETURN;
END;
/

SELECT * FROM   TABLE(URUN_GETIR('USER1'));

CREATED_BY  CREATED_DATE    UPDATED_BY  KULUSERNAME ID
TEST1   1.01.1900   TTEST1  USER1   1


问:
Get count data monthwise from iso-date mongo-db
I have collection users.

users collection has the data as following

```<code>{
  '_id' : '5ed52b5fc5a55a0d8556288d',
  'name' : 'Don',
  "createdAt" : ISODate("2020-01-01T00:00:00.000Z"),
},
{
  '_id' : '5ed52b5fc5a5230d8556288d',
  'name' : 'Fabiano',
  "createdAt" : ISODate("2020-02-01T00:00:00.000Z"),
},
{
  '_id' : '5ed52b5fc5a55a0d8500288d',
  'name' : 'Jose',
  "createdAt" : ISODate("2020-02-03T00:00:00.000Z"),
},
{
  '_id' : '5ed51b5fc5a52a0d8500288d',
  'name' : 'Capablanca',
  "createdAt" : ISODate("2020-04-03T00:00:00.000Z"),
}
</code>```

The Isodate year is 2020 only.
As we can observe that users are created the following months as below

```<code>  'Don' -> 'January','Fabiano' -> 'February','Jose' -> 'February','Capablanca' -> 'April'
</code>```

Is it possible that mongodb or moongoose query can get the result as something like or similar to below

```<code>[
  //key -> month and value -> no of users
 {
   1 : 1
 },
 {
   2 : 2
 },
 {
   4 : 1
 }
]
</code>```

I am using nodejs,express with mongodb and mongoose.

答:
You need to use aggregation

```<code>model.aggregate([
  {
    $unwind: "$createdAt"
  },
  {
    $group: {
      _id: { $month: "$createdAt" },
      userCount: { $sum: 1 }
    }
  },
  {
    $addFields: { monthNumber: "$_id" }
  },
  {
    $project: { _id: 0 }
  },
  {
    $sort: { monthNumber: 1 }
  }
])
</code>```

You will get following output

```<code>[
  {
    "monthNumber": 1,
    "userCount": 1
  },
  {
    "monthNumber": 2,
    "userCount": 2
  },
  {
    "monthNumber": 4,
    "userCount": 1
  }
]
</code>```

Here's a demo

Body:
I have collection users.

users collection has the data as following

{
  '_id' : '5ed52b5fc5a55a0d8556288d',
  'name' : 'Don',
  "createdAt" : ISODate("2020-01-01T00:00:00.000Z"),
},
{
  '_id' : '5ed52b5fc5a5230d8556288d',
  'name' : 'Fabiano',
  "createdAt" : ISODate("2020-02-01T00:00:00.000Z"),
},
{
  '_id' : '5ed52b5fc5a55a0d8500288d',
  'name' : 'Jose',
  "createdAt" : ISODate("2020-02-03T00:00:00.000Z"),
},
{
  '_id' : '5ed51b5fc5a52a0d8500288d',
  'name' : 'Capablanca',
  "createdAt" : ISODate("2020-04-03T00:00:00.000Z"),
}

The Isodate year is 2020 only.
As we can observe that users are created the following months as below

  'Don' -> 'January','Fabiano' -> 'February','Jose' -> 'February','Capablanca' -> 'April'

Is it possible that mongodb or moongoose query can get the result as something like or similar to below

[
  //key -> month and value -> no of users
 {
   1 : 1
 },
 {
   2 : 2
 },
 {
   4 : 1
 }
]

I am using nodejs,express with mongodb and mongoose.

Body:
You need to use aggregation

model.aggregate([
  {
    $unwind: "$createdAt"
  },
  {
    $group: {
      _id: { $month: "$createdAt" },
      userCount: { $sum: 1 }
    }
  },
  {
    $addFields: { monthNumber: "$_id" }
  },
  {
    $project: { _id: 0 }
  },
  {
    $sort: { monthNumber: 1 }
  }
])

You will get following output

[
  {
    "monthNumber": 1,
    "userCount": 1
  },
  {
    "monthNumber": 2,
    "userCount": 2
  },
  {
    "monthNumber": 4,
    "userCount": 1
  }
]

Here's a demo


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
All you youngsters yappin' on about 32 bit thiss and 64 bit that: you know, there were and are other machine architectures than the x86 family. A PDP-11 had 40-bit words, f'rinstance. </p>

<p>But the simplest answer is just to search Wikipedia. </p>

OwnerDisplayName: mixedpickles

Body:
All you youngsters yappin' on about 32 bit thiss and 64 bit that: you know, there were and are other machine architectures than the x86 family. A PDP-11 had 40-bit words, f'rinstance.

But the simplest answer is just to search Wikipedia.

OwnerDisplayName: Pontus Gagge

ContentLicense: CC BY-SA 2.5


问:
what do i need to do to develope an iphone\android app in vs2010?
we are a .net team that devleoped a full app in c# with web services and services that support it. we now want to develope a Mobile app (Android\Iphone) that will look similiar to the original to allow mobile use of it.
we thought about MonoTouch instead of trying to learn Objective-c and to try to develope a cross platform mobile app.
is anyone tried developing a mobile app in vs 2010 in MonoTouch? is there a simple add in for it? is it possible?</p>

答:
There is a GitHub project to allow you to use Visual Studio to code everything except the UI.

https://github.com/follesoe/VSMonoTouch

Also, he has a very good tutorial on doing cross platform mobile dev
https://github.com/follesoe/FlightsNorway/tree/workshop


问:
Cython FIFO cache for function result
I need some kind of cache to store the result of a function f in Cython for future reuse. A simple FIFO cache policy that discards the least recently computed result when the cache is full will do just fine. I need the cache to be reinitialised every time I call another function from Python which uses the cache and calls f. I came up with the following solution using a std::map wrapped in an extension type:

# distutils: language = c++

import sys
import time

from libcpp.map cimport map as cppmap
from libcpp.utility cimport pair as cpppair
from libcpp.queue cimport queue as cppqueue
from cython.operator cimport dereference as deref

ctypedef cpppair[long, long] mapitem_t
ctypedef cppmap[long, long].iterator mi_t

cdef class Cache_map:
    """Cache container"""
    cdef:
        cppmap[long, long] _cache_data
        cppqueue[long] _order
        long _cachesize
        long _size

    def __init__(self, long cachesize=100):
        self._cachesize = cachesize
        self._size = 0

    cdef mi_t setitem(
            self, mi_t it, long key, long value):
        """Insert key/value pair into cache and return position"""

        if self._size >= self._cachesize:
            self._cache_data.erase(self._order.front())
            self._order.pop()
        else:
            self._size += 1
        self._order.push(key)
        return self._cache_data.insert(it, mapitem_t(key, value))

    @property
    def cache_data(self):
        return self._cache_data

cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

cdef long cached_f(long x, Cache_map Cache):
    cdef mi_t search = Cache._cache_data.lower_bound(x)

    if search != Cache._cache_data.end() and x == deref(search).first:
        return deref(search).second
    return deref(Cache.setitem(search, x, f(x))).second

def use_cache():
    # Output container
    cdef list cache_size = []
    cdef list timings = []
    cdef list results = []

    cdef long i, r
    cdef Cache_map Cache = Cache_map(10)  # Initialise cache

    cache_size.append(sys.getsizeof(Cache))
    go = time.time()
    for i in range(100):
        # Silly loop using the cache
        for r in range(2):
            results.append(cached_f(i, Cache))
            timings.append(time.time() - go)
            go = time.time()
        cache_size.append(sys.getsizeof(Cache))
        go = time.time()

    return cache_size, timings, results
```

<p>While this works in principle, it has a few drawbacks:</p>

<ul>
<li>I have to manually create <code>cached_f</code> to wrap <code>f</code> (not very reusable)</li>
<li>I have to pass <code>Cache</code> to <code>cached_f</code> (unnecessarily expensive???)</li>
<li><code>Cached_map</code> is explicitly written to cache results from <code>f</code> (not very reusable)</li>
</ul>

<p>I would imagine that this is quite a standard task, so is there a better way?</p>

<p>I tried, for example, to pass a pointer to the Cache to <code>cached_f</code> but it seems I cannot create a pointer to an extension type object? The following:</p>

<pre class="lang-py prettyprint-override"><code>cdef Cache_map Cache = Cache_map(10)
cdef Cache_map *Cache_ptr

Cache_ptr = &Cache
</code>```

throws cache_map.pyx:66:16: Cannot take address of Python variable 'Cache'.

答:
I think from the software engineering point of view, it is a good idea to have the function (which is a function-pointer/functor in C/cdef-Cython) and its memoization bundled together in an object/class.

My approach would be to write a cdef class (let's call it FunWithMemoization) which has a function pointer and a memoization-data-structure for storing known results.

Because the life is too short to write c++-code with Cython, I have written memoization-class in pure c++ (whole code can be found further bellow), which more or less is very similar to your approach (but rather using unordered_map) and wrap/use it with Cython:

```<code>%%cython -+
from libcpp cimport bool
cdef extern from *:
    """
    // see full code bellow
    """
    struct memoization_result:
        long value;
        bool found;

    cppclass memoization:
        memoization()
        void set_value(long, long)
        memoization_result find_value(long key)

ctypedef long(*f_type)(long)
cdef long id_fun(long x):
    return x

cdef class FunWithMemoization:
    cdef memoization mem
    cdef f_type fun
    def __cinit__(self):
        self.fun = id_fun

    cpdef long evaluate(self, long x):
        cdef memoization_result look_up = self.mem.find_value(x)
        if look_up.found:
            return look_up.value
        cdef long val = self.fun(x)
        self.mem.set_value(x, val)
        return val
</code>```

I'have used id_fun to default initialize the fun-member, but we need further functionality to make FunWithMemoization useful, for example:

```<code>import time
cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

def create_f_with_memoization():
    fun = FunWithMemoization()
    fun.fun = f
    return fun
</code>```

There are obviously other approached to create a useful FunWithMemoization, one could use ctypes to get the addresses of functions or this receipt.

And now:

```<code>f = create_f_with_memoization()
# first time really calculated:
%timeit -r 1 -n 1 f.evaluate(2)
#10.5 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
# second time - from memoization:
%timeit -r 1 -n 1 f.evaluate(2)
1.4 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
</code>```

Whole code:

```<code>%%cython -+
from libcpp cimport bool
cdef extern from *:
    """
    #include<unordered_map>
    #include <queue>

    struct memoization_result{
       long value;
       bool found;
    };

    class memoization{
    private:
       std::unordered_map<long, long> map;
       std::queue<long> key_order;
       size_t max_size;
    public:
       memoization(): max_size(128){}
       void set_value(long key, long val){
            //assumes key isn't yet in map
            map[key]=val;
            key_order.push(key);
            if(key_order.size()>max_size){
                key_order.pop();
            }
       }
       memoization_result find_value(long key) const{
          auto it = map.find(key);
          if(it==map.cend()){
              return {0, false};
          }
          else{
              return {it->second, true};
          }
       }
    };
    """
    struct memoization_result:
        long value;
        bool found;

    cppclass memoization:
        memoization()
        void set_value(long, long)
        memoization_result find_value(long key)

ctypedef long(*f_type)(long)
cdef long id_fun(long x):
    return x

cdef class FunWithMemoization:
    cdef memoization mem
    cdef f_type fun
    def __cinit__(self):
        self.fun = id_fun

    cpdef long evaluate(self, long x):
        cdef memoization_result look_up = self.mem.find_value(x)
        if look_up.found:
            return look_up.value
        cdef long val = self.fun(x)
        self.mem.set_value(x, val)
        return val

import time
cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

def create_f_with_memoization():
    fun = FunWithMemoization()
    fun.fun = f
    return fun
</code>```

Title: Cython FIFO cache for function result

Body:
I need some kind of cache to store the result of a function f in Cython for future reuse. A simple FIFO cache policy that discards the least recently computed result when the cache is full will do just fine. I need the cache to be reinitialised every time I call another function from Python which uses the cache and calls f. I came up with the following solution using a std::map wrapped in an extension type:

# distutils: language = c++

import sys
import time

from libcpp.map cimport map as cppmap
from libcpp.utility cimport pair as cpppair
from libcpp.queue cimport queue as cppqueue
from cython.operator cimport dereference as deref

ctypedef cpppair[long, long] mapitem_t
ctypedef cppmap[long, long].iterator mi_t

cdef class Cache_map:
    """Cache container"""
    cdef:
        cppmap[long, long] _cache_data
        cppqueue[long] _order
        long _cachesize
        long _size

    def __init__(self, long cachesize=100):
        self._cachesize = cachesize
        self._size = 0

    cdef mi_t setitem(
            self, mi_t it, long key, long value):
        """Insert key/value pair into cache and return position"""

        if self._size >= self._cachesize:
            self._cache_data.erase(self._order.front())
            self._order.pop()
        else:
            self._size += 1
        self._order.push(key)
        return self._cache_data.insert(it, mapitem_t(key, value))

    @property
    def cache_data(self):
        return self._cache_data

cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

cdef long cached_f(long x, Cache_map Cache):
    cdef mi_t search = Cache._cache_data.lower_bound(x)

    if search != Cache._cache_data.end() and x == deref(search).first:
        return deref(search).second
    return deref(Cache.setitem(search, x, f(x))).second

def use_cache():
    # Output container
    cdef list cache_size = []
    cdef list timings = []
    cdef list results = []

    cdef long i, r
    cdef Cache_map Cache = Cache_map(10)  # Initialise cache

    cache_size.append(sys.getsizeof(Cache))
    go = time.time()
    for i in range(100):
        # Silly loop using the cache
        for r in range(2):
            results.append(cached_f(i, Cache))
            timings.append(time.time() - go)
            go = time.time()
        cache_size.append(sys.getsizeof(Cache))
        go = time.time()

    return cache_size, timings, results

While this works in principle, it has a few drawbacks:

I have to manually create cached_f to wrap f (not very reusable)

I have to pass Cache to cached_f (unnecessarily expensive???)

Cached_map is explicitly written to cache results from f (not very reusable)

I would imagine that this is quite a standard task, so is there a better way?

I tried, for example, to pass a pointer to the Cache to cached_f but it seems I cannot create a pointer to an extension type object? The following:

cdef Cache_map Cache = Cache_map(10)
cdef Cache_map *Cache_ptr

Cache_ptr = &Cache

throws cache_map.pyx:66:16: Cannot take address of Python variable 'Cache'.

Body:
I think from the software engineering point of view, it is a good idea to have the function (which is a function-pointer/functor in C/cdef-Cython) and its memoization bundled together in an object/class.

My approach would be to write a cdef class (let's call it FunWithMemoization) which has a function pointer and a memoization-data-structure for storing known results.

Because the life is too short to write c++-code with Cython, I have written memoization-class in pure c++ (whole code can be found further bellow), which more or less is very similar to your approach (but rather using unordered_map) and wrap/use it with Cython:

%%cython -+
from libcpp cimport bool
cdef extern from *:
    """
    // see full code bellow
    """
    struct memoization_result:
        long value;
        bool found;

    cppclass memoization:
        memoization()
        void set_value(long, long)
        memoization_result find_value(long key)

ctypedef long(*f_type)(long)
cdef long id_fun(long x):
    return x

cdef class FunWithMemoization:
    cdef memoization mem
    cdef f_type fun
    def __cinit__(self):
        self.fun = id_fun

    cpdef long evaluate(self, long x):
        cdef memoization_result look_up = self.mem.find_value(x)
        if look_up.found:
            return look_up.value
        cdef long val = self.fun(x)
        self.mem.set_value(x, val)
        return val

I'have used id_fun to default initialize the fun-member, but we need further functionality to make FunWithMemoization useful, for example:

import time
cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

def create_f_with_memoization():
    fun = FunWithMemoization()
    fun.fun = f
    return fun

There are obviously other approached to create a useful FunWithMemoization, one could use ctypes to get the addresses of functions or this receipt.

And now:

f = create_f_with_memoization()
# first time really calculated:
%timeit -r 1 -n 1 f.evaluate(2)
#10.5 ms ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)
# second time - from memoization:
%timeit -r 1 -n 1 f.evaluate(2)
1.4 µs ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each)

Whole code:

%%cython -+
from libcpp cimport bool
cdef extern from *:
    """
    #include<unordered_map>
    #include <queue>

    struct memoization_result{
       long value;
       bool found;
    };

    class memoization{
    private:
       std::unordered_map<long, long> map;
       std::queue<long> key_order;
       size_t max_size;
    public:
       memoization(): max_size(128){}
       void set_value(long key, long val){
            //assumes key isn't yet in map
            map[key]=val;
            key_order.push(key);
            if(key_order.size()>max_size){
                key_order.pop();
            }
       }
       memoization_result find_value(long key) const{
          auto it = map.find(key);
          if(it==map.cend()){
              return {0, false};
          }
          else{
              return {it->second, true};
          }
       }
    };
    """
    struct memoization_result:
        long value;
        bool found;

    cppclass memoization:
        memoization()
        void set_value(long, long)
        memoization_result find_value(long key)

ctypedef long(*f_type)(long)
cdef long id_fun(long x):
    return x

cdef class FunWithMemoization:
    cdef memoization mem
    cdef f_type fun
    def __cinit__(self):
        self.fun = id_fun

    cpdef long evaluate(self, long x):
        cdef memoization_result look_up = self.mem.find_value(x)
        if look_up.found:
            return look_up.value
        cdef long val = self.fun(x)
        self.mem.set_value(x, val)
        return val

import time
cdef long f(long x):
    """Expensive function"""
    time.sleep(0.01)
    return x**2

def create_f_with_memoization():
    fun = FunWithMemoization()
    fun.fun = f
    return fun