问:
Use Barman within a Docker swarm
I'm almost new to the PostgreSQL technology but today, I have a Docker swarm with two nodes dedicated for the databases. Consider that the first node contains the "master" PostgreSQL (> 9.3) and the second one is just a replica of the master.

This backup method doesn't suit me anymore since my cluster could grow up soon and I would need point in time recovery. In did some research and that's why I would like to use Barman (http://www.pgbarman.org/).

I was wondering if Barman can be efficient in a Docker swarm and if some of you had a return of experience on it.

I'm trying at the moment to build this infrastructure. I'll post updates if needed.

Additionnaly, more documentation on the topic could help me :)

Thanks, Paul

答:
After some days practicing barman and reading the documentation, I think Barman is a suitable and really good option for backups in a Docker Swarm since it allows streaming backup.

You can choose to backup every minutes a small amount of data. It's light for Docker.
If there is a disaster and your PostgreSQL service comes down you can still recover from a recent backup.

Title: Use Barman within a Docker swarm


来源: stackexchange

问:
How to use angular 'title' API?
I want to get or set title of my page dynamically. I found this but i don't know how to using it.</p>

答:
It's pretty straightforward. In your component where you want to manipulate title add the following:

component.ts

```<code>constructor(private documentTitle: Title) {
    documentTitle.setTitle('Whatever title you want');
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use angular 'title' API?

Body:
It's pretty straightforward. In your component where you want to manipulate title add the following:

component.ts

constructor(private documentTitle: Title) {
    documentTitle.setTitle('Whatever title you want');
}


问:
Converting 2 dimensional array to Single dimensional in C#?
I am converting 2dimensional array to Single dimensional in C#.
I receive the 2 dimensional array from device (C++) and then I convert it to 1 dimensional in C#.
Here is my code:

```<code>int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure
byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device
byte[] baData = new byte[iSize];

for (int i = 0; i < bData.GetLength(0); i++)
{
    for (int j = 0; j < iSize; j++)
    {
        baData[j] = bData[i, j];
    }
}
</code>```

I get the desired result from above code, but the problem is it is not the standard way of implementation.
I want to know how it can be done in a standard way.
May be doing Marshalling , I am not sure.
Thanks in advance.

答:
bData.Cast<byte>() will convert the multi-dimensional array to a single dimension.

This will do boxing, unboxing so isn't the most performant way, but is certainly the simplest and safest.

Body:
I am converting 2dimensional array to Single dimensional in C#.
I receive the 2 dimensional array from device (C++) and then I convert it to 1 dimensional in C#.
Here is my code:

int iSize = Marshal.SizeOf(stTransactionLogInfo); //stTransactionLogInfo is a structure
byte[,] bData = (byte[,])objTransLog; //objTransLog is 2 dimensionl array from device
byte[] baData = new byte[iSize];

for (int i = 0; i < bData.GetLength(0); i++)
{
    for (int j = 0; j < iSize; j++)
    {
        baData[j] = bData[i, j];
    }
}

I get the desired result from above code, but the problem is it is not the standard way of implementation.
I want to know how it can be done in a standard way.
May be doing Marshalling , I am not sure.
Thanks in advance.


问:
Regex how to match the group that was matched
Like for example here:

```<code>/(\.\s)|(\!\s)|(\?\s)|(\:\s)/
</code>```

So for example if the ? is matched I want it to be replaced with itself. Obviously matching with "$1" wouldn't work too well here.

EDIT: It seems it needs more explanation. So if I have this string:

```<code>OK good. And this sentence? And maybe even this one!
</code>```

Then I can match the endings. So its matching the punctuation.

答:
Change your regex to

```<code>/([.!?:])\s/
</code>```

Now you can match group 1 to get the punctuations.

Body:
Like for example here:

/(\.\s)|(\!\s)|(\?\s)|(\:\s)/

So for example if the ? is matched I want it to be replaced with itself. Obviously matching with "$1" wouldn't work too well here.

EDIT: It seems it needs more explanation. So if I have this string:

OK good. And this sentence? And maybe even this one!

Then I can match the endings. So its matching the punctuation.

Body:
Change your regex to

/([.!?:])\s/

Now you can match group 1 to get the punctuations.


问:
Sitecore 7.2 links to csv download in the browser
I want to export Sitecore redirect links to a CSV file. Created in the ribbon a button, and the code referend page in the project.(see below)

```<code>public class ExportRedirectsListCmd : Command
{
    public override void Execute(CommandContext context)
    {
        var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
        var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
        var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
        var sb = new StringBuilder();
        sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
        // collect all information
        var allLines = (from item in lstLinkToRedirect
                        select new object[]
                        {
                            item.RedirectType,
                            item.SourceLink.Url,
                            item.TargetLink.Url
                        }).ToList();

        // insert the content
        allLines.ForEach(line =>
        {
            sb.AppendLine(string.Join(",", line));
        });

        // Alertbox just for test
        // SheerResponse.Alert(sb.ToString());
        // return;
    }
}
</code>```

Code collects all information in the StringBuilder. By testing the alert box displays the expected information.

Now to download the StringBuilder information to the browser. HttpContext does not work in Sitecore.

答:
You need to save the file in temp folder then use SheerResponse.Download()  API to download the CSV file, I have not tested this, but this is probably what you need :

```<code>    public override void Execute(CommandContext context)
    {
        var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
        var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
        var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
        var sb = new StringBuilder();
        sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
        // collect all information
        var allLines = (from item in lstLinkToRedirect
                        select new object[]
                        {
                                           item.RedirectType,
                                           item.SourceLink.Url,
                                           item.TargetLink.Url
                        }).ToList();

        // insert the content
        allLines.ForEach(line =>
        {
            sb.AppendLine(string.Join(",", line));
        });
        string filePath = "/temp/" + filename;
        using( TextWriter tw = new StreamWriter(filePath))
       {
           tw.WriteLine(sb.ToString());
           tw.Close();
       }
       SheerResponse.Download(filePath);
    }
</code>```

Body:
I want to export Sitecore redirect links to a CSV file. Created in the ribbon a button, and the code referend page in the project.(see below)

public class ExportRedirectsListCmd : Command
{
    public override void Execute(CommandContext context)
    {
        var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
        var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
        var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
        var sb = new StringBuilder();
        sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
        // collect all information
        var allLines = (from item in lstLinkToRedirect
                        select new object[]
                        {
                            item.RedirectType,
                            item.SourceLink.Url,
                            item.TargetLink.Url
                        }).ToList();

        // insert the content
        allLines.ForEach(line =>
        {
            sb.AppendLine(string.Join(",", line));
        });

        // Alertbox just for test
        // SheerResponse.Alert(sb.ToString());
        // return;
    }
}

Code collects all information in the StringBuilder. By testing the alert box displays the expected information.

Now to download the StringBuilder information to the browser. HttpContext does not work in Sitecore.

Body:
You need to save the file in temp folder then use SheerResponse.Download()  API to download the CSV file, I have not tested this, but this is probably what you need :

    public override void Execute(CommandContext context)
    {
        var RedirectFolder = new SitecoreContext(GetContentDatabase()).GetItem<BaseCommon>(context.Items[0].ID.ToGuid(), context.Items[0].Language);
        var lstLinkToRedirect = RedirectFolder.Children.OfType<LinkToLinkRedirect>();
        var filename = "RedirectsOutput_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv";
        var sb = new StringBuilder();
        sb.AppendLine($"{"Redirecttype"},{"Sourcelink Url"}, {"Targetlink Url"}");
        // collect all information
        var allLines = (from item in lstLinkToRedirect
                        select new object[]
                        {
                                           item.RedirectType,
                                           item.SourceLink.Url,
                                           item.TargetLink.Url
                        }).ToList();

        // insert the content
        allLines.ForEach(line =>
        {
            sb.AppendLine(string.Join(",", line));
        });
        string filePath = "/temp/" + filename;
        using( TextWriter tw = new StreamWriter(filePath))
       {
           tw.WriteLine(sb.ToString());
           tw.Close();
       }
       SheerResponse.Download(filePath);
    }


问:
Error installing facebook/graph-sdk with composer 1.5.2 on XAMPP PHP 7.0.3 on ubuntu 14.0.4 lts
I have xampp with php 7.0.3 installed on ubuntu 14.04 lts.

I installed composer globally (version: 1.5.2 2017-09-11 16:59:25)

In my codeigniter project I want to use the Facebook SDK, but it won't work unless I install the Graph SDK.

So I did the following:

```<code>$ composer show --all facebook/graph-sdk

name     : facebook/graph-sdk
descrip. : Facebook SDK for PHP
keywords : facebook, sdk
versions : dev-master, 6.x-dev, 5.x-dev, 5.6.1, 5.6.0, 5.5.x-dev, 5.5.0, 5.4.x-dev, 5.4.4, 5.4.3, 5.4.2, 5.4.1, 5.4.0, 5.3.x-dev, 5.3.1, 5.3.0, 5.2.x-dev, 5.2.1, 5.2.0, 5.1.x-dev, 5.1.5, 5.1.4, 5.1.3, 5.1.2, 5.1.1, 5.1.0, 5.0.0, 4.0.23, 4.0.22, 4.0.21, 4.0.20, 4.0.19, 4.0.18, 4.0.17, 4.0.16, 4.0.15, 4.0.14, 4.0.13, 4.0.12, 4.0.11, 4.0.10, 4.0.9, 4.0.8, 4.0.7, 4.0.6, 4.0.5, 4.0.4, 4.0.3, 4.0.2, 4.0.1, v4.0.0, dev-4.1-dev, dev-4.0-dev
type     : library
license  : Facebook Platform
source   : [git] https://github.com/facebook/php-graph-sdk.git 6bb017aa3d4b24852a619a8f00340cfe2a34f6cc
dist     : [zip] https://api.github.com/repos/facebook/php-graph-sdk/zipball/6bb017aa3d4b24852a619a8f00340cfe2a34f6cc 6bb017aa3d4b24852a619a8f00340cfe2a34f6cc
names    : facebook/graph-sdk

autoload
psr-4
Facebook\ => src/

requires
php ^7.1
psr/http-message ^1.0
php-http/client-implementation ^1.0
php-http/httplug ^1.0
php-http/discovery ^1.0
php-http/message ^1.0

requires (dev)
phpunit/phpunit ^6.2
php-http/guzzle6-adapter ^1.0

$ composer require facebook/graph-sdk
Using version ^5.6 for facebook/graph-sdk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package facebook/graph-sdk No version set (parsed as 1.0.0) is satisfiable by facebook/graph-sdk[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

Installation failed, reverting ./composer.json to its original content.
</code>```

These lines seem to imply that v 5.6 of facebook/graph-sdk needs php 7.1 or higher:

```<code>requires
php ^7.1
...
Using version ^5.6 for facebook/graph-sdk
</code>```

Is my conclusion correct, or is the error something completely different?

My issue is that I cannot upgrade php to 7.1 easily as it might break a lot of code in production in a huge application.

So what options do I have? As far as my googling tells me:

I can use the manual method of installing the Facebook Graph SDK from https://github.com/facebook/php-graph-sdk/blob/5.x/docs/getting_started.md#manually-installing-if-you-really-have-to and hope that I do not have to run the code that needs the PHP 7.1 changes.

I might be able to coax composer into using a version of the facebook/graph-sdk package that works with php 7.0 rather than 7.1. I don't know how to do that yet. Any help is greatly appreciated.

Edit - The composer.json file here https://github.com/facebook/php-graph-sdk/blob/5.x/composer.json does not show php7.1 as a requirement. It says "php": "^5.4|^7.0". How can I tell composer to use this version, so as to see if this is really the source of the error?

Anything else I can do?

Thanks.

答:
It seems composer tries to install 5.6 version and if you look at this file https://github.com/facebook/php-graph-sdk/blob/master/composer.json PHP 7.1 is required for this version.

If you want to use it with PHP 7.0 try to install previous 5.5 version:

```<code>composer require facebook/graph-sdk:5.5.*
</code>```

but it's possible 5.5 version might conflict with other packages you have already installed

Body:
I have xampp with php 7.0.3 installed on ubuntu 14.04 lts.

I installed composer globally (version: 1.5.2 2017-09-11 16:59:25)

In my codeigniter project I want to use the Facebook SDK, but it won't work unless I install the Graph SDK.

So I did the following:

$ composer show --all facebook/graph-sdk

name     : facebook/graph-sdk
descrip. : Facebook SDK for PHP
keywords : facebook, sdk
versions : dev-master, 6.x-dev, 5.x-dev, 5.6.1, 5.6.0, 5.5.x-dev, 5.5.0, 5.4.x-dev, 5.4.4, 5.4.3, 5.4.2, 5.4.1, 5.4.0, 5.3.x-dev, 5.3.1, 5.3.0, 5.2.x-dev, 5.2.1, 5.2.0, 5.1.x-dev, 5.1.5, 5.1.4, 5.1.3, 5.1.2, 5.1.1, 5.1.0, 5.0.0, 4.0.23, 4.0.22, 4.0.21, 4.0.20, 4.0.19, 4.0.18, 4.0.17, 4.0.16, 4.0.15, 4.0.14, 4.0.13, 4.0.12, 4.0.11, 4.0.10, 4.0.9, 4.0.8, 4.0.7, 4.0.6, 4.0.5, 4.0.4, 4.0.3, 4.0.2, 4.0.1, v4.0.0, dev-4.1-dev, dev-4.0-dev
type     : library
license  : Facebook Platform
source   : [git] https://github.com/facebook/php-graph-sdk.git 6bb017aa3d4b24852a619a8f00340cfe2a34f6cc
dist     : [zip] https://api.github.com/repos/facebook/php-graph-sdk/zipball/6bb017aa3d4b24852a619a8f00340cfe2a34f6cc 6bb017aa3d4b24852a619a8f00340cfe2a34f6cc
names    : facebook/graph-sdk

autoload
psr-4
Facebook\ => src/

requires
php ^7.1
psr/http-message ^1.0
php-http/client-implementation ^1.0
php-http/httplug ^1.0
php-http/discovery ^1.0
php-http/message ^1.0

requires (dev)
phpunit/phpunit ^6.2
php-http/guzzle6-adapter ^1.0

$ composer require facebook/graph-sdk
Using version ^5.6 for facebook/graph-sdk
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package facebook/graph-sdk No version set (parsed as 1.0.0) is satisfiable by facebook/graph-sdk[No version set (parsed as 1.0.0)] but these conflict with your requirements or minimum-stability.

Installation failed, reverting ./composer.json to its original content.

These lines seem to imply that v 5.6 of facebook/graph-sdk needs php 7.1 or higher:

requires
php ^7.1
...
Using version ^5.6 for facebook/graph-sdk

Is my conclusion correct, or is the error something completely different?

My issue is that I cannot upgrade php to 7.1 easily as it might break a lot of code in production in a huge application.

So what options do I have? As far as my googling tells me:

I can use the manual method of installing the Facebook Graph SDK from https://github.com/facebook/php-graph-sdk/blob/5.x/docs/getting_started.md#manually-installing-if-you-really-have-to and hope that I do not have to run the code that needs the PHP 7.1 changes.

I might be able to coax composer into using a version of the facebook/graph-sdk package that works with php 7.0 rather than 7.1. I don't know how to do that yet. Any help is greatly appreciated.

Edit - The composer.json file here https://github.com/facebook/php-graph-sdk/blob/5.x/composer.json does not show php7.1 as a requirement. It says "php": "^5.4|^7.0". How can I tell composer to use this version, so as to see if this is really the source of the error?

Anything else I can do?

Thanks.

Body:
It seems composer tries to install 5.6 version and if you look at this file https://github.com/facebook/php-graph-sdk/blob/master/composer.json PHP 7.1 is required for this version.

If you want to use it with PHP 7.0 try to install previous 5.5 version:

composer require facebook/graph-sdk:5.5.*

but it's possible 5.5 version might conflict with other packages you have already installed


问:
Why does checking whether a file exists in hadoop cause a NullPointerException?
I'm trying to create or open a file to store some output in HDFS, but I'm getting a NullPointerException when I call the exists method in the second to last line of the code snippet below:

```<code>DistributedFileSystem dfs = new DistributedFileSystem();
Path path = new Path("/user/hadoop-user/bar.txt");
if (!dfs.exists(path)) dfs.createNewFile(path);
FSDataOutputStream dos = dfs.create(path);
</code>```

Here is the stack trace:

```<code>java.lang.NullPointerException
        at org.apache.hadoop.dfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:667)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:80)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:65)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:47)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:227)
        at org.apache.hadoop.mapred.TaskTracker$Child.main(TaskTracker.java:2209)
</code>```

What could the problem be?

答:
I think the preferred way of doing this is:

```<code>Configuration conf = new Configuration();
conf.set("fs.default.name", "hdfs://mynamenodehost:9000");
FileSystem fs = FileSystem.get(conf);
Path path = ...
</code>```

That way you don't tie your code to a particular implementation of FileSystem; plus you don't have to worry about how each implementation of FileSystem is initialized.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create or open a file to store some output in HDFS, but I'm getting a NullPointerException when I call the exists method in the second to last line of the code snippet below:

DistributedFileSystem dfs = new DistributedFileSystem();
Path path = new Path("/user/hadoop-user/bar.txt");
if (!dfs.exists(path)) dfs.createNewFile(path);
FSDataOutputStream dos = dfs.create(path);

Here is the stack trace:

java.lang.NullPointerException
        at org.apache.hadoop.dfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:390)
        at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:667)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:80)
        at ClickViewSessions$ClickViewSessionsMapper.map(ClickViewSessions.java:65)
        at org.apache.hadoop.mapred.MapRunner.run(MapRunner.java:47)
        at org.apache.hadoop.mapred.MapTask.run(MapTask.java:227)
        at org.apache.hadoop.mapred.TaskTracker$Child.main(TaskTracker.java:2209)

What could the problem be?

Body:
I think the preferred way of doing this is:

Configuration conf = new Configuration();
conf.set("fs.default.name", "hdfs://mynamenodehost:9000");
FileSystem fs = FileSystem.get(conf);
Path path = ...

That way you don't tie your code to a particular implementation of FileSystem; plus you don't have to worry about how each implementation of FileSystem is initialized.


问:
How to work with Gmail attachments on Azure Logic App
I have created a Logic app where I get emails from a Gmail Account and I want to post the attachment of the email to my rest API. But I don't understand which type I get as the attachment. I have seen: if I use the Outlook.com trigger I get a base64String but from Gmail I get something else.
Is there an example how to work with Gmail attachments.

答:
Thanks for the input SahadevSinh. I have changed my workflow like this:

And in my endpoint I do this:

```<code> public async System.Threading.Tasks.Task<MissionOutputDto> CreateMissionFromMail(HttpRequestMessage req)
    {
        string body = await req.Content.ReadAsStringAsync();
        dynamic fileData = JObject.Parse(body);
        string email = fileData.email;
        JArray files = fileData.files;

        string fileString = null;
        string fileName = null;
        string mimeType = null;

        foreach (dynamic file in files)
        {
            fileString = file.ContentBytes;
            fileName = file.Name;
            mimeType = file.ContentType;
        }
</code>```

Body:
Thanks for the input SahadevSinh. I have changed my workflow like this:

And in my endpoint I do this:

 public async System.Threading.Tasks.Task<MissionOutputDto> CreateMissionFromMail(HttpRequestMessage req)
    {
        string body = await req.Content.ReadAsStringAsync();
        dynamic fileData = JObject.Parse(body);
        string email = fileData.email;
        JArray files = fileData.files;

        string fileString = null;
        string fileName = null;
        string mimeType = null;

        foreach (dynamic file in files)
        {
            fileString = file.ContentBytes;
            fileName = file.Name;
            mimeType = file.ContentType;
        }


问:
Can't access Docker database using IP (only localhost)
I'm trying to setup Docker to allow connections from other devices on my network. Currently to access Docker I visit localhost on my computer. I'm trying to connect using my computer's local IP (192.168.0.140), which lets me see my files but not connect to my database.

I assume this is a problem with my configuration but I don't know enough about Docker to troubleshoot it.

```<code>version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    ports:
      - 3306
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - '8080:80'
</code>```

Any help would be greatly appreciated.

答:
The reason you are able to connect to the other containers is because you have mapped the ports between the container and the host.
For the database you are using the short port syntax:

```<code>ports:
  - 3306
</code>```

This will choose a random port on the host. To be able to connect to the database, use the long form syntax:

```<code>ports:
  - '3306:3306'
</code>```

In that case, you will be able to connect to the database on localhost:3306

Body:
I'm trying to setup Docker to allow connections from other devices on my network. Currently to access Docker I visit localhost on my computer. I'm trying to connect using my computer's local IP (192.168.0.140), which lets me see my files but not connect to my database.

I assume this is a problem with my configuration but I don't know enough about Docker to troubleshoot it.

version: '2'

services:
  webserver:
    build: ./docker/webserver
    image: localdev
    ports:
      - '80:80'
      - '443:443'
    volumes:
      - ./www:/var/www/html
    links:
      - db

  db:
    image: mysql:5.6
    ports:
      - 3306
    volumes:
      - ./db:/var/lib/mysql
    environment:
      - MYSQL_ROOT_PASSWORD=secret

  phpmyadmin:
    image: phpmyadmin/phpmyadmin:latest
    links:
      - db
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
      MYSQL_USER: root
      MYSQL_ROOT_PASSWORD: secret
    ports:
      - '8080:80'

Any help would be greatly appreciated.

Body:
The reason you are able to connect to the other containers is because you have mapped the ports between the container and the host.
For the database you are using the short port syntax:

ports:
  - 3306

This will choose a random port on the host. To be able to connect to the database, use the long form syntax:

ports:
  - '3306:3306'

In that case, you will be able to connect to the database on localhost:3306


问:
Markdown editing does not work under paragraph
I have following MD code for one of my GitHub page.

Text Text Text.

**Text** Text Text.

`Text` Text.

```

While the first paragraph tag works Okay as there is no Markdown editing done inside it, text inside second paragraph tag is not Formatted as it should be. (No Bold, no quotes)

Why is it so?? And how to use Markdown editing inside paragraph then?

答:
The Markdown rules plainly state:

Note that Markdown formatting syntax is not processed within block-level HTML tags. E.g., you can’t use Markdown-style *emphasis* inside an HTML block.

That said, GitHub Pages uses Kramdown to parse Markdown, and Krandown has a slightly different behavior which gives you more flexibility. In fact, Kramdown's documentation states:

If an HTML tag has an attribute markdown="1", then the default mechanism for parsing syntax in this tag is used.

In other words, do this:

```<code><p align="justify" markdown="1">
**Text** Text Text.

`Text` Text.
</p>
</code>```

And you will get the following output:

```<code><p align="justify">
<strong>Text</strong> Text Text.
<code>Text</code> Text.</p>
</code>```

Kramdown is smart enough to recognize that you are inside a
 tag, and does not wrap the individual lines in new
 tags, which would be invalid HTML. If you actually want each line to be a separate paragraph, then you should use a
 to wrap everything. Like this:

```<code><div align="justify" markdown="1">
**Text** Text Text.

`Text` Text.
</div>
</code>```

Which results in this output:

```<code><div align="justify">
    <p><strong>Text</strong> Text Text.</p>
    <p><code>Text</code> Text.</p>
</div>
</code>```

For completeness, it should be noted that GitHub READMEs and Gists do not use the same Markdown parser. Instead they use an extended Commonmark parser, which handles Markdown in raw HTML differently that the two ways described above. In Commonmark, whether the content of a raw HTML block is parsed as Markdown or not depends on whether the content is wrapped by blank lines. In that case, the proper way would be to do this:

```<code><div align="justify">

**Text** Text Text.

`Text` Text.

</div>
</code>```

However, as GitHub will strip out the align attribute, there isn't any point it doing that on pages hosted on github.com (such as READMEs). There is also the problem that Commonmark is not smart enough to detect that the wrapping raw HTML tag is a
 tag, and wraps each line in another
, resulting in invalid HTML. Therefore, you must use a
 in that case.

While the use-blank-lines method of telling the parser to parse the contents as Markdown is a more elegant solution that markdown="1", it is only supported by Commonmark parsers, which Kramdown is not. Therefore, as long as GitHub Pages uses Kramdown, you need to follow Kramdown's rules.

Body:
I have following MD code for one of my GitHub page.

Text Text Text.

**Text** Text Text.

`Text` Text.

While the first paragraph tag works Okay as there is no Markdown editing done inside it, text inside second paragraph tag is not Formatted as it should be. (No Bold, no quotes)

Why is it so?? And how to use Markdown editing inside paragraph then?

Body:
The Markdown rules plainly state:

Note that Markdown formatting syntax is not processed within block-level HTML tags. E.g., you can’t use Markdown-style *emphasis* inside an HTML block.

That said, GitHub Pages uses Kramdown to parse Markdown, and Krandown has a slightly different behavior which gives you more flexibility. In fact, Kramdown's documentation states:

If an HTML tag has an attribute markdown="1", then the default mechanism for parsing syntax in this tag is used.

In other words, do this:

<p align="justify" markdown="1">
**Text** Text Text.

`Text` Text.
</p>

And you will get the following output:

<p align="justify">
<strong>Text</strong> Text Text.
<code>Text</code> Text.</p>

Kramdown is smart enough to recognize that you are inside a <p> tag, and does not wrap the individual lines in new <p> tags, which would be invalid HTML. If you actually want each line to be a separate paragraph, then you should use a <div> to wrap everything. Like this:

<div align="justify" markdown="1">
**Text** Text Text.

`Text` Text.
</div>

Which results in this output:

<div align="justify">
    <p><strong>Text</strong> Text Text.</p>
    <p><code>Text</code> Text.</p>
</div>

For completeness, it should be noted that GitHub READMEs and Gists do not use the same Markdown parser. Instead they use an extended Commonmark parser, which handles Markdown in raw HTML differently that the two ways described above. In Commonmark, whether the content of a raw HTML block is parsed as Markdown or not depends on whether the content is wrapped by blank lines. In that case, the proper way would be to do this:

<div align="justify">

**Text** Text Text.

`Text` Text.

</div>

However, as GitHub will strip out the align attribute, there isn't any point it doing that on pages hosted on github.com (such as READMEs). There is also the problem that Commonmark is not smart enough to detect that the wrapping raw HTML tag is a <p> tag, and wraps each line in another <p>, resulting in invalid HTML. Therefore, you must use a <div> in that case.

While the use-blank-lines method of telling the parser to parse the contents as Markdown is a more elegant solution that markdown="1", it is only supported by Commonmark parsers, which Kramdown is not. Therefore, as long as GitHub Pages uses Kramdown, you need to follow Kramdown's rules.


问:
Cancel build in drone.io
I'm working on setting Drone.io into repositories of my team, in order to have continuous integration.

The problem is I have a test build locked and I see no way to cancel it. Is there a way to cancel it manually? If not, is there a timeout that causes the build expire?

Thank you.

答:
You can kill a build using drone-cli command, see https://discourse.drone.io/t/how-to-kill-a-build-stuck-in-running-state/1022/2 for details.

Note: You should use the same version for drone-cli and drone-server/agent

Title: Cancel build in drone.io


问:
How do i stop 'sign up' from triggering onAuthStateChange in javascript?
When I sign up a user it automatically signs in the user in Firebase.
I have tried using
var user = firebase.auth().getCurrentUser() if (user) then ...   (something like that) to replace the onAuthStateChange, but it does not work.

Is there any solutions to this? I am doing it both in plain Javascript and React-native.

答: You can't stop sign up from triggering onAuthStateChanged listener. Sign up also signs in the user and this is why the listener gets triggered. You also need that listener to properly detect the initial auth state as well as subsequent sign in/out events.


问:
Where did RU/m go?
This used to be a feature of CosmosDb to provision Request Units Per Minute (as well as Request Units Per Second) however the option appears to have disappeared from the portal and all online documentation has been removed?

Thanks, Oliver

答: It was a preview feature that is not now retired.

Title: Where did RU/m go?


问:
How to triangulate a polygon without random inner points?
I would like to create triangles a predefined polygon. My requirement is that I don't want to create random points inside of this polygon for processing it with a Delaunay Triangulation algorithm.

The polygon can be concave or convex.

It's totally ok for me to use a Delaunay Triangulation but I don't want to create random points inside the polygon. It would be much nicer if I can create as less points as possible inside this polygon.

I would like to minimize the number of used triangles.

How can I establish this?

Comment: It's more a language agnostic thing, I like to know how to implement this on my own.

答:
If the polygon is convex, it's easy to just use the boundary and triangulate using points along the boundary. If it's non-convex I would make a convex boundary, and mark the points inserted as inserted. Then, when done with everything else, remove the inserted points.

You can also use a mesh refinement algorithm to refine the mesh if you get long and thin triangles. Using Delaunay you can just check if a triangle is "thin" by some definition, and if it's "thin" insert a point in the circumcenter of that triangle. Thus all you then have to do is use Delaunay theory.


问:
Do not un-highlight cell immediately after selection (instead, un-highlight it on view-will-appear)
I have a table view with custom cells that have custom highlight styles defined in delegate-functions didHighlightRowAt and didUnhighlightRowAt (e.g., I'm changing the background color).

However, when I select a cell, the unhighlighting function is triggered immediately - how can I avoid this? I want the cell to remain highlighted and instead, unhighlight it in viewwillappear.

Thanks!

[I set tableView.selectionStyle to .none, because it was the only way to do custom highlighting without using the standard selection style. might this be the problem?]

答:
OK, I've fixed this problem, however I think my solution is more like a work-around so better approaches are still highly appreciated!

It looks like the flow is the following:

```<code>- releasing a cell
- cell is unhighlighting
- cell becomes selected
</code>```

So what I did was after unhighlighting, manually highlighting the cell again and then, in in viewWillAppear

Body:
OK, I've fixed this problem, however I think my solution is more like a work-around so better approaches are still highly appreciated!

It looks like the flow is the following:

- releasing a cell
- cell is unhighlighting
- cell becomes selected

So what I did was after unhighlighting, manually highlighting the cell again and then, in in viewWillAppear


问:
operation on aggregated values SQL
I want to sum my revenue by week, and my expenses by week.

```<code>select *
from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;
</code>```

Now, I would like to add a column containing the difference between money in and money out (earned - spent AS balance), with the same weekly aggregation. but I don't seize at which level I can insert the statement.
Any advice?
Thank you

答:
I would say you should be able to do that at the top of your statement instead of selecting *

So something like:

```<code>select earned week,
earned,
spent,
earned - spent as balance,

from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;
</code>```

Title: operation on aggregated values SQL

Body:
I want to sum my revenue by week, and my expenses by week.

select *
from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;

Now, I would like to add a column containing the difference between money in and money out (earned - spent AS balance), with the same weekly aggregation. but I don't seize at which level I can insert the statement.
Any advice?
Thank you

Body:
I would say you should be able to do that at the top of your statement instead of selecting *

So something like:

select earned week,
earned,
spent,
earned - spent as balance,

from (select sum(revenue) earned
            , week(transaction_date) earned_week

    from mytable

    where year(transaction_date) = '1988'

    group by week(transaction_date)

    ) moneyin

    inner join
        (select sum(expenses) spent
                  , week(expense_date) spent_week

          from mytable

          where year(expense_date) = '1988'

          group by week(expense_date)

          ) moneyout

    on moneyin.earned_week = moneyout.spent_week;


问:
Why my PHP Curl POST request turns data array into string?
I'm trying to send some data to a given API with the POST method.
I wrote a function in order to execute any CURL request from my project.
When I use it with a param which the value is an array, this array is automatically turned into a string "Array".

Exemple :
Here is my function :

```<code>function callAPI($method, $url, $data = false)
    {
        $curl = curl_init();
        // First var_dump()
        var_dump($data);

        switch ($method)
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    // Second var_dump()
                    var_dump($data);
                }
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
            default:
                if ($data)
                    $url = sprintf("%s?%s", $url, http_build_query($data));
        }

        $headers = array();
        $headers[] = 'Accept: application/json';
        $headers[] = 'Content-Type: application/json';

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $auth = "username:pwd";
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_USERPWD, $auth);
        curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);

        ....
    }
</code>```

Here is an use case of my function :

```<code>$values = array(
    "param1" => "value1",
    "param2" => "value2",
    "param3" => "value3",
     ...
    "param10" => array("23"),
);

callAPI('POST', "https://myapi", $values);
</code>```

The first var_dump prints the corrects values :

```<code>array(4) {
    ["param1"]=>
        string(6) "value1"
    ["param2"]=>
        string(6) "value2"
    ["param3"]=>
        string(6) "value3"
    ["param10"]=>
        array(1) {
            [0]=>
                string(2) "23"
        }
}
</code>```

But the second one gives a wrong value for "param10" :

```<code>array(4) {
    ["param1"]=>
        string(6) "value1"
    ["param2"]=>
        string(6) "value2"
    ["param3"]=>
        string(6) "value3"
    ["param10"]=>
        string(5) "Array"
}
</code>```

Is there someone having an idea in order to fix this issue ?

答: you have to use http_build_query() also in POST. You have to replace your curl_setopt($curl,CURLOPT_POSTFIELDS, $data); like this: curl_setopt($curl,CURLOPT_POSTFIELDS, http_build_query($data));

Body:
I'm trying to send some data to a given API with the POST method.
I wrote a function in order to execute any CURL request from my project.
When I use it with a param which the value is an array, this array is automatically turned into a string "Array".

Exemple :
Here is my function :

function callAPI($method, $url, $data = false)
    {
        $curl = curl_init();
        // First var_dump()
        var_dump($data);

        switch ($method)
        {
            case "POST":
                curl_setopt($curl, CURLOPT_POST, 1);
                if ($data) {
                    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
                    // Second var_dump()
                    var_dump($data);
                }
                break;
            case "PUT":
                curl_setopt($curl, CURLOPT_PUT, 1);
                break;
            default:
                if ($data)
                    $url = sprintf("%s?%s", $url, http_build_query($data));
        }

        $headers = array();
        $headers[] = 'Accept: application/json';
        $headers[] = 'Content-Type: application/json';

        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

        $auth = "username:pwd";
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_USERPWD, $auth);
        curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);

        ....
    }

Here is an use case of my function :

$values = array(
    "param1" => "value1",
    "param2" => "value2",
    "param3" => "value3",
     ...
    "param10" => array("23"),
);

callAPI('POST', "https://myapi", $values);

The first var_dump prints the corrects values :

array(4) {
    ["param1"]=>
        string(6) "value1"
    ["param2"]=>
        string(6) "value2"
    ["param3"]=>
        string(6) "value3"
    ["param10"]=>
        array(1) {
            [0]=>
                string(2) "23"
        }
}

But the second one gives a wrong value for "param10" :

array(4) {
    ["param1"]=>
        string(6) "value1"
    ["param2"]=>
        string(6) "value2"
    ["param3"]=>
        string(6) "value3"
    ["param10"]=>
        string(5) "Array"
}

Is there someone having an idea in order to fix this issue ?


问:
How can I reference xaml Template from a Converter?
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

```<code>        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>
</code>```

and I have this control using this converter:

```<code><ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

My Converter:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }
</code>```

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

答:
What you are trying to accomplish is called a Template Selector. You can read about it, for example, here: http://codingbandit.com/Blog/blog/wpf-data-templates-part-4-template-selectors/

Given that, you will be defining a template selector (see ContentTemplateSelector property on your control). And its SelectTemplate method will look something like this:

```<code>public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
    ControlTemplate template = null;
    ContentPresenter pres = container as ContentPresenter;

    try
    {
        if (value != null)
            template = item.useTemplate1 ? pres.FindResource("_templateA") : pres.FindResource("_templateB");
    }
    catch (Exception ex)
    {
        Debug.Assert(false, ex.ToString());
    }

    return toolbar;
}
</code>```

Update:
Sorry, I overlooked that you are trying to get a ControlTemplate, while template selectors are for selecting a DataTemplate. But I believe that you task can also be achieved using data templates.

If you still want to use ControlTemplate then triggers is the way to go:

```<code><ControlTemplate x:Name="_templateA" x:Key="templateA">
    <StackPanel Grid.Column="0" Margin="0,0,5,0">
        <Blah />
    </StackPanel>
</ControlTemplate>

<ControlTemplate x:Name="_templateB" x:Key="templateB">
    <StackPanel Grid.Column="0" Margin="0,0,5,0">
        <Blah Blah />
    </StackPanel>
</ControlTemplate>

<Style x:Key="MyControlStyle" TargetType="[x:Type Control}">
   <Setter Property="Template" Value="{StaticResource templateB}"/>
   <Style.Triggers>
       <DataTrigger Binding="{Binding useTemplate1}" Value="True">
           <Setter Property="Template" Value="{StaticResource templateA}"/>
       </DataTrigger>
   </Style.Triggers>
</Style>
</code>```

And you control:

```<code><ControlA x:Name="_controlA" >
     <Control Style="{StaticResource MyControlStyle}" />
</ControlA>
</code>```

Body:
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>

and I have this control using this converter:

<ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>

My Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

Body:
What you are trying to accomplish is called a Template Selector. You can read about it, for example, here: http://codingbandit.com/Blog/blog/wpf-data-templates-part-4-template-selectors/

Given that, you will be defining a template selector (see ContentTemplateSelector property on your control). And its SelectTemplate method will look something like this:

public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
{
    ControlTemplate template = null;
    ContentPresenter pres = container as ContentPresenter;

    try
    {
        if (value != null)
            template = item.useTemplate1 ? pres.FindResource("_templateA") : pres.FindResource("_templateB");
    }
    catch (Exception ex)
    {
        Debug.Assert(false, ex.ToString());
    }

    return toolbar;
}

Update:
Sorry, I overlooked that you are trying to get a ControlTemplate, while template selectors are for selecting a DataTemplate. But I believe that you task can also be achieved using data templates.

If you still want to use ControlTemplate then triggers is the way to go:

<ControlTemplate x:Name="_templateA" x:Key="templateA">
    <StackPanel Grid.Column="0" Margin="0,0,5,0">
        <Blah />
    </StackPanel>
</ControlTemplate>

<ControlTemplate x:Name="_templateB" x:Key="templateB">
    <StackPanel Grid.Column="0" Margin="0,0,5,0">
        <Blah Blah />
    </StackPanel>
</ControlTemplate>

<Style x:Key="MyControlStyle" TargetType="[x:Type Control}">
   <Setter Property="Template" Value="{StaticResource templateB}"/>
   <Style.Triggers>
       <DataTrigger Binding="{Binding useTemplate1}" Value="True">
           <Setter Property="Template" Value="{StaticResource templateA}"/>
       </DataTrigger>
   </Style.Triggers>
</Style>

And you control:

<ControlA x:Name="_controlA" >
     <Control Style="{StaticResource MyControlStyle}" />
</ControlA>

ContentLicense: CC BY-SA 4.0


问:
How to change background color in static text visual studio?
I am trying to change background color of static text in our project. We use BCG library also.

In h. file I have

```<code>afx_msg HBRUSH CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor);
COLORREF m_bckNewsClr;
</code>```

In cpp. I have:

```<code>m_bckNewsClr = RGB(255, 255, 255);

HBRUSH CStartPage::CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor)
{
    pWnd->GetDlgItem(IDC_STATIC_NEWS_CAPTION_1);
    pDC->SetBkColor(m_bckNewsClr);
    return (HBRUSH)m_Brush.GetSafeHandle();
}
</code>```

In massage map:

```<code>ON_WM_CTLCOLOR()
</code>```

Anyway, it is even not visible the function CtlColor, when I put the breakpoint.

Does someone know how to change this backgound static text in this case?

答:
The ON_WM_CTLCOLOR expects a method named:

```<code>afx_msg HBRUSH OnCtlColor(
   CDC* pDC,
   CWnd* pWnd,
   UINT nCtlColor
);
</code>```

See also CWnd::OnCtlColor for a sample how to do it.

And also https://stackoverflow.com/a/12007350/8918119

Body:
I am trying to change background color of static text in our project. We use BCG library also.

In h. file I have

afx_msg HBRUSH CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor);
COLORREF m_bckNewsClr;

In cpp. I have:

m_bckNewsClr = RGB(255, 255, 255);

HBRUSH CStartPage::CtlColor(CDC * pDC, CWnd * pWnd, UINT nCtlColor)
{
    pWnd->GetDlgItem(IDC_STATIC_NEWS_CAPTION_1);
    pDC->SetBkColor(m_bckNewsClr);
    return (HBRUSH)m_Brush.GetSafeHandle();
}

In massage map:

ON_WM_CTLCOLOR()

Anyway, it is even not visible the function CtlColor, when I put the breakpoint.

Does someone know how to change this backgound static text in this case?

Body:
The ON_WM_CTLCOLOR expects a method named:

afx_msg HBRUSH OnCtlColor(
   CDC* pDC,
   CWnd* pWnd,
   UINT nCtlColor
);

See also CWnd::OnCtlColor for a sample how to do it.

And also https://stackoverflow.com/a/12007350/8918119


问:
How to correctly malloc a struct in C
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

```<code>//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}
</code>```

I'm using Visual Studio.

Thanks for help!

答:
You are not allocating it back! Take a look at how realloc works. You need to assign the pointer back after making the re-allocation like this.

```<code>if (scount == 0)
{
    s = (students*)malloc(sizeof(students));
}
else
{
    students *temp = realloc(s, sizeof(students) * (scount+1));
    if(temp == NULL){
        free(s);
    }
    else{
        s = temp;
    }
}
</code>```

By Definition, realloc returns a void pointer but you aren't collecting it.

```<code>void *realloc(void *ptr, size_t size);
</code>```

realloc returns a NULL if there's not enough space. So you can re-assign it when you are sure that it is not NULL

Just make a small change above and your code works like a charm!

Cheers!

Title: How to correctly malloc a struct in C

Body:
Here is my full code, it looks like to work, but it's not working very well.
I would accept any code, that is working like this.

Firstly, the code works, but when I want to add the third name to the struct, it crashes.

Is there any other way to do this?

I need struct, because in the future, I want to add some other params, like age, average, gender, etc.

Please, help me out.

//The student table
typedef struct students {
    char name[50];
} students;

//Global params
int scount = 0;
students *s;

//Basic functions
void addNewStudent();

int main()
{
    int loop = 1;
    char in;
    int ch;
    printf("Willkommen.\n Wahlen Sie bitte von die folgenden Optionen:\n");
    while (loop)
    {
        printf("\t[1] Neue Student eingeben\n");
        printf("\t[9] Programm beenden\n");

        scanf(" %c", &in);
        while ((ch = getchar()) != '\n');
        switch (in)
        {
        case '1':
            addNewStudent();
            break;
        case '9':
            loop = 0;
            break;
        default: printf("------\nOption nicht gefunden.\n------\n");
            break;
        }
    }
    free(s);
    return 0;
}

void addNewStudent()
{
    int index = 0;
    if (scount == 0)
    {
        s = (students*)malloc(sizeof(students));
    }
    else
    {
        realloc(s, sizeof(students) * scount);
    }

    printf("Geben Sie Bitte die Name:\n");
    fgets(s[scount].name, sizeof(s[scount].name), stdin);

    while (s[scount].name[index] != '\n')
    {
        index++;
    }
    s[scount].name[index] = '\0';
    scount++;
}

I'm using Visual Studio.

Thanks for help!

Body:
You are not allocating it back! Take a look at how realloc works. You need to assign the pointer back after making the re-allocation like this.

if (scount == 0)
{
    s = (students*)malloc(sizeof(students));
}
else
{
    students *temp = realloc(s, sizeof(students) * (scount+1));
    if(temp == NULL){
        free(s);
    }
    else{
        s = temp;
    }
}

By Definition, realloc returns a void pointer but you aren't collecting it.

void *realloc(void *ptr, size_t size);

realloc returns a NULL if there's not enough space. So you can re-assign it when you are sure that it is not NULL

Just make a small change above and your code works like a charm!

Cheers!


问:
Significance of finally block
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}
</code>```

equivalent to

```<code>Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()
</code>```

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?

答:
No, it is not equivalent. In the first snippet r.close() will be always called, while in the second snippet r.close() might not be called:

when the try block throws an Error (what might happen when you use assertions and an assertion fails)

when the exception handler throws another Exception

To ensure the resources are always released close() method should be called from finally blocks.

Title: Significance of finally block

Body:
What is the significance of the Finally block in a Try...[Catch]...Finally block?

Isn't this code

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
} finally {
  r.close()
}

equivalent to

Resource r;
try{
  r = new Resource();
  r.methodThatThrowsException();
} catch (Exception e) {
  e.printStackTrace()
}
r.close()

? I would understand if they have the same scope, but the fact that I have to define Resource r outside the try block anyway to use it in the finally block means that I see no advantage to using a finally block.

Am I missing something? Is there a certain case that I haven't thought of that requires a Finally block?


问:
How to process a list of files in MATLAB
in MATLAB, my function is like this:

```<code> names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results
</code>```

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

答:
If your function needs the entire cell array at once, then here's an option:

```<code>Cnum     = strsplit(strtrim(sprintf('C%03d ', 1:100)))';
basepath = 'D:';
complete = @(str) fullfile(basepath, Cnum, strcat(Cnum, '_', str, '.csv'));
pths     = [complete('Deo') complete('Oxy') complete('Tal')];
</code>```

Otherwise, go with Laure's solution.

Body:
in MATLAB, my function is like this:

 names = {'d:\C001\C001_Deo.csv','d:\C001\C001_Oxy.csv','d:\C001\C001_Tal.csv'}
 data_conversion(names)         %this function creat a folder in C001 to save results

I have 100 folders named as C001, C002, ..., C100. Each folder has three .csv files, named like this: C001_Deo.csv, C001_Oxy.csv, C001_Tal.csv,  C002_Deo.csv, C002_Oxy.csv, C002_Tal.csv, ...

Does anyone can help me to write a loop so I can run data_conversion(names) at a time to get all the results. Then I don't need to run it 100 times.
I tried many times but failed. Thanks!

Body:
If your function needs the entire cell array at once, then here's an option:

Cnum     = strsplit(strtrim(sprintf('C%03d ', 1:100)))';
basepath = 'D:';
complete = @(str) fullfile(basepath, Cnum, strcat(Cnum, '_', str, '.csv'));
pths     = [complete('Deo') complete('Oxy') complete('Tal')];

Otherwise, go with Laure's solution.


问:
How to ensure Makefile variable is set as a prerequisite?
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

```<code>ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"
</code>```

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

```<code>deploy: make-sure-ENV-variable-is-set
</code>```

答:
As I see the command itself needs the ENV variable so you can check it in the command itself:</p>

```<code>.PHONY: deploy check-env

deploy: check-env
    rsync . $(ENV).example.com:/var/www/myapp/

check-env:
    if test "$(ENV)" = "" ; then \
        echo "ENV not set"; \
        exit 1; \
    fi
</code>```

Body:
A Makefile deploy recipe needs an environment variable ENV to be set to properly execute itself, whereas other recipes don't care, e.g.,

ENV =

.PHONY: deploy hello

deploy:
    rsync . $(ENV).example.com:/var/www/myapp/

hello:
    echo "I don't care about ENV, just saying hello!"

How can I make sure this ENV variable is set? Is there a way to declare this makefile variable as a prerequisite of the deploy recipe? e.g.,

deploy: make-sure-ENV-variable-is-set

Body:
As I see the command itself needs the ENV variable so you can check it in the command itself:

.PHONY: deploy check-env

deploy: check-env
    rsync . $(ENV).example.com:/var/www/myapp/

check-env:
    if test "$(ENV)" = "" ; then \
        echo "ENV not set"; \
        exit 1; \
    fi


问:
Dygraphs StackedBarChart with Multiple Line Series
We are looking for a Graph similar where we can plot StackedBarChart with multiple line series. This chart is available in Dygraphs for R.

Is this available in Dygraphs for JS? Can someone help?

Regards,
Ashish

答:
dygraphs for R is using dygraphs JS under the hood, so it's definitely possible. You'll want to set a custom plotter for the series you want rendered as bar charts.

```<code>g = new Dygraph(div, data,
        {
          labels: ['Date', 'A', 'B'],
          series: {
            "A": {
              strokeWidth: 2
            },
            "B": {
              plotter: barChartPlotter
            }
          }
        });
</code>```

You can find a fully-worked example on the plotters demo page.

Body:
dygraphs for R is using dygraphs JS under the hood, so it's definitely possible. You'll want to set a custom plotter for the series you want rendered as bar charts.

g = new Dygraph(div, data,
        {
          labels: ['Date', 'A', 'B'],
          series: {
            "A": {
              strokeWidth: 2
            },
            "B": {
              plotter: barChartPlotter
            }
          }
        });

You can find a fully-worked example on the plotters demo page.


问:
How can I test my pre-receive hook?
I need to create a pre-receive hook that rejects push from any client from any branch which is not master, So I wrote this script:

```<code>     #!/bin/bash

    refname="$0"
    oldrev="$1"
    newrev="$2"

    alowed_branch='master'
    current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

    if [ $alowed_branch = $current_branch ]
    then
      echo "you are pushing to master branch"
      exit 0
    else
      echo Branch $current_branch is Locked.
     exit 1
    fi
</code>```

Now I don't know how can I test it...

When tested on a 'pre-commit' hook on my local git repo I get what I want:

But when trying to test it as a pre-push or pre-receive hook as suggested it doesn't take any effect and I can commit and push with no interference.

is there a way to test it on GitHub?

答:
Testing hooks, especially pre-receive hooks, is difficult: they run in unusual environments.  There are few good ways to test them (the main good way is a sacrificial repository or two).

You have a number of intertwining problems here:

```<code>refname="$0"
</code>```

This is just wrong no matter what, as in a shell script, $0 refers to the name of the script itself.

```<code>current_branch=$(refname)
</code>```

This, which you deleted in an edit, was also wrong: it tries to run the command refname.  So it's good that you replaced it, but:

```<code>current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
</code>```

This is subtly wrong: if your current branch is named fixes/bug-123 it will set current_branch to bug-123, not fixes/bug-123.

To get the current branch name as a symbolic reference minus the refs/heads/ part, use:

```<code>current_branch=$(git symbolic-ref --short HEAD) || exit 1
</code>```

The --short directs git symbolic-ref to omit the refs/heads/ part, and the || exit 1 directs the shell to exit (with failure status) if git symbolic-ref itself fails, which it could: if you have a "detached HEAD", HEAD is not a symbolic ref, and Git will complain about that and current_branch will be set to the empty string.

Now, with those out of the way, you mention:

... trying to test it as a pre-push or pre-receive hook ...

As a pre-push hook, $1 and $2 (which you store in oldrev and newrev) would actually be set to the name and URL of the remote!  The old and new revision IDs, and the old and new reference names, are passed to that hook as its standard input.  This all happens on the client side, after connecting to the other Git (the remote) but before sending anything.  (See the section on pre-push hooks in the githooks documentation.)

As a pre-receive hook, $1 and $2 would not be set to anything at all (which is OK since you never use the variables anyway).  The current branch would be the current branch in the other Git on the remote.  A pre-receive hook, like a pre-push hook, must read its standard input, one line at a time, checking each group of parameters supplied on that line.  If the hook exits with a nonzero return, the entire push is rejected (from the server's side).

When checking reference names in a pre-push or pre-receive hook, be sure to check the entire reference: an incoming reference (in either hook) or outgoing reference (in a pre-push hook) can refer to a tag, for instance, as in refs/tags/v1.2, or a branch whose name includes slashes, as in refs/heads/feature/tall.  Don't just chop off all but the last part of the name, nor the first two components without looking at them.  And, in either hook, the current branch name is normally entirely irrelevant: someone running git push specifies which reference(s) to push on the command line:

```<code>git push origin \
  refs/heads/master:refs/for/master \
  refs/tags/v1.2:refs/tags/v1.2 \
  refs/notes/commits:refs/notes/commits \
  refs/peculiar-ref:refs/even-stranger/master
</code>```

for instance.  None of these is going into a branch on the target; only one is from a branch on the source.

(Note that hooks can be written in any language that can run on the machine on which that particular Git is installed.  They don't have to be bash / sh scripts—though if you have Git you must have a shell, since parts of Git are written in shell.  Always beware of hardcoded paths: for instance, bash may be located in /usr/local/bin/bash rather than /bin/bash on some systems.)

Title: How can I test my pre-receive hook?

Body:
I need to create a pre-receive hook that rejects push from any client from any branch which is not master, So I wrote this script:

     #!/bin/bash

    refname="$0"
    oldrev="$1"
    newrev="$2"

    alowed_branch='master'
    current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

    if [ $alowed_branch = $current_branch ]
    then
      echo "you are pushing to master branch"
      exit 0
    else
      echo Branch $current_branch is Locked.
     exit 1
    fi

Now I don't know how can I test it...

When tested on a 'pre-commit' hook on my local git repo I get what I want:

But when trying to test it as a pre-push or pre-receive hook as suggested it doesn't take any effect and I can commit and push with no interference.

is there a way to test it on GitHub?

Body:
Testing hooks, especially pre-receive hooks, is difficult: they run in unusual environments.  There are few good ways to test them (the main good way is a sacrificial repository or two).

You have a number of intertwining problems here:

refname="$0"

This is just wrong no matter what, as in a shell script, $0 refers to the name of the script itself.

current_branch=$(refname)

This, which you deleted in an edit, was also wrong: it tries to run the command refname.  So it's good that you replaced it, but:

current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

This is subtly wrong: if your current branch is named fixes/bug-123 it will set current_branch to bug-123, not fixes/bug-123.

To get the current branch name as a symbolic reference minus the refs/heads/ part, use:

current_branch=$(git symbolic-ref --short HEAD) || exit 1

The --short directs git symbolic-ref to omit the refs/heads/ part, and the || exit 1 directs the shell to exit (with failure status) if git symbolic-ref itself fails, which it could: if you have a "detached HEAD", HEAD is not a symbolic ref, and Git will complain about that and current_branch will be set to the empty string.

Now, with those out of the way, you mention:

... trying to test it as a pre-push or pre-receive hook ...

As a pre-push hook, $1 and $2 (which you store in oldrev and newrev) would actually be set to the name and URL of the remote!  The old and new revision IDs, and the old and new reference names, are passed to that hook as its standard input.  This all happens on the client side, after connecting to the other Git (the remote) but before sending anything.  (See the section on pre-push hooks in the githooks documentation.)

As a pre-receive hook, $1 and $2 would not be set to anything at all (which is OK since you never use the variables anyway).  The current branch would be the current branch in the other Git on the remote.  A pre-receive hook, like a pre-push hook, must read its standard input, one line at a time, checking each group of parameters supplied on that line.  If the hook exits with a nonzero return, the entire push is rejected (from the server's side).

When checking reference names in a pre-push or pre-receive hook, be sure to check the entire reference: an incoming reference (in either hook) or outgoing reference (in a pre-push hook) can refer to a tag, for instance, as in refs/tags/v1.2, or a branch whose name includes slashes, as in refs/heads/feature/tall.  Don't just chop off all but the last part of the name, nor the first two components without looking at them.  And, in either hook, the current branch name is normally entirely irrelevant: someone running git push specifies which reference(s) to push on the command line:

git push origin \
  refs/heads/master:refs/for/master \
  refs/tags/v1.2:refs/tags/v1.2 \
  refs/notes/commits:refs/notes/commits \
  refs/peculiar-ref:refs/even-stranger/master

for instance.  None of these is going into a branch on the target; only one is from a branch on the source.

(Note that hooks can be written in any language that can run on the machine on which that particular Git is installed.  They don't have to be bash / sh scripts—though if you have Git you must have a shell, since parts of Git are written in shell.  Always beware of hardcoded paths: for instance, bash may be located in /usr/local/bin/bash rather than /bin/bash on some systems.)


问:
Navigation Controller back button is not releasing memory of dismissed viewController
Newbie question here.
Imagine a very basic storyboard with 2 vc (A and B).
A is embedded in a navController. A has a collectionView showing a grid of images. B is displaying the clicked grid item in big. So simple list->detail.

Doing all with IB, I ctrl-dragged from collectionView cell item to B and selected 'show (e.g Push)' segue.

Now when I run the app and click multiple times on image in grid and then on '< Back' button, I explore the memory graph.
I can see 10 'B' view controllers if I did the navigation 10 times.

That causes a lot of memory to be used and it grows every time.

I found a few posts speaking about unwind, and pop to root vc, but all are dealing with programmatic navigation. Here's just the case of simple storyboard done all with IB.

Expected: A->B->A. Memory: A

Reality: A->B->A. Memory: A, B

How can I avoid retaining the memory for those vc that are dismissed?

in A I have:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "dreamDetail" {
        let newViewController = segue.destination as! DreamDetailViewController
        newViewController.dream = allDreams?[(collectionView.indexPathsForSelectedItems?.first?.item)!]
        newViewController.dreams = allDreams
    }
}
</code>```

in B I have:

```<code>weak var dream: DreamRealm?{
    didSet {
    }
}

var dreams: [DreamRealm]?{
    didSet {
    }
}
</code>```

DreamRealm is just a Realm model.

```<code>class DreamRealm: Object {

@objc dynamic var filename: String? = nil
@objc dynamic var path = ""
</code>```

答:
To avoid retaining the memory for your VC that are dismissed, you need to check if there is any retain cycle.

One step to help you to check if your VCs are correctly deinitialised, you can implement a method called deinit. It's a method called when your VC is deinit and no longer in the memory. You can print a message to see if it's the case or not.

If it's not the case, you probably have a strong reference somewhere in your code. You need to avoid it by weakening your reference with weak keyword or unowned or just delete it if you don't need it.

Body:
Newbie question here.
Imagine a very basic storyboard with 2 vc (A and B).
A is embedded in a navController. A has a collectionView showing a grid of images. B is displaying the clicked grid item in big. So simple list->detail.

Doing all with IB, I ctrl-dragged from collectionView cell item to B and selected 'show (e.g Push)' segue.

Now when I run the app and click multiple times on image in grid and then on '< Back' button, I explore the memory graph.
I can see 10 'B' view controllers if I did the navigation 10 times.

That causes a lot of memory to be used and it grows every time.

I found a few posts speaking about unwind, and pop to root vc, but all are dealing with programmatic navigation. Here's just the case of simple storyboard done all with IB.

Expected: A->B->A. Memory: A

Reality: A->B->A. Memory: A, B

How can I avoid retaining the memory for those vc that are dismissed?

in A I have:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "dreamDetail" {
        let newViewController = segue.destination as! DreamDetailViewController
        newViewController.dream = allDreams?[(collectionView.indexPathsForSelectedItems?.first?.item)!]
        newViewController.dreams = allDreams
    }
}

in B I have:

weak var dream: DreamRealm?{
    didSet {
    }
}

var dreams: [DreamRealm]?{
    didSet {
    }
}

DreamRealm is just a Realm model.

class DreamRealm: Object {

@objc dynamic var filename: String? = nil
@objc dynamic var path = ""


问:
UML use-cases and iterations
How can I represent in a UML use case's diagram the fact that an action is iterative? For example: actor Admin can add new categories and new subcategories. A subcategory can have other subcategories, so admin can add a new subcategory in a subcategory. Thanks.</p>

答:
In an UML use case, you do not model the process, but the features ...

So you can't ...

Next time, at least provide your own schema to show that you worked at least a little ...

And if you provide some works, you could get a more helpful answer ...

Title: UML use-cases and iterations


问:
How to redirect correctly in a global error handler
I have this global error handler:

```<code>import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler
    {
        constructor(private injector: Injector) {
            super(false);
        }

        handleError(error) {
            super.handleError(error);
            const router = this.injector.get(Router);
                router.navigateByUrl('/error');
        }

    }
</code>```

I put it in app.module:

```<code>  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]
</code>```

to test this I throw an error inside a service. For some reason the error component shows up together with the other contents of the page. Something like this:

if I test the error component by going to /error it shows up like this (the error page is a paragraph with a single line):

```<code>Sorry, something went wrong!
</code>```

but when I go to my home page where the error should trigger it shows up like this:

```<code>Sorry, something went wrong!

....
... Original content for /home
....

Sorry, something went wrong!
</code>```

Can someone enlighten me what am I doing wrong?

Update

I've updated to angular-cli 1.5.2 AND also updated to angular 5 and the bug seems fixed there. I can navigate to the error page using the router.

答:
I've made some research and here is the reason why it behaves this way:

Since you're throwing an error in your service, the component which is using the service cannot be destroyed, thus the router is not able to release it. Thanks @TetraDev for pointing this out.

While someone might think it's an Angular bug I cannot confirm because I haven't found an open issue regarding it (feel free to update the answer if you have the link).

In order to resolve your problem I suggest not to use Router in this case and perform a browser redirect window.location.href = '/error'; instead.

Body:
I have this global error handler:

import { ErrorHandler, Injectable, Injector } from '@angular/core';
import { Router } from '@angular/router';

    @Injectable()
    export class GlobalErrorHandler extends ErrorHandler
    {
        constructor(private injector: Injector) {
            super(false);
        }

        handleError(error) {
            super.handleError(error);
            const router = this.injector.get(Router);
                router.navigateByUrl('/error');
        }

    }

I put it in app.module:

  providers: [
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler
    }
  ]

to test this I throw an error inside a service. For some reason the error component shows up together with the other contents of the page. Something like this:

if I test the error component by going to /error it shows up like this (the error page is a paragraph with a single line):

Sorry, something went wrong!

but when I go to my home page where the error should trigger it shows up like this:

Sorry, something went wrong!

....
... Original content for /home
....

Sorry, something went wrong!

Can someone enlighten me what am I doing wrong?

Update

I've updated to angular-cli 1.5.2 AND also updated to angular 5 and the bug seems fixed there. I can navigate to the error page using the router.


问:
When programming for iphone how do you use data for multiple views?
I am a objective-c newbie and I was wondering how do you use data obtained from one view in another? For example I ask a user for a text input, and this text input then changes a label when a button is hit. I want this information for another label in a different view. how would I get it?
Thanks</p>

答:
When the text input finishes, it tells the view controller. A view controller can control a number of views, or even control other controllers. When it gets the notification, it can tell the other views about it.

You do this by having the text field trigger an action in your controller.

You can do this directly, or you could set up "bindings".


问:
png.file at the top center of Shiny app
I create my Shiny app and I just add one png.file at the top of Shiny app and I would like to see it in center position.
I use the code:

```<code>img(src = "logo.png", align = "center")
</code>```

or

```<code>img(src = "logo.png", align = "centre")
</code>```

but it does not work.
How to do it?

答:
This might be what you're after: https://github.com/rstudio/shiny/issues/555

Sorry it's so late!

AB

The align attribute of  is not what you need. It is a different
  thing (http://www.w3schools.com/tags/att_img_align.asp). You can use
  style="display: block; margin-left: auto; margin-right: auto;" to
  center an image. Or div(img(...), style="text-align: center;").

Title: png.file at the top center of Shiny app

Body:
I create my Shiny app and I just add one png.file at the top of Shiny app and I would like to see it in center position.
I use the code:

img(src = "logo.png", align = "center")

or

img(src = "logo.png", align = "centre")

but it does not work.
How to do it?


问:
WPF TreeviewItem Width
i am trying to prevent my treeviewitems from overflowing the window size when
the content is too long.I have tried various approaches (Binding ActualWidth of parent, HorizontalContentAlign, Wrapping into other containers,...) but without success.

I want to achieve 2 things:

All TreeviewItems must fill the remaining space (Stretch)

I do not want a horizontal scrollbar, instead i want the text within the
textbox overflowing.

That's my code so far.

Any ideas??

KR Manu

```<code> <TreeView x:Name="tv">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="KeyboardNavigation.TabNavigation" Value="Continue"/>
                <Setter Property="IsTabStop" Value="True"/>
                <Setter Property="Focusable" Value="False" />
                <Setter Property="IsExpanded" Value="True" />
                <Setter Property="Background" Value="Transparent"/>
                <Setter Property="HorizontalAlignment" Value="Stretch"/>
                <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                <Setter Property="Padding" Value="1,0,0,1"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TreeViewItem}">
                            <Grid>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition MinWidth="19" Width="Auto"/>
                                    <ColumnDefinition Width="*"/>
                                </Grid.ColumnDefinitions>
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto"/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>

                                <!-- Connecting Lines -->
                                <Rectangle x:Name="HorLn" Margin="9,1,0,0" Height="1" Stroke="Red" SnapsToDevicePixels="True"/>
                                <Rectangle x:Name="VerLn" Width="1" Stroke="Red" Margin="0,0,1,0" Grid.RowSpan="2" SnapsToDevicePixels="true"/>
                                <ToggleButton Margin="-1,0,0,0" x:Name="Expander" Visibility="Hidden"  IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press"/>
                                <Border x:Name="Bd" Grid.Column="1" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
                                    <ContentPresenter Grid.Column="1" x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" MinWidth="20"/>
                                </Border>
                                <ItemsPresenter x:Name="ItemsHost" Grid.Row="1" Grid.Column="1"/>
                            </Grid>
                            <ControlTemplate.Triggers>
                                <Trigger Property="IsExpanded" Value="false">
                                    <Setter TargetName="ItemsHost" Property="Visibility" Value="Collapsed"/>
                                </Trigger>
                                <Trigger Property="HasItems" Value="false">
                                    <Setter TargetName="Expander" Property="Visibility" Value="Hidden"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="HasHeader" Value="false"/>
                                        <Condition Property="Width" Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="PART_Header" Property="MinWidth" Value="75"/>
                                </MultiTrigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="HasHeader" Value="false"/>
                                        <Condition Property="Height" Value="Auto"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="PART_Header" Property="MinHeight" Value="19"/>
                                </MultiTrigger>
                                <Trigger Property="IsSelected" Value="true">
                                    <Setter TargetName="Bd" Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                                </Trigger>
                                <MultiTrigger>
                                    <MultiTrigger.Conditions>
                                        <Condition Property="IsSelected" Value="true"/>
                                        <Condition Property="IsSelectionActive" Value="false"/>
                                    </MultiTrigger.Conditions>
                                    <Setter TargetName="Bd" Property="Background" Value="Transparent"/>
                                    <Setter Property="Foreground" Value="White"/>
                                </MultiTrigger>
                                <Trigger Property="IsEnabled" Value="false">
                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
        <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBox Text="{Binding Mode=OneWay}" />
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</code>```

答:
Maybe, you have 2 choice.

TextBox TextTrimming

or you will set the max lenght of char in textbox.

Title: WPF TreeviewItem Width

Body:
i am trying to prevent my treeviewitems from overflowing the window size when
the content is too long.I have tried various approaches (Binding ActualWidth of parent, HorizontalContentAlign, Wrapping into other containers,...) but without success.

I want to achieve 2 things:

All TreeviewItems must fill the remaining space (Stretch)

I do not want a horizontal scrollbar, instead i want the text within the
textbox overflowing.

That's my code so far.

Any ideas??

KR Manu

 <TreeView x:Name="tv">
        <TreeView.Resources>

        </TreeView.Resources>
        <TreeView.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <TextBox Text="{Binding Mode=OneWay}" />
                </Grid>
            </DataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>


问:
CodeIgniter Pagination Problem
Helo. I’m trying to make a items pagination. I have 3 function, first displaying category, 2nd displaying sucategory. 3rd displaying items is cold get_books_by_subcategory. 3rd function get a segment->url(3) argumnet, i want to make a pagination in the same function. but i cant do it.

This is functions code in controller:

```<code>function get_category()
    {

        $query = $this->Kategorie_model->get_category();
        $this->response['podkategorie'] = '';
        $this->response['kategorie'] = '';
        $podkategorie = '';

        if($query->num_rows() > 0)
        {
            foreach($query->result() as $item)
            {
                $podkategorie = $this->get_sub_category($item->CAT_ID);

                $this->response['kategorie'] .=  $this->load->view('Ksiegarnia/left', array('kategorie' =>$item, 'podkategorie'=>$podkategorie), true);
            }
        }

        $data = $this->response['kategorie'];
        return $data;

    }

     function get_sub_category($id)
    {

           $this->response['wynik'] = '';

           $query = $this->Kategorie_model->get_sub_category($id);

           if($query->num_rows() > 0)
           {

                foreach($query->result() as $row)
                {

                   $link = site_url('ksiegarnia/get_books_by_subcategory/'.$row->SUBC_ID);
                    $this->response['wynik'] .= '<div class="subcat_name"><a href = "'.$link.'">'.$row->SUBC_Name.'</a></div>';

                }
           }
           else
           {
                $this->response['wynik'] = '<H1>BRAK DANYCH </H1>';
           }

            return $this->response['wynik'];
    }

    function get_books_by_subcategory()
    {
        $widok['center'] = '';
         $widok['left'] = $this->get_category();
         $widok['right'] = $this->load->view('Ksiegarnia/right', '', true);
          $id = $this->uri->segment(3);
        if(isset($id) and is_numeric($id))
        {
             $query = $this->Kategorie_model->get_books_by_subcategory($id, $this->uri->segment(4));

             if($query->num_rows() > 0)
             {

                foreach($query->result() as $item)
                {

                    $widok['center'] .=  $this->load->view('Ksiegarnia/get_books', array('data' =>$item), true);

                }
            }
            else
            {
                $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);;
            }

            $widok['center'] .= $this->pagination->create_links();
             $this->load->view('Ksiegarnia/index', $widok);

        }

    }
</code>```

And this is my model:

```<code>function get_books_by_subcategory($id, $offset=0)
    {

                  $config['base_url'] = 'http://lukaszbielecki.cba.pl/ksiegarnia/CI/index.php/ksiegarnia/get_books_by_subcategory/'.$id;
                  $config['per_page'] = 7;
                  $this->db->where('SUB_CATEGORY_SUBC_ID', $id);

                  $config['total_rows'] = $this->db->get('books')->num_rows();
                  $config['num_links'] = 20;

                   $this->pagination->initialize($config);
         return   $this->db->get('books',$config['per_page'],$offset);
          //$wynik = $this->db->query("Select * from books where SUB_CATEGORY_SUBC_ID = '".$id."'");
          //return $wynik;
    }
</code>```

The arguments in url is changing, but dispalyin only a items from first subcategory.
Help, please.

答:
On this line $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'
brak danych
'), true);; in your controller, you have an additional  semicolon ; that is causing a syntax error.

Title: CodeIgniter Pagination Problem

Body:
Helo. I’m trying to make a items pagination. I have 3 function, first displaying category, 2nd displaying sucategory. 3rd displaying items is cold get_books_by_subcategory. 3rd function get a segment->url(3) argumnet, i want to make a pagination in the same function. but i cant do it.

This is functions code in controller:

function get_category()
    {

        $query = $this->Kategorie_model->get_category();
        $this->response['podkategorie'] = '';
        $this->response['kategorie'] = '';
        $podkategorie = '';

        if($query->num_rows() > 0)
        {
            foreach($query->result() as $item)
            {
                $podkategorie = $this->get_sub_category($item->CAT_ID);

                $this->response['kategorie'] .=  $this->load->view('Ksiegarnia/left', array('kategorie' =>$item, 'podkategorie'=>$podkategorie), true);
            }
        }

        $data = $this->response['kategorie'];
        return $data;

    }

     function get_sub_category($id)
    {

           $this->response['wynik'] = '';

           $query = $this->Kategorie_model->get_sub_category($id);

           if($query->num_rows() > 0)
           {

                foreach($query->result() as $row)
                {

                   $link = site_url('ksiegarnia/get_books_by_subcategory/'.$row->SUBC_ID);
                    $this->response['wynik'] .= '
'.$row->SUBC_Name.'
';

                }
           }
           else
           {
                $this->response['wynik'] = '
BRAK DANYCH
';
           }

            return $this->response['wynik'];
    }

    function get_books_by_subcategory()
    {
        $widok['center'] = '';
         $widok['left'] = $this->get_category();
         $widok['right'] = $this->load->view('Ksiegarnia/right', '', true);
          $id = $this->uri->segment(3);
        if(isset($id) and is_numeric($id))
        {
             $query = $this->Kategorie_model->get_books_by_subcategory($id, $this->uri->segment(4));

             if($query->num_rows() > 0)
             {

                foreach($query->result() as $item)
                {

                    $widok['center'] .=  $this->load->view('Ksiegarnia/get_books', array('data' =>$item), true);

                }
            }
            else
            {
                $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'
brak danych
'), true);;
            }

            $widok['center'] .= $this->pagination->create_links();
             $this->load->view('Ksiegarnia/index', $widok);

        }

    }

And this is my model:

function get_books_by_subcategory($id, $offset=0)
    {

                  $config['base_url'] = 'http://lukaszbielecki.cba.pl/ksiegarnia/CI/index.php/ksiegarnia/get_books_by_subcategory/'.$id;
                  $config['per_page'] = 7;
                  $this->db->where('SUB_CATEGORY_SUBC_ID', $id);

                  $config['total_rows'] = $this->db->get('books')->num_rows();
                  $config['num_links'] = 20;

                   $this->pagination->initialize($config);
         return   $this->db->get('books',$config['per_page'],$offset);
          //$wynik = $this->db->query("Select * from books where SUB_CATEGORY_SUBC_ID = '".$id."'");
          //return $wynik;
    }

The arguments in url is changing, but dispalyin only a items from first subcategory.
Help, please.

Body: On this line $widok['center'] = $this->load->view('Ksiegarnia/get_books', array('tytul' =>'<h1>brak danych</h1>'), true);; in your controller, you have an additional  semicolon ; that is causing a syntax error.


问:
Counting the (year)quarters between two dates
I have project built using laravel and a I have to build a function that counts all the complete quarters that are in the selected date range - the dates used are inserted via input.

Here are the quarters(i used numerical representations for the months)

01 - 03 first quarter
04 - 06 second quarter
07 - 09 third quarter
10 - 12 forth quarter

I would really appreciate your help,because I've been at it for an entire day now and basically have nothing to show for it,i thing I've been trying so hard i'm actually at the point where i'm so tired, i can t think straight.

I do have some code but it;s worthless, because it doesn't work, and any kind of idea or snippet of code is welcomed.

Thanks for your help in advance.

答:
You can do something like in this example:

```<code>$February = 2;
$October = 10;

$completedQuarters = ceil($October/3) - ceil($February/3); // = 3
</code>```

What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:

```<code>$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;
</code>```

You´re description is not very clear, let me know if that´s what you had in mind.

Body:
You can do something like in this example:

$February = 2;
$October = 10;

$completedQuarters = ceil($October/3) - ceil($February/3); // = 3

What about the quarter in which the date range starts, should it also count? If it should only count if it begins in the first month of a quarter you can check for it like this:

$completedQuarters = ceil($October/3) - ceil($February/3) -1; // = 2
if($February-1%3 == 0) $completedQuarters += 1;

You´re description is not very clear, let me know if that´s what you had in mind.