问:
Webpack, vue.js and component bundles separation
We are trying to build a 'pluginisable' Java webapp which use vue.js on client-side.

General description

Let say we want to get the following server-side application simplified architecture without NodeJs in production (and using Java and Osgi but it doesn't really matter here in my opinion, it may be PHP, .Net or wathever) :

A main webapp which exposes, among others : vuejs2, router and some general dependencies (bootstrap, jQuery etc...) on the client-side,

Many webapp plugins which expose, among others : additional and/or optional vue.js components and third party dependencies.

What we want

The webapp does the work to check for available webapp plugins on server-side and then expose the appropriate JS files in the index file. For example :

app.js : the main webapp loader and general dependencies,

pluginA.js : the vue.js components provided by the server-side plugin "A",

pluginB.js : the vue.js components provided by the server-side plugin "B".

The entire webapp is not build through nodejs but each of the 3 examples are built separately using node and webpack.

Constraints

How can we achieve a build process for the plugins following these constraints :

we want to avoid the javascript build process to have to conciliate all parts of the application at the same time : Checked, we have 1 embedded vue app per webapp plugin, Maven runs the node build process for each webapp plugin and the server-side already does the job to expose all of the 3 files separately,

the plugin JS files only contain the built vue components and 3rd-party dependencies that they want to provide : Not checked, all of the 3 output folders contains all the JS dependencies.

Line of thought

For each webapp plugin, we think we need to find a way to build all .vue files of a webapp plugin and exclude all other dependencies from the output file. As we are new to the node and vuejs world, how could we achieve this ?

Thanks for your help.

答:
You may want to try code splitting:

Code splitting is the idea that a bundle [a .js file with all your Vue.js code bundled together] can be fragmented into smaller files allowing the user to only download what code they need, when they need it.

(...)

The key to code splitting a Vue.js app is async components. These are components where the component definition (including its template, data, methods etc) is loaded asynchronously.

(...)

We’ll need Webpack’s help to dynamically load [components]. (...) Webpack has an implementation [of an] import() [method] and treats it as a code split point, putting the requested module into a separate file when the bundle is created.

Source: Code Splitting With Vue.js And Webpack, a very helpful guide for implementing code splitting.

Below is the main.js code that the author of the guide ends up with to dynamically load a component. If I read the guide correctly, this change in the way you register a component is the only change necessary to implement code splitting. No changes are necessary in your Webpack config.

```<code>new Vue({
  el: '#app',
  components: {
    ExampleAsyncComponent: () => import('./ExampleAsyncComponent.vue') /* This is the changed part. */
  }
});
</code>```

Body:
You may want to try code splitting:

Code splitting is the idea that a bundle [a .js file with all your Vue.js code bundled together] can be fragmented into smaller files allowing the user to only download what code they need, when they need it.

(...)

The key to code splitting a Vue.js app is async components. These are components where the component definition (including its template, data, methods etc) is loaded asynchronously.

(...)

We’ll need Webpack’s help to dynamically load [components]. (...) Webpack has an implementation [of an] import() [method] and treats it as a code split point, putting the requested module into a separate file when the bundle is created.

Source: Code Splitting With Vue.js And Webpack, a very helpful guide for implementing code splitting.

Below is the main.js code that the author of the guide ends up with to dynamically load a component. If I read the guide correctly, this change in the way you register a component is the only change necessary to implement code splitting. No changes are necessary in your Webpack config.

new Vue({
  el: '#app',
  components: {
    ExampleAsyncComponent: () => import('./ExampleAsyncComponent.vue') /* This is the changed part. */
  }
});


来源: stackexchange

问:
copy all request attributes in class attributes
In my controller I have methods to store and update. As you see, I am copying $request attributes in $tour attributes one by one:

```<code>class TourController extends Controller
{
    public function store(Request $request, Tour $tour)
        {
          $tour->name = $request->name;
          $tour->flight = $request->flight;
          $tour->price = $request->price;
          $tour->description = $request->description;
          $tour->save();
          return redirect('home/tour/see');
        }
    public function update(Request $request)
        {
            $tour = Tour::find($request->id);
            $tour->name = $request->name;
            $tour->flight = $request->flight;
            $tour->price = $request->price;
            $tour->description = $request->description;
            $tour->save();
            return redirect('home/tour/see');
        }
}
</code>```

It seems, I'm repeating my code, and my question is, is there a way to copy all of them at once? How to copy all request attributes in tour attributes?

答:
yes you can do $tour = request()->all(); to get all the inputs at the same time

or you could do smth like this:

```<code>$tour = new Tour;

$tour= save(request()->all());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In my controller I have methods to store and update. As you see, I am copying $request attributes in $tour attributes one by one:

class TourController extends Controller
{
    public function store(Request $request, Tour $tour)
        {
          $tour->name = $request->name;
          $tour->flight = $request->flight;
          $tour->price = $request->price;
          $tour->description = $request->description;
          $tour->save();
          return redirect('home/tour/see');
        }
    public function update(Request $request)
        {
            $tour = Tour::find($request->id);
            $tour->name = $request->name;
            $tour->flight = $request->flight;
            $tour->price = $request->price;
            $tour->description = $request->description;
            $tour->save();
            return redirect('home/tour/see');
        }
}

It seems, I'm repeating my code, and my question is, is there a way to copy all of them at once? How to copy all request attributes in tour attributes?

Body:
yes you can do $tour = request()->all(); to get all the inputs at the same time

or you could do smth like this:

$tour = new Tour;

$tour= save(request()->all());


问:
Programming tabbed activity content
Where do I need to put the Java code to program the buttons in a tabbed activity? In the activity that contains those two tabs I have this code:

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

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
private DatePickerDialog.OnDateSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_picker;
private TextView date_text;
private TextView hora_text;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // 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.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    date_button = (Button) findViewById(R.id.date_button);

    date_button.setOnClickListener(
            new View.OnClickListener(){
                public void onClick(View v){
                        Calendar cal = Calendar.getInstance();
                        int year = cal.get(Calendar.YEAR);
                        int month = cal.get(Calendar.MONTH);
                        int day = cal.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog date_dialog = new DatePickerDialog(
                                Testes.this,
                                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                hourSetListener,
                                year, month, day);
                        date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        date_dialog.show();

                    };
                }

    );

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month=month+1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            String dt = day+"-"+month+"-"+year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            try {
                sdf.parse(dt);
                date_text.setText(dt);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

}

@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_testes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()){
       case go_to_fazer_media:{
           if (item.isChecked())
               item.setChecked(false);
            else{
           Intent i = new Intent(Testes.this,Formas.class);
           startActivity(i);
               return true;
            }
       }
       case definicoes:{
           if (item.isChecked())
               item.setChecked(false);
           else{
              return true;
           }
       }
   }

    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch(position){

            case 0:
                Tab1tests tab1 =  new Tab1tests();
                return tab1;
            case 1:
                Tab2calendar tab2 =  new Tab2calendar();
                return tab2;
            default:
                return null;
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Adicionar Testes";
            case 1:
                return "Mapa de Testes";
        }
        return null;
    }
}
</code>```

These is the xml of the tab that I want to program the buttons:

```<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

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

<TextView
    android:id="@+id/disciplina"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/section_label"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Disciplina:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/sala"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/disciplina"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Sala:"
    android:textSize="35sp"/>

<TextView
    android:id="@+id/Dia"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/sala"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Dia:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/Hora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/Dia"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Hora:"
    android:textSize="35sp" />

<Button
    android:id="@+id/add_test"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_marginBottom="95dp"
    android:text="Adicionar o teste"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/date_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:visibility="invisible"/>

<Button
    android:id="@+id/date_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:onClick="setDate"/>

<TextView
    android:id="@+id/hora_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/Hora"
    android:visibility="invisible"/>
<Button
    android:id="@+id/hora_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBaseline="@+id/Hora"
    android:layout_toEndOf="@+id/sala" />

<EditText
    android:id="@+id/sala_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/sala"
    android:layout_toEndOf="@+id/Hora"
    android:ems="10"
    android:hint="Nª/Nome da sala"
    android:textSize="25sp"
    android:inputType="textPersonName" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/disciplina"
    android:layout_toEndOf="@+id/disciplina"
    android:scrollbarSize="25sp"
    android:layout_alignTop="@+id/disciplina" />
</code>```

}This layout

答: You will have to code the buttons in the Fragment class which you are using in the activity. In your case you will have to add and code the buttons in the Tab1tests  and Tab2calendar classes and not in the activity itself as you have done.</p>

Title: Programming tabbed activity content

Body:
Where do I need to put the Java code to program the buttons in a tabbed activity? In the activity that contains those two tabs I have this code:

   public class Testes extends AppCompatActivity {

private SectionsPagerAdapter mSectionsPagerAdapter;

private ViewPager mViewPager;
private DatePickerDialog.OnDateSetListener hourSetListener;
private DatePickerDialog.OnDateSetListener dateSetListener;
private Button date_button;
private Button hora_picker;
private TextView date_text;
private TextView hora_text;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    // 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.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);

    date_button = (Button) findViewById(R.id.date_button);

    date_button.setOnClickListener(
            new View.OnClickListener(){
                public void onClick(View v){
                        Calendar cal = Calendar.getInstance();
                        int year = cal.get(Calendar.YEAR);
                        int month = cal.get(Calendar.MONTH);
                        int day = cal.get(Calendar.DAY_OF_MONTH);
                        DatePickerDialog date_dialog = new DatePickerDialog(
                                Testes.this,
                                android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                                hourSetListener,
                                year, month, day);
                        date_dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                        date_dialog.show();

                    };
                }

    );

    dateSetListener = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int month, int day) {
            month=month+1;
            date_button.setVisibility(View.GONE);
            date_text = (TextView) findViewById(R.id.date_text);
            date_text.setVisibility(View.VISIBLE);
            String dt = day+"-"+month+"-"+year;
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
            try {
                sdf.parse(dt);
                date_text.setText(dt);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

}

@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_testes, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   switch (item.getItemId()){
       case go_to_fazer_media:{
           if (item.isChecked())
               item.setChecked(false);
            else{
           Intent i = new Intent(Testes.this,Formas.class);
           startActivity(i);
               return true;
            }
       }
       case definicoes:{
           if (item.isChecked())
               item.setChecked(false);
           else{
              return true;
           }
       }
   }

    return super.onOptionsItemSelected(item);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {
        switch(position){

            case 0:
                Tab1tests tab1 =  new Tab1tests();
                return tab1;
            case 1:
                Tab2calendar tab2 =  new Tab2calendar();
                return tab2;
            default:
                return null;
        }
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "Adicionar Testes";
            case 1:
                return "Mapa de Testes";
        }
        return null;
    }
}

These is the xml of the tab that I want to program the buttons:

   <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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin">

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

<TextView
    android:id="@+id/disciplina"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/section_label"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Disciplina:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/sala"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/disciplina"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Sala:"
    android:textSize="35sp"/>

<TextView
    android:id="@+id/Dia"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/sala"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Dia:"
    android:textSize="35sp" />

<TextView
    android:id="@+id/Hora"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/Dia"
    android:layout_margin="20dp"
    android:layout_toEndOf="@+id/section_label"
    android:text="Hora:"
    android:textSize="35sp" />

<Button
    android:id="@+id/add_test"
    style="@style/Widget.AppCompat.Button.Colored"
    android:layout_width="wrap_content"
    android:layout_height="60dp"
    android:layout_marginBottom="95dp"
    android:text="Adicionar o teste"
    android:textSize="20sp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<TextView
    android:id="@+id/date_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:visibility="invisible"/>

<Button
    android:id="@+id/date_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignStart="@+id/hora_picker"
    android:layout_alignTop="@+id/Dia"
    android:text="ESCOLHER DATA"
    android:textSize="25sp"
    android:textStyle="bold"
    android:onClick="setDate"/>

<TextView
    android:id="@+id/hora_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBottom="@+id/Hora"
    android:layout_toEndOf="@+id/Hora"
    android:visibility="invisible"/>
<Button
    android:id="@+id/hora_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:text="ESCOLHER HORA"
    android:textStyle="bold"
    android:textSize="25sp"
    android:layout_alignBaseline="@+id/Hora"
    android:layout_toEndOf="@+id/sala" />

<EditText
    android:id="@+id/sala_text"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/sala"
    android:layout_toEndOf="@+id/Hora"
    android:ems="10"
    android:hint="Nª/Nome da sala"
    android:textSize="25sp"
    android:inputType="textPersonName" />

<Spinner
    android:id="@+id/spinner2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/disciplina"
    android:layout_toEndOf="@+id/disciplina"
    android:scrollbarSize="25sp"
    android:layout_alignTop="@+id/disciplina" />

}This layout


问:
Windows Forms in c# error
For one of my projects, I need to write a program that shows a list of products with a check and or cross to the left of it. I have everything sorted except the forms part
I have come across this problem:

```<code>class Presentation
{
    static Form Window = new Form();
    static public void Configuration()
    {
        Window.Height = 800;
        Window.Width = 800;
        Window.Text = "Homework";

        Graphics draw = Window.CreateGraphics();

        Window.Paint += Window_Paint();

        Window.Show();
    }
    void Window_Paint(System.Object sender, PaintEventArgs e)
    {
        AnyOtherConfigurations(e);
    }
    static public void AnyOtherConfigurations(PaintEventArgs e)
    {
        Pen pen1 = new Pen(Color.Red);
        Font font = new Font(FontFamily.GenericSansSerif, 8,
        FontStyle.Regular, GraphicsUnit.Millimeter);
        Graphics draw = Window.CreateGraphics();
        e.Graphics.FillEllipse(new SolidBrush(Color.Yellow),x,y,80,80);
        draw.DrawRectangle(pen1, 0, 0, 90, 90);

    }
}
</code>```

It gives me the error that says:

```<code>CS7036 There is no argument given that corresponds to the required formal parameter 'sender' of 'UserQuery.Presentation.Window_Paint(object, PaintEventArgs)'
CS0029 Cannot implicitly convert type 'void' to 'System.Windows.Forms.PaintEventHandler'
</code>```

Can anyone suggest a reason why this might be happening and give me advice on how to fix it?

答:
Do not write

```<code>Object.Event += Method();
</code>```

but

```<code>Object.Event += Method;
</code>```

instead.

The eventlistener wants a reference to the method to use the delegate, not to the returnvalue of the method itself. This explains your error.

Title: Windows Forms in c# error

Body:
For one of my projects, I need to write a program that shows a list of products with a check and or cross to the left of it. I have everything sorted except the forms part
I have come across this problem:

class Presentation
{
    static Form Window = new Form();
    static public void Configuration()
    {
        Window.Height = 800;
        Window.Width = 800;
        Window.Text = "Homework";

        Graphics draw = Window.CreateGraphics();

        Window.Paint += Window_Paint();

        Window.Show();
    }
    void Window_Paint(System.Object sender, PaintEventArgs e)
    {
        AnyOtherConfigurations(e);
    }
    static public void AnyOtherConfigurations(PaintEventArgs e)
    {
        Pen pen1 = new Pen(Color.Red);
        Font font = new Font(FontFamily.GenericSansSerif, 8,
        FontStyle.Regular, GraphicsUnit.Millimeter);
        Graphics draw = Window.CreateGraphics();
        e.Graphics.FillEllipse(new SolidBrush(Color.Yellow),x,y,80,80);
        draw.DrawRectangle(pen1, 0, 0, 90, 90);

    }
}

It gives me the error that says:

CS7036 There is no argument given that corresponds to the required formal parameter 'sender' of 'UserQuery.Presentation.Window_Paint(object, PaintEventArgs)'
CS0029 Cannot implicitly convert type 'void' to 'System.Windows.Forms.PaintEventHandler'

Can anyone suggest a reason why this might be happening and give me advice on how to fix it?

Body:
Do not write

Object.Event += Method();

but

Object.Event += Method;

instead.

The eventlistener wants a reference to the method to use the delegate, not to the returnvalue of the method itself. This explains your error.


问:
SonarQube complains about using ResponseEntity with a wildcard
I use SpringBoot for REST web services development and SonarQube for static analysis.

I have a few endpoints in my application that look the following way:

```<code>@PostMapping
ResponseEntity<?> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
</code>```

SonarQube complains about using ResponseEntity with a wildcard, reporting me a Critical issue "Generic wildcard types should not be used in return parameters".

I wonder if I should disable this verification in SonarQube or come up with something different for return type for these cases.

What do you think about it?

答:
So actually i find the rule pretty self describing:

Using a wildcard as a return type implicitly means that the return value should be considered read-only, but without any way to enforce this contract.

Let's take the example of method returning a "List". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. The consumer of a method should not have to deal with such disruptive questions.

https://sonarcloud.io/organizations/default/rules#rule_key=squid%3AS1452

So Actually in your case, you do not want any kind of Class in there, you specifically want an Serializable-object - for obvious reasons: it should be serialized later on

So instead of using ? it would be more suitable in your case to use Serializable. This is always case dependent, but normally you definitly expect some kind of common interface or base class as a return value. Hence that, the follow up developer, definitly knows what he can expect, and what kind of functionality he definitly can use.

Body:
I use SpringBoot for REST web services development and SonarQube for static analysis.

I have a few endpoints in my application that look the following way:

@PostMapping
ResponseEntity<?> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

SonarQube complains about using ResponseEntity with a wildcard, reporting me a Critical issue "Generic wildcard types should not be used in return parameters".

I wonder if I should disable this verification in SonarQube or come up with something different for return type for these cases.

What do you think about it?


问:
Why is RuntimeException legal here?
This is my code:

```<code> import java.io.*;
 import java.sql.*;
 import java.io.*;
 import java.sql.*;
 class Vehicle{
    public void park()throws IOException {//compiletime checked
    }
 }
 class Car extends Vehicle{
     public void park()throws RuntimeException{//compile time unchecked
         //
     }
 }
</code>```

Why compile time unchecked exceptions is legal here?

答:
If superclass method throws/declare checked/compileTime exception, then--

overridden method of subclass can declare/throw narrower (subclass of) checked exception

overridden method of subclass cannot declare/throw broader (superclass of) checked exception

overridden method of subclass can declare/throw any unchecked /RuntimeException

overridden method of subclass can declare/throw same exception

overridden method of subclass may not declare/throw any exception.

Title: Why is RuntimeException legal here?

Body:
This is my code:

 import java.io.*;
 import java.sql.*;
 import java.io.*;
 import java.sql.*;
 class Vehicle{
    public void park()throws IOException {//compiletime checked
    }
 }
 class Car extends Vehicle{
     public void park()throws RuntimeException{//compile time unchecked
         //
     }
 }

Why compile time unchecked exceptions is legal here?


问:
How to install wxWidgets with Code::Blocks?
I'm a windows developer and I need to use Code::Blocks
to develope multiplataform C++ GUI applications.

After installing Code::Blocks and wxWidgets in my first try to do a simple "Hello World" application, the IDE show me a box with $(#wx)

What is the $(#wx) ?

Googling for tutorials I see this

What is the -g ?

Finally the following error message appear:

For 3 days I'm trying over and over again without success !

I even try wxPack. Nothing works !

With VC++, C++Builder and even wxDev-C++ this is straightforward

Only Code::Blocks is so difficult !

Googling, I find many people with the same error, but the advices they get didn't work for me !

Can someone tell me step by step what I must do?

Thank you.

答: Since you having hard time using C::B, I suggest you switch to CodeLite which I find simpler to start with than C::B (My experience). Everything you need is documented on CodeLite Wiki. Creating project is well documented with screenshots but before you compile, open environment variables (Settings->Environment Variables) and add line WXWIN=/path/to/your/wxwidgets/installation and compile as it is explained there.

ContentLicense: CC BY-SA 4.0


问:
How to Get A Element First Child Text Using Jquery And Class Selector?
I Have Two Element Inside a Element. like below =>

```<code><div class="NDateCount" style="display:inline-block">
     <!--Issue to solve-->
     <small style="display:none;" class="ng-binding">2017-07-08T12:44:10.367+06:00</small>
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"><i class="fa fa-clock-o"></i> 3 hours ago</small>
     <!--End of Issue to solve-->
</div>
</code>```

i have this kind of div more than 10 time with is generating dynamically. and i want first child of div element which is small text; and i have done so far ==>

```<code>    var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).first().text();
            alert(OldValue);
         });
        setTimeout(ReloadTime, 50);
    }
</code>```

but the above function giving something like both small tag innner text.
like ==>

is there ant way to solve this problem......

答:
Do like this

```<code>var ReloadTime = function () {
    $('.NDateCount').each(function () {
        var OldValue = $(this).find('small').eq(0).text();
        alert(OldValue);
     });
    setTimeout(ReloadTime, 50);
}
</code>```

It will work for you.

Body:
I Have Two Element Inside a Element. like below =>

     2017-07-08T12:44:10.367+06:00
     <small ng-show="CountPostDate(post.timelineStrore.creationDate) < 2" style="color:#1ab394;" class="ng-binding"> 3 hours ago

i have this kind of div more than 10 time with is generating dynamically. and i want first child of div element which is small text; and i have done so far ==>

    var ReloadTime = function () {
        $('.NDateCount').each(function () {
            var OldValue = $(this).first().text();
            alert(OldValue);
         });
        setTimeout(ReloadTime, 50);
    }

but the above function giving something like both small tag innner text.
like ==>

is there ant way to solve this problem......

Body:
Do like this

var ReloadTime = function () {
    $('.NDateCount').each(function () {
        var OldValue = $(this).find('small').eq(0).text();
        alert(OldValue);
     });
    setTimeout(ReloadTime, 50);
}

It will work for you.


问:
Display text with icon in Xamarin forms
How to display text with icon in button? I am using font awesome icons and displaying them using their uni code. Like this:

Now if i add unicode with text the icon doesnt show although text still shows.

This only shows text and Cross instead of icon.

答:
you use hex "&#x" instead of "\u"

eg.

```<code><Button Text="⚙"/>
</code>```

Title: Display text with icon in Xamarin forms

Body:
you use hex "&#x" instead of "\u"

eg.

<Button Text="&#x2699;"/>


问:
What is the PHP7 version of $_SERVER['HOME']
Recently, I have installed a new Ubuntu server which incorporates PHP7. Previously, on PHP5.3 (or it may have been a later version of PHP5, I could use $_SERVER['HOME'] which returned the home path of the server (i.e. /var/www/). However, this is not possible in PHP7 as $_SERVER['HOME'] is no more.

If I have a site which has a document root of /var/www//httpdocs, how do I get the /var/www/ part. I can not hard code it as my test server (a Synology NAS) does not use PHP7 and can not be upgraded to PHP7 and thus, I need to use a variable that is constant for PHP5 and PHP7 which return the same result to forumate the same result as $_SERVER['HOME'] did in PHP5.

I tried using $_ENV['HOME'] but this appears to print nothing from my system when a simple die($_ENV['HOME']); is executed.

Can someone put me out of my misery please?

Thanks

答:
OK, thanks to @apokryfos, I have sorted the issue. I perhaps should have mention I wanted to include a file outside of the document root (oops, my bad).

The getenv('HOME') for some unknown reason returns an empty string on my server, but the method I used to overcome this was to use the dirname option.

The final result was:

```<code>set_include_path(get_include_path().PATH_SEPARATOR.dirname($_SERVER['DOCUMENT_ROOT'],1)."/includes");
</code>```

Thanks again for your assistance.

Body:
OK, thanks to @apokryfos, I have sorted the issue. I perhaps should have mention I wanted to include a file outside of the document root (oops, my bad).

The getenv('HOME') for some unknown reason returns an empty string on my server, but the method I used to overcome this was to use the dirname option.

The final result was:

set_include_path(get_include_path().PATH_SEPARATOR.dirname($_SERVER['DOCUMENT_ROOT'],1)."/includes");

Thanks again for your assistance.


问:
Angular 2 ngFor - reverse order of output using the index
Trying to learn something about filtering and ordering in Angular 2. I can't seem to find any decent resources and I'm stuck at how to order an ngFor output in reverse order using the index. I have written the the following pipe put it keeps giving me errors that array slice in not a function.

```<code>@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(arr) {
        var copy = arr.slice();
        return copy.reverse();
    }
}
</code>```

and my ngfor looks like this.

```<code><div class="table-row generic" *ngFor="let advert of activeAdverts | reverse let i = index;" [attr.data-index]="i" (click)="viewAd(advert.title)">
    <div class="table-cell white-text">{{ i+1 }}</div>
    <div class="table-cell white-text">{{advert.title}}</div>
    <div class="table-cell green-text">{{advert.advert}}</div>
</div>
</code>```

答:
Using the following method u can reverse the output, but orignal array won't be modified,</p>

```<code> <tr *ngFor="let advert of activeAdverts; let i = index" >
           <td>{{activeAdverts[activeAdverts.length-i-1]}}</td>
  </tr>
</code>```

Body:
Trying to learn something about filtering and ordering in Angular 2. I can't seem to find any decent resources and I'm stuck at how to order an ngFor output in reverse order using the index. I have written the the following pipe put it keeps giving me errors that array slice in not a function.

@Pipe({
    name: 'reverse'
})
export class ReversePipe implements PipeTransform {
    transform(arr) {
        var copy = arr.slice();
        return copy.reverse();
    }
}

and my ngfor looks like this.

{{ i+1 }}

{{advert.title}}

{{advert.advert}}

Body:
Using the following method u can reverse the output, but orignal array won't be modified,

 <tr *ngFor="let advert of activeAdverts; let i = index" >
           <td>{{activeAdverts[activeAdverts.length-i-1]}}</td>
  </tr>


问:
Error inflating class android.support.design.widget.FloatingActionButton
My app crashed because

Error inflating class android.support.design.widget.FloatingActionButton

This is my code in the XML

```<code><android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:src="@drawable/icon_right"
        app:backgroundTint="@color/green"
        android:onClick="previewphoto"
        app:layout_anchorGravity="bottom|right|end" />
</code>```

and here is my gradle

```<code>compile 'com.android.support:appcompat-v7:23.4.0' // appcompat library
compile 'com.android.support:design:23.4.0'
</code>```

my logcat

FATAL EXCEPTION: main Process: com.cyanlabsid.cetakphoto, PID: 15298
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.cyanlabsid.cetakphoto/com.cyanlabsid.cetakphoto.PhotoPicker}:
  android.view.InflateException: Binary XML file line #76: Binary XML
  file line #76: Error inflating class
  android.support.design.widget.FloatingActionButton at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
  at android.app.ActivityThread.access$900(ActivityThread.java:153) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:148) at
  android.app.ActivityThread.main(ActivityThread.java:5441) at
  java.lang.reflect.Method.invoke(Native Method) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) Caused
  by: android.view.InflateException: Binary XML file line #76: Binary
  XML file line #76: Error inflating class
  android.support.design.widget.FloatingActionButton at
  android.view.LayoutInflater.inflate(LayoutInflater.java:543) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:427) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:374) at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
  at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
  at com.cyanlabsid.cetakphoto.PhotoPicker.onCreate(PhotoPicker.java:74)
  at android.app.Activity.performCreate(Activity.java:6303) at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
  at android.app.ActivityThread.access$900(ActivityThread.java:153)  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
  at android.os.Handler.dispatchMessage(Handler.java:102)  at
  android.os.Looper.loop(Looper.java:148)  at
  android.app.ActivityThread.main(ActivityThread.java:5441)  at
  java.lang.reflect.Method.invoke(Native Method)  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

Can somebody tell my fault?

答:
I had the same problem

I faced the same issue with Pre-Lolipop version and to resolve it, I just changed "android:src" to "app:srcCompat"  & it worked for me.

To make compatibility with older version and if you're using a Vector graphics (as drawable assets) you should use:

```<code>app:srcCompat="@drawable/you_graphics"
</code>```

instead of:

```<code>android:src="@drawable/your_graphics"
</code>```

Body:
My app crashed because

Error inflating class android.support.design.widget.FloatingActionButton

This is my code in the XML

<android.support.design.widget.FloatingActionButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_margin="16dp"
        android:src="@drawable/icon_right"
        app:backgroundTint="@color/green"
        android:onClick="previewphoto"
        app:layout_anchorGravity="bottom|right|end" />

and here is my gradle

compile 'com.android.support:appcompat-v7:23.4.0' // appcompat library
compile 'com.android.support:design:23.4.0'

my logcat

FATAL EXCEPTION: main Process: com.cyanlabsid.cetakphoto, PID: 15298
  java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.cyanlabsid.cetakphoto/com.cyanlabsid.cetakphoto.PhotoPicker}:
  android.view.InflateException: Binary XML file line #76: Binary XML
  file line #76: Error inflating class
  android.support.design.widget.FloatingActionButton at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2423)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
  at android.app.ActivityThread.access$900(ActivityThread.java:153) at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
  at android.os.Handler.dispatchMessage(Handler.java:102) at
  android.os.Looper.loop(Looper.java:148) at
  android.app.ActivityThread.main(ActivityThread.java:5441) at
  java.lang.reflect.Method.invoke(Native Method) at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628) Caused
  by: android.view.InflateException: Binary XML file line #76: Binary
  XML file line #76: Error inflating class
  android.support.design.widget.FloatingActionButton at
  android.view.LayoutInflater.inflate(LayoutInflater.java:543) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:427) at
  android.view.LayoutInflater.inflate(LayoutInflater.java:374) at
  android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
  at
  android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
  at com.cyanlabsid.cetakphoto.PhotoPicker.onCreate(PhotoPicker.java:74)
  at android.app.Activity.performCreate(Activity.java:6303) at
  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
  at
  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2376)
  at
  android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2483)
  at android.app.ActivityThread.access$900(ActivityThread.java:153)  at
  android.app.ActivityThread$H.handleMessage(ActivityThread.java:1349)
  at android.os.Handler.dispatchMessage(Handler.java:102)  at
  android.os.Looper.loop(Looper.java:148)  at
  android.app.ActivityThread.main(ActivityThread.java:5441)  at
  java.lang.reflect.Method.invoke(Native Method)  at
  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

Can somebody tell my fault?

Body:
I had the same problem

I faced the same issue with Pre-Lolipop version and to resolve it, I just changed "android:src" to "app:srcCompat"  & it worked for me.

To make compatibility with older version and if you're using a Vector graphics (as drawable assets) you should use:

app:srcCompat="@drawable/you_graphics"

instead of:

android:src="@drawable/your_graphics"


答:
Create a class which gets all attributes from the request and sets these properties.

```<code>class TourHydrator

public function updateFromRequest(Request $request, Tour $tour)
{
     $tour->name = $request->name;
     $tour->flight = $request->flight;
     $tour->price = $request->price;
     $tour->description = $request->description;
}
</code>```

Then inject it in your controller

```<code>class TourController extends Controller
{

    /**
     * @var TourHydrator
     */
    private $tourHydrator;

    public function __construct(TourHydrator $tourHydrator)
    {
        $this->tourHydrator = $tourHydrator;
    }

    public function store(Request $request, Tour $tour)
    {
        $this->tourHydrator->updateFromRequest($request, $tour);
        $tour->save();
        return redirect('home/tour/see');
    }

    public function update(Request $request)
    {
        $tour = Tour::find($request->id);
        $this->tourHydrator->updateFromRequest($request, $tour);
        $tour->save();
        return redirect('home/tour/see');
    }
}
</code>```

I would recommend this approach rather than using $request->all() because the request might change as the application evolves.

You can also add validation for instance and in your controller you can treat them:

```<code>try {
    $this->tourHydrator->updateFromRequest($request, $tour);
    $tour->save();
    return redirect('home/tour/see');
} catch (SomeException $e) {
    return redirect('home/tour/invalid');
}
</code>```

I would also recommend using gettest and setters in your Tour model because sometimes magic methods can be tricky especially when it comes to testing. Then you could change the TourHydrator to use the appropriate setters.

Title: copy all request attributes in class attributes

Body:
Create a class which gets all attributes from the request and sets these properties.

class TourHydrator

public function updateFromRequest(Request $request, Tour $tour)
{
     $tour->name = $request->name;
     $tour->flight = $request->flight;
     $tour->price = $request->price;
     $tour->description = $request->description;
}

Then inject it in your controller

class TourController extends Controller
{

    /**
     * @var TourHydrator
     */
    private $tourHydrator;

    public function __construct(TourHydrator $tourHydrator)
    {
        $this->tourHydrator = $tourHydrator;
    }

    public function store(Request $request, Tour $tour)
    {
        $this->tourHydrator->updateFromRequest($request, $tour);
        $tour->save();
        return redirect('home/tour/see');
    }

    public function update(Request $request)
    {
        $tour = Tour::find($request->id);
        $this->tourHydrator->updateFromRequest($request, $tour);
        $tour->save();
        return redirect('home/tour/see');
    }
}

I would recommend this approach rather than using $request->all() because the request might change as the application evolves.

You can also add validation for instance and in your controller you can treat them:

try {
    $this->tourHydrator->updateFromRequest($request, $tour);
    $tour->save();
    return redirect('home/tour/see');
} catch (SomeException $e) {
    return redirect('home/tour/invalid');
}

I would also recommend using gettest and setters in your Tour model because sometimes magic methods can be tricky especially when it comes to testing. Then you could change the TourHydrator to use the appropriate setters.


问:
REST Client not generating Webhook Events in Sandbox
I am unable to get the Paypal provided REST client  (the client side js) to trigger webhook events in the sandbox to receive payment confirmation on my server app.

Here's what I can do/ have done:

I have created a REST app in the sandbox.

I have subscribed to all webhook events.

I am able to pay with the client app using my sandbox client id and see see the payment reflected in the facilitator account.

I am able to generate a webhook event using the Webhook simulator and receive it / parse it on my server.

However, when I do a sandbox payment transaction using the client, no webhook event is created (as reflected in the Webhook events list provided in the dashboard), nor it is sent to my server.  Again, my server receives simulated webhooks just fine.

The problem seems to be that the Paypal REST Client is not generating a webhook event.  I have tripled checked everything, but cannot see what I've missed.  Help!

答: I have the same problem. I racked my brain trying to figure out if something was wrong with my code. I contacted Paypal and they said this is an ongoing issue with Paypal sandbox and are working to resolve it. </p>


问:
Cordova dialog plugin not working
I've been stuck on this issue for 10+ hours now and I'm having no luck in fixing it by myself. The problem is that I'm trying to use this dialog plugin on my Cordova app but its not working. I don't even think that the deviceready script is working.

Any questions feel free to ask

www/index.html:

```<code><!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Security-Policy" content=".." />
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="css/layout-styles.css" rel="stylesheet" type="text/css">
        <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">
        <script src="cordova_plugins.js"></script>
        <script src="cordova.js"></script>
        <script src="js/index.js"></script>
        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/bootstrap.js"></script>
        <title>Plugins Not Working</title>

        <script src="cordova.js">

            document.addEventListener("deviceready", onDeviceReady(), false)

            function onDeviceReady() {
                navigator.notification.alert(
                    'Script has loaded',  // message
                    alertDismissed,       // callback
                    'Loaded',             // title
                    'Done'                // buttonName
                );
            };

            function alertDismissd() {
                // do something
            };

         </script>
    </head>
</html>
</code>```

The <plugin name="cordova-plugin-dialogs" spec="^1.3.3" /> is in config.xml

答: I reinstalled windows 10 and reinstalled cordova as a whole. Now all plugins work :) sorry if this isnt the answer you wanted but it worked for me! Have a good day!</p>

Title: Cordova dialog plugin not working

Body:
I've been stuck on this issue for 10+ hours now and I'm having no luck in fixing it by myself. The problem is that I'm trying to use this dialog plugin on my Cordova app but its not working. I don't even think that the deviceready script is working.

Any questions feel free to ask

www/index.html:

<!DOCTYPE html>

        <meta http-equiv="Content-Security-Policy" content=".." />
        <meta name="format-detection" content="telephone=no">
        <meta name="msapplication-tap-highlight" content="no">
        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
        <link rel="stylesheet" type="text/css" href="css/index.css">
        <link href="css/layout-styles.css" rel="stylesheet" type="text/css">
        <link href="css/bootstrap-3.3.7.css" rel="stylesheet" type="text/css">

        <title>Plugins Not Working</title>

The <plugin name="cordova-plugin-dialogs" spec="^1.3.3" /> is in config.xml


问:
choose rows from two matrices
I am trying to solve the following problem. I have two matrices A and B and I want to create a new matrix C which consists of the rows of the matrices A and B depending on some condition which is encoded in the array v, i.e. if the i'th entry of v is a one then I want the i'th row of C to be the i'th row of B and if it is a zero then it should be the i'th row of A. I came up with the following solution

```<code>C = np.choose(v,A.T,B.T).T
</code>```

but it is too slow. One obvious bad thing are the two transposes, but since np.choose does not take an axis argument I don't know how to get rid of them. Any ideas for a fast solution of this problem?

For Example let

```<code>A = np.arange(20).reshape([4,5])
</code>```

and

```<code>B = 10 - A
</code>```

Then one could imagine that one wants the matrix C to be the matrix of rows with smallest maximum norm. So we let

```<code>v = np.sum(A,axis=1)<np.sum(B,axis=1)
</code>```

and then C is the matrix

```<code>C = np.choose(v,[A.T,B.T]).T
</code>```

which is

```<code>array([[10,  9,  8,  7,  6],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
</code>```

答:
Seems like a good setup to use np.where to do the chosing operation based on the mask/binary input data -

```<code>C = np.where(v[:,None],B,A)
</code>```

That v[:,None] part basically extends v to broadcastable shape as A and B allowing the broadcasting to let chosing work along the appropriate axis, axis=0 in this case for the two 2D arrays.

Sample run -

```<code>In [58]: A
Out[58]:
array([[82, 78, 57],
       [14, 97, 32],
       [72, 11, 49],
       [98, 34, 41],
       [89, 71, 52],
       [34, 51, 55],
       [26, 92, 59]])

In [59]: B
Out[59]:
array([[55, 67, 50],
       [49, 64, 21],
       [34, 18, 72],
       [24, 61, 65],
       [56, 59, 23],
       [44, 77, 13],
       [56, 55, 58]])

In [62]: v
Out[62]: array([1, 0, 0, 0, 0, 1, 1])

In [63]: np.where(v[:,None],B,A)
Out[63]:
array([[55, 67, 50],
       [14, 97, 32],
       [72, 11, 49],
       [98, 34, 41],
       [89, 71, 52],
       [44, 77, 13],
       [56, 55, 58]])
</code>```

If v doesn't strictly consist of 0s and 1s only, use v[:,None]==1 as the first argument with np.where.

Another approach would be with boolean-indexing -

```<code>C = A.copy()
mask = v==1
C[mask] = B[mask]
</code>```

Note : If v is already a boolean array, skip the comparison against 1 for the mask creation.

Runtime test -

```<code>In [77]: A = np.random.randint(11,99,(10000,3))

In [78]: B = np.random.randint(11,99,(10000,3))

In [79]: v = np.random.rand(A.shape[0])>0.5

In [82]: def choose_rows_copy(A, B, v):
    ...:     C = A.copy()
    ...:     C[v] = B[v]
    ...:     return C
    ...:

In [83]: %timeit np.where(v[:,None],B,A)
10000 loops, best of 3: 107 µs per loop

In [84]: %timeit choose_rows_copy(A, B, v)
1000 loops, best of 3: 226 µs per loop
</code>```

Title: choose rows from two matrices

Body:
I am trying to solve the following problem. I have two matrices A and B and I want to create a new matrix C which consists of the rows of the matrices A and B depending on some condition which is encoded in the array v, i.e. if the i'th entry of v is a one then I want the i'th row of C to be the i'th row of B and if it is a zero then it should be the i'th row of A. I came up with the following solution

C = np.choose(v,A.T,B.T).T

but it is too slow. One obvious bad thing are the two transposes, but since np.choose does not take an axis argument I don't know how to get rid of them. Any ideas for a fast solution of this problem?

For Example let

A = np.arange(20).reshape([4,5])

and

B = 10 - A

Then one could imagine that one wants the matrix C to be the matrix of rows with smallest maximum norm. So we let

v = np.sum(A,axis=1)<np.sum(B,axis=1)

and then C is the matrix

C = np.choose(v,[A.T,B.T]).T

which is

array([[10,  9,  8,  7,  6],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

Body:
Seems like a good setup to use np.where to do the chosing operation based on the mask/binary input data -

C = np.where(v[:,None],B,A)

That v[:,None] part basically extends v to broadcastable shape as A and B allowing the broadcasting to let chosing work along the appropriate axis, axis=0 in this case for the two 2D arrays.

Sample run -

In [58]: A
Out[58]:
array([[82, 78, 57],
       [14, 97, 32],
       [72, 11, 49],
       [98, 34, 41],
       [89, 71, 52],
       [34, 51, 55],
       [26, 92, 59]])

In [59]: B
Out[59]:
array([[55, 67, 50],
       [49, 64, 21],
       [34, 18, 72],
       [24, 61, 65],
       [56, 59, 23],
       [44, 77, 13],
       [56, 55, 58]])

In [62]: v
Out[62]: array([1, 0, 0, 0, 0, 1, 1])

In [63]: np.where(v[:,None],B,A)
Out[63]:
array([[55, 67, 50],
       [14, 97, 32],
       [72, 11, 49],
       [98, 34, 41],
       [89, 71, 52],
       [44, 77, 13],
       [56, 55, 58]])

If v doesn't strictly consist of 0s and 1s only, use v[:,None]==1 as the first argument with np.where.

Another approach would be with boolean-indexing -

C = A.copy()
mask = v==1
C[mask] = B[mask]

Note : If v is already a boolean array, skip the comparison against 1 for the mask creation.

Runtime test -

In [77]: A = np.random.randint(11,99,(10000,3))

In [78]: B = np.random.randint(11,99,(10000,3))

In [79]: v = np.random.rand(A.shape[0])>0.5

In [82]: def choose_rows_copy(A, B, v):
    ...:     C = A.copy()
    ...:     C[v] = B[v]
    ...:     return C
    ...:

In [83]: %timeit np.where(v[:,None],B,A)
10000 loops, best of 3: 107 µs per loop

In [84]: %timeit choose_rows_copy(A, B, v)
1000 loops, best of 3: 226 µs per loop


问:
Ionic2 grid columns
I'm trying to fit two items (two columns) in each row with ionic2, but it's not working.

```<code>  <ion-grid>
   <ion-row wrap>
    <ion-col width-50 *ngFor="let item of items">
        <div class="myCell">
        <div class="card">

        <div class="item item-body">
        <img class="full-image" src="...">
          <div class="item item-avatar">
            <img src="...">
          </div>
          <div style="font-size:3vw;margin:2vw">    {{item.name}}</div>
        </div>
        </div>
        </div>
      </ion-col>
   </ion-row>

I use this code but it still not working, someone knows something about this difficult topic?
</code>```

Thanks

答:
Ionic uses a grid system, similar to bootstrap, that has 12 columns.
So if you want your columns to take 50% of the width, they have to take the space of 6 columns each (since 100% is 12 columns).

Just change width-50 to col-6.

```<code><ion-col col-6 *ngFor="let item of items">
</code>```

Title: Ionic2 grid columns

Body:
I'm trying to fit two items (two columns) in each row with ionic2, but it's not working.

  <ion-grid>
   <ion-row wrap>
    <ion-col width-50 *ngFor="let item of items">

    {{item.name}}

      </ion-col>
   </ion-row>

I use this code but it still not working, someone knows something about this difficult topic?

Thanks

Body:
Ionic uses a grid system, similar to bootstrap, that has 12 columns.
So if you want your columns to take 50% of the width, they have to take the space of 6 columns each (since 100% is 12 columns).

Just change width-50 to col-6.

<ion-col col-6 *ngFor="let item of items">


问:
Wordpress Category ID vs Eval Issue
Ok this is a little complex. I am creating a plugin, and want to find the category ID from the Post page.

That's the easy part.

What makes it complex is I am doing it within an ob_start (started in a 'template_redirect' action) as I want to edit the full page before it is returned to the browser. Again that is easy enough from the ob_start function.

With the ID returned I want to evaluate some php stored in a sql field. I am trying to do this from within the ob_start function

```<code>$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);
</code>```

This calls this

```<code>function tui_cifp_evaluate_html($string) {
return preg_replace_callback("/(<\?php|<\?|< \?php)(.*?)\?>/si",'EvalBuffer', $string);
}
</code>```

Which in turn calls

```<code>function EvalBuffer($string) {
ob_start();
eval("$string[2];");
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}
</code>```

And the php I am trying to evaluate is.

```<code><?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>
</code>```

This all works outside the ob_start routine, but here even simple php doesn't work. From within the ob_start routine the plugin breaks and a blank page returns.

So I thought I could evaluate the php before the start of the ob_start and pass the result through a global variable. That works, but at the point this starts using the following, the category ID is not available.

```<code>if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) {

global $holdvalue;

$tui_cifp_insertvalue = get_option('tui_cifp_insertvalue');

$categories = get_the_category();
$categoryID = $categories[0]->cat_ID;

$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);

$holdvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

add_action('template_redirect','tui_cifp_ob_start'); //

}
</code>```

The ob_start function

```<code>function tui_cifp_ob_start()
{

ob_start('tui_cifp_templatefilter');

}
</code>```

Ok I am stumped ... any ideas?

I either need to find a hook that executes at the right time so that I have access to the category ID, or I need to work out how to evaluate the php during the ob_start.

Oh ... I guess I should say. What I want to do is replace a tag on a wordpress page with some other information saved in a string, but need to be able to do this once the full page if drawn.

Thanks
Stephen

PS I have asked this on the wordpress forums without a response. Sorry for the cross posting but I am a little desperate.

答:
Thanks OIS, I appreciate your proposing that solution. It is however doing the same thing as I have been doing. I guess structured differently.

It did however cause me to look at the problem from a different prospective.

What I realised was that get_the_category() needs a parameter and wasn't getting a category because it was the Post ID that wasn't available. I solved the problem by doing the setup up front like so.

```<code>function tui_cifp_ob_start()
{

    global $tui_cifp_message, $tui_cifp_div, $wp_query;

    if (is_single())
    {

        $tui_cifp_div = get_option('tui_cifp_div');

        if ($tui_cifp_div !== '')
        {

        $thePostID = $wp_query->post->ID;
        $categories = get_the_category($thePostID);
        $categoryID = $categories[0]->cat_ID;

        $tui_cifp_message = get_option('tui_cifp_message');

        $categoryTitle = $categories[0]->cat_name;
        $categoryDescription = $categories[0]->category_description;

        $tui_cifp_message = str_replace("[categoryID]", $categoryID, $tui_cifp_message);
        $tui_cifp_message = str_replace("[categoryTitle]", $categoryTitle, $tui_cifp_message);
        $tui_cifp_message = str_replace("[categoryDescription]", $categoryDescription, $tui_cifp_message);
        $tui_cifp_message = $tui_cifp_div.$tui_cifp_message;

        $tui_cifp_message = tui_cifp_evaluate_html($tui_cifp_message);

        }

        ob_start('tui_cifp_templatefilter');

    }

}
</code>```

Thanks again.

OwnerDisplayName: Stephen Baugh

ContentLicense: CC BY-SA 2.5

Title: Wordpress Category ID vs Eval Issue

Body:
Ok this is a little complex. I am creating a plugin, and want to find the category ID from the Post page.

That's the easy part.

What makes it complex is I am doing it within an ob_start (started in a 'template_redirect' action) as I want to edit the full page before it is returned to the browser. Again that is easy enough from the ob_start function.

With the ID returned I want to evaluate some php stored in a sql field. I am trying to do this from within the ob_start function

$tui_cifp_insertvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

This calls this

function tui_cifp_evaluate_html($string) {
return preg_replace_callback("/(<\?php|<\?|< \?php)(.*?)\?>/si",'EvalBuffer', $string);
}

Which in turn calls

function EvalBuffer($string) {
ob_start();
eval("$string[2];");
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}

And the php I am trying to evaluate is.

<?php tui_findPostThumbIMG([categoryID],100,100,'categoryintro-thumbnail','','',''); ?>

This all works outside the ob_start routine, but here even simple php doesn't work. From within the ob_start routine the plugin breaks and a blank page returns.

So I thought I could evaluate the php before the start of the ob_start and pass the result through a global variable. That works, but at the point this starts using the following, the category ID is not available.

if ( strpos($_SERVER['REQUEST_URI'], 'wp-admin') === false ) {

global $holdvalue;

$tui_cifp_insertvalue = get_option('tui_cifp_insertvalue');

$categories = get_the_category();
$categoryID = $categories[0]->cat_ID;

$tui_cifp_insertvalue = str_replace("[categoryID]", $categoryID, $tui_cifp_insertvalue);

$holdvalue = tui_cifp_evaluate_html($tui_cifp_insertvalue);

add_action('template_redirect','tui_cifp_ob_start'); //

}

The ob_start function

function tui_cifp_ob_start()
{

ob_start('tui_cifp_templatefilter');

}

Ok I am stumped ... any ideas?

I either need to find a hook that executes at the right time so that I have access to the category ID, or I need to work out how to evaluate the php during the ob_start.

Oh ... I guess I should say. What I want to do is replace a tag on a wordpress page with some other information saved in a string, but need to be able to do this once the full page if drawn.

Thanks
Stephen

PS I have asked this on the wordpress forums without a response. Sorry for the cross posting but I am a little desperate.

LastEditorDisplayName: Stephen Baugh

Body:
Thanks OIS, I appreciate your proposing that solution. It is however doing the same thing as I have been doing. I guess structured differently.

It did however cause me to look at the problem from a different prospective.

What I realised was that get_the_category() needs a parameter and wasn't getting a category because it was the Post ID that wasn't available. I solved the problem by doing the setup up front like so.

function tui_cifp_ob_start()
{

    global $tui_cifp_message, $tui_cifp_div, $wp_query;

    if (is_single())
    {

        $tui_cifp_div = get_option('tui_cifp_div');

        if ($tui_cifp_div !== '')
        {

        $thePostID = $wp_query->post->ID;
        $categories = get_the_category($thePostID);
        $categoryID = $categories[0]->cat_ID;

        $tui_cifp_message = get_option('tui_cifp_message');

        $categoryTitle = $categories[0]->cat_name;
        $categoryDescription = $categories[0]->category_description;

        $tui_cifp_message = str_replace("[categoryID]", $categoryID, $tui_cifp_message);
        $tui_cifp_message = str_replace("[categoryTitle]", $categoryTitle, $tui_cifp_message);
        $tui_cifp_message = str_replace("[categoryDescription]", $categoryDescription, $tui_cifp_message);
        $tui_cifp_message = $tui_cifp_div.$tui_cifp_message;

        $tui_cifp_message = tui_cifp_evaluate_html($tui_cifp_message);

        }

        ob_start('tui_cifp_templatefilter');

    }

}

Thanks again.


问:
MySQL full text search, why am I getting Incorrect arguments to MATCH
```<code>SELECT
*
FROM
company c
INNER JOIN
city ci ON ci.city_id = c.city_id
INNER JOIN
state s ON s.state_id = c.state_id
WHERE
MATCH (
c.name, ci.name, c.zipcode, s.name
)
AGAINST (
'los angeles'
)
</code>```

答:
I had the same problem and solved it like this:

```<code>SELECT
*
FROM
company c
INNER JOIN
city ci ON ci.city_id = c.city_id
INNER JOIN
state s ON s.state_id = c.state_id
WHERE
   MATCH (c.name) AGAINST ('los angeles')
OR MATCH (ci.name) AGAINST ('los angeles')
OR MATCH (c.zipcode) AGAINST ('los angeles')
OR MATCH (s.name) AGAINST ('los angeles')
</code>```

But as I see, You are searching in simple fields like 'name' and 'zipcode'. As for me, it would be better to use LIKE and just concatenate them

```<code>SELECT
*
FROM
company c
INNER JOIN
city ci ON ci.city_id = c.city_id
INNER JOIN
state s ON s.state_id = c.state_id
WHERE
CONCAT_WS (' ', c.name, ci.name, c.zipcode, s.name)
LIKE ('%los angeles%')
</code>```

Body:
I had the same problem and solved it like this:

SELECT
*
FROM
company c
INNER JOIN
city ci ON ci.city_id = c.city_id
INNER JOIN
state s ON s.state_id = c.state_id
WHERE
   MATCH (c.name) AGAINST ('los angeles')
OR MATCH (ci.name) AGAINST ('los angeles')
OR MATCH (c.zipcode) AGAINST ('los angeles')
OR MATCH (s.name) AGAINST ('los angeles')

But as I see, You are searching in simple fields like 'name' and 'zipcode'. As for me, it would be better to use LIKE and just concatenate them

SELECT
*
FROM
company c
INNER JOIN
city ci ON ci.city_id = c.city_id
INNER JOIN
state s ON s.state_id = c.state_id
WHERE
CONCAT_WS (' ', c.name, ci.name, c.zipcode, s.name)
LIKE ('%los angeles%')


问:
Does Windows 7 IE 11 support video streaming without plugins
I have a very specific target audience that I need to stream live video to (not prerecorded), that must run stock Internet Explorer 11 on Windows 7. This means without Flash, Silverlight or any other plugins. Is this possible? My fears are that it is not, but I thought I would ask just in case I'm missing some special feature.

To reiterate:

1 Only needs to support 1 browser, IE 11 running under Window 7

2 No browser plugins

3 JavaScript is ok

Please note that I already tried broadway, it was not performant enough.

答:
I think I found a solution!
After days of searching around, I found THEOplayer which is supposed to work in IE11 under Windows 7 without Flash, without any plugin, as stated on their HTML5 Support Matrix.

Only downside: it is not free. But pricing seems fair and if you don't aim at millions of video-read per month you should be okay.


问:
Using coverage to test python program
I'm using https://coverage.readthedocs.io/en/coverage-4.4.1/ to determine how much of a Python program I'm using.

However, when I use command line:

```<code>$coverage myprogram.py
</code>```

It runs the program in Python 2 and my program only works in Python 3.  I can't figure out how to get coverage to use Python 3. Also my command line is set up to use Python 3.

答:
I had to add the

```<code>alias pip='pip3'
</code>```

Then I had to install coverage3 and that did the trick.

Title: Using coverage to test python program

Body:
I'm using https://coverage.readthedocs.io/en/coverage-4.4.1/ to determine how much of a Python program I'm using.

However, when I use command line:

$coverage myprogram.py

It runs the program in Python 2 and my program only works in Python 3.  I can't figure out how to get coverage to use Python 3. Also my command line is set up to use Python 3.

Body:
I had to add the

alias pip='pip3'

Then I had to install coverage3 and that did the trick.


问:
Why Joda DateTimeFormatter cannot parse timezone names ('z')
From DateTimeFormatter javadoc:

Zone names: Time zone names ('z') cannot be parsed.

Therefore timezone parsing like:

```<code>System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse("Fri Nov 11 12:13:14 JST 2010"));
</code>```

cannot be done in Joda:

```<code>DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy");
System.out.println(dtf.parseDateTime("Fri Nov 11 12:13:14 JST 2010"));
//Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Fri Nov 11 12:13:14 JST 2010" is malformed at "JST 2010"
//at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)
</code>```

答:
Probably because some time zone abbreviations are ambiguous and the parser can't know which time zone is meant.

It might of course also be one of the tiny, strange ticks and missing features you find after working with Joda for a while.

Body:
From DateTimeFormatter javadoc:

Zone names: Time zone names ('z') cannot be parsed.

Therefore timezone parsing like:

System.out.println(new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse("Fri Nov 11 12:13:14 JST 2010"));

cannot be done in Joda:

DateTimeFormatter dtf = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss z yyyy");
System.out.println(dtf.parseDateTime("Fri Nov 11 12:13:14 JST 2010"));
//Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "Fri Nov 11 12:13:14 JST 2010" is malformed at "JST 2010"
//at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673)


问:
Modify a list's elements based on element index
Using Haskell:

Let's say I have list: [1,3,4,2,3]
And I want to modify all 3's in the list. I know that I can apply this to select the 3's in this case:

```<code>map (\x -> if p x then f x else x) xs
</code>```

However, the functions being applied to the threes is dependent on their index within the list.

So for example if the index was added to the desired number the output of the function I'm going for would be: [1,4,4,2,7].

答:
You can use zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] for this:

```<code><b>zipWith</b> (\<b>i</b> x -> if p x then f <b>i</b> x else x) <b>[0..]</b> xs</code>```

where f thus takes i (the index) and x (the element) both into account.

For example:

```<code>zipWith (\i x -> if x == 3 then (i+x) else x) [0..] xs
</code>```

Which generates the desired output:

```<code>Prelude> let xs = [1,3,4,2,3]
Prelude> zipWith (\i x -> if x == 3 then (i+x) else x) [0..] xs
[1,4,4,2,7]
</code>```

You can encapsulate this logic into a separate function, for instance imap :: (Enum n, Num n) => (n -> a -> b) -> [a] -> b:

```<code>imap :: (Enum n, Num n) => (n -> a -> b) -> [a] -> b
imap = flip zipWith [0..]
</code>```

This will work with any type that is an instance of Num and Enum (so Integer, Int, Float,...).

Body:
Using Haskell:

Let's say I have list: [1,3,4,2,3]
And I want to modify all 3's in the list. I know that I can apply this to select the 3's in this case:

map (\x -> if p x then f x else x) xs

However, the functions being applied to the threes is dependent on their index within the list.

So for example if the index was added to the desired number the output of the function I'm going for would be: [1,4,4,2,7].

Body:
You can use zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] for this:

zipWith (\i x -> if p x then f i x else x) [0..] xs

where f thus takes i (the index) and x (the element) both into account.

For example:

zipWith (\i x -> if x == 3 then (i+x) else x) [0..] xs

Which generates the desired output:

Prelude> let xs = [1,3,4,2,3]
Prelude> zipWith (\i x -> if x == 3 then (i+x) else x) [0..] xs
[1,4,4,2,7]

You can encapsulate this logic into a separate function, for instance imap :: (Enum n, Num n) => (n -> a -> b) -> [a] -> b:

imap :: (Enum n, Num n) => (n -> a -> b) -> [a] -> b
imap = flip zipWith [0..]

This will work with any type that is an instance of Num and Enum (so Integer, Int, Float,...).


问:
Clockwork with a multi-tenant setup
My app uses postgres schemas to implement multi-tenancy. So for a table like users, each tenant actually has it's own users table -

public.users (default)

foo.users

bar.users

...

As a side note, it implements multi-tenancy using the apartment gem

The clockwork gem allows you to read events from a database table, with the use of it's sync_database_events method. For example, it can read events from a scheduled_jobs table/model:

```<code>sync_database_events model: ScheduledJob, every: 1.minute do |model_instance|
  rake model_instance.name
end
</code>```

By default this reads from public.scheduled_jobs, but each one of my schemas will have it's own scheduled_jobs to read from.

Is there a convenient way to have it loop through all my tenants?

答:
I'm doing a very similar thing with the difference that I'm using Apartment and MySQL not Postgres.  Apartment is very, very powerful but it feels poorly documented at best.  Here was how I approached this:

```<code>if Rails.env.development?
  every(1.day, '3am.job -- Daily Job', :at => '03:00') do |job|
    User.delay.crawl
    Search.delay.crawl
  end
elsif Rails.env.production?
  every(1.day, '3am.job -- Daily Job', :at => '03:00') do |job|
    SiteApi.usernames.each do |username|
      Apartment::Tenant.switch!(username)
      User.delay.crawl
      Search.delay.crawl
    end
  end
end
</code>```

The magic happens in my Rails.env.production? block.  SiteApi is an API that talks to my master database of users and gets back an array of usernames.  It then calls Apartment::Tenant.switch!(username) to switch the tenancy context to the right user. It then calls the functions that I need to run on each tenant.

You should note that I am also making use of the Apartment Sidekiq extension for delay.

I suspect this conceptual leap is what you're looking for.

Title: Clockwork with a multi-tenant setup

Body:
My app uses postgres schemas to implement multi-tenancy. So for a table like users, each tenant actually has it's own users table -

public.users (default)

foo.users

bar.users

...

As a side note, it implements multi-tenancy using the apartment gem

The clockwork gem allows you to read events from a database table, with the use of it's sync_database_events method. For example, it can read events from a scheduled_jobs table/model:

sync_database_events model: ScheduledJob, every: 1.minute do |model_instance|
  rake model_instance.name
end

By default this reads from public.scheduled_jobs, but each one of my schemas will have it's own scheduled_jobs to read from.

Is there a convenient way to have it loop through all my tenants?

Body:
I'm doing a very similar thing with the difference that I'm using Apartment and MySQL not Postgres.  Apartment is very, very powerful but it feels poorly documented at best.  Here was how I approached this:

if Rails.env.development?
  every(1.day, '3am.job -- Daily Job', :at => '03:00') do |job|
    User.delay.crawl
    Search.delay.crawl
  end
elsif Rails.env.production?
  every(1.day, '3am.job -- Daily Job', :at => '03:00') do |job|
    SiteApi.usernames.each do |username|
      Apartment::Tenant.switch!(username)
      User.delay.crawl
      Search.delay.crawl
    end
  end
end

The magic happens in my Rails.env.production? block.  SiteApi is an API that talks to my master database of users and gets back an array of usernames.  It then calls Apartment::Tenant.switch!(username) to switch the tenancy context to the right user. It then calls the functions that I need to run on each tenant.

You should note that I am also making use of the Apartment Sidekiq extension for delay.

I suspect this conceptual leap is what you're looking for.


问:
Loss suddenly increases with Adam Optimizer in Tensorflow
I am using a CNN for a regression task. I use Tensorflow and the optimizer is Adam. The network seems to converge perfectly fine till one point where the loss suddenly increases along with the validation error. Here are the loss plots of the labels and the weights separated (Optimizer is run on the sum of them)

I use l2 loss for weight regularization and also for the labels. I apply some randomness on the training data. I am currently trying RSMProp to see if the behavior changes but it takes at least 8h to reproduce the error.

I would like to understand how this can happen. Hope you can help me.

答:
My experience over the last months is the following:
Adam is very easy to use because you don't have to play with initial learning rate very much and it almost always works. However, when coming to convergence Adam does not really sattle with a solution but jiggles around at higher iterations. While SGD gives an almost perfectly shaped loss plot and seems to converge much better in higher iterations.
But changing litte parts of the setup requires to adjust the SGD parameters or you will end up with NaNs... For experiments on architectures and general approaches I favor Adam, but if you want to get the best version of one chosen architecture you should use SGD and at least compare the solutions.

I also noticed that a good initial SGD setup (learning rate, weight decay etc.) converges as fast as using Adam, at leas for my setup.
Hope this may help some of you!

EDIT: Please note that the effects in my initial question are NOT normal even with Adam. Seems like I had a bug but I can't really remember the issue there.


问:
PySpark 1.5 & MSSQL jdbc
I am using PySpark on Spark 1.5 on Cloudera YARN, using Python 3.3 on Centos 6 Machines. The SQL Server instance is SQL Server Enterprise 64bit. The SQL Server driver is listed below; sqljdbc4.jar; and I have added to my .bashrc

```<code>export SPARK_CLASSPATH="/var/lib/spark/sqljdbc4.jar"
export PYSPARK_SUBMIT_ARGS="--conf spark.executor.extraClassPath="/var/lib/spark/sqljdbc4.jar" --driver-class-path="/var/lib/spark/sqljdbc4.jar" --jars="/var/lib/spark/sqljdbc4.jar" --master yarn --deploy-mode client"
</code>```

And I can see confirmation when I launch Spark that

```<code>SPARK_CLASSPATH was detected (set to '/var/lib/spark/sqljdbc4.jar')
</code>```

I have a dataframe that looks like this schema

```<code>root
 |-- daytetime: timestamp (nullable = true)
 |-- ip: string (nullable = true)
 |-- tech: string (nullable = true)
 |-- th: string (nullable = true)
 |-- car: string (nullable = true)
 |-- min_dayte: timestamp (nullable = true)
 |-- max_dayte: timestamp (nullable = true)
</code>```

I have created an empty table already in my MS SQL server called 'dbo.shaping', where the 3 timestamp columns will be datetime2(7) and the others nvarchar(50).

I try to export the dataframe from PySpark using this

```<code>properties = {"user": "<username>", "password": "<password>"}

df.write.format('jdbc').options(url='<IP>:1433/<dbname>', dbtable='dbo.shaping',driver="com.microsoft.sqlserver.jdbc.SQLServerDriver",properties=properties)
</code>```

I get the following traceback error

```<code>Py4JError: An error occurred while calling o250.option. Trace:
py4j.Py4JException: Method option([class java.lang.String, class java.util.HashMap]) does not exist
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:333)
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:342)
at py4j.Gateway.invoke(Gateway.java:252)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:207)
at java.lang.Thread.run(Thread.java:744)
</code>```

Are my methods at least correct, and perhaps this error is related to writing the specific type of data, ie, I have an issue with the data construct and not my code?

答:
You cannot use a dict as a value for options. options method expects only str arguments (Scala docs and PySpark annotations) and is expanded to separate calls to Java option.

In current Spark versions value is automatically converted to string, so your code would fail silently, but it isn't the case in 1.5.

Since properties are specific to JDBC driver anyway, you should use jdbc method:

```<code>properties = {
    "user": "<username>", "password": "<password>", "driver":
    "com.microsoft.sqlserver.jdbc.SQLServerDriver"}

df.write.jdbc(
    url='<IP>:1433/<dbname>',
    table='dbo.shaping',
    properties=properties)
</code>```

though unpacking properties should work as well:

```<code>.options(
    url='<IP>:1433/<dbname>',
    dbtable='dbo.shaping',
    driver="com.microsoft.sqlserver.jdbc.SQLServerDriver",
    **properties)
</code>```

In general, when you see:

```<code>py4j.Py4JException: Method ... does not exist
</code>```

it usually signalizes mismatch between local Python types, and the types expected by JVM method in use.

See also: How to use JDBC source to write and read data in (Py)Spark?

Title: PySpark 1.5 & MSSQL jdbc

Body:
I am using PySpark on Spark 1.5 on Cloudera YARN, using Python 3.3 on Centos 6 Machines. The SQL Server instance is SQL Server Enterprise 64bit. The SQL Server driver is listed below; sqljdbc4.jar; and I have added to my .bashrc

export SPARK_CLASSPATH="/var/lib/spark/sqljdbc4.jar"
export PYSPARK_SUBMIT_ARGS="--conf spark.executor.extraClassPath="/var/lib/spark/sqljdbc4.jar" --driver-class-path="/var/lib/spark/sqljdbc4.jar" --jars="/var/lib/spark/sqljdbc4.jar" --master yarn --deploy-mode client"

And I can see confirmation when I launch Spark that

SPARK_CLASSPATH was detected (set to '/var/lib/spark/sqljdbc4.jar')

I have a dataframe that looks like this schema

root
 |-- daytetime: timestamp (nullable = true)
 |-- ip: string (nullable = true)
 |-- tech: string (nullable = true)
 |-- th: string (nullable = true)
 |-- car: string (nullable = true)
 |-- min_dayte: timestamp (nullable = true)
 |-- max_dayte: timestamp (nullable = true)

I have created an empty table already in my MS SQL server called 'dbo.shaping', where the 3 timestamp columns will be datetime2(7) and the others nvarchar(50).

I try to export the dataframe from PySpark using this

properties = {"user": "<username>", "password": "<password>"}

df.write.format('jdbc').options(url='<IP>:1433/<dbname>', dbtable='dbo.shaping',driver="com.microsoft.sqlserver.jdbc.SQLServerDriver",properties=properties)

I get the following traceback error

Py4JError: An error occurred while calling o250.option. Trace:
py4j.Py4JException: Method option([class java.lang.String, class java.util.HashMap]) does not exist
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:333)
at py4j.reflection.ReflectionEngine.getMethod(ReflectionEngine.java:342)
at py4j.Gateway.invoke(Gateway.java:252)
at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:133)
at py4j.commands.CallCommand.execute(CallCommand.java:79)
at py4j.GatewayConnection.run(GatewayConnection.java:207)
at java.lang.Thread.run(Thread.java:744)

Are my methods at least correct, and perhaps this error is related to writing the specific type of data, ie, I have an issue with the data construct and not my code?

Body:
You cannot use a dict as a value for options. options method expects only str arguments (Scala docs and PySpark annotations) and is expanded to separate calls to Java option.

In current Spark versions value is automatically converted to string, so your code would fail silently, but it isn't the case in 1.5.

Since properties are specific to JDBC driver anyway, you should use jdbc method:

properties = {
    "user": "<username>", "password": "<password>", "driver":
    "com.microsoft.sqlserver.jdbc.SQLServerDriver"}

df.write.jdbc(
    url='<IP>:1433/<dbname>',
    table='dbo.shaping',
    properties=properties)

though unpacking properties should work as well:

.options(
    url='<IP>:1433/<dbname>',
    dbtable='dbo.shaping',
    driver="com.microsoft.sqlserver.jdbc.SQLServerDriver",
    **properties)

In general, when you see:

py4j.Py4JException: Method ... does not exist

it usually signalizes mismatch between local Python types, and the types expected by JVM method in use.

See also: How to use JDBC source to write and read data in (Py)Spark?


问:
ArrayOutOfBoundException while inserting elements
Getting ArrayIndexOutOfBoundException while inserting elements to a two Dimensional array..I dont know where the problem is..
I tried a lot but couldn't understand why this is giving the exception.Here is my code..Thanks in advance..

```<code>public class TruthTableAutoMateClass extends JPanel implements ActionListener
{

static int size;

private int i = 0;

static JButton btnOk = new JButton();

String[][] array= new String[size][];

private double[][] dim = { {0.50, 0.50}, {0.25, 0.20, 0.20, 0.20, TableLayout.FILL}};

public static void main(String args[])
{
    TruthTableAutoMateClass auto = new TruthTableAutoMateClass();
    checkAdding(auto);
    btnOk.addActionListener(auto);
}

private static String[] prepareArray()
{
    String[] arr = new String[2];

    if (size == 16)
    {

        String text1 = field1.getText();
        String text2 = field2.getText();
        String text3 = field3.getText();
        String text4 = field4.getText();

        String firstArray = new StringBuilder().append(text1).append("|").append(text3).append("|").append(text3).append("|").append(text4).toString();

        arr[0] = firstArray;
        arr[1] = ledValue1.getText();

    }
    else if (size == 9)
    {

    }
    else if (size == 4)
    {

    }

    return arr;
}

private static void checkAdding(TruthTableAutoMateClass auto1)
{
    TruthTableAutoMateClass auto = auto1;
    String answer = JOptionPane.showInputDialog("How many values are there 4 or 3 " + "if 4 yes else press no");

    if (answer.equalsIgnoreCase("yes"))
    {

        size = 4 * 4;
        auto.add(lbl1, "0,0");
        auto.add(lbl2, "0,1");
        auto.add(lbl3, "0,2");
        auto.add(lbl4, "0,3");

        auto.add(field1, "1,0");
        auto.add(field2, "1,1");
        auto.add(field3, "1,2");
        auto.add(field4, "1,3");

        auto.add(ledValue1, "1,4");
        /*auto.add(ledValue2);
        auto.add(ledValue3);
        auto.add(ledValue4);*/

        auto.add(btnOk, "0,4");

    }
    else
    {
        size = 3 * 3;
        String answer2 = JOptionPane.showInputDialog("Again enter yes or no" + "3 for yes , 2 for no");
        if (answer2.equalsIgnoreCase("yes"))
        {
            auto.add(lbl1, "0,0");
            auto.add(lbl2, "0,1");
            auto.add(lbl3, "0,2");
            auto.add(field1, "1,0");
            auto.add(field2, "1,1");
            auto.add(field3, "1,2");

            auto.add(ledValue1, "1,4");
            /* auto.add(ledValue2);
             auto.add(ledValue3);*/

            auto.add(btnOk, "0,4");
        }
        else
        {
            size = 2 * 2;
            auto.add(lbl1, "0,0");
            auto.add(lbl2, "0,1");

            auto.add(field1, "1,0");
            auto.add(field2, "1,1");

            auto.add(ledValue1, "1,4");
            /* auto.add(ledValue2);*/
            auto.add(btnOk, "0,4");
        }
    }
}

@Override
public void actionPerformed(ActionEvent e)
{

    array[i] = prepareArray();

    i++;

    System.out.println(Arrays.toString(array));
}}
</code>```

答:
At the main() method you are creating an instance of TruthTableAutoMateClass. When this one is creating, size = 0 (by default) and String[][] array= new String[size][]; creates an array with size 0.

So, your array had size 0 and you got an exception when you had tried to assign some value like this array[i] = prepareArray();.

Body:
Getting ArrayIndexOutOfBoundException while inserting elements to a two Dimensional array..I dont know where the problem is..
I tried a lot but couldn't understand why this is giving the exception.Here is my code..Thanks in advance..

public class TruthTableAutoMateClass extends JPanel implements ActionListener
{

static int size;

private int i = 0;

static JButton btnOk = new JButton();

String[][] array= new String[size][];

private double[][] dim = { {0.50, 0.50}, {0.25, 0.20, 0.20, 0.20, TableLayout.FILL}};

public static void main(String args[])
{
    TruthTableAutoMateClass auto = new TruthTableAutoMateClass();
    checkAdding(auto);
    btnOk.addActionListener(auto);
}

private static String[] prepareArray()
{
    String[] arr = new String[2];

    if (size == 16)
    {

        String text1 = field1.getText();
        String text2 = field2.getText();
        String text3 = field3.getText();
        String text4 = field4.getText();

        String firstArray = new StringBuilder().append(text1).append("|").append(text3).append("|").append(text3).append("|").append(text4).toString();

        arr[0] = firstArray;
        arr[1] = ledValue1.getText();

    }
    else if (size == 9)
    {

    }
    else if (size == 4)
    {

    }

    return arr;
}

private static void checkAdding(TruthTableAutoMateClass auto1)
{
    TruthTableAutoMateClass auto = auto1;
    String answer = JOptionPane.showInputDialog("How many values are there 4 or 3 " + "if 4 yes else press no");

    if (answer.equalsIgnoreCase("yes"))
    {

        size = 4 * 4;
        auto.add(lbl1, "0,0");
        auto.add(lbl2, "0,1");
        auto.add(lbl3, "0,2");
        auto.add(lbl4, "0,3");

        auto.add(field1, "1,0");
        auto.add(field2, "1,1");
        auto.add(field3, "1,2");
        auto.add(field4, "1,3");

        auto.add(ledValue1, "1,4");
        /*auto.add(ledValue2);
        auto.add(ledValue3);
        auto.add(ledValue4);*/

        auto.add(btnOk, "0,4");

    }
    else
    {
        size = 3 * 3;
        String answer2 = JOptionPane.showInputDialog("Again enter yes or no" + "3 for yes , 2 for no");
        if (answer2.equalsIgnoreCase("yes"))
        {
            auto.add(lbl1, "0,0");
            auto.add(lbl2, "0,1");
            auto.add(lbl3, "0,2");
            auto.add(field1, "1,0");
            auto.add(field2, "1,1");
            auto.add(field3, "1,2");

            auto.add(ledValue1, "1,4");
            /* auto.add(ledValue2);
             auto.add(ledValue3);*/

            auto.add(btnOk, "0,4");
        }
        else
        {
            size = 2 * 2;
            auto.add(lbl1, "0,0");
            auto.add(lbl2, "0,1");

            auto.add(field1, "1,0");
            auto.add(field2, "1,1");

            auto.add(ledValue1, "1,4");
            /* auto.add(ledValue2);*/
            auto.add(btnOk, "0,4");
        }
    }
}

@Override
public void actionPerformed(ActionEvent e)
{

    array[i] = prepareArray();

    i++;

    System.out.println(Arrays.toString(array));
}}