问:
Servicestack SOAP - Invalid credentials returning html in response
In my service, I have a custom auth provider that throws a HttpError if the credentials are invalid like so:

```<code>throw HttpError.Unauthorized("Invalid Username or Password");
</code>```

When I access this service via REST and purposely enter invalid credentials, I get the expected response:

```<code>{
  "ResponseStatus": {
    "ErrorCode": "Unauthorized",
    "Message": "Invalid UserName or Password",
  }
}
</code>```

However, doing the same thing via a SOAP client, I get a Html response from the IIS server:

This causes my SOAP client to break as it can't deserialize the response. This can also occur if incorrect data values are included in the request e.g. setting a string value on an integer parameter. The response is fine if an exception occurs in one of my services where I am handling the request (i.e. HttpError.NotFound thrown). I know a similar question has been answered here but it hasn't been updated since 2013. Is there a way to configure the response or override it?

Edit 1

I've updated my web.config to look like so (in system.webServer, I had to use "modules" instead of "httpModules".):

```<code><system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
    <httpHandlers>
      <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </modules>
    <urlCompression doStaticCompression="true" doDynamicCompression="false" />
    <handlers>
      <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>
</code>```

and my AppHost has the following:

```<code>SetConfig(new HostConfig
{
    HandlerFactoryPath = "/api"
});

SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath;
</code>```

However I'm still getting the same error as before. I'm wondering if this is due to me passing in credentials as a header with every request rather than specifically authenticating first? It's worth pointing out that this same error occurs when e.g. a string is set on an integer parameter.

Edit 2

This solution does in fact work. I was defining the incorrect HandlerFactoryPath:

```<code>SetConfig(new HostConfig
{
    HandlerFactoryPath = "api"
});
</code>```

答:
The Yellow Screen Of Death is the result of ASP.NET Hijacking the Error Response of Unauthorized Error Responses. You can prevent ASP.NET from hijacking the Error Response with the SuppressFormsAuthenticationRedirectModule.

First you need to register the HTTP Module in your web.config:

```<code><system.web>
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
</system.web>

<!-- Required for IIS 7.0 (and above?) -->
<system.webServer>
  <validation validateIntegratedModeConfiguration="false" />
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
</system.webServer>
</code>```

next, configure the module with where your API lives - defaults to /api, so in your AppHost Configure:

```<code>public override void Configure(Funq.Container container)
{
    SetConfig(new HostConfig {
        HandlerFactoryPath = "api",
    });

    //this is the configuration for Hijacking prevention
    SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath;
}
</code>```

Body:
In my service, I have a custom auth provider that throws a HttpError if the credentials are invalid like so:

throw HttpError.Unauthorized("Invalid Username or Password");

When I access this service via REST and purposely enter invalid credentials, I get the expected response:

{
  "ResponseStatus": {
    "ErrorCode": "Unauthorized",
    "Message": "Invalid UserName or Password",
  }
}

However, doing the same thing via a SOAP client, I get a Html response from the IIS server:

This causes my SOAP client to break as it can't deserialize the response. This can also occur if incorrect data values are included in the request e.g. setting a string value on an integer parameter. The response is fine if an exception occurs in one of my services where I am handling the request (i.e. HttpError.NotFound thrown). I know a similar question has been answered here but it hasn't been updated since 2013. Is there a way to configure the response or override it?

Edit 1

I've updated my web.config to look like so (in system.webServer, I had to use "modules" instead of "httpModules".):

<system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
    <httpHandlers>
      <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" />
    </httpHandlers>
  </system.web>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </modules>
    <urlCompression doStaticCompression="true" doDynamicCompression="false" />
    <handlers>
      <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
    </handlers>
  </system.webServer>

and my AppHost has the following:

SetConfig(new HostConfig
{
    HandlerFactoryPath = "/api"
});

SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath;

However I'm still getting the same error as before. I'm wondering if this is due to me passing in credentials as a header with every request rather than specifically authenticating first? It's worth pointing out that this same error occurs when e.g. a string is set on an integer parameter.

Edit 2

This solution does in fact work. I was defining the incorrect HandlerFactoryPath:

SetConfig(new HostConfig
{
    HandlerFactoryPath = "api"
});

Body:
The Yellow Screen Of Death is the result of ASP.NET Hijacking the Error Response of Unauthorized Error Responses. You can prevent ASP.NET from hijacking the Error Response with the SuppressFormsAuthenticationRedirectModule.

First you need to register the HTTP Module in your web.config:

<system.web>
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
</system.web>

<!-- Required for IIS 7.0 (and above?) -->
<system.webServer>
  <validation validateIntegratedModeConfiguration="false" />
    <httpModules>
      <add name="FormsAuthenticationDisposition" type="ServiceStack.SuppressFormsAuthenticationRedirectModule, ServiceStack" />
    </httpModules>
</system.webServer>

next, configure the module with where your API lives - defaults to /api, so in your AppHost Configure:

public override void Configure(Funq.Container container)
{
    SetConfig(new HostConfig {
        HandlerFactoryPath = "api",
    });

    //this is the configuration for Hijacking prevention
    SuppressFormsAuthenticationRedirectModule.PathToSupress = Config.HandlerFactoryPath;
}


来源: stackexchange

问:
Prevent to cancel Action Mode by press back button
Action mode started by calling getActivity().startActionMode(calback); is automatically canceled after back button pressed. Is possible avoid this behavior? I need to do another operation after back button was pressed in some situation during action mode.

答:
Create your own Window.Callback and intercept event before it is passed to AppCompatDelegateImplBase.

```<code>@Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        //default delegate
        final Window window = getActivity().getWindow();
        mWindowCallbackDelegate = new WindowCallbackDelegate(window.getCallback(), this);
        window.setCallback(mWindowCallbackDelegate);
        return true;
    }
</code>```

In your own delegate :

```<code>@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    return myWindowDelegate.dispatchKeyEvent(event) || mOriginalWindowCallback.dispatchKeyEvent(event);
}
</code>```

When you destroy action mode, restore reference to previous delegate

```<code> @Override
        public void onDestroyActionMode(ActionMode mode) {
        Window.Callback originalWindowCallback = mWindowCallbackDelegate.getOriginalWindowCallback();
        if (originalWindowCallback != null) {
            getActivity().getWindow().setCallback(originalWindowCallback);
        }}
</code>```

You own delegate signature:

public class WindowCallbackDelegate implements Window.Callback {...}

ContentLicense: CC BY-SA 3.0

Body:
Create your own Window.Callback and intercept event before it is passed to AppCompatDelegateImplBase.

@Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        //default delegate
        final Window window = getActivity().getWindow();
        mWindowCallbackDelegate = new WindowCallbackDelegate(window.getCallback(), this);
        window.setCallback(mWindowCallbackDelegate);
        return true;
    }

In your own delegate :

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    return myWindowDelegate.dispatchKeyEvent(event) || mOriginalWindowCallback.dispatchKeyEvent(event);
}

When you destroy action mode, restore reference to previous delegate

 @Override
        public void onDestroyActionMode(ActionMode mode) {
        Window.Callback originalWindowCallback = mWindowCallbackDelegate.getOriginalWindowCallback();
        if (originalWindowCallback != null) {
            getActivity().getWindow().setCallback(originalWindowCallback);
        }}

You own delegate signature:

public class WindowCallbackDelegate implements Window.Callback {...}


问:
When to use each type of loop?
I'm learning the basics of programming here (C#) but I think this question is generic in its nature.

What are some simple practical situations that lend themselves closer to a particular type of loop?

The while and for loops seem pretty similar and there are several SO questions addressing the differences between the two. How about foreach? From my basic understanding, its seems I ought to be able to do everything a foreach loop does within a for loop.

答:
If you are writing a parser class, lets say an XMLParser that will read XML nodes from a given source, you can use while loop as you don't know how many tags are there.
Also you can use while when you iterate if the variable is true or not.

You can use for loop if you want to have a bit more control over your iterations

Title: When to use each type of loop?

ContentLicense: CC BY-SA 2.5


问:
Finding cartesian product with PHP associative arrays
Say that I have an array like the following:

```<code>Array
(
    [arm] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )
    [gender] => Array
        (
            [0] => Female
            [1] => Male
        )
    [location] => Array
        (
            [0] => Vancouver
            [1] => Calgary
        )
)
</code>```

How can I find the cartesian product while preserving the keys of the outer associative array and using them in the inner ones? The result of the algorithm should be this:

```<code>Array
(
    [0] => Array
        (
            [arm] => A
            [gender] => Female
            [location] => Vancouver
        )

    [1] => Array
        (
            [arm] => A
            [gender] => Female
            [location] => Calgary
        )

    [2] => Array
        (
            [arm] => A
            [gender] => Male
            [location] => Vancouver
        )

...etc.
</code>```

I've looked up quite a number of cartesian product algorithms but I'm getting stuck on the specifics of how to preserve the associative keys. The current algorithm I am using gives numerical indices only:

```<code>    $result = array();
    foreach ($map as $a) {
        if (empty($result)) {
            $result = $a;
            continue;
        }
        $res = array();
        foreach ($result as $r) {
            foreach ($a as $v) {
                $res[] = array_merge((array)$r, (array)$v);
            }
        }
        $result = $res;
    }

    print_r($result);
</code>```

Any help would be appreciated.

答:
In PHP 7 @Serg's answer can be shortened to:</p>

```<code>function cartesian(array $input)
{
    $result = [[]];
    foreach ($input as $key => $values) {
        $append = [];
        foreach ($values as $value) {
            foreach ($result as $data) {
                $append[] = $data + [$key => $value];
            }
        }
        $result = $append;
    }

    return $result;
}
</code>```

Body:
Say that I have an array like the following:

Array
(
    [arm] => Array
        (
            [0] => A
            [1] => B
            [2] => C
        )
    [gender] => Array
        (
            [0] => Female
            [1] => Male
        )
    [location] => Array
        (
            [0] => Vancouver
            [1] => Calgary
        )
)

How can I find the cartesian product while preserving the keys of the outer associative array and using them in the inner ones? The result of the algorithm should be this:

Array
(
    [0] => Array
        (
            [arm] => A
            [gender] => Female
            [location] => Vancouver
        )

    [1] => Array
        (
            [arm] => A
            [gender] => Female
            [location] => Calgary
        )

    [2] => Array
        (
            [arm] => A
            [gender] => Male
            [location] => Vancouver
        )

...etc.

I've looked up quite a number of cartesian product algorithms but I'm getting stuck on the specifics of how to preserve the associative keys. The current algorithm I am using gives numerical indices only:

    $result = array();
    foreach ($map as $a) {
        if (empty($result)) {
            $result = $a;
            continue;
        }
        $res = array();
        foreach ($result as $r) {
            foreach ($a as $v) {
                $res[] = array_merge((array)$r, (array)$v);
            }
        }
        $result = $res;
    }

    print_r($result);

Any help would be appreciated.

Body:
In PHP 7 @Serg's answer can be shortened to:

function cartesian(array $input)
{
    $result = [[]];
    foreach ($input as $key => $values) {
        $append = [];
        foreach ($values as $value) {
            foreach ($result as $data) {
                $append[] = $data + [$key => $value];
            }
        }
        $result = $append;
    }

    return $result;
}


问:
javascript determining if a day is beyond 2 days
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

```<code>var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();
</code>```

but how do i find if the asked by just day name is beyond 2 days or not?

答:
```<code>new Date().getDay();
</code>```

The getDay function will return the number of the day.
Sunday is 0, Monday is 1, and so on.

That means Wednesday = 3 and Friday = 5
however when it is Saturday = 6 the next 2 days will be 0 and 1 .

Body:
i have a requirement where i only get the name of the day. like what i am doing on friday.

i want to determine if the asked day is beyond 2 days. for example, like today is tuesday. and if someone ask what i am doing on friday. then friday is the 3rd day from today.

in javascript i could see i can do data operation like

var tomorrow = new Date(new Date().getTime() + 24 * 60 * 60 * 1000);
schDate = tomorrow.toDateString();

but how do i find if the asked by just day name is beyond 2 days or not?

Body:
new Date().getDay();

The getDay function will return the number of the day.
Sunday is 0, Monday is 1, and so on.

That means Wednesday = 3 and Friday = 5
however when it is Saturday = 6 the next 2 days will be 0 and 1 .


问:
Windows Cmd - How to delete all but a given file type
I am looking for something like this:

```<code>  Process.Start("cmd.exe", "/C del path\*.(filetypetobedeleted)");
</code>```

but instead I want to delete all but one type of file type (.txt). This includes folders in the path, so I want everything in the path to be deleted but .txt files.

答:
.NET has built-in types for working with directories and files. It's easier to use these classes than starting a separate process just to execute del.

You could write something like:

```<code>var skipExtension=".some";
var directory=new DirectoryInfo(myTargetPath);
var filesToKill=directory.EnumerateFiles()
                         .Where(fi=>fi.Extension!=skipExtension);
foreach(var file in filesToKill)
{
    file.Delete();
}
</code>```

EnumerateFiles has overloads that allow searching for specific patterns and searching all subdirectories, eg:

```<code>EnumerateFiles("*.*",SearchOption.AllDirectories)
</code>```

If you absolutely have to use batch processing, use PowerShell, not cmd. You can create and execute a PowerShell pipeline directly from C#, by using the PowerShell class.

del is a synonym for Remove-Item  in PowerShell which contains an -Exclude parameter. If you want to exclude a specific extension, you can write:

```<code>Remove-Item c:\scripts\*.* -Exclude *.wav
</code>```

or

```<code>del c:\scripts\*.* -Exclude *.wav
</code>```

To execute this command from a C# program, you need to create a PowerShell instance and add the command and parameters:

```<code>PowerShell ps = PowerShell.Create();
ps.AddCommand("Remove-Item")
  .AddParameter("Path",@"h:\test\*.*")
  .AddParameter("Exclude","*.svc");
var results=ps.Invoke();
</code>```

If you want to delete folders as well, you need to add the -Recurse parameter

```<code>PowerShell ps = PowerShell.Create();
ps.AddCommand("Remove-Item")
  .AddParameter("Path",@"h:\test\*")
  .AddParameter("Exclude","*.svc")
  .AddParameter("Recurse");
var results=ps.Invoke();
</code>```

Body:
I am looking for something like this:

  Process.Start("cmd.exe", "/C del path\*.(filetypetobedeleted)");

but instead I want to delete all but one type of file type (.txt). This includes folders in the path, so I want everything in the path to be deleted but .txt files.

Body:
.NET has built-in types for working with directories and files. It's easier to use these classes than starting a separate process just to execute del.

You could write something like:

var skipExtension=".some";
var directory=new DirectoryInfo(myTargetPath);
var filesToKill=directory.EnumerateFiles()
                         .Where(fi=>fi.Extension!=skipExtension);
foreach(var file in filesToKill)
{
    file.Delete();
}

EnumerateFiles has overloads that allow searching for specific patterns and searching all subdirectories, eg:

EnumerateFiles("*.*",SearchOption.AllDirectories)

If you absolutely have to use batch processing, use PowerShell, not cmd. You can create and execute a PowerShell pipeline directly from C#, by using the PowerShell class.

del is a synonym for Remove-Item  in PowerShell which contains an -Exclude parameter. If you want to exclude a specific extension, you can write:

Remove-Item c:\scripts\*.* -Exclude *.wav

or

del c:\scripts\*.* -Exclude *.wav

To execute this command from a C# program, you need to create a PowerShell instance and add the command and parameters:

PowerShell ps = PowerShell.Create();
ps.AddCommand("Remove-Item")
  .AddParameter("Path",@"h:\test\*.*")
  .AddParameter("Exclude","*.svc");
var results=ps.Invoke();

If you want to delete folders as well, you need to add the -Recurse parameter

PowerShell ps = PowerShell.Create();
ps.AddCommand("Remove-Item")
  .AddParameter("Path",@"h:\test\*")
  .AddParameter("Exclude","*.svc")
  .AddParameter("Recurse");
var results=ps.Invoke();


问:
What's my best approach re: creating calculated tables based on scraped data
I have a few spiders running on my vps to scrape data each day and the data is stored in MySQL.

I need to build a pretty complicated time series model on the data from varies data sources.

Here I run into an issue which is that:

I need to create a new calculated table based on my scraped data. The model is quite complicated as it involves historical raw data and calculated data. I was going to write a python script to do this, but it seems not efficient enough.

I then realize that I can just create a view within MySQL and write my model in the format of a nested sql query. That said, I want the view to be materialized ( which is not supported by MySQL now) , and the view can be refreshed each day when new data comes in.

I know there is a third party plugin called flex*** , but i searched online and it seems not easy to install and maintain.

What is my best approach here?

Thanks for the help.

=========================================================================

To add some clarification, the time series model I made is very complicated, it involves:

rolling average on raw data

rolling average on the rolling averaged data above

So it depends on both the raw data and previously calculated data.

The timestamp solution does not really solve the complexity of the issue.

I'm just not sure about the best way to.

答:
Leaving aside whether you should use a dedicated time-series tool such as rrdtool or carbon, mysql provides the functionality you need to implement a semi-materialized view, e.g. given data batch consolidated by date:

```<code>SELECT DATE(event_time), SUM(number_of_events) AS events,
, SUM(metric) AS total
, SUM(metric)/SUM(number_of_events) AS average
FROM (
  SELECT pc.date AS event_time, events AS number_of_events
  , total AS metric
  FROM pre_consolidated pc
  UNION
  SELECT rd.timestamp, 1
  , rd.metric
  FROM raw_data rd
  WHERE rd.timestamp>@LAST_CONSOLIDATED_TIMESTAMP
)
GROUP BY DATE(event_time)
</code>```

(note that although you could create this as a view and access that, IME, MySQL is not the best at optimizing queries involving views and you might be better using the equivalent of the above as a template for building your queries around)

The most flexible way to maintain an accurate record of @LAST_CONSOLIDATED_TIMESTAMP would be to add a state column to the raw_data table (to avoid locking and using transactions to ensure consistency) and an index on the timestamp of the event, then, periodically:

```<code>UPDATE raw_data
SET state='PROCESSING'
WHERE timestamp>=@LAST_CONSOLIDATED_TIMESTAMP
AND state IS NULL;

INSERT INTO pre_consolidated (date, events, total)
SELECT DATE(rd.timestamp), COUNT(*), SUM(rd.metric)
FROM raw_data
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING'
GROUP BY DATE(rd.timestamp);

SELECT @NEXT_CONSOLIDATED_TIMESTAMP := MAX(timestamp)
FROM raw_data
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING';

UPDATE raw_data
SET state='CONSOLIDATED'
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING';

SELECT @LAST_CONSOLIDATED_TIMESTAMP := @NEXT_CONSOLIDATED_TIMESTAMP;
</code>```

(you should think of a way to persist LAST_CONSOLIDATED_TIMESTAMP between DBMS sessions)

Hence the base query (to allow for more than one event with the same timestamp) should be:

```<code>SELECT DATE(event_time), SUM(number_of_events) AS events,
, SUM(metric) AS total
, SUM(metric)/SUM(number_of_events) AS average
FROM (
  SELECT pc.date AS event_time, events AS number_of_events
  , total AS metric
  FROM pre_consolidated pc
  UNION
  SELECT rd.timestamp, 1
  , rd.metric
  FROM raw_data rd
  WHERE rd.timestamp>@LAST_CONSOLIDATED_TIMESTAMP
  AND state IS NULL
)
GROUP BY DATE(event_time)
</code>```

Adding the state variable to the timestamp index will likely slow down the overall performance of the update as long as you are applying the consolidation reasonably frequently.

Body:
Leaving aside whether you should use a dedicated time-series tool such as rrdtool or carbon, mysql provides the functionality you need to implement a semi-materialized view, e.g. given data batch consolidated by date:

SELECT DATE(event_time), SUM(number_of_events) AS events,
, SUM(metric) AS total
, SUM(metric)/SUM(number_of_events) AS average
FROM (
  SELECT pc.date AS event_time, events AS number_of_events
  , total AS metric
  FROM pre_consolidated pc
  UNION
  SELECT rd.timestamp, 1
  , rd.metric
  FROM raw_data rd
  WHERE rd.timestamp>@LAST_CONSOLIDATED_TIMESTAMP
)
GROUP BY DATE(event_time)

(note that although you could create this as a view and access that, IME, MySQL is not the best at optimizing queries involving views and you might be better using the equivalent of the above as a template for building your queries around)

The most flexible way to maintain an accurate record of @LAST_CONSOLIDATED_TIMESTAMP would be to add a state column to the raw_data table (to avoid locking and using transactions to ensure consistency) and an index on the timestamp of the event, then, periodically:

UPDATE raw_data
SET state='PROCESSING'
WHERE timestamp>=@LAST_CONSOLIDATED_TIMESTAMP
AND state IS NULL;

INSERT INTO pre_consolidated (date, events, total)
SELECT DATE(rd.timestamp), COUNT(*), SUM(rd.metric)
FROM raw_data
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING'
GROUP BY DATE(rd.timestamp);

SELECT @NEXT_CONSOLIDATED_TIMESTAMP := MAX(timestamp)
FROM raw_data
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING';

UPDATE raw_data
SET state='CONSOLIDATED'
WHERE timestamp>@LAST_CONSOLIDATED_TIMESTAMP
AND state='PROCESSING';

SELECT @LAST_CONSOLIDATED_TIMESTAMP := @NEXT_CONSOLIDATED_TIMESTAMP;

(you should think of a way to persist LAST_CONSOLIDATED_TIMESTAMP between DBMS sessions)

Hence the base query (to allow for more than one event with the same timestamp) should be:

SELECT DATE(event_time), SUM(number_of_events) AS events,
, SUM(metric) AS total
, SUM(metric)/SUM(number_of_events) AS average
FROM (
  SELECT pc.date AS event_time, events AS number_of_events
  , total AS metric
  FROM pre_consolidated pc
  UNION
  SELECT rd.timestamp, 1
  , rd.metric
  FROM raw_data rd
  WHERE rd.timestamp>@LAST_CONSOLIDATED_TIMESTAMP
  AND state IS NULL
)
GROUP BY DATE(event_time)

Adding the state variable to the timestamp index will likely slow down the overall performance of the update as long as you are applying the consolidation reasonably frequently.


问:
adding a row for missing data
Between a date range 2017-02-01 - 2017-02-10, i'm calculating a running balance.
I have days where we have missing data, how would I include these missing dates with the previous days balance ?

Example data:

we are missing data for 2017-02-04,2017-02-05 and 2017-02-06, how would i add a row in the query with the previous balance?
The date range is a parameter, so could change....

Can i use something like the lag function?

答:
You can generate dates using tally table as below:

```<code>Declare @d1 date ='2017-02-01'
Declare @d2 date ='2017-02-10'

;with cte_dates as (
    Select top (datediff(D, @d1, @d2)+1) Dates = Dateadd(day, Row_Number() over (order by (Select NULL))-1, @d1) from
        master..spt_values s1, master..spt_values s2
)
Select * from cte_dates left join ....
</code>```

And do left join to your table and get running total

Title: adding a row for missing data

Body:
You can generate dates using tally table as below:

Declare @d1 date ='2017-02-01'
Declare @d2 date ='2017-02-10'

;with cte_dates as (
    Select top (datediff(D, @d1, @d2)+1) Dates = Dateadd(day, Row_Number() over (order by (Select NULL))-1, @d1) from
        master..spt_values s1, master..spt_values s2
)
Select * from cte_dates left join ....

And do left join to your table and get running total


问:
Java - access to variable within inner class or assign a value to final variable
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}
```

<p>The error is: <code>Variable file is accessed from within inner class, needs to be declared final</code></p>

<p>I have checked some similar questions in stackoverflow. I know <code>file</code> has to be final like <code>label</code> and <code>fileName</code> here.</p>

<p>However <code>file</code> here could be <code>final</code> since I would like to assign <code>selectedFile</code> to it.</p>

<p>I would like to know if there is any walkaround for this problem.</p>

<p>Any help would be appreciated. :)</p>

<p>Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances</p>

<blockquote>
  <p>Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.</p>
</blockquote>

<p>So when I tried to send a parameter <code>file</code> inside <code>FileSlectionListener</code>, there will be a compile error. However, the member <code>file1</code> inside Solution is not local variable, so if I delete the <code>file</code> from my method, there will be no error. So @talex 's anwser is right in this case.</p>

<p>However since my problem is to find a method to pass a <code>File</code> to inner class and assign the variable with <code>selectedFile</code>, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.</p>

<p>My revised code is as below:</p>

<pre class="lang-java prettyprint-override"><code>public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}
</code>```

Still, welcome to give me any advise if you have a better answer. :)

答:
You have two variables with name file. One is class variable and another is method parameter.

Just remove parameter file from your method and all will work fine.

Body:
I need to create several buttons and upload files. So I want to create a function to set these buttons. However, I'm getting a compilation error inside of my setNewButton.

My code is shown as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format, File file) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                file = selectedFile;  // compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }
}

The error is: Variable file is accessed from within inner class, needs to be declared final

I have checked some similar questions in stackoverflow. I know file has to be final like label and fileName here.

However file here could be final since I would like to assign selectedFile to it.

I would like to know if there is any walkaround for this problem.

Any help would be appreciated. :)

Thanks to @M. Prokhorov and @Chang Liu.
According to  JLS 8.1.3. Inner Classes and Enclosing Instances

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must either be declared final or be effectively final, or a compile-time error occurs where the use is attempted.

So when I tried to send a parameter file inside FileSlectionListener, there will be a compile error. However, the member file1 inside Solution is not local variable, so if I delete the file from my method, there will be no error. So @talex 's anwser is right in this case.

However since my problem is to find a method to pass a File to inner class and assign the variable with selectedFile, I couldn't find a way for it. My workaround is based on @Chang Liu's answer.

My revised code is as below:

public class Solution extends JFrame {
    private static final String FILE_NAME_1 = "my file1";
    private File file1;
    private void setNewButton(Container contentPane, final String fileName, String format) {
        contentPane.add(Box.createVerticalStrut(5));
        final Label label = new Label("Select " + fileName + " in ." + format +" format");
        contentPane.add(label);
        contentPane.add(Box.createVerticalStrut(10));
        Button selection = new Button("Select " + fileName);
        contentPane.add(selection);
        selection.addActionListener(new FileSelectionListener("Only " + format + " is allowed", format) {
            @Override
            protected void setSelection(File selectedFile) {
                setFile(selectedFile, fileName);  // no compilation error here
                label.setText("Selected" + fileName + selectedFile.getAbsolutePath());
            }
        });
    }

    public uploadFiles() {
        Container contentPane = this.getContentPane();
        setNewButton(contentPane, FILE_NAME_1, "xls", file1);
    }

    private void setFile(File file, String fileName) {
        switch (fileName) {
            case FILE_NAME_1:
                sollFile = file;
                break;
            default:
                throw new AssertionError("Unknown File");
        }
    }
}

Still, welcome to give me any advise if you have a better answer. :)


问:
Should I use CSS unit pt for UI controls?
I am working on some UI controls and wondering if I should use pt for the widths, heights, border sizes, margins, paddings, and font sizes? I want the controls to be scalable and look the same on every screen and projector.

Is there something else I should worry about when designing for scalable user interfaces? I am already using non-raster based graphics (colors and SVG).

答:
As has been mentioned,  1 point is 1/72 of an inch.  The screen I'm using has 1200 pixels on a height of 20cm.  If I project it,  those 1200 pixels spread to 3 metres.

There are many measurements in the w3c CSS specification,  many are used but few properly.

Your best bet is to use em's for layout which is related to the font in use.  Percentages can also be used.

However,  you'll need to 'nudge' some browser layouts by "a gnat's tadger",  particularly when looking at buttons, dropdowns and text boxes.  Often these are setting something to position relative to nudge it up/left/down/whatever.  Typical examples are when IE and Firefox have slight differences.

It's quite ambitious to have your forms rendering "the same on all screens and projectors", implying different browsers all look the same.


问:
Django Testing - loading data into the database before loading the apps
I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database.

Let me explain with some (very simplified) code :

I have a django view which is something like :

view.py

```<code>from myapp.models import Item
from myapp.utils import MyClass

# need to initialize with the set of items
item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

class MyView(APIView):
    def post(selfself, request):
        result = my_class_object.process(request.data)
        return Response(result)
</code>```

So basically I need to initialize a class with some data from the database, and I then use this class in my view to process the data received by the endpoint.

Now the test :

my_test.py

```<code>from rest_framework.test import APILiveServerTestCase
from myapp.models import Item

class MyTest(APILiveServerTestCase):

    def setUp(self):
        self.URL = '/some_url_linking_to_myview/'

        # load some data
        Item.objects.create(name="first item")
        Item.objects.create(name="second item")

    def test_myview_return_correct_result(self):
        post_data = {"foo"}
        response = self.client.post(self.URL,
                                    data=post_data,
                                    format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, {"my_expected_result"})
</code>```

When running the test, what currently happens is that view.py is loaded before the setUp() method get excecuted, so when I instantiate the class with these two lines :

```<code>item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)
</code>```

the database is still empty.

I'm wondering if there is a way to either get the data into the database before view.py get executed, or maybe somehow force reloading the app after setUp(), or instantiate my class somewhere else so it gets called after loading the data ?

thanks !

答:
Why not put the initiate code in the function and call from inside the post.

```<code>class MyView(APIView):
    def initialize(self):
        item_set = {item.name for item in Item.objects.all()}
        my_class_object = MyClass(item_set)

    def post(self, request):
        self.initialize()
        result = my_class_object.process(request.data)
        return Response(result)
</code>```

Edit 1
Optionally, you can use fixture to load MyClass objects in the database beforehand

```<code>class MyTest(APILiveServerTestCase):
    fixtures = [
        // my class objects fixtures file
    ]
    def setUp():
        // rest of the code
</code>```

Body:
I'm currently writting some tests for a Django app (+ REST framework), and having some issues loading the test data into the database.

Let me explain with some (very simplified) code :

I have a django view which is something like :

view.py

from myapp.models import Item
from myapp.utils import MyClass

# need to initialize with the set of items
item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

class MyView(APIView):
    def post(selfself, request):
        result = my_class_object.process(request.data)
        return Response(result)

So basically I need to initialize a class with some data from the database, and I then use this class in my view to process the data received by the endpoint.

Now the test :

my_test.py

from rest_framework.test import APILiveServerTestCase
from myapp.models import Item

class MyTest(APILiveServerTestCase):

    def setUp(self):
        self.URL = '/some_url_linking_to_myview/'

        # load some data
        Item.objects.create(name="first item")
        Item.objects.create(name="second item")

    def test_myview_return_correct_result(self):
        post_data = {"foo"}
        response = self.client.post(self.URL,
                                    data=post_data,
                                    format='json')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.data, {"my_expected_result"})

When running the test, what currently happens is that view.py is loaded before the setUp() method get excecuted, so when I instantiate the class with these two lines :

item_set = {item.name for item in Item.objects.all()}
my_class_object = MyClass(item_set)

the database is still empty.

I'm wondering if there is a way to either get the data into the database before view.py get executed, or maybe somehow force reloading the app after setUp(), or instantiate my class somewhere else so it gets called after loading the data ?

thanks !

Body:
Why not put the initiate code in the function and call from inside the post.

class MyView(APIView):
    def initialize(self):
        item_set = {item.name for item in Item.objects.all()}
        my_class_object = MyClass(item_set)

    def post(self, request):
        self.initialize()
        result = my_class_object.process(request.data)
        return Response(result)

Edit 1
Optionally, you can use fixture to load MyClass objects in the database beforehand

class MyTest(APILiveServerTestCase):
    fixtures = [
        // my class objects fixtures file
    ]
    def setUp():
        // rest of the code


问:
Do we have to create db and schema in mongodb before using it in node app using mongoose?
I am a beginner to MEAN stack,I have one doubt that if I want to use any database and schema in my app using mongoose .Is it important that the same database and schema should exist in mongo db before?</p>

答:
Mongodb is schema-less. In other words the schema lives in the application. So no separate schema definitely is required in Mongodb prior to using it. Both database and collection (schema) gets created on the fly while using it.

However if authentication is enabled in Mongodb, then the userid should have sufficient privilege to access the database and create collections within them.


问:
sql 2014 problems storing decimal
i have a stored procedure and i initially create a temp table.  i populate the first 3 columns and then i want to get the percentage when jobs are voided.  but i can't seem to get a good value.  if Void=10 and Total_Jobs=59 then 10/59 = 0.16 but it populates table with zero.  what am i doing wrong?</p>

```<code>Create table #tbl_WeeklyJobsRpt
(
Region_Code varchar(25),
Void int DEFAULT 0,
Total_Jobs int DEFAULT 0,
Void_Pctg decimal(10,2) DEFAULT 0
)

-- Void_Pctg
Update #tbl_WeeklyJobsRpt
  set Void_Pctg = ((Void)/Total_Jobs)
Where Void <> 0
</code>```

答:
@Alex, that was the correct answer, thank you.
I had to set my fields as float and then when i divided later on, it all worked.  I thought I had tried that already but obviously i missed a detail somewhere.
Answer here:</p>

Title: sql 2014 problems storing decimal

Body:
i have a stored procedure and i initially create a temp table.  i populate the first 3 columns and then i want to get the percentage when jobs are voided.  but i can't seem to get a good value.  if Void=10 and Total_Jobs=59 then 10/59 = 0.16 but it populates table with zero.  what am i doing wrong?

Create table #tbl_WeeklyJobsRpt
(
Region_Code varchar(25),
Void int DEFAULT 0,
Total_Jobs int DEFAULT 0,
Void_Pctg decimal(10,2) DEFAULT 0
)

-- Void_Pctg
Update #tbl_WeeklyJobsRpt
  set Void_Pctg = ((Void)/Total_Jobs)
Where Void <> 0


问:
r- transforming columns, calling them by $name, using a loop
imported tibble from textfile. Many numeric columns are imported as "chr". I guess it's because they contain a "," instead of a ".".
My goal is to write a loop which runs through the names of desired columns, replaces "," with "." and converts columns into "num".
Little example:

```<code>data <- data.frame("A1" =c("2,1","2,1","2,1"), "A2" =c("1,3","1,3","1,3"),
                   stringsAsFactors = F) %>% as.tibble() #example data
colname <- c("A1", "A2") #creating variable for loop

for(i in colname) {
    nam <- paste0("data$", i)
    assign(nam, as.numeric(gsub(",",".", eval(parse(text = paste0("data$",i))))) )
  }
</code>```

Instead of overwriting the existing column, R creates a new variable:

```<code>data$A1 # that's the existing column as part of the tibble
[1] "2,1" "2,1" "2,1"
`data$A1` # thats just a new variable. mind the little``
[1] 2.1 2.1 2.1
</code>```

I also tried to assign (<-) the new numeric values via eval, but that does not work either.

```<code>eval(parse(text = paste0("data$", i))) <- as.numeric(
gsub(",",".", eval(parse(text = paste0("data$",i)))))

Error: target of assignment expands to non-language object
</code>```

Any suggestions on how to transform? I have the same issue with other columns that I want to aggregate to a new variable. This variable should also be part of the existing tibble. I could do it by hand. This would take lots of time and probably produce many mistakes.
Thanks a lot!
Sam

答:
As you are already working with the tidyverse, you can use dplyr::mutate_at and the colname variable you have already defined.

```<code>data %>%
  mutate_at(.vars = colname,
            .funs = function(x) { as.numeric(gsub(",", ".", x))  })
</code>```

Body:
imported tibble from textfile. Many numeric columns are imported as "chr". I guess it's because they contain a "," instead of a ".".
My goal is to write a loop which runs through the names of desired columns, replaces "," with "." and converts columns into "num".
Little example:

data <- data.frame("A1" =c("2,1","2,1","2,1"), "A2" =c("1,3","1,3","1,3"),
                   stringsAsFactors = F) %>% as.tibble() #example data
colname <- c("A1", "A2") #creating variable for loop

for(i in colname) {
    nam <- paste0("data$", i)
    assign(nam, as.numeric(gsub(",",".", eval(parse(text = paste0("data$",i))))) )
  }

Instead of overwriting the existing column, R creates a new variable:

data$A1 # that's the existing column as part of the tibble
[1] "2,1" "2,1" "2,1"
`data$A1` # thats just a new variable. mind the little``
[1] 2.1 2.1 2.1

I also tried to assign (<-) the new numeric values via eval, but that does not work either.

eval(parse(text = paste0("data$", i))) <- as.numeric(
gsub(",",".", eval(parse(text = paste0("data$",i)))))

Error: target of assignment expands to non-language object

Any suggestions on how to transform? I have the same issue with other columns that I want to aggregate to a new variable. This variable should also be part of the existing tibble. I could do it by hand. This would take lots of time and probably produce many mistakes.
Thanks a lot!
Sam

Body:
As you are already working with the tidyverse, you can use dplyr::mutate_at and the colname variable you have already defined.

data %>%
  mutate_at(.vars = colname,
            .funs = function(x) { as.numeric(gsub(",", ".", x))  })


问:
Multiprocessing c in gtk c
I built a code using multithreading and it works just fine as it is. When I click the button it start the loop writing in the console and when I click again it stops.

But, when I try to implement my real code there an error pops up: error corrupted double linked list.

I thinks it's because Thread are in the same memory space. I'm thinking about switching to process instead. Is there any library? Because all I can find are fork() and exec() and i'm not sure what I can do with them.

So how do I handle multiprocessing in a gtk application?

```<code>#include <pthread.h>
#include <gtk/gtk.h>

int CLICK;

void* fonc(void* arg){
 int i;
 while (CLICK==1){
    printf("nope \n");
    usleep(100000); //wait
 }
}

static void cb_clicked( GtkButton *button, gpointer   data )
{
 pthread_t interface, lancementWhile; //déclaration des deux tâches
    /* No need to call gdk_threads_enter/gdk_threads_leave,
       since gtk callbacks are executed withing main lock. */
     if (CLICK==0){
        CLICK=1;
        pthread_create(&lancementWhile, NULL, fonc, (void*)NULL);
        printf("you started \n");
        gtk_button_set_label( button, "Clicked" );

     }
     else{
        CLICK=0;
        printf("you stoped \n");
         gtk_button_set_label( button, "Unclicked" );
    }
}

void *creationInterface(void *arg){

    GtkWidget *window;
    GtkWidget *button;

    /* Do stuff as usual */
    gtk_init( NULL, NULL );

    window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
    g_signal_connect( G_OBJECT( window ), "destroy",
                      G_CALLBACK( gtk_main_quit ), NULL );

    button = gtk_button_new_with_label( "Initial value" );
    g_signal_connect( G_OBJECT( button ), "clicked",
                      G_CALLBACK( cb_clicked ), NULL );
    gtk_container_add( GTK_CONTAINER( window ), button );

    gtk_widget_show_all( window );

    gtk_main();
}

int main(void)

{
 /* Secure glib */
    if( ! g_thread_supported() )
        g_thread_init( NULL );

    /* Secure gtk */
    gdk_threads_init();

    /* Obtain gtk's global lock */
    gdk_threads_enter();

    CLICK=0;
    pthread_t interface;
    pthread_create(&interface, NULL, creationInterface, NULL);
    pthread_join(interface, NULL);

}
</code>```

答: gtk_main() should be call from main only and you should use flag to control threads.</p>

Title: Multiprocessing c in gtk c

Body:
I built a code using multithreading and it works just fine as it is. When I click the button it start the loop writing in the console and when I click again it stops.

But, when I try to implement my real code there an error pops up: error corrupted double linked list.

I thinks it's because Thread are in the same memory space. I'm thinking about switching to process instead. Is there any library? Because all I can find are fork() and exec() and i'm not sure what I can do with them.

So how do I handle multiprocessing in a gtk application?

#include <pthread.h>
#include <gtk/gtk.h>

int CLICK;

void* fonc(void* arg){
 int i;
 while (CLICK==1){
    printf("nope \n");
    usleep(100000); //wait
 }
}

static void cb_clicked( GtkButton *button, gpointer   data )
{
 pthread_t interface, lancementWhile; //déclaration des deux tâches
    /* No need to call gdk_threads_enter/gdk_threads_leave,
       since gtk callbacks are executed withing main lock. */
     if (CLICK==0){
        CLICK=1;
        pthread_create(&lancementWhile, NULL, fonc, (void*)NULL);
        printf("you started \n");
        gtk_button_set_label( button, "Clicked" );

     }
     else{
        CLICK=0;
        printf("you stoped \n");
         gtk_button_set_label( button, "Unclicked" );
    }
}

void *creationInterface(void *arg){

    GtkWidget *window;
    GtkWidget *button;

    /* Do stuff as usual */
    gtk_init( NULL, NULL );

    window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
    g_signal_connect( G_OBJECT( window ), "destroy",
                      G_CALLBACK( gtk_main_quit ), NULL );

    button = gtk_button_new_with_label( "Initial value" );
    g_signal_connect( G_OBJECT( button ), "clicked",
                      G_CALLBACK( cb_clicked ), NULL );
    gtk_container_add( GTK_CONTAINER( window ), button );

    gtk_widget_show_all( window );

    gtk_main();
}

int main(void)

{
 /* Secure glib */
    if( ! g_thread_supported() )
        g_thread_init( NULL );

    /* Secure gtk */
    gdk_threads_init();

    /* Obtain gtk's global lock */
    gdk_threads_enter();

    CLICK=0;
    pthread_t interface;
    pthread_create(&interface, NULL, creationInterface, NULL);
    pthread_join(interface, NULL);

}


问:
Nested hyperlinked areas without nested link elements in HTML source
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

```
|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|
```

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

```<code><a href="xxx" style="display: block">
  Some text
  <a href="yyy">link</a>
</a>
</code>```

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

```<code><a href="xxx" ...>Some text</a>
<a href="yyy" ...>Link</a>
<a href="xxx" ...>& nbsp;</a>
...
</code>```

答:
Just place on onclick event handler on the outer element which when clicked calls "window.location ='yourURLhere';"

You could add a style attribute - "cursor:pointer" to get the hand cursor when mouse over.

You could also have a css hover code block to get the colour changes.

EDIT: just realised no javascript, so in that case, keep the 'a' tag and simply define a style for it in css, that way you can give it height, width, etc.

OwnerDisplayName: Jakub Narębski

Body:
I'd like to have something that looks and behaves as hyperlink inside larger rectangle (full page wide) which is also hyperlink. Below there is ASCII-art representation of what it should look like:

|-------------------------------------------|
| Some text  [_link_]                            |
|-------------------------------------------|

The whole outer rectangle (block element) is to be hyperlink. Inside this rectangle there should be some text, and at the end of this text there should be another link.

Unfortunately nesting links (A elements) is illegal in (X)HTML:

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested;
   an A element must not contain any other A elements.

(from http://www.w3.org/TR/html401/struct/links.html#h-12.2.2), so the most natural way of implementing above

  Some text
  link

is not valid HTML. What is even worse is that some web browsers in some cases enforce this requirement by moving inner link element just outside closing element of outer link element. This of course utterly breaks layout.

So what I'd like to ask is how to arrive at layout presented above using HTML and CSS (but no JavaScript), but without nested link elements in HTML source. It would be nice if behaviour was as close as possible to the one with nested link elements (for browsers which are not overly strict in implementing HTML standard).

Edit (16-01-2009)

Clarification: Solutions which use more than two link elements are perfectly acceptable

Some text
Link
& nbsp;
...

LastEditorDisplayName: Jakub Narębski

OwnerDisplayName: Jobo

LastEditorDisplayName: Jobo


问:
listview.setOnItemSelectedListener does not work
I'm using a string arrayList and a string arrayAdapter to populate a listView, this is my xml file:

```<code><LinearLayout
                android:id="@+id/llHoursD"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:descendantFocusability="blocksDescendants"
                android:visibility="visible"
                android:weightSum="1">

                <TextView
                    android:id="@+id/tvDay"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp"
                    android:layout_toRightOf="@+id/ivName"
                    android:background="@null"
                    android:enabled="false"
                    android:gravity="center_horizontal"
                    android:inputType="textPersonName"
                    android:text="Fecha Seleccionada"
                    android:textColor="@color/category"
                    android:textColorHint="@color/category"
                    android:visibility="visible"
                    android:textSize="17sp" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:layout_marginTop="10dp"
                android:scaleType="centerCrop"
                android:src="@drawable/separator" />

            <ListView
                android:id="@+id/lvReservationTime"
                android:layout_width="match_parent"
                android:layout_height="163dp"
                android:divider="@null"
                android:dividerHeight="8dp"
                android:layout_marginTop="8dp"
                android:visibility="visible"
                android:layout_weight="1.99">
            </ListView>

            </LinearLayout>
</code>```

This is the layout where the textview that is in the list is located

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtItemAva"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
</code>```

And this is the code in the fragment

```<code>listHourAvali = new ArrayList<>();
            adapterListHourAvali = new ArrayAdapter<String>(getActivity(),R.layout.detail_list_reservation,R.id.tvAvailiHours,listHourAvali);
            mLvReservationTime.setAdapter(adapterListHourAvali);

            mLvReservationTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    Toast.makeText(getActivity(),"Prueba",Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });
</code>```

The list is filled in another method, the problem is that pressing an item in the list does not go into setOnItemSelectedListener. What is the problem here?

答:
You have to be careful, selecting something is a different action than clicking something.

see: OnItemSelectedListener vs OnItemClickedListener

If you want to do some action when a list item is clicked (!= selected) then you should use the onClickListener:

```<code>mLvReservationTime.setOnItemClickListener(new OnItemClickListener()
{
  @Override
  public void onItemClick(AdapterView<?> adapter, View v, int position,
        long arg3)
  {
        // do what you intend to do on click of listview row
        Toast.makeText(getActivity(),"Prueba", Toast.LENGTH_LONG).show();
  }
});
</code>```

Body:
I'm using a string arrayList and a string arrayAdapter to populate a listView, this is my xml file:

<LinearLayout
                android:id="@+id/llHoursD"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:descendantFocusability="blocksDescendants"
                android:visibility="visible"
                android:weightSum="1">

                <TextView
                    android:id="@+id/tvDay"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="15dp"
                    android:layout_toRightOf="@+id/ivName"
                    android:background="@null"
                    android:enabled="false"
                    android:gravity="center_horizontal"
                    android:inputType="textPersonName"
                    android:text="Fecha Seleccionada"
                    android:textColor="@color/category"
                    android:textColorHint="@color/category"
                    android:visibility="visible"
                    android:textSize="17sp" />

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:layout_marginTop="10dp"
                android:scaleType="centerCrop"
                android:src="@drawable/separator" />

            <ListView
                android:id="@+id/lvReservationTime"
                android:layout_width="match_parent"
                android:layout_height="163dp"
                android:divider="@null"
                android:dividerHeight="8dp"
                android:layout_marginTop="8dp"
                android:visibility="visible"
                android:layout_weight="1.99">
            </ListView>

            </LinearLayout>

This is the layout where the textview that is in the list is located

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/txtItemAva"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

And this is the code in the fragment

listHourAvali = new ArrayList<>();
            adapterListHourAvali = new ArrayAdapter<String>(getActivity(),R.layout.detail_list_reservation,R.id.tvAvailiHours,listHourAvali);
            mLvReservationTime.setAdapter(adapterListHourAvali);

            mLvReservationTime.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                    Toast.makeText(getActivity(),"Prueba",Toast.LENGTH_LONG).show();
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

The list is filled in another method, the problem is that pressing an item in the list does not go into setOnItemSelectedListener. What is the problem here?

Body:
You have to be careful, selecting something is a different action than clicking something.

see: OnItemSelectedListener vs OnItemClickedListener

If you want to do some action when a list item is clicked (!= selected) then you should use the onClickListener:

mLvReservationTime.setOnItemClickListener(new OnItemClickListener()
{
  @Override
  public void onItemClick(AdapterView<?> adapter, View v, int position,
        long arg3)
  {
        // do what you intend to do on click of listview row
        Toast.makeText(getActivity(),"Prueba", Toast.LENGTH_LONG).show();
  }
});


问:
How can i get display column value in sql

This is the output of the query "select * from FindNthHighestNumber order by ProductAmount desc"

I want the individual value of bordered green portion of the above image. How can i do that? something like row = '2'

答:
I believe this is what you want:

```<code>select f.*, row_number() over (order by f.ProductAmount desc)
from FindNthHighestNumber f
order by f.ProductAmount desc;
</code>```

If you just want the numbers, then remove the f.* from the select.  If you want to select a particular value, then one method is to use a subquery:

```<code>select f.*
from (select f.*, row_number() over (order by f.ProductAmount desc) as seqnum
      from FindNthHighestNumber f
     ) f
where seqnum = 2;
</code>```

Or, if you just want the second row, then a better method is offset/fetch:

```<code>select f.*
from FindNthHighestNumber f
order by f.ProductAmount desc
offset 1
fetch first 1 row only;
</code>```

Body:
I believe this is what you want:

select f.*, row_number() over (order by f.ProductAmount desc)
from FindNthHighestNumber f
order by f.ProductAmount desc;

If you just want the numbers, then remove the f.* from the select.  If you want to select a particular value, then one method is to use a subquery:

select f.*
from (select f.*, row_number() over (order by f.ProductAmount desc) as seqnum
      from FindNthHighestNumber f
     ) f
where seqnum = 2;

Or, if you just want the second row, then a better method is offset/fetch:

select f.*
from FindNthHighestNumber f
order by f.ProductAmount desc
offset 1
fetch first 1 row only;


问:
Sum two input values in realtime
I want to sum two different inputs in a third realtime variable. I will explain better what I want:

1 variable : 100 (input)

2 variable : 150 (input)

sum : 250 (not input)

How can I do this?

答:
I would anyday recommend not using client side to handle such use cases but if you need to get it done using JS(JQuery), have a look below:

If HTML:

```<code><input class="one" type="number" />
<input class="two" type="number" />

<p class="result"></p>
</code>```

then JQuery should be:

```<code>$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});
</code>```

$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="one" type="number" />
<input class="two" type="number" />

<p class="result"></p></code>```

Title: Sum two input values in realtime

Body:
I would anyday recommend not using client side to handle such use cases but if you need to get it done using JS(JQuery), have a look below:

If HTML:

<input class="one" type="number" />
<input class="two" type="number" />

<p class="result"></p>

then JQuery should be:

$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});

$(".one, .two").keyup(function() {
  if($('.one').val() != "" && $('.two').val() != "") {
    var result = parseInt($('.one').val()) + parseInt($('.two').val());
    $('.result').text(result);
  }
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="one" type="number" />
<input class="two" type="number" />

<p class="result"></p>


问:
MVC Why unit test controllers
just a Provocative Question

why do you thing we should unit test controllers in MVC why not just write test against models or service layer.

答: One point is testing your routes.</p>

Title: MVC Why unit test controllers

Body: One point is testing your routes.


问:
How to implement azure push notifications in ionic 2 for iOS. (Closed)
I tried  all possible  way but not able to implement  azure push notifications  in ionic 2 .
Thanks in advance :-)</p>

答:
This link shows how to plug everything.

https://learn.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-cordova-get-started-push

And instead of use the phone gap version, you can install the Ionic Native version of that plugin.

http://ionicframework.com/docs/native/push/

Note: It's better if you post the code of what have you tried so we can give you a specific answer.

ContentLicense: CC BY-SA 4.0


问:
Align UIAlertAction Title to the Left
I've been trying to align the title of an UIAlertAction item, but I can't seem to make it work.

Do you guys have any idea how to make it work in Objective-C?

答:
UIAlertController is an opaque class. That kind of customization isn't supported. If you want, you can try to roll your own, or find an open source alternative.

I've tried hacking it by traversing the view hierarchy and finding labels, but it didn't seem to work. I also tested with UIAppearance, but labels don't respond to alignment changes.

My sample code (Swift) is on GitHub.

Some open source alternatives:

DAAlertController

PMAlertController

EZAlertController

Title: Align UIAlertAction Title to the Left


问:
easy code not working on empty project ( binding ,input , ng model) in any browser
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">
    Name: <input ng-model="firstname">
    <h1>{{firstname}}</h1>
</div></code>```

SOURCE

答:
In the example that you are referring as well as in the code that you posted above, you have:

```<code>$scope.firstname = "John";
$scope.lastname = "Doe";
</code>```

But in screenshot of your script.js you have:

```<code>$scope.data = {
    firstname : "John";
    lastname: "Doe";
};
</code>```

Both of these are different. The valid HTML attribute with each of these will be:

Method One: Works with code posted above

```<code>Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>
</code>```

Method Two: Works with the script.js as per your screenshot

```<code>Name: <input ng-model="data.firstname">
<h1>{{data.firstname}}</h1>
</code>```

So use either one of them as per your JS code.

Body:
Im having a problem with the following code, is a simple one, i want to be able to se in my view what i put in the input text. but nothing is happening. when running in the online simulator no problem, but in my browser nothing happens. what im doing wrong?. my project is empty. Also tried it in firefox, explorer and chrome, and not working at all. the only thing i have is this pice of code. have no error in browser console... im using angular cli.
what im doing wrong guys? please help.

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.firstname = "John";
    $scope.lastname = "Doe";
});

    Name: <input ng-model="firstname">

{{firstname}}

SOURCE

Body:
In the example that you are referring as well as in the code that you posted above, you have:

$scope.firstname = "John";
$scope.lastname = "Doe";

But in screenshot of your script.js you have:

$scope.data = {
    firstname : "John";
    lastname: "Doe";
};

Both of these are different. The valid HTML attribute with each of these will be:

Method One: Works with code posted above

Name: <input ng-model="firstname">
<h1>{{firstname}}</h1>

Method Two: Works with the script.js as per your screenshot

Name: <input ng-model="data.firstname">
<h1>{{data.firstname}}</h1>

So use either one of them as per your JS code.


问:
Adding NSMutableAttributedString into a TextField
I have a custom UITextfield which I want when the user finishes typing, a small "R$" must be added at the begging of the text with different size.

I call the method to add the "R$" like this:

```<code>self.addTarget(self, action: #selector(setCurrencyLabelPosition), for: .editingDidEnd)
</code>```

and then I try to change the attributes and content like this:

```<code> func setCurrencyLabelPosition(){

        let fullText:String = "R$\((self.text)!)"
        self.text = fullText
        var attribute:NSMutableAttributedString = NSMutableAttributedString(attributedString:self.attributedText!)
        attribute.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: 12), range: NSRange(location:  0, length: 2))
        self.attributedText = attribute

    }
</code>```

the original text of this textfield is set for size 40.0, I want only the "R$" to be of size 12.0

The problem I'm facing is that the whole text gets the size 40.0
It prints the "R$" but the size of 40.

Is it possible to do what I'm trying to using NSMutableAttributedString?

答:
I had been working on your question, I think there is a bug in UITextField because if you modify the font to bigger font it works but if you do so but for small font then don't work.

I have done a custom class and added some customizable Inspectable properties, hope this finally help you

This is  how looks, Note: the glitch is because of my gif converter

```<code>import UIKit

@IBDesignable
class CustomTextField: UITextField {

    @IBInspectable var prefix : String = ""
    @IBInspectable var removePrefixOnEditing : Bool = true

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.addTarget(self, action: #selector(setCurrencyLabelPosition), for: .editingDidEnd)
        self.addTarget(self, action: #selector(removePrefix), for: .editingDidBegin)
    }

    func removePrefix(){
        if self.attributedText != nil
        {
            if(self.removePrefixOnEditing)
            {
                self.defaultTextAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 20)]
                let prefixRange = NSString(string: (self.attributedText?.string)!).range(of: prefix)
                if(prefixRange.location != NSNotFound)
                {
                    self.attributedText = NSAttributedString(string: (self.attributedText?.string.replacingOccurrences(of: prefix, with: ""))!, attributes: self.defaultTextAttributes)
                }
            }
        }
    }

    func setCurrencyLabelPosition(){

        if self.attributedText != nil
        {
            var fullText:String = "\((self.attributedText?.string)!)"
            if(NSString(string: (self.attributedText?.string)!).range(of: prefix).location == NSNotFound)
            {
                fullText = "\(prefix)\((self.attributedText?.string)!)"
            }
            //hacky part, seems to be a bug in UITextField
            self.defaultTextAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 10)]
            self.attributedText = NSAttributedString(attributedString: self.changeFontForText(originalText: fullText, text: prefix, basicFont: UIFont.systemFont(ofSize: 20), newFont: UIFont.systemFont(ofSize: 12)))
        }
    }

    func changeFontForText(originalText:String,text:String,basicFont:UIFont, newFont:UIFont) -> NSMutableAttributedString
    {
        let resultAttributedString = NSMutableAttributedString(string: originalText, attributes: [NSFontAttributeName : basicFont])
        let range = NSString(string: originalText).range(of: text)
        if(range.location != NSNotFound)
        {
            resultAttributedString.setAttributes([NSFontAttributeName:newFont], range: range)
        }

        return resultAttributedString
    }

}
</code>```

Hope this helps

Body:
I have a custom UITextfield which I want when the user finishes typing, a small "R$" must be added at the begging of the text with different size.

I call the method to add the "R$" like this:

self.addTarget(self, action: #selector(setCurrencyLabelPosition), for: .editingDidEnd)

and then I try to change the attributes and content like this:

 func setCurrencyLabelPosition(){

        let fullText:String = "R$\((self.text)!)"
        self.text = fullText
        var attribute:NSMutableAttributedString = NSMutableAttributedString(attributedString:self.attributedText!)
        attribute.addAttribute(NSFontAttributeName, value:UIFont.systemFont(ofSize: 12), range: NSRange(location:  0, length: 2))
        self.attributedText = attribute

    }

the original text of this textfield is set for size 40.0, I want only the "R$" to be of size 12.0

The problem I'm facing is that the whole text gets the size 40.0
It prints the "R$" but the size of 40.

Is it possible to do what I'm trying to using NSMutableAttributedString?

Body:
I had been working on your question, I think there is a bug in UITextField because if you modify the font to bigger font it works but if you do so but for small font then don't work.

I have done a custom class and added some customizable Inspectable properties, hope this finally help you

This is  how looks, Note: the glitch is because of my gif converter

import UIKit

@IBDesignable
class CustomTextField: UITextField {

    @IBInspectable var prefix : String = ""
    @IBInspectable var removePrefixOnEditing : Bool = true

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        self.addTarget(self, action: #selector(setCurrencyLabelPosition), for: .editingDidEnd)
        self.addTarget(self, action: #selector(removePrefix), for: .editingDidBegin)
    }

    func removePrefix(){
        if self.attributedText != nil
        {
            if(self.removePrefixOnEditing)
            {
                self.defaultTextAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 20)]
                let prefixRange = NSString(string: (self.attributedText?.string)!).range(of: prefix)
                if(prefixRange.location != NSNotFound)
                {
                    self.attributedText = NSAttributedString(string: (self.attributedText?.string.replacingOccurrences(of: prefix, with: ""))!, attributes: self.defaultTextAttributes)
                }
            }
        }
    }

    func setCurrencyLabelPosition(){

        if self.attributedText != nil
        {
            var fullText:String = "\((self.attributedText?.string)!)"
            if(NSString(string: (self.attributedText?.string)!).range(of: prefix).location == NSNotFound)
            {
                fullText = "\(prefix)\((self.attributedText?.string)!)"
            }
            //hacky part, seems to be a bug in UITextField
            self.defaultTextAttributes = [NSFontAttributeName : UIFont.systemFont(ofSize: 10)]
            self.attributedText = NSAttributedString(attributedString: self.changeFontForText(originalText: fullText, text: prefix, basicFont: UIFont.systemFont(ofSize: 20), newFont: UIFont.systemFont(ofSize: 12)))
        }
    }

    func changeFontForText(originalText:String,text:String,basicFont:UIFont, newFont:UIFont) -> NSMutableAttributedString
    {
        let resultAttributedString = NSMutableAttributedString(string: originalText, attributes: [NSFontAttributeName : basicFont])
        let range = NSString(string: originalText).range(of: text)
        if(range.location != NSNotFound)
        {
            resultAttributedString.setAttributes([NSFontAttributeName:newFont], range: range)
        }

        return resultAttributedString
    }

}

Hope this helps


问:
Deploying Symfony 1.4 project
I have recently developed a project which is written using Symfony 1.4 which I installed through PEAR. In previous Symfony versions there used to be freeze and unfreeze functions to copy all the necessary files, but in this versions these functions are missing. So my question is - what is the fastest way to deploy my project on a shared hosting?

答:
In your config/ProjectConfiguration.class.php change the require_once statement for sfCoreAutoload class. Make it search for symfony in lib/vendor/symfony:

```<code>require_once dirname(__FILE__) . '/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';
</code>```

Now you can do two things:

Copy whole symfony lib into lib/vendor/symfony dir. This way you always have symfony with your project. Drawback is you have to copy it while sending files to the server.

Create lib/vendor/symfony symbolic link pointing to your symfony lib. Advantage is you don't have to copy whole framework all the time. Drawback is you still have to put symfony in the same location on dev and production servers. However, symbolic link might be relative to the project (i.e. one level up).

Title: Deploying Symfony 1.4 project

Body:
In your config/ProjectConfiguration.class.php change the require_once statement for sfCoreAutoload class. Make it search for symfony in lib/vendor/symfony:

require_once dirname(__FILE__) . '/../lib/vendor/symfony/lib/autoload/sfCoreAutoload.class.php';

Now you can do two things:

Copy whole symfony lib into lib/vendor/symfony dir. This way you always have symfony with your project. Drawback is you have to copy it while sending files to the server.

Create lib/vendor/symfony symbolic link pointing to your symfony lib. Advantage is you don't have to copy whole framework all the time. Drawback is you still have to put symfony in the same location on dev and production servers. However, symbolic link might be relative to the project (i.e. one level up).


问:
Chain map with object on Spark
I'm creating an object for each line read of a file inside a map.

On a chained map, I try to access a variable from that object, but I receive an empty variable.
I'm using Spark Streamer

```<code>//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData(line))
     .map(userData => userData.myVar)
.print()
</code>```

And my UserData Class

```<code>class UserData(csvLine: String) extends Serializable{
  {
     myVar = csvLine
  }
  var myVar = ""
}
</code>```

答:
I was doing something wrong, as Scala declares myVar as empty, then I assign the line (I added a println on that scope and it gets assigned), and again it sets it to empty. I moved the assign to a method and it works as intended. </p>

```<code>//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData().init(line))
     .map(userData => userData.myVar)
.print()
///...

class UserData() extends Serializable{
  var myVar = ""
   def init(csvLine: String): UserData=
   {
     myVar = csvLine
     return this
  }
}
</code>```

Title: Chain map with object on Spark

Body:
I'm creating an object for each line read of a file inside a map.

On a chained map, I try to access a variable from that object, but I receive an empty variable.
I'm using Spark Streamer

//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData(line))
     .map(userData => userData.myVar)
.print()

And my UserData Class

class UserData(csvLine: String) extends Serializable{
  {
     myVar = csvLine
  }
  var myVar = ""
}

Body:
I was doing something wrong, as Scala declares myVar as empty, then I assign the line (I added a println on that scope and it gets assigned), and again it sets it to empty. I moved the assign to a method and it works as intended.

//..
val lines = ssc.textFileStream("CSVs/")
lines.map(line => new UserData().init(line))
     .map(userData => userData.myVar)
.print()
///...

class UserData() extends Serializable{
  var myVar = ""
   def init(csvLine: String): UserData=
   {
     myVar = csvLine
     return this
  }
}


Title: Error of "Not supported within a window function" occurs when, operating on columns of dataframe performed in Spark in scala

Body:
I have the following raw data and I need to clean it:

 03:35:20.299037 IP 10.0.0.1 > 10.0.0.2: ICMP echo request, id 8321, seq 17, length 64
    03:35:20.327290 IP 10.0.0.1 > 10.0.0.3: ICMP echo reply, id 8321, seq 17, length 64
    03:35:20.330845 IP 10.0.0.1 > 10.0.0.3: ICMP echo request, id 8311, seq 19, length 64
 03:35:20.330892 IP 10.0.0.1 > 10.0.0.3: ICMP echo request, id 8321, seq 17, length 64
    03:35:20.330918 IP 10.0.0.1 > 10.0.0.3: ICMP echo reply, id 8321, seq 17, length 64
    03:35:20.330969 IP 10.0.0.1 > 10.0.0.4: ICMP echo request, id 8311, seq 19, length 64
  03:35:20.331041 IP 10.0.0.1 > 10.0.0.4: ICMP echo request, id 8311, seq 19, length 64

I need to have the following output:

+---------------+-----------+-------------+----+------+---+----+
|   time_stamp_0|sender_ip_1|receiver_ip_2|rank|count | xi|pi  |
+---------------+-----------+-------------+----+------+---+----+
|03:35:20.299037|   10.0.0.1|     10.0.0.2|   1|     7| 1 |0.14|
|03:35:20.327290|   10.0.0.1|     10.0.0.3|   1|     7| 4 |0.57|
|03:35:20.330845|   10.0.0.1|     10.0.0.3|   2|     7| 4 |0.57|
|03:35:20.330892|   10.0.0.1|     10.0.0.3|   3|     7| 4 |0.57|
|03:35:20.330918|   10.0.0.1|     10.0.0.3|   4|     7| 4 |0.57|
|03:35:20.330969|   10.0.0.1|     10.0.0.4|   1|     7| 2 |0.28|
|03:35:20.331041|   10.0.0.1|     10.0.0.4|   2|     7| 2 |0.28|

According to above dataframe, I need to put the total number of repetition of each source IP and destination IP as "xi" column, the number of total rows as "count" column and the devision of xi/count as "pi" column. My problem will start when I want to calculate xi and I got the following error:

   Exception in thread "main" org.apache.spark.sql.AnalysisException: Expression 'count#11L' not supported within a window function.;;
Project [time_stamp_0#3, sender_ip_1#4, receiver_ip_2#5, count#11L, rank#20, xi#45, pi#90]
+- Project [time_stamp_0#3, sender_ip_1#4, receiver_ip_2#5, count#11L, rank#20, xi#45, _we0#109L, (cast(xi#45 as double) / cast(_we0#109L as double)) AS pi#90]
   +- Window [count#11L windowspecdefinition(sender_ip_1#4, receiver_ip_2#5, ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS _we0#109L], [sender_ip_1#4, receiver_ip_2#5]

    ...

I have the following code:

      val customSchema = StructType(Array(
      StructField("time_stamp_0", StringType, true),
      StructField("sender_ip_1", StringType, true),
      StructField("receiver_ip_2", StringType, true)))

    ///////////////////////////////////////////////////make train dataframe
    val Dstream_Train = sc.textFile("/Users/saeedtkh/Desktop/sharedsaeed/Test/dsetcopy.txt")

    val Row_Dstream_Train = Dstream_Train.map(line => line.split(",")).map(array => {

      val array1 = array(0).trim.split("IP")
      val array2 = array1(1).split(">")
      val array3 = array2(1).split(":")

      val first = Try(array1(0).trim) getOrElse ""
      val second = Try(array2(0).trim) getOrElse ""
      val third = Try(array3(0)) getOrElse ""

      Row.fromSeq(Seq(first, second, third))
    })

    val Frist_Dataframe = session.createDataFrame(Row_Dstream_Train, customSchema)
    val columns1and2_count = Window.partitionBy("sender_ip_1", "receiver_ip_2")
    val columns1and2_rank = Window.partitionBy("sender_ip_1", "receiver_ip_2").orderBy("time_stamp_0")
    // <-- matches groupBy
    //Add rank() to df
    val Dataframe_add_rank = Frist_Dataframe.withColumn("count", count($"receiver_ip_2") over columns1and2_count).distinct()
    //Add cout to df
    val Dataframe_add_rank_count = Dataframe_add_rank.withColumn("rank", rank() over columns1and2_rank).distinct()// Dataframe.show()
    //Add x(i) to df
    val Dataframe_add_rank_count_xi = Dataframe_add_rank_count.withColumn("xi", rank() over columns1and2_rank).distinct()// Dataframe.show()
    //Add p(i)=maxrank(x(i))/count
    val Dataframe_add_rank_count_xi_pi = Dataframe_add_rank_count_xi.withColumn("pi", $"xi" / ($"count").over(columns1and2_count))// Dataframe.show()
  val std_dev=Dataframe_add_rank_count.agg(stddev_pop($"rank"))
    val stdDevValue = std_dev.head.getDouble(0)
    std_dev.show()
    //Add attack status

    val final_add_count_rank_xi_attack = Dataframe_add_rank_count_xi_pi.withColumn("attack", when($"rank" < stdDevValue , 0).otherwise(1))

Dataframe_add_rank_count_xi_pi.show()

Update:
According to answer one, I got the following output:

+---------------+-----------+-------------+-----+----+---+---+------+
|   time_stamp_0|sender_ip_1|receiver_ip_2|count|rank| xi| pi|attack|
+---------------+-----------+-------------+-----+----+---+---+------+
|03:35:20.330969|   10.0.0.1|     10.0.0.4|    2|   1|  4|2.0|     0|
|03:35:20.331041|   10.0.0.1|     10.0.0.4|    2|   2|  4|2.0|     1|
|03:35:20.299037|   10.0.0.1|     10.0.0.2|    1|   1|  4|4.0|     0|
|03:35:20.327290|   10.0.0.1|     10.0.0.3|    4|   1|  4|1.0|     0|
|03:35:20.330845|   10.0.0.1|     10.0.0.3|    4|   2|  4|1.0|     1|
|03:35:20.330892|   10.0.0.1|     10.0.0.3|    4|   3|  4|1.0|     1|
|03:35:20.330918|   10.0.0.1|     10.0.0.3|    4|   4|  4|1.0|     1|
+---------------+-----------+-------------+-----+----+---+---+------+

So the xi is not correct. :(
Can you help me? Thanks in advance.

Body:
If you are looking to populate xi column with max of count. As you said

the maximum number of repetition for each source and destination IP as "xi" column

then you should be doing

val maxForXI = Dataframe_add_rank_count.agg(max("rank")).first.get(0)
val Dataframe_add_rank_count_xi = Dataframe_add_rank_count.withColumn("xi", lit(maxForXI))

you should get

+---------------+-----------+-------------+-----+----+---+
|time_stamp_0   |sender_ip_1|receiver_ip_2|count|rank|xi |
+---------------+-----------+-------------+-----+----+---+
|03:35:20.330969|10.0.0.1   | 10.0.0.4    |2    |1   |4  |
|03:35:20.331041|10.0.0.1   | 10.0.0.4    |2    |2   |4  |
|03:35:20.299037|10.0.0.1   | 10.0.0.2    |1    |1   |4  |
|03:35:20.327290|10.0.0.1   | 10.0.0.3    |4    |1   |4  |
|03:35:20.330845|10.0.0.1   | 10.0.0.3    |4    |2   |4  |
|03:35:20.330892|10.0.0.1   | 10.0.0.3    |4    |3   |4  |
|03:35:20.330918|10.0.0.1   | 10.0.0.3    |4    |4   |4  |
+---------------+-----------+-------------+-----+----+---+

for the last column pi you said

the devision of xi/count as "pi" column

so for that you should do

val Dataframe_add_rank_count_xi_pi = Dataframe_add_rank_count_xi.withColumn("pi", $"xi" / $"count")

You should have desired result as

+---------------+-----------+-------------+-----+----+---+---+
|   time_stamp_0|sender_ip_1|receiver_ip_2|count|rank| xi| pi|
+---------------+-----------+-------------+-----+----+---+---+
|03:35:20.330969|   10.0.0.1|     10.0.0.4|    2|   1|  4|2.0|
|03:35:20.331041|   10.0.0.1|     10.0.0.4|    2|   2|  4|2.0|
|03:35:20.299037|   10.0.0.1|     10.0.0.2|    1|   1|  4|4.0|
|03:35:20.327290|   10.0.0.1|     10.0.0.3|    4|   1|  4|1.0|
|03:35:20.330845|   10.0.0.1|     10.0.0.3|    4|   2|  4|1.0|
|03:35:20.330892|   10.0.0.1|     10.0.0.3|    4|   3|  4|1.0|
|03:35:20.330918|   10.0.0.1|     10.0.0.3|    4|   4|  4|1.0|
+---------------+-----------+-------------+-----+----+---+---+

Edited

Since the question was edited, final edited answer would be as below, (these are the codes after window functions are defined)

//Add rank() to df
val cnt = Frist_Dataframe.count
val Dataframe_add_rank = Frist_Dataframe.withColumn("count", lit(cnt))
//Add cout to df
val Dataframe_add_rank_count = Dataframe_add_rank.withColumn("rank", rank() over columns1and2_rank).distinct()// Dataframe.show()
//Add x(i) to df
val Dataframe_add_rank_count_xi = Dataframe_add_rank_count.withColumn("xi", count($"receiver_ip_2") over columns1and2_count)// Dataframe.show()
//Add p(i)=maxrank(x(i))/count
val Dataframe_add_rank_count_xi_pi = Dataframe_add_rank_count_xi.withColumn("pi", $"xi" / $"count")// Dataframe.show()

val std_dev=Dataframe_add_rank_count.agg(stddev_pop($"rank"))
val stdDevValue = std_dev.head.getDouble(0)
std_dev.show()
//Add attack status

val final_add_count_rank_xi_attack = Dataframe_add_rank_count_xi_pi.withColumn("attack", when($"rank" < stdDevValue , 0).otherwise(1))
final_add_count_rank_xi_attack.show()

I hope you get the right table this time.