问:
How to pass values to IN operator dynamically?
I want to create a procedure which accepts an array list for IN operator.

For eg:

```<code>Create or Replace Procedure Test (a Arraylist)
{
Select * from table1 where col1 IN (Arraylist)
}
</code>```

If the procedure is called using two parameters then the query should be

```<code>Select * from table1 where col1 IN (val1,val2)
</code>```

If the procedure is called using one parameter then the query should be

```<code>Select * from table1 where col1 IN (val1)
</code>```

答:
Create a collection type:

```<code>CREATE TYPE stringlist IS TABLE OF VARCHAR2(100);
/
</code>```

Then you can pass it to a procedure and use the MEMBER OF operator (rather than the IN operator):

```<code>CREATE PROCEDURE Test (
  in_list     IN  stringlist,
  out_results OUT SYS_REFCURSOR
)
IS
BEGIN
  OPEN out_results FOR
  SELECT *
  FROM   your_table
  WHERE  your_column MEMBER OF in_list;
END;
/
</code>```

If you are connecting from an external language then you can quite easily pass an array to the procedure (Java example) or you can create the list in PL/SQL or from a delimited list.

Body:
I want to create a procedure which accepts an array list for IN operator.

For eg:

Create or Replace Procedure Test (a Arraylist)
{
Select * from table1 where col1 IN (Arraylist)
}

If the procedure is called using two parameters then the query should be

Select * from table1 where col1 IN (val1,val2)

If the procedure is called using one parameter then the query should be

Select * from table1 where col1 IN (val1)

Body:
Create a collection type:

CREATE TYPE stringlist IS TABLE OF VARCHAR2(100);
/

Then you can pass it to a procedure and use the MEMBER OF operator (rather than the IN operator):

CREATE PROCEDURE Test (
  in_list     IN  stringlist,
  out_results OUT SYS_REFCURSOR
)
IS
BEGIN
  OPEN out_results FOR
  SELECT *
  FROM   your_table
  WHERE  your_column MEMBER OF in_list;
END;
/

If you are connecting from an external language then you can quite easily pass an array to the procedure (Java example) or you can create the list in PL/SQL or from a delimited list.


来源: stackexchange

问:
Codeigniter - multiple checkbox values returns NULL
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

```<code>public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}
</code>```

Controller (view_leave)

```<code>$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');
</code>```

PHP/HTML (view_leave.php)

```<code><form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."<br/>";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>
</code>```

Controller (update_leave)

```<code>$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value
</code>```

Why and how can I check for the checkbox values?

Please help.

Thanks!

答:
my Sample work out

my controller

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

        if($this->input->post())
        {
            echo "```"; print_r($this->input->post()); exit();
        }

        $this->load->view('workout');
    }
```

<p>myview</p>

```<form name="customers" id="customers" method="post" action="<?php echo base_url(); ?>welcome/workout"  enctype="multipart/form-data"   >

<input type='checkbox' name='leave_types[]' value='1'>1

<input type='checkbox' name='leave_types[]' value='2'>2

<input type='checkbox' name='leave_types[]' value='3'>3

<input type='checkbox' name='leave_types[]' value='4'>4

<input type='checkbox' name='leave_types[]' value='5'>5

<input type='submit' name='submit' value='Submit'>Submit

    </form>
```

<p>and when i run this my output is </p>

```Array
(
    [leave_types] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [submit] => Submit
)
```

Try this Hope it helps. :)

ContentLicense: CC BY-SA 3.0

Body:
I have multiple check boxes from my View but it returns NULL value when passed to Controller.

I've searched (here, and here, and from other sites) for all possible answers to my problem but nothing helped.

Here are some of my CI codes:

Model (My_Model)

public function get_query_array($query_statement)
{
    $query = $this->db->query($query_statement);
    return $query->result();
}

Controller (view_leave)

$data["leave_list"] = $this->My_Model->get_query_array("SELECT * FROM Leave_List WHERE Leave_Status='ACTIVE'");

$this->load->view('header_view');
$this->load->view('view_leave', $data);
$this->load->view('footer_view');

PHP/HTML (view_leave.php)

<form role="form" method="post" action="<?php echo base_url();?>index.php/home/update_leave" >
<?php
    // assign all leave data into checkboxes and will be submitted to /updated_leave
    foreach($leave_list as $row)
    {
       echo "<input type='checkbox' name='leave_types[]' value='".$row->Leave_Code."'> ".$row->Leave_Description."
";
    }
?>
<input type="submit" value="Submit" name="submit_form" id="submit_form">
</form>

Controller (update_leave)

$data = $this->input->post('leave_types');
var_dump($data);

// Here I got some errors when I checked on the boxes
// I use the code above to check if my check boxes are working
// Unfortunately, it returns a NULL value

Why and how can I check for the checkbox values?

Please help.

Thanks!

Body:
my Sample work out

my controller

public function workout()
    {

        if($this->input->post())
        {
            echo "<pre>"; print_r($this->input->post()); exit();
        }

        $this->load->view('workout');
    }

myview

<form name="customers" id="customers" method="post" action="<?php echo base_url(); ?>welcome/workout"  enctype="multipart/form-data"   >

<input type='checkbox' name='leave_types[]' value='1'>1<br/>

<input type='checkbox' name='leave_types[]' value='2'>2<br/>

<input type='checkbox' name='leave_types[]' value='3'>3<br/>

<input type='checkbox' name='leave_types[]' value='4'>4<br/>

<input type='checkbox' name='leave_types[]' value='5'>5<br/>

<input type='submit' name='submit' value='Submit'>Submit<br/>

    </form>

and when i run this my output is

Array
(
    [leave_types] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [submit] => Submit
)

Try this Hope it helps. :)


问:
Alternative build manager to Hudson
I work at a software company where our primary development language is Java. Naturally, we use Hudson for continuous builds, which it works brilliantly for. However, Hudson is not so good at some of the other things we ask it to do. We also use Hudson jobs to deploy binaries, refresh databases, run load testing, run regressions, etc. We really run into trouble when there are build dependencies (i.e. load testings requires DB refresh).

Here's the one thing that Hudson doesn't do that we really need:

Build dependency: It supports build dependencies for Ant builds, but not for Hudson jobs. We're using the URL invocation feature to cause a Hudson job to invoke another Hudson job. The problem is that Hudson always returns a 200 and does not block until the job is done. This means that the calling job doesn't know a) if the build failed and b) if it didn't fail, how long it took.

It would be nice to not have to use shell scripting to specify the behavior of a build, but that's not totally necessary.

Any direction would be nice. Perhaps we're not using Hudson the right way (i.e. should all builds be Ant builds?) or perhaps we need another product for our one-click deployment, load testing, migration, DB refresh, etc.

Edit:

To clarify, we have parameters in our builds that can cause different dependencies depending on the parameters.  I.e. sometimes we want load testing with a DB refresh, sometimes without a DB refresh.  Unfortunately, creating a Hudson job for each combination of parameters (as the Join plugin requires) won't work because sometimes the different combinations could lead to dozens of jobs.

答:
There is a CLI for Hudson which allows you to issue commands to a Hudson instance.  Use "help" to get precise details.  I believe there is one which allows you to invoke a build and await its finish.

http://wiki.hudson-ci.org/display/HUDSON/Hudson+CLI

ContentLicense: CC BY-SA 2.5

Title: Alternative build manager to Hudson


问:
How to Intent into specific Tab Fragment?
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

```<code> protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }
</code>```

And This my Tab Fragment:

```<code>  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }
</code>```

答:
From your LoginActivity pass Intents like this

In LoginActivity.class

```<code>Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("Fragmentone", 0); //pass zero for Fragmentone.
startActivity(intent);

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
    intent.putExtra("FragmentTwo", 1); //pass zero for FragmentTwo.
    startActivity(intent);

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
    intent.putExtra("FragmentThree", 2); //pass zero for FragmentThree.
    startActivity(intent);
</code>```

In MainActivity.class

```<code>int value = getIntent().getIntExtra("Fragmentone", 0);
</code>```

From Your activity pass like this

```<code>Bundle bundle = new Bundle();
bundle.putString("key", value);
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.setArguments(bundle);
</code>```

and inside oncreateView of Fragment please define this

```<code>@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    int strtext = getArguments().getInt("key");
    return inflater.inflate(R.layout.fragment, container, false);
}
</code>```

Body:
T have two Activities: MainActivity and LoginActivity. I have one Fragment too, the name is TabFragment (with a TabLayout), its parent is MainActivity. How can I intent into the specific TabFragment from my Login Activity.

This is my Main Activity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        id = getIntent().getStringExtra("id");

        if (savedInstanceState == null) {
     getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new FragmentUtama()).commit();
            getSupportFragmentManager().beginTransaction().replace(R.id.confrag, new TabFragment()).commit();
        }
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        sharedPreferences = getSharedPreferences("login.conf", MODE_PRIVATE);
        editor = sharedPreferences.edit();
        String username = sharedPreferences.getString("username", "");
        String password = sharedPreferences.getString("password", "");
        Log.d(TAG, "Username:"+username+"\npassword:"+password);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }

And This my Tab Fragment:

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.viewpager, null);

        tabLayout = (TabLayout)view.findViewById(R.id.tabs);
        viewPager = (ViewPager)view.findViewById(R.id.viewpager);
        viewPager.setAdapter(new Adapterbaru(getChildFragmentManager()));
         tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        Long tsLong = System.currentTimeMillis()/1000;
        String ts = tsLong.toString();

        return view;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
    public class Adapterbaru extends FragmentPagerAdapter{
        public Adapterbaru(FragmentManager fm){
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0 : {
                    return new Fragmentone();
                }
                case 1 : {
                    return new FragmentTwo();

                }
                case 2 : {
                    return new Fragmenttree();

                }
            }
            return null;
        }

        @Override
        public int getCount() {
           return jumlah_tab;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch(position){
                case 0 : {
                    return "First";

                }
                case 1 : {
                    return "Second";

                }
                case 2 : {
                    return "Third";
                }
            }
            return null;
        }

Body:
From your LoginActivity pass Intents like this

In LoginActivity.class

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("Fragmentone", 0); //pass zero for Fragmentone.
startActivity(intent);

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
    intent.putExtra("FragmentTwo", 1); //pass zero for FragmentTwo.
    startActivity(intent);

Intent intent  = new Intent(LoginActivity.this, MainActivity.class);
    intent.putExtra("FragmentThree", 2); //pass zero for FragmentThree.
    startActivity(intent);

In MainActivity.class

int value = getIntent().getIntExtra("Fragmentone", 0);

From Your activity pass like this

Bundle bundle = new Bundle();
bundle.putString("key", value);
FragmentOne fragmentOne = new FragmentOne();
fragmentOne.setArguments(bundle);

and inside oncreateView of Fragment please define this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    int strtext = getArguments().getInt("key");
    return inflater.inflate(R.layout.fragment, container, false);
}


问:
Laravel: How to insert multi select2 dropdown selected data to mysql database?
I am trying to insert data into database. But i don't know how to insert multi select data into the mysql database.</p>

答:
I am not quite sure what you mean by multi-select

But I am going to tell you how to inset more than one row in a shot in database in Laravel.

First, You make an associative array of data you want to insert, which will contain column name as key and value as the value you want to insert.
Lets say you have a table named users in which you want to insert 4 new rows with different names you got from your form:

```<code>$data = [
  ['name'=>'xxx'],
  ['name'=>'yyy'],
  ['name'=>'zzz'],
  ['name'=>'qqq']
];
</code>```

Then you use model for that table(in our case: users) which will be most likely: User to insert data in one shot:

```<code>User::insert($data);
</code>```

Body:
I am not quite sure what you mean by multi-select

But I am going to tell you how to inset more than one row in a shot in database in Laravel.

First, You make an associative array of data you want to insert, which will contain column name as key and value as the value you want to insert.
Lets say you have a table named users in which you want to insert 4 new rows with different names you got from your form:

$data = [
  ['name'=>'xxx'],
  ['name'=>'yyy'],
  ['name'=>'zzz'],
  ['name'=>'qqq']
];

Then you use model for that table(in our case: users) which will be most likely: User to insert data in one shot:

User::insert($data);


问:
Xamarin iOS EventArgs missing first property
When using EventArgs attribute on delegate method it generates event handler class with properties based on method parameters except the first one.

The first parameter is missing in generated event args class.

For example:

```<code>[Protocol, Model]
[BaseType(typeof(NSObject))]
public interface TestDelegate
{
    // @required -(void)DidReceiveFrom:(NSString * _Nonnull)p1 withP2:(NSString * _Nonnull)p2 withP3:(NSString * _Nonnull)p3 withP4:(NSString * _Nonnull)p4;
    [Abstract]
    [Export("DidReceiveFrom:withP2:withP3:withP4:")]
    [EventArgs("DidReceiveFrom")]
    void DidReceiveFrom(string p1, string p2, string p3, string p4);
</code>```

Then generated EventArgs class becomes:

```<code>//
// EventArgs classes
//
public partial class DidReceiveFromEventArgs : EventArgs {
    public DidReceiveFromEventArgs (string p2, string p3, string p4)
    {
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
    }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}
</code>```

So it definitely missing p1 property. How to avoid this behavior?

答:
According to the Xamarin documentation this behavior is by default:

For events that take more than one parameter (in Objective-C the convention is that the first parameter in a delegate class is the instance of the sender object) you must provide the name that you would like for the generated EventArgs class to be. This is done with the EventArgs attribute on the method declaration in your Model class.

https://developer.xamarin.com/guides/cross-platform/macios/binding/binding-types-reference/#EventArgsAttribute

So is seems that delegates in source library for which I was generating bindings does not strictly follow this rule and the first parameter is semi-sender in string form.

Body:
When using EventArgs attribute on delegate method it generates event handler class with properties based on method parameters except the first one.

The first parameter is missing in generated event args class.

For example:

[Protocol, Model]
[BaseType(typeof(NSObject))]
public interface TestDelegate
{
    // @required -(void)DidReceiveFrom:(NSString * _Nonnull)p1 withP2:(NSString * _Nonnull)p2 withP3:(NSString * _Nonnull)p3 withP4:(NSString * _Nonnull)p4;
    [Abstract]
    [Export("DidReceiveFrom:withP2:withP3:withP4:")]
    [EventArgs("DidReceiveFrom")]
    void DidReceiveFrom(string p1, string p2, string p3, string p4);

Then generated EventArgs class becomes:

//
// EventArgs classes
//
public partial class DidReceiveFromEventArgs : EventArgs {
    public DidReceiveFromEventArgs (string p2, string p3, string p4)
    {
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
    }
    public string p2 { get; set; }
    public string p3 { get; set; }
    public string p4 { get; set; }
}

So it definitely missing p1 property. How to avoid this behavior?


问:
Hide/Show jcf Select (dropdown) from jquery
My select dropdown

```<code><select class="model" id="model" name="model" style="display:none;">
    <option value="model1">Model1</option>
    <option value="model2">Model2</option>
    <option value="model3">Model3</option>
    <option value="model4">Model4</option>
</select>
</code>```

I am using jcf plugin for select. Refrence https://www.psd2html.com/js-custom-forms/

Now i want to display my dropdown from jquery.
jQuery("select[name='model']").show();

But this is not working anymore.How can i change display:none to display:block ?

答:
You can change display:none to display:block by using this code:</p>

```<code>$("#model").css('display','block');
</code>```

Body:
My select dropdown

<select class="model" id="model" name="model" style="display:none;">
    <option value="model1">Model1</option>
    <option value="model2">Model2</option>
    <option value="model3">Model3</option>
    <option value="model4">Model4</option>
</select>

I am using jcf plugin for select. Refrence https://www.psd2html.com/js-custom-forms/

Now i want to display my dropdown from jquery.
jQuery("select[name='model']").show();

But this is not working anymore.How can i change display:none to display:block ?

Body:
You can change display:none to display:block by using this code:

$("#model").css('display','block');


问:
How to identify an anonymous function
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

```<code> public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}
</code>```

I need some way to identify

```<code>   p => { fake.Test(p); counter++; }
</code>```

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

答:
In your example, the caller is responsible from removing the handler. So, if the caller doesn't want to remove the handler, it won't get removed, no matter if the handler is an anonymous delegate/lambda or not.

My suggestion is to change the delegate container to something like this:

```<code>public class MyDelegateContainer
{
    List<Action<int>> m_Container = new List<Action<int>>();

    public Action Add(Action<int> del)
    {
        m_Container.Add(del);

        return new Action(() =>
        {
            m_Container.Remove(del);
        });
    }
}
</code>```

The caller is still responsible for removing the handler, but instead of passing the handler again to the container, it receives a "token" that it can save and use later to remove the handler.

Title: How to identify an anonymous function

Body:
I have a class that creates a List<Action<int>> and holds on to them until a later time. This class can add and remove delegates from this list. This works well as long as people don't get too fancy. To combat anonymous function (which can't be removed) I check against the target of the delegate being null. If its null I throw an exception. The problem comes in when there is an anonymous delegate that contains a function. This has a target, but is just as unremovable. The simplified code below illustrates my issues

 public class MyDelegateContainer
 {
    List<Action<int>> m_Container = new List<Action<int>>();

    public void Add(Action<int> del)
    {
        if (del.Target == null)
        {
            throw new Exception("No static handlers");
        }
        m_Container.Add(del);
    }

    public bool Remove(Action<int> del)
    {
        if (m_Container.Contains(del))
        {
            m_Container.Remove(del);
            return true;
        }

        return false;
    }
}

public class MyFakeActionClass
{
    public void Test(int temp) { }
}

class Program
{
    static void Main(string[] args)
    {
        bool removed = false;
        int counter = 0;
        MyDelegateContainer container = new MyDelegateContainer();
        MyFakeActionClass fake = new MyFakeActionClass();
        //container.Add(p => { }); //Throws, this is what I want to happen
        container.Add(fake.Test); //Works, this is the use case
        removed = container.Remove(fake.Test); //Works, this is the use case
        Debug.Assert(removed);
        container.Add(p => { fake.Test(p); counter++; }); //Works but I would like it not to
        removed = container.Remove(p => { fake.Test(p); counter++; }); //doesn't work
        Debug.Assert(removed);
    }
}

I need some way to identify

   p => { fake.Test(p); counter++; }

is an anonymous function so I can throw if someone tries it. Thanks for any help

EDIT: I should note that I could use an Action<int> variable for the anonymous function and everything would work, but the Add and Remove are never in the same scope in practice.

Body:
In your example, the caller is responsible from removing the handler. So, if the caller doesn't want to remove the handler, it won't get removed, no matter if the handler is an anonymous delegate/lambda or not.

My suggestion is to change the delegate container to something like this:

public class MyDelegateContainer
{
    List<Action<int>> m_Container = new List<Action<int>>();

    public Action Add(Action<int> del)
    {
        m_Container.Add(del);

        return new Action(() =>
        {
            m_Container.Remove(del);
        });
    }
}

The caller is still responsible for removing the handler, but instead of passing the handler again to the container, it receives a "token" that it can save and use later to remove the handler.


问:
How to loop over nextPageToken using GoogleDrive's Python Quickstart
My goal is to have a list of all of the items & folders in everyone's Google Drive. I'm starting with trying to make sure the script works on my own. I have read cover-to-cover the Drive REST API documentation, and eventually found this code, which can also be found here.

```<code>from __future__ import print_function
import httplib2
import os
import sys

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

reload(sys)
sys.setdefaultencoding('utf-8')

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    results = service.files().list(
        pageSize=1000,fields="nextPageToken, files(mimeType, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['mimeType']))

if __name__ == '__main__':
    main()
</code>```

My problem is with the nextPageToken, and how to properly use it. The max PageSize is 1000, so I must loop over the nextPageToken, fetch it from the resulting JSON, put it back into the original loop (line 66?), to get another 1000 results. How do I do this?

答:
I had quite a bit of trouble with this. I didn't read the example closely enough to notice that nextPageToken & newStartPageToken were not the same thing.

I split up the functions a little and added a loop. Basically, return the startPageToken and loop over the same function / call the function as required.

```<code>from __future__ import print_function
import httplib2
import os

#julian
import time

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    saved_start_page_token = StartPage_v3(service)
    saved_start_page_token = DetectChanges_v3(service, saved_start_page_token)

    starttime=time.time()
    while True:
        saved_start_page_token = DetectChanges_v3(service, saved_start_page_token)
        time.sleep(10.0 - ((time.time() - starttime) % 10.0))

def StartPage_v3(service):
    response = service.changes().getStartPageToken().execute()
    print('Start token: %s' % response.get('startPageToken'))
    return response.get('startPageToken')

def DetectChanges_v3(service, saved_start_page_token):
    # Begin with our last saved start token for this user or the
    # current token from getStartPageToken()
    page_token = saved_start_page_token;
    while page_token is not None:
        response = service.changes().list(pageToken=page_token, spaces='drive').execute()
        for change in response.get('changes'):
            # Process change
            mimeType = change.get('file').get('mimeType')
            print( 'Change found for: %s' % change)
        if 'newStartPageToken' in response:
            # Last page, save this token for the next polling interval
            saved_start_page_token = response.get('newStartPageToken')
        page_token = response.get('nextPageToken')
    return saved_start_page_token

if __name__ == '__main__':
    main()
</code>```

Body:
My goal is to have a list of all of the items & folders in everyone's Google Drive. I'm starting with trying to make sure the script works on my own. I have read cover-to-cover the Drive REST API documentation, and eventually found this code, which can also be found here.

from __future__ import print_function
import httplib2
import os
import sys

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

reload(sys)
sys.setdefaultencoding('utf-8')

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    results = service.files().list(
        pageSize=1000,fields="nextPageToken, files(mimeType, name)").execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
    else:
        print('Files:')
        for item in items:
            print('{0} ({1})'.format(item['name'], item['mimeType']))

if __name__ == '__main__':
    main()

My problem is with the nextPageToken, and how to properly use it. The max PageSize is 1000, so I must loop over the nextPageToken, fetch it from the resulting JSON, put it back into the original loop (line 66?), to get another 1000 results. How do I do this?

Body:
I had quite a bit of trouble with this. I didn't read the example closely enough to notice that nextPageToken & newStartPageToken were not the same thing.

I split up the functions a little and added a loop. Basically, return the startPageToken and loop over the same function / call the function as required.

from __future__ import print_function
import httplib2
import os

#julian
import time

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Drive API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,'drive-python-quickstart.json')

    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Google Drive API.

    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive', 'v3', http=http)

    saved_start_page_token = StartPage_v3(service)
    saved_start_page_token = DetectChanges_v3(service, saved_start_page_token)

    starttime=time.time()
    while True:
        saved_start_page_token = DetectChanges_v3(service, saved_start_page_token)
        time.sleep(10.0 - ((time.time() - starttime) % 10.0))

def StartPage_v3(service):
    response = service.changes().getStartPageToken().execute()
    print('Start token: %s' % response.get('startPageToken'))
    return response.get('startPageToken')

def DetectChanges_v3(service, saved_start_page_token):
    # Begin with our last saved start token for this user or the
    # current token from getStartPageToken()
    page_token = saved_start_page_token;
    while page_token is not None:
        response = service.changes().list(pageToken=page_token, spaces='drive').execute()
        for change in response.get('changes'):
            # Process change
            mimeType = change.get('file').get('mimeType')
            print( 'Change found for: %s' % change)
        if 'newStartPageToken' in response:
            # Last page, save this token for the next polling interval
            saved_start_page_token = response.get('newStartPageToken')
        page_token = response.get('nextPageToken')
    return saved_start_page_token

if __name__ == '__main__':
    main()


问:
PHP search filter function doesn't work
I created search filter function in php form. Fetched data from mysql in table. All query and others written well. But search function doesn't work.

```<code><?php
    require_once 'init.php';
    include 'header.php';
    include 'navigation.php';

    if(isset($_POST['search'])){
      $valSearch = $_POST['searchButton'];
      $query = "SELECT * FROM mainTable WHERE CONCAT ('id','commandName','commandDesc','status') LIKE '%".$valSearch."%'";
      $featured = filterTable($query);
    }else{
      $query = "SELECT * FROM mainTable";
      $featured = filterTable($query);
    }

    function filterTable($query){
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      return $filter_result;
    }

 ?>
 <form action = "index.php" method="post">
    <div class="container">
      <h3>Linux Fedora OS</h3><hr>
        <button type="submit" name ="searchButton" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
        <input type="text" name = "search" class="form-control" placeholder="Хайх үгээ бичнэ үү">
        <div class="col-md-12">
            <div class="row">
                <table class="table table-bordered">
                    <thead>
                        <th>ID</th>
                        <th>Command Name</th>
                        <th>Command Description</th>
                        <th>Status</th>
                    </thead>
                    <tbody>
                      <?php while($result = mysqli_fetch_assoc($featured)): ?>
                      <tr>
                          <td><?=$result['id']; ?></td>
                          <td><?=$result['commandName']; ?></td>
                          <td><?=$result['commandDesc']; ?></td>
                          <td><?=$result['status']; ?></td>
                      </tr>
                      <?php endwhile; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</form>
<?php
    include 'footer.php';
 ?>
 </body>
 </html>
</code>```

Here is Database structure.

```<code>create table if not exists mainTable(
   id int auto_increment,
   commandName varchar(255),
   commandDesc varchar(255),
   status int(2),
   primary key(id)
)
</code>```

答:
SInce you said you do not have any errors, try the following:

1- Run your query manually via your phpmyadmin and see if you get any results.

2- PAss your connection variable as a global variable. Read more on variable scopes here to better understand the concepts involved

```<code> function filterTable($query){
   global $connect;
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      // fetch results here as mysqli_query returns true/false.
      $final_results = array();
      while($row=mysqli_fetch_array($filter_result,MYSQLI_NUM)){
         $final_results[] = $row;
      }
      return $final_results;
    }
</code>```

3- turn on error_reporting to see if anything comes up

Title: PHP search filter function doesn't work

Body:
I created search filter function in php form. Fetched data from mysql in table. All query and others written well. But search function doesn't work.

<?php
    require_once 'init.php';
    include 'header.php';
    include 'navigation.php';

    if(isset($_POST['search'])){
      $valSearch = $_POST['searchButton'];
      $query = "SELECT * FROM mainTable WHERE CONCAT ('id','commandName','commandDesc','status') LIKE '%".$valSearch."%'";
      $featured = filterTable($query);
    }else{
      $query = "SELECT * FROM mainTable";
      $featured = filterTable($query);
    }

    function filterTable($query){
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      return $filter_result;
    }

 ?>
 <form action = "index.php" method="post">

Linux Fedora OS

        <button type="submit" name ="searchButton" class="btn btn-default"></button>
        <input type="text" name = "search" class="form-control" placeholder="Хайх үгээ бичнэ үү">

                        ID
                        Command Name
                        Command Description
                        Status

                      <?php while($result = mysqli_fetch_assoc($featured)): ?>

                          <?=$result['id']; ?>
                          <?=$result['commandName']; ?>
                          <?=$result['commandDesc']; ?>
                          <?=$result['status']; ?>

                      <?php endwhile; ?>

</form>
<?php
    include 'footer.php';
 ?>

Here is Database structure.

create table if not exists mainTable(
   id int auto_increment,
   commandName varchar(255),
   commandDesc varchar(255),
   status int(2),
   primary key(id)
)

Body:
SInce you said you do not have any errors, try the following:

1- Run your query manually via your phpmyadmin and see if you get any results.

2- PAss your connection variable as a global variable. Read more on variable scopes here to better understand the concepts involved

 function filterTable($query){
   global $connect;
      $connect = mysqli_connect("localhost","root","","linuxcommanddictionary");
      $filter_result = mysqli_query($connect,$query);
      // fetch results here as mysqli_query returns true/false.
      $final_results = array();
      while($row=mysqli_fetch_array($filter_result,MYSQLI_NUM)){
         $final_results[] = $row;
      }
      return $final_results;
    }

3- turn on error_reporting to see if anything comes up


问:
PHP preg_replace in javascript
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

```<code>preg_replace('/^\d+_/', '', $docTypes);
</code>```

And now, my JS looks like, important thing, var documentTypes is object:

```<code>   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);
</code>```

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

```<code>0_xxxx
1_xxxx
2_xxxx
</code>```

Thank you for advices!

答:
not sure on your input string, problem might be becouse you have line feed or carry return in string. If so, the solution you are looking for might be this:</p>

```<code>var documentTypes = '0_xxxx\n\
1_xxxx\n\
2_xxxx';

documentTypes = documentTypes.replace(/(^\d+_|[\r\n]+\d+_)/gm,'');
</code>```

Title: PHP preg_replace in javascript

Body:
I had working preg_replace in PHP, but I had to move it to JavaScript code and it doesn't work there. I've searched here in topics, but haven't found working solution for me...
My PHP looked like:

preg_replace('/^\d+_/', '', $docTypes);

And now, my JS looks like, important thing, var documentTypes is object:

   var documentTypesObj = {};
   var counter = 0;
   {foreach $documentTypes as $key =>$value}
   documentTypesObj[counter + '_' + {$key}] = {$value};
   counter++;
   {/foreach}

    var documentTypes = documentTypesObj;

    documentTypes = documentTypes.map(d => { return d.replace(/^\d+_/g, "")});

    console.log(documentTypes);

Inside var documentTypes are values with prefix, which I have to remove. Values are for example:

0_xxxx
1_xxxx
2_xxxx

Thank you for advices!

Body:
not sure on your input string, problem might be becouse you have line feed or carry return in string. If so, the solution you are looking for might be this:

var documentTypes = '0_xxxx\n\
1_xxxx\n\
2_xxxx';

documentTypes = documentTypes.replace(/(^\d+_|[\r\n]+\d+_)/gm,'');


问:
Lottie animation is not working as expected
I am using a Lottie file for animation purpose. It is not loading as expected. It should be like this http://www.lottiefiles.com/48-progress-bar

Current State: https://www.dropbox.com/s/xgvj9pss2cauv37/device-2017-04-03-113913.mp4?dl=0

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icici.iciciappathon.checkout.PaymentSucessActivity"
    android:background="@color/sky_blue">

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/animation_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:lottie_fileName="progress_bar.json"
        app:lottie_loop="true"
        app:lottie_autoPlay="true"
        android:layout_centerInParent="true"/>

</RelativeLayout>
</code>```

Any idea what I am doing wrong?

答:
Nothing wrong with what you are doing. Lottie is pretty straightforward to use. There's a problem with the progress_bar.json unfortunately.

Try to get in touch with the designer and maybe he can fix the issue.

ContentLicense: CC BY-SA 4.0

Body:
I am using a Lottie file for animation purpose. It is not loading as expected. It should be like this http://www.lottiefiles.com/48-progress-bar

Current State: https://www.dropbox.com/s/xgvj9pss2cauv37/device-2017-04-03-113913.mp4?dl=0

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.icici.iciciappathon.checkout.PaymentSucessActivity"
    android:background="@color/sky_blue">

    <com.airbnb.lottie.LottieAnimationView
        android:id="@+id/animation_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:lottie_fileName="progress_bar.json"
        app:lottie_loop="true"
        app:lottie_autoPlay="true"
        android:layout_centerInParent="true"/>

</RelativeLayout>

Any idea what I am doing wrong?


问:
What is the best way to query SharePoint data?
Should I just use ADO.NET to directly access the underlying data in the database or does .NET have a better way to do this?

I am currently using SharePoint 2007 but we are about to move to 2010.  I am using Visual Studio 2010.

答:
This depends on context. Answering the following questions will help you make the best choice to move forward.

What type of data?

List data from one site? Use webservices

Aggregating content across site collections? Use the server object model

What am I trying to do with the data?

Display a summary in a simple webpart? Consider using the CQWP(Content Query WebPart) or DVWP(Data View Webpart)

What is my timeline to deliver this solution?

If you haven't done SharePoint custom code deployments before and you are on a tight deadline try hard to stick to the web services api.


问:
Get the most precise time in Ruby
I want to get the most possible precis time using Ruby.  For example:

```<code>3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)
</code>```

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

答:
On Linux, I think the most precise time is just Time.now. The to_r method "is intended to be used to get an accurate value representing the nanoseconds since the Epoch" (from the docs).

```<code>t = Time.now

p t.to_r  # =>(1491206113721862629/1000000000)
p [t.to_i, t.nsec] # =>[1491206113, 721862629]
</code>```

Title: Get the most precise time in Ruby

Body:
I want to get the most possible precis time using Ruby.  For example:

3.times.map do
  Thread.new do
    # Expect 3 differnt results from each thread
    p Time.now.precis_time
  end
end.each(&:join)

However, even using the strftime, I still can not achieve the goal. So is there any other way to get this?

Body:
On Linux, I think the most precise time is just Time.now. The to_r method "is intended to be used to get an accurate value representing the nanoseconds since the Epoch" (from the docs).

t = Time.now

p t.to_r  # =>(1491206113721862629/1000000000)
p [t.to_i, t.nsec] # =>[1491206113, 721862629]


问:
JSON error org.json.JSONException: No value for item
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

```<code>04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4
</code>```

This my ActivityRegister.java class:

```<code>public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

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

This is the stringResponse I'm giving:

```<code>public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }
</code>```

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.

答:
As the crash logs suggest, you are trying to access retCode from the json but it not there.

You should use optString rather than getString , if you are not sure about the fields.

Body:
After tweaking JSON response a bit the error has changed to W/System.err: org.json.JSONException: No value for retCode.

The complete error:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

This my ActivityRegister.java class:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.\n\n"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

This is the stringResponse I'm giving:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {

            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

My base URL is: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest"; which is being provided when stringResponse is asked.
Any help would be appreciated.


问:
Capturing method in if statement in a list comprehension
I have a following use case:

```<code>[(x, f(x)) for x in list_x if f(x) == cond(x)]
</code>```

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.

答:
Filter would be a clean way of doing this.  It will evaluate the function passed and if it returns true, it will keep the element, otherwise, no.</p>

```<code>print (list(filter(lambda x: x[1] == cond(x[0]), [(x, f(x)) for x in list_x])))
</code>```

Body:
I have a following use case:

[(x, f(x)) for x in list_x if f(x) == cond(x)]

Above list comprehension, I think makes a f(x) call twice? How do I avoid that and capture value of f(x) so that f(x) is called only once.

I guess, easy fix is to convert above list comprehension into a for loop, but am curious if it can be done efficiently using a list comprehension.

Body:
Filter would be a clean way of doing this.  It will evaluate the function passed and if it returns true, it will keep the element, otherwise, no.

print (list(filter(lambda x: x[1] == cond(x[0]), [(x, f(x)) for x in list_x])))


问:
Does Azure Active Directory B2C work with Oauth or Open ID?
I successfully implemented Azure Active Directory for user management/authentication/login in a web app, following this example:
Azure Sample AAD with Flask

I decided to try Azure Active Directory B2C because of its integration for the various social apps. However, I could not get the flask app to work using OAuth 2.0, since Azure AD B2C does not seem to be compatible with OAuth 2.0. I found some documentation that states Azure AD B2C requires Open ID Connect.

Could you please confirm whether Azure Active Directory B2C requires Open ID Connect, or whether it works with OAuth 2.0 as well?

Thanks

答:
Azure AD B2C supports both OpenID Connect and OAuth 2.0 as noted in the official reference protocols documentation.

To be able to sign-in users with Azure AD B2C using OAuth 2.0 and Flask, you'll need to adapt the sample to follow the OAuth 2.0 approach used in this sample: An Android application with Azure AD B2C using OAuth. Key things you'll need to adapt:

You'll need to specify the B2C authorization and token endpoints: https://login.microsoftonline.com/tfp/TENANT_NAME/POLICY_NAME/oauth2/v2.0/authorize. Example from Android sample

You'll need to add your application/client ID as a scope. Example from Android sample

You won't be able to call the Graph's /me endpoint for token validation and to get user details. You'll need to validate the token and extract the claims from it yourself (ideally through a good JWT open source library since this isn't trivial, unfortunately I don't know any that I can recommend at this time).

EDIT

I've created a python sample for Azure AD B2C and used python-jose for token validation and claim retrieval. Check it out.


问:
PHP failed to send email after recieving 354
I am trying to send an email via pure php code without login SMTP server, code as follows:

```<code><?php
$from = "test@localhost";
$to = 'ayon@hyurl.com';
$domain = substr($to, strpos($to, '@')+1);
$dns = dns_get_record($domain, DNS_MX);
$mx = $dns[0]['target'];
$message = "
HELO localhost
MAIL FROM: $from
RCPT TO: $to
DATA
Subject: =?UTF-8?B?ztK1xLXa0ru49iBNb2RQSFAgs8zQ8g==?=
From: $from
To: $to
Date: Mon, 03 Apr 2017 13:54:10 +0800
Content-Transfer-Encoding: base64
MIME-Version: 1.0
Content-Type: text/plain

SGVsbG8sIFdvcmxkIQ==
.
";
$server = fsockopen($mx, 25, $errno, $error, 10);
if($errno){
    echo $error;
}else{
    fputs($server, $message);
    while(!feof($server)) {
        echo fgets($server);
    }
    fclose($server);
}
</code>```

After printing

```<code>220 bizmx8.qq.com MX QQ Mail Server
250 bizmx8.qq.com
250 Ok
250 Ok
354 End data with <CR><LF>.<CR><LF>
</code>```

the program hang up, anybody know why, how can I sent this email to the given address. Plus: I am very sure that my script use \r\n as line ending.

答:
Using PHP's mail() function it's possible.

```<code><?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>
</code>```

Take Below Reference for more :

http://php.net/manual/en/function.mail.php

Configure Your SMTP Server Settings in php.ini file :

In php.ini Configuration would be like this:

```<code>[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25
</code>```

Add Your server name instead of localhost.

Body:
I am trying to send an email via pure php code without login SMTP server, code as follows:

<?php
$from = "test@localhost";
$to = 'ayon@hyurl.com';
$domain = substr($to, strpos($to, '@')+1);
$dns = dns_get_record($domain, DNS_MX);
$mx = $dns[0]['target'];
$message = "
HELO localhost
MAIL FROM: $from
RCPT TO: $to
DATA
Subject: =?UTF-8?B?ztK1xLXa0ru49iBNb2RQSFAgs8zQ8g==?=
From: $from
To: $to
Date: Mon, 03 Apr 2017 13:54:10 +0800
Content-Transfer-Encoding: base64
MIME-Version: 1.0
Content-Type: text/plain

SGVsbG8sIFdvcmxkIQ==
.
";
$server = fsockopen($mx, 25, $errno, $error, 10);
if($errno){
    echo $error;
}else{
    fputs($server, $message);
    while(!feof($server)) {
        echo fgets($server);
    }
    fclose($server);
}

After printing

220 bizmx8.qq.com MX QQ Mail Server
250 bizmx8.qq.com
250 Ok
250 Ok
354 End data with <CR><LF>.<CR><LF>

the program hang up, anybody know why, how can I sent this email to the given address. Plus: I am very sure that my script use \r\n as line ending.

Body:
Using PHP's mail() function it's possible.

<?php
$to      = 'nobody@example.com';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?>

Take Below Reference for more :

http://php.net/manual/en/function.mail.php

Configure Your SMTP Server Settings in php.ini file :

In php.ini Configuration would be like this:

[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = localhost
; http://php.net/smtp-port
smtp_port = 25

Add Your server name instead of localhost.


问:
unable to append option in multiple select
I have a multipleSelect, it is created dynamically using javascript and I am currently not able to append options in it.

Below is a Fiddle

Here is what I tried :

```<code>$(selectEventTypeAssetId).append($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html('<option value="1">234</option>');
$(selectEventTypeAssetId).append('<option value="1">234</option>');
$(selectEventTypeAssetId).text('<option value="1">234</option>');
</code>```

None of these seem to help.

Any help would be appreciated.

答:
Try this,

$selectEventTypeAssetId = $("<select id='eventTypeSelect' class='form-control'>");
$selectEventTypeAssetId.html("<option value='1'>One</option>");
$(".alertTypeMultipleSelect").append($selectEventTypeAssetId);
$('select').multipleSelect({
  selectAll: false,
  width: "100%",
  filter: true,
  sort: true,
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/multiple-select/1.2.0/multiple-select.js"></script>
<link href="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.css" rel="stylesheet"/>
<div class="form-group">
  <label>Event Type:</label>
  <div class="alertTypeMultipleSelect"></div>
</div></code>```

I have made some changes as per creation of select element dynamically.

Body:
I have a multipleSelect, it is created dynamically using javascript and I am currently not able to append options in it.

Below is a Fiddle

Here is what I tried :

$(selectEventTypeAssetId).append($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html($('<option value="1"').text("2"));
$(selectEventTypeAssetId).html('<option value="1">234</option>');
$(selectEventTypeAssetId).append('<option value="1">234</option>');
$(selectEventTypeAssetId).text('<option value="1">234</option>');

None of these seem to help.

Any help would be appreciated.

Body:
Try this,

$selectEventTypeAssetId = $("<select id='eventTypeSelect' class='form-control'>");
$selectEventTypeAssetId.html("<option value='1'>One</option>");
$(".alertTypeMultipleSelect").append($selectEventTypeAssetId);
$('select').multipleSelect({
  selectAll: false,
  width: "100%",
  filter: true,
  sort: true,
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/multiple-select/1.2.0/multiple-select.js"></script>
<link href="https://rawgit.com/wenzhixin/multiple-select/master/multiple-select.css" rel="stylesheet"/>
<div class="form-group">
  <label>Event Type:</label>
  <div class="alertTypeMultipleSelect"></div>
</div>

I have made some changes as per creation of select element dynamically.


问:
initialized imageview in onCreate but still null
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

```<code>public class MainActivity extends AppCompatActivity {

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}
</code>```

The follwoing is the_other_layout xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>
</code>```

EDIT:

Please check the answer below if you have the similar problem

答:
The problem is in your initMap() method. You did not re-initialized myimage with the ImageView id android:id="@+id/imgview" of your layout the_other_layout.xml.

Update your initMap() as below:

```<code>public void initMap() {

    // ImageView
    myimage = (ImageView) findViewById(R.id.imgview);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap bmp = null;
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.somepngfile,options);

    myimage.setImageBitmap(bmp);
}
</code>```

Hope this will help~

Body:
I want to achieve the following: Once user click a button, change current layout(main) to the other and the other layout has an image loaded. But I keep getting error message say "virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference". The following is my mainactivity.java and 'the other layout'.xml

public class MainActivity extends AppCompatActivity {

    private Button mybtn;
    private ImageView myimage;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    public void init(){

        myimage = (ImageView) findViewById(R.id.imgview);
        mybtn = (Button) findViewById(R.id.btn);
        mybtn.setOnClickListener(new MyListener());
    }

    public class MyListener implements View.OnClickListener {

        @Override
        public void onClick(View v){
            switch (v.getId()){

                case R.id.btn:
                    setContentView(R.layout.the_other_layout);
                    initMap();
            }
        }
    }

    public void initMap(){

        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;
        Bitmap bmp = null;
        bmp = BitmapFactory.decodeResource(getResources(),R.drawable.somepngfile,options);
        myimage.setImageBitmap(bmp);
    }
}

The follwoing is the_other_layout xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imgview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal"
        />

</LinearLayout>

EDIT:

Please check the answer below if you have the similar problem

Body:
The problem is in your initMap() method. You did not re-initialized myimage with the ImageView id android:id="@+id/imgview" of your layout the_other_layout.xml.

Update your initMap() as below:

public void initMap() {

    // ImageView
    myimage = (ImageView) findViewById(R.id.imgview);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inScaled = false;
    Bitmap bmp = null;
    bmp = BitmapFactory.decodeResource(getResources(), R.drawable.somepngfile,options);

    myimage.setImageBitmap(bmp);
}

Hope this will help~


问:
Is there a "hook" for the end of a stage/task in spark?
I have a Spark UDF which needs to have a specific file (MATLAB runtime in my case) installed on the local disk of the executor (we are using YARN). As I don't have direct access to the executor machines, I have to find another way to deploy my runtime on the cluster.
As the file is very large, I cannot install/delete it for every invokation of the UDF, so I thought about the following strategy:

At the beginning of the UDF, I check whether the runtime is available locally under a specific path, e.g. the tmp-directory

If the runtime is not yet installed, I fetch it from the HDFS and install in in tmp. This is only done the first time the UDF is called on an specific executor.

The above screnario works fine, but leaves my installed runtimes all over the cluster, so I want to delete them afterwards.

There seems to be no way to add shutdown-hooks for the executors (Spark worker shutdown - how to free shared resources), is there another "hook" e.g. end-of-a-task hook?

答:
As I mentioned, you can listen for the end of a task (I just had the time to try it now), at least on a global level on the spark context with something the likes (I'll write something in scala later, as I can't run scala code at the moment):

```<code>//sc is the SparkContext
sc.addSparkListener(new SparkListener() {

        @Override
        public void onTaskEnd(SparkListenerTaskEnd taskEnd) {
            // TODO Auto-generated method stub
            System.out.println("Task ended: " + taskEnd);
            super.onTaskEnd(taskEnd);
        }
    });
</code>```

There are plenty of other listeners, see SparkListener

Body:
As I mentioned, you can listen for the end of a task (I just had the time to try it now), at least on a global level on the spark context with something the likes (I'll write something in scala later, as I can't run scala code at the moment):

//sc is the SparkContext
sc.addSparkListener(new SparkListener() {

        @Override
        public void onTaskEnd(SparkListenerTaskEnd taskEnd) {
            // TODO Auto-generated method stub
            System.out.println("Task ended: " + taskEnd);
            super.onTaskEnd(taskEnd);
        }
    });

There are plenty of other listeners, see SparkListener