问:
android.support.v7.internal.widget.ActionBarOverlayLayout could not be instantiated
I installed (Android studio 1.2 + SDK pack) for the first time, I created a test project with demo tab activity. I have not written a single line of code, everything has been generated by Android Studio

In fragment_main.xml the following problem occurs.

```<code>java.lang.ClassNotFoundException: android.support.v4.view.ViewPropertyAnimatorListener
    at org.jetbrains.android.uipreview.ModuleClassLoader.load(ModuleClassLoader.java:127)
    at com.android.tools.idea.rendering.RenderClassLoader.findClass(RenderClassLoader.java:53)
    at org.jetbrains.android.uipreview.ModuleClassLoader.findClass(ModuleClassLoader.java:84)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getConstructor0(Class.java:2885)
    at java.lang.Class.getConstructor(Class.java:1723)
    at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:348)
    at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
    at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:177)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:214)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:142)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
    at com.android.layoutlib.bridge.bars.BridgeActionBar.<init>(BridgeActionBar.java:84)
    at com.android.layoutlib.bridge.bars.AppCompatActionBar.<init>(AppCompatActionBar.java:56)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.createActionBar(RenderSessionImpl.java:1691)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:362)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:321)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:497)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:485)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:894)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:485)
    at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:590)
    at com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel$6.run(AndroidDesignerEditorPanel.java:480)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:351)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
</code>```

xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity$PlaceholderFragment">

    <TextView android:id="@+id/section_label" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
</code>```

Activity(No code errors here but I am surprised to see calls of deprecated functions in a demo code):

```<code>import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}
</code>```

答:
by changing res/values/styles.xml to

```<code><!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
</code>```

do DarkActionBarTheme or
    NoActionBar

Body:
I installed (Android studio 1.2 + SDK pack) for the first time, I created a test project with demo tab activity. I have not written a single line of code, everything has been generated by Android Studio

In fragment_main.xml the following problem occurs.

java.lang.ClassNotFoundException: android.support.v4.view.ViewPropertyAnimatorListener
    at org.jetbrains.android.uipreview.ModuleClassLoader.load(ModuleClassLoader.java:127)
    at com.android.tools.idea.rendering.RenderClassLoader.findClass(RenderClassLoader.java:53)
    at org.jetbrains.android.uipreview.ModuleClassLoader.findClass(ModuleClassLoader.java:84)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2585)
    at java.lang.Class.getConstructor0(Class.java:2885)
    at java.lang.Class.getConstructor(Class.java:1723)
    at org.jetbrains.android.uipreview.ViewLoader.createNewInstance(ViewLoader.java:348)
    at org.jetbrains.android.uipreview.ViewLoader.loadView(ViewLoader.java:105)
    at com.android.tools.idea.rendering.LayoutlibCallback.loadView(LayoutlibCallback.java:177)
    at android.view.BridgeInflater.loadCustomView(BridgeInflater.java:214)
    at android.view.BridgeInflater.createViewFromTag(BridgeInflater.java:142)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:482)
    at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
    at com.android.layoutlib.bridge.bars.BridgeActionBar.<init>(BridgeActionBar.java:84)
    at com.android.layoutlib.bridge.bars.AppCompatActionBar.<init>(AppCompatActionBar.java:56)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.createActionBar(RenderSessionImpl.java:1691)
    at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:362)
    at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:321)
    at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:350)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:497)
    at com.android.tools.idea.rendering.RenderTask$2.compute(RenderTask.java:485)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:894)
    at com.android.tools.idea.rendering.RenderTask.createRenderSession(RenderTask.java:485)
    at com.android.tools.idea.rendering.RenderTask.render(RenderTask.java:590)
    at com.intellij.android.designer.designSurface.AndroidDesignerEditorPanel$6.run(AndroidDesignerEditorPanel.java:480)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:320)
    at com.intellij.util.ui.update.MergingUpdateQueue.execute(MergingUpdateQueue.java:310)
    at com.intellij.util.ui.update.MergingUpdateQueue$2.run(MergingUpdateQueue.java:254)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:269)
    at com.intellij.util.ui.update.MergingUpdateQueue.flush(MergingUpdateQueue.java:227)
    at com.intellij.util.ui.update.MergingUpdateQueue.run(MergingUpdateQueue.java:217)
    at com.intellij.util.concurrency.QueueProcessor.runSafely(QueueProcessor.java:238)
    at com.intellij.util.Alarm$Request$1.run(Alarm.java:351)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity$PlaceholderFragment">

    <TextView android:id="@+id/section_label" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Activity(No code errors here but I am surprised to see calls of deprecated functions in a demo code):

import java.util.Locale;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    ViewPager mViewPager;

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

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

Body:
by changing res/values/styles.xml to

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->

do DarkActionBarTheme or
    NoActionBar


来源: stackexchange

问:
Most reliable way of comparing datetimes?
I primarly use Delphi in my workplace and during some thorough unit tests which involved comparing date times I discovered that a direct comparison using the equals operator was not reliable enough when comparing calculated dates etc. So as a rule I started using CompareDateTime and SameDateTime which are built in functions for date comparisons in Delphi.

In C# by force of habit I compare date/times using the standard operators =<>. We have similar functions like DateTime.Compare and DateTime.Equals for date time comparisons therefore in terms of accuracy & reliability should I really be using the built in functions instead?

Will they give me a more accurate comparison that using the operator?

答:
Given that your date/times are calculated you'd be better off calculating the difference between the times which gives you a TimeSpan.

```<code>TimeSpan travelTime = arrival - departure;
</code>```

You can then check that this is less than your allowed tolerance.

```<code>if (Math.Abs(travelTime.TotalMilliseconds) < tolerance)
{
    // times are equal.
}
</code>```

This similar to the approach you need to take for floating point values, but is independent of that as in this case the inaccuracy stems from your data not how it's represented in memory.

ContentLicense: CC BY-SA 2.5

Body:
Given that your date/times are calculated you'd be better off calculating the difference between the times which gives you a TimeSpan.

TimeSpan travelTime = arrival - departure;

You can then check that this is less than your allowed tolerance.

if (Math.Abs(travelTime.TotalMilliseconds) < tolerance)
{
    // times are equal.
}

This similar to the approach you need to take for floating point values, but is independent of that as in this case the inaccuracy stems from your data not how it's represented in memory.


问:
Regex to skip 1 but allow n number of 1s
I try to create a regular expression which skips 1 but should allow n number of 1s.

I tried using ^([^1])*)$

It skipped 1 but also skipping any 1s.

答:
Code

See regex in use here

```<code>\b1{2,}\b
</code>```

To match any number except 1, you can use the following regex:

See regex in use here

```<code>\b(?!1\b)\d+\b
</code>```

Results

Input

```<code>1
11
111
1111
</code>```

Output

Only matches are shown below

```<code>11
111
1111
</code>```

Explanation

\b Assert position as a word boundary

1{2,} Match the digit 1 (literally) two or more times

\b Assert position as a word boundary

ContentLicense: CC BY-SA 3.0

Body:
Code

See regex in use here

\b1{2,}\b

To match any number except 1, you can use the following regex:

See regex in use here

\b(?!1\b)\d+\b

Results

Input

1
11
111
1111

Output

Only matches are shown below

11
111
1111

Explanation

\b Assert position as a word boundary

1{2,} Match the digit 1 (literally) two or more times

\b Assert position as a word boundary


问:
opencsv does not export attributes of parent class
I use com.opencsv 4.1 and I want to export an entity class to a csv file.
The problem is that this entity class extends another class. So, when I export it, I get only the fields of the child class.

Below is my code for writting to the csv file:

```<code>List<ActiveSubstance> activeSubstances = getActiveSubstances();
    File reportFile = new File( "activeSubstances.csv");
    Writer writer = new PrintWriter(reportFile);

    StatefulBeanToCsv<ActiveSubstance> beanToCsv = new StatefulBeanToCsvBuilder<ActiveSubstance>(writer)
        .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
        .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
        .build();
    beanToCsv.write(activeSubstances);
    writer.close();
</code>```

The exported file that I get has the below line:

```<code> ,,false,xx.model.ActiveSubstanceClass@29f9a8b9
</code>```

My parent class:

```<code>@MappedSuperclass
public abstract class AbstractEntity {

  @Id
  @DiffIgnore
  @Column(name = "UUID")
  @CsvBindByName(column = "UUID")
  @CsvBindByPosition(position = 0)
  private String uuid;

  @Column(name = "CODE")
  @CsvBindByName(column = "CODE")
  @CsvBindByPosition(position = 1)
  private String code;

 public String getUuid() {
    return uuid;
  }

  public void setUuid(String uuid) {
    this.uuid = uuid;
  }

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }
}
</code>```

My child class:

```<code>@Entity
@Table(name = "T_ACTIVE_SUBSTANCE")
public class ActiveSubstance extends AbstractEntity {

  @Column(name = "CRITICAL")
  @CsvBindByName(column = "CRITICAL")
  @CsvBindByPosition(position = 3)
  private Boolean critical;

  @ManyToOne
  @JoinColumn(name = "ACTIVE_SUBSTANCE_CLASS_ID")
  @CsvBindByName(column = "ACTIVE_SUBSTANCE_CLASS_ID")
  @CsvBindByPosition(position = 4)
  private ActiveSubstanceClass activeSubstanceClass;

/**
   * Default constructor
   */
  public ActiveSubstance() {
  }

  public Boolean getCritical() {
    return critical;
  }

  public void setCritical(Boolean critical) {
    this.critical = critical;
  }

  public ActiveSubstanceClass getActiveSubstanceClass() {
    return activeSubstanceClass;
  }

  public void setActiveSubstanceClass(ActiveSubstanceClass activeSubstanceClass)
  {
    this.activeSubstanceClass = activeSubstanceClass;
  }
}
</code>```

Why are the parent's attributes not exported? How can I get them?
Moreover, how can I get the activeSubstanceClass.toString in my csv file and not the object?

I would be really grateful if somebody could help.

Thank you in advance.

答: Have you tried to make the fields in the abstract class protected instead of private so they are visible to the child class?</p>

Body:
I use com.opencsv 4.1 and I want to export an entity class to a csv file.
The problem is that this entity class extends another class. So, when I export it, I get only the fields of the child class.

Below is my code for writting to the csv file:

List<ActiveSubstance> activeSubstances = getActiveSubstances();
    File reportFile = new File( "activeSubstances.csv");
    Writer writer = new PrintWriter(reportFile);

    StatefulBeanToCsv<ActiveSubstance> beanToCsv = new StatefulBeanToCsvBuilder<ActiveSubstance>(writer)
        .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
        .withSeparator(CSVWriter.DEFAULT_SEPARATOR)
        .build();
    beanToCsv.write(activeSubstances);
    writer.close();

The exported file that I get has the below line:

 ,,false,xx.model.ActiveSubstanceClass@29f9a8b9

My parent class:

@MappedSuperclass
public abstract class AbstractEntity {

  @Id
  @DiffIgnore
  @Column(name = "UUID")
  @CsvBindByName(column = "UUID")
  @CsvBindByPosition(position = 0)
  private String uuid;

  @Column(name = "CODE")
  @CsvBindByName(column = "CODE")
  @CsvBindByPosition(position = 1)
  private String code;

 public String getUuid() {
    return uuid;
  }

  public void setUuid(String uuid) {
    this.uuid = uuid;
  }

  public String getCode() {
    return code;
  }

  public void setCode(String code) {
    this.code = code;
  }
}

My child class:

@Entity
@Table(name = "T_ACTIVE_SUBSTANCE")
public class ActiveSubstance extends AbstractEntity {

  @Column(name = "CRITICAL")
  @CsvBindByName(column = "CRITICAL")
  @CsvBindByPosition(position = 3)
  private Boolean critical;

  @ManyToOne
  @JoinColumn(name = "ACTIVE_SUBSTANCE_CLASS_ID")
  @CsvBindByName(column = "ACTIVE_SUBSTANCE_CLASS_ID")
  @CsvBindByPosition(position = 4)
  private ActiveSubstanceClass activeSubstanceClass;

/**
   * Default constructor
   */
  public ActiveSubstance() {
  }

  public Boolean getCritical() {
    return critical;
  }

  public void setCritical(Boolean critical) {
    this.critical = critical;
  }

  public ActiveSubstanceClass getActiveSubstanceClass() {
    return activeSubstanceClass;
  }

  public void setActiveSubstanceClass(ActiveSubstanceClass activeSubstanceClass)
  {
    this.activeSubstanceClass = activeSubstanceClass;
  }
}

Why are the parent's attributes not exported? How can I get them?
Moreover, how can I get the activeSubstanceClass.toString in my csv file and not the object?

I would be really grateful if somebody could help.

Thank you in advance.


问:
Angular 2 material autocomplete selected value
I have autocomplete input

```<code><div formArrayName="addresses">
  <div class="row"
       *ngFor="let itemrow of searchForm.controls.addresses.controls; let i=index"
       [formGroupName]="i">
    <mat-form-field>
      <input type="text"
             class="form-control" id="address"
             formControlName="address"
             matInput
             [matAutocomplete]="auto"
             (keyup)="getESRI($event.target.value)"
             (focusout)="bindLocation($event.target.value)">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of testLocation"
                    [value]="option.text">
           {{ option.text }}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>
  </div>
</div>
</code>```

"testlocation":[{"text":"Euronet","magicKey":"dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true},{"text":"Euronet","magicKey":"dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true}]

When I'm trying add value [value]="option.magicKey it shows in the input option.magicKey when I select option. I need option.magicKey only as the value, and option.text as the input option. Otherwise how to add option.magicKey as parameter to bindLocation($event.target.value) function?

答:
<mat-option> has event onSelectionChange, with this event you can call any function and bind everything from option object

```<code>(onSelectionChange)="bindLocation(option.text, option.magicKey)"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have autocomplete input

    <mat-form-field>
      <input type="text"
             class="form-control" id="address"
             formControlName="address"
             matInput
             [matAutocomplete]="auto"
             (keyup)="getESRI($event.target.value)"
             (focusout)="bindLocation($event.target.value)">
      <mat-autocomplete #auto="matAutocomplete">
        <mat-option *ngFor="let option of testLocation"
                    [value]="option.text">
           {{ option.text }}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>

"testlocation":[{"text":"Euronet","magicKey":"dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true},{"text":"Euronet","magicKey":"dHA9MSNubT1FdXJvbmV0I2NzPTE5OjExI3NjPURFVQ==","isCollection":true}]

When I'm trying add value [value]="option.magicKey it shows in the input option.magicKey when I select option. I need option.magicKey only as the value, and option.text as the input option. Otherwise how to add option.magicKey as parameter to bindLocation($event.target.value) function?

Body:
<mat-option> has event onSelectionChange, with this event you can call any function and bind everything from option object

(onSelectionChange)="bindLocation(option.text, option.magicKey)"


问:
Request processing time in python
I'm trying to test a web application using selenium python. I've wrote a script to mimic a user. It logs in to the server, generates some reports and so on. It is working fine.
Now, I need to see how much time the server is taking to process a specific request.
Is there a way to find that from the same python code?
Any alternate method is acceptable.

Note:

The server is in the same LAN

Also I don't have privileges to do anything at the server side. So anything I can do is from outside the server.

Any sort of help is appreciable. Thank you

答:
Have you considered the w3c HTTP access log field, "time-taken."  This will report on every single request the time in milliseconds maximally.  On some platforms the precision reported is more granular.  In order for a web server, an application server with an HTTP access layer, an enterprise services bus with an HTTP access layer (for SOAP and REST calls) to be fully w3c standards compliant this log value must be available for inclusion in the HTTP access logs.

You will see every single granular request and the time required for processing from first byte of receipt at the server to the last byte sent minus the final TCP ACK at the end.

Title: Request processing time in python


问:
Callback is not a function error [Nodejs]
I have the following code

```<code>var getUrl = function(callback) {
  ref.once('value')
    .then(function(snap) {
      let article_url = snap.val();
      console.log(article_url);
      callback(null, article_url); // I dont want to throw an error, so I pass null for the error argument
    });
};

var getImage = function(err, data, callback) {
  //if (err) throw err; // Check for the error and throw if it exists.
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    if (error === null) {
      //console.log(response.image);
      if (response.image == null || response.image == "") {
        image = "https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg"
      } else {
        image = response.image;
      }
    }
  });
  callback(null, image); // Otherwise proceed as usual.
};

var updateDatabase = function(err, data) {
  //if (err) throw err; // Check for the error and throw if it exists.
  refupdate.update ({
    "Article_Image_URL": data
  });
  console.log('success'); // Otherwise proceed as usual
};

getUrl(getImage);
getImage(updateDatabase);
</code>```

However I get an error callback is not a function at the line callback(null, image);

The thing is if I remove the updateDatabase function then I get no errors. However when it is within the code I get the error mentioned above.
Can someone please tell me what can be causing this error?

答:
```<code>const updateDatabase = async (value) => {
  try {
    let snap = await ref.once(value);
    let article_url = snap.val();
    let image = await textapi.extract({
      url: article_url,
      best_image: true
    });
    if (image==='') {image = 'https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg'}
    refupdate.update({
      "Article_Image_URL": article_url
    });
  } catch (err) {
    throw err;
  }
}
</code>```

Body:
I have the following code

var getUrl = function(callback) {
  ref.once('value')
    .then(function(snap) {
      let article_url = snap.val();
      console.log(article_url);
      callback(null, article_url); // I dont want to throw an error, so I pass null for the error argument
    });
};

var getImage = function(err, data, callback) {
  //if (err) throw err; // Check for the error and throw if it exists.
  textapi.extract({
    url: data,
    best_image: true
  }, function(error, response) {
    if (error === null) {
      //console.log(response.image);
      if (response.image == null || response.image == "") {
        image = "https://www.wefornews.com/wp-content/uploads/2017/01/news-3.jpg"
      } else {
        image = response.image;
      }
    }
  });
  callback(null, image); // Otherwise proceed as usual.
};

var updateDatabase = function(err, data) {
  //if (err) throw err; // Check for the error and throw if it exists.
  refupdate.update ({
    "Article_Image_URL": data
  });
  console.log('success'); // Otherwise proceed as usual
};

getUrl(getImage);
getImage(updateDatabase);

However I get an error callback is not a function at the line callback(null, image);

The thing is if I remove the updateDatabase function then I get no errors. However when it is within the code I get the error mentioned above.
Can someone please tell me what can be causing this error?


问:
transform json to key/value file in bash
I have a JSON which looks like this:

```<code>{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}
</code>```

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

```<code>key1=value1
key2=value2
</code>```

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

答:
In python
This reads stdin and outputs the desired "key=value" one per line

```<code>#!/usr/bin/python

import json
import sys

data = sys.stdin.read()

json_structure=json.loads(data)

start_point=json_structure["data"]

for k in start_point.keys():
    print("%s=%s" % (k, start_point[k]))
</code>```

If I was using python to unmangle the json input however, I would probably rewrite the bash script in python

Body:
I have a JSON which looks like this:

{
    "lorem": "ipsum",
    "dolor": "sid",
    "data": {
        "key1": "value1",
        "key2": "value2"
    }
}

and I want an output which is ini like where I only need the content of 'data' (which is always flat, no branches). The output should look like this:

key1=value1
key2=value2

I can use jq (just don't get it running) but have to use a bash script for it. Can anyone help?

Body:
In python
This reads stdin and outputs the desired "key=value" one per line

#!/usr/bin/python

import json
import sys

data = sys.stdin.read()

json_structure=json.loads(data)

start_point=json_structure["data"]

for k in start_point.keys():
    print("%s=%s" % (k, start_point[k]))

If I was using python to unmangle the json input however, I would probably rewrite the bash script in python


问:
String.Replace does not replace Unicode Character 'ARABIC LETTERS'
I have two arrays, one that contains a set of characters to search for in a specific string and the other the set of strings with which to replace a specific character if found.

I'm trying to use the standard String.Replace() to modify the given string when the specific character is found. The method I'm trying to use detects that the string contains the character/characters of my array, enters the loop and runs the operation but at the end nothing is changed.

I'm not sure why or how to go to solve this. Below is my code and results.

```<code>static void Main(string[] args)
{
    var wordToPass = "heyك";

    wordToPass = wordToPass.MultiReplace();

    Console.WriteLine(wordToPass);
    Console.ReadKey();

}
</code>```

The extension method to replace the characters:

```<code>    public static class StringExtension
{
    public static readonly char[] SignsArray = new char[] { 'ك', 'ـ', 'ض', 'ؤ', 'ا', 'ط', 'ئ', 'إ', 'ر', 'أ', ' ', 'ہ', 'ء', 'ب', 'ة', 'ت', 'ز',
                                                'س', 'ص', 'ظ', 'ع', 'ج', 'ح', '´', 'ف', 'ث', '¶', '°', '؛', '·', '`' };

    public static readonly string[] RepArray = new string[] { "SS", "UE", "OE", "AE", "C", "OE", "AE", "AA", "N", "A", "A", "A", "A", "E", "E", "E", "O", "O", "O",
                                                  "U", "U", "I", "I", "'", "Y", "E", "A", ".", ".", ".", "'"};

    // Extension on String
    public static string MultiReplace(this string stringValue)
    {
        HashSet<char> set = new HashSet<char>(SignsArray);

        for (int i = 0; i < stringValue.Length; ++i)
        {
            var currentCharacter = stringValue[i];
            string valueToReplace;
            string replaceValue;
            if (set.Contains(currentCharacter))
            {
                valueToReplace = Char.ToString(stringValue[i]);
                replaceValue = RepArray[Array.IndexOf(SignsArray, currentCharacter)];
                stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);
            }
        }

        return stringValue;
    }
}
</code>```

答:
.Replace returns a new string, as System.String is immutable.

Consider reassigning.

```<code>stringValue = stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);
</code>```

Body:
I have two arrays, one that contains a set of characters to search for in a specific string and the other the set of strings with which to replace a specific character if found.

I'm trying to use the standard String.Replace() to modify the given string when the specific character is found. The method I'm trying to use detects that the string contains the character/characters of my array, enters the loop and runs the operation but at the end nothing is changed.

I'm not sure why or how to go to solve this. Below is my code and results.

static void Main(string[] args)
{
    var wordToPass = "heyك";

    wordToPass = wordToPass.MultiReplace();

    Console.WriteLine(wordToPass);
    Console.ReadKey();

}

The extension method to replace the characters:

    public static class StringExtension
{
    public static readonly char[] SignsArray = new char[] { 'ك', 'ـ', 'ض', 'ؤ', 'ا', 'ط', 'ئ', 'إ', 'ر', 'أ', ' ', 'ہ', 'ء', 'ب', 'ة', 'ت', 'ز',
                                                'س', 'ص', 'ظ', 'ع', 'ج', 'ح', '´', 'ف', 'ث', '¶', '°', '؛', '·', '`' };

    public static readonly string[] RepArray = new string[] { "SS", "UE", "OE", "AE", "C", "OE", "AE", "AA", "N", "A", "A", "A", "A", "E", "E", "E", "O", "O", "O",
                                                  "U", "U", "I", "I", "'", "Y", "E", "A", ".", ".", ".", "'"};

    // Extension on String
    public static string MultiReplace(this string stringValue)
    {
        HashSet<char> set = new HashSet<char>(SignsArray);

        for (int i = 0; i < stringValue.Length; ++i)
        {
            var currentCharacter = stringValue[i];
            string valueToReplace;
            string replaceValue;
            if (set.Contains(currentCharacter))
            {
                valueToReplace = Char.ToString(stringValue[i]);
                replaceValue = RepArray[Array.IndexOf(SignsArray, currentCharacter)];
                stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);
            }
        }

        return stringValue;
    }
}

Body:
.Replace returns a new string, as System.String is immutable.

Consider reassigning.

stringValue = stringValue.Replace(Convert.ToString(currentCharacter), replaceValue);


问:
Fast binary parser algorithm

I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

```<code> static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}
</code>```

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

```<code>static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

```<code>if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}
</code>```

答:
You are accessing to disk in loop and I don't think SIMD will help too much there, you could use mmap.

Check these answers:

When should I use mmap for file access?

Fastest file reading in C

but you could also use SIMD (SSE/AVX/NEON) for other parts e.g in parsing code

Title: Fast binary parser algorithm

Body:
I'm writing a parser for binary files. The data is stored in consecutive 32 bit records. The files only have to be read once and as this is done it is fed into the analysis algorithm.

Now I am reading the file in chunks of 1024 records to avoid as much of the overhead from calling fread more frequently than necessary as possible. In the example below I use oflcorrection, timetag and channel as outputs for the algorithms and use the bool return value to check if the algorithm should stop. Also note that not all the records contain photons just those with positive values.

With this approach I can process  at up to 0.5GBps or 1.5 GBps  if I use the threaded version of the algorithms which break the file into pieces. I know my SSD can read at least a 40% faster. I was thinking of using SIMD to parse several records in parallel but I don't know how to do it with the conditional return clauses.

Do you know any other approach that would allow me to combine chunked reading and SIMD? Is there in general a better way of doing it?

Thanks

P.S. The records correspond to either photons arriving to detectors after going through a beam splitter or a special record that indicates an overflow condition. The latter is needed because Timetags are stored with picosecond resolution in uint64_t.

 static inline bool next_photon(FILE* filehandle, uint64_t * RecNum,
                               uint64_t StopRecord, record_buf_t *buffer,
                               uint64_t *oflcorrection, uint64_t *timetag, int *channel)
{
    pop_record:
    while (__builtin_unpredictable(buffer->head < RECORD_CHUNK)) { // still have records on buffer
        ParseHHT2_HH2(buffer->records[buffer->head], channel, timetag, oflcorrection);
        buffer->head++;
        (*RecNum)++;

        if (*RecNum >= StopRecord) { // run out of records
            return false;
        }

        if (*channel >= 0) { // found a photon
            return true;
        }
    }
    // run out of buffer
    buffer->head = 0;
    fread(buffer->records, RECORD_CHUNK, sizeof(uint32_t), filehandle);
    goto pop_record;
}

Please find below the parsing function. Keep in mind that I can't do anything about the file format. Thanks again, Guillem.

static inline void ParseHHT2_HH2(uint32_t record, int *channel,
                                 uint64_t *timetag, uint64_t *oflcorrection)
{
    const uint64_t T2WRAPAROUND_V2 = 33554432;
    union{
        uint32_t   allbits;
        struct{ unsigned timetag  :25;
            unsigned channel  :6;
            unsigned special  :1;
        } bits;
    } T2Rec;

    T2Rec.allbits = record;

    if(T2Rec.bits.special) {
        if(T2Rec.bits.channel==0x3F) {  //an overflow record
            if(T2Rec.bits.timetag!=0) {
                *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
            }
            else {  // if it is zero it is an old style single overflow
                *oflcorrection += T2WRAPAROUND_V2;  //should never happen with new Firmware!
            }
            *channel = -1;
        } else if(T2Rec.bits.channel == 0) {  //sync
            *channel = 0;
        } else if(T2Rec.bits.channel<=15) {  //markers
            *channel = -2;
        }
    } else {//regular input channel
        *channel = T2Rec.bits.channel + 1;
    }
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}

I came up with an almost branchless parsing function, but it doesn't produce any speed up.

if(T2Rec.bits.channel==0x3F) {  //an overflow record
        *oflcorrection += T2WRAPAROUND_V2 * T2Rec.bits.timetag;
    }
    *channel = (!T2Rec.bits.special) * (T2Rec.bits.channel + 1) - T2Rec.bits.special * T2Rec.bits.channel;
    *timetag = *oflcorrection + T2Rec.bits.timetag;
}


问:
asyncio event wait function does not continue after event has been stored
I'm working on a function that should continue after a response has been given through a websocket. In order to achieve this I use an asyncio event which will be set after the response has been given.

Three functions are involved:

```<code>async def send(self, message):
    await self.channel(message.toJSON())
    if (message.method == 'get' or message.method == 'post'):
        event = asyncio.Event()
        self._queueMessage(message, event)
        await event.wait()
    print('continue')

def _queueMessage(self, message, event):
    self.queue.append([message, event])

def _process_response_message(self, message):
    for entry in self.queue:
        if (message['_id'] == entry[0]._id):
            print(entry[1])
            entry[1].set()
            print(entry[1])
            return
</code>```

Returns:

```<code><asyncio.locks.Event object at 0x7f3a1ff20da0 [unset,waiters:1]>
<asyncio.locks.Event object at 0x7f3a1ff20da0 [set,waiters:1]>
</code>```

In this example, the print('continue') function is never called and I do not why because the .set() function is actually called and .set() does seem to work fine if I use it before I call await event.wait().

Is there something I'm missing?

答:
Based on message you get _process_response_message seems to be running in another thread. asyncio.Event is not thread-safe object you should use loop.call_soon_threadsafe function to call it's methods from other thread. Try to change your code like this:

```<code>async def send(self, message):
    await self.channel(message.toJSON())
    if (message.method == 'get' or message.method == 'post'):
        loop = asyncio.get_event_loop()
        event = asyncio.Event()
        self._queueMessage(message, loop, event)
        await event.wait()
    print('continue')

def _queueMessage(self, message, loop, event):
    self.queue.append([message, loop, event])

def _process_response_message(self, message):
    for entry in self.queue:
        qmsg, loop, event = entry
        if (message['_id'] == qmsg._id):
            loop.call_soon_threadsafe(event.set)
            return
</code>```

Body:
I'm working on a function that should continue after a response has been given through a websocket. In order to achieve this I use an asyncio event which will be set after the response has been given.

Three functions are involved:

async def send(self, message):
    await self.channel(message.toJSON())
    if (message.method == 'get' or message.method == 'post'):
        event = asyncio.Event()
        self._queueMessage(message, event)
        await event.wait()
    print('continue')

def _queueMessage(self, message, event):
    self.queue.append([message, event])

def _process_response_message(self, message):
    for entry in self.queue:
        if (message['_id'] == entry[0]._id):
            print(entry[1])
            entry[1].set()
            print(entry[1])
            return

Returns:

<asyncio.locks.Event object at 0x7f3a1ff20da0 [unset,waiters:1]>
<asyncio.locks.Event object at 0x7f3a1ff20da0 [set,waiters:1]>

In this example, the print('continue') function is never called and I do not why because the .set() function is actually called and .set() does seem to work fine if I use it before I call await event.wait().

Is there something I'm missing?

Body:
Based on message you get _process_response_message seems to be running in another thread. asyncio.Event is not thread-safe object you should use loop.call_soon_threadsafe function to call it's methods from other thread. Try to change your code like this:

async def send(self, message):
    await self.channel(message.toJSON())
    if (message.method == 'get' or message.method == 'post'):
        loop = asyncio.get_event_loop()
        event = asyncio.Event()
        self._queueMessage(message, loop, event)
        await event.wait()
    print('continue')

def _queueMessage(self, message, loop, event):
    self.queue.append([message, loop, event])

def _process_response_message(self, message):
    for entry in self.queue:
        qmsg, loop, event = entry
        if (message['_id'] == qmsg._id):
            loop.call_soon_threadsafe(event.set)
            return


问:
Elasticsearch _reindex fails
I am working on AWS Elasticsearch. It doesn't allow open/close index, so setting change can not be applied on the index.

In order to change the setting of a index, I have to create a new index with new setting and then move the data from the old index into new one.

So first I created a new index with

```<code>PUT new_index
{
  "settings": {
    "max_result_window":3000000,
    "analysis": {
      "filter": {
        "german_stop": {
          "type":       "stop",
          "stopwords":  "_german_"
        },
        "german_keywords": {
          "type":       "keyword_marker",
          "keywords":   ["whatever"]
        },
        "german_stemmer": {
          "type":       "stemmer",
          "language":   "light_german"
        }
      },
      "analyzer": {
        "my_german_analyzer": {
          "tokenizer":  "standard",
          "filter": [
            "lowercase",
            "german_stop",
            "german_keywords",
            "german_normalization",
            "german_stemmer"
          ]
        }
      }
    }
  }
}
</code>```

it succeeded. Then I try to move data from old index into new one with query:

```<code>POST _reindex
{
  "source": {
    "index": "old_index"
  },
  "dest": {
    "index": "new_index"
  }
}
</code>```

It failed with

```<code>Request failed to get to the server (status code: 504)
</code>```

I checked the indices with _cat api, it gives

```<code>health status index          uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   old_index      AGj8WN_RRvOwrajKhDrbPw   5   1    2256482       767034      7.8gb          7.8gb
yellow open   new_index      WnGZ3GsUSR-WLKggp7Brjg   5   1      52000            0    110.2mb        110.2mb
</code>```

Seemingly some data are loaded into there, just wondering why the _reindex doesn't work.

答:
You can check the status of reindex with api:

```<code>GET _tasks?detailed=true&actions=*reindex
</code>```

There is a "status" object in response which has field "total":

total is the total number of operations that the reindex expects to perform. You can estimate the progress by adding the updated, created, and deleted fields. The request will finish when their sum is equal to the total field.

Link to ES Documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html

Title: Elasticsearch _reindex fails

Body:
I am working on AWS Elasticsearch. It doesn't allow open/close index, so setting change can not be applied on the index.

In order to change the setting of a index, I have to create a new index with new setting and then move the data from the old index into new one.

So first I created a new index with

PUT new_index
{
  "settings": {
    "max_result_window":3000000,
    "analysis": {
      "filter": {
        "german_stop": {
          "type":       "stop",
          "stopwords":  "_german_"
        },
        "german_keywords": {
          "type":       "keyword_marker",
          "keywords":   ["whatever"]
        },
        "german_stemmer": {
          "type":       "stemmer",
          "language":   "light_german"
        }
      },
      "analyzer": {
        "my_german_analyzer": {
          "tokenizer":  "standard",
          "filter": [
            "lowercase",
            "german_stop",
            "german_keywords",
            "german_normalization",
            "german_stemmer"
          ]
        }
      }
    }
  }
}

it succeeded. Then I try to move data from old index into new one with query:

POST _reindex
{
  "source": {
    "index": "old_index"
  },
  "dest": {
    "index": "new_index"
  }
}

It failed with

Request failed to get to the server (status code: 504)

I checked the indices with _cat api, it gives

health status index          uuid                   pri rep docs.count docs.deleted store.size pri.store.size
yellow open   old_index      AGj8WN_RRvOwrajKhDrbPw   5   1    2256482       767034      7.8gb          7.8gb
yellow open   new_index      WnGZ3GsUSR-WLKggp7Brjg   5   1      52000            0    110.2mb        110.2mb

Seemingly some data are loaded into there, just wondering why the _reindex doesn't work.

Body:
You can check the status of reindex with api:

GET _tasks?detailed=true&actions=*reindex

There is a "status" object in response which has field "total":

total is the total number of operations that the reindex expects to perform. You can estimate the progress by adding the updated, created, and deleted fields. The request will finish when their sum is equal to the total field.

Link to ES Documentation: https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-reindex.html


问:
C++ - constant variable, is it a correct term?
At the end of the artile here: http://www.learncpp.com/cpp-tutorial/45-enumerated-types/

It mentions the following sentence:

Finally, as with constant variables, enumerated types show up in the debugger, making them more useful than #defined values in this regard.

Is "constant variables" a correct term to use? Aren't constants different from variables?

Thanks.

答: A constant is a variable. In C++ (and most languages), defining a variable as a constant simply tells the compiler that the variable is not allowed to be changed.</p>


问:
Migrating Shipping Extension for Magento 1.9 to Magento 2.2
I am trying to migrate a custom magento 1.9 extension to magento 2.2. I have done a lot of searching and can't find information on the use case I'm trying to migrate. I originally followed this tutorial for the 1.9 extension. I understand there is a tool to help port extensions, but I am trying to do this manually as I couldn't get that tool to function for me.

The custom shipping extension would run each time the shopping cart was updated to calculate a custom shipping rate. The goal is to recreate this extension in magento 2.2 such that each time the shopping cart is opened or updated it will run and calculate a shipping cost which will then propagate through the checkout process.

Below is an overview of the magento 1.9 extension. Any advice on how to translate this to magento 2.2?

/app/etc/modules/Extensions_Shipper.xml

```<code><?xml version="1.0"?>
<config>
<modules>
    <Extensions_Shipper>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Shipping />
        </depends>
    </Extensions_Shipper>
</modules>
</code>```

/app/code/local/Extensions/Shipper/etc/config.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
    <Extensions_Shipper>
        <module>0.0.1</module>
    </Extensions_Shipper>
</modules>
<global>
    <models>
        <extensions_shipper>
            <class>Extensions_Shipper_Model</class>
        </extensions_shipper>
    </models>
</global>
<default>
    <carriers>
        <extensions_shipper>
            <active>1</active>
            <model>extensions_shipper/carrier</model>
            <title>Shipping Options</title>
            <sort_order>10</sort_order>
            <sallowspecific>0</sallowspecific>
        </extensions_shipper>
    </carriers>
</default>
</code>```

/app/code/local/Extensions/Shipper/Model/Carrier.php

```<code><?php
class Extensions_Shipper_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface
{
    public function collectRates(Mage_Shipping_Model_Rate_Request $request)
    {
        //Are there magento 2.2 equivalence for the following?
        $addressInfo = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData();
        $result = Mage::getModel('shipping/rate_result');
        $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
        $currentItem = Mage::getModel('catalog/product')->load($items[$itemsArray[$i]]->getProduct()->getId());
        Mage::getSingleton('core/session')->addNotice('some text');
        //$result = some calculations for shipping rate
        return $result;
    }

    public function getAllowedMethods()
    {
        return array();
    }
}
</code>```

答:
You can create an event observer on the checkout_cart_add_product_complete event to execute the logic to update the shipping costs.

```<code>namespace MyCompany\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class MyObserver implements ObserverInterface
{
  public function __construct()
  {
    //Observer initialization code...
    //You can use dependency injection to get any class this observer may need.
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    //Observer execution code...
  }
}
</code>```

Subscribe to the event in events.xml:

```<code><?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="my_module_event_before">
        <observer name="myObserverName" instance="MyCompany\MyModule\Observer\MyObserver" />
    </event>
    <event name="my_module_event_after">
        <observer name="myObserverName" instance="MyCompany\MyModule\Observer\AnotherObserver" />
    </event>
</config>
</code>```

See Magento docs on events and observers: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/events-and-observers.html

For a list of all Magento 2.2 events, see: https://cyrillschumacher.com/magento-2.2-list-of-all-dispatched-events/

Body:
I am trying to migrate a custom magento 1.9 extension to magento 2.2. I have done a lot of searching and can't find information on the use case I'm trying to migrate. I originally followed this tutorial for the 1.9 extension. I understand there is a tool to help port extensions, but I am trying to do this manually as I couldn't get that tool to function for me.

The custom shipping extension would run each time the shopping cart was updated to calculate a custom shipping rate. The goal is to recreate this extension in magento 2.2 such that each time the shopping cart is opened or updated it will run and calculate a shipping cost which will then propagate through the checkout process.

Below is an overview of the magento 1.9 extension. Any advice on how to translate this to magento 2.2?

/app/etc/modules/Extensions_Shipper.xml

<?xml version="1.0"?>
<config>
<modules>
    <Extensions_Shipper>
        <active>true</active>
        <codePool>local</codePool>
        <depends>
            <Mage_Shipping />
        </depends>
    </Extensions_Shipper>
</modules>

/app/code/local/Extensions/Shipper/etc/config.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>
<modules>
    <Extensions_Shipper>
        <module>0.0.1</module>
    </Extensions_Shipper>
</modules>
<global>
    <models>
        <extensions_shipper>
            <class>Extensions_Shipper_Model</class>
        </extensions_shipper>
    </models>
</global>
<default>
    <carriers>
        <extensions_shipper>
            <active>1</active>
            <model>extensions_shipper/carrier</model>
            <title>Shipping Options</title>
            <sort_order>10</sort_order>
            <sallowspecific>0</sallowspecific>
        </extensions_shipper>
    </carriers>
</default>

/app/code/local/Extensions/Shipper/Model/Carrier.php

<?php
class Extensions_Shipper_Model_Carrier extends Mage_Shipping_Model_Carrier_Abstract implements Mage_Shipping_Model_Carrier_Interface
{
    public function collectRates(Mage_Shipping_Model_Rate_Request $request)
    {
        //Are there magento 2.2 equivalence for the following?
        $addressInfo = Mage::getSingleton('checkout/session')->getQuote()->getShippingAddress()->getData();
        $result = Mage::getModel('shipping/rate_result');
        $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
        $currentItem = Mage::getModel('catalog/product')->load($items[$itemsArray[$i]]->getProduct()->getId());
        Mage::getSingleton('core/session')->addNotice('some text');
        //$result = some calculations for shipping rate
        return $result;
    }

    public function getAllowedMethods()
    {
        return array();
    }
}

Body:
You can create an event observer on the checkout_cart_add_product_complete event to execute the logic to update the shipping costs.

namespace MyCompany\MyModule\Observer;

use Magento\Framework\Event\ObserverInterface;

class MyObserver implements ObserverInterface
{
  public function __construct()
  {
    //Observer initialization code...
    //You can use dependency injection to get any class this observer may need.
  }

  public function execute(\Magento\Framework\Event\Observer $observer)
  {
    //Observer execution code...
  }
}

Subscribe to the event in events.xml:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="my_module_event_before">
        <observer name="myObserverName" instance="MyCompany\MyModule\Observer\MyObserver" />
    </event>
    <event name="my_module_event_after">
        <observer name="myObserverName" instance="MyCompany\MyModule\Observer\AnotherObserver" />
    </event>
</config>

See Magento docs on events and observers: http://devdocs.magento.com/guides/v2.0/extension-dev-guide/events-and-observers.html

For a list of all Magento 2.2 events, see: https://cyrillschumacher.com/magento-2.2-list-of-all-dispatched-events/


问:
Parameterized includes
In a few C programs (for example in gecko) I've noticed an idiom whereby a program will temporarily define a macro, then include a file which uses that macro, then undefine the macro. Here's a trivial example:

speak.c:

```<code>#define SPEAK(phrase) (printf("When I speak I say %s\n", (phrase)))
#include "dog.h"
#undef SPEAK
</code>```

dog.h:

```<code>SPEAK("woof");
</code>```

Which expands to:

```<code>(printf("When I speak I say %s\n", ("woof")))
</code>```

I gather this might be a useful technique to generalize included code by being able to specify behavior at the expansion site.

Does this pattern have a name, or has it been written about previously?

答:
This is a variant of what are often called X macros.

Further reading

The New C: X Macros (Dr Dobbs)

Title: Parameterized includes

Body:
In a few C programs (for example in gecko) I've noticed an idiom whereby a program will temporarily define a macro, then include a file which uses that macro, then undefine the macro. Here's a trivial example:

speak.c:

#define SPEAK(phrase) (printf("When I speak I say %s\n", (phrase)))
#include "dog.h"
#undef SPEAK

dog.h:

SPEAK("woof");

Which expands to:

(printf("When I speak I say %s\n", ("woof")))

I gather this might be a useful technique to generalize included code by being able to specify behavior at the expansion site.

Does this pattern have a name, or has it been written about previously?


问:
Destroy other login Wordpress sessions except last two
I'm trying to add a function to the wp_login hook which scans all current user login sessions, and destroy all, except the last two (which contains current session). I'm want user to be logged in on max. two devices simultaneously.

I can fetch the sessions with:

```<code>$manager = WP_User_Meta_Session_Tokens::get_instance( $user->ID );
$tokens = $manager->get_all();
</code>```

or:

```<code>$tokens = get_user_meta($user->ID, 'session_tokens', true);
</code>```

But how can you destroy these sessions during a for loop?

```<code>foreach($tokens as $token){
  $manager->destroy( $token );
}
</code>```

returns: hash() expects parameter 2 to be string.
Using the keys as value doesn't work either.

答:
I used a different approach for now, updating the user_meta directly did the trick</p>

```<code>function limit_active_user_sessions( $user_login, $user ){

 $sessions = get_user_meta( $user->ID, 'session_tokens', true );
 $sessions_keys = array_keys($sessions);
 $sessions_count = count($sessions);
 $max_active_sessions = 2;
 if ( $sessions_count > 2 ){
  for($i=0;$i<($sessions_count-$max_active_sessions);$i++){
   unset( $sessions[$sessions_keys[$i]] );
  }
  update_user_meta( $user->ID, 'session_tokens', $sessions );
 }

add_action( 'wp_login', 'limit_active_user_sessions', 10, 2 );
</code>```

Body:
I'm trying to add a function to the wp_login hook which scans all current user login sessions, and destroy all, except the last two (which contains current session). I'm want user to be logged in on max. two devices simultaneously.

I can fetch the sessions with:

$manager = WP_User_Meta_Session_Tokens::get_instance( $user->ID );
$tokens = $manager->get_all();

or:

$tokens = get_user_meta($user->ID, 'session_tokens', true);

But how can you destroy these sessions during a for loop?

foreach($tokens as $token){
  $manager->destroy( $token );
}

returns: hash() expects parameter 2 to be string.
Using the keys as value doesn't work either.

Body:
I used a different approach for now, updating the user_meta directly did the trick

function limit_active_user_sessions( $user_login, $user ){

 $sessions = get_user_meta( $user->ID, 'session_tokens', true );
 $sessions_keys = array_keys($sessions);
 $sessions_count = count($sessions);
 $max_active_sessions = 2;
 if ( $sessions_count > 2 ){
  for($i=0;$i<($sessions_count-$max_active_sessions);$i++){
   unset( $sessions[$sessions_keys[$i]] );
  }
  update_user_meta( $user->ID, 'session_tokens', $sessions );
 }

add_action( 'wp_login', 'limit_active_user_sessions', 10, 2 );


问:
GET DIAGNOSTICS equivalent for mysql version older than 5.6
Is there anything equivalent to GET DIAGNOSTICS of mysql 5.6 version for lower versions of mysql?

I am using mysql 5.5 and I want do something like this

```<code>DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    ROLLBACK;
    GET DIAGNOSTICS CONDITION 1
    @p1 = MYSQL_ERRNO, @p2 = RETURNED_SQLSTATE, @p3=MESSAGE_TEXT,@p4=TABLE_NAME;
    select concat('Failed - ',@p1,@p2,@p3,@p4);
END;
</code>```

But 5.5 doesn't support this, is there any work around for this?

答: According to MySQL documentation for version 5.5, there doesn't seem to be an equivalent, but this article pointed me in the direction of using SHOW WARNINGS inside my handler, and using a local variable inside the handler to check if it was actually called (if that's needed).

Body:
Is there anything equivalent to GET DIAGNOSTICS of mysql 5.6 version for lower versions of mysql?

I am using mysql 5.5 and I want do something like this

DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    ROLLBACK;
    GET DIAGNOSTICS CONDITION 1
    @p1 = MYSQL_ERRNO, @p2 = RETURNED_SQLSTATE, @p3=MESSAGE_TEXT,@p4=TABLE_NAME;
    select concat('Failed - ',@p1,@p2,@p3,@p4);
END;

But 5.5 doesn't support this, is there any work around for this?


问:
MatCheckbox - Angular Material - Unit tests - How to click to select/deselect all lines
I use MatCheckboxModule from Angular Material in my Angular 5 application.

I have a table with multiple lines and a checkbox to select/deselect all lines from the table :

```<code><mat-checkbox [(ngModel)]="selectAll" (change)="toggleAll()">Toggle</mat-checkbox>
</code>```

The component part is composed of a selectAll boolean property, a selectedData array property and a toggleAll function.
This function fills the selectedData array with all the lines if selectAll is true, otherwise, set the selectedData to empty.

Below, a component code extract:

```<code>export class BookingComponent implements OnInit {

  booking: Booking;
  selectedData: Line[];
  private _selectAll: boolean;

  ngOnInit() {
    this._selectAll = false;
    this.selectedData = [];
    this.getBooking();
  }

  get selectAll(): boolean {
    return this._selectAll;
  }

  set selectAll(newValue: boolean) {
    this._selectAll = newValue;
  }

  toggleAll() {
    for (const line of this.booking.lines) {
      this.selectAll ? this.selectedData.push(line) : this.selectedData = [];
    }
  }
}
</code>```

This feature works. However, I don"t know how to test a click which will fill the selectedData array then will empty it. Indeed, in my following code, data are always push in my array because the selectAll property is not changed at the second click :

```<code>it(`should toggle all lines`, async(() => {
    component.ngOnInit();
    const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
    checkbox.click();
    fixture.whenStable().then(() => {
        expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
        checkbox.click();
        fixture.whenStable().then(() => {
            expect(component.selectedData.length).toEqual(0);
        });
    });
}));
</code>```

Do you have an idea how to solve this issue?

Thank you!

答:
I think a fixture.detectChanges(); should update the selectAll property. Try this:</p>

```<code>it(`should toggle all lines`, async(() => {
  component.ngOnInit();
  const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
  checkbox.click();
  fixture.detectChanges();
  fixture.whenStable().then(() => {
      expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
      checkbox.click();
      fixture.whenStable().then(() => {
          expect(component.selectedData.length).toEqual(0);
      });
  });
}));
</code>```

Body:
I use MatCheckboxModule from Angular Material in my Angular 5 application.

I have a table with multiple lines and a checkbox to select/deselect all lines from the table :

<mat-checkbox [(ngModel)]="selectAll" (change)="toggleAll()">Toggle</mat-checkbox>

The component part is composed of a selectAll boolean property, a selectedData array property and a toggleAll function.
This function fills the selectedData array with all the lines if selectAll is true, otherwise, set the selectedData to empty.

Below, a component code extract:

export class BookingComponent implements OnInit {

  booking: Booking;
  selectedData: Line[];
  private _selectAll: boolean;

  ngOnInit() {
    this._selectAll = false;
    this.selectedData = [];
    this.getBooking();
  }

  get selectAll(): boolean {
    return this._selectAll;
  }

  set selectAll(newValue: boolean) {
    this._selectAll = newValue;
  }

  toggleAll() {
    for (const line of this.booking.lines) {
      this.selectAll ? this.selectedData.push(line) : this.selectedData = [];
    }
  }
}

This feature works. However, I don"t know how to test a click which will fill the selectedData array then will empty it. Indeed, in my following code, data are always push in my array because the selectAll property is not changed at the second click :

it(`should toggle all lines`, async(() => {
    component.ngOnInit();
    const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
    checkbox.click();
    fixture.whenStable().then(() => {
        expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
        checkbox.click();
        fixture.whenStable().then(() => {
            expect(component.selectedData.length).toEqual(0);
        });
    });
}));

Do you have an idea how to solve this issue?

Thank you!

Body:
I think a fixture.detectChanges(); should update the selectAll property. Try this:

it(`should toggle all lines`, async(() => {
  component.ngOnInit();
  const checkbox = fixture.debugElement.nativeElement.querySelector('.select-all-container mat-checkbox label');
  checkbox.click();
  fixture.detectChanges();
  fixture.whenStable().then(() => {
      expect(component.selectedData.length).toEqual(component.booking.briefLines.length);
      checkbox.click();
      fixture.whenStable().then(() => {
          expect(component.selectedData.length).toEqual(0);
      });
  });
}));


问:
JS manipulation over BEM CSS structure
I'm getting  a hard time getting this:
BEM structure says I should do something like this:

```<code>.header
   .header__nav
      .header__icon
         .header__icon-text
      .header__menu
         .header__menu-list
</code>```

But what if I want to toggle some CSS class of the header__nav to modify the rest classes? Say, something like that:

```<code>.header
   .header__nav .header__nav--active
      .header__icon
         .header__icon-text
      .header__menu
         .header__menu-list
</code>```

It should be obvious to you that I don't want just to manipulate the parent(.header__nav), but its children as well, by using CSS only for performance reasons. But in the BEM structure, it seems like I must toggle classes for each of the children elements - this is nonsense! Or I need to use specific state(elem--active) for each of the children elements AND also I need to make sure it's in a proper structure in the CSS order - nonsense once again!

I really hope I didn't get this right and there actually is a way of doing this in performance wise manner - using JS to toggle ONE class to modify the rest with CSS.

答: You may use nested selectors for that. See https://en.bem.info/methodology/css/#nested-selectors for more info.</p>

Title: JS manipulation over BEM CSS structure

Body:
I'm getting  a hard time getting this:
BEM structure says I should do something like this:

.header
   .header__nav
      .header__icon
         .header__icon-text
      .header__menu
         .header__menu-list

But what if I want to toggle some CSS class of the header__nav to modify the rest classes? Say, something like that:

.header
   .header__nav .header__nav--active
      .header__icon
         .header__icon-text
      .header__menu
         .header__menu-list

It should be obvious to you that I don't want just to manipulate the parent(.header__nav), but its children as well, by using CSS only for performance reasons. But in the BEM structure, it seems like I must toggle classes for each of the children elements - this is nonsense! Or I need to use specific state(elem--active) for each of the children elements AND also I need to make sure it's in a proper structure in the CSS order - nonsense once again!

I really hope I didn't get this right and there actually is a way of doing this in performance wise manner - using JS to toggle ONE class to modify the rest with CSS.


问:
cx_Freeze not working - no module named cx_Freeze
I've been trying to compile a game I'm writing with python into an exe with cx_Freeze so my friends can play it without the python interpreter. However, when I run the "build" command through cmd, I get an error saying "ImportError: No module named 'cx_Freeze'". I've done this every way in and out, changing the capital letters in "cx_Freeze". I'm trying to use 3.4.3/3.5.1, and I'm using cx_Freeze version 4.3.4.

Thanks in advance...

in answer to Loïc's comment: yes, it is installed.

答: I know this is a year late but I ran into this issue as well. To solve the issue: I ran the cx_Freeze exe found here https://pypi.python.org/pypi/cx_Freeze/5.0.1.</p>


问:
AssertJ testing on a collection: what is better: 'extracting' or Java8 forEach
I'm new to AssertJ and using it to unit-test my written code and was thinking how to assert a list.

Lets assume we have a list of Consumers Entities. each Entity has it own Phone, own ServiceProvider which has it own Name and EntityName.

Now we want to assert that each Entity from a repository gets the right data, so we want to test that each item on list has equal Phone.

```<code>ConsumerEntity savedConsumer1 = Consumer(phone, name, serviceProvider)
List<ConsumerEntity> consumerListFromRepository = repository.findAllByPhone(phone)
</code>```

Now I want to test that the data given from Repository is correct,

I can use this:

```<code>   assertThat(consumerListFromRepository)
            .extracting(ConsumerEntity::getPhone())
            .containsOnly(savedConsumer1.getPhone());
</code>```

Or I can do this with forEach (java 8):

```<code>   consumerListFromRepository.forEach(consumerEntity ->
   assertThat(consumerEntity.getPhone()).isEqualTo(savedConsumer1.getPhone()));
</code>```

1. Which one is faster/simple-r/readable? I will go for the forEach for less lines of code but less read-ability as well.

2. Is there any other way to do it 1liner like the foreach but with asserThat? so it will be readable and simple - and without the need to use EqualTo each

time? something like:

```<code>   asserThat(list).forEach........
</code>```

3. Which one is faster? Extracting or forEach?

Thanks!

答:
I'm not sure that "faster" is a primary concern here. It's likely that any performance difference is immaterial; either the underlying implementations are ~equivalent in terms of non-functionals or - since the context here is a unit test - the consumerListFromRepository is trivially small thereby limiting the scope for any material performance differences.

I think your main concerns here should be

Making it as easy as possible for other developers to:

Understand/reason about your test case

Edit/refactor your test case

Ensuring that your approach to asserting is consistent with other test cases in your code base

Judging which of your two approaches best ticks this box is somewhat subjective but I think the following considerations are relevant:

The Java 8 forEach construct is well understood and the isEqualTo matcher is explicit and easily understood

The AssertJ extracting helper paired with the containsOnly is less common that Java8's forEach construct but this pairing reads logically and is easily understood

So, IMHO both approaches are valid. If your code base consistently uses AssertJ then I'd suggest using the extracting helper paired with the containsOnly matcher for consistency. Otherwise, use whichever of them reads best to you :)

Body:
I'm new to AssertJ and using it to unit-test my written code and was thinking how to assert a list.

Lets assume we have a list of Consumers Entities. each Entity has it own Phone, own ServiceProvider which has it own Name and EntityName.

Now we want to assert that each Entity from a repository gets the right data, so we want to test that each item on list has equal Phone.

ConsumerEntity savedConsumer1 = Consumer(phone, name, serviceProvider)
List<ConsumerEntity> consumerListFromRepository = repository.findAllByPhone(phone)

Now I want to test that the data given from Repository is correct,

I can use this:

   assertThat(consumerListFromRepository)
            .extracting(ConsumerEntity::getPhone())
            .containsOnly(savedConsumer1.getPhone());

Or I can do this with forEach (java 8):

   consumerListFromRepository.forEach(consumerEntity ->
   assertThat(consumerEntity.getPhone()).isEqualTo(savedConsumer1.getPhone()));

1. Which one is faster/simple-r/readable? I will go for the forEach for less lines of code but less read-ability as well.

2. Is there any other way to do it 1liner like the foreach but with asserThat? so it will be readable and simple - and without the need to use EqualTo each

time? something like:

   asserThat(list).forEach........

3. Which one is faster? Extracting or forEach?

Thanks!


问:
How to return a string (or similar) from Rust in WebAssembly?
I created a small Wasm file from this Rust code:

```<code>#[no_mangle]
pub fn hello() -> &'static str {
    "hello from rust"
}
</code>```

It builds and the hello function can be called from JS:

<!DOCTYPE html>

```

My problem is that the alert displays "undefined". If I return a i32, it works and displays the i32. I also tried to return a String but it does not work (it still displays "undefined").

Is there a way to return a string from Rust in WebAssembly? What type should I use?

答:
WebAssembly only supports a few numeric types, which is all that can be returned via an exported function.

When you compile to WebAssembly, your string will be held in the module's linear memory. In order to read this string from the hosting JavaScript, you need to return a reference to its location in memory, and the length of the string, i.e. two integers. This allows you to read the string from memory.

You use this same technique regardless of whichever language you are compiling to WebAssembly. How can I return a JavaScript string from a WebAssembly function provides a detailed background to the problem.

With Rust specifically, you need to make use of the Foreign Function Interface (FFI), using the CString type as follows:

```<code>use std::ffi::CString;
use std::os::raw::c_char;

static HELLO: &'static str = "hello from rust";

#[no_mangle]
pub fn get_hello() -> *mut c_char {
    let s = CString::new(HELLO).unwrap();
    s.into_raw()
}

#[no_mangle]
pub fn get_hello_len() -> usize {
    HELLO.len()
}
</code>```

The above code exports two functions, get_hello which returns a reference to the string, and get_hello_len which returns its length.

With the above code compiled to a wasm module, the string can be accessed as follows:

```<code>const res = await fetch('chip8.wasm');
const buffer = await res.arrayBuffer();
const module = await WebAssembly.compile(buffer);
const instance = await WebAssembly.instantiate(module);

// obtain the module memory
const linearMemory = instance.exports.memory;

// create a buffer starting at the reference to the exported string
const offset = instance.exports.get_hello();
const stringBuffer = new Uint8Array(linearMemory.buffer, offset,
  instance.exports.get_hello_len());

// create a string from this buffer
let str = '';
for (let i=0; i<stringBuffer.length; i++) {
  str += String.fromCharCode(stringBuffer[i]);
}

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

The C equivalent can be seen in action in a WasmFiddle.

Body:
I created a small Wasm file from this Rust code:

#[no_mangle]
pub fn hello() -> &'static str {
    "hello from rust"
}

It builds and the hello function can be called from JS:

<!DOCTYPE html>

My problem is that the alert displays "undefined". If I return a i32, it works and displays the i32. I also tried to return a String but it does not work (it still displays "undefined").

Is there a way to return a string from Rust in WebAssembly? What type should I use?

Body:
WebAssembly only supports a few numeric types, which is all that can be returned via an exported function.

When you compile to WebAssembly, your string will be held in the module's linear memory. In order to read this string from the hosting JavaScript, you need to return a reference to its location in memory, and the length of the string, i.e. two integers. This allows you to read the string from memory.

You use this same technique regardless of whichever language you are compiling to WebAssembly. How can I return a JavaScript string from a WebAssembly function provides a detailed background to the problem.

With Rust specifically, you need to make use of the Foreign Function Interface (FFI), using the CString type as follows:

use std::ffi::CString;
use std::os::raw::c_char;

static HELLO: &'static str = "hello from rust";

#[no_mangle]
pub fn get_hello() -> *mut c_char {
    let s = CString::new(HELLO).unwrap();
    s.into_raw()
}

#[no_mangle]
pub fn get_hello_len() -> usize {
    HELLO.len()
}

The above code exports two functions, get_hello which returns a reference to the string, and get_hello_len which returns its length.

With the above code compiled to a wasm module, the string can be accessed as follows:

const res = await fetch('chip8.wasm');
const buffer = await res.arrayBuffer();
const module = await WebAssembly.compile(buffer);
const instance = await WebAssembly.instantiate(module);

// obtain the module memory
const linearMemory = instance.exports.memory;

// create a buffer starting at the reference to the exported string
const offset = instance.exports.get_hello();
const stringBuffer = new Uint8Array(linearMemory.buffer, offset,
  instance.exports.get_hello_len());

// create a string from this buffer
let str = '';
for (let i=0; i<stringBuffer.length; i++) {
  str += String.fromCharCode(stringBuffer[i]);
}

console.log(str);

The C equivalent can be seen in action in a WasmFiddle.


问:
Laravel 5.5 eloquent cartesian
What I'm trying to accomplish, I believe, are cartesian results based upon related models.  I want to do this with eager loading.

My eloquent query looks like this:

```<code>$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
                       ->with('materials')
                       ->with('profiles')
                       ->get();
</code>```

And is yielding results of:

```<code>+Collection
    PartBasePart - Model
        +Collection
            Material - Model1
            Material - Model2
            Material - Model3
            Material - Model4
            Material - Model5
        +Collection
            Profile  - Model1
</code>```

What is desire is:

```<code>+Collection
    PartBasePart - Model
        +Collection
            Material - Model1
                +Collection
                    Profile  - Model1
            Material - Model2
                +Collection
                    Profile  - Model1
            Material - Model3
                +Collection
                    Profile  - Model1
            Material - Model4
                +Collection
                    Profile  - Model1
            Material - Model5
                +Collection
                    Profile  - Model1
</code>```

How is this possible?  Can I get an instance of 'Profile - Model1' inside of each Material collection?

The models are defined as follows:

PartBasePart

```<code>class PartBasePart extends Eloquent
{
    public function materials()
    {
        return $this->belongsToMany(\App\Models\Material::class)
                    ->withPivot('id');
    }

    public function profiles()
    {
        return $this->belongsToMany(\App\Models\Profile::class)
                    ->withPivot('id');
    }
}
</code>```

Material

```<code>class Material extends Eloquent
{
    public function partBaseParts()
    {
        return $this->belongsToMany(\App\Models\PartBasePart::class)
                    ->withPivot('id');
    }

    public function profiles()
    {
        return $this->belongsToMany(\App\Models\Profile::class)
                    ->withPivot('id');
    }
}
</code>```

Profile

```<code>class Profile extends Eloquent
{
    public function materials()
    {
        return $this->belongsToMany(\App\Models\Material::class)
                    ->withPivot('id');
    }

    public function partBaseParts()
    {
        return $this->belongsToMany(\App\Models\PartBasePart::class)
                    ->withPivot('id');
    }
}
</code>```

答:
This should do it:

```<code>$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
                   ->with('materials.profiles')
                   ->get();
</code>```

You want to tell Eloquent that you want the profiles related to the materials ('materials.profiles') rather than the profile related to the PartBasePart. Your original query's withs were the equivalent of with(['materials', 'profiles']).

Title: Laravel 5.5 eloquent cartesian

Body:
What I'm trying to accomplish, I believe, are cartesian results based upon related models.  I want to do this with eager loading.

My eloquent query looks like this:

$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
                       ->with('materials')
                       ->with('profiles')
                       ->get();

And is yielding results of:

+Collection
    PartBasePart - Model
        +Collection
            Material - Model1
            Material - Model2
            Material - Model3
            Material - Model4
            Material - Model5
        +Collection
            Profile  - Model1

What is desire is:

+Collection
    PartBasePart - Model
        +Collection
            Material - Model1
                +Collection
                    Profile  - Model1
            Material - Model2
                +Collection
                    Profile  - Model1
            Material - Model3
                +Collection
                    Profile  - Model1
            Material - Model4
                +Collection
                    Profile  - Model1
            Material - Model5
                +Collection
                    Profile  - Model1

How is this possible?  Can I get an instance of 'Profile - Model1' inside of each Material collection?

The models are defined as follows:

PartBasePart

class PartBasePart extends Eloquent
{
    public function materials()
    {
        return $this->belongsToMany(\App\Models\Material::class)
                    ->withPivot('id');
    }

    public function profiles()
    {
        return $this->belongsToMany(\App\Models\Profile::class)
                    ->withPivot('id');
    }
}

Material

class Material extends Eloquent
{
    public function partBaseParts()
    {
        return $this->belongsToMany(\App\Models\PartBasePart::class)
                    ->withPivot('id');
    }

    public function profiles()
    {
        return $this->belongsToMany(\App\Models\Profile::class)
                    ->withPivot('id');
    }
}

Profile

class Profile extends Eloquent
{
    public function materials()
    {
        return $this->belongsToMany(\App\Models\Material::class)
                    ->withPivot('id');
    }

    public function partBaseParts()
    {
        return $this->belongsToMany(\App\Models\PartBasePart::class)
                    ->withPivot('id');
    }
}

Body:
This should do it:

$results = PartBasePart::whereIn('id', array(1,2,3,4,5))
                   ->with('materials.profiles')
                   ->get();

You want to tell Eloquent that you want the profiles related to the materials ('materials.profiles') rather than the profile related to the PartBasePart. Your original query's withs were the equivalent of with(['materials', 'profiles']).