问:
Try Catch Errors many script components - JavaScript
I have a page that contains many script components (50+) and I am getting an error when using IE at some random instance (doesn't happen in Chrome or Firefox).

"Out of Memory at line: 1"

I've done some google search too and that reveals issues with IE handling things differently to Chrome and FF. I would like to catch this error and know exactly what the cause of that script error is.

What would be the best way to use a global try-catch block on that many script components? All these script components are on the same page. Looking forward to your suggestions.

答:
You could check your localStorage before and after any components called.

Something like:

```<code>function getLocalStorage() {
    return JSON.stringify(localStorage).length;
}

function addScript(src, log) {
    if(log){
        console.log("Adding " + src + ", local storage size: " + getLocalStorage());
    }
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', src );
    document.body.appendChild( s );
}

function callFunction(func, log){
    if(log){
        console.log("Calling " + func.name + ", local storage size: " + getLocalStorage());
    }
    func();
}

try {
    addScript(src1, true);
    addScript(src2, true);
    callFunction(func1, true);
    callFunction(func2, true);
}
catch(err) {
    console.log(err.message);
}
</code>```

I hope it helps you. Bye.

Body:
You could check your localStorage before and after any components called.

Something like:

function getLocalStorage() {
    return JSON.stringify(localStorage).length;
}

function addScript(src, log) {
    if(log){
        console.log("Adding " + src + ", local storage size: " + getLocalStorage());
    }
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', src );
    document.body.appendChild( s );
}

function callFunction(func, log){
    if(log){
        console.log("Calling " + func.name + ", local storage size: " + getLocalStorage());
    }
    func();
}

try {
    addScript(src1, true);
    addScript(src2, true);
    callFunction(func1, true);
    callFunction(func2, true);
}
catch(err) {
    console.log(err.message);
}

I hope it helps you. Bye.


来源: stackexchange

问:
How to get array format in javascript?
I am getting an array in AngularJs with factory function. This is the console

```<code>Array[0]
  0: "value1"
  1: "value2"
  length:2
</code>```

But when i want to get the length of the array

```<code>console.log(array.length)
</code>```

getting data from mysql in loopback

```<code> app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});
</code>```

The controller look like:

```<code>app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])
</code>```

I get that the length is 0. Why is that?

答:
try this,</p>

```<code>console.log(array[0].length)
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get array format in javascript?

Body:
I am getting an array in AngularJs with factory function. This is the console

Array[0]
  0: "value1"
  1: "value2"
  length:2

But when i want to get the length of the array

console.log(array.length)

getting data from mysql in loopback

 app.factory("getFoo", function(Communications){
 return {
   getCommi: function(val,id){
    var array = [];
    var myVals = Communications.find({
                    filter: {
                        where: {
                            and : [{
                                communications_type_code : val
                            },{
                                object_id : id
                            }]
                        }
                    }
                }, function(data){
                    for(var i=0; i< data.length; i++){
                        array[i] = data[i].contact_value;
                    }
                    return array;
        });

        return array;
      }
  }
});

The controller look like:

app.controller('usersFormCtrl', ['$scope','getFoo',function($scope,getFoo){
var emails = getFoo.getCommi(3,1);

setTimeout(function(){
    $scope.formModel.emails = [];
    for(var index=0; index < $scope.emails.length; index++){
        $scope.emails = emails;
    }
}, 0)
}])

I get that the length is 0. Why is that?

Body:
try this,

console.log(array[0].length)


问:
Image path uploading and retrieving it in view in Codeigniter
I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:

```<code>    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    class Users extends CI_Controller
    {
    function  __construct() {
    parent::__construct();
    $this->load->model('user');
    }

     function add(){
      if($this->input->post('userSubmit')){

        //Check whether user upload picture
        if(!empty($_FILES['picture']['name'])){
            $config['upload_path'] = 'uploads/images/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['file_name'] = $_FILES['picture']['name'];

            //Load upload library and initialize configuration
            $this->load->library('upload',$config);
            $this->upload->initialize($config);

            if($this->upload->do_upload('picture')){
                $uploadData = $this->upload->data();
                $picture = $uploadData['file_name'];
            }else{
                $picture = '';
            }
        }else{
            $picture = '';
        }

        //Prepare array of user data
        $userData = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'picture' => $picture
        );

        //Pass user data to model
        $insertUserData = $this->user->insert($userData);

        //Storing insertion status message.
        if($insertUserData){
            $this->session->set_flashdata('success_msg', 'User data have been added successfully.');
        }else{
            $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
        }
    }
    //Form for adding user data
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);
}

public function show()
{
    #code
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);

}
</code>```

}

I have this in my model:

```<code>    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class User extends CI_Model{
   function __construct() {
    $this->load->database();
    $this->tableName = 'users';
    $this->primaryKey = 'id';
}

   public function insert($data = array()){
    if(!array_key_exists("created",$data)){
        $data['created'] = date("Y-m-d H:i:s");
    }
    if(!array_key_exists("modified",$data)){
        $data['modified'] = date("Y-m-d H:i:s");
    }
    $insert = $this->db->insert($this->tableName,$data);
    if($insert){
        return $this->db->insert_id();
    }else{
        return false;
    }
}

    public function getdata()
{
  $query=$this->db->get('users');
  return $query->result_array();
}
</code>```

}

Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:

```<code>    root folder->image:
               -application
               -system
               -uploads
                  .images(images are saved here)
</code>```

Now in the problem is with view. I am trying to access the stored images dynamically like this:

```<code>      <!DOCTYPE html>
       <html>
     <head>
   <meta charset="utf-8">
   <title>show</title>
    </head>
       <body>

    <table border='1' cellpadding='4'>
        <tr>
            <td><strong>User_Id</strong></td>
            <td><strong>Name</strong></td>
            <td><strong>Image</strong></td>
            <td><strong>Option</strong></td>
        </tr>
    <?php foreach ($data as $p): ?>
            <tr>
                <td><?php echo $p['id']; ?></td>
                <td><?php echo $p['name']; ?></td>
                <td><img src="../uploads/images/<?php echo $p['picture']; ?>" /> </td>
                <td>
                    <a href="#">View</a> |

                </td>
            </tr>
    <?php endforeach; ?>
    </table>
</code>```

With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:

```<code>    <img src="../uploads/images/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
     or like this
     <img src="../../uploadsimages/image-0-02-03-15420e726f6e9c97408cbb86b222586f7efe3b002e588ae6bdcfc3bc1ea1561e-V.jpg" />
</code>```

but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.

答: Just a silly mistake. I made my virtual host to point up to index.html of root folder. so just pointing up to root folder the problem was solved.</p>

Body:
I am new in codeigniter. And i was trying to upload images for a product. Right now i am trying with uploading only one image for each product. And i have done this in my controller:

    <?php defined('BASEPATH') OR exit('No direct script access allowed');
    class Users extends CI_Controller
    {
    function  __construct() {
    parent::__construct();
    $this->load->model('user');
    }

     function add(){
      if($this->input->post('userSubmit')){

        //Check whether user upload picture
        if(!empty($_FILES['picture']['name'])){
            $config['upload_path'] = 'uploads/images/';
            $config['allowed_types'] = 'jpg|jpeg|png|gif';
            $config['file_name'] = $_FILES['picture']['name'];

            //Load upload library and initialize configuration
            $this->load->library('upload',$config);
            $this->upload->initialize($config);

            if($this->upload->do_upload('picture')){
                $uploadData = $this->upload->data();
                $picture = $uploadData['file_name'];
            }else{
                $picture = '';
            }
        }else{
            $picture = '';
        }

        //Prepare array of user data
        $userData = array(
            'name' => $this->input->post('name'),
            'email' => $this->input->post('email'),
            'picture' => $picture
        );

        //Pass user data to model
        $insertUserData = $this->user->insert($userData);

        //Storing insertion status message.
        if($insertUserData){
            $this->session->set_flashdata('success_msg', 'User data have been added successfully.');
        }else{
            $this->session->set_flashdata('error_msg', 'Some problems occured, please try again.');
        }
    }
    //Form for adding user data
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);
}

public function show()
{
    #code
    $data['data']=$this->user->getdata();
    $this->load->view('show',$data);

}

}

I have this in my model:

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class User extends CI_Model{
   function __construct() {
    $this->load->database();
    $this->tableName = 'users';
    $this->primaryKey = 'id';
}

   public function insert($data = array()){
    if(!array_key_exists("created",$data)){
        $data['created'] = date("Y-m-d H:i:s");
    }
    if(!array_key_exists("modified",$data)){
        $data['modified'] = date("Y-m-d H:i:s");
    }
    $insert = $this->db->insert($this->tableName,$data);
    if($insert){
        return $this->db->insert_id();
    }else{
        return false;
    }
}

    public function getdata()
{
  $query=$this->db->get('users');
  return $query->result_array();
}

}

Issue is i am being able to store data along with image name in the database, and the selected image is uploaded in the specified folder in project folder which currently is:

    root folder->image:
               -application
               -system
               -uploads
                  .images(images are saved here)

Now in the problem is with view. I am trying to access the stored images dynamically like this:

      <!DOCTYPE html>

   <meta charset="utf-8">
   <title>show</title>

            User_Id
            Name
            Image
            Option

    <?php foreach ($data as $p): ?>

                <?php echo $p['id']; ?>
                <?php echo $p['name']; ?>
                <img src="../uploads/images/<?php echo $p['picture']; ?>" />

                    View |

    <?php endforeach; ?>

With this image source the image is not coming. only imge crack thumbnails is seen. I also tried giving root folder of image manually like this:

     or like this

but it ain't helping. Can anyone help me? Any suggestions and advice are highly welcome.Thank you.


问:
Draw line in canvas with another dashed line next to it
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

```<code>Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);
</code>```

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75

答:
You need to do the following, considering that the dashed line would be drawn above the main line at the start and continue like that:

If only x is changing, then the line is moving horizontally, you need only to add the distance value to the x coordinate of your dashed line

If only y is changing, then the line is moving virtically, you need only to add the distance value to the y coordinate of your dashed line

If x is positive and both x and y are changing, then you need only to add on y

If x is negative and both x and y are changing, then you need only to subtract from y ... etc

This way you will keep track of your original line, always doing the operations keeping in mind the last values of the coordinates and comparing them with the new ones.

Body:
For an app I am working on I am drawing a line on a canvas using given coordinates. The problem is that I need to draw a dashed line next to it. Since the coordinates are coming from the API I only can use those coordinates for the dashed line. Is there any way to accomplish this? I really can't figure it out.

What I want:

The way I draw my current line:

Path line = new Path();
boolean first = true;
for (CircleArea circle : mCircles) {

    canv.drawCircle(circle.getDrawX(), circle.getDrawY(), mCircleRadius, mCirclePaint);
    if(!first) {
        line.lineTo(circle.getDrawX(), circle.getDrawY());
    } else {
        line.moveTo(circle.getDrawX(), circle.getDrawY());
    }

    first = false;
}
canv.drawPath(line, mLinePaint);

Sample coordinates:

50,50

75,75

100,75

150,10

170,10

170,75

160,75


问:
Unable to extract object values in Typescript
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to deal with the following (which works in JavaScript):

```<code>let fieldValues = JSON.parse(cookieData);

let keys = Object.keys(fieldValues);

let values = Object.values(fieldValues);
</code>```

Visual Studio tells me:

Error TS2339  Property 'values' does not exist on type
  'ObjectConstructor'.

What can I do?

答:
Just as an alternative. You also could use Object.getOwnPropertyNames()</p>

```<code>let obj = {...};
Object.getOwnPropertyNames(obj).forEach(key => {
    let value = obj[key];
});
</code>```

Body:
I have been trying to convert a JavaScript web form to Typescript, and have been unable to work out how to deal with the following (which works in JavaScript):

let fieldValues = JSON.parse(cookieData);

let keys = Object.keys(fieldValues);

let values = Object.values(fieldValues);

Visual Studio tells me:

Error TS2339  Property 'values' does not exist on type
  'ObjectConstructor'.

What can I do?

Body:
Just as an alternative. You also could use Object.getOwnPropertyNames()

let obj = {...};
Object.getOwnPropertyNames(obj).forEach(key => {
    let value = obj[key];
});


问:
how to call a function within an if statement (vba)
I am trying to call a function within my if statement. The function is called classyear and is just after the if. I am trying to run through a timetable and see what classes belong to each year. so if it ends in a 1 it will be counted. Does anyone know how I would go about calling the function? Any help is appreciated

```<code>Public Sub time()
Dim rgTimeTable As Range, rgClass As Range, counter As Integer

Set rgTimeTable = Range("B3, N11")

For Each rgClass In rgTimeTable
If rgClass.Value = classyear Then counter = counter + 1     ' classyear is the function

Next rgClass
MsgBox test     ' also a function

End Sub
</code>```

EDIT
Code for the function i am trying to call

```<code>Public Function classyear(class As String) As Integer

Dim yr As String

yr = Right(class, 1)
If IsNumeric(yr) Then classyear = yr Else classyear = 0

End Function
</code>```

答:
You can call a Sub inside if block like:

(Use function if you want to return some value else use Sub)

```<code>if (...)

   classyear() '<--Calling the Sub defined below

End if

Private Sub classyear()
  .
  .
End Sub
</code>```

Hope this is what you are looking for.

Body:
I am trying to call a function within my if statement. The function is called classyear and is just after the if. I am trying to run through a timetable and see what classes belong to each year. so if it ends in a 1 it will be counted. Does anyone know how I would go about calling the function? Any help is appreciated

Public Sub time()
Dim rgTimeTable As Range, rgClass As Range, counter As Integer

Set rgTimeTable = Range("B3, N11")

For Each rgClass In rgTimeTable
If rgClass.Value = classyear Then counter = counter + 1     ' classyear is the function

Next rgClass
MsgBox test     ' also a function

End Sub

EDIT
Code for the function i am trying to call

Public Function classyear(class As String) As Integer

Dim yr As String

yr = Right(class, 1)
If IsNumeric(yr) Then classyear = yr Else classyear = 0

End Function

Body:
You can call a Sub inside if block like:

(Use function if you want to return some value else use Sub)

if (...)

   classyear() '<--Calling the Sub defined below

End if

Private Sub classyear()
  .
  .
End Sub

Hope this is what you are looking for.


问:
Arduino to Arduino communication via SoftwareSerial
I have two Arduino Leonardo.
Could these two Arduino boards communicate with each other by SoftwareSerial library? (Not Serial1, Thank you)</p>

答: Yes! Simply use TX and RX pins of arduino. Connect the receiver TX, RX pins to RX, TX of the sender, respectively.</p>


问:
python sort strings with digits at the end
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

```<code>>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']
</code>```

should  put the 1234 one on the end. is there an easy way to do this?

答:
The issue is that the sorting is alphabetical here since they are strings. Each sequence of character is compared before moving to next character.

```<code>>>> 'a1234' < 'a124'  <----- positionally '3' is less than '4'
True
>>>
</code>```

You will need to due numeric sorting to get the desired output.

```<code>>>> x = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> y = [ int(t[4:]) for t in x]
>>> z = sorted(y)
>>> z
[111, 123, 124, 1234]
>>> l = ['asdf'+str(t) for t in z]
>>> l
['asdf111', 'asdf123', 'asdf124', 'asdf1234']
>>>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
what is the easiest way to sort a list of strings with digits at the end where some have 3 digits and some have 4:

>>> list = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> list.sort()
>>> print list
['asdf111', 'asdf123', 'asdf1234', 'asdf124']

should  put the 1234 one on the end. is there an easy way to do this?

Body:
The issue is that the sorting is alphabetical here since they are strings. Each sequence of character is compared before moving to next character.

>>> 'a1234' < 'a124'  <----- positionally '3' is less than '4'
True
>>>

You will need to due numeric sorting to get the desired output.

>>> x = ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
>>> y = [ int(t[4:]) for t in x]
>>> z = sorted(y)
>>> z
[111, 123, 124, 1234]
>>> l = ['asdf'+str(t) for t in z]
>>> l
['asdf111', 'asdf123', 'asdf124', 'asdf1234']
>>>


问:
how to get the last value of the array variable in loops
Here is my code:

```<code>class test {
  public static void main(String args[]) {
    int a[]={5,8,9,7,3};
    int j;

    for(j=0;j<a.length-1;j++)
    {
        if(a[j]>a[j+1])
        {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
        System.out.print(a[j]+"   "); // last value of array a[4] is not printed
    }
  }
}
</code>```

This is one part of my program, here last value of the array is not printed?!

Can you help me anyone how to get the last value of array?

答:
Simple: add another print statement after the loop; like:

```<code> System.out.println(a[a.length-1]);
</code>```

for example.

for example. The point is that your loop is (correctly skipping that last index). So one reasonable solution is to do that last print statement after your loop; as you know that you want to print it.

ContentLicense: CC BY-SA 4.0

Body:
Here is my code:

class test {
  public static void main(String args[]) {
    int a[]={5,8,9,7,3};
    int j;

    for(j=0;ja[j+1])
        {
            int temp=a[j];
            a[j]=a[j+1];
            a[j+1]=temp;
        }
        System.out.print(a[j]+"   "); // last value of array a[4] is not printed
    }
  }
}

This is one part of my program, here last value of the array is not printed?!

Can you help me anyone how to get the last value of array?

Body:
Simple: add another print statement after the loop; like:

 System.out.println(a[a.length-1]);

for example.

for example. The point is that your loop is (correctly skipping that last index). So one reasonable solution is to do that last print statement after your loop; as you know that you want to print it.


问:
cakephp getLastInsertID / Model->id
Is  getLastInsertID and Model->id  same? And which one can happen concurrency problem ?

```<code>$this->Model->save($this->data);
__thisFunctionTakesAVeryLongTimeToExecute(); //function 1
$insertId = $this->Model->getLastInsertId();
</code>```

Does getLastInsertId() return the ID from the data I've saved 2 lines above. Or does it return the latest ID that's created?

I mean
what happen if when the function 1 (__thisFunctionTakesAVeryLongTimeToExecute();) execute another user do an another save. then which id will i get?

答:
Use below code for cakePHP 3.0  or above

```<code> $result = $this->ModelName->save($data)
 echo $result->id;
</code>```

Title: cakephp getLastInsertID / Model->id

Body:
Is  getLastInsertID and Model->id  same? And which one can happen concurrency problem ?

$this->Model->save($this->data);
__thisFunctionTakesAVeryLongTimeToExecute(); //function 1
$insertId = $this->Model->getLastInsertId();

Does getLastInsertId() return the ID from the data I've saved 2 lines above. Or does it return the latest ID that's created?

I mean
what happen if when the function 1 (__thisFunctionTakesAVeryLongTimeToExecute();) execute another user do an another save. then which id will i get?

Body:
Use below code for cakePHP 3.0  or above

 $result = $this->ModelName->save($data)
 echo $result->id;


问:
Python3 use installed modules on another computer
I have downloaded the pycrypto module for python 3, so I Can use AES in my python code. (EG if I have a code called encodeUsingAES.py)

However, this wouldn't work if I just copied encodeUsingAES.py to a different computer and ran it right? Because it doesn't have the pycrypto module installed so it will pop up heaps of errors.

I tried just copying the Crypto folders inside pycrypto into the same directory as my .py file but it didn't work.

Is there anyway for my to have all the files I need in the same directory so when I compress and send the folder the recipient can just run the .py file without having to install extra modules?

Thanks!

```<code>from Crypto import Random
from Crypto.Cipher import AES
</code>```

EDIT:
Tried this didn't work

```<code>import sys
sys.path.append("/pycrypto")
from Crypto import Random
from Crypto.Cipher import AES

$ python3 testCrypto.py
  Traceback (most recent call last):
    File "testCrypto.py", line 5, in <module>
    from Crypto import Random
  ImportError: No module named 'Crypto'
</code>```

or

```<code>import sys
sys.path.append("pycrypto/lib")
from Crypto import Random
from Crypto.Cipher import AES

$ python3 testCrypto.py
  Traceback (most recent call last):
    File "testCrypto.py", line 5, in <module>
      from Crypto import Random
     File "pycrypto/lib/Crypto/Random/__init__.py", line 28, in <module>
      from Crypto.Random import OSRNG
    File "pycrypto/lib/Crypto/Random/OSRNG/__init__.py", line 32, in <module>
      from Crypto.Random.OSRNG.posix import new
    File "pycrypto/lib/Crypto/Random/OSRNG/posix.py", line 66
      except IOError, e:
</code>```

答:
If you copy the complete folder, you should add it to your path to be able to import it.

```<code>import sys
sys.path.append("/path/to/your/crypto/directory")

from Crypto import Random
</code>```

If the pycrypto folder is directly placed in your project folder, following statement should work.

sys.path.append('./pycrypto')

Body:
I have downloaded the pycrypto module for python 3, so I Can use AES in my python code. (EG if I have a code called encodeUsingAES.py)

However, this wouldn't work if I just copied encodeUsingAES.py to a different computer and ran it right? Because it doesn't have the pycrypto module installed so it will pop up heaps of errors.

I tried just copying the Crypto folders inside pycrypto into the same directory as my .py file but it didn't work.

Is there anyway for my to have all the files I need in the same directory so when I compress and send the folder the recipient can just run the .py file without having to install extra modules?

Thanks!

from Crypto import Random
from Crypto.Cipher import AES

EDIT:
Tried this didn't work

import sys
sys.path.append("/pycrypto")
from Crypto import Random
from Crypto.Cipher import AES

$ python3 testCrypto.py
  Traceback (most recent call last):
    File "testCrypto.py", line 5, in <module>
    from Crypto import Random
  ImportError: No module named 'Crypto'

or

import sys
sys.path.append("pycrypto/lib")
from Crypto import Random
from Crypto.Cipher import AES

$ python3 testCrypto.py
  Traceback (most recent call last):
    File "testCrypto.py", line 5, in <module>
      from Crypto import Random
     File "pycrypto/lib/Crypto/Random/__init__.py", line 28, in <module>
      from Crypto.Random import OSRNG
    File "pycrypto/lib/Crypto/Random/OSRNG/__init__.py", line 32, in <module>
      from Crypto.Random.OSRNG.posix import new
    File "pycrypto/lib/Crypto/Random/OSRNG/posix.py", line 66
      except IOError, e:

Body:
If you copy the complete folder, you should add it to your path to be able to import it.

import sys
sys.path.append("/path/to/your/crypto/directory")

from Crypto import Random

If the pycrypto folder is directly placed in your project folder, following statement should work.

sys.path.append('./pycrypto')


答:
The reason why it is not printed is because your for loop ranges from 0 (inclusive) to a.lenth-1 (exclusive). Therefore the loop is not executed for the last element.

You can however not simply set the bound one higher because then the swap will crash (generate an out of bounds exception).

You can solve the problem by simply printing the last element after the loop:

```<code>class test
{

    public static void main(String args[])
    {
        int a[]={5,8,9,7,3};
        int j;

        for(j=0;j<a.length-1;j++)
        {
            if(a[j]>a[j+1])
            {
                int temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
            System.out.print(a[j]+"   "); // last value of array a[4] is not printed
        }
        <b>if(a.length > 0) {
            System.out.print(a[a.length-1]);
        }</b>
    }

}</code>```

Title: how to get the last value of the array variable in loops

Body:
The reason why it is not printed is because your for loop ranges from 0 (inclusive) to a.lenth-1 (exclusive). Therefore the loop is not executed for the last element.

You can however not simply set the bound one higher because then the swap will crash (generate an out of bounds exception).

You can solve the problem by simply printing the last element after the loop:

class test
{

    public static void main(String args[])
    {
        int a[]={5,8,9,7,3};
        int j;

        for(j=0;j<a.length-1;j++)
        {
            if(a[j]>a[j+1])
            {
                int temp=a[j];
                a[j]=a[j+1];
                a[j+1]=temp;
            }
            System.out.print(a[j]+"   "); // last value of array a[4] is not printed
        }
        if(a.length > 0) {
            System.out.print(a[a.length-1]);
        }
    }

}


问:
Can I negate (!) a collection of spring profiles?
Is it possible to configure a bean in such a way that it wont be used by a group of profiles? Currently I can do this (I believe):

```<code>@Profile("!dev, !qa, !local")
</code>```

Is there a neater notation to achieve this? Let's assume I have lots of profiles. Also, if I have a Mock and concrete implementation of some service (or whatever), Can I just annotate one of them, and assume the other will be used in all other cases? In other words, is this, for example, necessary:

```<code>@Profile("dev, prof1, prof2")
public class MockImp implements MyInterface {...}

@Profile("!dev, !prof1, !prof2") //assume for argument sake that there are many other profiles
public class RealImp implements MyInterface {...}
</code>```

Could I just annotate one of them, and stick a @Primary annotation on the other instead?

In essence I want this:

```<code>@Profile("!(dev, prof1, prof2)")
</code>```

Thanks in advance!

答:
Short answer is: You can't in versions of Spring prior to Spring 5.1 (i.e. versions of Spring Boot prior to 2.1).

But there is a neat workarounds that exists thanks to the @Conditional annotation.

Create Condition matchers:

```<code>public static abstract class ProfileCondition extends SpringBootCondition {
    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        if (matchProfiles(conditionContext.getEnvironment())) {
            return ConditionOutcome.match("A local profile has been found.");
        }
        return ConditionOutcome.noMatch("No local profiles found.");
    }

    protected static abstract boolean matchProfiles(final Environment environment);
}

public class DevProfileCondition extends ProfileCondition {
   protected boolean matchProfiles(final Environment environment) {
        return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
            return prof.equals("dev") || prof.equals("prof1") || prof.equals("prof2");
        });
    }
}

public static class ProdProfileCondition extends ProfileCondition {
   protected boolean matchProfiles(final Environment environment) {
        return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
            return (!prof.equals("dev") && !prof.equals("prof1") && !prof.equals("prof2"));
        });
    }
}
</code>```

Use it

```<code>@Conditional(value = {DevProfileCondition.class})
public class MockImpl implements MyInterface {...}

@Conditional(value = {ProdProfileCondition.class})
public class RealImp implements MyInterface {...}
</code>```

However, this aproach requires Springboot.

Body:
Is it possible to configure a bean in such a way that it wont be used by a group of profiles? Currently I can do this (I believe):

@Profile("!dev, !qa, !local")

Is there a neater notation to achieve this? Let's assume I have lots of profiles. Also, if I have a Mock and concrete implementation of some service (or whatever), Can I just annotate one of them, and assume the other will be used in all other cases? In other words, is this, for example, necessary:

@Profile("dev, prof1, prof2")
public class MockImp implements MyInterface {...}

@Profile("!dev, !prof1, !prof2") //assume for argument sake that there are many other profiles
public class RealImp implements MyInterface {...}

Could I just annotate one of them, and stick a @Primary annotation on the other instead?

In essence I want this:

@Profile("!(dev, prof1, prof2)")

Thanks in advance!

Body:
Short answer is: You can't in versions of Spring prior to Spring 5.1 (i.e. versions of Spring Boot prior to 2.1).

But there is a neat workarounds that exists thanks to the @Conditional annotation.

Create Condition matchers:

public static abstract class ProfileCondition extends SpringBootCondition {
    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        if (matchProfiles(conditionContext.getEnvironment())) {
            return ConditionOutcome.match("A local profile has been found.");
        }
        return ConditionOutcome.noMatch("No local profiles found.");
    }

    protected static abstract boolean matchProfiles(final Environment environment);
}

public class DevProfileCondition extends ProfileCondition {
   protected boolean matchProfiles(final Environment environment) {
        return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
            return prof.equals("dev") || prof.equals("prof1") || prof.equals("prof2");
        });
    }
}

public static class ProdProfileCondition extends ProfileCondition {
   protected boolean matchProfiles(final Environment environment) {
        return Arrays.stream(environment.getActiveProfiles()).anyMatch(prof -> {
            return (!prof.equals("dev") && !prof.equals("prof1") && !prof.equals("prof2"));
        });
    }
}

Use it

@Conditional(value = {DevProfileCondition.class})
public class MockImpl implements MyInterface {...}

@Conditional(value = {ProdProfileCondition.class})
public class RealImp implements MyInterface {...}

However, this aproach requires Springboot.


问:
how to integration zoom Chart with angular 2
is this possible to integrate Zoom chart with angular 2need basic idea is anyone done this before , didn't find any thread related to this on Internet that's why i asked here, any clue ?  </p>

答:
1. Description based on angular-seed application

For Angular2 - here are step by step instructions on how to get
  ZoomCharts running within the angular-seed application. Note that they
  only describe the steps to get a sample running within the seed
  application, not the steps required to build fully functional
  component.

1. Copy zoomcharts.d.ts file into /tools/manual_typings/project/
  folder.

2. Modify the zoomcharts.d.ts file to support CommonJS/SystemJS
  module system by adding at the top of it these lines:

declare module "ZoomCharts" {
      export = ZoomCharts; }

3. In the tools\project.config.ts file add this line into the
  constructor (of course, using CDN is optional) to register the library
  with SystemJS loader:

this.addPackagesBundles([{    name: "ZoomCharts",    path:
  "https://cdn.zoomcharts-cloud.com/1/latest/zoomcharts.js"  }]);

4. Create a new component for the chart, for example,
  /src/client/app/home/zc-pie-chart.component.ts

``` /// </p>

  <p>import { Component, OnInit, ViewChild, AfterViewInit, ElementRef }
  from '@angular/core'; import { PieChart } from "ZoomCharts";</p>

  <p>@Component({
      moduleId: module.id,
      selector: "zc-pie-chart",
      template: "PieChart is being initialized..." }) export class ZcPieChart implements AfterViewInit {</p>

```@ViewChild("container")
private container: ElementRef;

ngAfterViewInit() {
    var x = new PieChart({
        container: this.container.nativeElement,
        assetsUrlBase: System.paths["ZoomCharts"] + "/../assets/",
        data: [{
            url: "https://zoomcharts.com/dvsl/data/pie-chart/browsers.json",
        }]
    });
} } ```
</code>```

5. Register the component in the module (in this sample case,
  home.module.ts):

``` import { ZcPieChart } from './zc-pie-chart.component';</p>

  <p>..   declarations: [..other components.., ZcPieChart], .. ```

6. Add it to the view, for example, home.component.html:

<zc-pie-chart></zc-pie-chart>

2. Integration with Webpack

Note: I tested this with Webpack 2.2.1.

With Webpack you can use simple import ZoomCharts from
  './zoomcharts/zoomcharts.js'; and it works fine - including bundling
  of the zoomcharts.js code.

Though in such case ZoomCharts will now load dependencies such as
  moment.js by itself even if they are already included in the webpack
  bundle. To enable loading moment.js from the bundle, I used this
  webpack.config.js file (and using the
  imports-loader
  plugin):

```js var path = require('path');</p>

  <p>module.exports = {
      entry: './index.js',
      output: {
          filename: 'bundle.js',
          path: path.resolve(__dirname)
      },
      resolve: {
          alias: {
              "moment": path.resolve(__dirname, "zoomcharts", "assets", "moment.js"),
              "moment-timezone": path.resolve(__dirname, "zoomcharts", "assets", "moment-tz.js"),
              "zoomcharts": path.resolve(__dirname, "zoomcharts", "zoomcharts.js"),
          }
      },
      module: {
          rules: [
              {
                  test: path.resolve(__dirname, "zoomcharts", "zoomcharts.js"),
                  loader: {
                      loader: "imports-loader",
                      options: {
                          "moment": "moment",
                          "momentTimezone": "moment-timezone",
                          // workaround that sets window.moment as required by zoomcharts.js
                          "_": ">window.moment=moment;"
                      }
                  }
              }
          ],
      } }; ```

Body:
1. Description based on angular-seed application

For Angular2 - here are step by step instructions on how to get
  ZoomCharts running within the angular-seed application. Note that they
  only describe the steps to get a sample running within the seed
  application, not the steps required to build fully functional
  component.

1. Copy zoomcharts.d.ts file into /tools/manual_typings/project/
  folder.

2. Modify the zoomcharts.d.ts file to support CommonJS/SystemJS
  module system by adding at the top of it these lines:

declare module "ZoomCharts" {
      export = ZoomCharts; }

3. In the tools\project.config.ts file add this line into the
  constructor (of course, using CDN is optional) to register the library
  with SystemJS loader:

this.addPackagesBundles([{    name: "ZoomCharts",    path:
  "https://cdn.zoomcharts-cloud.com/1/latest/zoomcharts.js"  }]);

4. Create a new component for the chart, for example,
  /src/client/app/home/zc-pie-chart.component.ts

``` /// </p>

  <p>import { Component, OnInit, ViewChild, AfterViewInit, ElementRef }
  from '@angular/core'; import { PieChart } from "ZoomCharts";</p>

  <p>@Component({
      moduleId: module.id,
      selector: "zc-pie-chart",
      template: "PieChart is being initialized..." }) export class ZcPieChart implements AfterViewInit {</p>

<pre><code>@ViewChild("container")
private container: ElementRef;

ngAfterViewInit() {
    var x = new PieChart({
        container: this.container.nativeElement,
        assetsUrlBase: System.paths["ZoomCharts"] + "/../assets/",
        data: [{
            url: "https://zoomcharts.com/dvsl/data/pie-chart/browsers.json",
        }]
    });
} } ```

5. Register the component in the module (in this sample case,
  home.module.ts):

``` import { ZcPieChart } from './zc-pie-chart.component';</p>

  <p>..   declarations: [..other components.., ZcPieChart], .. ```

6. Add it to the view, for example, home.component.html:

<zc-pie-chart></zc-pie-chart>

2. Integration with Webpack

Note: I tested this with Webpack 2.2.1.

With Webpack you can use simple import ZoomCharts from
  './zoomcharts/zoomcharts.js'; and it works fine - including bundling
  of the zoomcharts.js code.

Though in such case ZoomCharts will now load dependencies such as
  moment.js by itself even if they are already included in the webpack
  bundle. To enable loading moment.js from the bundle, I used this
  webpack.config.js file (and using the
  imports-loader
  plugin):

```js var path = require('path');</p>

  <p>module.exports = {
      entry: './index.js',
      output: {
          filename: 'bundle.js',
          path: path.resolve(__dirname)
      },
      resolve: {
          alias: {
              "moment": path.resolve(__dirname, "zoomcharts", "assets", "moment.js"),
              "moment-timezone": path.resolve(__dirname, "zoomcharts", "assets", "moment-tz.js"),
              "zoomcharts": path.resolve(__dirname, "zoomcharts", "zoomcharts.js"),
          }
      },
      module: {
          rules: [
              {
                  test: path.resolve(__dirname, "zoomcharts", "zoomcharts.js"),
                  loader: {
                      loader: "imports-loader",
                      options: {
                          "moment": "moment",
                          "momentTimezone": "moment-timezone",
                          // workaround that sets window.moment as required by zoomcharts.js
                          "_": ">window.moment=moment;"
                      }
                  }
              }
          ],
      } }; ```


问:
ASP.NET C# foreach only print last item in list
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

```<code>public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);
            }
        }
    }
</code>```

Here is the aspx part:

```<code><div class="admin-page">
      <h1>Valid Links:</h1>
        <asp:Literal ID="ValidLinksBox" runat="server" />
      <h1>Invalid Links:</h1>
        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />
  </div>
</code>```

This is the result:

Validate Links result

答:
replace

```<code>ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";
</code>```

with

```<code>ValidLinksBox.Text += "<br/>" + validPages[i] + "<br/>"; // = replaced by +=
</code>```

to append a string value - currently you're overwriting the content each iteration

Body:
I would like to show all valid links in a Literal Control container after clicking a button. However, only the last item in the list can be shown. I have used both for and foreach loop for testing but still not successful.

Any help is appreciated. Thanks in advance.

Here is my code:

public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ValidateButton.Click += ValidateButtonHandler;
        }

        private void ValidateButtonHandler(object sender, EventArgs e)
        {
            List<string> validPages = new List<string>();
            validPages.Add("www.google.com");
            validPages.Add("www.yahoo.com");
            validPages.Add("www.facebook.com");

            List<string> invalidPages = new List<string>();
            invalidPages.Add("www.gogle.com");
            invalidPages.Add("www.yaoo.com");
            invalidPages.Add("www.facbook.com");

            for (int i = 0; i < validPages.Count; i++)
            {
                ValidLinksBox.Text = "
" + validPages[i] + "
";
            }

            foreach (string invalidPage in invalidPages)
            {
                InvalidLinksBox.Text = string.Format("

{0}

", invalidPage);
            }
        }
    }

Here is the aspx part:

Valid Links:

        <asp:Literal ID="ValidLinksBox" runat="server" />

Invalid Links:

        <asp:Literal ID="InvalidLinksBox" runat="server" />
    <asp:Button ID="ValidateButton" runat="server" CssClass="btn btn-default" Text="Validate links" />

This is the result:

Validate Links result

Body:
replace

ValidLinksBox.Text = "<br/>" + validPages[i] + "<br/>";

with

ValidLinksBox.Text += "<br/>" + validPages[i] + "<br/>"; // = replaced by +=

to append a string value - currently you're overwriting the content each iteration


问:
What is a good design for an interface with optional components?
Suppose I have an interface that supports a few potential operations:

```<code>interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

```<code>interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}
</code>```

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

答:
The simpler solution is to add supports*() methods,

If you think that is not good style, then just forget about Frobnicator (it gives you very little as it is not an interface you can rely on) and code directly against FooFrobnicator and BarFrobnicator, and if they happen to be implemented by the same object, fine. This also gives you the possibility of requiring a specific interface in client code:

```<code>interface FooFrobnicator {
    doFoo();
}

interface BarFrobnicator {
    doBar();
}

public class Client {
     ...
     FooFrobnicator fooFrobnicator;
     public void setFooFrobnicator(FooFrobnicator fooFrobnicator) {
         this.fooFrobnicator = fooFrobnicator;
     }

     BarFrobnicator barFrobnicator;
     public void setBarFrobnicator(BarFrobnicator barFrobnicator) {
         this.barFrobnicator = barFrobnicator;
     }
     ...
     public void doSomething() {
         ...
         if (fooFrobnicator != null) { ... }
         ...
         if (barFrobnicator != null) { ... }
     }
}
...
public class FrobnicatorImpl implements FooFrobnicator, BarFrobnicator { ... }
...
public void doSomething() {
    ...
    FrobnicatorImpl impl = new FrobnicatorImpl();
    Client client = new Client();
    client.setFooFrobnicator(impl);
    client.setBarFrobnicator(impl);
    ...
}
</code>```

Body:
Suppose I have an interface that supports a few potential operations:

interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

Body:
The simpler solution is to add supports*() methods,

If you think that is not good style, then just forget about Frobnicator (it gives you very little as it is not an interface you can rely on) and code directly against FooFrobnicator and BarFrobnicator, and if they happen to be implemented by the same object, fine. This also gives you the possibility of requiring a specific interface in client code:

interface FooFrobnicator {
    doFoo();
}

interface BarFrobnicator {
    doBar();
}

public class Client {
     ...
     FooFrobnicator fooFrobnicator;
     public void setFooFrobnicator(FooFrobnicator fooFrobnicator) {
         this.fooFrobnicator = fooFrobnicator;
     }

     BarFrobnicator barFrobnicator;
     public void setBarFrobnicator(BarFrobnicator barFrobnicator) {
         this.barFrobnicator = barFrobnicator;
     }
     ...
     public void doSomething() {
         ...
         if (fooFrobnicator != null) { ... }
         ...
         if (barFrobnicator != null) { ... }
     }
}
...
public class FrobnicatorImpl implements FooFrobnicator, BarFrobnicator { ... }
...
public void doSomething() {
    ...
    FrobnicatorImpl impl = new FrobnicatorImpl();
    Client client = new Client();
    client.setFooFrobnicator(impl);
    client.setBarFrobnicator(impl);
    ...
}


问:
Android back button app is not closing
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice</p>

```<code>  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }
</code>```

答:
keep a boolean toClose=false;
and in onBackPressed() method use this code</p>

```<code>if (toClose)
    super.onBackPressed();
    else
    {
        toClose=true;
        Utils.showToast(context,getString(R.string.back_again));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                toClose=false;
            }
        },2000);
    }
</code>```

Title: Android back button app is not closing

Body:
i am using the below code for back button but it cant work it does not exit the app if i am pressing the back button of userdevice

  private Boolean exit = false;

        @Override
        public void onBackPressed() {
            if (exit) {
                this.finish(); // finish activity
            } else {
                Toast.makeText(this, "Press Back again to Exit.",
                        Toast.LENGTH_SHORT).show();
                exit = true;
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        exit = false;
                    }
                }, 3 * 1000);

            }

        }

Body:
keep a boolean toClose=false;
and in onBackPressed() method use this code

if (toClose)
    super.onBackPressed();
    else
    {
        toClose=true;
        Utils.showToast(context,getString(R.string.back_again));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                toClose=false;
            }
        },2000);
    }


问:
Excluding specific iPhone types from App Store submission
I created a SpriteKit game that needs large screen area to be played so I decided not to write the code for the iPhone SE, but now I'm not sure if I can submit it to the App Store for all devices except the SE. Please let me know whether it's possible, and if so how to do it (i.e. where on iTunes Connect would you do it).

I looked up a lot but I couldn't find anything that could help.
I also couldn't find anything in the API.

答:
Apple filters your app on 2 bases -

iOS Version

Universal or iPhone/iPad

You can not avoid any specific iPhone model based on the screen size if you have created an app for iPhone.


答:
You have to append text otherwise it'll replace all text and print last text

You can do something like below or you can use StringBuilder to append texts and than set InvalidLinksBox's text

```<code>InvalidLinksBox.Text += string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);
</code>```

Using StringBuilder it contains appendformat method as well for more info go to that official link

```<code>StringBuilder str = new StringBuilder();
foreach (string invalidPage in invalidPages)
{
   str.Append(string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage));
}
InvalidLinksBox.Text = str;
</code>```

Title: ASP.NET C# foreach only print last item in list

Body:
You have to append text otherwise it'll replace all text and print last text

You can do something like below or you can use StringBuilder to append texts and than set InvalidLinksBox's text

InvalidLinksBox.Text += string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage);

Using StringBuilder it contains appendformat method as well for more info go to that official link

StringBuilder str = new StringBuilder();
foreach (string invalidPage in invalidPages)
{
   str.Append(string.Format("<div class=\"alert success\"><p>{0}</p></div>", invalidPage));
}
InvalidLinksBox.Text = str;


答:
Change Your Code Like This.  </p>

```<code> private Boolean exit = false;

            @Override
            public void onBackPressed() {
                if (exit) {
                    this.finishAffinity();
                } else {
                    Toast.makeText(this, "Press Back again to Exit.",
                            Toast.LENGTH_SHORT).show();
                    exit = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;
                        }
                    }, 3 * 1000);

                }

            }
</code>```

Title: Android back button app is not closing

Body:
Change Your Code Like This.

 private Boolean exit = false;

            @Override
            public void onBackPressed() {
                if (exit) {
                    this.finishAffinity();
                } else {
                    Toast.makeText(this, "Press Back again to Exit.",
                            Toast.LENGTH_SHORT).show();
                    exit = true;
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            exit = false;
                        }
                    }, 3 * 1000);

                }

            }


问:
Select column based on input enum parameter
I have table with columns

```<code>Id | UserId | GoogleEnabled | FacebookEnabled | TwitterEnabled
</code>```

In code I want to select value of {provider}Enabled value - true/false base on input enum

```<code>enum Provider
{
   Google,
   Facebook,
   Twitter
}

private async Task CheckSettingsAsync(ISeedSession<IDbSession> seedSession, IUserInfo user, Provider provider){
...
var userSettingsTask = seedSession
                .Query<UserSettings>()
                .Where(us => us.UserId == user.UserId)
                .Select(us => us.GoogleEnabled) // if provider value is "Google"
                .SingleAsync();
...
}
</code>```

Is there any pattern/solution better than create some switch to select my value?

答:
You can build expression us => us.GoogleEnabled manually, like this:

```<code>var argument = Expression.Variable(typeof(UserSettings));
// assuming `provider` is enum with values "Google" etc
var accessor = (Expression<Func<UserSettings, bool>>) Expression.Lambda(
    Expression.PropertyOrField(argument, provider.ToString() + "Enabled"), argument);
</code>```

And then use it like this:

```<code>var userSettingsTask = seedSession
   .Query<UserSettings>()
   .Where(us => us.UserId == user.UserId)
   .Select(accessor) // < here
   .SingleAsync();
</code>```

Body:
I have table with columns

Id | UserId | GoogleEnabled | FacebookEnabled | TwitterEnabled

In code I want to select value of {provider}Enabled value - true/false base on input enum

enum Provider
{
   Google,
   Facebook,
   Twitter
}

private async Task CheckSettingsAsync(ISeedSession<IDbSession> seedSession, IUserInfo user, Provider provider){
...
var userSettingsTask = seedSession
                .Query<UserSettings>()
                .Where(us => us.UserId == user.UserId)
                .Select(us => us.GoogleEnabled) // if provider value is "Google"
                .SingleAsync();
...
}

Is there any pattern/solution better than create some switch to select my value?

Body:
You can build expression us => us.GoogleEnabled manually, like this:

var argument = Expression.Variable(typeof(UserSettings));
// assuming `provider` is enum with values "Google" etc
var accessor = (Expression<Func<UserSettings, bool>>) Expression.Lambda(
    Expression.PropertyOrField(argument, provider.ToString() + "Enabled"), argument);

And then use it like this:

var userSettingsTask = seedSession
   .Query<UserSettings>()
   .Where(us => us.UserId == user.UserId)
   .Select(accessor) // < here
   .SingleAsync();


问:
Full-calendar - combine Years view and language change
I'm trying to change language in FullCalendar with year view. I got 2 examples for Years view and Language support here :Lang support , Year View

Problem is - i can't get both to work together... I've tried to load both file like this :

```<code><script src='js/fullcalendar.min.js'></script>// years support
<script src='js/old/fullcalendar.js'></script>// Lang support
</code>```

And i also tried combining the code manually - but i found it time consuming and not so efficient....

Thanks.

答:
You do not need js/old/fullcalendar.js, as you are using newer minified version of js lib.

Using new and old two js libs of same plugin is highly avoidable as it may create conflicts and you may end up with two implementation/versions of a function.

They have provided base library, this contains year view, refer Year Demo

For language they are using another js lang-all.js with base fullcalendar.min.js and it perfectly working, refer Language and Year Demo

```<code><script src='../lang-all.js'></script>
</code>```

Body:
I'm trying to change language in FullCalendar with year view. I got 2 examples for Years view and Language support here :Lang support , Year View

Problem is - i can't get both to work together... I've tried to load both file like this :

// years support
// Lang support

And i also tried combining the code manually - but i found it time consuming and not so efficient....

Thanks.

Body:
You do not need js/old/fullcalendar.js, as you are using newer minified version of js lib.

Using new and old two js libs of same plugin is highly avoidable as it may create conflicts and you may end up with two implementation/versions of a function.

They have provided base library, this contains year view, refer Year Demo

<script src='../fullcalendar.min.js'></script>

For language they are using another js lang-all.js with base fullcalendar.min.js and it perfectly working, refer Language and Year Demo

<script src='../lang-all.js'></script>


问:
Set and get checked boxes in MultiSelectListPreference
I'm defining the MultiSelectListPreference in my axml file like this:

```<code> <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>
</code>```

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

答:
If someone stumbles across this question, here is how i solved it:

Read (the async part is pretty ugly, but I don't know how to add a 'preferenceChangeD' event)

```<code>private async void preferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
     await System.Threading.Tasks.Task.Delay(100);

     List<string> sList = new List<string>();
     ICollection<string> selectedValues = mslp_dutyMarks.Values;
     foreach(string x in selectedValues)
          sList.Add(x);
}
</code>```

Write

```<code>mslp_dutyMarks.Values = new List<string> { "A", "B", "C" };
</code>```

Body:
I'm defining the MultiSelectListPreference in my axml file like this:

 <MultiSelectListPreference
        android:title="Title"
        android:summary="Sum"
        android:key="dutyMarks"
        android:entries="@array/array_marks"
        android:entryValues="@array/array_marksValues">
 </MultiSelectListPreference>

How can check / read the checked boxes in code?

I tried to get the checked values via the PreferenceChange event:

The checked values appear there, but I have no idea how to get them...

Body:
If someone stumbles across this question, here is how i solved it:

Read (the async part is pretty ugly, but I don't know how to add a 'preferenceChangeD' event)

private async void preferenceChange(object sender, Preference.PreferenceChangeEventArgs e)
{
     await System.Threading.Tasks.Task.Delay(100);

     List<string> sList = new List<string>();
     ICollection<string> selectedValues = mslp_dutyMarks.Values;
     foreach(string x in selectedValues)
          sList.Add(x);
}

Write

mslp_dutyMarks.Values = new List<string> { "A", "B", "C" };


问:
Do class properties get overwritten on extended classes?
Say for example I have two classes A and B:

A:

```<code>class A {
    private $name = "Joe";
}
</code>```

B:

```<code>class B extends A {
       private $name = "Scotto";
}
</code>```

What will the value of $name be? Does it overwrite the parent class property or will it be it's on instance if instantiated? Any help would be great, thanks!

答:
I would suggest specifically reading this comment on the documentation pages. The focus is on methods, but it's the same for properties

... private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them.

Your example:

```<code>class A {
  private $name = "Joe";

  public function getName() {
    return $this->name;
  }
}

class B extends A {
  private $name = "Scotto";
}

class C extends A {
  private $name = "Scotto";

  public function getName() {
    return $this->name;
  }
}

$a = new A;
$b = new B;
$c = new C;

$a->getName(); // 'Joe'
$b->getName(); // 'Joe'
$c->getName(); // 'Scotto'
</code>```

Body:
Say for example I have two classes A and B:

A:

class A {
    private $name = "Joe";
}

B:

class B extends A {
       private $name = "Scotto";
}

What will the value of $name be? Does it overwrite the parent class property or will it be it's on instance if instantiated? Any help would be great, thanks!

Body:
I would suggest specifically reading this comment on the documentation pages. The focus is on methods, but it's the same for properties

... private methods are visible only for the class that defines them and the child class does not see the parent's private methods. If the child doesn't see the parent's private methods, the child can't override them.

Your example:

class A {
  private $name = "Joe";

  public function getName() {
    return $this->name;
  }
}

class B extends A {
  private $name = "Scotto";
}

class C extends A {
  private $name = "Scotto";

  public function getName() {
    return $this->name;
  }
}

$a = new A;
$b = new B;
$c = new C;

$a->getName(); // 'Joe'
$b->getName(); // 'Joe'
$c->getName(); // 'Scotto'


问:
Make UITextField accept small alphabet letter only in Swift?
I Want to Make textField that accept only small alphabet letter not capital alphabet letter or no any special symbol or not any digit.</p>

答:
To restrict Caps letters, Digits & Special symbols, return false other than small letters in text view delegate method textField:shouldChangeCharactersInRange:.

Swift 3.0:

```<code> func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var myCharSet = CharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz")
        for i in 0..<(string.characters.count ?? 0) {
            var c: unichar = string[i]
            if !myCharSet.characterIsMember(c) {
                return false
            }
        }
        return true
    }
</code>```

Body:
To restrict Caps letters, Digits & Special symbols, return false other than small letters in text view delegate method textField:shouldChangeCharactersInRange:.

Swift 3.0:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var myCharSet = CharacterSet(charactersInString: "abcdefghijklmnopqrstuvwxyz")
        for i in 0..<(string.characters.count ?? 0) {
            var c: unichar = string[i]
            if !myCharSet.characterIsMember(c) {
                return false
            }
        }
        return true
    }


问:
Tooltips for high points on low-height charts not displaying
I have a problem with tooltips not showing depending on the size of the chart/browser window. This originally looked to me like a problem with facet charts but the behaviour is also evident on regular/single charts. I've done a lot of searching for this and not found anything so far. There is a similar post over on plotly forums with no answers as of yet.

Here is an MRE for a single chart (HT)...

```<code>require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )

df1$tooltip <- sprintf("x: %s<br>y: %s<br>z: %s<br>2x: %s<br>2y: %s<br>2z: %s<br>3x: %s<br>3y: %s<br>3z: %s"
                                        ,df1$x, df1$y, df1$z, df1$x, df1$y, df1$z, df1$x, df1$y, df1$z)

g = ggplot(df1, aes(x,y,fill=z, text = tooltip)) +
        geom_tile()

ggplotly(g, tooltip = "tooltip")
</code>```

If you resize the browser window to a small enough height you will notice that the tooltip will not be displayed when hovering over the tiles near the top of the chart. The problem appears to be that the tooltip is too tall to display whereby the hover position would place the top of the tooltip box outside the top of the chart. This kind of makes sense even if problematic. However, this MRE example is a bit contrived and unrealistic.

This behaviour becomes a real issue on a facet chart with a large number of facets requiring tooltips. Here is an MRE for a facet chart. Even with a maximised browser window the same tooltip issue is evident.

```<code>require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))
facet_var = replicate(12, randomName(2))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )
df1 <- merge(x = facet_var, y = df1, by = NULL)

#df1$tooltip <- sprintf("x: %s<br>y: %s<br>z: %s<br>x+x: %s<br>y+y: %s<br>z+z: %s"
df1$tooltip <- sprintf("facet: %s<br>x: %s<br>y: %s<br>z: %s<br>2x: %s<br>2y: %s<br>2z: %s<br>3x: %s<br>3y: %s<br>3z: %s"
                                        ,df1$x.x, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z)

g = ggplot(df1, aes(x.y,y,fill=z, text = tooltip)) +
        geom_tile() +
        facet_wrap(~x.x, ncol=2)

ggplotly(g, tooltip = "tooltip")
</code>```

This issue exists both for default and bespoke tooltips - tested in Chrome(v56) and Edge(v38).

I had an earlier question posted on SO regarding this issue but my analysis was off the mark, and my example not an MRE, and I have closed/answered that question since.

I could reduce the number of lines in the tooltip to obviate the problem but I'd prefer not to have to do that. Is this a known feature or is there a workaround for this behaviour?

答:
The only way that I can see of working around this behaviour is to ensure that the tootip is no more that 1 or two lines deep which is, I suppose, what the intention of a tooltip is in the first place! That is what I am going to go with.

I was hoping to elaborate on the "tooltip" to have a nicely formatted tooltip containing a td/table. Maybe there is an alternative approach to achieving this effect?

Body:
I have a problem with tooltips not showing depending on the size of the chart/browser window. This originally looked to me like a problem with facet charts but the behaviour is also evident on regular/single charts. I've done a lot of searching for this and not found anything so far. There is a similar post over on plotly forums with no answers as of yet.

Here is an MRE for a single chart (HT)...

require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )

df1$tooltip <- sprintf("x: %s
y: %s
z: %s
2x: %s
2y: %s
2z: %s
3x: %s
3y: %s
3z: %s"
                                        ,df1$x, df1$y, df1$z, df1$x, df1$y, df1$z, df1$x, df1$y, df1$z)

g = ggplot(df1, aes(x,y,fill=z, text = tooltip)) +
        geom_tile()

ggplotly(g, tooltip = "tooltip")

If you resize the browser window to a small enough height you will notice that the tooltip will not be displayed when hovering over the tiles near the top of the chart. The problem appears to be that the tooltip is too tall to display whereby the hover position would place the top of the tooltip box outside the top of the chart. This kind of makes sense even if problematic. However, this MRE example is a bit contrived and unrealistic.

This behaviour becomes a real issue on a facet chart with a large number of facets requiring tooltips. Here is an MRE for a facet chart. Even with a maximised browser window the same tooltip issue is evident.

require(ggplot2)
require(plotly)

randomName <- function(n) {
    random.string <- rep(NA, n)
    randomizeString <- function(x) {
        a <-sample(letters, 1, replace = TRUE)
        return(a)
    }
    return(paste(c(sapply(random.string, randomizeString, simplify = TRUE)), collapse = ""))
}

xvar = replicate(10, randomName(15))
facet_var = replicate(12, randomName(2))

df1 <- data.frame(x = xvar, y = xvar, z = runif(10) )
df1 <- merge(x = facet_var, y = df1, by = NULL)

#df1$tooltip <- sprintf("x: %s
y: %s
z: %s
x+x: %s
y+y: %s
z+z: %s"
df1$tooltip <- sprintf("facet: %s
x: %s
y: %s
z: %s
2x: %s
2y: %s
2z: %s
3x: %s
3y: %s
3z: %s"
                                        ,df1$x.x, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z, df1$x.y, df1$y, df1$z)

g = ggplot(df1, aes(x.y,y,fill=z, text = tooltip)) +
        geom_tile() +
        facet_wrap(~x.x, ncol=2)

ggplotly(g, tooltip = "tooltip")

This issue exists both for default and bespoke tooltips - tested in Chrome(v56) and Edge(v38).

I had an earlier question posted on SO regarding this issue but my analysis was off the mark, and my example not an MRE, and I have closed/answered that question since.

I could reduce the number of lines in the tooltip to obviate the problem but I'd prefer not to have to do that. Is this a known feature or is there a workaround for this behaviour?


问:
Git: How to solve Permission denied (publickey) error when using Git?
I'm on Mac Snow Leopard and I just installed git.

I just tried

```<code>git clone git@thechaw.com:cakebook.git
</code>```

but that gives me this error:

```<code>Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
</code>```

What am I missing?

I've also tried doing ssh-keygen with no passphase but still same error.

答:
I was able to get over this issue by following below steps in my ubuntu system. As i was experimenting with passwordless ssh to the system.

sudo vi /etc/ssh/sshd_config

1) Commented below :
   #Change to no to disable tunnelled clear text passwords
   #PasswordAuthentication yes
    PasswordAuthentication no ----> commented this.

2) Then restarted the sshd daemon as below.

service sshd restart

Body:
I'm on Mac Snow Leopard and I just installed git.

I just tried

git clone git@thechaw.com:cakebook.git

but that gives me this error:

Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

What am I missing?

I've also tried doing ssh-keygen with no passphase but still same error.


问:
Android add shortcut icon from a url instead from drawable resources
I have an app where i am adding shortcut. I want to add shortcut icon image from URL path(images are stored on server and can be change) instead of using Drawable but i don't know how to do that. I tried to find a lot on this community. Any help?</p>

答:
add this in your build.gradle

```<code>compile 'com.squareup.picasso:picasso:2.5.2'
</code>```

now you can load the image using following code

```<code>Picaso.with(this).load(urlHere).into(imageView);
</code>```

Body:
add this in your build.gradle

compile 'com.squareup.picasso:picasso:2.5.2'

now you can load the image using following code

Picaso.with(this).load(urlHere).into(imageView);


问:
Singletons to facilate unit tests in a legacy code base. A good idea or not?
Folks,
    I've a large legacy .Net code base, and I'm trying to introduce Unit Testing to the team. They're good guys but this is all new to them (to be honest it's reasonably new to me too).

One of the problems is the code base makes heavy use of static classes in System.IO, there are extensive in-house libraries of static classes and classes aren't written to interfaces (unless there's an actual design reason to do so).

I'm developing an ease-it-in strategy using NUnit and FakeItEasy.

To address the static class dependencies I've written a tool that generates wrapper classes and interfaces for existing Static Classes. e.g. In a config file I say I want wrappers for System.IO Directory & File, the tool generates an assembly with code along the lines of . . .

```<code>public interface IFile
{
    // All Method signatures taken from System.IO.File
}

internal class File
    : IFile
{
    // All Methods delegate to System.IO.File
}

public interface IIO
{
    IFile File {get;}
    IDirectory Directory {get;}
}

internal class IO
    : IIO
{
    public IFile File {get; private set;}
    public IDirectory Directory {get; private set;}
    public IO()
    {
        File = new File();
        Directory = new Directory();
    }
}

public static class IO
{
    public IIO Instance {get; set;}
    static IO()
    {
        Instance = new IO();
    }
}
</code>```

The idea is that in the existing code base can be simply updated by a find/replace and adding a new project reference, and that in unit tests you can assign a Mock object to IO.Instance.

One one hand I'm quite happy with this approach, it gives a clean and fast way to move away from using static classes directly, plus gives us a way to mock those static classes and lets us test code that depends on them.

On the other hand, I kind of feel I've done a deal with the devil, I've replaced dependencies on implicit singletons with dependencies on explicit singletons.

Is this all going to go horribly wrong for me sometime in the near future, or do you think this is a workable approach?

答:
I would do as you did for a legacy application. Not much you can do without having to refactor larger pieces. It's still flexible since you can change implementation through the static class.

One idea could be to only make the Instance method static and register the IO class in your IOC instead (as a singleton). Then let the IOC find the correct implementation (which is returned by the static Instance method).

Nice introduction to IoC containers: http://joelabrahamsson.com/entry/inversion-of-control-introduction-with-examples-in-dotnet

Body:
Folks,
    I've a large legacy .Net code base, and I'm trying to introduce Unit Testing to the team. They're good guys but this is all new to them (to be honest it's reasonably new to me too).

One of the problems is the code base makes heavy use of static classes in System.IO, there are extensive in-house libraries of static classes and classes aren't written to interfaces (unless there's an actual design reason to do so).

I'm developing an ease-it-in strategy using NUnit and FakeItEasy.

To address the static class dependencies I've written a tool that generates wrapper classes and interfaces for existing Static Classes. e.g. In a config file I say I want wrappers for System.IO Directory & File, the tool generates an assembly with code along the lines of . . .

public interface IFile
{
    // All Method signatures taken from System.IO.File
}

internal class File
    : IFile
{
    // All Methods delegate to System.IO.File
}

public interface IIO
{
    IFile File {get;}
    IDirectory Directory {get;}
}

internal class IO
    : IIO
{
    public IFile File {get; private set;}
    public IDirectory Directory {get; private set;}
    public IO()
    {
        File = new File();
        Directory = new Directory();
    }
}

public static class IO
{
    public IIO Instance {get; set;}
    static IO()
    {
        Instance = new IO();
    }
}

The idea is that in the existing code base can be simply updated by a find/replace and adding a new project reference, and that in unit tests you can assign a Mock object to IO.Instance.

One one hand I'm quite happy with this approach, it gives a clean and fast way to move away from using static classes directly, plus gives us a way to mock those static classes and lets us test code that depends on them.

On the other hand, I kind of feel I've done a deal with the devil, I've replaced dependencies on implicit singletons with dependencies on explicit singletons.

Is this all going to go horribly wrong for me sometime in the near future, or do you think this is a workable approach?


问:
After installing my files on ubuntu apache server it stops working
I have a ubuntu server. I installed Apache there, added my files and after that I don't get any error just it can't connect to the address. (For my files I had to enable .htaccess as well). I'll add here the .htaccess, but the error still is there even if I deleted the .htaccess file.

```<code>RewriteEngine on
RewriteRule ^(\w+)$ index.php?page=$1 [L,NC,QSA]
RewriteRule ^(\w+)+\/$ index.php?page=$1 [L,NC,QSA]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

order allow,deny
allow from all
</code>```

I also have a vendor/autoload.php there I'm not sure if I have to install something for that to make it work 100%.

Apache error log

```<code>[Mon Apr 03 18:25:51.487006 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487042 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^(\\w+)$' to uri ''
[Mon Apr 03 18:25:51.487047 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487050 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^(\\w+)+\\/$' to uri ''
[Mon Apr 03 18:25:51.487053 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487055 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^' to uri ''
[Mon Apr 03 18:25:51.487061 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='EXAMPLE.com' pattern='!^$' => matched
[Mon Apr 03 18:25:51.487065 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='EXAMPLE.com' pattern='!^www\\.' [NC] => matched
[Mon Apr 03 18:25:51.487069 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='offs' pattern='^on(s)|' => matched
[Mon Apr 03 18:25:51.487077 2017] [rewrite:trace2] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] rewrite '' -> 'http://www.EXAMPLE.com/'
[Mon Apr 03 18:25:51.487081 2017] [rewrite:trace2] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] explicitly forcing redirect with http://www.EXAMPLE.com/
[Mon Apr 03 18:25:51.487084 2017] [rewrite:trace1] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] escaping http://www.EXAMPLE.com/ for redirect
[Mon Apr 03 18:25:51.487090 2017] [rewrite:trace1] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] redirect to http://www.EXAMPLE.com/ [REDIRECT/301]
</code>```

答:
First I'd suggest to change your .htaccess-file:

```<code>RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule .? https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^(.*)$ index.php?page=$1 [P,L,NC,QSA]
</code>```

That should do the same you tried to achieve with your config, but in the right order and clean syntax.

Also lost

```<code>order allow,deny
allow from all
</code>```

since it doesn't provide any benefit here. Probably you defined a DocumentRoot somewhere and you have to put this 'order,allow'-part into the directory-directive for your DocumentRoot, for example:

```<code>DocumentRoot "/srv/www/htdocs"

<Directory "/srv/www/htdocs">
  Options Indexes FollowSymLinks
  AllowOverride None
  Order allow,deny
  Allow from all
</Directory>
</code>```

If there are errors or non-functionality left, increase your 'LogLevel' in error.log to warn or even info, restart and check the error.log

Body:
I have a ubuntu server. I installed Apache there, added my files and after that I don't get any error just it can't connect to the address. (For my files I had to enable .htaccess as well). I'll add here the .htaccess, but the error still is there even if I deleted the .htaccess file.

RewriteEngine on
RewriteRule ^(\w+)$ index.php?page=$1 [L,NC,QSA]
RewriteRule ^(\w+)+\/$ index.php?page=$1 [L,NC,QSA]
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

order allow,deny
allow from all

I also have a vendor/autoload.php there I'm not sure if I have to install something for that to make it work 100%.

Apache error log

[Mon Apr 03 18:25:51.487006 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487042 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^(\\w+)$' to uri ''
[Mon Apr 03 18:25:51.487047 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487050 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^(\\w+)+\\/$' to uri ''
[Mon Apr 03 18:25:51.487053 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] strip per-dir prefix: /var/www/ ->
[Mon Apr 03 18:25:51.487055 2017] [rewrite:trace3] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] applying pattern '^' to uri ''
[Mon Apr 03 18:25:51.487061 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='EXAMPLE.com' pattern='!^$' => matched
[Mon Apr 03 18:25:51.487065 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='EXAMPLE.com' pattern='!^www\\.' [NC] => matched
[Mon Apr 03 18:25:51.487069 2017] [rewrite:trace4] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] RewriteCond: input='offs' pattern='^on(s)|' => matched
[Mon Apr 03 18:25:51.487077 2017] [rewrite:trace2] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] rewrite '' -> 'http://www.EXAMPLE.com/'
[Mon Apr 03 18:25:51.487081 2017] [rewrite:trace2] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] explicitly forcing redirect with http://www.EXAMPLE.com/
[Mon Apr 03 18:25:51.487084 2017] [rewrite:trace1] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] escaping http://www.EXAMPLE.com/ for redirect
[Mon Apr 03 18:25:51.487090 2017] [rewrite:trace1] [pid 53934] mod_rewrite.c(468): [client 127.0.0.1:63842] 127.0.0.1 - - [EXAMPLE.com/sid#7fc536e48158][rid#7fc536d8e0a0/initial] [perdir /var/www/] redirect to http://www.EXAMPLE.com/ [REDIRECT/301]

Body:
First I'd suggest to change your .htaccess-file:

RewriteEngine on

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .? https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} off
RewriteRule .? https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteRule ^(.*)$ index.php?page=$1 [P,L,NC,QSA]

That should do the same you tried to achieve with your config, but in the right order and clean syntax.

Also lost

order allow,deny
allow from all

since it doesn't provide any benefit here. Probably you defined a DocumentRoot somewhere and you have to put this 'order,allow'-part into the directory-directive for your DocumentRoot, for example:

DocumentRoot "/srv/www/htdocs"

<Directory "/srv/www/htdocs">
  Options Indexes FollowSymLinks
  AllowOverride None
  Order allow,deny
  Allow from all
</Directory>

If there are errors or non-functionality left, increase your 'LogLevel' in error.log to warn or even info, restart and check the error.log


问:
Replace character depend on the data
```<code>$defaultdata = "abcdef00000000000000000000000000";

$data1 = "271";

$output = "abcdef00000000000000000000000271";
</code>```

How can I replace the string based on the data. For example, if the default data is abcdef00000000000000000000000000 , so it will replace when the data1 got value. So the output will be abcdef00000000000000000000000271. How can I do this?

答:
I think the easiest way to solve this is to use str_pad. It is a built in function made to tackle situations like yours. Then you can easly swap defaultdata to something other. The code is as follow:

```<code>$output = str_pad($data1, strlen($defaultdata), $defaultdata, STR_PAD_LEFT);
</code>```

Title: Replace character depend on the data

Body:
$defaultdata = "abcdef00000000000000000000000000";

$data1 = "271";

$output = "abcdef00000000000000000000000271";

How can I replace the string based on the data. For example, if the default data is abcdef00000000000000000000000000 , so it will replace when the data1 got value. So the output will be abcdef00000000000000000000000271. How can I do this?

Body:
I think the easiest way to solve this is to use str_pad. It is a built in function made to tackle situations like yours. Then you can easly swap defaultdata to something other. The code is as follow:

$output = str_pad($data1, strlen($defaultdata), $defaultdata, STR_PAD_LEFT);