问:
updating a fragment from activity during runtime, view variable not global
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

```<code>public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}
</code>```

and my activity

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
</code>```

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

```<code>    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);
</code>```

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

答:
In my opinion the issue persists because of the manual instantiation you've performed at the line
TabFragment1 FragVar = new TabFragment1();

A little on that, the fragment objects are created and returned within the FragmentPagerAdapter and are then managed by the latter which is said to handle memory well.

So when you're recreating the TabFragment1 object manually inside onItemSelected(), the onCreateView() of your TabFragment1 isn't fired and thus the corresponding fragment view is not inflated.

At the same time you're trying to manipulate a TextView object (for instance) which hasn't been created as yet!

That's exactly why I guess you're getting a NPE.

And the probable solution on a very short note would be to use the Bundle class to add and receive extras, maybe. I guess that should work! Maybe someone else could add to it. :)

Hope this helps!

Body:
I have a tab page with 3 fragments. I have a spinner on the page. When a user selects a value from the spinner, the 3 fragments are updated with mysql data. I am having a problem with the OnCreateView, I am inflating the layout, and returning the view, but after returned to the mainactivity, the "global" view variable is cleared and when I try to update the textboxes, I get a NPE due to the view variable being null.

public class TabFragment1 extends Fragment {

public TabFragment1() {

    // Required empty public constructor
}

View loadInflatedView;
TextView txtLoadNumber,txtAddlStops;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    loadInflatedView = inflater.inflate(R.layout.tab_fragment_1, container, false);
    return loadInflatedView;
}

public void updateFragment1(Integer LoadNumber, Integer AddlStops){

    txtLoadNumber = (TextView) loadInflatedView.findViewById(R.id.textViewLoadNumber);
    txtAddlStops = (TextView) loadInflatedView.findViewById(R.id.textViewAddlStops);

    //Log.d(TAG, "Update Dashboard Location");
    txtLoadNumber.setText(LoadNumber);
    txtAddlStops.setText(AddlStops);
}

and my activity

@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loads_tabbed);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Load"));
    tabLayout.addTab(tabLayout.newTab().setText("Shipper"));
    tabLayout.addTab(tabLayout.newTab().setText("Consignee"));
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setOffscreenPageLimit(4);
    final PagerAdapter adapter = new com.jrs.loadmanager.PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

...

//this method will execute when we pic an item from the spinner
    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id) {

    final Integer LoadNumber = parseInt( parent.getItemAtPosition(position).toString());

    Cursor res = myDb.getLoadData(LoadNumber);
    ShortcutBadger.removeCount(getApplicationContext());
    session = new SessionManager(getApplicationContext());

    if (res.moveToFirst()) {

        Integer txtLoad = parseInt(res.getString(res.getColumnIndex(Config.TAG_LOADNUMBER)));
        Integer txtStop = parseInt(res.getString(res.getColumnIndex(Config.TAG_ADDSTOPS)));
        TabFragment1 FragVar = new TabFragment1();
        FragVar.updateFragment1(txtLoad,txtStop);

loadInflatedView is set when the OnCreateView is executed, but is null when I try to call loadInflatedView.findViewById(R.id.textViewLoadNumber);

I have searched and searched and cannot find a solution as to why this variable is clearing.

here is fatal error message:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jrs.loadmanager, PID: 11045
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.jrs.loadmanager.TabFragment1.updateFragment1(TabFragment1.java:54)
at com.jrs.loadmanager.LoadsActivity.onItemSelected(LoadsActivity.java:426)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:924)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:913)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:883)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)


来源: stackexchange

问:
How can I install ffmpeg to my docker image
I have setup a docker image in my Windows 10 Machine.
Can you please tell me how can I install ffmpeg to that docker image?</p>

答:
In your dockerfile you can write this command to add required repo, update your repository and then install ffmpeg.

Though I am not sure if this library still exist I just modified this Link for Docker you can follow same rules to install another package.

```<code>RUN set -x \
    && add-apt-repository ppa:mc3man/trusty-media \
    && apt-get update \
    && apt-get dist-upgrade \
    && apt-get install -y --no-install-recommends \
        ffmpeg \
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In your dockerfile you can write this command to add required repo, update your repository and then install ffmpeg.

Though I am not sure if this library still exist I just modified this Link for Docker you can follow same rules to install another package.

RUN set -x \
    && add-apt-repository ppa:mc3man/trusty-media \
    && apt-get update \
    && apt-get dist-upgrade \
    && apt-get install -y --no-install-recommends \
        ffmpeg \


问:
Where best to throw exception in this example?
In a library I am writing, I have some methods which would only be executed very rarely and on the fly. As I am modelling a vehicle, one of the (Exceptional) methods is a cracked engine, which would be very rare. Should  I throw an exception in this method? This will stop a vehicle from being usable.

I read the .NET Design Framework Guidelines book and it states that an exception should only occur when a method cannot complete execution. The actual engine cracked method will always complete, but if one of my methods, such as start engine (this method will store the amount of engine starts as a means of accruing stress to the engine), is called and results in a call to cracked engine, where (if anywhere) should I throw an exception?

答:
Think an exception should be thrown to highlight code or runtime issues. This is actually normal system logic (in this sense that a cracked engine is a model state, not a code problem), so shouldn't throw.

Instead, there should be some feedback mechanism that makes sense in the context of the system you're modelling.

ContentLicense: CC BY-SA 2.5


问:
How to create a nested object (JSON) of a form input values based on the input name in vanilla JavaScript?
//lets say the form is like below

```<code> <form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>
</code>```

// I want the output to be like this in JSON format based on the input name attr //(this is just an example, want  generic answer and the best way to do it)

```<code>{
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2",
        "foo.cat.biz.dog": {
            "bar": "child3"
        }
    }
}
</code>```

答:
You can use jQuery and use the serializeArray() method like this var jsonData = $('form').serializeArray();:

It doesn't match your sample object but it does what your question asked.

Once you have the fields in an Array you can manipulate your object however you want. I can't quite follow the logic of how you could ever arrive with that object from the form name attributes so I can't even attempt to map it.

<form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>
  <input id='btnSerialize' value='Serialize' type='button' onclick='serializeForm()' />

  ```
</div>
</div>
</p>

<p>If you change your form names so you can have a valid logical structure than in Plain javascript:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
{
  "foo": {
    "bar": "parent",
    "biz": "parent",
    "cat": {
      "bar": "child2achild2a,child2b",
      "biz": {
        "dog": {
          "bar": "child3"
        }
      }
    }
  }
}
*/</code>```

<form id="myform">
  <input name="foo.bar" value="parent" />
  <input name="foo.biz" value="parent" />
  <input name="foo.cat.bar" value="child2a" />
  <input name="foo.cat.bar" value="child2b" />
  <input name="foo.cat.biz.dog.bar" value="child3" />
</form>

<input type="button" value="go" onclick="serialize()" />

```

Body:
//lets say the form is like below

 <form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>

// I want the output to be like this in JSON format based on the input name attr //(this is just an example, want  generic answer and the best way to do it)

{
    "foo": "parent",
    "foo.cat": {
        "bar": "child1",
        "biz": "child2",
        "foo.cat.biz.dog": {
            "bar": "child3"
        }
    }
}

Body:
You can use jQuery and use the serializeArray() method like this var jsonData = $('form').serializeArray();:

It doesn't match your sample object but it does what your question asked.

Once you have the fields in an Array you can manipulate your object however you want. I can't quite follow the logic of how you could ever arrive with that object from the form name attributes so I can't even attempt to map it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
      <input name="foo" value="parent"/>
      <input name="foo.cat.bar" value="child1"/>
      <input name="foo.cat.biz" value="child2"/>
      <input name="foo.cat.biz.dog.bar" value="child3"/>
  </form>
  <input id='btnSerialize' value='Serialize' type='button' onclick='serializeForm()' />
  <div id='result'></div>
  <script>

  function serializeForm()
  {
    var jsonData = $('form').serializeArray();
    var jsonString = JSON.stringify(jsonData);
    $('#result').html(jsonString);
  }

  </script>

If you change your form names so you can have a valid logical structure than in Plain javascript:

/*
{
  "foo": {
    "bar": "parent",
    "biz": "parent",
    "cat": {
      "bar": "child2achild2a,child2b",
      "biz": {
        "dog": {
          "bar": "child3"
        }
      }
    }
  }
}
*/

<form id="myform">
  <input name="foo.bar" value="parent" />
  <input name="foo.biz" value="parent" />
  <input name="foo.cat.bar" value="child2a" />
  <input name="foo.cat.bar" value="child2b" />
  <input name="foo.cat.biz.dog.bar" value="child3" />
</form>
<script>
  function serialize() {
    var elements = document.querySelectorAll('#myform input');
    var data = {};
    for (var i = 0; i < elements.length; i++) {
      var el = elements[i];
      var val = el.value;
      if (!val) val = "";
      var fullName = el.getAttribute("name");
      if (!fullName) continue;
      var fullNameParts = fullName.split('.');
      var prefix = '';
      var stack = data;
      for (var k = 0; k < fullNameParts.length - 1; k++) {
        prefix = fullNameParts[k];
        if (!stack[prefix]) {
          stack[prefix] = {};
        }
        stack = stack[prefix];
      }
      prefix = fullNameParts[fullNameParts.length - 1];
      if (stack[prefix]) {

        var newVal = stack[prefix] + ',' + val;
        stack[prefix] += newVal;
      } else {
        stack[prefix] = val;
      }
    }
    console.log(data);

  }
</script>
<input type="button" value="go" onclick="serialize()" />
<p><br /></p>
<p><br /></p>


问:
Can't import certain package in cmd, but can import it with sublime text3
So I am trying to import certain packages, when I use this command in cmd, py test.py, all I get is ModuleNotFoundError: No module named holidays

The only thing in test.py is import holidays.

But when I try to execute test.py in sublime text3, it works. No error happens.

I have tried to find the answer by Google, but can's find anything helpful. Please help me. Thank you all!

答:
I think it may be linked to what @wim say in this post

You may want to check some points:

Do you use the same python interpreter?

import sys; print(sys.executable)

Is this the same current directory that both use?

import os; print(os.getcwd())

Check the sys.path, and difference between both could lead to error (can be caused by environment variable).

import sys; print(sys.path)

(This answer is totally based on what Wim said and was accepted on the question from the linked post, if it answer your question please give him credit).


问:
Microsecond timing in JavaScript
Are there any timing functions in JavaScript with microsecond resolution?

I am aware of timer.js for Chrome, and am hoping there will be a solution for other friendly browsers, like Firefox, Safari, Opera, Epiphany, Konqueror, etc.  I'm not interested in supporting any IE, but answers including IE are welcome.

(Given the poor accuracy of millisecond timing in JS, I'm not holding my breath on this one!)

Update: timer.js advertises microsecond resolution, but it simply multiplies the millisecond reading by 1,000.  Verified by testing and code inspection.  Disappointed. :[

答:
Here is an example showing my high-resolution timer for node.js:

```<code> function startTimer() {
   const time = process.hrtime();
   return time;
 }

 function endTimer(time) {
   function roundTo(decimalPlaces, numberToRound) {
     return +(Math.round(numberToRound + `e+${decimalPlaces}`)  + `e-${decimalPlaces}`);
   }
   const diff = process.hrtime(time);
   const NS_PER_SEC = 1e9;
   const result = (diff[0] * NS_PER_SEC + diff[1]); // Result in Nanoseconds
   const elapsed = result * 0.0000010;
   return roundTo(6, elapsed); // Result in milliseconds
 }
</code>```

Usage:

```<code> const start = startTimer();

 console.log('test');

 console.log(`Time since start: ${endTimer(start)} ms`);
</code>```

Normally, you might be able to use:

```<code> console.time('Time since start');

 console.log('test');

 console.timeEnd('Time since start');
</code>```

If you are timing sections of code that involve looping, you cannot gain access to the value of console.timeEnd() in order to add your timer results together. You can, but it get gets nasty because you have to inject the value of your iterating variable, such as i, and set a condition to detect if the loop is done.

Here is an example because it can be useful:

```<code> const num = 10;

 console.time(`Time til ${num}`);

 for (let i = 0; i < num; i++) {
   console.log('test');
   if ((i+1) === num) { console.timeEnd(`Time til ${num}`); }
   console.log('...additional steps');
 }
</code>```

Cite: https://nodejs.org/api/process.html#process_process_hrtime_time

Title: Microsecond timing in JavaScript

Body:
Here is an example showing my high-resolution timer for node.js:

 function startTimer() {
   const time = process.hrtime();
   return time;
 }

 function endTimer(time) {
   function roundTo(decimalPlaces, numberToRound) {
     return +(Math.round(numberToRound + `e+${decimalPlaces}`)  + `e-${decimalPlaces}`);
   }
   const diff = process.hrtime(time);
   const NS_PER_SEC = 1e9;
   const result = (diff[0] * NS_PER_SEC + diff[1]); // Result in Nanoseconds
   const elapsed = result * 0.0000010;
   return roundTo(6, elapsed); // Result in milliseconds
 }

Usage:

 const start = startTimer();

 console.log('test');

 console.log(`Time since start: ${endTimer(start)} ms`);

Normally, you might be able to use:

 console.time('Time since start');

 console.log('test');

 console.timeEnd('Time since start');

If you are timing sections of code that involve looping, you cannot gain access to the value of console.timeEnd() in order to add your timer results together. You can, but it get gets nasty because you have to inject the value of your iterating variable, such as i, and set a condition to detect if the loop is done.

Here is an example because it can be useful:

 const num = 10;

 console.time(`Time til ${num}`);

 for (let i = 0; i < num; i++) {
   console.log('test');
   if ((i+1) === num) { console.timeEnd(`Time til ${num}`); }
   console.log('...additional steps');
 }

Cite: https://nodejs.org/api/process.html#process_process_hrtime_time


问:
How can i get subscribe to only last data?
i am doing system of searching in my App. And i subscribe on EventBusEvent

```<code>addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));
</code>```

Event:

```<code>public class UpdateSearchResults
{
    public UpdateSearchResults(String text)
    {
        this.text = text;
    }

    public String getText()
    {
        return text;
    }

    private String text;
}
</code>```

And each time when user input new symbol. I send event like this:

```<code>TheApplication.getEventBus().post(new UpdateSearchResults(newText));
</code>```

Can i with help rxJava handle only  last data?

Example: user is input string fast: "Example" and after input symbol "e" subscription will work. But for other symbols subscription will not work.

What kind of solutions to the problem exist?

答:
I create class who send new data once per set period.

```<code>public class EventSendOnPeriod
{
    public EventSendOnPeriod(Long period)
    {
        this.period = period;
        this.isChange = false;

        handler = new Handler();
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    if (isChange)
                    {
                        TheApplication.getEventBus().post(new UpdateSearchResults(text));
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    handler.postDelayed(this, period);
                    isChange = false;
                }
            }
        };
        runnable.run();
    }

    public void sendEvent(String text)
    {
        this.text = text;
        isChange = true;
    }

    private final Long period;
    private String text;
    private Boolean isChange;
    private final Handler handler;
}
</code>```

It's very easy for use. You should just use:

```<code>eventSendOnPeriod.sendEvent(newText);
</code>```

The class yourself once time per period send new data.

Variant #2:

```<code>addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).debounce(500, TimeUnit.MILLISECONDS).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));
</code>```

Body:
i am doing system of searching in my App. And i subscribe on EventBusEvent

addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));

Event:

public class UpdateSearchResults
{
    public UpdateSearchResults(String text)
    {
        this.text = text;
    }

    public String getText()
    {
        return text;
    }

    private String text;
}

And each time when user input new symbol. I send event like this:

TheApplication.getEventBus().post(new UpdateSearchResults(newText));

Can i with help rxJava handle only  last data?

Example: user is input string fast: "Example" and after input symbol "e" subscription will work. But for other symbols subscription will not work.

What kind of solutions to the problem exist?

Body:
I create class who send new data once per set period.

public class EventSendOnPeriod
{
    public EventSendOnPeriod(Long period)
    {
        this.period = period;
        this.isChange = false;

        handler = new Handler();
        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    if (isChange)
                    {
                        TheApplication.getEventBus().post(new UpdateSearchResults(text));
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                finally
                {
                    handler.postDelayed(this, period);
                    isChange = false;
                }
            }
        };
        runnable.run();
    }

    public void sendEvent(String text)
    {
        this.text = text;
        isChange = true;
    }

    private final Long period;
    private String text;
    private Boolean isChange;
    private final Handler handler;
}

It's very easy for use. You should just use:

eventSendOnPeriod.sendEvent(newText);

The class yourself once time per period send new data.

Variant #2:

addSubscription(TheApplication.getEventBus().observe(UpdateSearchResults.class).debounce(500, TimeUnit.MILLISECONDS).subscribe(event ->
        getViewModel().setParameter(event.getText())
    ));


问:
Tests passing when run by ant but fail when run by maven?
Does anyone have any ideas why a test would pass when run with ant, but fail when run with maven?

I'm running my tests on windows and apparently there are some issues with surefire and windows? I've tried changing useSystemClassLoader=False and useManifestOnlyJar=true, but haven't been able to get them to work. The stack is below for the error I am getting when running the test with maven.

One thing I noticed is that there are $Proxy.someMethod calls in the stack, I have no idea where they are coming from.

Thanks for any help.

```<code>javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:678)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
        at $Proxy27.persist(Unknown Source)
        at cheetah.repositories.businessdata.jpa.JpaAttributeRepository.create(JpaAttributeRepository.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at $Proxy29.create(Unknown Source)
        at cheetah.tests.integration.util.BusinessDataLookupData.createAttributeLookupData(BusinessDataLookupData.java:19)
        at cheetah.tests.integration.util.BusinessDataLookupData.create(BusinessDataLookupData.java:10)
        at cheetah.tests.integration.util.LookupData.create(LookupData.java:7)
        at cheetah.tests.integration.util.TestUtil.prepareData(TestUtil.java:23)
        at cheetah.repositories.businessdata.tests.integration.AttributeRepositoryTest.setUpClass(AttributeRepositoryTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
        at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
        at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
        at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
        at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:672)
        ... 43 more
</code>```

答: Setting forkMode=never in the sure fire configuration resolved the issue. I'm not sure of the reasoning, but without this option maven wasn't running pre-test code that ant was.</p>

Body:
Does anyone have any ideas why a test would pass when run with ant, but fail when run with maven?

I'm running my tests on windows and apparently there are some issues with surefire and windows? I've tried changing useSystemClassLoader=False and useManifestOnlyJar=true, but haven't been able to get them to work. The stack is below for the error I am getting when running the test with maven.

One thing I noticed is that there are $Proxy.someMethod calls in the stack, I have no idea where they are coming from.

Thanks for any help.

javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
        at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1153)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:678)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:240)
        at $Proxy27.persist(Unknown Source)
        at cheetah.repositories.businessdata.jpa.JpaAttributeRepository.create(JpaAttributeRepository.java:28)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
        at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
        at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
        at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
        at $Proxy29.create(Unknown Source)
        at cheetah.tests.integration.util.BusinessDataLookupData.createAttributeLookupData(BusinessDataLookupData.java:19)
        at cheetah.tests.integration.util.BusinessDataLookupData.create(BusinessDataLookupData.java:10)
        at cheetah.tests.integration.util.LookupData.create(LookupData.java:7)
        at cheetah.tests.integration.util.TestUtil.prepareData(TestUtil.java:23)
        at cheetah.repositories.businessdata.tests.integration.AttributeRepositoryTest.setUpClass(AttributeRepositoryTest.java:23)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
        at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
        at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
        at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
        at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:103)
        at org.apache.maven.surefire.Surefire.run(Surefire.java:169)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:350)
        at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1021)
Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: cheetah.entities.businessdata.Attribute
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:127)
        at org.hibernate.event.def.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:61)
        at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:808)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:782)
        at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:786)
        at org.hibernate.ejb.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:672)
        ... 43 more


问:
Admin notification when shipping address is the same on "processing" orders
I own/operate a WooCommerce Shop and I am looking for a way to Set up a Shop Notice when More than One Order comes in from the same Customer, Shipping to the Same Address.

I have been lucky enough to be blessed with tons of repeat customers. They will order from my shop on let's say a Monday and pay the shipping rate for their item(s) & then order on say a Tuesday (before I am able to ship out the first order), so I try to include the second product into first order to "SAVE" on shipping. But I can only save on Shipping if I pay attention to the customer's shipping address and bundle the items.

I would like my site to be a bit more efficient in this area and check for "OPEN" or "PROCESSING" orders that have matching shipping address's and pop up an alert when I open one of the orders in question...

Is something like this possible?

I have searched and searched and searched and nothing... I'm not completely sure where to start on this...

Is this possible with a custom script in functions.php file?

Is there a plugin that can help do this?

Any help is greatly appreciated.

Thanks.

答:
Version code for WooCommerce 3+

```<code>add_action( 'woocommerce_admin_order_data_after_order_details', 'same_shipping_open_order', 10, 1 );
function same_shipping_open_order( $order ){

    // Define HERE, in the array, your "OPEN" orders statuses
    $open_order_statuses = array('wc-pending','wc-processing','wc-on-hold');

    // Initialising variables
    $matching = false;

    // Get Order data (WC 3+ compatibility)
    $order_data = $order->get_data();

    // Get the shipping 'address_1' & 'postcode' fields for the CURRENT ORDER
    $order_ship_address1 = $order_data['shipping']['address_1']; # (WC 3+ compatibility)
    $order_ship_postcode = $order_data['shipping']['postcode']; # (WC 3+ compatibility)

    // Getting customer orders, with an open status
    $open_orders = wc_get_orders( array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => $order->get_user_id(),
        'post_type' => 'shop_order',
        'post_status' => $open_order_statuses,
        'exclude' => array($order_data['id']), # (WC 3+ compatibility)
    ) );

    // Other "Open" orders for this customer
    if( count($open_orders) != 0 ){
        // Iterating through each orders
        foreach($open_orders as $open_order){

            // Get "open" Order data (WC 3+ compatibility)
            $open_order_data = $open_order->get_data();
            // Orders Id
            $open_order_id = $open_order_data['id'];

            if( $order_ship_address1 == $open_order_data['shipping']['address_1'] && $order_ship_postcode == $open_order_data['shipping']['postcode'] ){
                // set condition to true (There is at once 1 matched order)
                $matching = true;

                // Other orders edit url
                $order_edit_url = home_url( "/wp-admin/post.php?post=$open_order_id&action=edit/" );

                // Storing orders edit url + ID
                $results_arr[] = "<a href='$order_edit_url'>#$open_order_id</a>";
            }
        }
    }

    // If there is matching "Open" orders shipping addresss with this order
    if ( $matching ) {

        ## 0. Converting the array in a string for output
        $output_html = implode(', ', $results_arr);

        ## 1. Displaying an alert message on the order
        echo '<br clear="all"><p style="margin-top:12px !important;"><strong style="color:red;">'. __("Same Shipping on Open Orders IDs: ").'</strong><br>'.$output_html.'</p>';

        ## 2. Javascript Alert message
        ?>
        <script>
            (function($){
                alert('SAME SHIPPING ON OPEN ORDERS!');
            })(jQuery);
        </script>
        <?php
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works the same way on WooCommerce 3+

See this related updated answer: How to get order details
 in WooCommerce 3.0+

Body:
Version code for WooCommerce 3+

add_action( 'woocommerce_admin_order_data_after_order_details', 'same_shipping_open_order', 10, 1 );
function same_shipping_open_order( $order ){

    // Define HERE, in the array, your "OPEN" orders statuses
    $open_order_statuses = array('wc-pending','wc-processing','wc-on-hold');

    // Initialising variables
    $matching = false;

    // Get Order data (WC 3+ compatibility)
    $order_data = $order->get_data();

    // Get the shipping 'address_1' & 'postcode' fields for the CURRENT ORDER
    $order_ship_address1 = $order_data['shipping']['address_1']; # (WC 3+ compatibility)
    $order_ship_postcode = $order_data['shipping']['postcode']; # (WC 3+ compatibility)

    // Getting customer orders, with an open status
    $open_orders = wc_get_orders( array(
        'numberposts' => -1,
        'meta_key' => '_customer_user',
        'meta_value' => $order->get_user_id(),
        'post_type' => 'shop_order',
        'post_status' => $open_order_statuses,
        'exclude' => array($order_data['id']), # (WC 3+ compatibility)
    ) );

    // Other "Open" orders for this customer
    if( count($open_orders) != 0 ){
        // Iterating through each orders
        foreach($open_orders as $open_order){

            // Get "open" Order data (WC 3+ compatibility)
            $open_order_data = $open_order->get_data();
            // Orders Id
            $open_order_id = $open_order_data['id'];

            if( $order_ship_address1 == $open_order_data['shipping']['address_1'] && $order_ship_postcode == $open_order_data['shipping']['postcode'] ){
                // set condition to true (There is at once 1 matched order)
                $matching = true;

                // Other orders edit url
                $order_edit_url = home_url( "/wp-admin/post.php?post=$open_order_id&action=edit/" );

                // Storing orders edit url + ID
                $results_arr[] = "<a href='$order_edit_url'>#$open_order_id</a>";
            }
        }
    }

    // If there is matching "Open" orders shipping addresss with this order
    if ( $matching ) {

        ## 0. Converting the array in a string for output
        $output_html = implode(', ', $results_arr);

        ## 1. Displaying an alert message on the order
        echo '<br clear="all"><p style="margin-top:12px !important;"><strong style="color:red;">'. __("Same Shipping on Open Orders IDs: ").'</strong><br>'.$output_html.'</p>';

        ## 2. Javascript Alert message
        ?>
        <script>
            (function($){
                alert('SAME SHIPPING ON OPEN ORDERS!');
            })(jQuery);
        </script>
        <?php
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works the same way on WooCommerce 3+

See this related updated answer: How to get order details
 in WooCommerce 3.0+


问:
Uncaught ReferenceError: value is not defined for imported module
Here is scenario:

index.js

```<code>import test1 from './test1';
window.test1 = test1;
</code>```

test1.js

```<code>import test2 from './test2';
var test1 =  (function (){
  var self = this;
  var x = {};
  x.test2 = test2;
  var testValue = 'TEST VALUE';
  let init = function(){
        console.log ( x.test2() );
  }
  init();
  return {
    x: x,
    testValue: testValue
  }
})();
export default test1;
</code>```

test2.js

```<code>var test2 =  function () {
    return (` value to use ${testValue} ` )
};

export default test2;
</code>```

I am getting the following error in test2.js when running index.js
 Uncaught ReferenceError: testValue is not defined

is there a way to use testValue without having to pass it in?

答: you can transform test1 to a Class Object, then use this.value in test2, and it will use the value of test1's instance

Body:
Here is scenario:

index.js

import test1 from './test1';
window.test1 = test1;

test1.js

import test2 from './test2';
var test1 =  (function (){
  var self = this;
  var x = {};
  x.test2 = test2;
  var testValue = 'TEST VALUE';
  let init = function(){
        console.log ( x.test2() );
  }
  init();
  return {
    x: x,
    testValue: testValue
  }
})();
export default test1;

test2.js

var test2 =  function () {
    return (` value to use ${testValue} ` )
};

export default test2;

I am getting the following error in test2.js when running index.js
 Uncaught ReferenceError: testValue is not defined

is there a way to use testValue without having to pass it in?


问:
Node process.env.VARIABLE_NAME returning undefined
I'm using environment variables on my mac to store some sensitive credentials, and trying to access them through Node. I added them into my environment profile with

export VARIABLE_NAME=mySensitiveInfo

When I use echo $VARIABLE_NAME I receive the correct output (my sensitive info).

However, when I am trying to access this same variable in Node with process.env.VARIABLE_NAME and try to print it out on the console, I get an undefined.

Other environment variables appear to be okay though. For example, when I console.log(process.env.FACEBOOK_CALLBACK_URL), it prints the correct value to my console. I added FACEBOOK_CALLBACK_URL a few days ago.

Do I have to restart my machine or something? Does it take a certain time before environment variables become available in Node? The closest answer I've seen on SO is this post, but nobody was able to figure out why it was happening.

答:
process.env.VARIABLE_NAME returns undefined because the Node.js execution environment does not know the newly added VARIABLE_NAME yet. To fix the issue, the Node.js execution environment (e.g. IDE) need to restart.

The following steps can be used to reproduce this issue:

Open IDE such as WebStorm and write a simple Node.js program: console.log(process.env.VARIABLE_NAME). It will print undefined as expected, as VARIABLE_NAME is not defined yet. Keep the IDE running, don't close it.

Open environment profile such as .bash_profile and add export VARIABLE_NAME=mySensitiveInfo in it.

Open system console and run source .bash_profile, so that the above export statement will be executed. From now on, whenever system console is opened, VARIABLE_NAME environment variable exists.

In system console, execute the Node.js program in step 1, it will print mySensitiveInfo.

Switch to IDE and execute Node.js program, it will print undefined.

Restart the IDE and execute Node.js program, this time, it will print mySensitiveInfo


问:
tensorflow linker_flag in CROSSTOOL
I am working with Tensorflow 1.1.0 with gcc 5.2.0 and bazel 0.4.5
When I do:

```    ./configure
    bazel build --verbose_failures --config=opt //tensorflow/tools/pip_package:build_pip_package```

I got the following error messages:

```ERROR: /remote/us03home4/rogerlo/.cache/bazel/_bazel_rogerlo/c6e718933b1d81ab029d890c5eecbc01/external/protobuf/BUILD:67
9:1: null failed: protoc failed: error executing command
  (cd /remote/us03home4/rogerlo/.cache/bazel/_bazel_rogerlo/c6e718933b1d81ab029d890c5eecbc01/execroot/tensorflow && \
  exec env - \
  bazel-out/host/bin/external/protobuf/protoc '--python_out=bazel-out/local-opt/genfiles/external/protobuf/python' -Iexternal/protobuf/python -Ibazel-out/local-opt/genfiles/external/protobuf/python bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/any.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/api.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/compiler/plugin.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/descriptor.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/duration.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/empty.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/field_mask.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/source_context.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/struct.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/timestamp.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/type.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/wrappers.proto): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by bazel-out/host/bin/external/protobuf/protoc)
____Building complete.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
____Elapsed time: 101.992s, Critical Path: 54.24s
make: *** [tensorflow] Error 1```

But if I added this line:

```    linker_flag: "-Wl,-rpath,/depot/gcc-5.2.0/lib64"```

to the file

```    $TENSORFLOW_ROOT/bazel-tensorflow/external/local_config_cc/CROSSTOOL```

Build will pass.

I wonder if I can configure that linker_flag from the configure file or somewhere else?

I did add it to the build option but it doesn't work.

```    bazel build --verbose_failures --config=opt --linkopt="-Wl,-rpath,/depot/gcc-5.2.0/lib6
4" //tensorflow/tools/pip_package:build_pip_package```

EDIT: added bazel version

SOLUTION:

Add the linker option to the configuration of Bazel.

Recompile Bazel.

Compile Tensorflow with the recompiled Bazel will pass.

Investigation

The target is built by external crosstool, so the --linkopt won't work. According to the Bazel official blog, the configuration of external crosstool (C++) is auto detected. It points to the C++ configuration file.

linker_flag rpath is computed by $LD_LIBRARY_PATH. That is, if you have some library paths defined in $LD_LIBRARY_PATH, Bazel will generate their rpath in the linker_flag.

But that dependency is removed because of [issue#2099](github.com/bazelbuild/bazel/issues/2099)

So setting $LD_LIBRARY_PATH doesn't work in [v0.4.5](github.com/bazelbuild/bazel/blob/0.4.5/tools/cpp/cc_configure.bzl#L250)

However, I haven't figure out how to do it correctly (setting env_action or something). So the quick solution is to hardcode it in the configuration file.

(Forgive me about the ugly hyperlinks above. My reputation is not enough to have more than 2 links in a post.)

答:
[Copy my answer here]

SOLUTION:

Add the linker option to the configuration of Bazel.

Recompile Bazel.

Compile Tensorflow with the recompiled Bazel will pass.

Investigation

The target is built by external crosstool, so the --linkopt won't work. According to the Bazel official blog, the configuration of external crosstool (C++) is auto detected. It points to the C++ configuration file.

linker_flag rpath is computed by $LD_LIBRARY_PATH. That is, if you have some library paths defined in $LD_LIBRARY_PATH, Bazel will generate their rpath in the linker_flag.

But that dependency is removed because of [issue#2099](github.com/bazelbuild/bazel/issues/2099)

So setting $LD_LIBRARY_PATH doesn't work in [v0.4.5](github.com/bazelbuild/bazel/blob/0.4.5/tools/cpp/cc_configure.bzl#L250)

However, I haven't figure out how to do it correctly (setting env_action or something). So the quick solution is to hardcode it in the configuration file.

(Forgive me about the ugly hyperlinks above. My reputation is not enough to have more than 2 links in a post.)

Title: tensorflow linker_flag in CROSSTOOL

Body:
I am working with Tensorflow 1.1.0 with gcc 5.2.0 and bazel 0.4.5
When I do:

    ./configure
    bazel build --verbose_failures --config=opt //tensorflow/tools/pip_package:build_pip_package

I got the following error messages:

ERROR: /remote/us03home4/rogerlo/.cache/bazel/_bazel_rogerlo/c6e718933b1d81ab029d890c5eecbc01/external/protobuf/BUILD:67
9:1: null failed: protoc failed: error executing command
  (cd /remote/us03home4/rogerlo/.cache/bazel/_bazel_rogerlo/c6e718933b1d81ab029d890c5eecbc01/execroot/tensorflow && \
  exec env - \
  bazel-out/host/bin/external/protobuf/protoc '--python_out=bazel-out/local-opt/genfiles/external/protobuf/python' -Iexternal/protobuf/python -Ibazel-out/local-opt/genfiles/external/protobuf/python bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/any.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/api.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/compiler/plugin.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/descriptor.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/duration.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/empty.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/field_mask.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/source_context.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/struct.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/timestamp.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/type.proto bazel-out/local-opt/genfiles/external/protobuf/python/google/protobuf/wrappers.proto): com.google.devtools.build.lib.shell.BadExitStatusException: Process exited with status 1.
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.20' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `CXXABI_1.3.8' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by bazel-out/host/bin/external/protobuf/protoc)
bazel-out/host/bin/external/protobuf/protoc: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by bazel-out/host/bin/external/protobuf/protoc)
____Building complete.
Target //tensorflow/tools/pip_package:build_pip_package failed to build
____Elapsed time: 101.992s, Critical Path: 54.24s
make: *** [tensorflow] Error 1

But if I added this line:

    linker_flag: "-Wl,-rpath,/depot/gcc-5.2.0/lib64"

to the file

    $TENSORFLOW_ROOT/bazel-tensorflow/external/local_config_cc/CROSSTOOL

Build will pass.

I wonder if I can configure that linker_flag from the configure file or somewhere else?

I did add it to the build option but it doesn't work.

    bazel build --verbose_failures --config=opt --linkopt="-Wl,-rpath,/depot/gcc-5.2.0/lib6
4" //tensorflow/tools/pip_package:build_pip_package

EDIT: added bazel version

SOLUTION:

Add the linker option to the configuration of Bazel.

Recompile Bazel.

Compile Tensorflow with the recompiled Bazel will pass.

Investigation

The target is built by external crosstool, so the --linkopt won't work. According to the Bazel official blog, the configuration of external crosstool (C++) is auto detected. It points to the C++ configuration file.

linker_flag rpath is computed by $LD_LIBRARY_PATH. That is, if you have some library paths defined in $LD_LIBRARY_PATH, Bazel will generate their rpath in the linker_flag.

But that dependency is removed because of [issue#2099](github.com/bazelbuild/bazel/issues/2099)

So setting $LD_LIBRARY_PATH doesn't work in [v0.4.5](github.com/bazelbuild/bazel/blob/0.4.5/tools/cpp/cc_configure.bzl#L250)

However, I haven't figure out how to do it correctly (setting env_action or something). So the quick solution is to hardcode it in the configuration file.

(Forgive me about the ugly hyperlinks above. My reputation is not enough to have more than 2 links in a post.)


问:
Using Dynamic Code in C# with Events?
I'm currently implementing a script engine in a game I wrote using the C# "dynamic" feature.

How the system should work is when a script is called, it should register the events it listens for, then return control to the application. Then when an event that the script is listening for is fired the script should execute. One thing I'd really like to implement in the script engine is to have methods with certain names automatically bind to events. For example, the onTurnStart() listener should automatically bind to the turnStart event.

The scripts will mostly need to execute existing methods and change variable values in classes; stuff like player.takeDamage() and player.HP = somevalue. Most scripts will need to wait for the start of the players' turn and the end of the players' turn before being unloaded.

The complicated part is that these scripts need to be able to be changed without making any code changes to the game. (Security aside) the current plan is to have all the script changes automatically download when the game starts up to ensure all the players are using the same version of the scripts.

However I have three questions:

1) How do I register and unregister the script event listeners?

2) Can dynamic code listen for events?

3) (How) can I register events dynamically?

This is my first time using C#'s dynamic feature, so any help will be appreciated.

Thanks

--Michael

答:
I'm not sure you've got the right end of the stick with the dynamic keyword. It doesn't by itself let you interpret new code at runtime. All it does it let you bypass static type checking by delaying the resolution of operations until runtime.

If you're looking to "script" your game, you probably want to take a look at integrating Lua, IronPython, or one of the other DLR languages:-

C#/.NET scripting library

IronRuby and Handling XAML UI Events

Otherwise, the usual thing to do is have something along the lines of:-

```<code>interface IBehavior
{
  // Binds whatever events this behaviour needs, and optionally adds
  // itself to a collection of behaviours on the entity.
  void Register(Entity entity);
}

// Just an example
public abstract class TurnEndingDoSomethingBehavior
{
  public void Register(Entity entity)
  {
    entity.TurnEnding += (s, e) => DoSomething();
  }

  private abstract void DoSomething();
}
</code>```

The question is, do you want to be able to add entirely new behaviours after compile-time? If so you'll need to expose some or all of your game-state to a scripting language.

Or is it sufficient to be able to compose existing behaviours at runtime?

After your edit

I'm still unsure, to be honest, about your requirement for the dynamic keyword and the DLR. Your game's launcher can download a class library full of behaviours just as easily as it can pull down a set of scripts! (That's what Minecraft's launcher does if memory serves)

If you absolutely must use the DLR then take a look at the links I posted. You'll have to expose as much of your game state as necessary to one of the DLR languages. Events get exposed as first-order-function properties. You shouldn't even need the "dynamic" keyword for basic stuff.

Quick example in IronPython:-

```<code>def DoSomethingWhenDamageTaken(*args):
  #do whatever...

player.DamageTaken += DoSomethingWhenDamageTaken
</code>```

The player class:-

```<code>public class Player
{
  public event EventHandler DamageTaken;

  // ...
}
</code>```

You set it up like:-

```<code>ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

// In an actual application you might even be
// parsing the script from user input.
ScriptSource source = engine.CreateScriptSourceFromFile(...);

Player p = new Player();
scope.SetVariable("player", p);
source.Execute(scope);
</code>```

Some links to get you started:-

IronPython: http://ironpython.net/

IronRuby: http://www.ironruby.net/

Lua: http://www.lua.inf.puc-rio.br/post/9

Title: Using Dynamic Code in C# with Events?

Body:
I'm not sure you've got the right end of the stick with the dynamic keyword. It doesn't by itself let you interpret new code at runtime. All it does it let you bypass static type checking by delaying the resolution of operations until runtime.

If you're looking to "script" your game, you probably want to take a look at integrating Lua, IronPython, or one of the other DLR languages:-

C#/.NET scripting library

IronRuby and Handling XAML UI Events

Otherwise, the usual thing to do is have something along the lines of:-

interface IBehavior
{
  // Binds whatever events this behaviour needs, and optionally adds
  // itself to a collection of behaviours on the entity.
  void Register(Entity entity);
}

// Just an example
public abstract class TurnEndingDoSomethingBehavior
{
  public void Register(Entity entity)
  {
    entity.TurnEnding += (s, e) => DoSomething();
  }

  private abstract void DoSomething();
}

The question is, do you want to be able to add entirely new behaviours after compile-time? If so you'll need to expose some or all of your game-state to a scripting language.

Or is it sufficient to be able to compose existing behaviours at runtime?

After your edit

I'm still unsure, to be honest, about your requirement for the dynamic keyword and the DLR. Your game's launcher can download a class library full of behaviours just as easily as it can pull down a set of scripts! (That's what Minecraft's launcher does if memory serves)

If you absolutely must use the DLR then take a look at the links I posted. You'll have to expose as much of your game state as necessary to one of the DLR languages. Events get exposed as first-order-function properties. You shouldn't even need the "dynamic" keyword for basic stuff.

Quick example in IronPython:-

def DoSomethingWhenDamageTaken(*args):
  #do whatever...

player.DamageTaken += DoSomethingWhenDamageTaken

The player class:-

public class Player
{
  public event EventHandler DamageTaken;

  // ...
}

You set it up like:-

ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();

// In an actual application you might even be
// parsing the script from user input.
ScriptSource source = engine.CreateScriptSourceFromFile(...);

Player p = new Player();
scope.SetVariable("player", p);
source.Execute(scope);

Some links to get you started:-

IronPython: http://ironpython.net/

IronRuby: http://www.ironruby.net/

Lua: http://www.lua.inf.puc-rio.br/post/9


问:
c# change color of duplicates rows on datagridview
Photo of datagridview

i have this datagridview on picture above and "Joe" name is duplicate on it
how can to highlight or change color to red for duplicates values like "Joe" by c#?
thanks:)

答:
Can you try this:</p>

```<code>    //using System.Linq;
    private void button1_Click(object sender, EventArgs e)
    {
        var rows = dataGridView1.Rows.OfType<DataGridViewRow>()
            .Reverse().Skip(1);//ignore the last empty line
        var dupRos = rows.GroupBy(r => r.Cells["name"].Value.ToString())
        .Where(g => g.Count() > 1)
        .SelectMany(r => r.ToList());
        foreach (var r in dupRos)
            r.DefaultCellStyle.BackColor = Color.Red;
        foreach (var r in rows.Except(dupRos))
            r.DefaultCellStyle.BackColor = Color.White;
    }
</code>```

Body:
Can you try this:

    //using System.Linq;
    private void button1_Click(object sender, EventArgs e)
    {
        var rows = dataGridView1.Rows.OfType<DataGridViewRow>()
            .Reverse().Skip(1);//ignore the last empty line
        var dupRos = rows.GroupBy(r => r.Cells["name"].Value.ToString())
        .Where(g => g.Count() > 1)
        .SelectMany(r => r.ToList());
        foreach (var r in dupRos)
            r.DefaultCellStyle.BackColor = Color.Red;
        foreach (var r in rows.Except(dupRos))
            r.DefaultCellStyle.BackColor = Color.White;
    }


问:
Is okio 1.9.0 backward compatible with okio 1.2.0?
My project depends on a couple of third party libraries, which bring in okio v. 1.9.0 and 1.2.0, respectively.

Can I count on backward compatibility, and just use okio version 1.9.0 (in place of 1.2.0)?

答: Yes, all 1.x versions of Okio are API-compatible. Check the CHANGELOG for details.</p>


问:
How to pass jq values to a variable in linux bash script
Can someone please help me out?

I am working on a raspberry pi project and i wanted to control my pins from the cloud. I have this bash script that connects to a web service periodically to check this response. {"status":1,"pin":4}

I am using jq and i was able to get the values that i need using

```<code>source gpio

foo = $(curl '{webservice_url}')
echo ${foo} | jq '.status'
echo ${foo} | jq '.pin'
</code>```

output : 1 and 4

problem is when i try to pass the value to a variable and use them it doesn't work

i tried:

```<code> foo = $(curl '{webservice_url}')
 status = `${foo} | jq '.status'`
 pin = `${foo} | jq '.pin'`

 echo "$status"
 echo "$pin"
</code>```

I tried using echo ${status} and still
the error says

  status: command not found

  pin: command not found

also i tried

```<code>source gpio
while true; do
   foo = $(curl '{webservice_url}')
   gpio mode "${foo} | jq '.pin'" out
   gpio write "${foo} | jq '.status'" 1
   sleep 1
done
</code>```

but its not working.

Thank you in advance

答:
Here is an illustration of how you can achieve what you want using bash and jq:

```<code># foo=$(curl '{webservice_url}')
foo='{"status": "S", "pin": "P"}'
status=$(jq .status <<< ${foo})
pin=$(jq .pin  <<< ${foo})

echo "$status"
echo "$pin"
</code>```

Since this involves one invocation of jq per variable, it might be worthwhile using an alternative approach.  If your bash has readarray (aka mapfile), then consider:

```<code>readarray -t lines <<< $(jq -cr .status,.pin <<< ${foo})
status=${lines[0]}
pin=${lines[1]}
</code>```

Otherwise:

```<code>i=0
while read -r line
do
    i=$((i+1))
    a[$i]="$line"
done < <(jq -cr .status,.pin <<< ${foo})
</code>```

Using @tsv

Here's a slightly different approach that relies on the fact that literal tabs cannot appear in JSON strings:

```<code>IFS=$'\t' read status pin < <(jq -r '[.status,.pin]|@tsv' <<< ${foo})
</code>```

Body:
Can someone please help me out?

I am working on a raspberry pi project and i wanted to control my pins from the cloud. I have this bash script that connects to a web service periodically to check this response. {"status":1,"pin":4}

I am using jq and i was able to get the values that i need using

source gpio

foo = $(curl '{webservice_url}')
echo ${foo} | jq '.status'
echo ${foo} | jq '.pin'

output : 1 and 4

problem is when i try to pass the value to a variable and use them it doesn't work

i tried:

 foo = $(curl '{webservice_url}')
 status = `${foo} | jq '.status'`
 pin = `${foo} | jq '.pin'`

 echo "$status"
 echo "$pin"

I tried using echo ${status} and still
the error says

  status: command not found

  pin: command not found

also i tried

source gpio
while true; do
   foo = $(curl '{webservice_url}')
   gpio mode "${foo} | jq '.pin'" out
   gpio write "${foo} | jq '.status'" 1
   sleep 1
done

but its not working.

Thank you in advance

Body:
Here is an illustration of how you can achieve what you want using bash and jq:

# foo=$(curl '{webservice_url}')
foo='{"status": "S", "pin": "P"}'
status=$(jq .status <<< ${foo})
pin=$(jq .pin  <<< ${foo})

echo "$status"
echo "$pin"

Since this involves one invocation of jq per variable, it might be worthwhile using an alternative approach.  If your bash has readarray (aka mapfile), then consider:

readarray -t lines <<< $(jq -cr .status,.pin <<< ${foo})
status=${lines[0]}
pin=${lines[1]}

Otherwise:

i=0
while read -r line
do
    i=$((i+1))
    a[$i]="$line"
done < <(jq -cr .status,.pin <<< ${foo})

Using @tsv

Here's a slightly different approach that relies on the fact that literal tabs cannot appear in JSON strings:

IFS=$'\t' read status pin < <(jq -r '[.status,.pin]|@tsv' <<< ${foo})


问:
Why am I getting a syntax error in setting this Array into a class?
I am getting a syntax error but I don;t understand exactly why, here is my code:

```<code>class VerifyEmail {

     private $ip_pool = array("167.114.48.81","167.114.48.82"....);
     private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool)]; //ERROR HERE
     .....
</code>```

I tried also:

```<code>     private $ip_to_use = $ip_pool[array_rand($ip_pool)];
</code>```

with no luck.

Am I missing something? Or you cannot do an array rand of a private variable when setting up the variables?

Thanks!

答:
You're currently trying to access the array as an index of the array itself.

Considering you're just trying to assign one string from within the $ip_pool array to $ip_to_use, all you need is $ip_to_use = array_rand($this->ip_pool).

```<code>class VerifyEmail {
  private $ip_pool = array("167.114.48.81","167.114.48.82"....);
  private $ip_to_use = array_rand($this->ip_pool);
  ...
</code>```

Hope this helps! :)

Body:
I am getting a syntax error but I don;t understand exactly why, here is my code:

class VerifyEmail {

     private $ip_pool = array("167.114.48.81","167.114.48.82"....);
     private $ip_to_use = $this->ip_pool[array_rand($this->ip_pool)]; //ERROR HERE
     .....

I tried also:

     private $ip_to_use = $ip_pool[array_rand($ip_pool)];

with no luck.

Am I missing something? Or you cannot do an array rand of a private variable when setting up the variables?

Thanks!

Body:
You're currently trying to access the array as an index of the array itself.

Considering you're just trying to assign one string from within the $ip_pool array to $ip_to_use, all you need is $ip_to_use = array_rand($this->ip_pool).

class VerifyEmail {
  private $ip_pool = array("167.114.48.81","167.114.48.82"....);
  private $ip_to_use = array_rand($this->ip_pool);
  ...

Hope this helps! :)


问:
Post articles from pages on my blog automatically
Can I make my blog create posts from articles or from other pages automatically?</p>

答: yes it is possible. no there isn't an automated tool to do it for you. plus it sounds like blatant copyright infringement.</p>


问:
extra characters after \ at the end of a command
When I try to insert new line in OSX using sed I'm getting the below error

extra characters after \ at the end of a command

Current File content is

```<code>{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}
</code>```

Expected content is

```<code>{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
 'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}
</code>```

The command I'm using is

```<code>sed -i '' "/localhost/a\                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web']," FILENAME
</code>```

答:
BSD/macOS sed requires an actual newline character to follow a\, before the text to append:

sed -i '' "/localhost/ a\\
                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web'],
" FILENAME
```

Since you're using "..." to enclose your sed script, a\ must be represented as a\\ so that the \ is not mistaken for a line continuation character.

It is generally better to use '...' to enclose your script argument, but here the use of "..." is convenient for easy embedding of ' instances.

As an aside: GNU sed - installable on macOS via Homebrew using brew install gnu-sed - offers more features and more convenient syntax - notably, no need for a newline to follow the a function; for a discussion of all differences between BSD/macOS sed and GNU sed, see this answer of mine.

Body:
When I try to insert new line in OSX using sed I'm getting the below error

extra characters after \ at the end of a command

Current File content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

Expected content is

{
'localhost' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
 'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'mobile'],
}

The command I'm using is

sed -i '' "/localhost/a\                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web']," FILENAME

Body:
BSD/macOS sed requires an actual newline character to follow a\, before the text to append:

sed -i '' "/localhost/ a\\
                        'dev.ops' => ['domain_name' => 'default', 'domain_type' => 'web'],
" FILENAME

Since you're using "..." to enclose your sed script, a\ must be represented as a\\ so that the \ is not mistaken for a line continuation character.

It is generally better to use '...' to enclose your script argument, but here the use of "..." is convenient for easy embedding of ' instances.

As an aside: GNU sed - installable on macOS via Homebrew using brew install gnu-sed - offers more features and more convenient syntax - notably, no need for a newline to follow the a function; for a discussion of all differences between BSD/macOS sed and GNU sed, see this answer of mine.

ContentLicense: CC BY-SA 4.0


问:
Drupal "You are not authorized to access this page"
I've taken over managing our site from MIA developers and have spent the day trying to find this answer.

After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).

Here's what I know:

Drupal Version 7.56

PHP 7.0.20

No errors when status report is run

Chron - no errors

Here's what I've done:

added $cookie_domain = '.example.com'; to settings.php

cleared browser cache and cookies

ensured admin has access to everything

cleared site cache

made sure code on page(s) was exactly the same as it was before I did the update

Not sure what to do or where to go from here. Any help is much appreciated.

UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.

Image 1: viewing page as admin

Image 2: viewing page as superadmin

```<code>function custom_reports_menu() {

    $items['administration/upcoming-classes'] = array(
    'title' => 'Upcoming Classes',
    'page callback' => 'custom_reports_upcoming_classes_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.upcoming-classes.inc',
    'type' => MENU_CALLBACK,
    );

    $items['administration/class-details'] = array(
    'title' => 'Class Details',
    'page callback' => 'custom_reports_class_details_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.class-details.inc',
    'type' => MENU_CALLBACK,
    );
    return $items;

}

function custom_reports_upcoming_classes_page() {

    drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));

    global $user;
    $uid = $user->uid;

    $output = '';

    $upcoming_classes = custom_reports_get_upcoming_classes();
    $attendee_count = custom_reports_get_attendee_count();

    // upcoming classes
    $output .= '<h2>Upcoming Classes</h2>';
    $output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);

    return $output;
}

function custom_reports_permission() {

  return array(
    'admin wdcc reports' => array(
      'title' => t('Admin WDCC Reports'),
      'description' => t('Perform administration tasks for WDCC.'),
      //'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function custom_reports_get_upcoming_classes() {

    $today = date('Y-m-d');

    $x = 0;
    $classes = '';

    // get classes from new db tables
    $today = date('Y-m-d H:i:s');

    $result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {

            $nid = $row->nid;
            $node = node_load($nid);

            $product_id = $nid;
            $product_title = $node->title;
            $product_type = 'public_class_date';
            $product_date = $node->field_date[$node->language][0]['value'];
            $product_datestamp = strtotime($product_date);
            //$product_datestamp = strtotime($product_date);

            // set vars
            $classes[$x]['product_id'] = $product_id;
            $classes[$x]['product_title'] = $product_title;
            $classes[$x]['product_type'] = $product_type;
            $classes[$x]['product_date'] = $product_date;
            $classes[$x]['product_datestamp'] = $product_datestamp;

            $x++;
        }
    }

    return $classes;
}

function custom_reports_get_attendee_count() {

    $attendees = array();
    $old_attendees = array();
    $new_attendees = array();

    $result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $item_id = $row->itemID;
            $attendee_id = 'B'.$row->attendeeID;
            $attendee_name = $row->attendeeName;

            $old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;

            if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
            } else {
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
            }
        }
    }
    if (is_array($old_attendees)) {
        $connect_class_ids = custom_accounts_connect_class_ids();
        foreach ($old_attendees as $old_item_id => $attendee_list) {
            if (isset($connect_class_ids[$old_item_id])) {
                $product_id = $connect_class_ids[$old_item_id];
                foreach ($attendee_list as $attendee_id => $attendee) {
                    $old_attendee_id = $attendee['old_attendee_id'];
                    $attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
                }
            }
        }
    }
    $result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->id;
            $product_id = $row->product_id;
            $attendees[$product_id][$attendee_id]['total_attendees'] = 1;
        }
    }
    $cancelled_attendees = array();
    $result = db_query("SELECT * FROM wdcc_attendees_cancelled");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->attendee_id;
            $old_attendee_id = 'B'.$row->old_attendee_id;

            if ($attendee_id > 0) {
                $cancelled_attendees[] = $attendee_id;
            } else {
                $cancelled_attendees[] = $old_attendee_id;
            }
        }
    }
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (in_array($attendee_id, $cancelled_attendees)) {
                unset($attendees[$product_id][$attendee_id]);
            }
        }
    }
    $attendee_count = array();
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (!isset($attendee_count[$product_id])) {
                $attendee_count[$product_id] = $attendee['total_attendees'];
            } else {
                $attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
            }
        }
    }

    return $attendee_count;
}

function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {

    $output = '';

    if (is_array($upcoming_classes)) {
        $output .= '<div class="table-responsive table-container">';
        $output .= '<table class="table">';
        $output .= '<tr><td>Class</td><td>Guests</td><td>Actions</td></tr>';
        foreach ($upcoming_classes as $class) {
            $nid = $class['product_id'];
            $node_url = url('node/'.$nid, array('absolute' => TRUE));
            $attendees = 0;
            if (isset($attendee_count[$nid])) {
                $attendees = $attendee_count[$nid];
            }

            $output .= '<tr><td><a href="'.$node_url.'">'.$class['product_title'].'</a><br />'.date('m/d/Y - g:i A', $class['product_datestamp']).'</td><td>'.$attendees.'</td><td><a href="/administration/class-details/'.$class['product_id'].'">View roster</a></td></tr>';
        }
        $output .= '</table>';
        $output .= '</div>';
    } else {
        $output .= '<p>No upcoming classes found.</p>';
    }

    return $output;
}
</code>```

答:
Probably would need more info, but it seems like a case of custom or hardcoded permissions.

Here's potential cases to explore:

Assign all the roles to the admin user

Search custom modules for this page URL. See if page is only certain users are allowed to access this page.

If report is Drupal View, find this view and check the permissions section.

Body:
I've taken over managing our site from MIA developers and have spent the day trying to find this answer.

After upgrading to v 7.56 there's just ONE specific page in a list of pages that I am unable to access as an admin. (and unfortunately it's probably the most needed report in our admin panel).

Here's what I know:

Drupal Version 7.56

PHP 7.0.20

No errors when status report is run

Chron - no errors

Here's what I've done:

added $cookie_domain = '.example.com'; to settings.php

cleared browser cache and cookies

ensured admin has access to everything

cleared site cache

made sure code on page(s) was exactly the same as it was before I did the update

Not sure what to do or where to go from here. Any help is much appreciated.

UPDATE: When logged in as super admin, received HTTP 500 error. After more research, I updated the php.ini to include memory_limit = 64M ;
Now I can view the page as the superadmin, but it still isn't available for other admins.

Image 1: viewing page as admin

Image 2: viewing page as superadmin

function custom_reports_menu() {

    $items['administration/upcoming-classes'] = array(
    'title' => 'Upcoming Classes',
    'page callback' => 'custom_reports_upcoming_classes_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.upcoming-classes.inc',
    'type' => MENU_CALLBACK,
    );

    $items['administration/class-details'] = array(
    'title' => 'Class Details',
    'page callback' => 'custom_reports_class_details_page',
    'access callback' => 'user_access',
    'access arguments' => array('admin wdcc reports'),
        'file' => 'includes/custom_reports.class-details.inc',
    'type' => MENU_CALLBACK,
    );
    return $items;

}

function custom_reports_upcoming_classes_page() {

    drupal_add_css(base_path().path_to_theme().'/assets/css/outburst-accounts.css', array('type' => 'external'));

    global $user;
    $uid = $user->uid;

    $output = '';

    $upcoming_classes = custom_reports_get_upcoming_classes();
    $attendee_count = custom_reports_get_attendee_count();

    // upcoming classes
    $output .= '
Upcoming Classes
';
    $output .= custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count);

    return $output;
}

function custom_reports_permission() {

  return array(
    'admin wdcc reports' => array(
      'title' => t('Admin WDCC Reports'),
      'description' => t('Perform administration tasks for WDCC.'),
      //'cache' => DRUPAL_NO_CACHE,
    ),
  );
}

function custom_reports_get_upcoming_classes() {

    $today = date('Y-m-d');

    $x = 0;
    $classes = '';

    // get classes from new db tables
    $today = date('Y-m-d H:i:s');

    $result = db_query("SELECT n.nid FROM node n, field_data_field_date fdfd WHERE n.status = :status AND n.type = :type AND n.nid = fdfd.entity_id AND fdfd.field_date_value >= :today ORDER BY fdfd.field_date_value ASC", array(':status' => 1, ':type' => 'public_class_date', ':today' => $today));
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {

            $nid = $row->nid;
            $node = node_load($nid);

            $product_id = $nid;
            $product_title = $node->title;
            $product_type = 'public_class_date';
            $product_date = $node->field_date[$node->language][0]['value'];
            $product_datestamp = strtotime($product_date);
            //$product_datestamp = strtotime($product_date);

            // set vars
            $classes[$x]['product_id'] = $product_id;
            $classes[$x]['product_title'] = $product_title;
            $classes[$x]['product_type'] = $product_type;
            $classes[$x]['product_date'] = $product_date;
            $classes[$x]['product_datestamp'] = $product_datestamp;

            $x++;
        }
    }

    return $classes;
}

function custom_reports_get_attendee_count() {

    $attendees = array();
    $old_attendees = array();
    $new_attendees = array();

    $result = db_query("SELECT itemID, attendeeID, attendeeName FROM wdcc_old_attendee");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $item_id = $row->itemID;
            $attendee_id = 'B'.$row->attendeeID;
            $attendee_name = $row->attendeeName;

            $old_attendees[$item_id][$attendee_id]['old_attendee_id'] = $attendee_id;

            if (strpos($attendee_name, '&') > 0 || strpos($attendee_name, ' and') > 0) { // couples
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 2;
            } else {
                $old_attendees[$item_id][$attendee_id]['total_attendees'] = 1;
            }
        }
    }
    if (is_array($old_attendees)) {
        $connect_class_ids = custom_accounts_connect_class_ids();
        foreach ($old_attendees as $old_item_id => $attendee_list) {
            if (isset($connect_class_ids[$old_item_id])) {
                $product_id = $connect_class_ids[$old_item_id];
                foreach ($attendee_list as $attendee_id => $attendee) {
                    $old_attendee_id = $attendee['old_attendee_id'];
                    $attendees[$product_id][$old_attendee_id]['total_attendees'] = $attendee['total_attendees'];
                }
            }
        }
    }
    $result = db_query("SELECT id, product_id FROM wdcc_attendees WHERE transaction_id > 0");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->id;
            $product_id = $row->product_id;
            $attendees[$product_id][$attendee_id]['total_attendees'] = 1;
        }
    }
    $cancelled_attendees = array();
    $result = db_query("SELECT * FROM wdcc_attendees_cancelled");
    if ($result->rowCount() > 0) {
        foreach ($result as $row) {
            $attendee_id = $row->attendee_id;
            $old_attendee_id = 'B'.$row->old_attendee_id;

            if ($attendee_id > 0) {
                $cancelled_attendees[] = $attendee_id;
            } else {
                $cancelled_attendees[] = $old_attendee_id;
            }
        }
    }
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (in_array($attendee_id, $cancelled_attendees)) {
                unset($attendees[$product_id][$attendee_id]);
            }
        }
    }
    $attendee_count = array();
    foreach ($attendees as $product_id => $product_attendees) {
        foreach ($product_attendees as $attendee_id => $attendee) {
            if (!isset($attendee_count[$product_id])) {
                $attendee_count[$product_id] = $attendee['total_attendees'];
            } else {
                $attendee_count[$product_id] = $attendee_count[$product_id] + $attendee['total_attendees'];
            }
        }
    }

    return $attendee_count;
}

function custom_reports_format_upcoming_classes($upcoming_classes, $attendee_count) {

    $output = '';

    if (is_array($upcoming_classes)) {
        $output .= '
';
        $output .= '
';
        $output .= '
Class	Guests	Actions
';
        foreach ($upcoming_classes as $class) {
            $nid = $class['product_id'];
            $node_url = url('node/'.$nid, array('absolute' => TRUE));
            $attendees = 0;
            if (isset($attendee_count[$nid])) {
                $attendees = $attendee_count[$nid];
            }

            $output .= '
'.$class['product_title'].'
'.date('m/d/Y - g:i A', $class['product_datestamp']).'	'.$attendees.'	View roster
';
        }
        $output .= '
';
        $output .= '
';
    } else {
        $output .= '
No upcoming classes found.
';
    }

    return $output;
}


问:
Concatenate in theano scan
I am having trouble figuring out why the following code doesn't work: </p>

```<code>import theano as th
import theano.tensor as tt

a = tt.vector("a")

res, up = th.scan(
    fn = lambda a : tt.concatenate([a,a]),
    outputs_info = a,
    n_steps = 2
)

f = th.function(inputs = [a], outputs=res)

f(np.array([1.]))
</code>```

<p>I would expect it to return the same as if </p>

```<code>f = th.function(
    inputs = [a],
    outputs = tt.concatenate([tt.concatenate([a,a]),tt.concatenate([a,a])])
)
</code>```

答:
In the theano.scan docstring:

... the initial state should have the same shape as the output ...

If your scan involves a recurrent expression on a vector, then the shape of that vector must not change.

```<code>lambda a: T.sqr(a)  # OK

lambda a: T.concat([a,a])  # ERROR
</code>```

The reason for that, scan internally uses a matrix to store your vector on all time steps. If the shape changes, the matrix would be ragged. While theoretically not impossible to implement, it introduces a lot more complexity and potential issues.

So, yeah, scan is a bit limited.

Title: Concatenate in theano scan

Body:
I am having trouble figuring out why the following code doesn't work:

import theano as th
import theano.tensor as tt

a = tt.vector("a")

res, up = th.scan(
    fn = lambda a : tt.concatenate([a,a]),
    outputs_info = a,
    n_steps = 2
)

f = th.function(inputs = [a], outputs=res)

f(np.array([1.]))

I would expect it to return the same as if

f = th.function(
    inputs = [a],
    outputs = tt.concatenate([tt.concatenate([a,a]),tt.concatenate([a,a])])
)

Body:
In the theano.scan docstring:

... the initial state should have the same shape as the output ...

If your scan involves a recurrent expression on a vector, then the shape of that vector must not change.

lambda a: T.sqr(a)  # OK

lambda a: T.concat([a,a])  # ERROR

The reason for that, scan internally uses a matrix to store your vector on all time steps. If the shape changes, the matrix would be ragged. While theoretically not impossible to implement, it introduces a lot more complexity and potential issues.

So, yeah, scan is a bit limited.


问:
Apply iCheck (jQuery plugin) to dynamically created CheckBoxes
I use the fantastic iCheck plugin to style my checkboxes in my form.

With the plugin, I am able to just call $('input').iCheck() to apply the desired look and functionality.

However, I am stuck at calling the .iCheck() function on dynamically created checkboxes.

In an ajax call, I build my checkboxes as follows in the success function; This is in an $.each block but for simplicity purposes, I've only included code within the statement.

```<code>var chk = $('<div><input id="' + n.ID + '" type="checkbox" name="lblChk"><label for="' + n.ID + '">' + n.Title + '</label></div>');
el.append(chk);
</code>```

Where el is a div with the id of container that already exists in the DOM tree and n is my object returned as JSON

After building the checkboxes and I call $('#container input').iCheck(); obviously I get nothing special but standard checkboxes. I presume it is because the checkboxes are created dynamically and after the .iCheck() is called. But even after I create checkboxes and call .iCheck() the result is the same.

Can anyone guide me on this?

答:
I just encountered the same problem and the solution is simple: call the iCheck method.</p>

```<code>var id = some_id;
var one_row = "<tr><td>...<td><td><input type=\"radio\" class=\"minimal\" id=\"" + id + "\" name=\"" + id + "\">radio1</td></tr>";
// add this row to HTML
// call the initialize method
$('#'+id).iCheck({radioClass: 'iradio_minimal-blue'});
</code>```

Body:
I use the fantastic iCheck plugin to style my checkboxes in my form.

With the plugin, I am able to just call $('input').iCheck() to apply the desired look and functionality.

However, I am stuck at calling the .iCheck() function on dynamically created checkboxes.

In an ajax call, I build my checkboxes as follows in the success function; This is in an $.each block but for simplicity purposes, I've only included code within the statement.

var chk = $('
<input id="' + n.ID + '" type="checkbox" name="lblChk">' + n.Title + '
');
el.append(chk);

Where el is a div with the id of container that already exists in the DOM tree and n is my object returned as JSON

After building the checkboxes and I call $('#container input').iCheck(); obviously I get nothing special but standard checkboxes. I presume it is because the checkboxes are created dynamically and after the .iCheck() is called. But even after I create checkboxes and call .iCheck() the result is the same.

Can anyone guide me on this?

Body:
I just encountered the same problem and the solution is simple: call the iCheck method.

var id = some_id;
var one_row = "<tr><td>...<td><td><input type=\"radio\" class=\"minimal\" id=\"" + id + "\" name=\"" + id + "\">radio1</td></tr>";
// add this row to HTML
// call the initialize method
$('#'+id).iCheck({radioClass: 'iradio_minimal-blue'});


问:
Assume f() is defined. In the statement a = f(), a is always a function.
Assume f() is defined. In the statement a = f(), a is always a function.

Why it is wrong?

答:
If you do a = f()  a become what the function f returns. It can be anything, even a function too as long as f() returns a function.

If you do a = f  and f is a function already defined , then a always be a function as long as you don't re-define a.


问:
Remove all space on input text using javascript
here is my html:

```<code><input class="form" type="text" placeholder="test" />
</code>```

and my JS

```<code>var str = $(".form").val();
var newStr = str.replace(/\s+/g, '');
</code>```

there is no space when user input text. How to I create the javascript? anybody help? Thank you

答:
If you want to remove starting and ending spaces use trim()

var value  = "  some text to trim  ";

console.log(value.trim());```
</div>
</div>
</p>

<p>If you want to remove all the spaces in entire string use replace</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var value = "Some text to replace spaces";
var newStr = value.replace(/\s+/g, '');
console.log(newStr);</code>```

```

Body:
here is my html:

<input class="form" type="text" placeholder="test" />

and my JS

var str = $(".form").val();
var newStr = str.replace(/\s+/g, '');

there is no space when user input text. How to I create the javascript? anybody help? Thank you

Body:
If you want to remove starting and ending spaces use trim()

var value  = "  some text to trim  ";

console.log(value.trim());

If you want to remove all the spaces in entire string use replace

var value = "Some text to replace spaces";
var newStr = value.replace(/\s+/g, '');
console.log(newStr);

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