问:
*ngFor on ng-template outputs nothing Angular2
Not sure why my *ngFor loop is printing nothing out. I have the following code in an html file:

```<code><table class="table table-hover">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Company</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <!-- NGFOR ATTEMPTED HERE -- no content printed -->
        <ng-template *ngFor="let xb of tempData">
            <tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle">
                <td>{{ xb.name }}</td>
                <td>{{ xb.email }}</td>
                <td>{{ xb.company }}</td>
                <td>{{ xb.status }}</td>
            </tr>
            <!-- other content -->
        </ng-template>
    </tbody>
</table>
</code>```

Then, in my simple component I have the following:

```<code>import { Component }        from '@angular/core';

@Component({
    selector: 'my-profile-exhibitors',
    templateUrl: './profile-exhibitors.component.html',
    styleUrls: ['./profile-exhibitors.component.scss']
})
export class ProfileExhibitorsComponent {
    public tempData: any = [
        {
            'name': 'name1',
            'email': 'email1@gmail',
            'company': 'company',
            'status': 'Complete'
        },
        {
            'name': 'name2',
            'email': 'email2@gmail',
            'company': 'company',
            'status': 'Incomplete'
        }
    ];
    constructor() {}
}
</code>```

When I run this code, I get zero output. Even weirder is that when I select the element using debug tools I see this:

Looks like it correctly recognizes my object, but then outputs nothing.

答:
I think what you want is

<ng-container *ngFor="let xb of tempData">
```

<p>or</p>

<pre class="lang-ts prettyprint-override"><code><ng-template ngFor let-xb [ngForOf]="tempData">
</code>```

Body:
Not sure why my *ngFor loop is printing nothing out. I have the following code in an html file:

            Name
            Email
            Company
            Status

        <ng-template *ngFor="let xb of tempData">

                {{ xb.name }}
                {{ xb.email }}
                {{ xb.company }}
                {{ xb.status }}

        </ng-template>

Then, in my simple component I have the following:

import { Component }        from '@angular/core';

@Component({
    selector: 'my-profile-exhibitors',
    templateUrl: './profile-exhibitors.component.html',
    styleUrls: ['./profile-exhibitors.component.scss']
})
export class ProfileExhibitorsComponent {
    public tempData: any = [
        {
            'name': 'name1',
            'email': 'email1@gmail',
            'company': 'company',
            'status': 'Complete'
        },
        {
            'name': 'name2',
            'email': 'email2@gmail',
            'company': 'company',
            'status': 'Incomplete'
        }
    ];
    constructor() {}
}

When I run this code, I get zero output. Even weirder is that when I select the element using debug tools I see this:

Looks like it correctly recognizes my object, but then outputs nothing.

Body:
I think what you want is

<ng-container *ngFor="let xb of tempData">

or

<ng-template ngFor let-xb [ngForOf]="tempData">


来源: stackexchange

问:
How to use a subquery for dbtable option in jdbc data source?
I want to use Spark to process some data from a JDBC source. But to begin with, instead of reading original tables from JDBC, I want to run some queries on the JDBC side to filter columns and join tables, and load the query result as a table in Spark SQL.

The following syntax to load raw JDBC table works for me:

```<code>df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="mydb.table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver" # mysql JDBC driver 5.1.41
).load()
df_table1.show() # succeeded
</code>```

According to Spark documentation (I'm using PySpark 1.6.3):

dbtable: The JDBC table that should be read. Note that anything that is valid
  in a FROM clause of a SQL query can be used. For example, instead of a
  full table you could also use a subquery in parentheses.

So just for experiment, I tried something simple like this:

```<code>df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="(SELECT * FROM mydb.table1) AS table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver"
).load() # failed
</code>```

It threw the following exception:

```<code>com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table1 WHERE 1=0' at line 1
</code>```

I also tried a few other variations of the syntax (add / remove parentheses, remove 'as' clause, switch case, etc) without any luck. So what would be the correct syntax? Where can I find more detailed documentation for the syntax? Besides, where does this weird "WHERE 1=0" in error message come from? Thanks!

答:
For reading data from JDBC source using sql query in Spark SQL, you can try something like this:

```<code>val df_table1 = sqlContext.read.format("jdbc").options(Map(
    ("url" -> "jdbc:postgresql://localhost:5432/mydb"),
    ("dbtable" -> "(select * from table1) as table1"),
    ("user" -> "me"),
    ("password" -> "******"),
    ("driver" -> "org.postgresql.Driver"))
).load()
</code>```

I tried it using PostgreSQL. You can modify it according to MySQL.

ContentLicense: CC BY-SA 3.0

Body:
I want to use Spark to process some data from a JDBC source. But to begin with, instead of reading original tables from JDBC, I want to run some queries on the JDBC side to filter columns and join tables, and load the query result as a table in Spark SQL.

The following syntax to load raw JDBC table works for me:

df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="mydb.table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver" # mysql JDBC driver 5.1.41
).load()
df_table1.show() # succeeded

According to Spark documentation (I'm using PySpark 1.6.3):

dbtable: The JDBC table that should be read. Note that anything that is valid
  in a FROM clause of a SQL query can be used. For example, instead of a
  full table you could also use a subquery in parentheses.

So just for experiment, I tried something simple like this:

df_table1 = sqlContext.read.format('jdbc').options(
    url="jdbc:mysql://foo.com:3306",
    dbtable="(SELECT * FROM mydb.table1) AS table1",
    user="me",
    password="******",
    driver="com.mysql.jdbc.Driver"
).load() # failed

It threw the following exception:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table1 WHERE 1=0' at line 1

I also tried a few other variations of the syntax (add / remove parentheses, remove 'as' clause, switch case, etc) without any luck. So what would be the correct syntax? Where can I find more detailed documentation for the syntax? Besides, where does this weird "WHERE 1=0" in error message come from? Thanks!

Body:
For reading data from JDBC source using sql query in Spark SQL, you can try something like this:

val df_table1 = sqlContext.read.format("jdbc").options(Map(
    ("url" -> "jdbc:postgresql://localhost:5432/mydb"),
    ("dbtable" -> "(select * from table1) as table1"),
    ("user" -> "me"),
    ("password" -> "******"),
    ("driver" -> "org.postgresql.Driver"))
).load()

I tried it using PostgreSQL. You can modify it according to MySQL.


问:
Programmatically setting a templated Button's VisualStates
In my WP7 application, I have a ListBox populated with buttons. I have a 'Pressed' visual state configured, and it works great. However, I would like to disable that 'Pressed' visual state (temporarily set it to do nothing) while the ListBox is scrolling.

I've created an event handler for detecting when the ListBox is scrolling (using Peter Torr's blog entry here. Using that event handler, how can I alter/disable that 'Pressed' visual state, and also return it to its originally (through XAML) defined state? The ListBox 'Generated Items' template is the button control, which itself is templated to use my custom 'Pressed' state animation.

Thanks!

答:
This is not execly what are you looking for, but you can try setting

```<code>myButton.IsEnabled = false;
</code>```

I assume your goal is to prevent user from clicking a button while scrolling.

ContentLicense: CC BY-SA 2.5

Body:
This is not execly what are you looking for, but you can try setting

myButton.IsEnabled = false;

I assume your goal is to prevent user from clicking a button while scrolling.


问:
How to scroll collectionview horizontal?
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

```<code>UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];
</code>```

答:
You can simply set it through property Inspector

Or you can set programatically with

```<code>UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
</code>```

Body:
I'm using camera and gallery to take image and add it to collection view, i want to add image to collection view to horizontal direction only so i add image to array and change collection frame to increase collection view width increase, but collection is not scroll to horizontal as i increase height of it, so what is way to do it?

Here is my code :

UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
[arrayPictures addObject:image];
_collPic.frame = CGRectMake(0, _collPic.frame.origin.y, arrayPictures.count*76, 76);
[_collPic reloadData];

Body:
You can simply set it through property Inspector

Or you can set programatically with

UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];


问:
Powershell to executable .bat
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

```<code>$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}
</code>```

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

答:
The Batch file below is practically a direct translation of your original PowerShell code, with the difference that each file is renamed only once.

```<code>@echo off
setlocal EnableDelayedExpansion

set /P "NEWSYSTEMID=Please input SEJ SYSTEM ID: "
set /P "NEWDATETIME=Please input the upload date and time: "
echo Renaming files
for /F "tokens=*" %%a in ('dir /B') do (
   set "name=%%a"
   set "name=!name:TKSYSTEMID=%NEWSYSTEMID%!"
   set "name=!name:YYYY MM DD HHMM=%NEWDATETIME%!"
   ren "%%a" "!name!"
)
</code>```

However, if the "Part 2" in the file names is comprised by a single word, like NOTES, then the code may be simpler, because the "Parts 1, 2 and rest" (tokens 1,2*) are directly taken in the rename process:

```<code>@echo off
setlocal

set /P "NEWSYSTEMID=Please input SEJ SYSTEM ID: "
set /P "NEWDATETIME=Please input the upload date and time: "
echo Renaming files
for /F "tokens=1,2*" %%a in ('dir /B') do (
   ren "%%a %%b %%c" "%NEWSYSTEMID% %%b %NEWDATETIME%"
)
</code>```

Title: Powershell to executable .bat

Body:
I'm trying to get the script below, which is in Powershell, converted to an executable .bat file. The basic idea is that I have a bunch of files of which the file name exists out of 3 parts:

Part 1: TKSYSTEMID

Part 2: Variable name

Part 3: YYYY MM DD HHMM

So a simple example would look like: TKSYSTEMID NOTES YYYY MM DD HHMM

I'm looking for a .bat file that can replace the TKSYSTEM ID and the YYYY MM DD HHMM with something the user gets prompted to input.

The powershell script I have so far is:

$NEWSYSTEMID = Read-Host -Prompt 'Please input SEJ SYSTEM ID'
Write-Host "Changing TKSYSTEMID to '$NEWSYSTEMID'"
dir | Rename-Item -NewName {$_.name -replace 'TKSYSTEMID',$NEWSYSTEMID}

$NEWDATETIME = Read-Host -Prompt 'Please input the upload date and time'
Write-Host "Changing YYYY MM DD HHMM to '$NEWDATETIME'"
dir | Rename-Item -NewName {$_.name -replace 'YYYY MM DD HHMM',$NEWDATETIME}

Could someone be so kind as to show me how to convert this or to provide a .bat script for this? It would mean the world.

Body:
The Batch file below is practically a direct translation of your original PowerShell code, with the difference that each file is renamed only once.

@echo off
setlocal EnableDelayedExpansion

set /P "NEWSYSTEMID=Please input SEJ SYSTEM ID: "
set /P "NEWDATETIME=Please input the upload date and time: "
echo Renaming files
for /F "tokens=*" %%a in ('dir /B') do (
   set "name=%%a"
   set "name=!name:TKSYSTEMID=%NEWSYSTEMID%!"
   set "name=!name:YYYY MM DD HHMM=%NEWDATETIME%!"
   ren "%%a" "!name!"
)

However, if the "Part 2" in the file names is comprised by a single word, like NOTES, then the code may be simpler, because the "Parts 1, 2 and rest" (tokens 1,2*) are directly taken in the rename process:

@echo off
setlocal

set /P "NEWSYSTEMID=Please input SEJ SYSTEM ID: "
set /P "NEWDATETIME=Please input the upload date and time: "
echo Renaming files
for /F "tokens=1,2*" %%a in ('dir /B') do (
   ren "%%a %%b %%c" "%NEWSYSTEMID% %%b %NEWDATETIME%"
)


问:
api test with postman in angular project
I want to test my api for resister which is post type it contain username, email, password, phone number. I really don't know how to test api in postman. It should be authorization type of no-auth. After this I have to validate or test api for login then it generate some key then I have to use this key to test other api's. </p>

答:
```<code>i believe to test post api withpostman
first you need to put the route of your api and the type of http in your case POST
then go to header tab and add this header(under key/value):-
Content-Type :application/json
then under body tab select row option and insert valid json as below
{
    "username": "Omar Shabro",
    "email": "o4@o.com",
    "phone": "0599"

}
</code>```


问:
How to watch for a route change in AngularJS?
How would one watch/trigger an event on a route change?</p>

答:
```<code>$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //if you want to interrupt going to another location.
  event.preventDefault();  });
</code>```


问:
Java Swing Font Chooser
In my Java Swing application I want to allow the user to pick their font. To my surprise there is no core swing library to pick fonts. I expected to find a JFileChooser but there is no such utility. This seems like a simple dialog that I'm sure exists out there. I do not really want to write it myself.

I looked around on the internet and found a few different implementations of this type of a dialog. The problem is most of them are on random blogs or are just code snippets. I am looking for something that is part of a library that is well used and tested. It also needs to have a commercial friendly license.

Does anyone know of a good Java file chooser in swing that they can recommend?

答:
JFontChooser is no longer maintained since 2008. I created a Java 9 compatible open source Java Swing Font Chooser dialog:

You can use this artifact:

```<code><dependency>
    <groupId>org.drjekyll</groupId>
    <artifactId>fontchooser</artifactId>
    <version>2.4</version>
</dependency>
</code>```

And insert something like this to your code:

```<code>FontDialog dialog = new FontDialog((Frame)null, "Font Dialog Example", true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
if (!dialog.isCancelSelected()) {
    System.out.println("Selected font is: " + dialog.getSelectedFont());
}
</code>```

or simply

```<code>JTextArea textArea = new JTextArea();
FontDialog.showDialog(textArea);
</code>```

Title: Java Swing Font Chooser

Body:
JFontChooser is no longer maintained since 2008. I created a Java 9 compatible open source Java Swing Font Chooser dialog:

You can use this artifact:

<dependency>
    <groupId>org.drjekyll</groupId>
    <artifactId>fontchooser</artifactId>
    <version>2.4</version>
</dependency>

And insert something like this to your code:

FontDialog dialog = new FontDialog((Frame)null, "Font Dialog Example", true);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
if (!dialog.isCancelSelected()) {
    System.out.println("Selected font is: " + dialog.getSelectedFont());
}

or simply

JTextArea textArea = new JTextArea();
FontDialog.showDialog(textArea);

ContentLicense: CC BY-SA 4.0


问:
Call connection string into another connection string in web.config
I have two connections in the web.config basically they are calling the same database. I want to manage this in  a better manner because change in one config also needs to change the second connection string as well.

```<code> <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;persist security info=True;user id=test;password=test123;database=db-AUTH" providerName="System.Data.SqlClient" />

<add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=db-AUTH;persist security info=True;user id=test;password=test123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</code>```

My question is, is there any way i can call the connection string into the other connection string.

For example. default connection connection string into db entities something like

```<code><add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string= DefaultConnection" providerName="System.Data.EntityClient" />
</code>```

Any suggestions would be appreciated thanks.

答:
You are not obliged to use connection string defined inside app.config(web.config) file for entity connection. You can change entity connection string at runtime. Read this article for that: http://www.c-sharpcorner.com/UploadFile/dacca2/pass-connection-string-in-run-time-to-entity-framework/ .

Also you can get another connnection string and separete every part of connection string( DataBase,DataSource and etc.) using StringConnectionBuilder class https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.initialcatalog.aspx.

The solution is: Get DefaultConnection string and change entity connection at runtime.

Body:
I have two connections in the web.config basically they are calling the same database. I want to manage this in  a better manner because change in one config also needs to change the second connection string as well.

 <add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;persist security info=True;user id=test;password=test123;database=db-AUTH" providerName="System.Data.SqlClient" />

<add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;initial catalog=db-AUTH;persist security info=True;user id=test;password=test123;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />

My question is, is there any way i can call the connection string into the other connection string.

For example. default connection connection string into db entities something like

<add name="dbEntities" connectionString="metadata=res://*/InsuranceFinderModel.csdl|res://*/InsuranceFinderModel.ssdl|res://*/InsuranceFinderModel.msl;provider=System.Data.SqlClient;provider connection string= DefaultConnection" providerName="System.Data.EntityClient" />

Any suggestions would be appreciated thanks.


问:
issue while printing the variable to html page
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

```<code><div ng-app="app" ng-controller="VolController">
<div class="account-action">

<h3 style="display:inline;"><img class="img"  align="left" src="images/u11.png">
    <p style="color:white">   Welcome {{first_name}}<p></h3>
</div>
</code>```

this is my controller:

```<code>    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);
</code>```

Question Updated!!!!

答:
You should use $scope,</p>

```<code>  $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);
</code>```

Body:
I am trying to get the first name of the user in the ajax method and trying to print it on the html page but it is not getting printed

this is my html:

   Welcome {{first_name}}

this is my controller:

    app.controller('VolController',['$scope','$sessionStorage','$state',function($scope,$sessionStorage,$state){

    var b=sessionStorage.getItem("userid");

    var a="http://localhost:8080/volunteers/"+b;

        $.ajax({
    type:'GET',
    url:a,

    success:function(data){
     console.log(JSON.stringify(data));
    $scope.volunteer=data;
    $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);

    console.log(data);

    },
    error:function(data){
        alert(data);
        },
    dataType:"json",
    contentType:"application/json",
})

}]);

Question Updated!!!!

Body:
You should use $scope,

  $scope.first_name=JSON.stringify($scope.volunteer.VolunteersDTO.first_name);


问:
How to perform a background load and scraping of a page with XUL/Firefox Extension
I want to scrape the user pages of SO to give the owners of my toolbar the updated information on their questions/answers/etc...

This means I need to do this in the background, parse the pages, extract the content, compare it with the last run and then present the results either on the toolbar or the status bar, or alternatively, on a pop-up window of some kind. And all of this has to be done while the user is going about his business not being interrupted or even being on SO.

I've searched quite thoroughly both on Google and on the Mozilla Wiki for some kind of hint. I've even gone to the extent of downloading a few other extensions that I think do the same. Unfortunately I've not had the time to go through all of them and the ones I've looked at, all use data APIs(Services, WebServices, XML), not  html scrapping.

Old question text

I'm looking for a nice place to learn how I can load a page inside a function called buy the infamous set_timeout() to process a screen-scraping in the background.

My idea is to present the results of such scraping in a status bar extension, just in case any thing changed from the last run.

Is there a hidden overlay or some other subterfuge?

答:
In case of XUL/Firefox, what you need is the nsIIOService interface, which you can get like this:

```<code>var mIOS = Components.classes["@mozilla.org/network/io-service;1"].
   getService(Components.interfaces.nsIIOService);
</code>```

Then you need to create a channel, and open an asynchronous link:

```<code>var channel = mIOS.newChannel(urlToOpen, 0, null);
channel.asyncOpen(new StreamListener(), channel);
</code>```

The key here is the StreamListener object:

```<code>var StreamListener = function() {
    return {
        QueryInterface: function(aIID) {
            if (aIID.equals(Components.interfaces.nsIStreamListener) ||
                aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
                aIID.equals(Components.interfaces.nsISupports))
                return this;
            throw Components.results.NS_NOINTERFACE;

        onStartRequest: function(aRequest, aContext)
           { return 0; },

        onStopRequest: function(aRequest, aChannel /* aContext */, aStatusCode)
           { return 9; },

        onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount)
           { return 0; }
    };
}
</code>```

You have to fill in the details in the onStartRequest, onStopRequest, onDataAvailable functions, but that should be enough to get you going.  You can have a look at how I used this interface in my Firefox extension (it is called IdentFavIcon, and it can be found on the mozilla add-ons site).

The part which I'm uncertain about is how you can trigger this page request from time to time,  set_timeout() should probably work, though.

Edit:

See example here (see section Downloading Images) for an example on how to collect downloaded data into a single variable; and

See this page on how to convert an HTML source into a DOM tree.

HTH.

OwnerDisplayName: Gustavo Carreno

LastEditorDisplayName: Gustavo Carreno

Body:
In case of XUL/Firefox, what you need is the nsIIOService interface, which you can get like this:

var mIOS = Components.classes["@mozilla.org/network/io-service;1"].
   getService(Components.interfaces.nsIIOService);

Then you need to create a channel, and open an asynchronous link:

var channel = mIOS.newChannel(urlToOpen, 0, null);
channel.asyncOpen(new StreamListener(), channel);

The key here is the StreamListener object:

var StreamListener = function() {
    return {
        QueryInterface: function(aIID) {
            if (aIID.equals(Components.interfaces.nsIStreamListener) ||
                aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
                aIID.equals(Components.interfaces.nsISupports))
                return this;
            throw Components.results.NS_NOINTERFACE;

        onStartRequest: function(aRequest, aContext)
           { return 0; },

        onStopRequest: function(aRequest, aChannel /* aContext */, aStatusCode)
           { return 9; },

        onDataAvailable: function(aRequest, aContext, aStream, aOffset, aCount)
           { return 0; }
    };
}

You have to fill in the details in the onStartRequest, onStopRequest, onDataAvailable functions, but that should be enough to get you going.  You can have a look at how I used this interface in my Firefox extension (it is called IdentFavIcon, and it can be found on the mozilla add-ons site).

The part which I'm uncertain about is how you can trigger this page request from time to time,  set_timeout() should probably work, though.

Edit:

See example here (see section Downloading Images) for an example on how to collect downloaded data into a single variable; and

See this page on how to convert an HTML source into a DOM tree.

HTH.

OwnerDisplayName: David Hanak

LastEditorDisplayName: David Hanak


问:
Make an object accessible outside a function in R
I have a function  called "p". In this function, there is an object called "marginal" which I need to make recognizable and retrievable outside this function when called. Right now, when I call the object "marginal" outside the function, I get an wrror message that:

object 'marginal' not found

Question: How can I make "marginal" recognizable outside the function?

```<code>p <- function(t, N1, N2=NULL, delta) {

    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    marginal <- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))

    list(marginal) ## What to use instead of list to object "marginal" recognizable
                    # outside the function?
 }

 marginal
</code>```

object 'marginal' not found

答:
The best solution for you would be to refactor your current function, possibly into smaller functions, in such a way that you can easily get the value of marginal separately.  Then, use it to complete your current calculation.

That being said, if you want a quick fix you could resort to using the parent scope assignment operator <<-, e.g.

```<code>marginal <- NULL

p <- function(t, N1, N2=NULL, delta) {
    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    # note the assignment being done here carefully
    marginal <<- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))
}

# now marginal contain the value assigned in the function call above
</code>```

However, it is usually not recommended to take such an approach.  I only offer it as a quick fix, with the strong suggestion that you rethink your code design.

Body:
I have a function  called "p". In this function, there is an object called "marginal" which I need to make recognizable and retrievable outside this function when called. Right now, when I call the object "marginal" outside the function, I get an wrror message that:

object 'marginal' not found

Question: How can I make "marginal" recognizable outside the function?

p <- function(t, N1, N2=NULL, delta) {

    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    marginal <- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))

    list(marginal) ## What to use instead of list to object "marginal" recognizable
                    # outside the function?
 }

 marginal

object 'marginal' not found

Body:
The best solution for you would be to refactor your current function, possibly into smaller functions, in such a way that you can easily get the value of marginal separately.  Then, use it to complete your current calculation.

That being said, if you want a quick fix you could resort to using the parent scope assignment operator <<-, e.g.

marginal <- NULL

p <- function(t, N1, N2=NULL, delta) {
    efN = ifelse(is.null(N2), N1, N1*N2/(N1+N2))
    df  = ifelse(is.null(N2), N1 - 1, N1 + N2 - 2)

    prior <- function(delta) dnorm(delta, 0, 1)
    likelihood <- function(delta) dt(t, df, delta*sqrt(efN) )

    # note the assignment being done here carefully
    marginal <<- integrate(function(x) prior(x)*likelihood(x), -Inf, Inf)[[1]]

    post <- function(x) prior(x)*likelihood(x) / marginal

    return(post(delta))
}

# now marginal contain the value assigned in the function call above

However, it is usually not recommended to take such an approach.  I only offer it as a quick fix, with the strong suggestion that you rethink your code design.


问:
sed: replace many lines from a file with single notification
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

```<code>  sed -i '218,226140d; 218i ...REMOVED...' psql.log
</code>```

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

```<code>  sed -i '218,226140d; 217i ...REMOVED...' psql.log
</code>```

result:

```<code>  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
</code>```

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

```<code>  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...
</code>```

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

```<code>  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)
</code>```

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

答:
There is example 'every output more than 50 rows I could squash down to just the first 5 rows and the last 5'.

With test input:

```<code>$ seq 160 | awk -vstart=10 -vmax=50 -vleft=5 '{if(NR < start) {print; next} {i++; if(i <= left || i > max - left){print}; if(i == left + 1){print "...REMOVED..."}if(i == max){i = 0}}}'
</code>```

If you line put script in file, store this to squash.awk

```<code>BEGIN {
    start=10;
    max=50;
    left=5;
}

{
    if(NR < start) {
        print;
        next
    }
    i++;
    if(i <= left || i > max - left) {
        print
    }
    if(i == left + 1) {
        print "...REMOVED...";
    }
    if(i == max) {
        i = 0
    }
}
</code>```

For testing:

```<code>$ seq 160 | awk -f squash.awk
</code>```

Variable start is line number from which squashing line will begin.

Variable max is maximum rows (in your example 50).

Variable left is how many rows will left from max first and last.

if(NR < start) {print; next} if line number less then start (in our case 10), we just print them and go to next line.
Here you can put any condition to skip squashing.

i++ it's rows counter increment.

if(i <= left || i > max - left){print} if rows counter less then 5 or more then max - 5 - print it.

if(i == left + 1){print "...REMOVED..."} when we starting skip rows - put "...REMOVED..." message

if(i == max){i = 0} if rows counter reach max, zero it

Body:
I'm looking for a solution in GNU sed, but POSIX sed is OK and awk will be OK but probably more complicated than necessary. I prefer sed for this, it should be easy but I'm stuck. Seems like a one-liner can do this, no need to create a python/bash script or anything.

my attempted solution

  sed -i '218,226140d; 218i ...REMOVED...' psql.log

This deletes the desired rows, but the insert gets lost. If I move the insert to line 217 I get:

  sed -i '218,226140d; 217i ...REMOVED...' psql.log

result:

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  ...REMOVED...
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘

I know - this should be good enough, but I'm annoyed that I can't get this simple one-liner to work right. What am I missing?

the problem

I keep the psql.log file as a reference for work I am doing developing SQL code. It's very useful to see iterations of the query and the results.

The problem is that sometimes I forget to limit the output and the query will generate 100k+ rows of results that aren't a helpful reference, and I'd like to delete them from my file, leaving a note that reminds me the query output has been excised.

It would be nice to match the pattern, say every output more than 50 rows I could squash down to just the first 5 rows and the last 5.  However, its easy for me to mark the line numbers where I've blown up the file, so I'd be happy with just using sed to delete lines N through M, and insert the message ...REMOVED... where line N was.

Here is an example log file, added notes are in parentheses. The query text can change and the number of columns can be from 1 to 100 or more:

  ...
  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217)
  │ CC6XF2SVWT │         13182280615 │ [null]          │
  (many rows)

  │ CC6XF2XWDT │           995086081 │ [null]          │
  │ CC6XFX3TL1 │         25195177405 │ [null]          │
  │ CC6XJ8YG5C │         24661013005 │ [null]          │  (line 226141)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  /* another query begins */

  select * from table where X = 1 limit 20;

  /* well done you remembered to limit the output */
  **************************
  ...

acceptable output

the query text should all be untouched, and the top/bottom three rows of output kept. The annotation ...REMOVED... has been added and rows 218 through 226140 have been deleted:

  ********* QUERY **********
  select      *
  from        table
  where       rnk <= 3
  **************************

  ┌────────────┬─────────────────────┬─────────────────┐
  │ col_one    │     col_two         │ column_three    │
  ├────────────┼─────────────────────┼─────────────────┤
  │ CC00CBSNRY │           553854451 │       15003.44  │
  │ CC00CBSNRY │          1334177150 │        5159.57  │
  │ CC6XDSQGH2 │         42385958605 │ [null]          │ (line 217 in original file)
  ...REMOVED...
  │ CC6XJ8YG5C │         24661013005 │ [null]          │ (line 226141 in original file)
  │ CC6XJ9HGRG │         44946564505 │ [null]          │
  │ CC6XMQW6SJ │         34496719615 │ [null]          │
  └────────────┴─────────────────────┴─────────────────┘
  (225926 rows)

  ********* QUERY **********
  (etc just like example above)

update

the border comes from my .psqlrc with \pset border 2

therefore solutions depending on the ┌ character are fragile but OK

over time i've learned that manually flagging the line numbers is too time consuming, so the best solution needs a pattern match

Body:
There is example 'every output more than 50 rows I could squash down to just the first 5 rows and the last 5'.

With test input:

$ seq 160 | awk -vstart=10 -vmax=50 -vleft=5 '{if(NR < start) {print; next} {i++; if(i <= left || i > max - left){print}; if(i == left + 1){print "...REMOVED..."}if(i == max){i = 0}}}'

If you line put script in file, store this to squash.awk

BEGIN {
    start=10;
    max=50;
    left=5;
}

{
    if(NR < start) {
        print;
        next
    }
    i++;
    if(i <= left || i > max - left) {
        print
    }
    if(i == left + 1) {
        print "...REMOVED...";
    }
    if(i == max) {
        i = 0
    }
}

For testing:

$ seq 160 | awk -f squash.awk

Variable start is line number from which squashing line will begin.

Variable max is maximum rows (in your example 50).

Variable left is how many rows will left from max first and last.

if(NR < start) {print; next} if line number less then start (in our case 10), we just print them and go to next line.
Here you can put any condition to skip squashing.

i++ it's rows counter increment.

if(i <= left || i > max - left){print} if rows counter less then 5 or more then max - 5 - print it.

if(i == left + 1){print "...REMOVED..."} when we starting skip rows - put "...REMOVED..." message

if(i == max){i = 0} if rows counter reach max, zero it


问:
Anonymous class how to pass local parameter?
I create a StreamResource in Vaadin. How can i pass the parameter fileName into the anonymous class? I have to set the fileName in the inner class.

Here's the source code:

```<code>String fileName;

public void anotherMethod(){
    StreamResource myResource = createResource();
    fileDownloader = new FileDownloader(myResource);
}

private StreamResource createResource() {
    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
            ....
            //some magic with the filename here
        }
    }, fileName);
}
</code>```

I get a NullPointerException by fileName.

答:
In your code, the variable fileName is not initialized or you didn't provide this piece of code. Try initializing it like:

String fileName = "some file name"; like:

```<code>String fileName = "virus.bat";

public void anotherMethod(){
       StreamResource myResource = createResource();
        fileDownloader = new FileDownloader(myResource);
}
private StreamResource createResource() {
    final String URL = "someURL";

    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
              // USE THE URL.
        }
    }, fileName);
}
</code>```

You don't pass the parameter to the anonymous class but to the StreamResource constructor which has two parameters: a StreamSource and a String.

I'm 100% sure you didn't assign anything to the fileName and the anonymous class has nothing to do with it! :)

Next time provide more code, at least with all the use-cases of presented variables so it'll be easier to help.

Body:
I create a StreamResource in Vaadin. How can i pass the parameter fileName into the anonymous class? I have to set the fileName in the inner class.

Here's the source code:

String fileName;

public void anotherMethod(){
    StreamResource myResource = createResource();
    fileDownloader = new FileDownloader(myResource);
}

private StreamResource createResource() {
    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
            ....
            //some magic with the filename here
        }
    }, fileName);
}

I get a NullPointerException by fileName.

Body:
In your code, the variable fileName is not initialized or you didn't provide this piece of code. Try initializing it like:

String fileName = "some file name"; like:

String fileName = "virus.bat";

public void anotherMethod(){
       StreamResource myResource = createResource();
        fileDownloader = new FileDownloader(myResource);
}
private StreamResource createResource() {
    final String URL = "someURL";

    return new StreamResource(new StreamResource.StreamSource() {
        @Override
        public InputStream getStream() {
              // USE THE URL.
        }
    }, fileName);
}

You don't pass the parameter to the anonymous class but to the StreamResource constructor which has two parameters: a StreamSource and a String.

I'm 100% sure you didn't assign anything to the fileName and the anonymous class has nothing to do with it! :)

Next time provide more code, at least with all the use-cases of presented variables so it'll be easier to help.


问:
Why are my semaphores allowing out-of-order events within forked processes?
I am trying to make a program that counts from 0 to whatever number is input in the command line in C. In this program, there has to be two fork() calls, making a total of 3 processes. I have to then use a minimum of 1 semaphore to ensure that the processes run in numerical order with each one in charge of a different n % 3.

The issue I am having is that despite the semaphores I'm using, the program seems to run out of order on a fairly regular basis. I am currently using a gate-style system where each process will force it's own designated semaphore to wait, and once finished, sem_post the semaphore of the process that is supposed to run next. I know this is not the prettiest or most logically efficient way of doing this, but it is one that I was pretty sure would work after my first two different attempts that got this same issue.

If anyone can give me any suggestions as to where I have gone so wrong, I would very much appreciate it.

My code is below:

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <fcntl.h>

    #define SEM_NAME1 "/sem1.mutex"
    #define SEM_NAME2 "/sem2.mutex"
    #define SEM_NAME3 "/sem3.mutex"

    int main(int argc, char *argv[]) {

        if(argc <= 1){
            printf("No arguments were provided so there is no number to count to");
            return 1;
        }

        // Create the 3 semaphores needed
        sem_t *sem1;
        sem_t *sem2;
        sem_t *sem3;

        //initialize to 0
        sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 0);
        if (sem1==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME1);
            return (-1);
        }
        //initialize to 1
        sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 1);
        if (sem2==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME2);
            return (-1);
        }
        //initialize to 1
        sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 1);
        if (sem3==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME3);
            return (-1);
        }

        pid_t pid;
        pid_t pid2;
        pid = fork();

        if(pid == 0){
            pid2 = fork();
        }
        // Shared fork variables
        int counter = 0;
        int ranOnce = 0;
        int max_num = atoi(argv[1]);

        while(counter <= max_num){
            if(pid > 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 1;
                    ranOnce = 1;
                }
                sem_wait(sem2);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem3);
            }
            else if(pid2 == 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 0;
                    ranOnce = 1;
                }
                sem_wait(sem1);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem2);
            }
            else{
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 2;
                    ranOnce = 1;
                }
                sem_wait(sem3);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem1);
            }
        }
        //sem_unlink(SEM_NAME1);
        //sem_unlink(SEM_NAME2);
        //sem_unlink(SEM_NAME3);
        return 0;
    }
</code>```

答:
Sorry, but your code can't work as designed.

After the fork calls, each process has its own private copy of the "shared" variables. Unlike a thread, you'll have to use shared memory regions you set up via SysV shared memory primitives.

So, each process is incrementing its own copy, and not a shared copy of counter.

Also, all access to shared variables [including the while clause] must be encapsulated in locks.

I'm not sure if you are implying in the third sentence that I want to use a shared variable or that I should be using the individual copies.

I was looking at your comment: // Shared fork variables, so I inferred that you wanted a common counter. IMO, you do want one as a cross-check

I am aware that each is only accessing their own individual copy of the counter variable and that is the purpose of the semaphore gates. When the thread is allowed to run again, it means that both other processes have done their print, so the next character in the sequence will be 3 ahead of the current value of counter.

I had recoded your app to simplify it so I could understand it.

I'm not seeing a clean round robin sequence. If you are, now, all is well, and I might have introduced a bug. I added a shared memory global counter using shmget et. al. and it should increment by one, but it occasionally slips backwards [Caveat: It's late here and I'm tired, so that may be part of the issue :-)]

Anyway, here's what I came up with:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SEM_NAME1 "/sem1.mutex"
#define SEM_NAME2 "/sem2.mutex"
#define SEM_NAME3 "/sem3.mutex"

typedef struct tsk {
    int tsk_idx;
    sem_t *tsk_sem;
    pid_t tsk_pid;
    char tsk_name[100];
} tsk_t;

#define NTASK       3

tsk_t tsklist[NTASK];

// Shared fork variables
volatile int counter = 0;
volatile int ranOnce = 0;
int max_num;
volatile int *globptr;

void
dochild(tsk_t *tsk)
{
    int stopflg;
    int tidx;
    tsk_t *tsk2;

    while (1) {
        sem_wait(tsk->tsk_sem);
        stopflg = (counter > max_num);

        if (! stopflg) {
            printf("Tidx:%d Pid:%d Seq:%d",tsk->tsk_idx,tsk->tsk_pid,*globptr);
            *globptr += 1;
            if (ranOnce == 0) {
                counter += 1;
                ranOnce = 1;
            }
            printf(" Counter:%d\n", counter);
            fflush(stdout);
            counter += 3;
        }

        tidx = tsk->tsk_idx + 1;
        tidx %= NTASK;
        tsk2 = &tsklist[tidx];

        sem_post(tsk2->tsk_sem);

        if (stopflg)
            break;
    }

    exit(0);
}

int
main(int argc, char *argv[])
{
    tsk_t *tsk;
    int tidx;
    void *sptr;

    if (argc <= 1) {
        printf("No arguments were provided so there is no number to count to\n");
        //return 1;
    }
    else
        max_num = atoi(argv[1]);

    int shmfd = shmget(IPC_PRIVATE,sizeof(int),0600);
    sptr = shmat(shmfd,NULL,0);
    globptr = sptr;
    *globptr = 0;

    // Create the 3 semaphores needed
    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        tsk->tsk_idx = tidx;

        sprintf(tsk->tsk_name,"/sem%d.mutex",tidx);

        if (max_num == 0) {
            sem_unlink(tsk->tsk_name);
            continue;
        }

        tsk->tsk_sem = sem_open(tsk->tsk_name, O_CREAT, O_RDWR,
            0644,(tidx == 0) ? 1 : 0);

        if (tsk->tsk_sem == SEM_FAILED) {
            printf("%s sem_open failed! -- %s\n",tsk->tsk_name,strerror(errno));
            return (-1);
        }
    }

    if (max_num == 0)
        return 0;

    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        tsk->tsk_pid = fork();
        if (tsk->tsk_pid != 0)
            continue;

        tsk->tsk_pid = getpid();
        dochild(tsk);
    }

    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        waitpid(tsk->tsk_pid,NULL,0);
    }

#if 1
    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        sem_unlink(tsk->tsk_name);
    }
#endif

    shmdt(sptr);

    return 0;
}
</code>```

Here's the output of a run:

```<code>Tidx:0 Pid:18563 Seq:0 Counter:1
Tidx:0 Pid:18563 Seq:1 Counter:4
Tidx:0 Pid:18563 Seq:2 Counter:7
Tidx:0 Pid:18563 Seq:3 Counter:10
Tidx:1 Pid:18564 Seq:4 Counter:1
Tidx:1 Pid:18564 Seq:5 Counter:4
Tidx:1 Pid:18564 Seq:6 Counter:7
Tidx:1 Pid:18564 Seq:7 Counter:10
Tidx:2 Pid:18565 Seq:4 Counter:1
Tidx:2 Pid:18565 Seq:9 Counter:4
Tidx:2 Pid:18565 Seq:10 Counter:7
Tidx:2 Pid:18565 Seq:11 Counter:10
</code>```

Body:
I am trying to make a program that counts from 0 to whatever number is input in the command line in C. In this program, there has to be two fork() calls, making a total of 3 processes. I have to then use a minimum of 1 semaphore to ensure that the processes run in numerical order with each one in charge of a different n % 3.

The issue I am having is that despite the semaphores I'm using, the program seems to run out of order on a fairly regular basis. I am currently using a gate-style system where each process will force it's own designated semaphore to wait, and once finished, sem_post the semaphore of the process that is supposed to run next. I know this is not the prettiest or most logically efficient way of doing this, but it is one that I was pretty sure would work after my first two different attempts that got this same issue.

If anyone can give me any suggestions as to where I have gone so wrong, I would very much appreciate it.

My code is below:

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    #include <sys/types.h>
    #include <unistd.h>
    #include <semaphore.h>
    #include <fcntl.h>

    #define SEM_NAME1 "/sem1.mutex"
    #define SEM_NAME2 "/sem2.mutex"
    #define SEM_NAME3 "/sem3.mutex"

    int main(int argc, char *argv[]) {

        if(argc <= 1){
            printf("No arguments were provided so there is no number to count to");
            return 1;
        }

        // Create the 3 semaphores needed
        sem_t *sem1;
        sem_t *sem2;
        sem_t *sem3;

        //initialize to 0
        sem1 = sem_open(SEM_NAME1, O_CREAT, O_RDWR, 0);
        if (sem1==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME1);
            return (-1);
        }
        //initialize to 1
        sem2 = sem_open(SEM_NAME2, O_CREAT, O_RDWR, 1);
        if (sem2==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME2);
            return (-1);
        }
        //initialize to 1
        sem3 = sem_open(SEM_NAME3, O_CREAT, O_RDWR, 1);
        if (sem3==SEM_FAILED) {
            printf("%s sem_open failed!", SEM_NAME3);
            return (-1);
        }

        pid_t pid;
        pid_t pid2;
        pid = fork();

        if(pid == 0){
            pid2 = fork();
        }
        // Shared fork variables
        int counter = 0;
        int ranOnce = 0;
        int max_num = atoi(argv[1]);

        while(counter <= max_num){
            if(pid > 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 1;
                    ranOnce = 1;
                }
                sem_wait(sem2);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem3);
            }
            else if(pid2 == 0){
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 0;
                    ranOnce = 1;
                }
                sem_wait(sem1);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem2);
            }
            else{
                printf("%d",getpid());
                if(ranOnce == 0){
                    counter += 2;
                    ranOnce = 1;
                }
                sem_wait(sem3);
                printf(" %d \n", counter);
                counter += 3;
                sem_post(sem1);
            }
        }
        //sem_unlink(SEM_NAME1);
        //sem_unlink(SEM_NAME2);
        //sem_unlink(SEM_NAME3);
        return 0;
    }

Body:
Sorry, but your code can't work as designed.

After the fork calls, each process has its own private copy of the "shared" variables. Unlike a thread, you'll have to use shared memory regions you set up via SysV shared memory primitives.

So, each process is incrementing its own copy, and not a shared copy of counter.

Also, all access to shared variables [including the while clause] must be encapsulated in locks.

I'm not sure if you are implying in the third sentence that I want to use a shared variable or that I should be using the individual copies.

I was looking at your comment: // Shared fork variables, so I inferred that you wanted a common counter. IMO, you do want one as a cross-check

I am aware that each is only accessing their own individual copy of the counter variable and that is the purpose of the semaphore gates. When the thread is allowed to run again, it means that both other processes have done their print, so the next character in the sequence will be 3 ahead of the current value of counter.

I had recoded your app to simplify it so I could understand it.

I'm not seeing a clean round robin sequence. If you are, now, all is well, and I might have introduced a bug. I added a shared memory global counter using shmget et. al. and it should increment by one, but it occasionally slips backwards [Caveat: It's late here and I'm tired, so that may be part of the issue :-)]

Anyway, here's what I came up with:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SEM_NAME1 "/sem1.mutex"
#define SEM_NAME2 "/sem2.mutex"
#define SEM_NAME3 "/sem3.mutex"

typedef struct tsk {
    int tsk_idx;
    sem_t *tsk_sem;
    pid_t tsk_pid;
    char tsk_name[100];
} tsk_t;

#define NTASK       3

tsk_t tsklist[NTASK];

// Shared fork variables
volatile int counter = 0;
volatile int ranOnce = 0;
int max_num;
volatile int *globptr;

void
dochild(tsk_t *tsk)
{
    int stopflg;
    int tidx;
    tsk_t *tsk2;

    while (1) {
        sem_wait(tsk->tsk_sem);
        stopflg = (counter > max_num);

        if (! stopflg) {
            printf("Tidx:%d Pid:%d Seq:%d",tsk->tsk_idx,tsk->tsk_pid,*globptr);
            *globptr += 1;
            if (ranOnce == 0) {
                counter += 1;
                ranOnce = 1;
            }
            printf(" Counter:%d\n", counter);
            fflush(stdout);
            counter += 3;
        }

        tidx = tsk->tsk_idx + 1;
        tidx %= NTASK;
        tsk2 = &tsklist[tidx];

        sem_post(tsk2->tsk_sem);

        if (stopflg)
            break;
    }

    exit(0);
}

int
main(int argc, char *argv[])
{
    tsk_t *tsk;
    int tidx;
    void *sptr;

    if (argc <= 1) {
        printf("No arguments were provided so there is no number to count to\n");
        //return 1;
    }
    else
        max_num = atoi(argv[1]);

    int shmfd = shmget(IPC_PRIVATE,sizeof(int),0600);
    sptr = shmat(shmfd,NULL,0);
    globptr = sptr;
    *globptr = 0;

    // Create the 3 semaphores needed
    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        tsk->tsk_idx = tidx;

        sprintf(tsk->tsk_name,"/sem%d.mutex",tidx);

        if (max_num == 0) {
            sem_unlink(tsk->tsk_name);
            continue;
        }

        tsk->tsk_sem = sem_open(tsk->tsk_name, O_CREAT, O_RDWR,
            0644,(tidx == 0) ? 1 : 0);

        if (tsk->tsk_sem == SEM_FAILED) {
            printf("%s sem_open failed! -- %s\n",tsk->tsk_name,strerror(errno));
            return (-1);
        }
    }

    if (max_num == 0)
        return 0;

    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        tsk->tsk_pid = fork();
        if (tsk->tsk_pid != 0)
            continue;

        tsk->tsk_pid = getpid();
        dochild(tsk);
    }

    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        waitpid(tsk->tsk_pid,NULL,0);
    }

#if 1
    for (tidx = 0;  tidx < NTASK;  ++tidx) {
        tsk = &tsklist[tidx];
        sem_unlink(tsk->tsk_name);
    }
#endif

    shmdt(sptr);

    return 0;
}

Here's the output of a run:

Tidx:0 Pid:18563 Seq:0 Counter:1
Tidx:0 Pid:18563 Seq:1 Counter:4
Tidx:0 Pid:18563 Seq:2 Counter:7
Tidx:0 Pid:18563 Seq:3 Counter:10
Tidx:1 Pid:18564 Seq:4 Counter:1
Tidx:1 Pid:18564 Seq:5 Counter:4
Tidx:1 Pid:18564 Seq:6 Counter:7
Tidx:1 Pid:18564 Seq:7 Counter:10
Tidx:2 Pid:18565 Seq:4 Counter:1
Tidx:2 Pid:18565 Seq:9 Counter:4
Tidx:2 Pid:18565 Seq:10 Counter:7
Tidx:2 Pid:18565 Seq:11 Counter:10


问:
android data binding <include> layout OnClick listener doesn't work
I have a data binding layout that contains a frame layout with <include> of other layout inside:

```<code><FrameLayout
    android:id="@+id/global_actions_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.075"
    android:background="@color/colorToolBar">
    <include
        android:id="@+id/included"
        layout="@layout/global_actions">
    </include>
</FrameLayout>
</code>```

the layout has image buttons inside in this format:

```<code><ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
android:alpha="0.4"/>
</code>```

and I added the  tag around them and I added data with  name of activity

```<code> <data>
    <import type="android.view.View"/>
    <variable name="listener" type="MyActivity"/>
</data>
</code>```

and in MyActivity I called a function to listen to On click from the image buttons:

```<code>public void onClickState(View view){
int id = view.getId();
}
</code>```

but from some reason I don't get to this function when I click
 I tried also

```<code> android:onClick="@{listener.onClickState}"
</code>```

but nothing helped.

答:
Activity:

```<code>activityMainBinding.included.setListener(this);
</code>```

global_actions.xml::

```<code><layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
    android:alpha="0.4"/>
</layout>
</code>```

Body:
I have a data binding layout that contains a frame layout with <include> of other layout inside:

<FrameLayout
    android:id="@+id/global_actions_frame_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="0.075"
    android:background="@color/colorToolBar">
    <include
        android:id="@+id/included"
        layout="@layout/global_actions">
    </include>
</FrameLayout>

the layout has image buttons inside in this format:

<ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
android:alpha="0.4"/>

and I added the  tag around them and I added data with  name of activity

 <data>
    <import type="android.view.View"/>
    <variable name="listener" type="MyActivity"/>
</data>

and in MyActivity I called a function to listen to On click from the image buttons:

public void onClickState(View view){
int id = view.getId();
}

but from some reason I don't get to this function when I click
 I tried also

 android:onClick="@{listener.onClickState}"

but nothing helped.

Body:
Activity:

activityMainBinding.included.setListener(this);

global_actions.xml::

<layout>
    <data>
        <variable type="your.packages.here.MainActivity" name="listener"/>
    </data>

    <ImageButton
    android:id="@+id/settingsButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_settings_black_36dp"
    android:layout_gravity="end"
    android:background="@color/colorToolBar"
    android:layout_margin="4dp"
    android:layout_marginLeft="20dp"
    android:onClick="@{listener::onClickState}"
    android:alpha="0.4"/>
</layout>


问:
How to set text view if something happened in another class
I have a text view in my ActivityMain and I have an adapter(for my recycler view) that if the user touches something value of text view should be changed.

Text view is in another part of the screen and is not related to recycler view.

how can I do that?

thank you.

答: simple  solution is to declare your text view as public static and access in adapter class using activity name and assign text on click</p>


问:
AngularJS - can you rename a service without modifying its core source?
I have a situation where I've downloaded a written service for angular.js, and it works fine - but I would prefer to have it called something different in my code just for the convenience and readability. It isn't really a requirement, just a desire.

I could go through and change this in the actual source code for the service, but that's obviously going to lead to all kinds of problems. So I was wondering, is this kind of thing possible? Can you 'alias' a service across your application so that it can be referred to something differently when you're passing it through controllers? For example...

normal

```<code>var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);

app.controller('HomeController', function(ngSomethingLongAndObtuseThatIsNotNecessary){
   ngSomethingLongAndObtuseThatIsNotNecessary.open();
});
</code>```

goal

```<code>var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);
var smallerName = ngSomethingLongAndObtuseThatIsNotNecessary;

app.controller('HomeController', function(smallerName){
   smallerName.open();
});
</code>```

I tried just doing that, assigning it to another variable, but it didn't work.

Update

I actually did make something work, but I'm not sure if this will have bad repercussions down the line.

```<code>var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);

app.service('ngSmaller', function(ngSomethingLongAndObtuseThatIsNotNecessary) {
   return ngSomethingLongAndObtuseThatIsNotNecessary;
});

app.controller('HomeController', function(ngSmaller){
   ngSmaller.open();
});
</code>```

答:
Another approach can be just create a new factory with a smaller name but use functionality of the existing service. Possibly can help in achieving what you want without polluting the global namespace.</p>

```<code>angular.module('myApp').factory('simpleService',['IHaveAVeryLongOrConfusingName', function(foo){
  return foo;
}])
</code>```

Body:
I have a situation where I've downloaded a written service for angular.js, and it works fine - but I would prefer to have it called something different in my code just for the convenience and readability. It isn't really a requirement, just a desire.

I could go through and change this in the actual source code for the service, but that's obviously going to lead to all kinds of problems. So I was wondering, is this kind of thing possible? Can you 'alias' a service across your application so that it can be referred to something differently when you're passing it through controllers? For example...

normal

var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);

app.controller('HomeController', function(ngSomethingLongAndObtuseThatIsNotNecessary){
   ngSomethingLongAndObtuseThatIsNotNecessary.open();
});

goal

var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);
var smallerName = ngSomethingLongAndObtuseThatIsNotNecessary;

app.controller('HomeController', function(smallerName){
   smallerName.open();
});

I tried just doing that, assigning it to another variable, but it didn't work.

Update

I actually did make something work, but I'm not sure if this will have bad repercussions down the line.

var app = angular.module('demo', [ 'ngSomethingLongAndObtuseThatIsNotNecessary' ]);

app.service('ngSmaller', function(ngSomethingLongAndObtuseThatIsNotNecessary) {
   return ngSomethingLongAndObtuseThatIsNotNecessary;
});

app.controller('HomeController', function(ngSmaller){
   ngSmaller.open();
});

Body:
Another approach can be just create a new factory with a smaller name but use functionality of the existing service. Possibly can help in achieving what you want without polluting the global namespace.

angular.module('myApp').factory('simpleService',['IHaveAVeryLongOrConfusingName', function(foo){
  return foo;
}])


问:
Why do I need to configurate Authentication/Authorization in this tuto
I am following this tuto:

https://blogs.msdn.microsoft.com/benjaminperkins/2016/10/20/how-i-connected-a-console-application-to-a-web-api-protected-by-an-azure-active-directory/

I really don't understand why I need the step "configure  Authentication/Authorization for the web apps" in order to make the demo working.

I get a token, send it and the web api receive it. What is this step made for?
The web  api has AuthorizeArribute and a middleware to analyse the token. What more?

答:
App Service Authentication / Authorization is a feature that provides a way for your application to sign in users so that you don't have to change code on the app backend. It provides an easy way to protect your application and work with per-user data. Please click here for more details .

The tutorial tried App Service Authentication/Authorization but not saying that feature should enable if you want to access web api which protected by Azure AD. You could also implement the authentication/authorization with your own code(managed in app), OpenID Connect (ASP.Net OpenID Connect OWIN middleware) could be used to authenticate users from an Azure AD tenant .


问:
How do I run a Julia function from a package remotely?
I'm porting a program which used to work in Julia 0.4 to Julia 0.5 and having trouble.

This is the program:

```<code>addprocs(3)
ref = @spawn factor(21883298135690819)
factors = fetch(ref)
@assert factors == Dict(234711901=>1,93234719=>1)
</code>```

When running on Julia 0.5, I get the error

ERROR: On worker 2:

  factor(21883298135690819,) has been moved to the package Primes.jl.

  Run Pkg.add("Primes") to install Primes on Julia v0.5-

Fair enough. But even when I go into the interactive terminal, my code still won't work! Here is the transcript:

```<code>julia> Pkg.add("Primes")
INFO: Nothing to be done

julia> using Primes

julia> Primes.factor(21883298135690819)
Dict{Int64,Int64} with 2 entries:
  234711901 => 1
  93234719  => 1

julia> addprocs(3)
3-element Array{Int64,1}:
 2
 3
 4

julia> ref = @spawn factor(21883298135690819)
Future(2,1,5,Nullable{Any}())

julia> factors = fetch(ref)
ERROR: On worker 2:
factor(21883298135690819,) has been moved to the package Primes.jl.
Run Pkg.add("Primes") to install Primes on Julia v0.5-
</code>```

Same problem!

I've read the documentation which seems to suggest that the using declaration makes the code available to all processes, but this is not the case.

What am I doing wrong?

答:
the documentation says "using DummyModule causes the module to be loaded on all processes when starting Julia with julia -p 2", which means, in REPL, one should run addprocs(2) firstly.
so you should put addprocs(3) before using Primes.

Body:
I'm porting a program which used to work in Julia 0.4 to Julia 0.5 and having trouble.

This is the program:

addprocs(3)
ref = @spawn factor(21883298135690819)
factors = fetch(ref)
@assert factors == Dict(234711901=>1,93234719=>1)

When running on Julia 0.5, I get the error

ERROR: On worker 2:

  factor(21883298135690819,) has been moved to the package Primes.jl.

  Run Pkg.add("Primes") to install Primes on Julia v0.5-

Fair enough. But even when I go into the interactive terminal, my code still won't work! Here is the transcript:

julia> Pkg.add("Primes")
INFO: Nothing to be done

julia> using Primes

julia> Primes.factor(21883298135690819)
Dict{Int64,Int64} with 2 entries:
  234711901 => 1
  93234719  => 1

julia> addprocs(3)
3-element Array{Int64,1}:
 2
 3
 4

julia> ref = @spawn factor(21883298135690819)
Future(2,1,5,Nullable{Any}())

julia> factors = fetch(ref)
ERROR: On worker 2:
factor(21883298135690819,) has been moved to the package Primes.jl.
Run Pkg.add("Primes") to install Primes on Julia v0.5-

Same problem!

I've read the documentation which seems to suggest that the using declaration makes the code available to all processes, but this is not the case.

What am I doing wrong?


问:
GCD background task maximum TTL
I need to be able to program background tasks. Little "crons" if you will, that execute some simple code. While not being an expert in GCD I was wondering:

What is the maximum time I expect for the background task to actually perform its duties in the background before apps quits completely

Can I "program" multiple tasks and expect them to complete in timely order

Are they only active as long as the app is launched? ( I bet they are, unlike local notifications that dont really care whether the app is running in the background or not, so just asking to be sure)

How to I keep track of them and cancel if needed?

For instance I able to do something like this and task is performed. I went as far as 1 minute here and it works.

```<code>let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 60) {
            // Some action here
            UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
})
</code>```

答: You can print the time remaining for a given session using backgroundTimeRemaining (docs here). Apple makes no guarantees about what this time will be, it varies with battery level, hardware, resources, etc., so probably no good for a long running persistent background task. You might want to consider the background fetch API, although this is similarly throttled by iOS and you don't have complete control over when it runs.

Title: GCD background task maximum TTL

Body:
I need to be able to program background tasks. Little "crons" if you will, that execute some simple code. While not being an expert in GCD I was wondering:

What is the maximum time I expect for the background task to actually perform its duties in the background before apps quits completely

Can I "program" multiple tasks and expect them to complete in timely order

Are they only active as long as the app is launched? ( I bet they are, unlike local notifications that dont really care whether the app is running in the background or not, so just asking to be sure)

How to I keep track of them and cancel if needed?

For instance I able to do something like this and task is performed. I went as far as 1 minute here and it works.

let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
DispatchQueue.main.asyncAfter(wallDeadline: DispatchWallTime.now() + 60) {
            // Some action here
            UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
})


问:
VirtualStringTree filtering done right
I'm looking for a quick way to filter nodes in a VirtualStringTree based on a filter rule, especially when the filter rule changes. There is a filter mechanism built in the VST where you can define whether the node is filtered out.

My solution right now is to determine on node initialization whether the node is filtered out. When the filter changes, I iterate through all initialized nodes and change the filter state if needed.

The problem is that the more nodes are initialized, the longer it takes to iterate through them. There are many nodes outside of the window where the filter information is not needed right now (the virtual paradigm).

The question is, is there anything like a filter invalidation system / filter events / other solutions to only touch the nodes that really needs the "filter-has-changed" information?

```<code>procedure TfrmMain.vstInitNode(Sender: TBaseVirtualTree; ParentNode,
          Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
  Data: PMyDataType;
begin
  Data  := Sender.GetNodeData(Node);
  Data^ := GetData(Node.Index);

  if IsNodeFiltered(Data^) then Include(InitialStates, ivsFiltered);
end;

procedure TfrmMain.OnFilterRuleChanged();
var
  Node: PVirtualNode;
  Data: PMyDataType;
begin
  vst.BeginUpdate;
  try
    for Node in vst.InitializedNodes do
    begin
      Data := vst.GetNodeData(Node);
      vst.IsFiltered[Node] := IsNodeFiltered(Data^);
    end;
  finally
    vst.EndUpdate;
  end;
end;
</code>```

答: There is no invalidation system that "only touches nodes that really needs the "filter-has-changed" information". In order to display correct scrollbars and the correct expandable state of all nodes, you need to review all initialized nodes if they are still to display or not. With the knowledge how your filter works, you may be able to optimize things in your for-loop and skip certain nodes. You may also consider using vst.VisibleNodes instead of InitializedNodes, but then need to also filter when a node is expanded.

Title: VirtualStringTree filtering done right

Body:
I'm looking for a quick way to filter nodes in a VirtualStringTree based on a filter rule, especially when the filter rule changes. There is a filter mechanism built in the VST where you can define whether the node is filtered out.

My solution right now is to determine on node initialization whether the node is filtered out. When the filter changes, I iterate through all initialized nodes and change the filter state if needed.

The problem is that the more nodes are initialized, the longer it takes to iterate through them. There are many nodes outside of the window where the filter information is not needed right now (the virtual paradigm).

The question is, is there anything like a filter invalidation system / filter events / other solutions to only touch the nodes that really needs the "filter-has-changed" information?

procedure TfrmMain.vstInitNode(Sender: TBaseVirtualTree; ParentNode,
          Node: PVirtualNode; var InitialStates: TVirtualNodeInitStates);
var
  Data: PMyDataType;
begin
  Data  := Sender.GetNodeData(Node);
  Data^ := GetData(Node.Index);

  if IsNodeFiltered(Data^) then Include(InitialStates, ivsFiltered);
end;

procedure TfrmMain.OnFilterRuleChanged();
var
  Node: PVirtualNode;
  Data: PMyDataType;
begin
  vst.BeginUpdate;
  try
    for Node in vst.InitializedNodes do
    begin
      Data := vst.GetNodeData(Node);
      vst.IsFiltered[Node] := IsNodeFiltered(Data^);
    end;
  finally
    vst.EndUpdate;
  end;
end;


问:
Finding the max of sum of the values in the inner nested defaultdict
Given a defaultdict(Counter) as such:

```<code>from collections import defaultdict, Counter

from collections import defaultdict, Counter

x = {('a', 'z'): Counter({'crazy': 1, 'lazy': 1}),
     ('b', 'r'): Counter({'brown': 1}),
     ('d', 'o'): Counter({'dog': 1}),
     ('e', 'r'): Counter({'over': 1}),
     ('f', 'o'): Counter({'fox': 1}),
     ('h', 'e'): Counter({'the': 2}),
     ('j', 'u'): Counter({'jumps': 1}),
     ('l', 'a'): Counter({'lazy': 1}),
     ('m', 'p'): Counter({'jumps': 1}),
     ('o', 'g'): Counter({'dog': 1}),
     ('o', 'v'): Counter({'over': 1}),
     ('o', 'w'): Counter({'brown': 1}),
     ('o', 'x'): Counter({'fox': 1}),
     ('p', 's'): Counter({'jumps': 1}),
     ('r', 'o'): Counter({'brown': 1}),
     ('t', 'h'): Counter({'the': 2}),
     ('u', 'm'): Counter({'jumps': 1}),
     ('v', 'e'): Counter({'over': 1}),
     ('w', 'n'): Counter({'brown': 1}),
     ('z', 'y'): Counter({'crazy': 1, 'lazy': 1})}
</code>```

I can access the values in the tuple key as such:

```<code>>>> x[('a', 'z')]
Counter({'crazy': 1, 'lazy': 1})
</code>```

If I want to find the tuple key with the highest sum of the values in the inner dictionary, i.e. the Counter, I can do this:

```<code>>>> max([(sum(x[ng].values()), ng) for ng in x])
(2, ('z', 'y'))
>>> max([(sum(x[ng].values()), ng) for ng in x])[1]
('z', 'y')
</code>```

I think the steps are a little convoluted to get the max values. Is there a more straightforward way to get the max of sum of the values in the inner nested defaultdict?

Note as much as possible don't recreate another object from x. This sample is small but the actual size of the x object can contain 1,000,000 keys and the inner counters could be in 10,000,000 in size.

答:
You can catch the value in the iteration to avoid looking up the value with [], but it's not that much cleaner:

```<code>max((sum(c.values()), key) for key, c in x.items())
</code>```

You can provide max with a function which looks nice if you only want to return the key of the max entry:

```<code>max(x, key=lambda k: sum(x[k].values()))
</code>```

Body:
Given a defaultdict(Counter) as such:

from collections import defaultdict, Counter

from collections import defaultdict, Counter

x = {('a', 'z'): Counter({'crazy': 1, 'lazy': 1}),
     ('b', 'r'): Counter({'brown': 1}),
     ('d', 'o'): Counter({'dog': 1}),
     ('e', 'r'): Counter({'over': 1}),
     ('f', 'o'): Counter({'fox': 1}),
     ('h', 'e'): Counter({'the': 2}),
     ('j', 'u'): Counter({'jumps': 1}),
     ('l', 'a'): Counter({'lazy': 1}),
     ('m', 'p'): Counter({'jumps': 1}),
     ('o', 'g'): Counter({'dog': 1}),
     ('o', 'v'): Counter({'over': 1}),
     ('o', 'w'): Counter({'brown': 1}),
     ('o', 'x'): Counter({'fox': 1}),
     ('p', 's'): Counter({'jumps': 1}),
     ('r', 'o'): Counter({'brown': 1}),
     ('t', 'h'): Counter({'the': 2}),
     ('u', 'm'): Counter({'jumps': 1}),
     ('v', 'e'): Counter({'over': 1}),
     ('w', 'n'): Counter({'brown': 1}),
     ('z', 'y'): Counter({'crazy': 1, 'lazy': 1})}

I can access the values in the tuple key as such:

>>> x[('a', 'z')]
Counter({'crazy': 1, 'lazy': 1})

If I want to find the tuple key with the highest sum of the values in the inner dictionary, i.e. the Counter, I can do this:

>>> max([(sum(x[ng].values()), ng) for ng in x])
(2, ('z', 'y'))
>>> max([(sum(x[ng].values()), ng) for ng in x])[1]
('z', 'y')

I think the steps are a little convoluted to get the max values. Is there a more straightforward way to get the max of sum of the values in the inner nested defaultdict?

Note as much as possible don't recreate another object from x. This sample is small but the actual size of the x object can contain 1,000,000 keys and the inner counters could be in 10,000,000 in size.

Body:
You can catch the value in the iteration to avoid looking up the value with [], but it's not that much cleaner:

max((sum(c.values()), key) for key, c in x.items())

You can provide max with a function which looks nice if you only want to return the key of the max entry:

max(x, key=lambda k: sum(x[k].values()))


问:
what is this path 'tomcat/work/Catalina/localhost/_/org/apache/jsp' in tomcat?
My customer told what is path of

```<code>'tomcat/work/Catalina/localhost/_/org/apache/jsp'
</code>```

but i don`t know well what is it.
I saw these folder fist time. and maybe the path is created just in operation environment that in my environment of development, these path isn't created.
what is that path and is that must necessity on tomcat?

答:
work directory is where your compiled JSPs and other static resources will go.

if you have Deployed archive file as ROOT.war folder with name _ will be created in tomcat/work/Catalina/localhost/ otherwise the folder name will be same as that of your web archieve file.

Note: It is advised to clear work directory before every deployment.

Clarifications on Tomcat's "temp" and "work" directories

https://tomcat.apache.org/tomcat-7.0-doc/config/host.html

Body:
My customer told what is path of

'tomcat/work/Catalina/localhost/_/org/apache/jsp'

but i don`t know well what is it.
I saw these folder fist time. and maybe the path is created just in operation environment that in my environment of development, these path isn't created.
what is that path and is that must necessity on tomcat?


问:
Android Error in Text_Input_Layout Edittext

Does anyone know how I can change the position of the mentioned part of error floating label (as in the attached image) ? In the picture it is on the left but I want it to be on the right side of the edittext (because of my native language) . I tried gravity and layout gravity but none of them worked out . Thanks in advance .

```<code> <android.support.design.widget.TextInputLayout
android:id="@+id/numid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
app:errorEnabled="true"
app:errorTextAppearance="@style/myerror"
android:layout_gravity="center"
    app:hintTextAppearance="@style/TextAppearance.AppCompat.TextInputLayout"
style="@style/EditScreenTextInputLayoutStyle">

 <android.support.v7.widget.AppCompatEditText
    android:id="@+id/tie"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:gravity="right"
    android:textAlignment="gravity"
    android:hint="@string/hint2"
    android:textDirection="rtl"
    />
</code>```

```<code>  <style name="TextAppearance.AppCompat.TextInputLayout" parent="@android:style/TextAppearance">
<item name="android:textColor">#ff0000</item>
<item name="android:layout_gravity">right</item>
<item name="android:textColorHint">#736f6e</item>
<item name="android:gravity">right</item>
</code>```

```<code><style name="EditScreenTextInputLayoutStyle" parent="Theme.AppCompat.Light">
<item name="colorControlNormal">#000</item>
<item name="colorControlActivated">#000</item>
<item name="colorControlHighlight">#ff0000</item>
<item name="colorAccent">#ffff02</item>
<item name="android:textColorHint">#0000ff</item>
  </style>

<style name="myerror" parent="TextAppearance.Design.Error">
    <item name="android:textColor">#ff0000</item>
    <item name="android:background">#000000</item>
    <item name="android:gravity">center</item>

</style>
</code>```

答:
Try this:

```<code>    Drawable err_indiactor = ContextCompat.getDrawable(this,R.drawable.indicator_input_error);
    yourEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, err_indiactor, null);
</code>```

this is the Drawable indicator_input_error

Body:
Does anyone know how I can change the position of the mentioned part of error floating label (as in the attached image) ? In the picture it is on the left but I want it to be on the right side of the edittext (because of my native language) . I tried gravity and layout gravity but none of them worked out . Thanks in advance .

 <android.support.design.widget.TextInputLayout
android:id="@+id/numid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
app:errorEnabled="true"
app:errorTextAppearance="@style/myerror"
android:layout_gravity="center"
    app:hintTextAppearance="@style/TextAppearance.AppCompat.TextInputLayout"
style="@style/EditScreenTextInputLayoutStyle">

 <android.support.v7.widget.AppCompatEditText
    android:id="@+id/tie"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:gravity="right"
    android:textAlignment="gravity"
    android:hint="@string/hint2"
    android:textDirection="rtl"
    />

Body:
Try this:

    Drawable err_indiactor = ContextCompat.getDrawable(this,R.drawable.indicator_input_error);
    yourEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, err_indiactor, null);

this is the Drawable indicator_input_error


问:
Regex finding aa but not aaa with grep
Can't figure out the regex pattern for matching aa but not aaa.

```<code>x <- c("ab", "abc", "abcc", "abccc", "abcccc", "abccccc")

grep(pattern="c{2,3}", x, value=TRUE, perl=TRUE)
## [1] "abcc"    "abccc"   "abcccc"  "abccccc"

grep(pattern="^((?!c{4,}).)*$", x, value=TRUE, perl=TRUE)
## [1] "ab"    "abc"   "abcc"  "abccc"
</code>```

But what's the pattern to yield:

```<code>grep(pattern=..., x, value=TRUE, perl=TRUE)
## [1] "abcc"  "abccc"
</code>```

答:
But what's the pattern to yield 1 "abcc"  "abccc"

You need to assure that the 2 or 3 cs are not preceded nor followed with c:

```<code>grep(pattern="(^|[^c])c{2,3}([^c]|$)", x, value=TRUE)
</code>```

Details:

(^|[^c])  - an alternation group matching start of string (^ anchor) or any char other than c (with a negated character class (bracket expression) [^c])

c{2,3} - 2 or 3 cs

([^c]|$) -  an alternation group matching end of string ($ anchor) or any char other than c

Alternatively, use a PCRE regex with lookarounds if your c is actually a placeholder for a multicharacter substring:

```<code>grep(pattern="(?<!c)c{2,3}(?!c)", x, value=TRUE, perl=TRUE)
</code>```

See the R demo

The (?<!c) negative lookbehind will fail the match if there is a c right before 2 or 3 cs and (?!c) negative lookahead fails the match if there is a c right after the 2 or 3 cs.

Title: Regex finding aa but not aaa with grep

Body:
Can't figure out the regex pattern for matching aa but not aaa.

x <- c("ab", "abc", "abcc", "abccc", "abcccc", "abccccc")

grep(pattern="c{2,3}", x, value=TRUE, perl=TRUE)
## [1] "abcc"    "abccc"   "abcccc"  "abccccc"

grep(pattern="^((?!c{4,}).)*$", x, value=TRUE, perl=TRUE)
## [1] "ab"    "abc"   "abcc"  "abccc"

But what's the pattern to yield:

grep(pattern=..., x, value=TRUE, perl=TRUE)
## [1] "abcc"  "abccc"

Body:
But what's the pattern to yield 1 "abcc"  "abccc"

You need to assure that the 2 or 3 cs are not preceded nor followed with c:

grep(pattern="(^|[^c])c{2,3}([^c]|$)", x, value=TRUE)

Details:

(^|[^c])  - an alternation group matching start of string (^ anchor) or any char other than c (with a negated character class (bracket expression) [^c])

c{2,3} - 2 or 3 cs

([^c]|$) -  an alternation group matching end of string ($ anchor) or any char other than c

Alternatively, use a PCRE regex with lookarounds if your c is actually a placeholder for a multicharacter substring:

grep(pattern="(?<!c)c{2,3}(?!c)", x, value=TRUE, perl=TRUE)

See the R demo

The (?<!c) negative lookbehind will fail the match if there is a c right before 2 or 3 cs and (?!c) negative lookahead fails the match if there is a c right after the 2 or 3 cs.


问:
on click of div Collapse all the other divs
i have 7 divs one beside the other in horizontal line.

i want to make animation when the user click on a div of them the other divs will collapse under the dive clicked.

is there any code to do it no matter what is the code that will do it?

also is the code will work if the divs in a table ?

答:
html

```<code><style>
  .hidden {
    display: none;
  }
</style>
<div class="forHide">1</div>
<div class="forHide">2</div>
<div class="forHide">3</div>
<div class="forHide">4</div>
</code>```

js

```<code>$(document).ready(function(){
  $('.forHide').on('click', function(){
    $('.forHide').addClass('hidden'); // hides all
    $(this).removeClass('hidden'); // current hide deleted
  });
});
</code>```

Body:
html

<style>
  .hidden {
    display: none;
  }
</style>
<div class="forHide">1</div>
<div class="forHide">2</div>
<div class="forHide">3</div>
<div class="forHide">4</div>

js

$(document).ready(function(){
  $('.forHide').on('click', function(){
    $('.forHide').addClass('hidden'); // hides all
    $(this).removeClass('hidden'); // current hide deleted
  });
});


问:
MongoDB - Find by keyword - different data types
I'm using MongoDB as my database engine and trying to execute a find query based on a given keyword. If all of the data fields are type of String, then I could perform the find query like this:

```<code>test.find({
    $or: [
        {'field1': {'$regex': req.body.keyword} },
        {'field2': {'$regex': req.body.keyword} }
    ]})
    .then(function(records) {
        if(records.length >= 1) {
            return res.json({error: false, message: null, data: records});
        } else {
            return res.json({error: false, message: "No results", data: null});
        }
    });
</code>```

However, I have some fields that has a field type of Number and $reqex cannot be used with any other types than String.

Is it even possible to perform a find query on different data types? Any help/ideas/thoughts are much appreciated!

答:
To answer the more general question first, yes, it's possible to perform a find on different data types, not just strings.  $regex is meant for pattern matching on strings though.

Pattern matching on numbers, which seems to be what you are looking for, is demonstrated in this post:
MongoDB Regex Search on Integer Value

Here's a specific example that may help... the document is inserted and then it is matched using $where. The result is on the last line:

```<code>db.B_CooperA.insert({number:51})
db.B_CooperA.find({ $where: "/^51*/.test(this.number)" })
{ "_id" : ObjectId("58e1e4cfb8400a4eb8032748"), "number" : 51 }
</code>```

Body:
I'm using MongoDB as my database engine and trying to execute a find query based on a given keyword. If all of the data fields are type of String, then I could perform the find query like this:

test.find({
    $or: [
        {'field1': {'$regex': req.body.keyword} },
        {'field2': {'$regex': req.body.keyword} }
    ]})
    .then(function(records) {
        if(records.length >= 1) {
            return res.json({error: false, message: null, data: records});
        } else {
            return res.json({error: false, message: "No results", data: null});
        }
    });

However, I have some fields that has a field type of Number and $reqex cannot be used with any other types than String.

Is it even possible to perform a find query on different data types? Any help/ideas/thoughts are much appreciated!

Body:
To answer the more general question first, yes, it's possible to perform a find on different data types, not just strings.  $regex is meant for pattern matching on strings though.

Pattern matching on numbers, which seems to be what you are looking for, is demonstrated in this post:
MongoDB Regex Search on Integer Value

Here's a specific example that may help... the document is inserted and then it is matched using $where. The result is on the last line:

db.B_CooperA.insert({number:51})
db.B_CooperA.find({ $where: "/^51*/.test(this.number)" })
{ "_id" : ObjectId("58e1e4cfb8400a4eb8032748"), "number" : 51 }