问:
How can i style just a specific part of timeformat?
how can i style just a part of a timeformat?

The hours and minutes shoud me in a darkblue and the rest in a lightblue.

It should be also in the users local format, like on this image.

Anyone know how to do something like this?

答:
You can color parts of a TextView text in different colors using Spannable. See some examples here.

The example below shows how to get time string according to local format by calling the method getTimeString(Context context, Date date).

All the methods in the example are static so you can put them in some Utils class and call it like Utils.getTimeString(context, date).

```<code>public static String getTimeString(Context context, Date date) {
        DateFormat dateFormat = new SimpleDateFormat(getTimePattern(context), currentLocale(context));
        return dateFormat.format(date);
    }

public static boolean is24HourTimeFormat(Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }

private static String getTimePattern(Context context) {
        return is24HourTimeFormat(context) ? "HH:mm" : "hh:mm a";
    }

private static Locale currentLocale(Context context) {
        return context.getResources().getConfiguration().locale;
    }
</code>```

Body:
You can color parts of a TextView text in different colors using Spannable. See some examples here.

The example below shows how to get time string according to local format by calling the method getTimeString(Context context, Date date).

All the methods in the example are static so you can put them in some Utils class and call it like Utils.getTimeString(context, date).

public static String getTimeString(Context context, Date date) {
        DateFormat dateFormat = new SimpleDateFormat(getTimePattern(context), currentLocale(context));
        return dateFormat.format(date);
    }

public static boolean is24HourTimeFormat(Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }

private static String getTimePattern(Context context) {
        return is24HourTimeFormat(context) ? "HH:mm" : "hh:mm a";
    }

private static Locale currentLocale(Context context) {
        return context.getResources().getConfiguration().locale;
    }


来源: stackexchange

问:
Kotlin infinity loop on list in recursion
This follows infinite loop, in clojure such things just fine  </p>

```<code>tailrec fun passHeaders (xH: List<Int>)
{
    while (xH.isNotEmpty())
    {
        passHeaders(xH.drop(1))
    }
}
</code>```

答:
You don't provide a base case, that's why. Because in each call to passHeaders, xH is it's own copy, it will NEVER not be empty. Remember, when you call drop(), a new list is created.

```<code>while (xH.isNotEmpty())
</code>```

What this says is "while my copy of xH is not empty, call passHeaders.

On the other hand:

```<code>if (xH.isNotEmpty())
</code>```

Will probably do what you intend.

ContentLicense: CC BY-SA 3.0

Body:
This follows infinite loop, in clojure such things just fine

tailrec fun passHeaders (xH: List<Int>)
{
    while (xH.isNotEmpty())
    {
        passHeaders(xH.drop(1))
    }
}

Body:
You don't provide a base case, that's why. Because in each call to passHeaders, xH is it's own copy, it will NEVER not be empty. Remember, when you call drop(), a new list is created.

while (xH.isNotEmpty())

What this says is "while my copy of xH is not empty, call passHeaders.

On the other hand:

if (xH.isNotEmpty())

Will probably do what you intend.


问:
SourceTree left pane view spinning, won't load
I recently upgraded to SourceTree 2.0.20.1.  After that upgrade one of my projects won't load the left pane.  It just sits with the windows busy spinning icon (see attached image).  All my other projects seem to load fine.  The history shows fine and I can commit to the repository, just can't view my branches in the left pane.  All my project remotes reside on the same VSO git server.  Any ideas?

SourceTree Left Pane View Spinning

答:
If you are using git, try running git fsck in the a command line.

The sourcetree left-hand panel was not loading for me either.
I had errors reported by git fsck, but once I resolved those errors, sourcetree worked correctly again.


答:
What a logic problem.  Got it right the 1st time</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication60
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Date", typeof(DateTime));
            dt.Columns.Add("Amount", typeof(int));

            DataTable dt2 = dt.Clone();

            dt.Rows.Add(new object[] { DateTime.Parse("5/1/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/2/17"), 4000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/3/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/4/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/5/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/6/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/7/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/8/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/9/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/10/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/11/17"), 4000 });

            for (int rowNumber = 0; rowNumber < dt.Rows.Count; rowNumber++)
            {
                Boolean exceeds = false;

                switch (rowNumber)
                {
                    case 0:
                        exceeds = (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false;
                        break;

                    case 1:
                        exceeds = ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false) ||
                                  ((int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false);
                        break;
                    default:
                        if (rowNumber < dt.Rows.Count - 3)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false);
                        }
                        if (rowNumber == dt.Rows.Count - 2)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false);
                        }
                        if (rowNumber == dt.Rows.Count - 1)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false);
                        }
                        break;
                }
                if (exceeds)
                {
                    dt2.Rows.Add(new object[] { dt.Rows[rowNumber]["Date"], dt.Rows[rowNumber]["Amount"] });
                }
            }

        }

    }
}
</code>```

Title: C# SQL Server Output transactions that exceed certain amount within 3 days

Body:
I'm using C# and SQL Server

In a month, seperate by AccountNo, all transaction that exceeds 10,000 amount within 3 days must be outputted.

This is a sample table:

AccountNo-----Date------------Amount
1-------------5/1/17----------8000
1-------------5/3/17----------1000
1-------------5/4/17----------1000
1-------------5/6/17----------1000
2-------------5/7/17----------3000
2-------------5/10/17---------2000
2-------------5/13/17---------2000
2-------------5/13/17---------3000
3-------------5/14/17---------3000
3-------------5/15/17---------3000
3-------------5/16/17---------9000
4-------------5/17/17---------1000
5-------------5/18/17---------1000
5-------------5/19/17---------1000
5-------------5/20/17---------1000

The result must be:

AccountNo-----Date------------Amount
1-------------5/1/17----------8000
1-------------5/3/17----------1000
1-------------5/4/17----------1000
2-------------5/7/17----------3000
2-------------5/10/17---------2000
2-------------5/13/17---------2000
2-------------5/13/17---------3000
3-------------5/14/17---------3000
3-------------5/15/17---------3000
3-------------5/16/17---------9000

There is a code given to me, but it's not completely working yet.

Select A.*
 From  YourTable A
 Cross Apply (
                Select RT1 = sum(case when [Date] <= B2.TstDate then [Amount] else 0 end)
                      ,RT2 = sum(case when [Date] >= B2.TstDate then [Amount] else 0 end)
             From  YourTable B1
             Cross Join (Select TstDate=A.[Date]) B2
             Where [Date] between DateAdd(DAY,-2,A.[Date]) and DateAdd(DAY,2,A.[Date])
               and Year([Date])=Year(TstDate)
               and Month([Date])=Month(TstDate)
         ) B
 Where RT1>=10000 or RT2>=10000

Body:
What a logic problem.  Got it right the 1st time

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication60
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Date", typeof(DateTime));
            dt.Columns.Add("Amount", typeof(int));

            DataTable dt2 = dt.Clone();

            dt.Rows.Add(new object[] { DateTime.Parse("5/1/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/2/17"), 4000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/3/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/4/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/5/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/6/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/7/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/8/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/9/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/10/17"), 3000 });
            dt.Rows.Add(new object[] { DateTime.Parse("5/11/17"), 4000 });

            for (int rowNumber = 0; rowNumber < dt.Rows.Count; rowNumber++)
            {
                Boolean exceeds = false;

                switch (rowNumber)
                {
                    case 0:
                        exceeds = (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false;
                        break;

                    case 1:
                        exceeds = ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false) ||
                                  ((int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false);
                        break;
                    default:
                        if (rowNumber < dt.Rows.Count - 3)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] + (int)dt.Rows[rowNumber + 2]["Amount"] >= 10000 ? true : false);
                        }
                        if (rowNumber == dt.Rows.Count - 2)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false) ||
                                      ((int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] + (int)dt.Rows[rowNumber + 1]["Amount"] >= 10000 ? true : false);
                        }
                        if (rowNumber == dt.Rows.Count - 1)
                        {
                            exceeds = ((int)dt.Rows[rowNumber - 2]["Amount"] + (int)dt.Rows[rowNumber - 1]["Amount"] + (int)dt.Rows[rowNumber]["Amount"] >= 10000 ? true : false);
                        }
                        break;
                }
                if (exceeds)
                {
                    dt2.Rows.Add(new object[] { dt.Rows[rowNumber]["Date"], dt.Rows[rowNumber]["Amount"] });
                }
            }

        }

    }
}


问:
How to append text to an existing text file?
I wrote an application that would ask the user for some details of the hotel that they are staying at, and the text does luckily get added, but if I add another person it will override the previous data that was in the file already.  However, I want it to keep all of the data inputs.

Here is my code:

```<code>hotelName = txt_HotelName.Text;

ratings = txt_HotelRating.Text;
roomsNeeded = txt_RoomsNeeded.Text;
name = txt_UserName.Text;
surname = txt_UserLastname.Text;
contactDetails = txt_ContactDetail.Text;
paymentDetails = txt_PaymentMehthod.Text;
paymentDate = txt_PaymentDate.Text;

using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
{
    sw.WriteLine(txt_HotelName + Environment.NewLine + txt_HotelRating + Environment.NewLine + txt_RoomsNeeded +
        Environment.NewLine + txt_UserName + Environment.NewLine + txt_UserLastname + Environment.NewLine + txt_ContactDetail +
        Environment.NewLine + txt_PaymentMehthod + Environment.NewLine + txt_PaymentDate);
}

MessageBox.Show($"Thank you for using our system {txt_UserName.Text}.", "Thank you", MessageBoxButtons.OK);
</code>```

So what I want is to collect all of the data, rather than having them over-write each time.

答:
You need to specify a unique name:

```<code> using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
</code>```

So instead of "HotelDocument.txt"  maybe use the current DateTime, or even a new Guid() to be 100% unique. So something like:

```<code>var uniqueFileName = new Guid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(uniqueFileName))
</code>```

Or are you looking to append new data within the existing HotelDocument.txt?

Body:
I wrote an application that would ask the user for some details of the hotel that they are staying at, and the text does luckily get added, but if I add another person it will override the previous data that was in the file already.  However, I want it to keep all of the data inputs.

Here is my code:

hotelName = txt_HotelName.Text;

ratings = txt_HotelRating.Text;
roomsNeeded = txt_RoomsNeeded.Text;
name = txt_UserName.Text;
surname = txt_UserLastname.Text;
contactDetails = txt_ContactDetail.Text;
paymentDetails = txt_PaymentMehthod.Text;
paymentDate = txt_PaymentDate.Text;

using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))
{
    sw.WriteLine(txt_HotelName + Environment.NewLine + txt_HotelRating + Environment.NewLine + txt_RoomsNeeded +
        Environment.NewLine + txt_UserName + Environment.NewLine + txt_UserLastname + Environment.NewLine + txt_ContactDetail +
        Environment.NewLine + txt_PaymentMehthod + Environment.NewLine + txt_PaymentDate);
}

MessageBox.Show($"Thank you for using our system {txt_UserName.Text}.", "Thank you", MessageBoxButtons.OK);

So what I want is to collect all of the data, rather than having them over-write each time.

Body:
You need to specify a unique name:

 using (StreamWriter sw = new StreamWriter("HotelDocument.txt"))

So instead of "HotelDocument.txt"  maybe use the current DateTime, or even a new Guid() to be 100% unique. So something like:

var uniqueFileName = new Guid().ToString() + ".txt";
using (StreamWriter sw = new StreamWriter(uniqueFileName))

Or are you looking to append new data within the existing HotelDocument.txt?


问:
Use of Global Variables in Python
Why the value of variable is not changing while using global in function.

Am i missing something?

```<code>class testglobal():
    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)
</code>```

答:
To get your claimed output, your code would have to be indented like this:

```<code>class testGlobal:

    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)
</code>```

Both print statements are executed while the class is being defined, at which point both references to a refer to the class variable a, not the global variable a which change refers to.

If you are really interested in global variables, you don't need this class at all. Try the following code:

```<code>a = 2
print(a)
def change():
    global a
    a = 5
change()
print(a)
</code>```

Title: Use of Global Variables in Python

Body:
Why the value of variable is not changing while using global in function.

Am i missing something?

class testglobal():
    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)

Body:
To get your claimed output, your code would have to be indented like this:

class testGlobal:

    a=2
    print(a)

    def change():

        global a
        a = 5

    change()
    print(a)

Both print statements are executed while the class is being defined, at which point both references to a refer to the class variable a, not the global variable a which change refers to.

If you are really interested in global variables, you don't need this class at all. Try the following code:

a = 2
print(a)
def change():
    global a
    a = 5
change()
print(a)


问:
Find out specific Exception
Apologies for the lack of information...

Is there a way to find out what is the specific Exception that is causing a call to throw the Exception?

Currently, I am catching all the Exceptions by doing catch(Exception e) but I know this is not good practices at all.

Is there a way to know from the Exception what is the specific one that caused the issue so I can be more granular?

答:
You can get more information for the particular exception using different methods on it. Here I'm using the System.Diagnostics.Debug class to print in Visual Studio's output console. In your catch block:

```<code>using System.Diagnostics;

try
{
    // do stuff
}
catch (Exception e)
{
    Debug.WriteLine(e.GetType());  // Displays the type of exception
    Debug.WriteLine(e.Message());  // Displays the exception message
}
</code>```

You can see more here: Exception methods &
                       Exception properties

Title: Find out specific Exception

Body:
You can get more information for the particular exception using different methods on it. Here I'm using the System.Diagnostics.Debug class to print in Visual Studio's output console. In your catch block:

using System.Diagnostics;

try
{
    // do stuff
}
catch (Exception e)
{
    Debug.WriteLine(e.GetType());  // Displays the type of exception
    Debug.WriteLine(e.Message());  // Displays the exception message
}

You can see more here: Exception methods &
                       Exception properties


问:
How i transfer character from UWP application to android app using bluetooth connection?
I am developing an application for Raspberry pi its UWP application, so i want to send and receive characters from UWP application  to android app.
SO please tell me what is code for UWP application. Thanks in advance :) </p>

答:
This site shows you how to send and receive serial bluetooth data.

Source on GitHub


问:
How do I remove illegal characters from an NSString?
I am parsing a tab seperated list using a NSScanner based upon each line and the tabs. However for some reason the last field in the array (parsed from each row) contains a \r character.

How can I strip this from the NSString that represents the line (or the field)

答: If the \r character is at the end (probably because the file being parsed is CRLF), you can just do something like [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]. (You might want to use an explicitly created '\r' character set instead if you don't want to strip whitespace as well.)

OwnerDisplayName: tigermain

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chris Hanson

OwnerDisplayName: Chuck


问:
Where do I add the database reference from Firebase on iOS?
I am following instructions for installation and setup of realtime database on iOS app from this link
and I am confused where to add the statement
self.ref = FIRDatabase.database().reference() in my app in xcode. Which file or location?

答:
Firebase 4.0 and later:
Make sure you add the following to Podfile! I had the same problem as you until I added this (found on the previous page of the Firebase setup tutorial).

```<code>pod 'Firebase/Database'
</code>```

If you're like me, you ignored it because you thought you already added this line in the Firebase setup tutorial, but the line added in setup is:

```<code>pod 'Firebase/Core'
</code>```

After you add that, it should work. A generic view controller would look like the following:

```<code>import Firebase
import FirebaseDatabase

class GenericViewController: UITableViewController {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
    }
}
</code>```

This had me stuck for a while - I hope this helps! :)

Body:
Firebase 4.0 and later:
Make sure you add the following to Podfile! I had the same problem as you until I added this (found on the previous page of the Firebase setup tutorial).

pod 'Firebase/Database'

If you're like me, you ignored it because you thought you already added this line in the Firebase setup tutorial, but the line added in setup is:

pod 'Firebase/Core'

After you add that, it should work. A generic view controller would look like the following:

import Firebase
import FirebaseDatabase

class GenericViewController: UITableViewController {

    var ref: DatabaseReference!

    override func viewDidLoad() {
        super.viewDidLoad()

        ref = Database.database().reference()
    }
}

This had me stuck for a while - I hope this helps! :)


问:
Rugarch package using external regressors
I’m using the rugarch package and I’m having troubles understanding how the external.regressors work.

For example I would expect that fitting a time series with gjr-garch(1,1) should give the same results as fitting the same time series with the plain vanilla garch(1,1) augmented with S_(t-1)*eps_(t-1)^2 as an external regressor.

However I'm not getting the same results.

Specifically this is the code I'm running:

```<code>rm(list = ls()) # empty memory

library(rugarch)
library(xts)
data(sp500ret)
spx <- xts(sp500ret, as.Date(rownames(sp500ret)))
t = length(spx)
# assuming mu = 0; r_t = eps_t
s = rep(0,t)
for(i in 1:t){
  if(spx[i]<0){s[i]=1}
}
# eps.neg represents the leverage effect regressor
eps.neg <- xts(spx*s, as.Date(rownames(sp500ret)))
colnames(eps.neg)<-"eps.neg"
# lag eps.neg
eps.neg.lag = lag(eps.neg,1)
inputs<-na.omit(cbind(spx, eps.neg.lag, join="left"))
# gjrgarch(1,1)
gjr.spec <- ugarchspec(variance.model = list(model='gjrGARCH', garchOrder=c(1,1),
                      external.regressors = NULL, variance.targeting = T),
                      mean.model = list(armaOrder=c(0,0)),fixed.pars=list(mu = 0))
gjr.fit <- ugarchfit(spec=gjr.spec, data=inputs[,1],
                     solver.control=list(trace = 1))
# garch(1,1) augmented with inputs[,2]
aug.s.spec <- ugarchspec(variance.model = list(model='sGARCH', garchOrder=c(1,1),
                        external.regressors = inputs[,2]^2, variance.targeting = T),
                        mean.model = list(armaOrder=c(0,0)),fixed.pars=list(mu = 0))
aug.s.fit <- ugarchfit(spec=aug.s.spec, data=inputs[,1],
                       solver.control=list(trace = 1))
#results
gjr.fit
aug.s.fit
</code>```

However these are the results:

GJR-GARCH(1,1)

```<code>Robust Standard Errors:
        Estimate  Std. Error    t value Pr(>|t|)
mu      0.000000          NA         NA       NA
alpha1  0.007933    0.000184     43.139        0
beta1   0.909048    0.000008 117316.512        0
gamma1  0.139258    0.004006     34.764        0
omega   0.000002          NA         NA       NA
</code>```

Augmented-Garch(1,1)

```<code>Robust Standard Errors:
        Estimate  Std. Error    t value Pr(>|t|)
mu      0.000000          NA         NA       NA
alpha1  0.085378    0.002123 4.0223e+01  0.00000
beta1   0.904696    0.000001 1.0116e+06  0.00000
vxreg1  0.000000    0.000060 1.6700e-04  0.99987
omega   0.000001          NA         NA       NA
</code>```

I would expect vxreg1 and gamma1 to be equivalent, which is not happening!

What am I doing wrong?

答:
I don't think that these two results should be the same.
The GJR-GARCH(1,1) variance model can be written:

GJR-GARCH(1,1) variance model

The standard Garch(1,1) variance model is:

sGARCH(1,1) variance model with external regressor

where delta is the vxreg1 coef. and reg are the external regressors.

If I understood your code correctly,  s = It-1 but spx are the returns and not the residuals. Therefore your equations are not equivalent.

Body:
I’m using the rugarch package and I’m having troubles understanding how the external.regressors work.

For example I would expect that fitting a time series with gjr-garch(1,1) should give the same results as fitting the same time series with the plain vanilla garch(1,1) augmented with S_(t-1)*eps_(t-1)^2 as an external regressor.

However I'm not getting the same results.

Specifically this is the code I'm running:

rm(list = ls()) # empty memory

library(rugarch)
library(xts)
data(sp500ret)
spx <- xts(sp500ret, as.Date(rownames(sp500ret)))
t = length(spx)
# assuming mu = 0; r_t = eps_t
s = rep(0,t)
for(i in 1:t){
  if(spx[i]<0){s[i]=1}
}
# eps.neg represents the leverage effect regressor
eps.neg <- xts(spx*s, as.Date(rownames(sp500ret)))
colnames(eps.neg)<-"eps.neg"
# lag eps.neg
eps.neg.lag = lag(eps.neg,1)
inputs<-na.omit(cbind(spx, eps.neg.lag, join="left"))
# gjrgarch(1,1)
gjr.spec <- ugarchspec(variance.model = list(model='gjrGARCH', garchOrder=c(1,1),
                      external.regressors = NULL, variance.targeting = T),
                      mean.model = list(armaOrder=c(0,0)),fixed.pars=list(mu = 0))
gjr.fit <- ugarchfit(spec=gjr.spec, data=inputs[,1],
                     solver.control=list(trace = 1))
# garch(1,1) augmented with inputs[,2]
aug.s.spec <- ugarchspec(variance.model = list(model='sGARCH', garchOrder=c(1,1),
                        external.regressors = inputs[,2]^2, variance.targeting = T),
                        mean.model = list(armaOrder=c(0,0)),fixed.pars=list(mu = 0))
aug.s.fit <- ugarchfit(spec=aug.s.spec, data=inputs[,1],
                       solver.control=list(trace = 1))
#results
gjr.fit
aug.s.fit

However these are the results:

GJR-GARCH(1,1)

Robust Standard Errors:
        Estimate  Std. Error    t value Pr(>|t|)
mu      0.000000          NA         NA       NA
alpha1  0.007933    0.000184     43.139        0
beta1   0.909048    0.000008 117316.512        0
gamma1  0.139258    0.004006     34.764        0
omega   0.000002          NA         NA       NA

Augmented-Garch(1,1)

Robust Standard Errors:
        Estimate  Std. Error    t value Pr(>|t|)
mu      0.000000          NA         NA       NA
alpha1  0.085378    0.002123 4.0223e+01  0.00000
beta1   0.904696    0.000001 1.0116e+06  0.00000
vxreg1  0.000000    0.000060 1.6700e-04  0.99987
omega   0.000001          NA         NA       NA

I would expect vxreg1 and gamma1 to be equivalent, which is not happening!

What am I doing wrong?


答:
Try appending the file:

```<code>  string line = string.Join(Environment.NewLine, new string[] {
    ratings,
    roomsNeeded,
    name,
    surname,
    contactDetails,
    paymentDetails,
    paymentDate});

  File.AppendAllLines("HotelDocument.txt", new string[] {line});
</code>```

Edit: if you want to organize the input data, I suggest using string interpolation (C# 6.0) or formatting:

```<code>  string line = string.Join(Environment.NewLine, new string[] {
    $"Ratings: {ratings}",
    $"Rooms need: {roomsNeeded}",
    $"Name: {name}",
    $"Surname: {surname}",
    $"Details: {contactDetails}",
    $"Payment: {paymentDetails}",
    $"Payment Date: {paymentDate}");
</code>```

Title: How to append text to an existing text file?

Body:
Try appending the file:

  string line = string.Join(Environment.NewLine, new string[] {
    ratings,
    roomsNeeded,
    name,
    surname,
    contactDetails,
    paymentDetails,
    paymentDate});

  File.AppendAllLines("HotelDocument.txt", new string[] {line});

Edit: if you want to organize the input data, I suggest using string interpolation (C# 6.0) or formatting:

  string line = string.Join(Environment.NewLine, new string[] {
    $"Ratings: {ratings}",
    $"Rooms need: {roomsNeeded}",
    $"Name: {name}",
    $"Surname: {surname}",
    $"Details: {contactDetails}",
    $"Payment: {paymentDetails}",
    $"Payment Date: {paymentDate}");


问:
Applying Functions to a Dictionary
I'm still learning Python and the basic rules here as well so please correct me if I'm making a faux pas.  One can't grow without proper criticism and coaching.

I'm trying to help my wife with a volunteer schedule for a fund raiser she is conducting.  The day contains 7 hourly events and I have 7 hourly schedules that will have a person working for 4 of the 7 events, for the volunteers to pick from.

What this code does is calculate the number of each schedule I'll need to meet the event volunteer requirements based on the number of volunteers I have available.  I currently do not know the exact number of volunteers she will have available.

```<code>import random
    # Volunteer Requirements for each of the 7 events
r = [6, 12, 14, 14, 12, 16, 10]
    # Available Schedules where 0 = hour off and 1 = hour working
s = []
s.append([0,1,1,1,1,0,0])
s.append([0,0,1,1,1,1,0])
s.append([0,0,0,1,1,1,1])
s.append([1,1,1,1,0,0,0])
s.append([1,1,0,0,0,1,1])
s.append([1,1,1,0,0,0,1])
s.append([1,0,0,0,1,1,1])

number_of_schedules = len(s)
number_of_vols = 21
number_of_hours = len(s[0])

while True:
    q = [0]*number_of_schedules
    for i in range(number_of_vols):
        q[random.randint(0,len(q)-1)] += 1
    t = [sum([q[j]*s[j][i] for j in range(number_of_schedules)]) for i in range(number_of_hours)]
    if sum([r[i] <= t[i] for i in range(number_of_hours)]) == number_of_hours:
        print '\n'.join(map(str,q))
        print '\n'.join(map(str,s))
        break
</code>```

When I run the code it prints as:

```<code>3
8
2
1
6
2
0
[0, 1, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0]
[1, 1, 0, 0, 0, 1, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 0, 0, 0, 1, 1, 1]
</code>```

This tells me that in order to meet the requirements I will need 3 people to take the first schedule, 8 to take the second, 2 to take the third, and so on.

What I want to do is build the list 's' as a dict so that I can give a name to each schedule, i.e. 'Schedule A', 'Schedule B', etc.  This way I can call the print function to print each schedule the number of times it is needed.

The preferred end result would look something like this when I call the print function.

```<code>    Schedule A
    Schedule A
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    ........
    Schedule G
</code>```

Then each volunteer can put their name next to an available schedule.

The problem I run into is that regardless of what method I attempt, I cannot get it to work correctly.  I'm hoping to get this done by Friday as my wife wants to send out a volunteer request email this weekend.  Any help/direction anyone can provide would be greatly appreciated.

Thanks in advance.

答:
Hugh Bothwell's solution is very nice if you need the extra speed or scientific rigor. It kind of answers a question that wasn't asked, though. If you're happy with the way the calculations are working now, and just want to be able to print the schedule names rather than (or in addition to) the sequence of zeros and ones, it's much simpler.

You're not going to be able to "multiply" a whole dictionary by a number. There are fancy ways to make a dictionarylike object which will work the way you seem to want, but I think that's overkill for what you're trying to accomplish.

It's low-tech and perhaps not elegant-looking, but the simplest thing to do is make another list that just consists of schedule names, in the same order as s. A given index in s will correspond to the same index in the list of names. (On the off-chance you won't be processing them sequentially, you can look up the index for a given value using .index(). For example, s.index([0, 0, 0, 1, 1, 1, 1]) would return 2.)

Title: Applying Functions to a Dictionary

Body:
I'm still learning Python and the basic rules here as well so please correct me if I'm making a faux pas.  One can't grow without proper criticism and coaching.

I'm trying to help my wife with a volunteer schedule for a fund raiser she is conducting.  The day contains 7 hourly events and I have 7 hourly schedules that will have a person working for 4 of the 7 events, for the volunteers to pick from.

What this code does is calculate the number of each schedule I'll need to meet the event volunteer requirements based on the number of volunteers I have available.  I currently do not know the exact number of volunteers she will have available.

import random
    # Volunteer Requirements for each of the 7 events
r = [6, 12, 14, 14, 12, 16, 10]
    # Available Schedules where 0 = hour off and 1 = hour working
s = []
s.append([0,1,1,1,1,0,0])
s.append([0,0,1,1,1,1,0])
s.append([0,0,0,1,1,1,1])
s.append([1,1,1,1,0,0,0])
s.append([1,1,0,0,0,1,1])
s.append([1,1,1,0,0,0,1])
s.append([1,0,0,0,1,1,1])

number_of_schedules = len(s)
number_of_vols = 21
number_of_hours = len(s[0])

while True:
    q = [0]*number_of_schedules
    for i in range(number_of_vols):
        q[random.randint(0,len(q)-1)] += 1
    t = [sum([q[j]*s[j][i] for j in range(number_of_schedules)]) for i in range(number_of_hours)]
    if sum([r[i] <= t[i] for i in range(number_of_hours)]) == number_of_hours:
        print '\n'.join(map(str,q))
        print '\n'.join(map(str,s))
        break

When I run the code it prints as:

3
8
2
1
6
2
0
[0, 1, 1, 1, 1, 0, 0]
[0, 0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 1, 1]
[1, 1, 1, 1, 0, 0, 0]
[1, 1, 0, 0, 0, 1, 1]
[1, 1, 1, 0, 0, 0, 1]
[1, 0, 0, 0, 1, 1, 1]

This tells me that in order to meet the requirements I will need 3 people to take the first schedule, 8 to take the second, 2 to take the third, and so on.

What I want to do is build the list 's' as a dict so that I can give a name to each schedule, i.e. 'Schedule A', 'Schedule B', etc.  This way I can call the print function to print each schedule the number of times it is needed.

The preferred end result would look something like this when I call the print function.

    Schedule A
    Schedule A
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    Schedule B
    ........
    Schedule G

Then each volunteer can put their name next to an available schedule.

The problem I run into is that regardless of what method I attempt, I cannot get it to work correctly.  I'm hoping to get this done by Friday as my wife wants to send out a volunteer request email this weekend.  Any help/direction anyone can provide would be greatly appreciated.

Thanks in advance.


问:
Spark kafka streaming - how to determine end of a batch
I am consuming from a Kafka topic by using Kafka Streaming. (kafka direct stream)
The data in this topic arrives after every 5 minutes from another source.
Now i need to process the data that arrives after every 5 minutes and convert that into a Spark DataFrame.

Now, stream is continuous flow of data.
My issue is , how do i determine that i am done reading first set of data that was loaded in Kafka topic? (So that i can convert that into DataFrame and start my work)

I know i can mention the batch interval( in JavaStreamingContext) to a certain number, but even then i can never be sure on how much time the source will take to push the data to the topic.

Any suggestions are welcome.

答:
If I understand your question correctly you would like to not create a batch till all the data for the 5 minute worth of input is read.
Spark out of the box does not provide any API like that.

You can how ever use a sliding window on your received stream to achieve part of what you want. (See last example code)

The other way(harder way) is to implement your own org.apache.spark.streaming.util.ManualClock to achieve what you need.

ManualClock is a private class so the override happens within the name space.

```<code>package org.apache.spark.streaming

import org.apache.spark.util.ManualClock
  object ClockWrapper {
    def advance(ssc: StreamingContext, timeToAdd: Duration): Unit = {
      val manualClock = ssc.scheduler.clock.asInstanceOf[ManualClock]
    manualClock.advance(timeToAdd.milliseconds)
  }
}
</code>```

Then in your own class

```<code>import org.apache.spark.streaming.{ClockWrapper, Duration, Seconds, StreamingContext}
//elided.
  override def sparkConfig: Map[String, String] = {
    super.sparkConfig + ("spark.streaming.clock" -> "org.apache.spark.streaming.util.ManualClock")
   }

   def ssc: StreamingContext = _ssc

   def advanceClock(timeToAdd: Duration): Unit = {
     //Only if some other conditions are met..
     ClockWrapper.advance(_ssc, timeToAdd)
   }

   def advanceClockOneBatch(): Unit = {
     advanceClock(Duration(batchDuration.milliseconds))
   }
</code>```

State based stream management can be done by using mapWithState API.

```<code>object StatefulStreamOperation {
  val sparkConf = new SparkConf().setAppName("")
  // Create the context with a 1 second batch size
  val ssc = new StreamingContext(sparkConf, Seconds(1))
  ssc.checkpoint(".")

  val incoming: DStream[(batchTimeMultipleOf5Minute, UserClass)]
  val mappingFunc = (key: batchTime, incoming: Option[Int], state: State[UserClass]) => {
  //Do what ever you need to do to the data.
  //say (result, newState) = Some_Cool_operation(incoming, state)
  state.update(newState)
  result
}

val stateDstream = dataDstream.mapWithState(
  StateSpec.function(mappingFunc).initialState(initialRDD))
//Do something with the result.
ssc.start()
ssc.awaitTermination()
</code>```

}
}

Body:
If I understand your question correctly you would like to not create a batch till all the data for the 5 minute worth of input is read.
Spark out of the box does not provide any API like that.

You can how ever use a sliding window on your received stream to achieve part of what you want. (See last example code)

The other way(harder way) is to implement your own org.apache.spark.streaming.util.ManualClock to achieve what you need.

ManualClock is a private class so the override happens within the name space.

package org.apache.spark.streaming

import org.apache.spark.util.ManualClock
  object ClockWrapper {
    def advance(ssc: StreamingContext, timeToAdd: Duration): Unit = {
      val manualClock = ssc.scheduler.clock.asInstanceOf[ManualClock]
    manualClock.advance(timeToAdd.milliseconds)
  }
}

Then in your own class

import org.apache.spark.streaming.{ClockWrapper, Duration, Seconds, StreamingContext}
//elided.
  override def sparkConfig: Map[String, String] = {
    super.sparkConfig + ("spark.streaming.clock" -> "org.apache.spark.streaming.util.ManualClock")
   }

   def ssc: StreamingContext = _ssc

   def advanceClock(timeToAdd: Duration): Unit = {
     //Only if some other conditions are met..
     ClockWrapper.advance(_ssc, timeToAdd)
   }

   def advanceClockOneBatch(): Unit = {
     advanceClock(Duration(batchDuration.milliseconds))
   }

State based stream management can be done by using mapWithState API.

object StatefulStreamOperation {
  val sparkConf = new SparkConf().setAppName("")
  // Create the context with a 1 second batch size
  val ssc = new StreamingContext(sparkConf, Seconds(1))
  ssc.checkpoint(".")

  val incoming: DStream[(batchTimeMultipleOf5Minute, UserClass)]
  val mappingFunc = (key: batchTime, incoming: Option[Int], state: State[UserClass]) => {
  //Do what ever you need to do to the data.
  //say (result, newState) = Some_Cool_operation(incoming, state)
  state.update(newState)
  result
}

val stateDstream = dataDstream.mapWithState(
  StateSpec.function(mappingFunc).initialState(initialRDD))
//Do something with the result.
ssc.start()
ssc.awaitTermination()

}
}


问:
Get value of drop down menu and save as variable in PHP
I want to get the selected value of a drop down menu and save it as a variable. I tried the following as documented in another post, but it seems not working: echo $selected = $_POST['<?php $as->my_name(); ?>'];

Drop down:

```<code><select name="<?php $as->my_name(); ?>">
                    <option value="">Select this</option>
                    <option value="91"<?php $mb->state('91'); ?>>91</option>
                    <option value="90"<?php $mb->state('90'); ?>>90</option>
                    <option value="89"<?php $mb->state('89'); ?>>89</option>
                    <option value="88"<?php $mb->state('88'); ?>>88</option>
                    <option value="87"<?php $mb->state('87'); ?>>87</option>
                    <option value="86"<?php $mb->state('86'); ?>>86</option>
                    <option value="85"<?php $mb->state('85'); ?>>85</option>
                    <option value="84"<?php $mb->state('84'); ?>>84</option>
                    <option value="83"<?php $mb->state('83'); ?>>83</option>
                    <option value="82"<?php $mb->state('82'); ?>>82</option>
</select>
</code>```

答:
Post the form:

You have to put the select option within form tags

```<code><form method="post">

    <select name="example">
        <option></option>
    </select>
    <input type="submit" />

 </form>
</code>```

Get the posted value:

To get the value of this example you can use:

```<code><?php
    $selected = $_POST['example'];
    echo $selected;
?>
</code>```

To get the value in your case:

```<code><select name="<?php echo $as->my_name(); ?>">
    <option value="test">test</option>
</select>

<?php
    $selected = $_POST[$as->my_name()];
    echo $selected;
?>
</code>```

Body:
I want to get the selected value of a drop down menu and save it as a variable. I tried the following as documented in another post, but it seems not working: echo $selected = $_POST['<?php $as->my_name(); ?>'];

Drop down:

<select name="<?php $as->my_name(); ?>">
                    <option value="">Select this</option>
                    <option value="91"<?php $mb->state('91'); ?>>91</option>
                    <option value="90"<?php $mb->state('90'); ?>>90</option>
                    <option value="89"<?php $mb->state('89'); ?>>89</option>
                    <option value="88"<?php $mb->state('88'); ?>>88</option>
                    <option value="87"<?php $mb->state('87'); ?>>87</option>
                    <option value="86"<?php $mb->state('86'); ?>>86</option>
                    <option value="85"<?php $mb->state('85'); ?>>85</option>
                    <option value="84"<?php $mb->state('84'); ?>>84</option>
                    <option value="83"<?php $mb->state('83'); ?>>83</option>
                    <option value="82"<?php $mb->state('82'); ?>>82</option>
</select>

Body:
Post the form:

You have to put the select option within form tags

<form method="post">

    <select name="example">
        <option></option>
    </select>
    <input type="submit" />

 </form>

Get the posted value:

To get the value of this example you can use:

<?php
    $selected = $_POST['example'];
    echo $selected;
?>

To get the value in your case:

<select name="<?php echo $as->my_name(); ?>">
    <option value="test">test</option>
</select>

<?php
    $selected = $_POST[$as->my_name()];
    echo $selected;
?>


问:
filtering out specific keys in an object
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

```<code>{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}
</code>```

Here is one of the objects in "paramas":

```<code>{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}
</code>```

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

答:
You almost did it by yourself :)

Here is the answer:

```<code>render() {
  const textElements = Object.entries(params.char)
    .filter(([key]) => key !== 'Attribute1' && key !== 'Attribute2')
    .map(([key, value]) => <Text key={key}>{key}, {value}</Text>);

  return (
    <View>
      {textElements}
    </View>
  );
}
</code>```

Body:
I am writing out the key/value pair of an object.  I'm trying to filter out 2 of the keys in the object like this:

{Object.entries(params.char).filter('Attribute1').filter('Attribute2').map(([key,value], index) => <Text key={key}>{key}</Text>)}

Here is one of the objects in "paramas":

{
    id: 1,
    Name: "Drax Bravesword",
    Rating: "*****",
    XP: 392
Age: 34
    Avatar: require('./images/profile1.png'),
    Map: require('./images/map_1.png'),
    Attribute1: "Power",
    Attribute2: "Knowledge",
    Attribute3: "Family"
}

However when I run this, I get this error:

"Array.prototype.filter callback must be a function"

I'm not quite sure how to fix this, but is there a way to fix it or am I doing this all wrong?

Thanks!

Body:
You almost did it by yourself :)

Here is the answer:

render() {
  const textElements = Object.entries(params.char)
    .filter(([key]) => key !== 'Attribute1' && key !== 'Attribute2')
    .map(([key, value]) => <Text key={key}>{key}, {value}</Text>);

  return (
    <View>
      {textElements}
    </View>
  );
}


问:
Execute a shell script from HTML
I have written a simple HTML code that upon submit, it executes a bash script.
The script is in the correct folder, (cgi-bin).
When I load this page on firefox. It gives an error as

```<code>/somePATH/cgi-bin/script.sh could not be opened because an unknown error occurred.
</code>```

Is the problem about script permissions? I have tried:

```<code>chmod 777
</code>```

Here is a a part of the HTML code.

```<code><form action="cgi-bin/script.sh" method="post">
<input type="submit" value="Call my Shell Script">
</form>
</code>```

EDIT:
The script basically just prints the date:

```<code>#!/bin/bash
# get today's date
OUTPUT=$(date)
# script
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Demo</title></head><body>"
echo "Today is $OUTPUT <br>"
echo "You can do anything with this Schell Script"
echo "</body></html>"
</code>```

答:
Here is a list of things you could check in your httpd.conf regarding CGI:

If you are loading or not the CGI module:

```<code>LoadModule cgi_module modules/mod_cgi.so
</code>```

Verify your aliases for CGI

```<code># ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client.  The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/etc/your_httpd_path/cgi-bin/"
</code>```

The rules of your directory of scripts:

```<code># "/etc/your_httpd_path/cgi-bin/" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/etc/your_httpd_path/cgi-bin/">
    AllowOverride All
    Options None
    Require all granted
</Directory>
</code>```

Handlers for different file extensions (add .sh)

```<code># AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
AddHandler cgi-script .cgi .pl .asp .sh
</code>```

Check if everything is configured as expected in your environment.

Btw as a good practice: Do not give 777 to the script, give specific permissions for the apache user, find out which user is running the httpd service (it's usually www-data) and do something like:

```<code># remove extra file permissions for others
chmod o-wx /somePATH/cgi-bin/script.sh
# Define the user of the script (same as the user who runs httpd)
chown www-data  /somePATH/cgi-bin/script.sh
</code>```

Title: Execute a shell script from HTML

Body:
I have written a simple HTML code that upon submit, it executes a bash script.
The script is in the correct folder, (cgi-bin).
When I load this page on firefox. It gives an error as

/somePATH/cgi-bin/script.sh could not be opened because an unknown error occurred.

Is the problem about script permissions? I have tried:

chmod 777

Here is a a part of the HTML code.

<form action="cgi-bin/script.sh" method="post">
<input type="submit" value="Call my Shell Script">
</form>

EDIT:
The script basically just prints the date:

#!/bin/bash
# get today's date
OUTPUT=$(date)
# script
echo "Content-type: text/html"
echo ""
echo "<title>Demo</title>"
echo "Today is $OUTPUT
"
echo "You can do anything with this Schell Script"
echo ""

Body:
Here is a list of things you could check in your httpd.conf regarding CGI:

If you are loading or not the CGI module:

LoadModule cgi_module modules/mod_cgi.so

Verify your aliases for CGI

# ScriptAlias: This controls which directories contain server scripts.
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client.  The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/etc/your_httpd_path/cgi-bin/"

The rules of your directory of scripts:

# "/etc/your_httpd_path/cgi-bin/" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/etc/your_httpd_path/cgi-bin/">
    AllowOverride All
    Options None
    Require all granted
</Directory>

Handlers for different file extensions (add .sh)

# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
AddHandler cgi-script .cgi .pl .asp .sh

Check if everything is configured as expected in your environment.

Btw as a good practice: Do not give 777 to the script, give specific permissions for the apache user, find out which user is running the httpd service (it's usually www-data) and do something like:

# remove extra file permissions for others
chmod o-wx /somePATH/cgi-bin/script.sh
# Define the user of the script (same as the user who runs httpd)
chown www-data  /somePATH/cgi-bin/script.sh


问:
Faster calculation histogram of a set of images
I have about 3 million images and need to calculate a histogram for each one. Right now I am using python but it is taking of lot of time. Is there any way to process the images in batches? I have NVIDIA 1080 Ti GPU cards, so maybe if there is a way to process on the GPU?

I can't find any code or library to process the images in parallel. Any kind of help to boost up the speed is appreciated

答:
Have you tried multiprocessing package for such heavy calculation tasks? Since I assume you don't care about the order in which those images are processed.

A sample use will be:

```<code>from multiprocessing import Pool

pool = Pool()
results = pool.map(create_histogram, images)
</code>```

Body:
Have you tried multiprocessing package for such heavy calculation tasks? Since I assume you don't care about the order in which those images are processed.

A sample use will be:

from multiprocessing import Pool

pool = Pool()
results = pool.map(create_histogram, images)


问:
Know clicked view using ButterKnife
I have this code :

```<code>@OnClick( {R.id.iv_first,R.id.iv_second} )
public void launchCards() {
    Log.i(TAG,"clicked");
}
</code>```

Is there a way to know inside the launchCards() method which of the two ImageView has been clicked ?

答:
You can do something like this:</p>

```<code>@OnClick({R.id.iv_first,R.id.iv_second})
public void launchCards(View view) {

        // Check which ImageView was clicked
        switch (view.getId()) {
          case R.id.iv_first:
              // 1 clicked
            break;
          case R.id.iv_second:
              // 2 clicked
            break;
        }
      }
</code>```

Title: Know clicked view using ButterKnife

Body:
I have this code :

@OnClick( {R.id.iv_first,R.id.iv_second} )
public void launchCards() {
    Log.i(TAG,"clicked");
}

Is there a way to know inside the launchCards() method which of the two ImageView has been clicked ?

Body:
You can do something like this:

@OnClick({R.id.iv_first,R.id.iv_second})
public void launchCards(View view) {

        // Check which ImageView was clicked
        switch (view.getId()) {
          case R.id.iv_first:
              // 1 clicked
            break;
          case R.id.iv_second:
              // 2 clicked
            break;
        }
      }


问:
How get page title dynamically in PHP
I am getting my main pages title but when it comes to getting inner pages (variable post) it's not working.</p>

```<code>$path=$_SERVER['PHP_SELF'];
$page_title=basename($path);
switch($page_title){
    case 'index.php':
        $title="Welcome to the the website";
        $description="description goes here";
        break;
    case 'about.php':
        $title="Welcome to the the website";
        $description="somehtinfd";
        break;
    case 'career.php':
        $title="Welcome to the the website";
        $description="ome textr";
        break;
    /*IT's NOT WORKING HERE*/
    case 'post.php?post_id=1':$title="graphics design services";
        $description= "about ";
        break;
}
</code>```

答:
I think you can use get().

```<code>case 'post.php':
    If($_GET["post_id"]== "1"){
        $title="graphics design services";
        $description= "about ";
    }elseif($_GET["post_id"]== "2"){

    }
    break;
</code>```

So use case to get the page post, the use get to get the ID.

Title: How get page title dynamically in PHP

Body:
I am getting my main pages title but when it comes to getting inner pages (variable post) it's not working.

$path=$_SERVER['PHP_SELF'];
$page_title=basename($path);
switch($page_title){
    case 'index.php':
        $title="Welcome to the the website";
        $description="description goes here";
        break;
    case 'about.php':
        $title="Welcome to the the website";
        $description="somehtinfd";
        break;
    case 'career.php':
        $title="Welcome to the the website";
        $description="ome textr";
        break;
    /*IT's NOT WORKING HERE*/
    case 'post.php?post_id=1':$title="graphics design services";
        $description= "about ";
        break;
}

Body:
I think you can use get().

case 'post.php':
    If($_GET["post_id"]== "1"){
        $title="graphics design services";
        $description= "about ";
    }elseif($_GET["post_id"]== "2"){

    }
    break;

So use case to get the page post, the use get to get the ID.


问:
Scientific notation values in datatable
I have a datatable that gets populated with excel.The datatable does not have fixed columns as it depends on the excel provided by the client.
While reading excel to datatable, the decimal values are getting converted to scientific notation values.
I do not want to save these values in database as scientific notation but as decimals.
I know I can convert a scientific notion value to decimal but how to find out the column of datatable that contains scientific values as columns of datatable depends on the excel provided.</p>

答:
When you read in the data from excel, you can try to convert number from each column by using

```<code>bool result = Decimal.TryParse(number_in_string)
</code>```

A succesful returned result means the scientific notation is parsed. You can use this to see which column contains the scientific notation.

Title: Scientific notation values in datatable

Body:
When you read in the data from excel, you can try to convert number from each column by using

bool result = Decimal.TryParse(number_in_string)

A succesful returned result means the scientific notation is parsed. You can use this to see which column contains the scientific notation.


问:
AWS upload a file to a specific user using s3 bucket
Hi StackOverFlow community,

I have no code to show for this question and I am missing alot of knowledge around AWS so i don't even know what to search or look for.

Here is what i want to achieve

Use Case:

User Signs up

Goes to his/her account.

Uploads a new profile picture.

Traditional Web Server

You would upload the file with the id of the user. (from previous request or session)

That way you can generate a name for the file, store it somewhere and reference that in the Database. How ever you decide. At the end the newly uploaded image, src path is in the Db and linked to the user.

I am trying to achieve the same thing on AWS.

These are the things that i think i understand.

S3 is used to store binary/static content
AWs Cognito is used to authenticate users and (I'm am not very confident here) is the equivalent of sessions.
Lambda is a web services that only accepts JSON.

How am I suppose to use those tools to achieve the desired effect.

I don't have code to try and if someone can point me in the direction of an example i would happily attempt and then return here if i have any futher questions.
I am just not sure if i have the right idea, am i on the right track. I keep searching but i can't find an example that could fulfill that use case.

Thanks in advance.

答:
You can go with any authentication mechanism available like Cognito or your own and after authentication you can create S3 SignedUrls and directly upload files to s3 bucket(s).

This is a secured way of uploading files to s3.

S3 Buckets do have option to use prefix before the actual filename which you can use to seperate and maintain your files with respect to your users.

For e.g

```<code>2017/06/8/<user_id>/ is a kind of prefix information will give you the time.
</code>```

Considering your backend system might include Java , here are steps to Generate a SignedUrls to upload files to s3.

Body:
You can go with any authentication mechanism available like Cognito or your own and after authentication you can create S3 SignedUrls and directly upload files to s3 bucket(s).

This is a secured way of uploading files to s3.

S3 Buckets do have option to use prefix before the actual filename which you can use to seperate and maintain your files with respect to your users.

For e.g

2017/06/8/<user_id>/ is a kind of prefix information will give you the time.

Considering your backend system might include Java , here are steps to Generate a SignedUrls to upload files to s3.


问:
Techniques for having a node module return a "stream" of data?
I hope I'm asking the question correctly, but essentially, is there a way in NodeJS to have a CommonJS module return a stream of data instead of a finalized chunk of data after a (long) computation? Assuming there is more than one way, what are those techniques?

For example, say I have a findPrimes function, written as a CommonJS module:

find-primes.js

```<code>/**
 * @module  findPrimes
 * @param {int} n - Find all primes less than this number
 * @return {array}
 */
module.exports = function(n) {
    if (n < 2) {
        return [];
    } else if (n === 2) {
        return [2];
    }

    var primes = [2];

    for (let i = 3; i < n; i += 2) {
        let is_prime = true;
        let sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t++) {
            if (i % t === 0) {
                is_prime = false;
                break;
            }
        }

        if (is_prime) {
            primes.push(i);
        }
    }

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

As you can see, this function returns an array of all the prime numbers less than its input. It returns the array after it has computed all those numbers.

So, say I go to use this module in a node script

index.js

```<code>const primes = require('./find-primes.js');

// Usage: `node index.js <num>`
let primes_less_than = process.argv[2];

console.log(primes(primes_less_than));
</code>```

When I run the above script with an arg of 25, I get the following (expected) output:

```<code>$ node index.js 25
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]
</code>```

However, say I passed in a much larger number, like 10,000,000

```<code>$ node index.js 10000000
# Takes a while to run before outputting the numbers...
</code>```

While this works, ideally I'd like the program to start writing out the numbers it has computed before it finishes.

So my program would still take a while to run, but it would start outputting information to the screen much faster than "compute EVERYTHING first, then output ALL results".

What is the best way to achieve this effect? Streams? Promises?

I'm open to any and all techniques for this, thanks.

答:
You may use Node.js's stream module for this. It's hard to answer your question within a few lines of code, but if you are really interested in how streams work, have a look at this video (this is me giving a talk about Node.js streams at the Node.js meetup in Munich, Germany).

Alternatively, you may use a generator function with yield, but this as well is hard to explain from scratch in a few lines.

Anyway, streams and generator functions are the terms you should look for.

Body:
I hope I'm asking the question correctly, but essentially, is there a way in NodeJS to have a CommonJS module return a stream of data instead of a finalized chunk of data after a (long) computation? Assuming there is more than one way, what are those techniques?

For example, say I have a findPrimes function, written as a CommonJS module:

find-primes.js

/**
 * @module  findPrimes
 * @param {int} n - Find all primes less than this number
 * @return {array}
 */
module.exports = function(n) {
    if (n < 2) {
        return [];
    } else if (n === 2) {
        return [2];
    }

    var primes = [2];

    for (let i = 3; i < n; i += 2) {
        let is_prime = true;
        let sq = Math.ceil(Math.sqrt(i));

        for (let t = 2; t <= sq; t++) {
            if (i % t === 0) {
                is_prime = false;
                break;
            }
        }

        if (is_prime) {
            primes.push(i);
        }
    }

    return primes;
};

As you can see, this function returns an array of all the prime numbers less than its input. It returns the array after it has computed all those numbers.

So, say I go to use this module in a node script

index.js

const primes = require('./find-primes.js');

// Usage: `node index.js <num>`
let primes_less_than = process.argv[2];

console.log(primes(primes_less_than));

When I run the above script with an arg of 25, I get the following (expected) output:

$ node index.js 25
[ 2, 3, 5, 7, 11, 13, 17, 19, 23 ]

However, say I passed in a much larger number, like 10,000,000

$ node index.js 10000000
# Takes a while to run before outputting the numbers...

While this works, ideally I'd like the program to start writing out the numbers it has computed before it finishes.

So my program would still take a while to run, but it would start outputting information to the screen much faster than "compute EVERYTHING first, then output ALL results".

What is the best way to achieve this effect? Streams? Promises?

I'm open to any and all techniques for this, thanks.


问:
Extracting string between special characters in a csv column
I want to extract userhandles from retweets, ie; any username between
"RT @username:xyzxyzxyz" to a new column. I did the following

```<code>df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    df['Influencers'] = df['Tweet'].str.extract("\(@*?)\:")
df.to_csv('string3.csv', index=False)
</code>```

It generated following error :

```<code>  File "C:\ANACONDA\lib\re.py", line 251, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis
</code>```

Sample DF:

```<code>df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})
</code>```

答:
Try this:

```<code>df = pd.read_csv("string.csv")
df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False)
</code>```

UPDATE:

```<code>In [34]: df
Out[34]:
                        Tweet
0      RT @username:xyzxyzxyz
1         Free text RT @user2
2                 Blah - blah
3  Text @another_user:aaaaaaa

In [35]: df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False).fillna('Original')

In [36]: df
Out[36]:
                        Tweet Influencers
0      RT @username:xyzxyzxyz   @username
1         Free text RT @user2      @user2
2                 Blah - blah    Original
3  Text @another_user:aaaaaaa    Original
</code>```

Body:
I want to extract userhandles from retweets, ie; any username between
"RT @username:xyzxyzxyz" to a new column. I did the following

df = pd.read_csv("string.csv")
for index,row in df.iterrows():
    df['Influencers'] = df['Tweet'].str.extract("\(@*?)\:")
df.to_csv('string3.csv', index=False)

It generated following error :

  File "C:\ANACONDA\lib\re.py", line 251, in _compile
    raise error, v # invalid expression

error: unbalanced parenthesis

Sample DF:

df=pd.DataFrame({"Tweet": ["RT @saikatd: Are editors involved in the transfer of Income Tax officials?","RT @CLManojET: Can't allow L-G's fantasy of running a parallel administration"," Fairplay n equity 2 consumers 2 be ensured"]})

Body:
Try this:

df = pd.read_csv("string.csv")
df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False)

UPDATE:

In [34]: df
Out[34]:
                        Tweet
0      RT @username:xyzxyzxyz
1         Free text RT @user2
2                 Blah - blah
3  Text @another_user:aaaaaaa

In [35]: df['Influencers'] = df['Tweet'].str.extract("RT\s+(\@[^\:]*)", expand=False).fillna('Original')

In [36]: df
Out[36]:
                        Tweet Influencers
0      RT @username:xyzxyzxyz   @username
1         Free text RT @user2      @user2
2                 Blah - blah    Original
3  Text @another_user:aaaaaaa    Original


答:
The simple answer is 'join'.

You can use the join command to match on the first column ( by default ) as long as the files are sorted.

Don't forget to sort your files.

Did I mention you need to sort your files ;)?   It's an easy mistake to make ( I've made that mistake plenty; hence the emphasis ).

```<code>sort  ZBND19X.csv >  ZBND19X.csv.sorted
sort ZBND39X.csv  > ZBND39X.csv.sorted
join -t, ZBND19X.csv.sorted ZBND39X.csv.sorted > RPKM_all.csv
</code>```

Here's the contents of RPKM_all.csv after running above :

```<code>ENSTGUG00000000915,862.597795025,588.002298061
ENSTGUG00000005054 (CAMKV),823.404021741,687.81249397
ENSTGUG00000006651 (ARPP19),845.045872644,634.296191033
ENSTGUG00000013338 (GAPDH),984.31862471,971.678203888
Gene,ZBND19X(26027342 pairs),ZBND39X(26558640 pairs)
</code>```

We can also look for rows that don't match like this:

```<code>$ join -v1 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,$2,0}'
ENSTGUG00000005949 (FTH1),585.628487964,0

$ join -v2 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,0,$2}'
ENSTGUG00000002582 (ITM2A),0,613.756010638
</code>```

Now you can combine the whole thing:

```<code>sort  ZBND19X.csv >  ZBND19X.csv.sorted
sort ZBND39X.csv  > ZBND39X.csv.sorted
join -t, ZBND19X.csv.sorted ZBND39X.csv.sorted > RPKM_all.csv
join -v1 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,$2,0}' >> RPKM_all.csv
join -v2 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,0,$2}'  >> RPKM_all.csv
</code>```

Title: How to merge multiple .csv files using the 1st column of one of them as a index (shell scripting)

Body:
How to merge multiple .csv files using the 1st column of one of them as an index (pref shell scripting - awk)

88 .csv files that look like this
input files names ZBND19X.csv

==> ZBND19X.csv <==
Gene,ZBND19X(26027342 pairs)
ENSTGUG00000013338 (GAPDH),984.31862471
ENSTGUG00000000915,862.597795025
ENSTGUG00000006651 (ARPP19),845.045872644
ENSTGUG00000005054 (CAMKV),823.404021741
ENSTGUG00000005949 (FTH1),585.628487964

and ZBND22V.csv

==> ZBND39X.csv <==
Gene,ZBND39X(26558640 pairs)
ENSTGUG00000013338 (GAPDH),971.678203888
ENSTGUG00000005054 (CAMKV),687.81249397
ENSTGUG00000006651 (ARPP19),634.296191033
ENSTGUG00000002582 (ITM2A),613.756010638
ENSTGUG00000000915,588.002298061

output file name RPKM_all.csv

Gene,ZBND19X(26027342 pairs),ZBND39X(26558640 pairs)
ENSTGUG00000013338 (GAPDH),984.31862471,971.678203888
ENSTGUG00000000915,862.597795025,588.002298061
ENSTGUG00000006651 (ARPP19),845.045872644,634.296191033
ENSTGUG00000005054 (CAMKV),823.404021741,687.81249397
ENSTGUG00000005949 (FTH1),585.628487964,0
ENSTGUG00000002582 (ITM2A),613.756010638,0

Adding the 0 when there is no corresponding value found.

Body:
The simple answer is 'join'.

You can use the join command to match on the first column ( by default ) as long as the files are sorted.

Don't forget to sort your files.

Did I mention you need to sort your files ;)?   It's an easy mistake to make ( I've made that mistake plenty; hence the emphasis ).

sort  ZBND19X.csv >  ZBND19X.csv.sorted
sort ZBND39X.csv  > ZBND39X.csv.sorted
join -t, ZBND19X.csv.sorted ZBND39X.csv.sorted > RPKM_all.csv

Here's the contents of RPKM_all.csv after running above :

ENSTGUG00000000915,862.597795025,588.002298061
ENSTGUG00000005054 (CAMKV),823.404021741,687.81249397
ENSTGUG00000006651 (ARPP19),845.045872644,634.296191033
ENSTGUG00000013338 (GAPDH),984.31862471,971.678203888
Gene,ZBND19X(26027342 pairs),ZBND39X(26558640 pairs)

We can also look for rows that don't match like this:

$ join -v1 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,$2,0}'
ENSTGUG00000005949 (FTH1),585.628487964,0

$ join -v2 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,0,$2}'
ENSTGUG00000002582 (ITM2A),0,613.756010638

Now you can combine the whole thing:

sort  ZBND19X.csv >  ZBND19X.csv.sorted
sort ZBND39X.csv  > ZBND39X.csv.sorted
join -t, ZBND19X.csv.sorted ZBND39X.csv.sorted > RPKM_all.csv
join -v1 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,$2,0}' >> RPKM_all.csv
join -v2 -t, ZBND19X.csv.sorted ZBND39X.csv.sorted | awk -F, -v OFS=, '{print $1,0,$2}'  >> RPKM_all.csv