问:
Floating context menu on button click inside Fragment
In my app I have created few buttons in one fragment which will redirect to several activity based on the click. Now if user click button1, they will get a floating context menu conataing the list of the comapny, such as company1, compan2...etc. I have followed this post Opening a floating menu (context menu) in Android? to develop this feature in my app. But the problem is that this code is implemented in Activity, where in my case I want ti implement it in Fragment. I wrote the code but nothig happen with the button click. Now how can I generate this menu on button click

My contextmenu is

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><item android:id="@+id/company_1"
    android:title="@string/company_1"></item>

<item android:id="@+id/company_2"
android:title="@string/company_2"></item>

<item android:id="@+id/company_3"
android:title="@string/company_3"></item>

<item android:id="@+id/company_4"
    android:title="@string/company_4">
</item>
<item android:id="@+id/company_5"
    android:title="@string/company_5"></item>

<item android:id="@+id/company_6"
    android:title="@string/company_6">
</item>
</code>```

My Fragment Class is

```<code>public class MainFragment extends Fragment implements View.OnClickListener{

public MainFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_main, container, false);

    Button button1=(Button) view.findViewById(R.id.button1);
    button1.setOnClickListener(this);
    registerForContextMenu(button);
    Button button2=(Button) view.findViewById(R.id.button2);
    button2.setOnClickListener(this);
    Button button3=(Button) view.findViewById(R.id.button3);
    button3.setOnClickListener(this);

    // Inflate the layout for this fragment
    return view;

}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    if(v.getId()==R.id.button1){
        this.getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
    }
    super.onCreateContextMenu(menu, v, menuInfo);

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    setHasOptionsMenu(true);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.company_1:
            Toast.makeText(getActivity().getApplicationContext(),"caompany1code",Toast.LENGTH_LONG).show();
            return true;
        case R.id.company_2:
           ......
        case R.id.company_3:
            .....
        case R.id.company_4:
           ....
            return true;
        case R.id.company_5:
            .....
            return true;
        case R.id.company_6:
           .....
            return true;
    }
    return super.onContextItemSelected(item);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button1:

            Toast.makeText(getActivity(),"My colleagues clicked", Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Toast.makeText(getActivity(), "News clicked", Toast.LENGTH_SHORT).show();
            break;
        case R.id.button3:
            Toast.makeText(getActivity(), "Navigator clicked", Toast.LENGTH_SHORT).show();
            break;

    }

}
</code>```

In MainActivity Class

```<code>public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

NavigationView navigationView = null;
Toolbar toolbar = null;

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

    //Set the fragment initially
    MainFragment fragment = new MainFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

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

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

    navigationView.setNavigationItemSelectedListener(this);

}
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

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

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
   .....

}
</code>```

答:
Well i found something here :

Try this in your fragment :

```<code>@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1{getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
}
</code>```

You are also calling this wrong:

```<code>//Instead of button use button1.
registerForContextMenu(button1);
</code>```

Maybe this will help.

Body:
In my app I have created few buttons in one fragment which will redirect to several activity based on the click. Now if user click button1, they will get a floating context menu conataing the list of the comapny, such as company1, compan2...etc. I have followed this post Opening a floating menu (context menu) in Android? to develop this feature in my app. But the problem is that this code is implemented in Activity, where in my case I want ti implement it in Fragment. I wrote the code but nothig happen with the button click. Now how can I generate this menu on button click

My contextmenu is

<?xml version="1.0" encoding="utf-8"?>

<item android:id="@+id/company_1"
    android:title="@string/company_1"></item>

<item android:id="@+id/company_2"
android:title="@string/company_2"></item>

<item android:id="@+id/company_3"
android:title="@string/company_3"></item>

<item android:id="@+id/company_4"
    android:title="@string/company_4">
</item>
<item android:id="@+id/company_5"
    android:title="@string/company_5"></item>

<item android:id="@+id/company_6"
    android:title="@string/company_6">
</item>

My Fragment Class is

public class MainFragment extends Fragment implements View.OnClickListener{

public MainFragment() {
    // Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_main, container, false);

    Button button1=(Button) view.findViewById(R.id.button1);
    button1.setOnClickListener(this);
    registerForContextMenu(button);
    Button button2=(Button) view.findViewById(R.id.button2);
    button2.setOnClickListener(this);
    Button button3=(Button) view.findViewById(R.id.button3);
    button3.setOnClickListener(this);

    // Inflate the layout for this fragment
    return view;

}

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
    if(v.getId()==R.id.button1){
        this.getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
    }
    super.onCreateContextMenu(menu, v, menuInfo);

}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    setHasOptionsMenu(true);
}

@Override
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.company_1:
            Toast.makeText(getActivity().getApplicationContext(),"caompany1code",Toast.LENGTH_LONG).show();
            return true;
        case R.id.company_2:
           ......
        case R.id.company_3:
            .....
        case R.id.company_4:
           ....
            return true;
        case R.id.company_5:
            .....
            return true;
        case R.id.company_6:
           .....
            return true;
    }
    return super.onContextItemSelected(item);
}

@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button1:

            Toast.makeText(getActivity(),"My colleagues clicked", Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Toast.makeText(getActivity(), "News clicked", Toast.LENGTH_SHORT).show();
            break;
        case R.id.button3:
            Toast.makeText(getActivity(), "Navigator clicked", Toast.LENGTH_SHORT).show();
            break;

    }

}

In MainActivity Class

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

NavigationView navigationView = null;
Toolbar toolbar = null;

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

    //Set the fragment initially
    MainFragment fragment = new MainFragment();
    android.support.v4.app.FragmentTransaction fragmentTransaction =
            getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment);
    fragmentTransaction.commit();
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

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

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

    navigationView.setNavigationItemSelectedListener(this);

}
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

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

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
   .....

}

Body:
Well i found something here :

Try this in your fragment :

@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenu.ContextMenuInfo menuInfo) {
if(v.getId()==R.id.button1{getActivity().getMenuInflater().inflate(R.menu.contextmenu_company,menu);
}
}

You are also calling this wrong:

//Instead of button use button1.
registerForContextMenu(button1);

Maybe this will help.


来源: stackexchange

问:
Android onClose event
I want to show a "Thanks for using" message when the application close.

What is the event that handles application closing?

答: Assuming you want the dialog to display only when the app is completely closed(removed from background as well), You could just override onDestroy() method in your first activity.

ContentLicense: CC BY-SA 3.0

Title: Android onClose event


问:
Performance of memmove compared to memcpy twice?
I have seen the difference pointed in the accepted answer in What is the difference between memmove and memcpy? and it said memmove might be very slightly slower than memcpy.

We can implement an alternative for memmove by doing as follows: allocate a temporary buffer, then memcpy twice (src -> tmp, tmp -> dest). My question is: which way is faster, memmove or the alternative?

答:
std::memmove "may be very slightly slower than std::memcpy" (emphasis added) because it has to first check whether the source and target ranges overlap. Internally, that's just a couple of pointer comparisons; having done that, if there's no overlap or the target starts below the source, it calls std::memcpy; otherwise, it calls a variant of std::memcpy that copies from the end toward the beginning.

In short, there only difference is that initial comparison; once that's done, it's just like std::memcpy. No need for that extra buffer and copying everything twice.


问:
Bring implicit to scope
I have a trait

```<code>trait Tr{
    def logic: Option[() => Unit] = None
    def apply(): Unit = logic match {
         case Some(l) => l()
         case None =>
    }
}

object Tr{
    implicit def procLogic2Opt(processingLogic: () => Unit): Option[() => Unit]
= Some(processingLogic)
}
</code>```

The thing is when subclassing the trait I have to import Tr._ explicitly to bring implicits into a scope. Like this

```<code>import Tr._ //otherwise does not compile

class Trrr extends Tr{
    override def processingLogic = () => println("test")
}
</code>```

Is there a way to do it without importing explicitly? How could I redesign it?

答:
Answering the headline question, if you really really really need it, move your implicit to trait:

```<code>trait Tr{
    implicit def procLogic2Opt(...) = ...
}
</code>```

This is not always a good practice though, because it's hard to find which implicit is responsible.

A story: In my previous project we had Logging trait with implicit (kind of) T => Any which we inherited everywhere - imagine how many unexpected type conversions we had. Same goes for () => Unit as many people might inherit your trait without even knowing about your implicit and wonder why functions other than apply work when they shouldn't.

Besides implicit conversions (like your procLogic2Opt) are a bad practice as well (almost always).

Quote from here:

Do not use implicits to do automatic conversions between similar
  datatypes (for example, converting a list to a stream); these are
  better done explicitly because the types have different semantics, and
  the reader should beware of these implications.

More precisely about your case: Scala Option implicit conversion - Bad practice or missing feature?

Use implicit-classes instead:

```<code>implicit class RichSomething(something: Something){
  def toSomethingElse = ...
}

something.toSomethingElse
</code>```

As mentioned in the comments your case is even simpler

```<code>Some(() => println("aaaa"))

class Trrr extends Tr{
   override def logic = Some(() => println("test"))
}
</code>```

This will give you explicit, easily understandable and discoverable types without wondering how () => Unit became an Option[() => Unit]

Title: Bring implicit to scope

Body:
I have a trait

trait Tr{
    def logic: Option[() => Unit] = None
    def apply(): Unit = logic match {
         case Some(l) => l()
         case None =>
    }
}

object Tr{
    implicit def procLogic2Opt(processingLogic: () => Unit): Option[() => Unit]
= Some(processingLogic)
}

The thing is when subclassing the trait I have to import Tr._ explicitly to bring implicits into a scope. Like this

import Tr._ //otherwise does not compile

class Trrr extends Tr{
    override def processingLogic = () => println("test")
}

Is there a way to do it without importing explicitly? How could I redesign it?

Body:
Answering the headline question, if you really really really need it, move your implicit to trait:

trait Tr{
    implicit def procLogic2Opt(...) = ...
}

This is not always a good practice though, because it's hard to find which implicit is responsible.

A story: In my previous project we had Logging trait with implicit (kind of) T => Any which we inherited everywhere - imagine how many unexpected type conversions we had. Same goes for () => Unit as many people might inherit your trait without even knowing about your implicit and wonder why functions other than apply work when they shouldn't.

Besides implicit conversions (like your procLogic2Opt) are a bad practice as well (almost always).

Quote from here:

Do not use implicits to do automatic conversions between similar
  datatypes (for example, converting a list to a stream); these are
  better done explicitly because the types have different semantics, and
  the reader should beware of these implications.

More precisely about your case: Scala Option implicit conversion - Bad practice or missing feature?

Use implicit-classes instead:

implicit class RichSomething(something: Something){
  def toSomethingElse = ...
}

something.toSomethingElse

As mentioned in the comments your case is even simpler

Some(() => println("aaaa"))

class Trrr extends Tr{
   override def logic = Some(() => println("test"))
}

This will give you explicit, easily understandable and discoverable types without wondering how () => Unit became an Option[() => Unit]


问:
Why don't Scala Lists have an Ordering?
Is there a reason why there is no implicit Ordering for Lists in Scala?

```<code>val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]
</code>```

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

答:
Incidentally even before I fixed this you could do this other ways:

```<code>scala> List[Iterable[Int]](List(2, 3, 1), List(2, 1, 3)).sorted
res0: List[Iterable[Int]] = List(List(2, 1, 3), List(2, 3, 1))

scala> List(List(2, 3, 1), List(2, 1, 3)).sorted(Ordering[Iterable[Int]])
res1: List[List[Int]] = List(List(2, 1, 3), List(2, 3, 1))
</code>```

But now it works like you'd hope.

Edit: due to sketchy divergence issues with the requisite implicit I moved it out of the default scope.  Having an implicit conversion which acts across a bound like this:

```<code>implicit def SeqDerived[CC[X] <: collection.Seq[X], T](implicit ord: Ordering[T]): Ordering[CC[T]]
</code>```

...is a potential recipe for issues.  It'll be available in 2.9, but you have to import it as follows.

```<code>scala> val lists = List(List(2, 3, 1), List(2, 1, 3))
lists: List[List[Int]] = List(List(2, 3, 1), List(2, 1, 3))

scala> lists.sorted
<console>:9: error: could not find implicit value for parameter ord: Ordering[List[Int]]
       lists.sorted
             ^

scala> import Ordering.Implicits._
import Ordering.Implicits._

scala> lists.sorted
res1: List[List[Int]] = List(List(2, 1, 3), List(2, 3, 1))
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why don't Scala Lists have an Ordering?

Body:
Is there a reason why there is no implicit Ordering for Lists in Scala?

val lists = List(List(2, 3, 1), List(2, 1, 3))
lists.sorted

error: could not find implicit value for parameter ord: Ordering[List[Int]]

EDIT

Yes, my question is why there is no built-in Ordering that's already implicitly in scope. To me, it seems obvious that the second list should be "less than" the first list since the items at 0 are equal and the second list has the lower item at 1. I was wondering if maybe it's that there's no good answer when the Lists are two different sizes.

Body:
Incidentally even before I fixed this you could do this other ways:

scala> List[Iterable[Int]](List(2, 3, 1), List(2, 1, 3)).sorted
res0: List[Iterable[Int]] = List(List(2, 1, 3), List(2, 3, 1))

scala> List(List(2, 3, 1), List(2, 1, 3)).sorted(Ordering[Iterable[Int]])
res1: List[List[Int]] = List(List(2, 1, 3), List(2, 3, 1))

But now it works like you'd hope.

Edit: due to sketchy divergence issues with the requisite implicit I moved it out of the default scope.  Having an implicit conversion which acts across a bound like this:

implicit def SeqDerived[CC[X] <: collection.Seq[X], T](implicit ord: Ordering[T]): Ordering[CC[T]]

...is a potential recipe for issues.  It'll be available in 2.9, but you have to import it as follows.

scala> val lists = List(List(2, 3, 1), List(2, 1, 3))
lists: List[List[Int]] = List(List(2, 3, 1), List(2, 1, 3))

scala> lists.sorted
<console>:9: error: could not find implicit value for parameter ord: Ordering[List[Int]]
       lists.sorted
             ^

scala> import Ordering.Implicits._
import Ordering.Implicits._

scala> lists.sorted
res1: List[List[Int]] = List(List(2, 1, 3), List(2, 3, 1))


问:
How to do an array in a cURL POST request from the command line
I am trying to send a POST request given the following requirements.

Guidelines

The content type for the submission should be application/json

The following is the structure of the body:

Name: String

PhoneNumber: String

Email: String

Position: String

Urls: Array of objects containing the following properties

Type: String

Link: String

All fields are required.
At least one URL with the "Resume" type is required

If your submission was successful, you will receive a HTTP 202 response

I believe my syntax is correct for sending the data in JSON.

I am having trouble with correctly coding the array.

My code so far:

```<code>curl -g -i -H "Accept: application/json" -H "Content-Type:
     application/json" -X POST -d '{"Name":"data",
     "PhoneNumber":"data", "Email":"data@gmail.com",
     "Position":"data", "Url[]=GitHub",
     "Url[]=github.com/data", "Url[]=Resume",
     "Url[]=linkedin.com/in/data"}'
     https://example
</code>```

Here are the errors I am receiving:

```<code>curl: (3) Port number out of range
curl: (6) Could not resolve host: gmail.com
curl: (3) Illegal port number
curl: (6) Could not resolve host: url[]=Github,
curl: (6) Could not resolve host: url[]=github.com
curl: (6) Could not resolve host: url[]=Resume,
curl: (6) Could not resolve host: url[]=linkedin.com
</code>```

Any help will be appreciated and please let me know if you need any more information.

答:
You are better off putting the data in a file and calling it (e.g. data.json, calling that with -d @data.json).

Otherwise you need to escape your double quotes that are inside.

Body:
I am trying to send a POST request given the following requirements.

Guidelines

The content type for the submission should be application/json

The following is the structure of the body:

Name: String

PhoneNumber: String

Email: String

Position: String

Urls: Array of objects containing the following properties

Type: String

Link: String

All fields are required.
At least one URL with the "Resume" type is required

If your submission was successful, you will receive a HTTP 202 response

I believe my syntax is correct for sending the data in JSON.

I am having trouble with correctly coding the array.

My code so far:

curl -g -i -H "Accept: application/json" -H "Content-Type:
     application/json" -X POST -d '{"Name":"data",
     "PhoneNumber":"data", "Email":"data@gmail.com",
     "Position":"data", "Url[]=GitHub",
     "Url[]=github.com/data", "Url[]=Resume",
     "Url[]=linkedin.com/in/data"}'
     https://example

Here are the errors I am receiving:

curl: (3) Port number out of range
curl: (6) Could not resolve host: gmail.com
curl: (3) Illegal port number
curl: (6) Could not resolve host: url[]=Github,
curl: (6) Could not resolve host: url[]=github.com
curl: (6) Could not resolve host: url[]=Resume,
curl: (6) Could not resolve host: url[]=linkedin.com

Any help will be appreciated and please let me know if you need any more information.


问:
How do I use some inputted text in a html form to query a SQLite database?
How do I use some inputted text in a html form to query a SQLite database?

Forgive me, I am very new to Ruby on Rails (couple of days).

I am getting a user to enter a number followed by enter, I then want to query my SQLite db and return results to a variable. I am working in a Ruby on Rails project. Here is the code in my home.html.erb file.

```<code><form name="myform" action="" method="get">

  <input type="text" name="CardNumber" onkeypress="if(event.keyCode==13) {javascript:form.submit();>
    <input type="submit" onClick="javascript:form.submit();"/>
  <br>
</form>

<br>
<br>

<script type="text/javascript" language="JavaScript">
document.forms['myform'].elements['CardNumber'].focus();
</script>
</code>```

答:
First I think you'll want to do a post instead of a get. Then you need to point action to the correct route.

Usually in rails you'll have a model object instantiated on the action that renders the view with the form. Like if it's a form for creating a new User, on the controller#new action you'll have something like:

```<code>def new
  @user = User.new
end
</code>```

then on the view you'll have <%= form_for(@user) ... %>
Since you instantiated @user, form_for will be able to render correctly the path and action when you give it that object as a parameter. It won't be able to figure out if it's a multipart or whatever else, but the basis of routing it will.

But you don't need it obviously. Going back to your sample.
Imagine you have a route

post "save_payment_info", to: "payments#save_cc", as: :cc_save

Then a controller:

```<code>payments_controller.rb

def save_cc
   cc_number_from_form = params[:CardNumber]
end
</code>```

So you'll be able to access your form fields (as long as they're named correctly) on the params hash inside the controller.

You can do the same with Ajax and return a JSON response, etc.

Body:
How do I use some inputted text in a html form to query a SQLite database?

Forgive me, I am very new to Ruby on Rails (couple of days).

I am getting a user to enter a number followed by enter, I then want to query my SQLite db and return results to a variable. I am working in a Ruby on Rails project. Here is the code in my home.html.erb file.

<form name="myform" action="" method="get">

  <input type="text" name="CardNumber" onkeypress="if(event.keyCode==13) {javascript:form.submit();>
    <input type="submit" onClick="javascript:form.submit();"/>

</form>

Body:
First I think you'll want to do a post instead of a get. Then you need to point action to the correct route.

Usually in rails you'll have a model object instantiated on the action that renders the view with the form. Like if it's a form for creating a new User, on the controller#new action you'll have something like:

def new
  @user = User.new
end

then on the view you'll have <%= form_for(@user) ... %>
Since you instantiated @user, form_for will be able to render correctly the path and action when you give it that object as a parameter. It won't be able to figure out if it's a multipart or whatever else, but the basis of routing it will.

But you don't need it obviously. Going back to your sample.
Imagine you have a route

post "save_payment_info", to: "payments#save_cc", as: :cc_save

Then a controller:

payments_controller.rb

def save_cc
   cc_number_from_form = params[:CardNumber]
end

So you'll be able to access your form fields (as long as they're named correctly) on the params hash inside the controller.

You can do the same with Ajax and return a JSON response, etc.


问:
“ORA-12154: TNS: could not resolve the connect identifier specified”
I know this questions with title like these are common, but I couldnt find solution on these and my question is bit different.

I'm trying to use login authenification via database via VPN. Oracle SQL Developer can connect perfectly using TNS, but c# app cant and I am getting this error (cant check if this is right error number right now, but problem is still same, I will check it tomorrow). I cant share login data from job, so any ideas what can be wrong are welcome.

Edit: I forgot to mention, I have seen just the bit of implementation, but we were trying to try connection via odbc and it didnt work either, just oracle sql developer was able to connect

答: Problem was in tsnnames.ora, some magic characters appeared somewhere</p>


问:
TestNG IReporter , how to call generateReport method.
From one of the example(s) I found a method generateReport(List xml, List suites, String outdir).
From where can i call this method/how to get the parameter values to call this method.</p>

答:
I have a custom listener class file: "Run_Listen.java" present within a package named "com.qa.api.utils". Place the following snippet in maven.</p>

```<code><properties>
    <property>
        <name>listener</name>`
            <value>com.qa.api.utils.Run_Listen</value>`
    </property>
</properties>
</code>```

Body:
I have a custom listener class file: "Run_Listen.java" present within a package named "com.qa.api.utils". Place the following snippet in maven.

<properties>
    <property>
        <name>listener</name>`
            <value>com.qa.api.utils.Run_Listen</value>`
    </property>
</properties>


问:
import js not found in Glitch
I use Glitch to write a WebVR prject. If I set the script direct in views/index.html, it works well. But if I save the script in js/openclosedrawer.js and import it in index.html. This .js file would not found.
The project ist here:
https://glitch.com/edit/#!/skill-lab
Does somebody know the reason?
Thanks in advance.</p>

```<code><script src="../js/openclosedrawer.js"></script>
<script>
  /**
  AFRAME.registerComponent('openclosedrawer',{

    schema: {
      open : {default: '1.8 0 0.1'},
      close : {default: '0 0 0.1'},
      dur : {default: 300},
      closed : {default: "true"}
    },

    init: function (){
      var data= this.data;
      var el=this.el;
      var closed=true;

      var move=document.createElement("a-animation");
      move.setAttribute("begin","click");
      move.setAttribute("attribute", "position");
      move.setAttribute("from", data.close)
      move.setAttribute("to", data.open);
      move.setAttribute("dur", data.dur);
      move.setAttribute("direction", "alternate");

      el.appendChild(move);

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

答:
In Your server.js, You only expose the 'public' folder

```<code>// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));
</code>```

When You change Your component path to public/js/openclosedrawer.js, it works fine. My remix here.

Title: import js not found in Glitch

Body:
In Your server.js, You only expose the 'public' folder

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

When You change Your component path to public/js/openclosedrawer.js, it works fine. My remix here.


问:
Running script even with no page loaded
Please understand that the following question is more of an academic one as I am trying to understand the logic behind the issue I am going to describe.

Many times I've seen websites (especially about upcoming movie films) that have a countdown timer. This tells the page visitor about the film's date release in theaters.

My question is how do they code this in order to run even when no one has visited the page? For example JavaScript code works only when the page is loaded. This would make a countdown timer to reset every time. I am really confused how people visit these websites and the countdown timer is already working.

I just need the logic and not some specific coding. Thank you all in advance.

答:
Here I've made a simple countdown timer, you may take a look and see that there's nothing special, you just need to know the end date and set it. All the rest it is just matter of math ;].

function countDown (endDate) {
  var dateEnd = new Date(endDate); // set future date
  var curDate = new Date(); // set current date
  var diff = dateEnd.getTime() - curDate.getTime(); // get the difference
  var leftSecs = diff/1000;
  var oneMinSecs = 60;
  var oneHourSecs = 60 * oneMinSecs;
  var oneDaySecs = oneHourSecs * 24;

  var estDays = Math.floor(leftSecs/oneDaySecs);
  var estHours = Math.floor((leftSecs - (estDays*oneDaySecs))/oneHourSecs);
  var estMins = Math.floor((leftSecs - ((estDays*oneDaySecs)+(estHours*oneHourSecs)))/60);
  var estSecs = Math.floor(leftSecs - ((estDays*oneDaySecs)+(estHours*oneHourSecs)+(estMins*oneMinSecs)));

  return [estDays, estHours, estMins, estSecs];
}

var timerEl = document.getElementById('timer');

setInterval(function() {
  var est = countDown('07-15-2017');
  timerEl.innerHTML = 'days: ' + est[0]
  + ' hours: ' + est[1]
  + ' mins: ' + est[2]
  + ' sec: ' + est[3] + ' left to 07-15-2017';
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="timer"></div></code>```

Title: Running script even with no page loaded

Body:
Here I've made a simple countdown timer, you may take a look and see that there's nothing special, you just need to know the end date and set it. All the rest it is just matter of math ;].

function countDown (endDate) {
  var dateEnd = new Date(endDate); // set future date
  var curDate = new Date(); // set current date
  var diff = dateEnd.getTime() - curDate.getTime(); // get the difference
  var leftSecs = diff/1000;
  var oneMinSecs = 60;
  var oneHourSecs = 60 * oneMinSecs;
  var oneDaySecs = oneHourSecs * 24;

  var estDays = Math.floor(leftSecs/oneDaySecs);
  var estHours = Math.floor((leftSecs - (estDays*oneDaySecs))/oneHourSecs);
  var estMins = Math.floor((leftSecs - ((estDays*oneDaySecs)+(estHours*oneHourSecs)))/60);
  var estSecs = Math.floor(leftSecs - ((estDays*oneDaySecs)+(estHours*oneHourSecs)+(estMins*oneMinSecs)));

  return [estDays, estHours, estMins, estSecs];
}

var timerEl = document.getElementById('timer');

setInterval(function() {
  var est = countDown('07-15-2017');
  timerEl.innerHTML = 'days: ' + est[0]
  + ' hours: ' + est[1]
  + ' mins: ' + est[2]
  + ' sec: ' + est[3] + ' left to 07-15-2017';
}, 1000);

<div id="timer"></div>


问:
Python - Collapse Groups of strings
I have a list of strings, e.g. ['Apple', 'Appl','Elephnt', 'Elephant']. I need collapse this list of strings into distinct groups i.e. ['Apple', 'Elephnt'].

My criteria for strings that should be in the same group is based on a percentage match of above 80%. i.e. Apple and Appl share an 88% match, and Elephnt and Elephant share a 93% match.

```<code>def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()
</code>```

The function similar is used to calculate the percentage match of two strings.
How do I compute this collapse grouping using the above function?

答:
If you wish to partition your initial list of strings (names) into a list of groups, each of similar strings:

```<code>from difflib import SequenceMatcher
from functools import partial

def is_similar(a, b):
    return SequenceMatcher(None, a, b).ratio() > 0.8

def similar_groups(names):
    remaining = set(names)
    groups = []
    while remaining:
        ref = remaining.pop()
        group = [ref] + filter(partial(is_similar, ref), remaining)
        groups.append(group)
        remaining -= set(group)
    return groups
</code>```

For example:

```<code>>>> similar_groups(['Apple', 'Appl','Elephnt', 'Elephant'])
[['Elephant', 'Elephnt'], ['Appl', 'Apple']]
</code>```

Title: Python - Collapse Groups of strings

Body:
I have a list of strings, e.g. ['Apple', 'Appl','Elephnt', 'Elephant']. I need collapse this list of strings into distinct groups i.e. ['Apple', 'Elephnt'].

My criteria for strings that should be in the same group is based on a percentage match of above 80%. i.e. Apple and Appl share an 88% match, and Elephnt and Elephant share a 93% match.

def similar(a, b):
    return SequenceMatcher(None, a, b).ratio()

The function similar is used to calculate the percentage match of two strings.
How do I compute this collapse grouping using the above function?

Body:
If you wish to partition your initial list of strings (names) into a list of groups, each of similar strings:

from difflib import SequenceMatcher
from functools import partial

def is_similar(a, b):
    return SequenceMatcher(None, a, b).ratio() > 0.8

def similar_groups(names):
    remaining = set(names)
    groups = []
    while remaining:
        ref = remaining.pop()
        group = [ref] + filter(partial(is_similar, ref), remaining)
        groups.append(group)
        remaining -= set(group)
    return groups

For example:

>>> similar_groups(['Apple', 'Appl','Elephnt', 'Elephant'])
[['Elephant', 'Elephnt'], ['Appl', 'Apple']]


问:
Service posting null values to the MySQL database
I am trying to post a JSON object to my service, deserialize it and save it to the database. It works - kind of. The problem is that some fields of the JSON get saved to the database, while others are null.

For example, when posting this JSON:

```<code>{
"FirstName": "Michael",
"LastName": "Ledley",
"BirthPlace": "Austria",
"Gender": "M",
"OIB": "12348879991",
"CurrentPlace": "New Guinea",
"Department": "D_21570"
}
</code>```

... in the database only CurrentPlace, Gender and Department are stored correctly, while all the other values (FirstName, LastName, BirthPlace, ...) are NULL. The type for all of them is VARCHAR(45), the same as for the CurrentPlace which is stored properly.

The code that executes the saving looks like this:

```<code>[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{

    readonly EmployeePersistence persistence;

    public EmployeeApiController()
    {
        persistence = new EmployeePersistence();
    }

    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

    public long SaveEmployee(Employee employee)
    {
        string sqlString =
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES (@FirstName, @LastName, @BirthPlace, @CurrentPlace, @Gender, @Department, @OIB)";

        MySqlCommand cmd = new MySqlCommand(sqlString, conn);

        cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
        cmd.Parameters.AddWithValue("@LastName", employee.LastName);
        cmd.Parameters.AddWithValue("@BirthPlace", employee.BirthPlace);
        cmd.Parameters.AddWithValue("@CurrentPlace", employee.CurrentPlace);
        cmd.Parameters.AddWithValue("@Gender", employee.Gender == EmployeeGender.M ? 1 : 0);
        cmd.Parameters.AddWithValue("@Department", employee.Department.GetStringValue());
        cmd.Parameters.AddWithValue("@OIB", employee.OIB);

        ExecuteSqlCommand(cmd);
        return cmd.LastInsertedId;
    }

    void ExecuteSqlCommand(MySqlCommand cmd)
    {
        try
        {
            // execute the SQL command
            cmd.ExecuteNonQuery();
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                              cmd, e.Message));
        }
    }
</code>```

Why are some values NULL and some not when saved in the database?

答:
You may find it helpful to populate your Parameter objects more completely.

Instead of ...

```<code> MySqlCommand cmd = new MySqlCommand(sqlString, conn);
 cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
  ...
</code>```

Try this.

```<code> MySqlCommand cmd = new MySqlCommand(sqlString, conn);
 cmd.Parameters.Add("@CategoryName", SqlDbType.VarChar, 45).Value = employee.FirstName;
  ...
</code>```

The point is to declare the parameters' data types and lengths explicitly.

Body:
I am trying to post a JSON object to my service, deserialize it and save it to the database. It works - kind of. The problem is that some fields of the JSON get saved to the database, while others are null.

For example, when posting this JSON:

{
"FirstName": "Michael",
"LastName": "Ledley",
"BirthPlace": "Austria",
"Gender": "M",
"OIB": "12348879991",
"CurrentPlace": "New Guinea",
"Department": "D_21570"
}

... in the database only CurrentPlace, Gender and Department are stored correctly, while all the other values (FirstName, LastName, BirthPlace, ...) are NULL. The type for all of them is VARCHAR(45), the same as for the CurrentPlace which is stored properly.

The code that executes the saving looks like this:

[RoutePrefix("api/employee")]
public class EmployeeApiController : ApiController
{

    readonly EmployeePersistence persistence;

    public EmployeeApiController()
    {
        persistence = new EmployeePersistence();
    }

    [HttpPost]
    [Route("")]
    public void Post([FromBody] Employee employee)
    {
        // saving id for the debugging purposes
        long id = persistence.SaveEmployee(employee);
    }

    public long SaveEmployee(Employee employee)
    {
        string sqlString =
            "INSERT INTO Employee (FirstName, LastName, BirthPlace, CurrentPlace, Gender, Department, OIB) " +
            "VALUES (@FirstName, @LastName, @BirthPlace, @CurrentPlace, @Gender, @Department, @OIB)";

        MySqlCommand cmd = new MySqlCommand(sqlString, conn);

        cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
        cmd.Parameters.AddWithValue("@LastName", employee.LastName);
        cmd.Parameters.AddWithValue("@BirthPlace", employee.BirthPlace);
        cmd.Parameters.AddWithValue("@CurrentPlace", employee.CurrentPlace);
        cmd.Parameters.AddWithValue("@Gender", employee.Gender == EmployeeGender.M ? 1 : 0);
        cmd.Parameters.AddWithValue("@Department", employee.Department.GetStringValue());
        cmd.Parameters.AddWithValue("@OIB", employee.OIB);

        ExecuteSqlCommand(cmd);
        return cmd.LastInsertedId;
    }

    void ExecuteSqlCommand(MySqlCommand cmd)
    {
        try
        {
            // execute the SQL command
            cmd.ExecuteNonQuery();
        }
        catch (MySqlException e)
        {
            // log the error
            throw new Exception(
                String.Format("Error executing the command '{0}'. The error is '{1}'.",
                              cmd, e.Message));
        }
    }

Why are some values NULL and some not when saved in the database?

Body:
You may find it helpful to populate your Parameter objects more completely.

Instead of ...

 MySqlCommand cmd = new MySqlCommand(sqlString, conn);
 cmd.Parameters.AddWithValue("@FirstName", employee.FirstName);
  ...

Try this.

 MySqlCommand cmd = new MySqlCommand(sqlString, conn);
 cmd.Parameters.Add("@CategoryName", SqlDbType.VarChar, 45).Value = employee.FirstName;
  ...

The point is to declare the parameters' data types and lengths explicitly.


问:
How to add class to all rows
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

```<code>$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});
</code>```

Demo Here (Fiddle)

答:
You need to check the clicked checkbox is  selectAll or not like this $(this).attr('id')=='selectAll'

$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {

       if($(this).attr('id')=='selectAll'){

           if($(this).is(":checked")){

               $('table').find('tr').addClass("warning");

             $('table').find("input[type='checkbox']").prop('checked',true);

            }else{

             $('table').find('tr').removeClass("warning");

            $('table').find("input[type='checkbox']").prop('checked',false);

            }
       }else{

             if ($(this).is(":checked")) {

                $(this).closest('tr').addClass("warning");

             } else {

              $(this).closest('tr').removeClass("warning");

             }

             if($("input[type=checkbox]:checked").not('#selectAll').length==0){

                $('#selectAll').prop('checked',false);

}else if($("input[type='checkbox']:checked").not('#selectAll').length==$("input[type='checkbox']").not('#selectAll').length){

         $('#selectAll').prop('checked',true);
       }

       }

    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-striped table-hover table-condensed">
    <tr>
        <th><input type="checkbox" id="selectAll"/></th>
        <th>Title</th>
        <th>Title</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
</table></code>```

Title: How to add class to all rows

Body:
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});

Demo Here (Fiddle)

Body:
You need to check the clicked checkbox is  selectAll or not like this $(this).attr('id')=='selectAll'

$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {

       if($(this).attr('id')=='selectAll'){

           if($(this).is(":checked")){

               $('table').find('tr').addClass("warning");

             $('table').find("input[type='checkbox']").prop('checked',true);

            }else{

             $('table').find('tr').removeClass("warning");

            $('table').find("input[type='checkbox']").prop('checked',false);

            }
       }else{

             if ($(this).is(":checked")) {

                $(this).closest('tr').addClass("warning");

             } else {

              $(this).closest('tr').removeClass("warning");

             }

             if($("input[type=checkbox]:checked").not('#selectAll').length==0){

                $('#selectAll').prop('checked',false);

}else if($("input[type='checkbox']:checked").not('#selectAll').length==$("input[type='checkbox']").not('#selectAll').length){

         $('#selectAll').prop('checked',true);
       }

       }

    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-striped table-hover table-condensed">
    <tr>
        <th><input type="checkbox" id="selectAll"/></th>
        <th>Title</th>
        <th>Title</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
</table>


问:
Copying a struct member into a new struct
I have a structure outlined below:

```<code>typedef struct {
    /* Device */
    UART_DEV uartDev;
    /* gpio */
    uint32_t gpiopio;
} DEVICE;
</code>```

In main.c I declare a new uart device and pass it to a function called configure();

```<code>/* main.c */

static UART_DEV newUartDev;
configure(newUartDev);
</code>```

configure() is located in test.c and inside the configure function I want to create a copy of the uart device and store it in global memory.

```<code>/* Test.c */

UART_DEV globalUartDev;
DEVICE globalDevice;

static int configure(UART_DEV newUartDev) {
    /* Create a global copy of spi device */
    globalUartDev = newUartDev;
    DEVICE.uartDev = globalUartDev;

}
</code>```

Then I call another function in main.c setTest. setTest is located in test.c. I do not pass it the uart device declared in main.c instead I want to just use the global struct I created previously. setTest calls open in dev.c

```<code>/* test.c */

setTest() {
    open(&globalDevice);
}
</code>```

and finally I will use the uart device in open.

```<code>/* dev.c */
int  open(DEVICE *dev) {
read(dev->uartDev)
}
</code>```

Is this the correct way to create a copy and pass it around files?

答:
```<code>DEVICE.uartDev = globalUartDev;
</code>```

DEVICE is not an object, it is a structure.globalDevice is an object.So it should be

```<code>globalDevice.uartDev = globalUartDev;
</code>```

Body:
I have a structure outlined below:

typedef struct {
    /* Device */
    UART_DEV uartDev;
    /* gpio */
    uint32_t gpiopio;
} DEVICE;

In main.c I declare a new uart device and pass it to a function called configure();

/* main.c */

static UART_DEV newUartDev;
configure(newUartDev);

configure() is located in test.c and inside the configure function I want to create a copy of the uart device and store it in global memory.

/* Test.c */

UART_DEV globalUartDev;
DEVICE globalDevice;

static int configure(UART_DEV newUartDev) {
    /* Create a global copy of spi device */
    globalUartDev = newUartDev;
    DEVICE.uartDev = globalUartDev;

}

Then I call another function in main.c setTest. setTest is located in test.c. I do not pass it the uart device declared in main.c instead I want to just use the global struct I created previously. setTest calls open in dev.c

/* test.c */

setTest() {
    open(&globalDevice);
}

and finally I will use the uart device in open.

/* dev.c */
int  open(DEVICE *dev) {
read(dev->uartDev)
}

Is this the correct way to create a copy and pass it around files?

Body:
DEVICE.uartDev = globalUartDev;

DEVICE is not an object, it is a structure.globalDevice is an object.So it should be

globalDevice.uartDev = globalUartDev;


问:
Laravel 5.4 Redirect not working
There is no problem adding data to the database but after adding the data to the database, redirect is not working. It keeps me on the "saving" page

Here is my controller;

```<code>public function postSave(Request $gamedata)
{
    $postcheck = Validator:: make($gamedata -> all(), array(

        'game_name' => 'required|min:3',
        'game_year' => 'numeric',
        'game_type' => 'required',
    ));
   if ($postcheck-> fails()) {
       return redirect() -> to('/')->withErrors($postcheck)->withInput();
   } else {

       $game_name = $gamedata -> input('game_name');
       $game_year = $gamedata -> input('game_year');
       $game_type = $gamedata -> input('game_type');

       $saving= games::create(array('name' =>$game_name , 'year' =>$game_year , 'type' =>$game_type));
   }
if ($saving){
    redirect() -> route('index') ;
}
return null;
}
</code>```

my form;

```<code><div class="col-md-6">
    <form action="{{url('/saving')}}" method="post">
        {{csrf_field()}}
        <div class="form-group">
            <label for="game_name">Game Name</label>
            <input type="text" class="form-control" name="game_name" placeholder="Game Name">
        </div>
        <div class="form-group">
            <label for="exampleInputPassword1">Release Date</label>
            <input type="number" class="form-control" name="game_year" placeholder="Release Date">
        </div>
        <div class="form-group">
            <label for="Game_Type">Game Type</label>
            <input type="text" class="form-control" name="game_type" placeholder="Game type">
        </div>
        <button type="submit" class="btn btn-default" name="gameinfo_save">Add a new game</button>

    </form>
</div>
</code>```

and routes;

```<code>    Route::get('/', array ('as' => 'index', 'uses' =>'homecontroller@getIndex'));
    Route::post('/saving', array ('as' => 'saving', 'uses' =>'homecontroller@postSave'));
</code>```

This not a project, I'm just trying to learn.. So where do i mistake ?

答:
used this for redirect in laravel and your view name is must be index.blade.php

```<code>return redirect('index');
</code>```

and also you can redirect like this

```<code>return redirect()->route('index');
</code>```

Title: Laravel 5.4 Redirect not working

Body:
There is no problem adding data to the database but after adding the data to the database, redirect is not working. It keeps me on the "saving" page

Here is my controller;

public function postSave(Request $gamedata)
{
    $postcheck = Validator:: make($gamedata -> all(), array(

        'game_name' => 'required|min:3',
        'game_year' => 'numeric',
        'game_type' => 'required',
    ));
   if ($postcheck-> fails()) {
       return redirect() -> to('/')->withErrors($postcheck)->withInput();
   } else {

       $game_name = $gamedata -> input('game_name');
       $game_year = $gamedata -> input('game_year');
       $game_type = $gamedata -> input('game_type');

       $saving= games::create(array('name' =>$game_name , 'year' =>$game_year , 'type' =>$game_type));
   }
if ($saving){
    redirect() -> route('index') ;
}
return null;
}

my form;

    <form action="{{url('/saving')}}" method="post">
        {{csrf_field()}}

            Game Name
            <input type="text" class="form-control" name="game_name" placeholder="Game Name">

            Release Date
            <input type="number" class="form-control" name="game_year" placeholder="Release Date">

            Game Type
            <input type="text" class="form-control" name="game_type" placeholder="Game type">

        <button type="submit" class="btn btn-default" name="gameinfo_save">Add a new game</button>

    </form>

and routes;

    Route::get('/', array ('as' => 'index', 'uses' =>'homecontroller@getIndex'));
    Route::post('/saving', array ('as' => 'saving', 'uses' =>'homecontroller@postSave'));

This not a project, I'm just trying to learn.. So where do i mistake ?

Body:
used this for redirect in laravel and your view name is must be index.blade.php

return redirect('index');

and also you can redirect like this

return redirect()->route('index');


问:
Flexbox - align items left and centered

JS Fiddle

body {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
}

* {
  box-sizing: border-box;
}

h1 {
  font-size: 20px;
  text-align: center;
}

span {
  font-size: 14px;
  text-align: left;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.box7,
.box8 {
  flex-basis: 100%;
  width: 100%;
  justify-content: center;
}

.box {
  height: 50px;
  width: calc(100% - 20px);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2em;
  flex: 1;
}

input {
  background-color: #f9a558;
  border: 1px solid #fff;
  height: 25px;
  width: 100%;
  flex: 1;
}

.company,
.comments {
  display: flex;
  margin: 5px 5px;
  flex-grow: 3;
  width 100%;
}

.company {
  margin-bottom: 3%;
}

@media (min-width: 426px) {
  .container {
    flex-direction: row;
    flex-wrap: wrap;
    align-self: flex-start;
  }
  .box {
    flex-basis: 45%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1"><span>First Name
    <input type="text"></span></div>
  <div class="box box2"><span>Last Name
    <input type="text"></span></div>
  <div class="box box3"><span>Email
    <input type="text"></span></div>
  <div class="box box4"><span>Phone
    <input type="text"></span></div>
  <div class="box box1"><span>City
    <input type="text"></span></div>
  <div class="box box2"><span>State/Province
    <input type="text"></span></div>
</div>

<div class="container">
  <div class=" company"><span>Company
    <input class="company" type="text"></span></div>
</div>

<div class="container">
  <div class="comments"><span>Comments
    <input class="comments" type="text"></span></div>
</div></code>```

I am attempting to center the boxes within my form as demonstrated in the attached picture. How can I get the form boxes to align left and appear side by?  As you can see in my jsfiddle, the from boxes are centered, however they do not align correctly nor do they appear side by side.

答:
Try below CSS I think this is for helpfull:

See Fiddle Demo

body {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
}

* {
  box-sizing: border-box;
}

h1 {
  font-size: 20px;
  text-align: center;
}

span {
  font-size: 14px;
  text-align: left;
  float: left;
  width: 100%;
}

input[type="text"] {
  float: left;
  width: 98%;
  padding: 10px;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.box7,
.box8 {
  flex-basis: 100%;
  width: 100%;
  justify-content: center;
}

.box {
  height: 50px;
  /* width: calc(100% - 20px); */
  /* display: flex; */
  /* justify-content: center; */
  /* align-items: center; */
  /* font-size: 1.2em; */
  /* flex: 1; */
  float: left;
  width: 48%;
  margin: 2% 1%;
}

(index):38 input {
  background-color: #f9a558;
  border: 1px solid #fff;
  height: 25px;
  width: 100%;
  flex: 1;
}

.company,
.comments {
  display: flex;
  margin: 5px 5px;
  flex-grow: 3;
  width 100%;
}

.company {
  margin-bottom: 3%;
}

@media (min-width: 426px) {
  .container {
    flex-direction: row;
    flex-wrap: wrap;
    align-self: flex-start;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box box1"><span>First Name
    <input type="text"></span></div>
  <div class="box box2"><span>Last Name
    <input type="text"></span></div>
  <div class="box box3"><span>Email
    <input type="text"></span></div>
  <div class="box box4"><span>Phone
    <input type="text"></span></div>
  <div class="box box1"><span>City
    <input type="text"></span></div>
  <div class="box box2"><span>State/Province
    <input type="text"></span></div>
</div>

<div class="container">
  <div class=" company"><span>Company
    <input class="company" type="text"></span></div>
</div>

<div class="container">
  <div class="comments"><span>Comments
    <input class="comments" type="text"></span></div>
</div></code>```

CSS:

```<code>span {
    font-size: 14px;
    text-align: left;
    float: left;
    width: 100%;
}

input[type="text"] {
    float: left;
    width: 100%;
    padding: 10px;
}

.box {
    height: 50px;
    float: left;
    width: 48%;
    margin: 2% 1%;
}
</code>```

Title: Flexbox - align items left and centered

Body:
JS Fiddle

body {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
}

* {
  box-sizing: border-box;
}

h1 {
  font-size: 20px;
  text-align: center;
}

span {
  font-size: 14px;
  text-align: left;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.box7,
.box8 {
  flex-basis: 100%;
  width: 100%;
  justify-content: center;
}

.box {
  height: 50px;
  width: calc(100% - 20px);
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.2em;
  flex: 1;
}

input {
  background-color: #f9a558;
  border: 1px solid #fff;
  height: 25px;
  width: 100%;
  flex: 1;
}

.company,
.comments {
  display: flex;
  margin: 5px 5px;
  flex-grow: 3;
  width 100%;
}

.company {
  margin-bottom: 3%;
}

@media (min-width: 426px) {
  .container {
    flex-direction: row;
    flex-wrap: wrap;
    align-self: flex-start;
  }
  .box {
    flex-basis: 45%;
  }
}

First Name
    <input type="text">

Last Name
    <input type="text">

Email
    <input type="text">

Phone
    <input type="text">

City
    <input type="text">

State/Province
    <input type="text">

Company
    <input class="company" type="text">

Comments
    <input class="comments" type="text">

I am attempting to center the boxes within my form as demonstrated in the attached picture. How can I get the form boxes to align left and appear side by?  As you can see in my jsfiddle, the from boxes are centered, however they do not align correctly nor do they appear side by side.

Body:
Try below CSS I think this is for helpfull:

See Fiddle Demo

body {
  color: #fff;
  background-color: #f78e2a;
  text-align: center;
}

* {
  box-sizing: border-box;
}

h1 {
  font-size: 20px;
  text-align: center;
}

span {
  font-size: 14px;
  text-align: left;
  float: left;
  width: 100%;
}

input[type="text"] {
  float: left;
  width: 98%;
  padding: 10px;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 5px 0;
}

.box7,
.box8 {
  flex-basis: 100%;
  width: 100%;
  justify-content: center;
}

.box {
  height: 50px;
  /* width: calc(100% - 20px); */
  /* display: flex; */
  /* justify-content: center; */
  /* align-items: center; */
  /* font-size: 1.2em; */
  /* flex: 1; */
  float: left;
  width: 48%;
  margin: 2% 1%;
}

(index):38 input {
  background-color: #f9a558;
  border: 1px solid #fff;
  height: 25px;
  width: 100%;
  flex: 1;
}

.company,
.comments {
  display: flex;
  margin: 5px 5px;
  flex-grow: 3;
  width 100%;
}

.company {
  margin-bottom: 3%;
}

@media (min-width: 426px) {
  .container {
    flex-direction: row;
    flex-wrap: wrap;
    align-self: flex-start;
  }
}

<div class="container">
  <div class="box box1"><span>First Name
    <input type="text"></span></div>
  <div class="box box2"><span>Last Name
    <input type="text"></span></div>
  <div class="box box3"><span>Email
    <input type="text"></span></div>
  <div class="box box4"><span>Phone
    <input type="text"></span></div>
  <div class="box box1"><span>City
    <input type="text"></span></div>
  <div class="box box2"><span>State/Province
    <input type="text"></span></div>
</div>

<div class="container">
  <div class=" company"><span>Company
    <input class="company" type="text"></span></div>
</div>

<div class="container">
  <div class="comments"><span>Comments
    <input class="comments" type="text"></span></div>
</div>

CSS:

span {
    font-size: 14px;
    text-align: left;
    float: left;
    width: 100%;
}

input[type="text"] {
    float: left;
    width: 100%;
    padding: 10px;
}

.box {
    height: 50px;
    float: left;
    width: 48%;
    margin: 2% 1%;
}


问:
"sh: Error: Can't open display" when I try to start a program from python
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

```<code>sh[2321]: Error: Can't open Display
</code>```

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

```<code> import subprocess
 subprocess.call("/usr/bin/xpdf")
</code>```

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

答:
Since the issue is that xpdf isn't finding a display to connect to, we have two basic options: find and authenticate with an existing display, or make a new one. The latter is usually easier, something like:

```<code>xinit /usr/bin/xpdf -fullscreen $PDFFILE -- :2
</code>```

This would start a new X display :2 running only xpdf, not even a window manager.

Body:
I have this really strange problem, basically I want to start xpdf (or Libreoffice) from my Python script, that is started by a systemd-service. When I start the script from terminal everything is working fine, but when I plug in my USB device that start the Service, I'll get this Error in my syslog:

sh[2321]: Error: Can't open Display

This error has something to do with X11, that's what my Google searches tell me.
So, my question is: How can I properly run a program like xpdf or libreoffice from Python?

 import subprocess
 subprocess.call("/usr/bin/xpdf")

This is it, basically. I know that it has something to do with the graphical enviroment, but I don't know how I can solve it.

Body:
Since the issue is that xpdf isn't finding a display to connect to, we have two basic options: find and authenticate with an existing display, or make a new one. The latter is usually easier, something like:

xinit /usr/bin/xpdf -fullscreen $PDFFILE -- :2

This would start a new X display :2 running only xpdf, not even a window manager.


问:
Is there a way to get the input date format based on timezone?
The timezone looks like this:

```<code>{ value: 'Australia/Sydney',
  name: '(GMT+10:00) Canberra, Melbourne, Sydney' },
</code>```

The preferred date input format on that timezone is DD/MM/YYYY.

I will then use that as the date input format on jquery ui datepicker

https://jqueryui.com/datepicker/#date-formats

Or more accurately, I'll be passing the DD/MM/YYYY on ui-date-format attribute of angular-ui-date (which is based on jquery ui datepicker) https://github.com/angular-ui/ui-date#ui-date-format-directive

I tried looking at momentjs documentation, but I can't see anything there that can be passed of the timezone value Australia/Sydney and returns the date input format.

答:
Momentjs has a specific plugin for timezones: https://momentjs.com/timezone/
Data formats contains also Australian timezones (https://momentjs.com/timezone/docs/#/data-formats/unpacked-format/)

For instance:

    moment().tz("Australia/Sydney"); //.format();

    let now = moment(new Date()).format("L");

    console.log(now);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-utils.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script></code>```

Body:
The timezone looks like this:

{ value: 'Australia/Sydney',
  name: '(GMT+10:00) Canberra, Melbourne, Sydney' },

The preferred date input format on that timezone is DD/MM/YYYY.

I will then use that as the date input format on jquery ui datepicker

https://jqueryui.com/datepicker/#date-formats

Or more accurately, I'll be passing the DD/MM/YYYY on ui-date-format attribute of angular-ui-date (which is based on jquery ui datepicker) https://github.com/angular-ui/ui-date#ui-date-format-directive

I tried looking at momentjs documentation, but I can't see anything there that can be passed of the timezone value Australia/Sydney and returns the date input format.

Body:
Momentjs has a specific plugin for timezones: https://momentjs.com/timezone/
Data formats contains also Australian timezones (https://momentjs.com/timezone/docs/#/data-formats/unpacked-format/)

For instance:

    moment().tz("Australia/Sydney"); //.format();

    let now = moment(new Date()).format("L");

    console.log(now);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-utils.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>


问:
The system cannot find the file specified in Kotlin
I try to read from file in same package so when i run code it give me error

```<code>var buffer: BufferedReader? = null

val result = try {

    buffer = BufferedReader(FileReader("file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println(" Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)
</code>```

output :

file.txt (The system cannot find the file specified)

closed

2

when i specify full path FileNoFoundException not throw why ?.

```<code>var buffer: BufferedReader? = null

val result = try {
    buffer = BufferedReader(FileReader("C:\\Users\\Mahmood Ali\\IdeaProjects\\Kotlin wih hadi\\src\\tidbits\\file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println("Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)
</code>```

output:

Exception handle

closed

1

答: If you pass a filename without a path, the JVM is going to look for that file in the current working directory, not the package folder of the class you're making the call from. So, to use relative paths, you have to first find out the working directory of your program, which should usually be the root folder of the project if you're running it from intelliJ.

Body:
I try to read from file in same package so when i run code it give me error

var buffer: BufferedReader? = null

val result = try {

    buffer = BufferedReader(FileReader("file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println(" Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)

output :

file.txt (The system cannot find the file specified)

closed

2

when i specify full path FileNoFoundException not throw why ?.

var buffer: BufferedReader? = null

val result = try {
    buffer = BufferedReader(FileReader("C:\\Users\\Mahmood Ali\\IdeaProjects\\Kotlin wih hadi\\src\\tidbits\\file.txt"))
    val chars = CharArray(30)
    buffer.read(chars, 0, 40)
    0
} catch (e: IndexOutOfBoundsException) {
    println("Exception handle")
    1
} catch(e: FileNotFoundException) {
    println(e.message)
    2
} finally {
    buffer?.close()
    println("closed")
}

println(result)

output:

Exception handle

closed

1


问:
Get is working but post is not working in spring boot
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

```<code><form id="forgotpassForm" action="anonymous/forgot_password"
method="post">
</code>```

Here is the error:

```<code>17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported
</code>```

Thanks is advance for your responses.

答:
```<code>    @RequestMapping(value = "forgot_password", method=
RequestMethod.POST)
public ResponseEntity<ServiceResponse>
changePassword(@RequestParam("email") String email) {
    anonService.requestForgotPassword(email);
    return new ResponseEntity<>(
            ServiceResponse.getServiceResponse("Forgot password
request processed successfully. " +
                    "An email has been sent to the provided email with
password reset link"),
            HttpStatus.OK
    );
}
</code>```

Body:
I am trying to display a page using action in jsp page when submit button gets clicked. But I am facing a problem. When I use method="get" its works and url shows parameter that I send using the form. But the problem is when I use method="post" the url is correct but it displays error page.

Here is the code:

<form id="forgotpassForm" action="anonymous/forgot_password"
method="post">

Here is the error:

17:27:24.305 WARN --- [http-nio-8080-exec-4] org.springframework.web.servlet.PageNotFound : Request method 'POST' not supported

Thanks is advance for your responses.


问:
ES6 Class - Call method from within event handler
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

```<code>class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;
</code>```

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

```<code>this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);
</code>```

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

答:
You can use bind to create a partial function:

```<code>this.eventButtons.forEach(button => button.addEventListener('click', this.method1.bind(this, button));
</code>```

It works assuming you change method1 to be:

```<code>method1 (button, e) {
  e.preventDefault();
  this.method2(e.target.href);
}
</code>```

Body:
I am trying to write an ES6 class for an interactive calendar on my current project.

The Class looks similar to the below:

class Calendar {

constructor (s) {

    this.eventButtons = s.eventButtons;
    this.eventButtons.forEach(button => button.addEventListener('click', this.method1);
    this.eventBoxes = s.eventBoxes;

method1 (e) {
    e.preventDefault();
    this.method2(e.target.href);
}

method2 (url) {
    console.log(url);
}

}

export default Calendar;

I know that the context of the 'this' keyword has changed from the constructor to the button which has been clicked within the method1 function. However I don't know how to keep the context of the button and the constructor within the same function. I tried changing the button event listener code to the following:

this.eventButtons.forEach(button => button.addEventListener('click', this.method1).bind(this);

But this just switches the context of the 'this' keyword to the constructor rather than the button. I need to use both in my function.

Any ideas? I'm hoping this is quite a common issue?

Body:
You can use bind to create a partial function:

this.eventButtons.forEach(button => button.addEventListener('click', this.method1.bind(this, button));

It works assuming you change method1 to be:

method1 (button, e) {
  e.preventDefault();
  this.method2(e.target.href);
}


答:
You have a few options:

You can bind the methods themselves:

```<code>this.method1 = this.method1.bind(this);
this.method2 = this.method2.bind(this);
</code>```

There's the bind operator if you're using Babel (or some other transpiler). It hasn't been accepted into the standard yet, so I'd be weary of using it. Using the bind operator, you can do the equivalent:

```<code>this.method1 = ::this.method1
this.method2 = ::this.method2
</code>```

The other option is to do what you've done already, just corrected.

You have to bind the method, not the result of the forEach.

```<code>this.eventButtons.forEach(button =>
    button.addEventListener('click', this.method1.bind(this)));
</code>```

or with bind op:

```<code>this.eventButtons.forEach(button =>
    button.addEventListener('click', ::this.method1));
</code>```

Finally, you also have the option of creating a wrapper function using arrow notation for lexical scope:

```<code>this.eventButtons.forEach(button =>
    button.addEventListener('click', (...params) => this.method1(...params)));
</code>```

Title: ES6 Class - Call method from within event handler

Body:
You have a few options:

You can bind the methods themselves:

this.method1 = this.method1.bind(this);
this.method2 = this.method2.bind(this);

There's the bind operator if you're using Babel (or some other transpiler). It hasn't been accepted into the standard yet, so I'd be weary of using it. Using the bind operator, you can do the equivalent:

this.method1 = ::this.method1
this.method2 = ::this.method2

The other option is to do what you've done already, just corrected.

You have to bind the method, not the result of the forEach.

this.eventButtons.forEach(button =>
    button.addEventListener('click', this.method1.bind(this)));

or with bind op:

this.eventButtons.forEach(button =>
    button.addEventListener('click', ::this.method1));

Finally, you also have the option of creating a wrapper function using arrow notation for lexical scope:

this.eventButtons.forEach(button =>
    button.addEventListener('click', (...params) => this.method1(...params)));


问:
VBA: best way to delete all buttons except one
I have different buttons in Excel and I would like to delete all of them except some.

I run

```<code>ActiveSheet.Buttons.Delete
</code>```

but how can I declare to keep one (we may assume it is called "MyButton1")?

答:
Do a For Each, by looping through ActiveSheet.Shapes you can see all the different buttons on your worksheet(s).  In the example below, it assigns btn = to the current button it's looking at.  If the name of the Button is NOT "MyButton1" then it is deleted.  The Next sends it back to the top to start again.

```<code>For Each btn In ActiveSheet.Buttons
    If btn.Text <> "MyButton1" Then
        btn.Delete
    End If
Next
</code>```

You can do this and change the "MyButton1" to whatever you would like.  Since I am assuming that's not the name of your actual button.  Also, if for some reason you only wanted to delete that particularly named button, you would just switch the <> with a =.  So it would read

If btn.Text = "MyButton1" Then btn.Delete

Edit -

Changed btn.Name to btn.AlternativeText to search for the visible text of the button instead of the object name itself.

Edit 2 -

I've removed ActiveSheet.Shapes as you had additional elements in the worksheet you didn't want deleted.  I have replaced the original code with ActiveSheet.Buttons and replaced AlternativeText with btn.Text to identify the Button Names.

Again, if you are not running this code on the sheet with Buttons, you will need to reference the workbook and worksheet first.

Body:
I have different buttons in Excel and I would like to delete all of them except some.

I run

ActiveSheet.Buttons.Delete

but how can I declare to keep one (we may assume it is called "MyButton1")?

Body:
Do a For Each, by looping through ActiveSheet.Shapes you can see all the different buttons on your worksheet(s).  In the example below, it assigns btn = to the current button it's looking at.  If the name of the Button is NOT "MyButton1" then it is deleted.  The Next sends it back to the top to start again.

For Each btn In ActiveSheet.Buttons
    If btn.Text <> "MyButton1" Then
        btn.Delete
    End If
Next

You can do this and change the "MyButton1" to whatever you would like.  Since I am assuming that's not the name of your actual button.  Also, if for some reason you only wanted to delete that particularly named button, you would just switch the <> with a =.  So it would read

If btn.Text = "MyButton1" Then btn.Delete

Edit -

Changed btn.Name to btn.AlternativeText to search for the visible text of the button instead of the object name itself.

Edit 2 -

I've removed ActiveSheet.Shapes as you had additional elements in the worksheet you didn't want deleted.  I have replaced the original code with ActiveSheet.Buttons and replaced AlternativeText with btn.Text to identify the Button Names.

Again, if you are not running this code on the sheet with Buttons, you will need to reference the workbook and worksheet first.


问:
Using FreeText with SubSonic
Is there a general consensus on how to use SQL 2005's full text search with SubSonic?  I know that I can use the InlineQuery and get an IDataReader, but is this the only way to do this?  Also, how would I incorporate paging into it?  Would I have to write the paging myself in the InlineQuery?

What I would really like to do is something like this:

```<code>new Select().From<Item>().Where("FreeText(Title, @title)").ExecuteAsCollection<ItemCollection>();
</code>```

This way, I can use the built-in Subsonic paging functions and not have to write the entire query in SQL

答: This won't work with SubSonic as it is now. I made a patch a while ago that would do something like this but it never got in. I'm wondering if it should be their or not what do you think?</p>

OwnerDisplayName: Kevin Pang

Title: Using FreeText with SubSonic

Body:
Is there a general consensus on how to use SQL 2005's full text search with SubSonic?  I know that I can use the InlineQuery and get an IDataReader, but is this the only way to do this?  Also, how would I incorporate paging into it?  Would I have to write the paging myself in the InlineQuery?

What I would really like to do is something like this:

new Select().From<Item>().Where("FreeText(Title, @title)").ExecuteAsCollection<ItemCollection>();

This way, I can use the built-in Subsonic paging functions and not have to write the entire query in SQL

LastEditorDisplayName: Kevin Pang

OwnerDisplayName: Yitzchok-adminjew


问:
How to set number of calls of the function scheduled by LoopingCall?
Here is the skeleton of the code:

```<code>from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something():
    print "Doing something..."

def process_result():
    print "Processing result..."

def loop():
    LoopingCall(do_something).start(1)

reactor.callWhenRunning(loop)
reactor.run()
</code>```

In my code I want to run do_something for 100 times, and after that I will call process_result to do what its name indicates.

In the documentation I found a withCount, however I was confused about "which should have occurred since it was last invoked" and "The count is normally 1" in it. (Using LoopingCall to call a function once? What's the point? I think I misunderstood it but what is the correct explanation?)

I'd like to know: is withCount the correct thing to use? If yes, can someone provide a concrete example?

答:
withCount gives you useful information when LoopingCall misses iterations. For example, if the interval is 1, but the function takes 5 seconds, the number of times which the function should have been called would be 5. However, in your example, the function returns almost instantly (and is not a deferred) so it'll be always 1.

```<code>from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something(count):
    print "Doing something..." + str(count)

def process_result():
    print "Processing result..."

def loop():
    LoopingCall.withCount(do_something).start(1)

reactor.callWhenRunning(loop)
reactor.run()
</code>```

You need to check the number of times that the function has been called and use lc.stop when you reach the designated number of times. If you do not want to introduce extra logic in do_something, you can make a wrapper class.

```<code>from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something():
    print "Doing something..."

def process_result():
    print "Processing result..."

def loop():
    LoopingCallWithCounter(5, do_something).lc.start(1)

class LoopingCallWithCounter:
    def __init__(self, count, f, *a, **kw):
        self.i = 0
        def wrapper():
            if self.i >= count:
                self.lc.stop()
            else:
                f(*a, **kw)
                self.i += 1
        self.lc = LoopingCall(wrapper)

reactor.callWhenRunning(loop)
reactor.run()
</code>```

Finally, since lc.start returns a deferred when lc.stop is called, you can simply use addCallback(process_result) to do the post processing. Note that process_result should take an argument.

Body:
Here is the skeleton of the code:

from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something():
    print "Doing something..."

def process_result():
    print "Processing result..."

def loop():
    LoopingCall(do_something).start(1)

reactor.callWhenRunning(loop)
reactor.run()

In my code I want to run do_something for 100 times, and after that I will call process_result to do what its name indicates.

In the documentation I found a withCount, however I was confused about "which should have occurred since it was last invoked" and "The count is normally 1" in it. (Using LoopingCall to call a function once? What's the point? I think I misunderstood it but what is the correct explanation?)

I'd like to know: is withCount the correct thing to use? If yes, can someone provide a concrete example?

Body:
withCount gives you useful information when LoopingCall misses iterations. For example, if the interval is 1, but the function takes 5 seconds, the number of times which the function should have been called would be 5. However, in your example, the function returns almost instantly (and is not a deferred) so it'll be always 1.

from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something(count):
    print "Doing something..." + str(count)

def process_result():
    print "Processing result..."

def loop():
    LoopingCall.withCount(do_something).start(1)

reactor.callWhenRunning(loop)
reactor.run()

You need to check the number of times that the function has been called and use lc.stop when you reach the designated number of times. If you do not want to introduce extra logic in do_something, you can make a wrapper class.

from twisted.internet import reactor
from twisted.internet.task import LoopingCall

def do_something():
    print "Doing something..."

def process_result():
    print "Processing result..."

def loop():
    LoopingCallWithCounter(5, do_something).lc.start(1)

class LoopingCallWithCounter:
    def __init__(self, count, f, *a, **kw):
        self.i = 0
        def wrapper():
            if self.i >= count:
                self.lc.stop()
            else:
                f(*a, **kw)
                self.i += 1
        self.lc = LoopingCall(wrapper)

reactor.callWhenRunning(loop)
reactor.run()

Finally, since lc.start returns a deferred when lc.stop is called, you can simply use addCallback(process_result) to do the post processing. Note that process_result should take an argument.


问:
Replace script tag that has a dynamic version number which keeps changing
I would like to remove or replace this string in an HTML file using javascript.

```<code>'<script src="../assets/js/somejs.js?1.0.953"></script>'
</code>```

Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace

答:
You could achieve this using the following Regex:

```<code>\?.*?\"
</code>```

Or, more specifically

```<code>(\d+)\.(\d+)\.(\d+)
</code>```

For matching the version number.

Utilizing the regex, you can replace the version number with a blank value.

Body:
I would like to remove or replace this string in an HTML file using javascript.

''

Trouble is, the version number "1.0.953" keeps changing so I can't use a simple string.replace

Body:
You could achieve this using the following Regex:

\?.*?\"

Or, more specifically

(\d+)\.(\d+)\.(\d+)

For matching the version number.

Utilizing the regex, you can replace the version number with a blank value.


问:
The SDK Build Tools revision (23.0.1) is too low for project ':app'. Minimum required is 25.0.0
I have been stuck in a problem.. Its been probably 3 hours..
     In android studio message says.

```<code>Error: The SDK Build Tools revision (23.0.1) is too low for project ':app'. Minimum required is 25.0.0
Install Build Tools 25.0.0, update version in build file and sync ..
</code>```

But the version 25.0.0 is not available when i went for update...

答:
Try to check here https://github.com/oblador/react-native-keychain/issues/68#issuecomment-304836725
It helped me, but I faced a little bit other issue: “The SDK Build Tools revision (23.0.1) is too low for project ‘:{project_name}’. Minimum required is 25.0.0”</p>

Body:
I have been stuck in a problem.. Its been probably 3 hours..
     In android studio message says.

Error: The SDK Build Tools revision (23.0.1) is too low for project ':app'. Minimum required is 25.0.0
Install Build Tools 25.0.0, update version in build file and sync ..

But the version 25.0.0 is not available when i went for update...


问:
Connecting to chromecast - a fatal developer error has occured

06-22 08:17:30.568 31107-31119/? E/CastService: [instance-4]
  ICastDeviceControllerListener can't be null. 06-22 08:17:30.578
  8284-8601/? E/EnterpriseContainerManager: ContainerPolicy Service is
  not yet ready!!! 06-22 08:17:30.578 31107-31136/? E/Publisher:
  ProcessDatabaseInternal start 06-22 08:17:30.578 32326-32326/?
  E/ViewRootImpl: sendUserActionEvent() mView == null 06-22 08:17:30.588
  32326-32326/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                     java.lang.IllegalStateException:

A fatal developer error has occurred. Check the logs for further
  information.
                                                         at com.google.android.gms.internal.jl$h.b(Unknown Source)
                                                         at com.google.android.gms.internal.jl$h.g(Unknown Source)
                                                         at com.google.android.gms.internal.jl$b.hy(Unknown Source)
                                                         at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
                                                         at android.os.Handler.dispatchMessage(Handler.java:99)
                                                         at android.os.Looper.loop(Looper.java:137)
                                                         at android.app.ActivityThread.main(ActivityThread.java:5283)
                                                         at java.lang.reflect.Method.invokeNative(Native Method)
                                                         at java.lang.reflect.Method.invoke(Method.java:511)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                         at dalvik.system.NativeStart.main(Native Method) 06-22 08:17:30.919
  8284-8333/? E/android.os.Debug: !@Dumpstate > dumpstate -k -t -z -d -o
  /data/log/dumpstate_app_error 06-22 08:17:36.414 31107-31136/?
  E/Publisher: ProcessDatabaseInternal start

I have this issue while connecting to chromecast. I've gone back to the previous code, and I still have the same issue, so something must have changed with chromecast. When I click my chromecast device to connect to "Sankey", this is when the crash occurs. Image below:

Research on this has pointed to a problem with the manifest, and not declaring the app_id properly. Below is my manifest file which shows this, and also the google play services version.

```<code>    <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/control_panel_app_id" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</code>```

Here is the declarations in strings.xml with last 4 digits blocked out:

string name="control_panel_app_id" translatable="false">75468636XXXX

Checking the logs in vicinity of the crash has not given me any useful information.

答:
My app was previously running cast SDK v1. I had two options to fix it:  1) wait approximately 3 months until google updated their gms code. 2) upgrade to cast v2.

I chose option 2.

Upgrading to cast v2 was done by the following:

change gradle files, so everything referencing any part of google play is version 11.0.0.  ex: com.google.android.gms:play-services-games:11.0.0

required deleting references to "AppStateManager" in GameHelper.java (this is not necessary for cast, but was part of my project).

required changing minSdkVersion from 11 to 14 :(

in gradle file(s), update compileSdkVersion to 25, and buildToolsVersion to 25.0.2

Hope this helps someone out.

Body:
06-22 08:17:30.568 31107-31119/? E/CastService: [instance-4]
  ICastDeviceControllerListener can't be null. 06-22 08:17:30.578
  8284-8601/? E/EnterpriseContainerManager: ContainerPolicy Service is
  not yet ready!!! 06-22 08:17:30.578 31107-31136/? E/Publisher:
  ProcessDatabaseInternal start 06-22 08:17:30.578 32326-32326/?
  E/ViewRootImpl: sendUserActionEvent() mView == null 06-22 08:17:30.588
  32326-32326/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                     java.lang.IllegalStateException:

A fatal developer error has occurred. Check the logs for further
  information.
                                                         at com.google.android.gms.internal.jl$h.b(Unknown Source)
                                                         at com.google.android.gms.internal.jl$h.g(Unknown Source)
                                                         at com.google.android.gms.internal.jl$b.hy(Unknown Source)
                                                         at com.google.android.gms.internal.jl$a.handleMessage(Unknown Source)
                                                         at android.os.Handler.dispatchMessage(Handler.java:99)
                                                         at android.os.Looper.loop(Looper.java:137)
                                                         at android.app.ActivityThread.main(ActivityThread.java:5283)
                                                         at java.lang.reflect.Method.invokeNative(Native Method)
                                                         at java.lang.reflect.Method.invoke(Method.java:511)
                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                         at dalvik.system.NativeStart.main(Native Method) 06-22 08:17:30.919
  8284-8333/? E/android.os.Debug: !@Dumpstate > dumpstate -k -t -z -d -o
  /data/log/dumpstate_app_error 06-22 08:17:36.414 31107-31136/?
  E/Publisher: ProcessDatabaseInternal start

I have this issue while connecting to chromecast. I've gone back to the previous code, and I still have the same issue, so something must have changed with chromecast. When I click my chromecast device to connect to "Sankey", this is when the crash occurs. Image below:

Research on this has pointed to a problem with the manifest, and not declaring the app_id properly. Below is my manifest file which shows this, and also the google play services version.

    <meta-data android:name="com.google.android.gms.games.APP_ID"
        android:value="@string/control_panel_app_id" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

Here is the declarations in strings.xml with last 4 digits blocked out:

string name="control_panel_app_id" translatable="false">75468636XXXX

Checking the logs in vicinity of the crash has not given me any useful information.


问:
How to validate image size, height, width and format before upload with jquery of PHP?
I want to validate my image size, height, width and image format before upload with jquery or PHP. I found many answers, but I have not found all validate is together.

Image format = png, Image size = 2mb, Image height = 800px, Image width= 600

答:
As you have asked for jquery or PHP, I will suggest you to use php for this kind validation, Due to security point of view you must validate your uploaded file at server side.
First to check if file is image you can use

```<code>mime_content_type or finfo_open()
</code>```

After validating your file is image you can go for width and height

```<code>list($width, $height) = getimagesize($_FILES["fileToUpload"]);
</code>```

for size you use

```<code>$_FILES["fileToUpload"]["size"]
</code>```

Hope combining this will resolve your issue.

Body:
As you have asked for jquery or PHP, I will suggest you to use php for this kind validation, Due to security point of view you must validate your uploaded file at server side.
First to check if file is image you can use

mime_content_type or finfo_open()

After validating your file is image you can go for width and height

list($width, $height) = getimagesize($_FILES["fileToUpload"]);

for size you use

$_FILES["fileToUpload"]["size"]

Hope combining this will resolve your issue.