问:
transfer data from fragment A -> fragment B - > fragment C. When user click Back button, I want to return to fragment A and data
I'm a newbie in android developer. I have a question about transfer with 3 fragments.

I have 3 fragments (A - B - C). I want o transfer data from A -> B -> C.

In each the fragment, data was been changed.
When user click BACK BUTTON, user want to return A with the updated data.
How to return fragment A with the update data?
Thanks.

答:
Here is a sample idea how to achieve communication.</p>

```<code> // activity classs
 public class SampleActivity extends Activity implements    OnFragmentChangeListener {
 OnBackPressListener  dataFragment;
 public void onCreate(bundle){

      android.app.FragmentManager fragmentManager=getFragmentManager();

    android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    dataFragment = new DataFragment();
    fragmentTransaction.add(R.id.audio_permission_button,dataFragment);
    fragmentTransaction.commit()
 }
  @override
  public void OnFragmentChange(Bundle bundle){
  //here you go.
  // write code to load new fragment with same idea. now you have bundle do what you want.

}
@Override
public void onBackPressed() {
 // you can call this method from any click event, This just an sample idea.
 dataFragment.OnActivityBackPress();
}

}
 // interface to communicate with fragment
 public interface OnFragmentChangeListener {
     public void OnFragmentChange()
 }
 // fragment class
public class DataFragment extends Fragment implements OnBackPressListener {

 OnFragmentChangeListener onFragmentChangeListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 onFragmentChangeListener=(OnFragmentChangeListener) getActivity();

}

    @Override
public void OnActivityBackPress() {
 // pass you data to activity for loading new fragment or to refresh data.
 Bundle bundle= new Bundle();

 onFragmentChangeListener.OnFragmentChange(bundle);

}
}

// interface behave like mediator
public interface OnBackPressListener {

public void OnActivtiyBackPress();
}
</code>```

Body:
Here is a sample idea how to achieve communication.

 // activity classs
 public class SampleActivity extends Activity implements    OnFragmentChangeListener {
 OnBackPressListener  dataFragment;
 public void onCreate(bundle){

      android.app.FragmentManager fragmentManager=getFragmentManager();

    android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    dataFragment = new DataFragment();
    fragmentTransaction.add(R.id.audio_permission_button,dataFragment);
    fragmentTransaction.commit()
 }
  @override
  public void OnFragmentChange(Bundle bundle){
  //here you go.
  // write code to load new fragment with same idea. now you have bundle do what you want.

}
@Override
public void onBackPressed() {
 // you can call this method from any click event, This just an sample idea.
 dataFragment.OnActivityBackPress();
}

}
 // interface to communicate with fragment
 public interface OnFragmentChangeListener {
     public void OnFragmentChange()
 }
 // fragment class
public class DataFragment extends Fragment implements OnBackPressListener {

 OnFragmentChangeListener onFragmentChangeListener;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
 onFragmentChangeListener=(OnFragmentChangeListener) getActivity();

}

    @Override
public void OnActivityBackPress() {
 // pass you data to activity for loading new fragment or to refresh data.
 Bundle bundle= new Bundle();

 onFragmentChangeListener.OnFragmentChange(bundle);

}
}

// interface behave like mediator
public interface OnBackPressListener {

public void OnActivtiyBackPress();
}


来源: stackexchange

问:
Alternative to Akka for handling tasks sequentially
I have a system which may generate certain events in the lifecycle of a transaction. On every even I need to update a row in a DB and also send out a UI event over websocket.

One option I have is to implement the event processing (DB and UI) in actors thus avoiding any locking issues - also I can afford minor delays so handling this sequentially will greatly simplify matters.

What are alternative ways of handling this in Scala as I feel maybe Actors might be overkill in this case?
There are those blogs stating that actors should be used for "concurrency with state" - though I would like to see a more appropriate mechanism in order to eliminate this option.

答:
Not at all sure if this is applicable for Scala, but there's a great lib for Groovy and Java with several concurrency models. I've myself used the Dataflow Concurrency with great success and can recommend it as a light-weight yet manageable model.

Dataflow Concurrency offers an alternative concurrency model, which is
  inherently safe and robust. It puts an emphasis on the data and their
  flow though your processes instead of the actual processes that
  manipulate the data. Dataflow algorithms relieve developers from
  dealing with live-locks, race-conditions and make dead-locks
  deterministic and thus 100% reproducible. If you don’t get dead-locks
  in tests you won’t get them in production.

There are other models available in the linked GPars library as well.

I wouldn't suggest making the threading yourself, unless you have no other choices.

Addendum

After posting I got interested in the topic and made a few searches. Seems like Akka has direct support for Dataflow model also. Or at least has had in some version.

ContentLicense: CC BY-SA 3.0


问:
I don't understand the error message in declaration the avl tree
I'm trying to program an AVL tree and I got this error that I don't understand, can someone help. Thank you

source

```<code>template<class KeyType, class ItemType>
class AVL
{
 protected:
 template<class KeyType, class ItemType>
 class AVLNode
 {
  public:
  AVLNode(KeyType key, ItemType item) :
  m_Balance(0), m_Depth(0),
  m_Key(key), m_Data(item),
  m_pLeft(0), m_pRight(0)
  {
  }

  KeyType       m_Key;
  ItemType  m_Data;

  AVLNode*  m_pLeft;
  AVLNode*  m_pRight;
  };

  AVLNode<KeyType, ItemType>* m_pRoot;
  public:
  AVL() : m_pRoot(0) { }
  ~AVL() { }
};
</code>```

答:
Try it with these changes:

```<code>template<class KeyType, class ItemType>
class AVL
{
 protected:
 // Unnecessary -> template<class KeyType, class ItemType>
 class AVLNode
 {
  public:
     AVLNode(KeyType key, ItemType item) : m_Balance(0), m_Depth(0),
                                           m_Key(key), m_Data(item),
                                           m_pLeft(0), m_pRight(0)
  { }

  private:
     int m_Balance;  // Missing from the ctor declaration
     int m_Depth;  // Missing from the ctor declaration
     KeyType m_Key;
     ItemType m_Data;

     AVLNode<KeyType, ItemType>*  m_pLeft;  // Change here
     AVLNode<KeyType, ItemType>*  m_pRight; // Change here
  };

  AVLNode<KeyType, ItemType>* m_pRoot;
  public:
  AVL() : m_pRoot(0) { }
  ~AVL() { }
};
</code>```

Body:
I'm trying to program an AVL tree and I got this error that I don't understand, can someone help. Thank you

source

template<class KeyType, class ItemType>
class AVL
{
 protected:
 template<class KeyType, class ItemType>
 class AVLNode
 {
  public:
  AVLNode(KeyType key, ItemType item) :
  m_Balance(0), m_Depth(0),
  m_Key(key), m_Data(item),
  m_pLeft(0), m_pRight(0)
  {
  }

  KeyType       m_Key;
  ItemType  m_Data;

  AVLNode*  m_pLeft;
  AVLNode*  m_pRight;
  };

  AVLNode<KeyType, ItemType>* m_pRoot;
  public:
  AVL() : m_pRoot(0) { }
  ~AVL() { }
};

Body:
Try it with these changes:

template<class KeyType, class ItemType>
class AVL
{
 protected:
 // Unnecessary -> template<class KeyType, class ItemType>
 class AVLNode
 {
  public:
     AVLNode(KeyType key, ItemType item) : m_Balance(0), m_Depth(0),
                                           m_Key(key), m_Data(item),
                                           m_pLeft(0), m_pRight(0)
  { }

  private:
     int m_Balance;  // Missing from the ctor declaration
     int m_Depth;  // Missing from the ctor declaration
     KeyType m_Key;
     ItemType m_Data;

     AVLNode<KeyType, ItemType>*  m_pLeft;  // Change here
     AVLNode<KeyType, ItemType>*  m_pRight; // Change here
  };

  AVLNode<KeyType, ItemType>* m_pRoot;
  public:
  AVL() : m_pRoot(0) { }
  ~AVL() { }
};


问:
Python solve given conditions
everyone

Is it possible to solve the following like:

```<code>x = np.matrix([[8.3,-20.6],[-20.6,65.8]])
</code>```

y is a function of P:

```<code>y = lambda P: np.matrix([[0.02P,-0.02P], [-0.02P,0.04P]])
</code>```

I want to find the P value given conditions that:

```<code>P>0, det(x-y)==0;
</code>```

Is there any handy way for this?

Thank you very much!
Shawn

答:
If you don't mind using an additional package, scipy.optimize has a number of methods that would be perfect. Otherwise, you could implement your own zero finding function.

If you want to go the scipy route:

1) Define your problem as a function that takes your unknown parameter (P) as its first argument, and returns the value you want to minimize:

```<code>def zerofn(P, x, y):
    return np.linalg.det(x - y(P))
</code>```

2) Optimize this function, using scipy. The example here uses a simple Newton-Raphson zero finder, but there are many other options which you might want to use to specify parameter bounds (e.g. P > 0).

```<code>import scipy.optimize as opt

opt.newton(zerofn, x0=1, args=(x, y))

>> 160.25865914054651
</code>```

The result of this zero finder is your optimized value of P.

Title: Python solve given conditions

Body:
everyone

Is it possible to solve the following like:

x = np.matrix([[8.3,-20.6],[-20.6,65.8]])

y is a function of P:

y = lambda P: np.matrix([[0.02P,-0.02P], [-0.02P,0.04P]])

I want to find the P value given conditions that:

P>0, det(x-y)==0;

Is there any handy way for this?

Thank you very much!
Shawn

Body:
If you don't mind using an additional package, scipy.optimize has a number of methods that would be perfect. Otherwise, you could implement your own zero finding function.

If you want to go the scipy route:

1) Define your problem as a function that takes your unknown parameter (P) as its first argument, and returns the value you want to minimize:

def zerofn(P, x, y):
    return np.linalg.det(x - y(P))

2) Optimize this function, using scipy. The example here uses a simple Newton-Raphson zero finder, but there are many other options which you might want to use to specify parameter bounds (e.g. P > 0).

import scipy.optimize as opt

opt.newton(zerofn, x0=1, args=(x, y))

>> 160.25865914054651

The result of this zero finder is your optimized value of P.


问:
ASP.Net login page problem
I had a website project which worked fine. I have converted it into a web application project in VS 2010. Now when I start the project from VS my login page is never loaded because when it tries to load images, scripts, css all the requests are redirected back to login page.

However if I setup a website under my local IIS to use the folder where the project is the website works no problem.

I have created a test web app to play with. And it does pretty much the same. Login page cannot load an image because the request is redirected.
Here is what I've got.

web.config

```<code><configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms name=".ASPXAUTH" loginUrl="~/login1.aspx" defaultUrl="~/default.aspx"  slidingExpiration="true"/>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>
    <trace enabled="true" pageOutput="true" requestLimit="150" mostRecent="false" />
  </system.web>
  <location path="trace.axd">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>
</code>```

login1.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login1.aspx.cs" Inherits="TestWebApp.login1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
    <img src="bcb.jpeg" />
login page
</div>
</form>
</body>
</html>
</code>```

default.aspx

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="TestWebApp._default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    default page
    </div>
    </form>
</body>
</html>
</code>```

and the trace looks like

Requests to this Application Remaining: 140

No. Time of Request File Status Code Verb

1 11/30/2010 10:57:20 AM default.aspx 302 GET View Details

2 11/30/2010 10:57:20 AM login1.aspx 200 GET View Details

3 11/30/2010 10:57:22 AM bcb.jpeg 302 GET View Details

4 11/30/2010 10:57:22 AM login1.aspx 200 GET View Details

I'm missing something. Any ideas?

Thanks

答:
See the following post for a solution:

How to use ASP.NET Authorization Yet Permit Access to .css Files?

ContentLicense: CC BY-SA 2.5

Title: ASP.Net login page problem

Body:
I had a website project which worked fine. I have converted it into a web application project in VS 2010. Now when I start the project from VS my login page is never loaded because when it tries to load images, scripts, css all the requests are redirected back to login page.

However if I setup a website under my local IIS to use the folder where the project is the website works no problem.

I have created a test web app to play with. And it does pretty much the same. Login page cannot load an image because the request is redirected.
Here is what I've got.

web.config

<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <authentication mode="Forms">
      <forms name=".ASPXAUTH" loginUrl="~/login1.aspx" defaultUrl="~/default.aspx"  slidingExpiration="true"/>
    </authentication>
    <authorization>
      <deny users="?"/>
    </authorization>
    <trace enabled="true" pageOutput="true" requestLimit="150" mostRecent="false" />
  </system.web>
  <location path="trace.axd">
    <system.web>
      <authorization>
        <allow users="*"/>
      </authorization>
    </system.web>
  </location>
  <system.webServer>
     <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
</configuration>

login1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login1.aspx.cs" Inherits="TestWebApp.login1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title></title>

<form id="form1" runat="server">

login page

</form>

default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="TestWebApp._default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

    default page

    </form>

and the trace looks like

Requests to this Application Remaining: 140

No. Time of Request File Status Code Verb

1 11/30/2010 10:57:20 AM default.aspx 302 GET View Details

2 11/30/2010 10:57:20 AM login1.aspx 200 GET View Details

3 11/30/2010 10:57:22 AM bcb.jpeg 302 GET View Details

4 11/30/2010 10:57:22 AM login1.aspx 200 GET View Details

I'm missing something. Any ideas?

Thanks


问:
Timer countdown is negative
I have a code of which is used to create a 24 hour countdown.

This code checks if a "date" file exists and if it doesn't it creates one, which contains the date and time in 24 hourse/a day. It then gets the current time and compares the two, to create a countdown from the current date, to the date in the document.

This makes it possible to save the timer and check how far it has come even though the code is "turned off". The only issue is the fact that sometimes the timer turns negative. Like if I run the code from the start with no "date" file created on Monday, right before midnight, lets say Monday at half past eleven at night. Then if I stop the code and run it again when the current date has passed midnight, so it is actually Tuesday, but there is still missing up to 23 hours before it hits the actual goal timer. If this is the case, the time left in the countdown is negative. Like it would show "-1day 23hours 60minutes and 60seconds remaining". But if as an example it is run from scratch past midnight on Tuesday and then relaunch after 30 minutes the same day, there is no issue.

I hope you can understand what the issue is, it is slightly hard to express through text. But I have attached the whole code of mine, which is the exact one I am using and of which is having that issue. The code has comments for every actions happening, so it should be rather easy to understand.

```<code>static File dFileD = new File("date.txt");
    static String date = "";

  public static void main(String[] args) throws ParseException {

      Timer tickTock = new Timer();
      TimerTask tickTockTask = new TimerTask(){

          public void run(){
              try {
                timFunRun(); //Timer calls method to start the countdown
            } catch (ParseException e) {
                e.printStackTrace();
            }
          }
      };

      tickTock.schedule(tickTockTask, 1000, 1000);

  }

  static void timFunRun() throws ParseException {

      if (!dFileD.exists()){ //if it doesn't exist, first part

          //Get current date and time
          Calendar startDat = Calendar.getInstance();
          System.out.println("Current date: " + startDat.getTime());

          //Get that current date and time and then add 1 day
          Calendar todAdd = Calendar.getInstance();
          todAdd.add(Calendar.DATE, 1);
          System.out.println("Date in 1 day: " + todAdd.getTime());

          //Create a format for sending date to text file
          SimpleDateFormat formDat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
          String formatted = formDat.format(todAdd.getTime());
          System.out.println("Formatted: " + formatted);

          try{
              PrintWriter dW = new PrintWriter("date.txt");
              dW.println(formatted);
              dW.close();
          } catch (IOException e) {
          }

          System.out.println(formDat.parse(formatted));

      } else { //if it does exist, second part

          //Get current date and time
          Calendar currentDeT = Calendar.getInstance();
          System.out.println("Current date: " + currentDeT.getTime());
          SimpleDateFormat formDat2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");

          Date dateFroText = null; //Get the "goal" date
          try {
              Scanner dateRead = new Scanner(dFileD);
              while (dateRead.hasNextLine()) {
                  date = dateRead.nextLine();
                  dateFroText = formDat2.parse(date);
                  System.out.println("Date from text new format: " + dateFroText);
              }
              dateRead.close();
            } catch (Exception e) {
                System.out.println("Error!");
            }

          if (dateFroText != null){ //method to compare the current date and the goal date
              Calendar dateFromTxtCal = Calendar.getInstance();
              dateFromTxtCal.setTime(dateFroText);
          int yearDiff = dateFromTxtCal.get(Calendar.YEAR) - currentDeT.get(Calendar.YEAR);
          int dayDiff = ((yearDiff*365) + dateFromTxtCal.get(Calendar.DAY_OF_YEAR)) - currentDeT.get(Calendar.DAY_OF_YEAR);
          dayDiff--;
          int hourDiffer = dateFromTxtCal.get(Calendar.HOUR_OF_DAY)+23 - currentDeT.get(Calendar.HOUR_OF_DAY);
          int minuDiff = dateFromTxtCal.get(Calendar.MINUTE)+60 - currentDeT.get(Calendar.MINUTE);
          int secoDiff = dateFromTxtCal.get(Calendar.SECOND)+60 - currentDeT.get(Calendar.SECOND);
          System.out.println(dayDiff + " days " + hourDiffer + " hours " + minuDiff +" minutes " + secoDiff + "seconds remaining");
          }

      }

  }
</code>```

答:
Avoid legacy date-time classe

You are working too hard. And you are using troublesome old date-time classes now obsoleted and supplanted by the java.time classes.

Work in UTC

Also, if you only care about the next 24 hours, then no need for time zones. Just use UTC.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

```<code>Instant instantNow = Instant.now();
</code>```

Duration

A span of time unattached to the timeline is represented by the Duration or Period classes.

```<code>Duration duration = Duration.ofHours( 24 );
</code>```

You can perform date-time math, adding a Duration to an Instant. The java.time classes use immutable objects, so the result of such manipulations is a fresh object with values based on the original.

```<code>Instant instantLater = instantNow.plus( duration );
</code>```

ISO 8601

To serialize date-time values such as those to text, use the standard ISO 8601 formats. The java.time classes use ISO 8601 by default when generating and parsing strings.

```<code>String output = instantNow.toString();
</code>```

2017-04-03T03:18:48.183Z

Calculate remaining time

To get the remaining time, let java.time do the math.

```<code>Duration remaining = Duration.between( Instant.now() , instantLater );
</code>```

To report that in standard ISO 8601 format, call toString. The format for durations is PnYnMnDTnHnMnS. The P marks the beginning (for Period), and the T separates any years-months-dates from hours-minutes-seconds.

```<code>String outputRemaining = remaining.toString();
</code>```

PT23H34M22S

To generate a longer string, in Java 9 call the to…Part method for each unit (hours, minutes, seconds). Oddly those methods were omitted from the original java.time.Duration class in Java 8. You could look to the source code of Java 9 to write similar code.

Or more simply, manipulate the standard string. Delete the PT. Replace the H with hours and so on. Do S first to avoid the plural s in the other two words. Admittedly this is kind of a hack, but it works thanks to some good luck in the occurrence of letters is the English spelling of hours-minutes-seconds.

```<code>String output = remaining.toString()
                         .replace( "PT" , "" )
                         .replace( "S" , " seconds " )
                         .replace( "H" , " hours " )
                         .replace( "M" , " minutes " ) ;
</code>```

23 hours 34 minutes 22 seconds

ZonedDateTime

If you want to display the target date-time in the user's desired/expected time zone, apply a ZoneId to get a ZonedDateTime object.

```<code>ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
</code>```

To generate a string in standard format, call toString. Actually the ZonedDateTime class extends the standard by appending the name of the time zone in square brackets.

To generate strings in other formats, search Stack Overflow for many examples of DateTimeFormatter class.

Converting to java.util.Date

The Timer class has not yet been updated to work with the java.time types. So convert back to a Date object via new methods added to the old classes, in this case from.

```<code>java.util.Date date = java.util.Date.from( instantLater );
</code>```

Or use a count of milliseconds from the Duration object.

```<code>long milliseconds = duration.toMillis() ;
</code>```

ScheduledExecutorService

FYI, the Timer and TimeTask classes have been supplanted by the Executors framework. Specifically for your purpose, the ScheduledExecutorService. Search Stack Overflow for many examples and discussions.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Title: Timer countdown is negative

Body:
I have a code of which is used to create a 24 hour countdown.

This code checks if a "date" file exists and if it doesn't it creates one, which contains the date and time in 24 hourse/a day. It then gets the current time and compares the two, to create a countdown from the current date, to the date in the document.

This makes it possible to save the timer and check how far it has come even though the code is "turned off". The only issue is the fact that sometimes the timer turns negative. Like if I run the code from the start with no "date" file created on Monday, right before midnight, lets say Monday at half past eleven at night. Then if I stop the code and run it again when the current date has passed midnight, so it is actually Tuesday, but there is still missing up to 23 hours before it hits the actual goal timer. If this is the case, the time left in the countdown is negative. Like it would show "-1day 23hours 60minutes and 60seconds remaining". But if as an example it is run from scratch past midnight on Tuesday and then relaunch after 30 minutes the same day, there is no issue.

I hope you can understand what the issue is, it is slightly hard to express through text. But I have attached the whole code of mine, which is the exact one I am using and of which is having that issue. The code has comments for every actions happening, so it should be rather easy to understand.

static File dFileD = new File("date.txt");
    static String date = "";

  public static void main(String[] args) throws ParseException {

      Timer tickTock = new Timer();
      TimerTask tickTockTask = new TimerTask(){

          public void run(){
              try {
                timFunRun(); //Timer calls method to start the countdown
            } catch (ParseException e) {
                e.printStackTrace();
            }
          }
      };

      tickTock.schedule(tickTockTask, 1000, 1000);

  }

  static void timFunRun() throws ParseException {

      if (!dFileD.exists()){ //if it doesn't exist, first part

          //Get current date and time
          Calendar startDat = Calendar.getInstance();
          System.out.println("Current date: " + startDat.getTime());

          //Get that current date and time and then add 1 day
          Calendar todAdd = Calendar.getInstance();
          todAdd.add(Calendar.DATE, 1);
          System.out.println("Date in 1 day: " + todAdd.getTime());

          //Create a format for sending date to text file
          SimpleDateFormat formDat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
          String formatted = formDat.format(todAdd.getTime());
          System.out.println("Formatted: " + formatted);

          try{
              PrintWriter dW = new PrintWriter("date.txt");
              dW.println(formatted);
              dW.close();
          } catch (IOException e) {
          }

          System.out.println(formDat.parse(formatted));

      } else { //if it does exist, second part

          //Get current date and time
          Calendar currentDeT = Calendar.getInstance();
          System.out.println("Current date: " + currentDeT.getTime());
          SimpleDateFormat formDat2 = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");

          Date dateFroText = null; //Get the "goal" date
          try {
              Scanner dateRead = new Scanner(dFileD);
              while (dateRead.hasNextLine()) {
                  date = dateRead.nextLine();
                  dateFroText = formDat2.parse(date);
                  System.out.println("Date from text new format: " + dateFroText);
              }
              dateRead.close();
            } catch (Exception e) {
                System.out.println("Error!");
            }

          if (dateFroText != null){ //method to compare the current date and the goal date
              Calendar dateFromTxtCal = Calendar.getInstance();
              dateFromTxtCal.setTime(dateFroText);
          int yearDiff = dateFromTxtCal.get(Calendar.YEAR) - currentDeT.get(Calendar.YEAR);
          int dayDiff = ((yearDiff*365) + dateFromTxtCal.get(Calendar.DAY_OF_YEAR)) - currentDeT.get(Calendar.DAY_OF_YEAR);
          dayDiff--;
          int hourDiffer = dateFromTxtCal.get(Calendar.HOUR_OF_DAY)+23 - currentDeT.get(Calendar.HOUR_OF_DAY);
          int minuDiff = dateFromTxtCal.get(Calendar.MINUTE)+60 - currentDeT.get(Calendar.MINUTE);
          int secoDiff = dateFromTxtCal.get(Calendar.SECOND)+60 - currentDeT.get(Calendar.SECOND);
          System.out.println(dayDiff + " days " + hourDiffer + " hours " + minuDiff +" minutes " + secoDiff + "seconds remaining");
          }

      }

  }

Body:
Avoid legacy date-time classe

You are working too hard. And you are using troublesome old date-time classes now obsoleted and supplanted by the java.time classes.

Work in UTC

Also, if you only care about the next 24 hours, then no need for time zones. Just use UTC.

Instant

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instantNow = Instant.now();

Duration

A span of time unattached to the timeline is represented by the Duration or Period classes.

Duration duration = Duration.ofHours( 24 );

You can perform date-time math, adding a Duration to an Instant. The java.time classes use immutable objects, so the result of such manipulations is a fresh object with values based on the original.

Instant instantLater = instantNow.plus( duration );

ISO 8601

To serialize date-time values such as those to text, use the standard ISO 8601 formats. The java.time classes use ISO 8601 by default when generating and parsing strings.

String output = instantNow.toString();

2017-04-03T03:18:48.183Z

Calculate remaining time

To get the remaining time, let java.time do the math.

Duration remaining = Duration.between( Instant.now() , instantLater );

To report that in standard ISO 8601 format, call toString. The format for durations is PnYnMnDTnHnMnS. The P marks the beginning (for Period), and the T separates any years-months-dates from hours-minutes-seconds.

String outputRemaining = remaining.toString();

PT23H34M22S

To generate a longer string, in Java 9 call the to…Part method for each unit (hours, minutes, seconds). Oddly those methods were omitted from the original java.time.Duration class in Java 8. You could look to the source code of Java 9 to write similar code.

Or more simply, manipulate the standard string. Delete the PT. Replace the H with hours and so on. Do S first to avoid the plural s in the other two words. Admittedly this is kind of a hack, but it works thanks to some good luck in the occurrence of letters is the English spelling of hours-minutes-seconds.

String output = remaining.toString()
                         .replace( "PT" , "" )
                         .replace( "S" , " seconds " )
                         .replace( "H" , " hours " )
                         .replace( "M" , " minutes " ) ;

23 hours 34 minutes 22 seconds

ZonedDateTime

If you want to display the target date-time in the user's desired/expected time zone, apply a ZoneId to get a ZonedDateTime object.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

To generate a string in standard format, call toString. Actually the ZonedDateTime class extends the standard by appending the name of the time zone in square brackets.

To generate strings in other formats, search Stack Overflow for many examples of DateTimeFormatter class.

Converting to java.util.Date

The Timer class has not yet been updated to work with the java.time types. So convert back to a Date object via new methods added to the old classes, in this case from.

java.util.Date date = java.util.Date.from( instantLater );

Or use a count of milliseconds from the Duration object.

long milliseconds = duration.toMillis() ;

ScheduledExecutorService

FYI, the Timer and TimeTask classes have been supplanted by the Executors framework. Specifically for your purpose, the ScheduledExecutorService. Search Stack Overflow for many examples and discussions.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Java SE 8 and SE 9 and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and SE 7

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

Android

The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.

See How to use ThreeTenABP….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


问:
Sweet Alert for Laravel 5.4 Error: Class '‘Alerts' not found
I'm trying to install the Sweet Alert package for Laravel: https://github.com/socieboy/alerts. I'm using Laravel 5.4.

I've followed all the directions exactly as outlined on the GitHub page, but I'm getting an error when I try to load any page that uses the master.blade.php template: "Class '‘Alerts' not found."

Has anyone else run into this? Is this package not compatible with v5.4?

Also, it seems like there is another Sweet Alert package for Laravel: https://github.com/uxweb/sweet-alert Does one replace the other? Is there any difference between the two?

Thanks

答: The error had to do with how some partials for my header were being pulled in. Nothing to do with Sweet Alert. Problem solved. </p>


问:
Background image clipped to draggable div
i'm trying to make this thing where i have a div with a full background image and a div on top with a container, and this div is draggable, and when dragged it shows the same image as the background but altered.

Well, something among the lines of this pen

My CSS so far:

```<code>.contain{
    position:relative;
}

#dummy{
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}
</code>```

答:
For what I assume you want to do I've edited your pen to reflect the proper changes. You can see it here.

Improper Nesting
First thing changed was switching the div you wanted draggable

 to be a child of the

 element.

CSS Image URLs
Just another thing to look out for - when specifying a URL in CSS you need to wrap it within quotation marks. These " $url_here ".

Body:
i'm trying to make this thing where i have a div with a full background image and a div on top with a container, and this div is draggable, and when dragged it shows the same image as the background but altered.

Well, something among the lines of this pen

My CSS so far:

.contain{
    position:relative;
}

#dummy{
    background:url(http://i.imgur.com/CxYGDBq.jpg);
    background-attachment:fixed;
    background-repeat:no-repeat;
    background-size:cover;
    position:absolute;
    top:0;
    left:0;
}

#dummy2{
    position:absolute;
    top:0;
    z-index:99;
    left:0;
}

.mao{
    background: url(http://i.imgur.com/UbNyhzS.png);
    width:250px;
    height:300px;
    position:absolute;
    bottom:0;
    z-index:999;
    background-size:contain;
}

.screen{
    width:960px;
    height:995px;
    background-color:pink;
    position:relative;
    left:32px;
    top:30px;
    background-attachment:fixed;
    background: url(http://i.imgur.com/yjR8SCL.jpg);

}

Body:
For what I assume you want to do I've edited your pen to reflect the proper changes. You can see it here.

Improper Nesting
First thing changed was switching the div you wanted draggable <div class="mao"></div> to be a child of the <div class="screen"></div> element.

CSS Image URLs
Just another thing to look out for - when specifying a URL in CSS you need to wrap it within quotation marks. These " $url_here ".


问:
Hierarchical select module issue in drupal
i am using 'Hierarchical select' module in Drupal to create 2 drop down of States and cities and connecting the city ones to state in a way by changing the state,the list of cities changes too.(it is beside of CCK and taxonomy content module)

The problem is that by selecting the state and city for a new content,just the city shown.but i need both of them,State - city combination.

答:
Hierarchical select is UI representation of hierarchical structure of vocabulary that is normally shown in a flat list.

From a single vocabulary (if multi select is disabled) you can select only one term. Selecting a leaf would not enlist parent tids.

Use taxonomy_get_parents() or taxonomy_get_parents_all() functions.


问:
Unable to load DLL 'SqlServerSpatial140.dll': The specified module could not be found
This all new to me, so bear with me...

I'm working on a Visual Studio project; it's a web service that returns some data.

I've just tried to make a particular call to the web server on my local machine (IIS) and I'm getting this error:

Unable to load DLL 'SqlServerSpatial140.dll': The specified module
  could not be found

Before anyone says it - yes, obviously I am missing this DLL file. I've searched online and don't see where I could download it from (I have Microsoft SQL Server System CLR Types (x64) and non-X64 both installed. I have Microsoft System CLR Types for SQL Server 2014 and 2016 both installed)

Does anyone know how to fix this? Does anyone know if I can just download this file from somewhere?

答:
When you install the Microsoft.SqlServer.Types nuget package, this should create a new folder in root:

```<code>\SqlServerTypes
   |_x64
   |_x86
</code>```

which should contain the appropriate dll's. It's also auto setup to copy if newer.

Then, make sure your app loads the appropriate assembly:

For ASP.NET Web Applications: SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));

For desktop applications / others: SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

Not sure if this works with .NET Core though.

Body:
When you install the Microsoft.SqlServer.Types nuget package, this should create a new folder in root:

\SqlServerTypes
   |_x64
   |_x86

which should contain the appropriate dll's. It's also auto setup to copy if newer.

Then, make sure your app loads the appropriate assembly:

For ASP.NET Web Applications: SqlServerTypes.Utilities.LoadNativeAssemblies(Server.MapPath("~/bin"));

For desktop applications / others: SqlServerTypes.Utilities.LoadNativeAssemblies(AppDomain.CurrentDomain.BaseDirectory);

Not sure if this works with .NET Core though.


问:
How do I correctly enforce Javascript Validation in HTML Form?
I'm having a hard time enforcing the JavaScript parameters I have put into my HTML Form. Essentially I want all the parameters satisfied, before a successful submission of the HTML Form, into my Google SpreadSheet.

What is happening now, is that my HTML form can be submitted (with the exception of email validation) directly into my Google Spreadsheet, without going through my JavaScript parameters. How do I fix this?

```<code><!DOCTYPE html>

<title>Sample Site</title>

<!-- STYLE STARTS HERE -->
   <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
   <!-- Style The Contact Form How Ever You Prefer -->
   <link rel="stylesheet" href="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/style.css">
<!-- STYLE ENDS HERE -->

<!-- The CULPRIT -->
  <form id="gform" method="POST" class="pure-form pure-form-stacked"
  action="https://script.google.com/macros/s/AKfycbxjs3igiMCNaHOjBtsiujnGmMpGz_L57LOS7qzegOWpSQ2cyWq-/exec">

<!-- CULPRIT -->

<header class="entry-header">
<h1 class="entry-title">Something Else</h1>
</header>

<!-- .entry-header -->
<div class="entry-content">
<form method="post" action="checkout/" autocomplete="off" onsubmit="return isValidForm()">
<label for="buyer_email" style="font-weight: bold">Email:</label><p></p>
<p></p>
<p> <input id="buyer_email" name="buyer_email" placeholder="yourpersonalemail@gmail.com"
size="50" onfocus="removeHighlightEmail()" required="" type="text"></p>
<p> <label for="links_string" style="font-weight: bold">Course Hero links:</label></p>
<p></p>

<p> <textarea cols="200" id="links_string" name="links_string"
placeholder="https://www.coursehero.com/file/6007102/Tutorial-91-92-Gauss-Law/"
onfocus="removeHighlightTextArea()" oninput="checkTutor()" rows="7" required=""></textarea></p>
<p></p>

<div id="info_text"></div>
<p></p>
<p> <input value="Pay" type="submit"><br></p>
</form>
<span class="" style="display:block;clear:both;height:
0px;padding-top: 100px;border-top-width:0px;border-bottom-width:0px;"></span>
<p style="visibility: hidden;">.</p>

<!-- Lightbox Plus Colorbox v2.7.2/1.5.9 - 2013.01.24 - Message: 1-->
<script type="text/javascript">
jQuery(document).ready(function($){
  $("a[rel*=lightbox]").colorbox({initialWidth:"30%",initialHeight:"30%",maxWidth:"90%",maxHeight:"90%",opacity:0.8});
  $(".popup").colorbox({speed:300,width:"80%",height:"90%",innerWidth:"50%",innerHeight:"50%",initialWidth:"30%",initialHeight:"40%",maxWidth:"90%",maxHeight:"90%",opacity:0.5,iframe:true});
});
</script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/jquery_005.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var _wpcf7 = {"loaderUrl":"http:\/\/docunlocks.com\/wp-content\/plugins\/contact-form-7\/images\/ajax-loader.gif","recaptchaEmpty":"Please verify that you are not a robot.","sending":"Sending ..."};
/* ]]> */
</script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/scripts.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/jquery_003.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/jquery_004.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/helpers-functions.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/helpers_002.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/helpers-beaver.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/skip-link-focus-fix.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/getcoursehero.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/jquery_002.js"></script>
<script type="text/javascript" src="Unlock%20Documents%20%E2%80%93%20Doc%20Unlocks_files/wp-embed.js"></script>
</code>```

getcoursehero.js

```<code> function validateEmail() {
        var email = document.getElementById("buyer_email").value;
        var textInvalidEmail = document.getElementById("text_invalid_email");
        var valid = false;

        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(re.test(email)){
            valid = true;
        }

        return valid;
    }

    function validateLinks(){
        var links = document.getElementById("links_string").value;
        var valid = false;

        var reg = /((https:\/\/)?(www.)?(coursehero.com\/)(tutors-problems|file)\/[a-z0-9\-+]+(\/)[a-z0-9\-\%]+(\/)?)/gi;

        if(links.match(reg)){
            valid = true;
        }

        return valid;
    }

    function removeHighlightEmail(){
        document.getElementById("buyer_email").style.boxShadow = "none";
    }

    function removeHighlightTextArea(){
        document.getElementById("links_string").style.boxShadow = "none";
    }

    function isValidForm(){
        var result = true;

        if(!validateEmail()){
            document.getElementById("buyer_email").style.boxShadow = "0px 0px 5px red";
            result = false;
        }

        if(!validateLinks()){
            document.getElementById("links_string").style.boxShadow = "0px 0px 5px red";
            result = false;
        }

        return result;
    }

    function checkTutor(){
        var links = document.getElementById("links_string").value;

        var reg = /((https:\/\/)?(www.)?(coursehero.com\/)(tutors-problems)\/[a-z0-9\-+]+(\/)[a-z0-9\-\%]+(\/)?)/gi;

        if(links.match(reg)){
            document.getElementById("info_text").innerHTML = "<p>Before proceeding further, make sure the tutor-problem question(s) has been answered and make sure there's a file attachment in the solution (very important). <a target=\"_blank\" style=\"text-decoration: underline;\" href=\"https://www.coursehero.com/tutors-problems/Java-Programming/8788216-iLab-5-of-6-GUI-Graphics-and-File-IO-40-points-0243-PM-MT-09282/\">Click here</a> to see an example of a valid tutor-problem question (scroll down and notice that there's a file attachment in the tutor answer). You may proceed to the next step after this verification.</p>";
            //document.getElementById("info_text").style.color = "#199cd8";
            document.getElementById("info_text").style.color = "red";
        }else{
            document.getElementById("info_text").innerHTML = "";
    }
}
</code>```

答:
I look at your code and it looks you need you are missing to set the name's property of your form.

```<code><form method="post" name="yourFormsName" action="checkout/" autocomplete="off"
 onsubmit="return isValidForm()">
</code>```

I did a testing with this page to test my point.

https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js

if you delete the name property it will not validate.

Hope it helps.

Body:
I'm having a hard time enforcing the JavaScript parameters I have put into my HTML Form. Essentially I want all the parameters satisfied, before a successful submission of the HTML Form, into my Google SpreadSheet.

What is happening now, is that my HTML form can be submitted (with the exception of email validation) directly into my Google Spreadsheet, without going through my JavaScript parameters. How do I fix this?

<!DOCTYPE html>

<title>Sample Site</title>

   <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.6.0/pure-min.css">
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

   <link rel="stylesheet" href="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/style.css">

  <form id="gform" method="POST" class="pure-form pure-form-stacked"
  action="https://script.google.com/macros/s/AKfycbxjs3igiMCNaHOjBtsiujnGmMpGz_L57LOS7qzegOWpSQ2cyWq-/exec">

Something Else

<form method="post" action="checkout/" autocomplete="off" onsubmit="return isValidForm()">
Email:

 <input id="buyer_email" name="buyer_email" placeholder="yourpersonalemail@gmail.com"
size="50" onfocus="removeHighlightEmail()" required="" type="text">

 Course Hero links:

 <textarea cols="200" id="links_string" name="links_string"
placeholder="https://www.coursehero.com/file/6007102/Tutorial-91-92-Gauss-Law/"
onfocus="removeHighlightTextArea()" oninput="checkTutor()" rows="7" required=""></textarea>

 <input value="Pay" type="submit">

</form>

.

getcoursehero.js

 function validateEmail() {
        var email = document.getElementById("buyer_email").value;
        var textInvalidEmail = document.getElementById("text_invalid_email");
        var valid = false;

        var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if(re.test(email)){
            valid = true;
        }

        return valid;
    }

    function validateLinks(){
        var links = document.getElementById("links_string").value;
        var valid = false;

        var reg = /((https:\/\/)?(www.)?(coursehero.com\/)(tutors-problems|file)\/[a-z0-9\-+]+(\/)[a-z0-9\-\%]+(\/)?)/gi;

        if(links.match(reg)){
            valid = true;
        }

        return valid;
    }

    function removeHighlightEmail(){
        document.getElementById("buyer_email").style.boxShadow = "none";
    }

    function removeHighlightTextArea(){
        document.getElementById("links_string").style.boxShadow = "none";
    }

    function isValidForm(){
        var result = true;

        if(!validateEmail()){
            document.getElementById("buyer_email").style.boxShadow = "0px 0px 5px red";
            result = false;
        }

        if(!validateLinks()){
            document.getElementById("links_string").style.boxShadow = "0px 0px 5px red";
            result = false;
        }

        return result;
    }

    function checkTutor(){
        var links = document.getElementById("links_string").value;

        var reg = /((https:\/\/)?(www.)?(coursehero.com\/)(tutors-problems)\/[a-z0-9\-+]+(\/)[a-z0-9\-\%]+(\/)?)/gi;

        if(links.match(reg)){
            document.getElementById("info_text").innerHTML = "
Before proceeding further, make sure the tutor-problem question(s) has been answered and make sure there's a file attachment in the solution (very important). Click here to see an example of a valid tutor-problem question (scroll down and notice that there's a file attachment in the tutor answer). You may proceed to the next step after this verification.
";
            //document.getElementById("info_text").style.color = "#199cd8";
            document.getElementById("info_text").style.color = "red";
        }else{
            document.getElementById("info_text").innerHTML = "";
    }
}

Body:
I look at your code and it looks you need you are missing to set the name's property of your form.

<form method="post" name="yourFormsName" action="checkout/" autocomplete="off"
 onsubmit="return isValidForm()">

I did a testing with this page to test my point.

https://www.w3schools.com/js/tryit.asp?filename=tryjs_validation_js

if you delete the name property it will not validate.

Hope it helps.


问:
How to get the image of a transparent element without source?
I see an element in a HTML5 game which can be rotated, hidden and moved.
But it has a background... And the element is transparent.

For example, this moves the element:

```<code>$("#elementr2").animate({left: '650px'});
</code>```

I can capture it perfectly because it is transparent.

What could I do?

答:
Okay... If you can do this:

```<code>$("#elementr2").animate({left: '650px'});
</code>```

Then, you can set a perfect white background covering the whole screen and bring only the wanted element above it.

```<code>// This will set a white background.
var myBackground = $("<div>").attr("style","width:100%;"+
                                   "height:100%;"+
                                   "top:0;"+
                                   "right:0;"+
                                   "bottom:0;"+
                                   "left:0;"+
                                   "background-color:#FFF;"+
                                   "position:fixed;"+
                                   "z-index:999999;"
                                  );

// This will bring the element you want above the background.
$("body").append(myBackground);
$("#elementr2").css({"position":"fixed",
                     "z-index":"1000000",
                    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I see an element in a HTML5 game which can be rotated, hidden and moved.
But it has a background... And the element is transparent.

For example, this moves the element:

$("#elementr2").animate({left: '650px'});

I can capture it perfectly because it is transparent.

What could I do?

Body:
Okay... If you can do this:

$("#elementr2").animate({left: '650px'});

Then, you can set a perfect white background covering the whole screen and bring only the wanted element above it.

// This will set a white background.
var myBackground = $("<div>").attr("style","width:100%;"+
                                   "height:100%;"+
                                   "top:0;"+
                                   "right:0;"+
                                   "bottom:0;"+
                                   "left:0;"+
                                   "background-color:#FFF;"+
                                   "position:fixed;"+
                                   "z-index:999999;"
                                  );

// This will bring the element you want above the background.
$("body").append(myBackground);
$("#elementr2").css({"position":"fixed",
                     "z-index":"1000000",
                    });


问:
Python divide a list of ints on every recurring specific int in list
How can I change a list like

[30,20,0,48,20,10,20,0,30]

to:

[[30,20],[48,20,10,20],[30]]

by dividing it everytime there is a 0 in the list? I have tried many ways but they all take up too much lines to make sense (10 lines). I have looked at many list-splitting questions on stack overflow and I cant find anything that works.

EDIT:

I was asking if there was any way to do list.split(0) or something like that, but it appears that the answer is that there is no way to do that. I wanted to know if I can do it in one line or if there is any way I can use a common module. I have already tried doing it in multiple lines, it has worked, but I think it is inconvenient.

EDIT 2:

The code I tried was:

```<code>list = [30,20,0,48,20,10,20,0,30]  #1, 1 list
newlist = []                       #2, 2 lists
addinglist = []                    #3, 3 lists
for x in list:                     #4
    if x == 0:                     #5
        newlist.append(addinglist) #6
        addinglist = []            #7
    else:                          #8
        addinglist.append(x)       #9
newlist.append(addinglist)         #10
list = newlist                     #11 lines, 3 lists.
print(addinglist)
</code>```

The code requires 11 lines and 3 lists (one getting modified and the other two are useless).

答:
As TigerhawkT3 said:

Starting a result list, starting a running list, appending to the
  running list as long as a condition holds true, and appending the
  current list and starting a new one every time it doesn't is a very
  common task. Please demonstrate that you've tried something yourself
  first.

In fact, it is such an easy task, that it is possible to do it in 4 readeable lines of Python code:

```<code>final=[]
for elem in [0]+x:
    if elem == 0: final.append([])
    else: final[-1].append(elem)
</code>```

Where x is your list.

The purpose of this answer is not to tell you how to do it. But to tell you that with any related code that you could have posted, (and not necessarily working), this answer would have been more accepted.

In conclusion:

Remember to show your research, just saying to have made the effort does not count, it is not that difficult to copy and paste whatever you have found/made.

Body:
How can I change a list like

[30,20,0,48,20,10,20,0,30]

to:

[[30,20],[48,20,10,20],[30]]

by dividing it everytime there is a 0 in the list? I have tried many ways but they all take up too much lines to make sense (10 lines). I have looked at many list-splitting questions on stack overflow and I cant find anything that works.

EDIT:

I was asking if there was any way to do list.split(0) or something like that, but it appears that the answer is that there is no way to do that. I wanted to know if I can do it in one line or if there is any way I can use a common module. I have already tried doing it in multiple lines, it has worked, but I think it is inconvenient.

EDIT 2:

The code I tried was:

list = [30,20,0,48,20,10,20,0,30]  #1, 1 list
newlist = []                       #2, 2 lists
addinglist = []                    #3, 3 lists
for x in list:                     #4
    if x == 0:                     #5
        newlist.append(addinglist) #6
        addinglist = []            #7
    else:                          #8
        addinglist.append(x)       #9
newlist.append(addinglist)         #10
list = newlist                     #11 lines, 3 lists.
print(addinglist)

The code requires 11 lines and 3 lists (one getting modified and the other two are useless).

Body:
As TigerhawkT3 said:

Starting a result list, starting a running list, appending to the
  running list as long as a condition holds true, and appending the
  current list and starting a new one every time it doesn't is a very
  common task. Please demonstrate that you've tried something yourself
  first.

In fact, it is such an easy task, that it is possible to do it in 4 readeable lines of Python code:

final=[]
for elem in [0]+x:
    if elem == 0: final.append([])
    else: final[-1].append(elem)

Where x is your list.

The purpose of this answer is not to tell you how to do it. But to tell you that with any related code that you could have posted, (and not necessarily working), this answer would have been more accepted.

In conclusion:

Remember to show your research, just saying to have made the effort does not count, it is not that difficult to copy and paste whatever you have found/made.


问:
nodejs + mqlight connection error
I am using nodejs with mqlight to run a sample code which is provided by https://www.npmjs.com/package/mqlight.

I am using nodejs 5.5.0 and npm version is 3.3.12.

I installed mqlight using ```npm install mqlight```.

```

    var mqlight = require('mqlight');
    var recvClient = mqlight.createClient({service: 'amqp://localhost'});
    var topicPattern = 'public';
    recvClient.on('started', function() {
      recvClient.subscribe(topicPattern);
      recvClient.on('message', function(data, delivery) {
        console.log('Recv: %s', data);
      });
    });

    var sendClient = mqlight.createClient({service: 'amqp://localhost'});

    var topic = 'public';
    sendClient.on('started', function() {
      sendClient.send(topic, 'Hello World!', function (err, data) {
        console.log('Sent: %s', data);
        sendClient.stop();
      });
    });

```

While I am running above code I got below error.

```

     E:\nodejs>node mqtest.js

    events.js:154
          throw er; // Unhandled 'error' event
          ^
     NetworkError: CONNECTION ERROR (localhost:5672): Connect failure: The remote co
    mputer refused the network connection.
        at Socket.connError (E:\nodejs\node_modules\mqlight\mqlight.js:1437:19)
        at emitOne (events.js:90:13)
        at Socket.emit (events.js:182:7)
        at emitErrorNT (net.js:1255:8)
        at nextTickCallbackWith2Args (node.js:474:9)
        at process._tickCallback (node.js:388:17)

```

Please help to solve this problem. I am using window 7 64 bit os.

答:
Are you sure the service amqp is running? You can follow the below script to start amqp service.</p>

```<code>START SERVICE(SYSTEM.AMQP.SERVICE)
START CHANNEL(SYSTEM.DEF.AMQP)
REFRESH SECURITY TYPE(CONNAUTH)
DISPLAY CHSTATUS(SYSTEM.DEF.AMQP) CHLTYPE(AMQP)
</code>```

Title: nodejs + mqlight connection error

Body:
I am using nodejs with mqlight to run a sample code which is provided by https://www.npmjs.com/package/mqlight.

I am using nodejs 5.5.0 and npm version is 3.3.12.

I installed mqlight using
npm install mqlight
.

    var mqlight = require('mqlight');
    var recvClient = mqlight.createClient({service: 'amqp://localhost'});
    var topicPattern = 'public';
    recvClient.on('started', function() {
      recvClient.subscribe(topicPattern);
      recvClient.on('message', function(data, delivery) {
        console.log('Recv: %s', data);
      });
    });

    var sendClient = mqlight.createClient({service: 'amqp://localhost'});

    var topic = 'public';
    sendClient.on('started', function() {
      sendClient.send(topic, 'Hello World!', function (err, data) {
        console.log('Sent: %s', data);
        sendClient.stop();
      });
    });

While I am running above code I got below error.

     E:\nodejs>node mqtest.js

    events.js:154
          throw er; // Unhandled 'error' event
          ^
     NetworkError: CONNECTION ERROR (localhost:5672): Connect failure: The remote co
    mputer refused the network connection.
        at Socket.connError (E:\nodejs\node_modules\mqlight\mqlight.js:1437:19)
        at emitOne (events.js:90:13)
        at Socket.emit (events.js:182:7)
        at emitErrorNT (net.js:1255:8)
        at nextTickCallbackWith2Args (node.js:474:9)
        at process._tickCallback (node.js:388:17)

Please help to solve this problem. I am using window 7 64 bit os.

Body:
Are you sure the service amqp is running? You can follow the below script to start amqp service.

START SERVICE(SYSTEM.AMQP.SERVICE)
START CHANNEL(SYSTEM.DEF.AMQP)
REFRESH SECURITY TYPE(CONNAUTH)
DISPLAY CHSTATUS(SYSTEM.DEF.AMQP) CHLTYPE(AMQP)


问:
Custom list class in Python 3 with __get__ and __set__ attributes
I would like to write a custom list class in Python 3 like in this question How would I create a custom list class in python?, but unlike that question I would like to implement __get__ and __set__ methods. Although my class is similar to the list, but there are some magic operations hidden behind these methods. And so I would like to work with this variable like with list, like in main of my program (see below). I would like to know, how to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class.

My current solution (also, I added output for each operation for clarity):

```<code>class MyList:

    def __init__(self, data=[]):
        print('MyList.__init__')
        self._mylist = data

    def __getitem__(self, key):
        print('MyList.__getitem__')
        return self._mylist[key]

    def __setitem__(self, key, item):
        print('MyList.__setitem__')
        self._mylist[key] = item

    def __str__(self):
        print('MyList.__str__')
        return str(self._mylist)

class Foo:

    def __init__(self, mylist=[]):
        self._mylist = MyList(mylist)

    def fget(self):
        print('Foo.fget')
        return self._mylist

    def fset(self, data):
        print('Foo.fset')
        self._mylist = MyList(data)

    mylist = property(fget, fset, None, 'MyList property')

if __name__ == '__main__':
    foo = Foo([1, 2, 3])
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3]
    foo.mylist = [1, 2, 3, 4]
    # >>> Foo.fset
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3, 4]
    foo.mylist[0] = 0
    # >>> Foo.fget
    # >>> MyList.__setitem__
    print(foo.mylist[0])
    # >>> Foo.fget
    # >>> MyList.__getitem__
    # >>> 0
</code>```

Thank you in advance for any help.

How to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class?

UPD:

Thanks a lot to @Blckknght! I tried to understand his answer and it works very well for me! It's exactly what I needed. As a result, I get the following code:

```<code>class MyList:
    def __init__(self, value=None):
        self.name = None
        if value is None:
            self.value = []
        else:
            self.value = value

    def __set_name__(self, owner, name):
        self.name = "_" + name

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

    def __set__(self, instance, value):
        setattr(instance, self.name, MyList(value))

    def __getitem__(self, key):
        return self.value[key]

    def __setitem__(self, key, value):
        self.value[key] = value

    def append(self, value):
        self.value.append(value)

    def __str__(self):
        return str(self.value)

class Foo:
    my_list = MyList()

    def __init__(self):
        self.my_list = [1, 2, 3]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list = [4, 5, 6, 7, 8]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list[0] = 10
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list.append(7)
        print(type(self.my_list))       # <class '__main__.MyList'>
        print(self.my_list)             # [10, 5, 6, 7, 8, 7]

foo = Foo()
</code>```

I don't know, that's Pythonic way or not, but it works as I expected.

答:
In a comment, you explained what you actually want:

```<code>x = MyList([1])
x = [2]
# and have x be a MyList after that.
</code>```

That is not possible.  In Python, plain assignment to a bare name (e.g., x = ..., in contrast to x.blah = ... or x[0] = ...) is an operation on the name only, not the value, so there is no way for any object to hook into the name-binding process.  An assignment like x = [2] works the same way no matter what the value of x is (and indeed works the same way regardless of whether x already has a value or whether this is the first value being assigned to x).

Body:
I would like to write a custom list class in Python 3 like in this question How would I create a custom list class in python?, but unlike that question I would like to implement __get__ and __set__ methods. Although my class is similar to the list, but there are some magic operations hidden behind these methods. And so I would like to work with this variable like with list, like in main of my program (see below). I would like to know, how to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class.

My current solution (also, I added output for each operation for clarity):

class MyList:

    def __init__(self, data=[]):
        print('MyList.__init__')
        self._mylist = data

    def __getitem__(self, key):
        print('MyList.__getitem__')
        return self._mylist[key]

    def __setitem__(self, key, item):
        print('MyList.__setitem__')
        self._mylist[key] = item

    def __str__(self):
        print('MyList.__str__')
        return str(self._mylist)

class Foo:

    def __init__(self, mylist=[]):
        self._mylist = MyList(mylist)

    def fget(self):
        print('Foo.fget')
        return self._mylist

    def fset(self, data):
        print('Foo.fset')
        self._mylist = MyList(data)

    mylist = property(fget, fset, None, 'MyList property')

if __name__ == '__main__':
    foo = Foo([1, 2, 3])
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3]
    foo.mylist = [1, 2, 3, 4]
    # >>> Foo.fset
    # >>> MyList.__init__
    print(foo.mylist)
    # >>> Foo.fget
    # >>> MyList.__str__
    # >>> [1, 2, 3, 4]
    foo.mylist[0] = 0
    # >>> Foo.fget
    # >>> MyList.__setitem__
    print(foo.mylist[0])
    # >>> Foo.fget
    # >>> MyList.__getitem__
    # >>> 0

Thank you in advance for any help.

How to move __get__ and __set__ methods (fget and fset respectively) from Foo class to MyList class to have only one class?

UPD:

Thanks a lot to @Blckknght! I tried to understand his answer and it works very well for me! It's exactly what I needed. As a result, I get the following code:

class MyList:
    def __init__(self, value=None):
        self.name = None
        if value is None:
            self.value = []
        else:
            self.value = value

    def __set_name__(self, owner, name):
        self.name = "_" + name

    def __get__(self, instance, owner):
        return getattr(instance, self.name)

    def __set__(self, instance, value):
        setattr(instance, self.name, MyList(value))

    def __getitem__(self, key):
        return self.value[key]

    def __setitem__(self, key, value):
        self.value[key] = value

    def append(self, value):
        self.value.append(value)

    def __str__(self):
        return str(self.value)

class Foo:
    my_list = MyList()

    def __init__(self):
        self.my_list = [1, 2, 3]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list = [4, 5, 6, 7, 8]
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list[0] = 10
        print(type(self.my_list))       # <class '__main__.MyList'>
        self.my_list.append(7)
        print(type(self.my_list))       # <class '__main__.MyList'>
        print(self.my_list)             # [10, 5, 6, 7, 8, 7]

foo = Foo()

I don't know, that's Pythonic way or not, but it works as I expected.

Body:
In a comment, you explained what you actually want:

x = MyList([1])
x = [2]
# and have x be a MyList after that.

That is not possible.  In Python, plain assignment to a bare name (e.g., x = ..., in contrast to x.blah = ... or x[0] = ...) is an operation on the name only, not the value, so there is no way for any object to hook into the name-binding process.  An assignment like x = [2] works the same way no matter what the value of x is (and indeed works the same way regardless of whether x already has a value or whether this is the first value being assigned to x).


问:
Cufon multiple fonts - How?
I am trying to implement 2 cufon fonts on the same page for the first time. Its not working.

In the documentation this is provided as an example:

```<code>            <script src="Vegur_300.font.js" type="text/javascript"></script>
    <script src="Myriad_Pro_400.font.js" type="text/javascript"></script>
    <script type="text/javascript">
                    Cufon.replace('h1', { fontFamily: 'Vegur' });
        Cufon.replace('h2', { fontFamily: 'Myriad Pro' });
    </script>
</code>```

The thing I dont understand is - what is the link between fontFamily: 'Vegur' and the actual Vegur_300.font.js file?

In other words, how does the browser know that 'Vegur' is that particular file?

thanks in advance

答:
```<code><script src="Vegur_300.font.js" type="text/javascript"></script>
<script type="text/javascript">
  Cufon.replace('h1');
</script>

<script src="Myriad_Pro_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
  Cufon.replace('h2');
</script>
</code>```

This worked for me.

Title: Cufon multiple fonts - How?

Body:
I am trying to implement 2 cufon fonts on the same page for the first time. Its not working.

In the documentation this is provided as an example:

The thing I dont understand is - what is the link between fontFamily: 'Vegur' and the actual Vegur_300.font.js file?

In other words, how does the browser know that 'Vegur' is that particular file?

thanks in advance

Body:
<script src="Vegur_300.font.js" type="text/javascript"></script>
<script type="text/javascript">
  Cufon.replace('h1');
</script>

<script src="Myriad_Pro_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
  Cufon.replace('h2');
</script>

This worked for me.


问:
How to change 1,000,000 price to 1,XXX,XXX using php or javascript?
This is my source code:

```<code>preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));
</code>```

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

答:
Here are a couple of straightforward ways to do it in JavaScript:

var input = "1,000,000"
var output = input.substr(0,1) + input.substr(1).replace(/\d/g, 'x')
console.log(output)

// or:
var output2 = input.replace(/\d/g, function(m, i) { return i ? 'x' : m })
console.log(output2)```

(I assume you can convert at least the first one to PHP with no trouble if you'd rather do it server-side, though you did ask for PHP or JS.)

Body:
This is my source code:

preg_replace('/[A-Z0-9]/', 'X', number_format('1000000'));

Result: x,xxx,xxx

But, I want the result like 1,xxx,xxx, i.e., don't replace the first number.

Body:
Here are a couple of straightforward ways to do it in JavaScript:

var input = "1,000,000"
var output = input.substr(0,1) + input.substr(1).replace(/\d/g, 'x')
console.log(output)

// or:
var output2 = input.replace(/\d/g, function(m, i) { return i ? 'x' : m })
console.log(output2)

(I assume you can convert at least the first one to PHP with no trouble if you'd rather do it server-side, though you did ask for PHP or JS.)


问:
Is it possible to delete a marker 10 seconds after it's placed on map automatically?
I hope to add multiple markers to Google Map and have each one of them deleted permanently and automatically exactly 2 seconds after the marker is added. I saw someone suggesting to use PostDelayed for making marker blink. I would like to know if it's possible to do this for making them disappearing.

In addition to that, if this method actually works, will it be able to handle a large number of markers? If each PostDelayed creates one thread, I'm afraid that after a certain number of markers the performance would be severely slowed.

Please give me some advice on it. Thanks!

答:
Show marker

```<code>Marker restuarantMarkers = gMap.addMarker(new MarkerOptions()
                .position(latlng)
                .title("MyPlace").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).draggable(true));
</code>```

Hide marker

```<code>restuarantMarkers.setVisible(false);
</code>```

Use handler like that to hide marker

```<code>final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        // hide marker after 1000 millies means 1sec
      }
    }, 1000);
</code>```

Hope these helps you.

Body:
Show marker

Marker restuarantMarkers = gMap.addMarker(new MarkerOptions()
                .position(latlng)
                .title("MyPlace").icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pin)).draggable(true));

Hide marker

restuarantMarkers.setVisible(false);

Use handler like that to hide marker

final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        // hide marker after 1000 millies means 1sec
      }
    }, 1000);

Hope these helps you.


问:
undefined method `todo_lists' for nil:NilClass
Im in progress of developing a todolist app which the app will only show a user's todo list based on their user_id. Which means if a user logged in, the database will only show the todo list with the same user_id.

but im getting this error:

```<code>undefined method `todo_lists' for nil:NilClass

  # GET /todo_lists/new
def new
@todo_list = current_user.todo_lists.build
end
  # GET /todo_lists/1/edit
</code>```

todo_lists_controller.rb

```<code>class TodoListsController < ApplicationController
before_action :set_todo_list, only: [:show, :edit, :update, :destroy]

def index
@todo_lists = TodoList.all
end

def new
@todo_list = current_user.todo_lists.build
end

def create
@todo_list = current_user.todo_lists.build(todo_list_params)

respond_to do |format|
  if @todo_list.save
    format.html { redirect_to @todo_list, notice: 'Todo list was
successfully created.' }
    format.json { render :show, status: :created, location: @todo_list }
  else
    format.html { render :new }
    format.json { render json: @todo_list.errors, status: :unprocessable_entity }
  end
 end
end

private
def set_todo_list
  @todo_list = TodoList.find(params[:id])
end

def todo_list_params
  params.require(:todo_list).permit(:title, :description)
 end
end
</code>```

got other method like destroy, update, show and edit but i dont paste it here cuz i think it has nothing to do with this problem. i tried to change the todo_lists to other, like @todo_lists, TodoLists and todo_list but none of them work.

I search for the solution in various site but i dont find any. I really think that the main problem here is that i dont understand what code to write cuz i have different code with the same meaning like i stated above (@todo_lists and others). Kinda stupid but yeah, still tryin' here

P/S 2 months of learning rails ^^' sry for my broken english

答:
The problem is that current_user is nil.

If you are using devise, add before_action :authenticate_user! in your TodoListsController.

If not, then add similar code to your application_helper.rb

```<code>def current_user
   User.first
end
</code>```

Body:
Im in progress of developing a todolist app which the app will only show a user's todo list based on their user_id. Which means if a user logged in, the database will only show the todo list with the same user_id.

but im getting this error:

undefined method `todo_lists' for nil:NilClass

  # GET /todo_lists/new
def new
@todo_list = current_user.todo_lists.build
end
  # GET /todo_lists/1/edit

todo_lists_controller.rb

class TodoListsController < ApplicationController
before_action :set_todo_list, only: [:show, :edit, :update, :destroy]

def index
@todo_lists = TodoList.all
end

def new
@todo_list = current_user.todo_lists.build
end

def create
@todo_list = current_user.todo_lists.build(todo_list_params)

respond_to do |format|
  if @todo_list.save
    format.html { redirect_to @todo_list, notice: 'Todo list was
successfully created.' }
    format.json { render :show, status: :created, location: @todo_list }
  else
    format.html { render :new }
    format.json { render json: @todo_list.errors, status: :unprocessable_entity }
  end
 end
end

private
def set_todo_list
  @todo_list = TodoList.find(params[:id])
end

def todo_list_params
  params.require(:todo_list).permit(:title, :description)
 end
end

got other method like destroy, update, show and edit but i dont paste it here cuz i think it has nothing to do with this problem. i tried to change the todo_lists to other, like @todo_lists, TodoLists and todo_list but none of them work.

I search for the solution in various site but i dont find any. I really think that the main problem here is that i dont understand what code to write cuz i have different code with the same meaning like i stated above (@todo_lists and others). Kinda stupid but yeah, still tryin' here

P/S 2 months of learning rails ^^' sry for my broken english

Body:
The problem is that current_user is nil.

If you are using devise, add before_action :authenticate_user! in your TodoListsController.

If not, then add similar code to your application_helper.rb

def current_user
   User.first
end


问:
Don't understand excel formula embedded in VBA
Can someone please explain this Excel formula inside the VBA code.

```<code>Range("U8").FormulaR1C1 = _
=IF(ISNA(VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)=""True""),""No Title Found"",VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE))"
</code>```

I get that the IF is checking for the #N/A value. What I don't understand is what either of the VLOOKUPfunctions is doing exactly. What cell are being reference by the R1C1 notation? Why doesn't the column need to be specified? Then I don't get the 'C:\temp\MasterRecords.xls'!C2:C15 arguments. Thanks.

答:
Looking through what you have written lets break down the vlookup:

```<code>VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)
</code>```

RC[-1] = Lookup the value in 1 column to the left of current cell. (same row)

'C:\temp\MasterRecords.xls'!C2:C15 = Look for the data in C2:C15 (column 2 to column 15 of the masterRecords xl file.

14 = Returns the 14th column in the lookup range. Will return column 15 of the file.

FALSE = exact match.

Body:
Can someone please explain this Excel formula inside the VBA code.

Range("U8").FormulaR1C1 = _
=IF(ISNA(VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)=""True""),""No Title Found"",VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE))"

I get that the IF is checking for the #N/A value. What I don't understand is what either of the VLOOKUPfunctions is doing exactly. What cell are being reference by the R1C1 notation? Why doesn't the column need to be specified? Then I don't get the 'C:\temp\MasterRecords.xls'!C2:C15 arguments. Thanks.

Body:
Looking through what you have written lets break down the vlookup:

VLOOKUP(RC[-1],'C:\temp\MasterRecords.xls'!C2:C15,14,FALSE)

RC[-1] = Lookup the value in 1 column to the left of current cell. (same row)

'C:\temp\MasterRecords.xls'!C2:C15 = Look for the data in C2:C15 (column 2 to column 15 of the masterRecords xl file.

14 = Returns the 14th column in the lookup range. Will return column 15 of the file.

FALSE = exact match.


问:
What windows component implement functionality similar to readline?
In this question I'm asking of one specific bit of functionality of readline:

The Readline library includes additional functions to maintain a list of previously-entered command lines, to recall and perhaps reedit those lines

Now on Windows with Visual Studio you ain't need no stinking readline. You can use fgets and arrow keys will happily recall what you typed previously. Of course you can edit these too.

On linux the very same code (fgets in a loop ) does not work like this. Up arrow is shown as ^[[A and left and right arrows also does not allow you navigating the line as shown by experiment and also described here.

My question is, what part of Windows makes the editing possible?

I think it can be either conhost.exe or how fgets, et al, are implemented. Somehow I suspect that it's the former. In any case, I'd like to know how exactly it works if it's documented anywhere, etc. For example, what other keys, apart from arrows have a special meaning and processed differently instead of being returned as par of the buffer fgets writes to.

答:
The documentation for DOSKEY lists the special keys.

I am not aware of any documentation explaining that in 32-bit Windows this functionality is built into the console and that doskey.exe is merely an interface to it.  However, it is easy to confirm that this functionality does not depend on the running console application using the C runtime library or having been launched from the command-line shell.

It is a reasonable guess that the actual code implementing this feature lives inside conhost.exe on current versions of Windows, but of course that's an implementation detail, subject to change without notice.  From the programmer's perspective, all that matters is that DOSKEY functionality is present on any console window, and is available whenever the application is in cooked mode.

Note that cooked mode is the default setting.  Therefore, console applications will have DOSKEY functionality unless the application specifically disables it.


问:
how to count no of records in and display in view

This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

```<code>public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}
</code>```

model

```<code>function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}
</code>```

view

```<code><div class="inner">
<?php foreach ($h as $counts){?>
            <h3><?php echo $counts; ?></h3>
<?php } ?>
          <p>Total No. of Visitors till yet</p>
        </div>
</code>```

答:
Change Model by this

```<code>function visitor_count() {
    $query = $this->db->query("SELECT * FROM create_new_pass");
    return $query->num_rows();
}
</code>```

And change your view by this:

```<code><div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>
</code>```

Body:
This error will show when i want to display no. of records in a table.
  A PHP Error was encountered

Severity: Notice

Message: Undefined variable: h

Filename: views/index.php

A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: views/index.php

Controller

public function index() {
    if ($this->session->userdata('admin_logged_in')) {
        $data['h']= $this->admin_model->visitor_count();

        $this->load->view('header');
        $this->load->view('sidebar');
        $this->load->view('index',$data);
        $this->load->view('footer');
    } else {
        $this->load->view('login');
    }
}

model

function visitor_count() {
    $query = $this->db->query("SELECT COUNT(*) FROM create_new_pass");
    return $query->num_rows();
}

view

<?php foreach ($h as $counts){?>

<?php echo $counts; ?>

<?php } ?>

Total No. of Visitors till yet

Body:
Change Model by this

function visitor_count() {
    $query = $this->db->query("SELECT * FROM create_new_pass");
    return $query->num_rows();
}

And change your view by this:

<div class="inner">
    <h3><?php echo $h; ?></h3>
    <p>Total No. of Visitors till yet</p>
</div>


问:
Adding 1 to elements of an empty list using another list to count up (maybe with += ?)
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

```<code>input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]
</code>```

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

答:
You will have to loop through the data list, since you cannot pass a list to the index of a list (which is what the error is telling you).

Something like:

```<code>for ind in data:
    input[ind]+=1
</code>```

Note also that Python lists are 0-indexed, which means the first element is called using:

```<code>input[0]
</code>```

I notice you have 5's in your data list - there is no 5th element in your input - the indices are 0,1,2,3,4 so you'd need to modify your code (or input list) for it to run without an error.

Body:
I'm very new to python and programming, so please keep answers simple if you can.

I'm trying to create a script that will add 1 to elements in an empty list based on an unordered other list. My inputs are shown below as well as my desired output. Since 5 appears twice in the 'data' list, element 5 in 'input' should count up to 2.

Here's the code I tried, with the error it gives:

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

input[data] += 1

#desired output: [1, 1, 0, 0, 2]

The error this gives:

TypeError: list indices must be integers, not list

I'm confused, because I have a list of integers, but I guess that doesn't count as type 'int'. I searched to try to convert a list to integers, but all the solutions I found result in still having type 'list'. I'm thinking += might not be the right operator to use in this instance, but I'm not sure what else to use.

Edit: Oops, I forgot about lists starting at 0. Thanks for pointing that out, and thanks for all the great answers! Hard to choose just one.

Body:
You will have to loop through the data list, since you cannot pass a list to the index of a list (which is what the error is telling you).

Something like:

for ind in data:
    input[ind]+=1

Note also that Python lists are 0-indexed, which means the first element is called using:

input[0]

I notice you have 5's in your data list - there is no 5th element in your input - the indices are 0,1,2,3,4 so you'd need to modify your code (or input list) for it to run without an error.


答:
What you can do to speed things up is to use a collections.Counter to count the number of times it appeared in data.

```<code>input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

from collections import Counter
counted = Counter(data)
for i, b in counted.items():
    input[i-1] = b
</code>```

And as a side note, input or any other pre-defined names isn't good variable names since they could mess things up in the future.

A easier way to create the input is to do this in case you don't know how many zeroes you need.

```<code>input = [0 for _ in range(max(a))] # place this after you defined counted
</code>```

And I believe you don't even need to do this, just use the Counter instance can surely get the job done. Counter({5: 2, 1: 1, 2: 1}) It behaves almost the same way as a dict.

Title: Adding 1 to elements of an empty list using another list to count up (maybe with += ?)

Body:
What you can do to speed things up is to use a collections.Counter to count the number of times it appeared in data.

input = [0, 0, 0, 0, 0]
data = [5, 1, 2, 5]

from collections import Counter
counted = Counter(data)
for i, b in counted.items():
    input[i-1] = b

And as a side note, input or any other pre-defined names isn't good variable names since they could mess things up in the future.

A easier way to create the input is to do this in case you don't know how many zeroes you need.

input = [0 for _ in range(max(a))] # place this after you defined counted

And I believe you don't even need to do this, just use the Counter instance can surely get the job done. Counter({5: 2, 1: 1, 2: 1}) It behaves almost the same way as a dict.


问:
How to dynamically configure rampart on service side
how can i dynamically configure rampart on the service side? I mean I'd like to use different service keys for different clients.

Any hint or link to a tutorial is a big help.

thanks

答:
To clarify, you want the ability to issue a different token depending on the client credentials?  This sounds a lot like Security Token Service (STS)

It is possible to accept a range of credential options. Rampart makes you implement your own callback class to verify the initial credentials.

You can implement your own TokenIssuer to customize the response (http://axis.apache.org/axis2/java/rampart/setting-up-sts.html)  and either bundle that inside your service archive or externalize it.  You can use whatever criteria is fit for determining the responsetoken.


问:
AWS Aurora server sometimes responds with "Unknown Database: ..."
I have a .NET application that executes queries on a MySQL database in Amazon Aurora RDS. The database is a MySQL 5.6 database - the version that comes with Aurora.

I execute the queries against a schema (name: flight) within the database (name: SSIMLoader). I am using the MySQL 6.9.8.0 libraries.

edit: The connection string points to the master server in the cluster, not to a specific server.

The error occurs when doing inserts, selects, and updates so there's no real pattern to it. Even simple select statements fail randomly.

However, we receive no such error when executing the queries through MySQL workbench.

After restarting the server, the error disappears for a few days and then returns.

We have some very intense queries that do hike the CPU up to 90% for extended periods, but the error persists even after the CPU has dropped back down to 10%.

Has anyone else experienced this and if so, how did you get past it?

Thanks in advance.

edit:
Finally got the error again:

MySql.Data.MySqlClient.MySqlException (0x80004005): Unknown database 'flight'
  at MySql.Data.MySqlClient.MySqlStream.ReadPacket()
  at MySql.Data.MySqlClient.NativeDriver.ReadOk(Boolean read)
  at MySql.Data.MySqlClient.MySqlConnection.ChangeDatabase(String databaseName)
  at MySql.Data.MySqlClient.MySqlConnection.Open()
  at MySql.Data.MySqlClient.MySqlConnection.Open()
  at Universal.Access.Database.BaseDatabaseConnection.EstablishFactoryConnection()
  at Universal.Access.Database.BaseDatabaseConnection.ExecuteReader(CommandType commandType, CommandText commandText)
  at Universal.Core.DataModel.ExecutableDatabaseConnection.ExecuteQuery(String sqlQuery) in C:\tc-projects\universal-platform\Universal.Core\DataModel\ExecutableDatabaseConnection.cs:line 65

This is the query that was running:

UP-DEV | Universal.Core.Data.Importer Error finding current record, SQL: SELECT aircraft_config,updated_by,asa_flight_id,atd_utc,bay,terminal,is_cancelled,flight_number,created_at,from_iata,flight_date_utc,std_local,takeoff_time_local,is_international,is_aerocare,cobt_local,customer_atd_local,takeoff_time_utc,std_utc,atd_local,asa_state,aircraft_type,customer_atd_utc,carrier_code,updated_at,gate,service_type,etd_local,cobt_utc,flight_status,etd_utc,aircraft_rego,created_by,id,flight_date,to_iata FROM flight.departure_flight WHERE carrier_code='JQ' AND flight_date_utc='2017-01-20T00:00:00' AND flight_number='57' AND from_iata='MEL'. Database returned: Unknown database 'flight'

答:
So it seems that this error occurs when the Aurora instance cpu is at 100%.
The connection cannot find the database specified because it cannot connect to the instance as there are no threads left with which to establish a connection.</p>


问:
Vue.js - this.data not storing GET response
```<code><!DOCTYPE html>
<html>
<head>
  <title>Welcome to Vue</title>
  <script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <button v-on:click="sendTime">Load</button>
  <div v-for="user in users">
    <p>{{ user.username }}</p>
  </div>
</div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
new Vue({
el: '#app',
data: {
  users: [
    { username: "billy" },
    { username: "ryan" }
  ],
},
methods: {
  sendTime : function () {
    axios.get('/api/users')
  .then(function (response) {
    console.log(response.data);
    this.users = response.data;
  })
  .catch(function (error) {
    console.log(error);
  });
  },
}
})
</script>

</body>
</html>
</code>```

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

For some reason I can't seem to get this Array to assign to 'this.data'? When ever the button is clicked the only change is a new console.log, but the two default users in data are displayed. Any help would be greatly appreciated!

答:
```<code>axios.get(...).then(function(response){
      this.users = response.data;
}.bind(this))
</code>```

See How to access the correct this inside a callback?

Body:
<!DOCTYPE html>

  <title>Welcome to Vue</title>

    <button v-on:click="sendTime">Load</button>

{{ user.username }}

console.log returns -

Array [ Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, 15 more… ]

For some reason I can't seem to get this Array to assign to 'this.data'? When ever the button is clicked the only change is a new console.log, but the two default users in data are displayed. Any help would be greatly appreciated!

Body:
axios.get(...).then(function(response){
      this.users = response.data;
}.bind(this))

See How to access the correct this inside a callback?