问:
pytest-flask -- can not access application's endpoints from test client function
Edit:

After moving stuff around and renaming things, I'm revising this post to reflect my current issue.

I'm unable to access the endpoints in the files inside my views folder. I thought importing them explicitly in test_example.py or having them already imported in __init__.py would do the trick.

Here's the error when running pytest:

```<code>    rv = self._partial_build(endpoint, values, method, append_unknown)
    if rv is None:
>       raise BuildError(endpoint, values, method, self)
E       werkzeug.routing.BuildError: Could not build url for endpoint '/api/create_booth'. Did you mean 'static' instead?
</code>```

Also, I tried substituting url_for('some_endpoint') with url_for('some_endpoint', _external=True) -- had no effect.

Here's my directory structure and the simplified contents of the relevant files:

directory structure

```<code>server/
    my_app/
        __init__.py
        views/
            __init__.py
            some_views.py
    test/
        __init__.py
        conftest.py
        test_example.py
</code>```

__init__.py:

```<code>from flask import Flask

def create_app():
    app = Flask(__name__)
    return app

app = create_app()
from views.some_view import *

if __name__ == '__main__':
    app.run(debug=True)
</code>```

conftest.py

```<code>import pytest
from my_app import create_app

@pytest.fixture
def app():
    app = create_app()
    return app
</code>```

test_example.py

```<code>from flask import url_for
from my_app.views.some_views import some_endpoint

def test_some_endpoint(client):
    assert client.post(url_for('some_endpoint'),
           data=json.dumps(dict(some_attr='some_value')),
           content_type='application/json').status_code == 200
</code>```

some_views.py

```<code>from my_app import app

@app.route('/api/some_endpoint/', methods=['POST'])
def some_endpoint():
    return "success"
</code>```

I'm running pytest-flask-0.10.0, Python 3.4.3, and Flask 0.12.2

答:
I think you should really consider reorganizing your app structure. The way you are doing it will lead to circular imports which is probably why you have your views import after your app creation. I would suggest moving your app factory into its own file since you will reuse it in your tests.

my_app/factory.py

```<code>def create_app():
    # init extensions
    # init blueprints
    return app
</code>```

Then while your app is small simply keep the views in app.py As your app gets larger consider implementing the blueprint design pattern -> docs

my_app/app.py

```<code>from factory import create_app

app = create_app()

@app.route('/')
def index():
    return 'hello'

if __name__ == '__main__':
    app.run()
</code>```

In your tests

test_example.py

```<code>from factory import create_app

@py.fixture
def client():
    return create_app().test_client()

def test_route(client):
    response = client.get('/')
    assert response.json() == 'hello', 'Route should return "hello"'
</code>```

Miguel Grinberg has a really great blog on Flask he's the author of Flask Web Development which is an excellent resource. Looks like he is in the process of rewriting his tutorial on flask.

Blueprints example

my_app/factory.py

```<code>def create_app():
    app = Flask(__name__)
    from main import main
    app.register_blueprint(main)

    return app
</code>```

my_app/main.py

```<code>from flask import Blueprint

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return "hello"
</code>```

my_app/app.py

```<code>from factory import create_app

app = create_app()

if __name__ == '__main__':
    app.run()
</code>```

Hope that helps

Body:
Edit:

After moving stuff around and renaming things, I'm revising this post to reflect my current issue.

I'm unable to access the endpoints in the files inside my views folder. I thought importing them explicitly in test_example.py or having them already imported in __init__.py would do the trick.

Here's the error when running pytest:

    rv = self._partial_build(endpoint, values, method, append_unknown)
    if rv is None:
>       raise BuildError(endpoint, values, method, self)
E       werkzeug.routing.BuildError: Could not build url for endpoint '/api/create_booth'. Did you mean 'static' instead?

Also, I tried substituting url_for('some_endpoint') with url_for('some_endpoint', _external=True) -- had no effect.

Here's my directory structure and the simplified contents of the relevant files:

directory structure

server/
    my_app/
        __init__.py
        views/
            __init__.py
            some_views.py
    test/
        __init__.py
        conftest.py
        test_example.py

__init__.py:

from flask import Flask

def create_app():
    app = Flask(__name__)
    return app

app = create_app()
from views.some_view import *

if __name__ == '__main__':
    app.run(debug=True)

conftest.py

import pytest
from my_app import create_app

@pytest.fixture
def app():
    app = create_app()
    return app

test_example.py

from flask import url_for
from my_app.views.some_views import some_endpoint

def test_some_endpoint(client):
    assert client.post(url_for('some_endpoint'),
           data=json.dumps(dict(some_attr='some_value')),
           content_type='application/json').status_code == 200

some_views.py

from my_app import app

@app.route('/api/some_endpoint/', methods=['POST'])
def some_endpoint():
    return "success"

I'm running pytest-flask-0.10.0, Python 3.4.3, and Flask 0.12.2

Body:
I think you should really consider reorganizing your app structure. The way you are doing it will lead to circular imports which is probably why you have your views import after your app creation. I would suggest moving your app factory into its own file since you will reuse it in your tests.

my_app/factory.py

def create_app():
    # init extensions
    # init blueprints
    return app

Then while your app is small simply keep the views in app.py As your app gets larger consider implementing the blueprint design pattern -> docs

my_app/app.py

from factory import create_app

app = create_app()

@app.route('/')
def index():
    return 'hello'

if __name__ == '__main__':
    app.run()

In your tests

test_example.py

from factory import create_app

@py.fixture
def client():
    return create_app().test_client()

def test_route(client):
    response = client.get('/')
    assert response.json() == 'hello', 'Route should return "hello"'

Miguel Grinberg has a really great blog on Flask he's the author of Flask Web Development which is an excellent resource. Looks like he is in the process of rewriting his tutorial on flask.

Blueprints example

my_app/factory.py

def create_app():
    app = Flask(__name__)
    from main import main
    app.register_blueprint(main)

    return app

my_app/main.py

from flask import Blueprint

main = Blueprint('main', __name__)

@main.route('/')
def index():
    return "hello"

my_app/app.py

from factory import create_app

app = create_app()

if __name__ == '__main__':
    app.run()

Hope that helps


来源: stackexchange

问:
Pygame - playing mp3 files downloaded by youtube-dl is not working

Hello, I'm trying to download a mp3 file via youtube-dl and then play it on my machine using PyGame. However, all the downloaded mp3 files don't work. The weird this is if I import them myself by downloading manually from the internet and putting into the folder then there is no problem. Has anyone experienced something like that? What may be the cause of the problem?

```<code>def playMusic():
    ydl_opts = {
        'outtmpl': '%(id)s' + '.mp3',
        'format': 'bestaudio/best',
        'audioformat': 'mp3'
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=TKTg3Wg1keg'])
    startPlayer()

def startPlayer():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load('TKTg3Wg1keg.mp3')
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)

playMusic()
</code>```

答:
There is no audioformat key for youtube-dl. To download mp3, set up a postprocessor. Adapted from another answer:

```<code>ydl_opts = {
    'format': 'bestaudio/best',
    'outtmpl': '%(id)s.%(ext)s',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=TKTg3Wg1keg'])
</code>```

Notice that YouTube does not serve mp3s natively at the moment, so there is always some recoding necessary. It may be faster to skip the recoding to mp3 and directly play the downloaded m4a file.

ContentLicense: CC BY-SA 3.0

Body:
Hello, I'm trying to download a mp3 file via youtube-dl and then play it on my machine using PyGame. However, all the downloaded mp3 files don't work. The weird this is if I import them myself by downloading manually from the internet and putting into the folder then there is no problem. Has anyone experienced something like that? What may be the cause of the problem?

def playMusic():
    ydl_opts = {
        'outtmpl': '%(id)s' + '.mp3',
        'format': 'bestaudio/best',
        'audioformat': 'mp3'
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(['https://www.youtube.com/watch?v=TKTg3Wg1keg'])
    startPlayer()

def startPlayer():
    pygame.init()
    pygame.mixer.init()
    pygame.mixer.music.load('TKTg3Wg1keg.mp3')
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        pygame.time.Clock().tick(10)

playMusic()

Body:
There is no audioformat key for youtube-dl. To download mp3, set up a postprocessor. Adapted from another answer:

ydl_opts = {
    'format': 'bestaudio/best',
    'outtmpl': '%(id)s.%(ext)s',
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=TKTg3Wg1keg'])

Notice that YouTube does not serve mp3s natively at the moment, so there is always some recoding necessary. It may be faster to skip the recoding to mp3 and directly play the downloaded m4a file.

OwnerDisplayName: anon


问:
use variable from other function in same class codeigniter
i'm newbie codeigniter programmer.

i want to use function and all variable from this function to another function in same class controller. this my code

```<code>function page()
{

    $page_id = $this->uri->segment(3);
    $page_details = $this->m_module->submenu($page_id)->row_array();
    $data['title']= $page_details['sub_title'];
    $data['menu'] = $page_details['title'];
    $data['submenu'] = $page_details['sub_title'];
    $data['link'] = $page_details['sub_target'];
    $data['page_id'] = $page_id;
}

function employee()
    {
        $data['employee']= $this->m_module->employee()->result_array();
        $this->page();
        $this->template->display($data['link'],$data);
    }
</code>```

the problem is variable function page() can't call in function employee().

this i get at browser

```<code>A PHP Error was encountered

Severity: Notice

Message: Undefined index: link

Filename: controllers/Module.php

Line Number: 39
</code>```

please help.

Thank you

答:
Update your method like the following

```<code>private function page() {
$page_id = $this->uri->segment(3);
$page_details = $this->m_module->submenu($page_id)->row_array();

return [
    'title' => $page_details['sub_title'];
    'menu' => $page_details['title'];
    'submenu' => $page_details['sub_title'];
    'link'=> $page_details['sub_target'];
    'page_id' => $page_id;
];
</code>```

}

```<code>private function employee() {
  $data = $this->page();
  $data['employee']= $this->m_module->employee()->result_array();
 $this->template->display($data['link'],$data);
}
</code>```

The reason you were not getting was because your method was not returning as value.

Body:
i'm newbie codeigniter programmer.

i want to use function and all variable from this function to another function in same class controller. this my code

function page()
{

    $page_id = $this->uri->segment(3);
    $page_details = $this->m_module->submenu($page_id)->row_array();
    $data['title']= $page_details['sub_title'];
    $data['menu'] = $page_details['title'];
    $data['submenu'] = $page_details['sub_title'];
    $data['link'] = $page_details['sub_target'];
    $data['page_id'] = $page_id;
}

function employee()
    {
        $data['employee']= $this->m_module->employee()->result_array();
        $this->page();
        $this->template->display($data['link'],$data);
    }

the problem is variable function page() can't call in function employee().

this i get at browser

A PHP Error was encountered

Severity: Notice

Message: Undefined index: link

Filename: controllers/Module.php

Line Number: 39

please help.

Thank you

Body:
Update your method like the following

private function page() {
$page_id = $this->uri->segment(3);
$page_details = $this->m_module->submenu($page_id)->row_array();

return [
    'title' => $page_details['sub_title'];
    'menu' => $page_details['title'];
    'submenu' => $page_details['sub_title'];
    'link'=> $page_details['sub_target'];
    'page_id' => $page_id;
];

}

private function employee() {
  $data = $this->page();
  $data['employee']= $this->m_module->employee()->result_array();
 $this->template->display($data['link'],$data);
}

The reason you were not getting was because your method was not returning as value.


问:
AWS Fargate - pulling from a private repo
When searching for this it yields how to do this using ECS. This requires either putting a config file in a particular directory or setting env variables, neither of which are possible when using Fargate as it's serverless.

I feel as if I'm missing something here, anyone have any ideas?

Thanks!

答:
update As of 2018 This answer is no longer valid; You can now use private registries. see https://stackoverflow.com/a/52267257

I found
 http://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definitions

The Fargate launch type only supports images in Amazon ECR or public repositories in Docker Hub.

Which seems to imply it's currently not supported.

The easiest workaround would be to upload a copy of the image to ECR.

ContentLicense: CC BY-SA 4.0


问:
Right way to get element of array in PHP
Here is the sample of the array data pushing to my webhook

I'm not great with PHP and know I'm calling the returned emails incorrectly, how can I grab the email address from that child array? I guess maybe could be more than 1 email for the array parent but I guess for now fine just grabbing the email result if exists.

PHP:

```<code>//Get and decode JSON
$str = file_get_contents("php://input");
$json = json_decode($str, true);
// debugging
print_r($json);

$tracking_number = $json['msg']['tracking_number'];
$tracking_status = $json['msg']['tag'];
$tracking_email = $json['msg']['emails'];
$customer_name = $json['msg']['customer_name'];

$userarr = Array(
  Array(
    'tracking_number'=>$tracking_number,
    'tracking_status'=>$tracking_status,
    'tracking_email'=>$tracking_email,
    'customer_name'=>$customer_name
  )
);

// debugging
print_r($userarr);

//Update to the latest shipment status
//update_post_meta( $shiporderid, '_shipment_status', $shipmentstatus );
//Check if shipping status =  InTransit, set order status to complete
//if($shipmentstatus == 'InTransit'):
//  $order = wc_get_order( $shiporderid );
//  $order->update_status( 'completed' );
//endif;

$m = new MailSender;
$m->sendMail($userarr, 'StatusUpdate');
</code>```

ARRAY RETURNED:

```<code>{
    "event": "tracking_update",
    "msg": {
        "id": "5a288fdea631d07e0b0e410d",
        "tracking_number": "EK329287025GB",
        "title": "EK329287025GB",
        "origin_country_iso3": "GBR",
        "destination_country_iso3": null,
        "shipment_package_count": 1,
        "active": false,
        "order_id": null,
        "order_id_path": null,
        "customer_name": "James Brandon",
        "source": "web",
        "emails": [
            "james@domain.co.uk"
        ],
        "smses": [],
        "custom_fields": {},
        "tag": "Delivered",
        "tracked_count": 1,
        "expected_delivery": null,
        "signed_by": null,
        "shipment_type": null,
        "created_at": "2017-12-07T00:48:30+00:00",
        "updated_at": "2017-12-07T00:48:37+00:00",
        "slug": "parcel-force",
        "unique_token": "r_30v1xzI-G",
        "path": "r_30v1xzI-G",
        "shipment_weight": null,
        "shipment_weight_unit": null,
        "content_type": "json",
        "delivery_time": 5,
        "checkpoints": [
            {
                "location": "Gatwick Depot",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "On route to hub",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T17:26:00",
                "slug": "parcel-force"
            },
            {
                "location": "International Hub",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Sorted for export",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T23:13:00",
                "slug": "parcel-force"
            },
            {
                "location": "International Hub",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Exported from the UK",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T23:18:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-29T02:46:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T06:07:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Prepared for delivery",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T06:17:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Addressee to collect from depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T09:23:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Delivery attempted - premises closed",
                "coordinates": [],
                "tag": "AttemptFail",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T16:03:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Held in depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T21:11:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Held in depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T05:20:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T06:06:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Prepared for delivery",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T08:48:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Addressee advised to collect from Parcelshop",
                "coordinates": [],
                "tag": "AttemptFail",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T11:41:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Delivered",
                "coordinates": [],
                "tag": "Delivered",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T19:27:00",
                "slug": "parcel-force"
            }
        ],
        "tracking_account_number": null,
        "tracking_destination_country": null,
        "tracking_key": null,
        "tracking_postal_code": null,
        "tracking_ship_date": null
    },
    "ts": 1512607722
}
</code>```

答:
You simply need to step into each key inside the $userarr object. Note that james@ is the first element inside emails, which is an array in itself, so the final step requires either [0] to access the first index, or a loop over the emails key.

To do this, you can use either the square bracket notation:

```<code>$userarr["event"]["msg"]["emails"][0] // james@domain.co.uk
</code>```

Or the arrow notation:

```<code>$userarr->event->msg->emails[0] // james@domain.co.uk
</code>```

Hope this helps! :)

Body:
Here is the sample of the array data pushing to my webhook

I'm not great with PHP and know I'm calling the returned emails incorrectly, how can I grab the email address from that child array? I guess maybe could be more than 1 email for the array parent but I guess for now fine just grabbing the email result if exists.

PHP:

//Get and decode JSON
$str = file_get_contents("php://input");
$json = json_decode($str, true);
// debugging
print_r($json);

$tracking_number = $json['msg']['tracking_number'];
$tracking_status = $json['msg']['tag'];
$tracking_email = $json['msg']['emails'];
$customer_name = $json['msg']['customer_name'];

$userarr = Array(
  Array(
    'tracking_number'=>$tracking_number,
    'tracking_status'=>$tracking_status,
    'tracking_email'=>$tracking_email,
    'customer_name'=>$customer_name
  )
);

// debugging
print_r($userarr);

//Update to the latest shipment status
//update_post_meta( $shiporderid, '_shipment_status', $shipmentstatus );
//Check if shipping status =  InTransit, set order status to complete
//if($shipmentstatus == 'InTransit'):
//  $order = wc_get_order( $shiporderid );
//  $order->update_status( 'completed' );
//endif;

$m = new MailSender;
$m->sendMail($userarr, 'StatusUpdate');

ARRAY RETURNED:

{
    "event": "tracking_update",
    "msg": {
        "id": "5a288fdea631d07e0b0e410d",
        "tracking_number": "EK329287025GB",
        "title": "EK329287025GB",
        "origin_country_iso3": "GBR",
        "destination_country_iso3": null,
        "shipment_package_count": 1,
        "active": false,
        "order_id": null,
        "order_id_path": null,
        "customer_name": "James Brandon",
        "source": "web",
        "emails": [
            "james@domain.co.uk"
        ],
        "smses": [],
        "custom_fields": {},
        "tag": "Delivered",
        "tracked_count": 1,
        "expected_delivery": null,
        "signed_by": null,
        "shipment_type": null,
        "created_at": "2017-12-07T00:48:30+00:00",
        "updated_at": "2017-12-07T00:48:37+00:00",
        "slug": "parcel-force",
        "unique_token": "r_30v1xzI-G",
        "path": "r_30v1xzI-G",
        "shipment_weight": null,
        "shipment_weight_unit": null,
        "content_type": "json",
        "delivery_time": 5,
        "checkpoints": [
            {
                "location": "Gatwick Depot",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "On route to hub",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T17:26:00",
                "slug": "parcel-force"
            },
            {
                "location": "International Hub",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Sorted for export",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T23:13:00",
                "slug": "parcel-force"
            },
            {
                "location": "International Hub",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Exported from the UK",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-27T23:18:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-29T02:46:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T06:07:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Prepared for delivery",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T06:17:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Addressee to collect from depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T09:23:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Delivery attempted - premises closed",
                "coordinates": [],
                "tag": "AttemptFail",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T16:03:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Held in depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-11-30T21:11:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Held in depot",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T05:20:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Tracked in destination country",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T06:06:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Prepared for delivery",
                "coordinates": [],
                "tag": "InTransit",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T08:48:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Addressee advised to collect from Parcelshop",
                "coordinates": [],
                "tag": "AttemptFail",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T11:41:00",
                "slug": "parcel-force"
            },
            {
                "location": "Delivery Agent - NETHERLANDS",
                "country_name": null,
                "country_iso3": null,
                "state": null,
                "city": null,
                "zip": null,
                "message": "Delivered",
                "coordinates": [],
                "tag": "Delivered",
                "created_at": "2017-12-07T00:48:37+00:00",
                "checkpoint_time": "2017-12-01T19:27:00",
                "slug": "parcel-force"
            }
        ],
        "tracking_account_number": null,
        "tracking_destination_country": null,
        "tracking_key": null,
        "tracking_postal_code": null,
        "tracking_ship_date": null
    },
    "ts": 1512607722
}

Body:
You simply need to step into each key inside the $userarr object. Note that james@ is the first element inside emails, which is an array in itself, so the final step requires either [0] to access the first index, or a loop over the emails key.

To do this, you can use either the square bracket notation:

$userarr["event"]["msg"]["emails"][0] // james@domain.co.uk

Or the arrow notation:

$userarr->event->msg->emails[0] // james@domain.co.uk

Hope this helps! :)


问:
IPHONE UIIMAGEVIEW can't release?
guys.i'm new to iphone.
i encounter a problem.the uiimageview can't release...here is the code.

```<code>    #import <UIKit/UIKit.h>
@interface imageNavView : UIImageView {

    int index;
}
@property int index;

@end
#import "imageNavView.h"

    @implementation imageNavView
    @synthesize index;
    - (id)initWithFrame:(CGRect)frameRect{
        self = [super initWithFrame:frameRect];
        if (self) {
            // Custom initialization.
            self.userInteractionEnabled=YES;
            self.multipleTouchEnabled=YES;
            self.opaque=YES;
            self.autoresizingMask=(UIViewAutoresizingFlexibleHeight|
                                   UIViewAutoresizingFlexibleWidth|
                                   UIViewAutoresizingFlexibleRightMargin
                                   |UIViewAutoresizingFlexibleLeftMargin
                                   |UIViewAutoresizingFlexibleTopMargin
                                   |UIViewAutoresizingFlexibleBottomMargin);
            index=0;
        }
        return self;
    }

    - (void)dealloc {
        NSLog(@"before image dealloc %i",[self retainCount]);-------- log is 1
            [super dealloc];
        NSLog(@"after image dealloc %i",[self retainCount]);-------- log is 1,why itn't bad access?
    }

    @end
</code>```

why does the second log NSLog(@"after image dealloc %i",[self retainCount]); is 1,not a bad access,so the imageview is not released.
i can't understand,any possible way can make this happen?...any advice will be gratefull.thanks in advance!

答:
dealloc is a call-back method while system releases an object.

The following description is a api doc of dealloc,

Instead, an object’s dealloc method is invoked indirectly through the release NSObject protocol method (if the release message results in the receiver's retain count becoming 0).

ContentLicense: CC BY-SA 2.5

Title: IPHONE UIIMAGEVIEW can't release?

Body:
guys.i'm new to iphone.
i encounter a problem.the uiimageview can't release...here is the code.

    #import <UIKit/UIKit.h>
@interface imageNavView : UIImageView {

    int index;
}
@property int index;

@end
#import "imageNavView.h"

    @implementation imageNavView
    @synthesize index;
    - (id)initWithFrame:(CGRect)frameRect{
        self = [super initWithFrame:frameRect];
        if (self) {
            // Custom initialization.
            self.userInteractionEnabled=YES;
            self.multipleTouchEnabled=YES;
            self.opaque=YES;
            self.autoresizingMask=(UIViewAutoresizingFlexibleHeight|
                                   UIViewAutoresizingFlexibleWidth|
                                   UIViewAutoresizingFlexibleRightMargin
                                   |UIViewAutoresizingFlexibleLeftMargin
                                   |UIViewAutoresizingFlexibleTopMargin
                                   |UIViewAutoresizingFlexibleBottomMargin);
            index=0;
        }
        return self;
    }

    - (void)dealloc {
        NSLog(@"before image dealloc %i",[self retainCount]);-------- log is 1
            [super dealloc];
        NSLog(@"after image dealloc %i",[self retainCount]);-------- log is 1,why itn't bad access?
    }

    @end

why does the second log NSLog(@"after image dealloc %i",[self retainCount]); is 1,not a bad access,so the imageview is not released.
i can't understand,any possible way can make this happen?...any advice will be gratefull.thanks in advance!


问:
How to use ternary operator?
How does this return statement works?</p>

```<code>return [weekend, !weekend ? 'myweekend' : ''];
</code>```

答: If weekend is false/falsy it will return [weekend, 'myweekend'] otherwise [weekend, '']

Title: How to use ternary operator?

Body:
How does this return statement works?

return [weekend, !weekend ? 'myweekend' : ''];


问:
Bash Shell Scripting: How to Sum the Values in a File With the Use of For Loop and bc Command
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

```<code>12
4
53
19
6
</code>```

So here's what I have so far:

```<code>function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}
</code>```

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

答:
You can do it easily without the need of a for loop.</p>

```<code>paste -s -d+ numbers.txt | bc
</code>```

Body:
I'm currently trying to write a function in my bash script that does the following: Take in a file as an argument and calculate the sum of the numbers within that file. I must make use of a for loop and the bc command.

Example of values in the file (each value on their own line):

12
4
53
19
6

So here's what I have so far:

function sum_values() {
  for line in $1; do
  #not sure how to sum the values using bc
  done
}

Am I on the right track? I'm not sure how to implement the bc command  in this situation.

Body:
You can do it easily without the need of a for loop.

paste -s -d+ numbers.txt | bc


问:
Arithmetic operations evaluation in GWT
Is there any library / module for simple arithmetic operations evaluation for GWT?

For example, some method which could transform string "14 + (28 * 10)" to 294?

I know, that there's arity for Java. I need something more lightweight which would work in GWT.

答:
Javascript's eval should be adequate. Using JSNI from your Java code:</p>

```<code>public void test() {
    double result = calculate("14 + (28 * 10)");
}

public final native double calculate(String op) /*-{
    return eval(op);
}-*/;
</code>```

Title: Arithmetic operations evaluation in GWT

Body:
Javascript's eval should be adequate. Using JSNI from your Java code:

public void test() {
    double result = calculate("14 + (28 * 10)");
}

public final native double calculate(String op) /*-{
    return eval(op);
}-*/;


问:
getenv() returning environment as null?
I am trying to print the executables in the current directory in c and bash with the following code:

```<code>system("EXEC_PATH=$(find . -maxdepth 1 -type f -executable)");
printf("executables are: %s\n", getenv("EXEC_PATH"));
</code>```

However, when I compile and run the c code, the result I get is:

```<code>executables are: (null)
</code>```

Any help will be appreciated!

答:
system() is creating a new shell and setting the environment in there and then throwing it away when that shell exits.

getenv() is using the environment of the "current" process.

Try getting the result of the system call and using putenv to modify the current environment.

Title: getenv() returning environment as null?

Body:
I am trying to print the executables in the current directory in c and bash with the following code:

system("EXEC_PATH=$(find . -maxdepth 1 -type f -executable)");
printf("executables are: %s\n", getenv("EXEC_PATH"));

However, when I compile and run the c code, the result I get is:

executables are: (null)

Any help will be appreciated!


问:
iOS11 keyboard issue - incorrect keyboard height
The keyboard shifts a little bit up sometimes, as shown in picture here

Firstly, this issue happens only on iOS11 but not on earlier iOS versions.
Secondly, this issue happens with every UITextField instance across the app not only in one specific text field within a specific view controller.

By observing UIKeyboardWillShowNotification, found that the frame of keyboard stored in UIKeyboardFrameEndUserInfoKey is incorrect, to be exact, the height is wrong.

```<code>- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSString *curveValue = [info objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    CGRect rect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"keyboard frame: %@", NSStringFromCGRect(rect));
}
</code>```

We got logs like this when running on iPhone7 (11.1):

```<code>keyboard frame {{0, 451}, {375, 216}}
keyboard frame {{0, 292}, {375, 375}}
keyboard frame {{0, 451}, {375, 216}}
keyboard frame {{0, 292}, {375, 375}}
keyboard frame {{0, 292}, {375, 375}}
</code>```

216 should be the correct height, while 375 is wrong. It is weird that the height of the keyboard happens to be equal to the width of the screen.

Based on the facts i got, i think it is an IOS 11 keyboard issue, because it happens only on iOS 11, and the height of the keyboard is definitely controlled by iOS, however it returns a wrong height for some reason.

However, the tricky thing is that, i extracted a specific view controller containing a textfield from our app and created a separate demo project, everything works fine then. And i didn't found similar issues happened to others by Googling. So i doubt it maybe because of some settings in our app, which causes this iOS11 keyboard height issue.

Have you guys experienced this kind of weird issues before? Or is there anything you guys can think of which maybe the culprit? I have run out of my thoughts on this. Thanks!

答:
Got it sorted. Finally found it is because a UIView category we use in our project.

```<code>- (void)setWidth:(CGFloat)width;
- (void)setHeight:(CGFloat)height;
- (void)setSize:(CGFloat)size;
- (void)setXPos:(CGFloat)xPos;
- (void)setYPos:(CGFloat)yPos;
- (void)setXPos:(CGFloat)xPos yPos:(CGFloat)yPos;
</code>```

From iOS11 somehow these methods become reserved methods and overriding these methods will cause this annoying issue.

Body:
The keyboard shifts a little bit up sometimes, as shown in picture here

Firstly, this issue happens only on iOS11 but not on earlier iOS versions.
Secondly, this issue happens with every UITextField instance across the app not only in one specific text field within a specific view controller.

By observing UIKeyboardWillShowNotification, found that the frame of keyboard stored in UIKeyboardFrameEndUserInfoKey is incorrect, to be exact, the height is wrong.

- (void)keyboardWillShow:(NSNotification *)notification {
    NSDictionary *info = [notification userInfo];
    NSString *curveValue = [info objectForKey:UIKeyboardAnimationCurveUserInfoKey];
    CGRect rect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"keyboard frame: %@", NSStringFromCGRect(rect));
}

We got logs like this when running on iPhone7 (11.1):

keyboard frame {{0, 451}, {375, 216}}
keyboard frame {{0, 292}, {375, 375}}
keyboard frame {{0, 451}, {375, 216}}
keyboard frame {{0, 292}, {375, 375}}
keyboard frame {{0, 292}, {375, 375}}

216 should be the correct height, while 375 is wrong. It is weird that the height of the keyboard happens to be equal to the width of the screen.

Based on the facts i got, i think it is an IOS 11 keyboard issue, because it happens only on iOS 11, and the height of the keyboard is definitely controlled by iOS, however it returns a wrong height for some reason.

However, the tricky thing is that, i extracted a specific view controller containing a textfield from our app and created a separate demo project, everything works fine then. And i didn't found similar issues happened to others by Googling. So i doubt it maybe because of some settings in our app, which causes this iOS11 keyboard height issue.

Have you guys experienced this kind of weird issues before? Or is there anything you guys can think of which maybe the culprit? I have run out of my thoughts on this. Thanks!

Body:
Got it sorted. Finally found it is because a UIView category we use in our project.

- (void)setWidth:(CGFloat)width;
- (void)setHeight:(CGFloat)height;
- (void)setSize:(CGFloat)size;
- (void)setXPos:(CGFloat)xPos;
- (void)setYPos:(CGFloat)yPos;
- (void)setXPos:(CGFloat)xPos yPos:(CGFloat)yPos;

From iOS11 somehow these methods become reserved methods and overriding these methods will cause this annoying issue.


问:
Advice on working with legacy code
I need some advice on how to work with legacy code.

A while ago, I was given the task to add a few reports to a reporting app. written in Struts 1, back in 2005. No big deal, but the code is quite messy. No usage of Action forms, and basically the code is one huge action, and a lot of if-else statements inside. Also, no one here has functional knowledge on this. We just happened to have it in our contract.

I'm quite unhappy about this, and not sure how to proceed. This application is invisible: Few people (but all very important) use it, so they don't care whether my eyes bleed while reading the code, standards, etc.

However, I feel that a technical debt is to be paid. How should I proceed on this? Continue down the if-else road, or try to do this requirement the right way, ignoring the rest of the project? Starting a huge refactor, risking my deadline?

答:
I agree with other comments. If you don't have to, then don't do it. It usually cost far more then it's worth if the code base is more or less dead any way.

On the other hand, if you feel that you cannot get your head around the code then a refactor is probably unavoidable. If this is the case then, since it's a web application, can you create a solid suite of functional tests using selenium? If so this is the fastest and most rewarding test approach for such code and will catch most bugs for the buck.

Second, start with the extract method refactoring to create compose methods of the big difficult methods. Every time you think to your self "This should have a comment to explain what it does" you should extract it to a method with a name that replaces the comment.

Once this has been done, if you still can't add the functionality required, you can go for more advanced refactorings, and perhaps even adding some unit tests. But I usually find that I can add what is required/fix the bug in legacy code by just creating self documenting code.

Title: Advice on working with legacy code


问:
How to Get Groups of Files from GetFiles()
I have to process files everyday.  The files are named like so:

```<code> fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy
</code>```

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

```<code>        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }
</code>```

Any help or advice would be greatly appreciated.

答:
Here is a simple class</p>

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] filenames = { "fg1a.12012017", "fg1b.12012017", "fg1c.12012017", "fg2a.12012017", "fg2b.12012017", "fg2c.12012017", "fg2d.12012017" };
            new SplitFileName(filenames);
            List<List<SplitFileName>> results = SplitFileName.GetGroups();
        }
    }
    public class SplitFileName
    {
        public static List<SplitFileName> names = new List<SplitFileName>();
        string filename { get; set; }
        string prefix { get; set; }
        string letter { get; set; }
        DateTime date { get; set; }

        public SplitFileName() { }
        public SplitFileName(string[] splitNames)
        {
            foreach(string name in splitNames)
            {
                SplitFileName splitName = new SplitFileName();
                names.Add(splitName);
                splitName.filename = name;
                string[] splitArray = name.Split(new char[] { '.' });
                splitName.date = DateTime.ParseExact(splitArray[1],"MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
                splitName.prefix = splitArray[0].Substring(0, splitArray[0].Length - 1);
                splitName.letter = splitArray[0].Substring(splitArray[0].Length - 1,1);
            }
        }
        public static List<List<SplitFileName>> GetGroups()
        {
            return names.OrderBy(x => x.letter).GroupBy(x => new { date = x.date, prefix = x.prefix })
                .Where(x => string.Join(",",x.Select(y => y.letter)) == "a,b,c,d")
                .Select(x => x.ToList())
                .ToList();
        }

    }
}
</code>```

Body:
I have to process files everyday.  The files are named like so:

 fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }

Any help or advice would be greatly appreciated.

Body:
Here is a simple class

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] filenames = { "fg1a.12012017", "fg1b.12012017", "fg1c.12012017", "fg2a.12012017", "fg2b.12012017", "fg2c.12012017", "fg2d.12012017" };
            new SplitFileName(filenames);
            List<List<SplitFileName>> results = SplitFileName.GetGroups();
        }
    }
    public class SplitFileName
    {
        public static List<SplitFileName> names = new List<SplitFileName>();
        string filename { get; set; }
        string prefix { get; set; }
        string letter { get; set; }
        DateTime date { get; set; }

        public SplitFileName() { }
        public SplitFileName(string[] splitNames)
        {
            foreach(string name in splitNames)
            {
                SplitFileName splitName = new SplitFileName();
                names.Add(splitName);
                splitName.filename = name;
                string[] splitArray = name.Split(new char[] { '.' });
                splitName.date = DateTime.ParseExact(splitArray[1],"MMddyyyy", System.Globalization.CultureInfo.InvariantCulture);
                splitName.prefix = splitArray[0].Substring(0, splitArray[0].Length - 1);
                splitName.letter = splitArray[0].Substring(splitArray[0].Length - 1,1);
            }
        }
        public static List<List<SplitFileName>> GetGroups()
        {
            return names.OrderBy(x => x.letter).GroupBy(x => new { date = x.date, prefix = x.prefix })
                .Where(x => string.Join(",",x.Select(y => y.letter)) == "a,b,c,d")
                .Select(x => x.ToList())
                .ToList();
        }

    }
}


问:
Gap above a navbar in mobile view with viewport
I started diving into html/css this evening and stumbled upon a roadblock. I am trying to make a navbar for my GitHub page and it displays just fine on desktop view. The navbar is to be fixed on desktop view, however on mobile view I want to keep in on the top of the page.

This is how it displays when width is less than 600px.
<img src="https://i.stack.imgur.com/gv9A6.png

I want to remove the gap above the navbar but can't figure out how.

html, body {
    height: 100%; margin: 0; padding: 0; padding-top: 40px;
}

body {
    font-family: sans-serif;
    background: #daf2ea
}

a {
    text-decoration: none;
}

.navbar {
    height: 40px;
    background: #333;
    color: #eee;
    padding-top: 7px;
    padding-bottom: 7px;
    box-shadow: 0 0 5px #777;
    position: fixed;
    top: 0;
    width: 100%;
}

.navbar h1 {
    font-weight: 300;
    font-size: 26px;
    margin-top: 4px;
    margin-left: 20px;
    padding-top: 0;
    text-shadow: 0 1px 2px #000;
    float: left;
}

.navbar a {color:white;}

.navbar a:hover {text-decoration: underline;}

.navbar ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

.navbar li {float: left;}

.navbar li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

@media screen and (max-width: 600px) {
    .navbar {
        position: static;
        top: auto;
        width: auto;
        padding-bottom: 14px;
    }

    .navbar h1 {
        float: none;
        text-align: center;
        margin-left: 0px;
    }

    .navbar li {float: none;}

    .navbar li a:hover {
        background-color: #1384c1;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Lukasz Salitra - Home</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
  </head>
  <body>
      <div class="navbar">
          <h1>Lukasz Salitra</h1>
          <ul>
              <li>
                  Home
              </li>
              <li>
                  About
              </li>
              <li>
                  Contact
              </li>
          </ul>
      </div>
  </body>
<html></code>```

答:
Just remove padding-top: 40px; line from html selector.

```<code>html, body {
    height: 100%; margin: 0; padding: 0;
}
</code>```

Body:
I started diving into html/css this evening and stumbled upon a roadblock. I am trying to make a navbar for my GitHub page and it displays just fine on desktop view. The navbar is to be fixed on desktop view, however on mobile view I want to keep in on the top of the page.

This is how it displays when width is less than 600px.
<a href="https://i.stack.imgur.com/gv9A6.png
<img src="https://i.stack.imgur.com/gv9A6.png

I want to remove the gap above the navbar but can't figure out how.

html, body {
    height: 100%; margin: 0; padding: 0; padding-top: 40px;
}

body {
    font-family: sans-serif;
    background: #daf2ea
}

a {
    text-decoration: none;
}

.navbar {
    height: 40px;
    background: #333;
    color: #eee;
    padding-top: 7px;
    padding-bottom: 7px;
    box-shadow: 0 0 5px #777;
    position: fixed;
    top: 0;
    width: 100%;
}

.navbar h1 {
    font-weight: 300;
    font-size: 26px;
    margin-top: 4px;
    margin-left: 20px;
    padding-top: 0;
    text-shadow: 0 1px 2px #000;
    float: left;
}

.navbar a {color:white;}

.navbar a:hover {text-decoration: underline;}

.navbar ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

.navbar li {float: left;}

.navbar li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

@media screen and (max-width: 600px) {
    .navbar {
        position: static;
        top: auto;
        width: auto;
        padding-bottom: 14px;
    }

    .navbar h1 {
        float: none;
        text-align: center;
        margin-left: 0px;
    }

    .navbar li {float: none;}

    .navbar li a:hover {
        background-color: #1384c1;
    }
}

<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Lukasz Salitra - Home</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

Lukasz Salitra

                  Home

                  About

                  Contact

Body:
Just remove padding-top: 40px; line from html selector.

html, body {
    height: 100%; margin: 0; padding: 0;
}


问:
In Chrome V8 Engine Source, What it means for?
I have a question in following piece of code.

```<code>#define V8_DECLARE_ONCE(NAME) ::v8::base::OnceType NAME
</code>```

In cpp file, '::' means for referencing namespace, but where '::v8' included?

```<code>std::cout << ... << std::endl;
</code>```

cout is under the 'std' namespace,,, but, in this case, i have no idea how to interpret it.

part of this code is following one.

```<code> namespace v8 {
 namespace base {

 typedef AtomicWord OnceType;

 #define V8_ONCE_INIT 0

 #define V8_DECLARE_ONCE(NAME) ::v8::base::OnceType NAME
</code>```

答:
::ns means to look in the root namespace for ns. It's to avoid possible namespace collisions, since it avoids looking in the current namespace, if you define your own namespace and it has the same name. Here's an example that demonstrates the difference.

```<code>#include <iostream>

namespace v8 {

constexpr int val = 5;

} // namespace v8

namespace my {
namespace v8 {

constexpr int val = 10;

} // namespace my::v8

void some_func()
{
  std::cout << ::v8::val << ", " << v8::val << '\n';
}

} // namespace my

int main()
{
  my::some_func();
}
</code>```

prints 5, 10.

Body:
I have a question in following piece of code.

#define V8_DECLARE_ONCE(NAME) ::v8::base::OnceType NAME

In cpp file, '::' means for referencing namespace, but where '::v8' included?

std::cout << ... << std::endl;

cout is under the 'std' namespace,,, but, in this case, i have no idea how to interpret it.

part of this code is following one.

 namespace v8 {
 namespace base {

 typedef AtomicWord OnceType;

 #define V8_ONCE_INIT 0

 #define V8_DECLARE_ONCE(NAME) ::v8::base::OnceType NAME

Body:
::ns means to look in the root namespace for ns. It's to avoid possible namespace collisions, since it avoids looking in the current namespace, if you define your own namespace and it has the same name. Here's an example that demonstrates the difference.

#include <iostream>

namespace v8 {

constexpr int val = 5;

} // namespace v8

namespace my {
namespace v8 {

constexpr int val = 10;

} // namespace my::v8

void some_func()
{
  std::cout << ::v8::val << ", " << v8::val << '\n';
}

} // namespace my

int main()
{
  my::some_func();
}

prints 5, 10.


问:
laravel 5 : Class 'input' not found
In my routes.php file I have :

```<code>Route::get('/', function () {

    return view('login');
});

Route::get('/index', function(){
    return view('index');
});

Route::get('/register', function(){
    return view('register');
});
Route::post('/register',function(){

    $user = new \App\User;
    $user->username = input::get('username');
    $user->email  = input::get('email');
    $user->password = Hash::make(input::get('username'));
    $user->designation = input::get('designation');
    $user->save();

});
</code>```

I have a form for users registration. I am also taking the form inputs value in the routes.php.

But the error comes up when I register a user .
Error:

```<code>FatalErrorException in routes.php line 61:
Class 'input' not found
</code>```

答: Miscall of Class it should be Input not input

Title: laravel 5 : Class 'input' not found

Body:
In my routes.php file I have :

Route::get('/', function () {

    return view('login');
});

Route::get('/index', function(){
    return view('index');
});

Route::get('/register', function(){
    return view('register');
});
Route::post('/register',function(){

    $user = new \App\User;
    $user->username = input::get('username');
    $user->email  = input::get('email');
    $user->password = Hash::make(input::get('username'));
    $user->designation = input::get('designation');
    $user->save();

});

I have a form for users registration. I am also taking the form inputs value in the routes.php.

But the error comes up when I register a user .
Error:

FatalErrorException in routes.php line 61:
Class 'input' not found


问:
How can I extract the week number from java.util.Date in scala
I already tried to use:
getWeek
getCalendarDate
and I don't want to use Calendar package (because I am using a specific software that don't allow me to use it)
Thanks in advance,</p>

答:
tl;dr

```<code>org.threeten.extra.YearWeek.from(
    myJavaUtilDate.toInstant()
                  .atZone( ZoneId.of( "Pacific/Auckland" )  )
).getWeek()
</code>```

49

YearWeek

The Answer by Ole V.V. is correct and wise.

(Java syntax here; do not know Scala)

If doing much work with weeks, and your definition of week agrees with the ISO 8601 definition of week where week # 1 contains the first Thursday and where Monday is the first day-of-week, then consider adding the ThreeTen-Extra library to your project. That library includes many classes extending the functionality of the java.time classes. In particular is a YearWeek class.

First convert the awful troubled java.util.Date object to java.time.

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

```<code>Instant instant = myJavaUtilDate.toInstant();
</code>```

Assign the time zone through which you want to perceive a date. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

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

Generate the YearWeek object to represent that moment’s year-week in the ISO 8601 week date system, the combination of a week-based-year and week-of-week-based-year.

```<code>YearWeek yw = YearWeek.from( zdt ) ;
</code>```

If you want to represent that value with a standard ISO 8601 format, simply call YearWeek::toString.

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

2017-W49

If you want to represent that value with the week number as an integer, call YearWeek::getWeek.

```<code>int weekNumber = yw.getWeek() ;
</code>```

49

Avoid legacy date-time classes

By the way, you should indeed be avoiding the Calendar class, as well as Date, SimpleDateFormat, and the java.sql classes. All those troublesome old date-time classes are now legacy, entirely supplanted by the java.time classes.

About java.time

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

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

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

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

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

Android

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

See How to use ThreeTenABP….

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

Body:
tl;dr

org.threeten.extra.YearWeek.from(
    myJavaUtilDate.toInstant()
                  .atZone( ZoneId.of( "Pacific/Auckland" )  )
).getWeek()

49

YearWeek

The Answer by Ole V.V. is correct and wise.

(Java syntax here; do not know Scala)

If doing much work with weeks, and your definition of week agrees with the ISO 8601 definition of week where week # 1 contains the first Thursday and where Monday is the first day-of-week, then consider adding the ThreeTen-Extra library to your project. That library includes many classes extending the functionality of the java.time classes. In particular is a YearWeek class.

First convert the awful troubled java.util.Date object to java.time.

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

Instant instant = myJavaUtilDate.toInstant();

Assign the time zone through which you want to perceive a date. A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

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

Generate the YearWeek object to represent that moment’s year-week in the ISO 8601 week date system, the combination of a week-based-year and week-of-week-based-year.

YearWeek yw = YearWeek.from( zdt ) ;

If you want to represent that value with a standard ISO 8601 format, simply call YearWeek::toString.

String output = yw.toString() ;

2017-W49

If you want to represent that value with the week number as an integer, call YearWeek::getWeek.

int weekNumber = yw.getWeek() ;

49

Avoid legacy date-time classes

By the way, you should indeed be avoiding the Calendar class, as well as Date, SimpleDateFormat, and the java.sql classes. All those troublesome old date-time classes are now legacy, entirely supplanted by the java.time classes.

About java.time

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

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

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

Where to obtain the java.time classes?

Java SE 8, Java SE 9, and later

Built-in.

Part of the standard Java API with a bundled implementation.

Java 9 adds some minor features and fixes.

Java SE 6 and Java SE 7

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

Android

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

See How to use ThreeTenABP….

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


问:
Tesseract - Recognizing text problems
I am having problems recognizing text with Tesseract and need some help.

The first is a input that is very fuzzy that does not get recognized:

The second is a input that gives a broken result:

Which returns this broken result:

"I CRANKSHAFT FORCES Each time combustion occurs, the for rce deﬂects the crankshaft as it transfers torque to the ou put shaft. This deﬂection occursm ' twow ways, to be edn the shaft sidew ways sand to twist the shaft in torsi SlOn Thec an-k mum. ran ankshaft deﬂections are edirectly related to oper- ating roughness of an einng .When back- and—f forth"

I call the windows exe using this PHP commandline which could perhaps be modified to give better results:

```<code>$exe = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe';
$image = 'Book.png';
$output = 'Out';
$language = ''; // '-l deu' = German etc

$img = 'Images/' . $image;

exec("\"$exe\" \"$img\" \"$output\" {$language} ");
</code>```

How can i return the correct results for both images?

答:
Using ImageMagick and morphology close and open one can improve the first image.

```<code>convert jrxjek.png -morphology close diamond:1 -morphology open diamond:1 jrxjek_close_open.png
</code>```

Using one of my bash unix shell scripts with ImageMagick, one can automatically detect the rotation in a text image and deskew/derotate it.

```<code>textdeskew crankshaft.png crankshaft_textdeskew.png
</code>```

See my scripts at http://www.fmwconcepts.com/imagemagick/index.html

Title: Tesseract - Recognizing text problems

Body:
I am having problems recognizing text with Tesseract and need some help.

The first is a input that is very fuzzy that does not get recognized:

The second is a input that gives a broken result:

Which returns this broken result:

"I CRANKSHAFT FORCES Each time combustion occurs, the for rce deﬂects the crankshaft as it transfers torque to the ou put shaft. This deﬂection occursm ' twow ways, to be edn the shaft sidew ways sand to twist the shaft in torsi SlOn Thec an-k mum. ran ankshaft deﬂections are edirectly related to oper- ating roughness of an einng .When back- and—f forth"

I call the windows exe using this PHP commandline which could perhaps be modified to give better results:

$exe = 'C:/Program Files (x86)/Tesseract-OCR/tesseract.exe';
$image = 'Book.png';
$output = 'Out';
$language = ''; // '-l deu' = German etc

$img = 'Images/' . $image;

exec("\"$exe\" \"$img\" \"$output\" {$language} ");

How can i return the correct results for both images?

Body:
Using ImageMagick and morphology close and open one can improve the first image.

convert jrxjek.png -morphology close diamond:1 -morphology open diamond:1 jrxjek_close_open.png

Using one of my bash unix shell scripts with ImageMagick, one can automatically detect the rotation in a text image and deskew/derotate it.

textdeskew crankshaft.png crankshaft_textdeskew.png

See my scripts at http://www.fmwconcepts.com/imagemagick/index.html


问:
R assigning names to lists in matrix
I'm iterating a function through each parameter value of Lx for each value of Ly. The function produces a list and then the lists are put into a matrix. I'm trying to give names to the resultant lists so that I know what combination of parameters (Lx and Ly) was used for each run of the function. See reproducible example below:

```<code>test_sim <- function(Lx, Ly){
  results=list()
  ret <- runif(3, min=0, max=100)
  results[[1]]=ret
  names(results)[1]=paste(Lx,Ly,sep = "_")
  return(results)
}
Lx <- seq(0.25,0.5,0.25)
Ly <- seq(0.05, 0.10, 0.05)
blam <- sapply(Lx, function(x) mapply(test_sim, x, Ly))
</code>```

However, that appears to only name the first two rows of the matrix. How can I name each list appropriately?

Title: R assigning names to lists in matrix

Body:
I'm iterating a function through each parameter value of Lx for each value of Ly. The function produces a list and then the lists are put into a matrix. I'm trying to give names to the resultant lists so that I know what combination of parameters (Lx and Ly) was used for each run of the function. See reproducible example below:

test_sim <- function(Lx, Ly){
  results=list()
  ret <- runif(3, min=0, max=100)
  results[[1]]=ret
  names(results)[1]=paste(Lx,Ly,sep = "_")
  return(results)
}
Lx <- seq(0.25,0.5,0.25)
Ly <- seq(0.05, 0.10, 0.05)
blam <- sapply(Lx, function(x) mapply(test_sim, x, Ly))

However, that appears to only name the first two rows of the matrix. How can I name each list appropriately?

Body:
You can use lapply instead of sapply.

This will produce a nested list:

# This produces a nested list
blam <- lapply(Lx, function(x) mapply(test_sim, x, Ly))
blam;
#[[1]]
#[[1]]$`0.25_0.05`
#[1] 80.11677 60.42781 83.07715
#
#[[1]]$`0.25_0.1`
#[1] 34.98122 13.24191 64.38831
#
#
#[[2]]
#[[2]]$`0.5_0.05`
#[1] 56.466308  7.158086 66.655274
#
#[[2]]$`0.5_0.1`
#[1] 66.88615 16.05237 43.16896

You can then flatten the list using unlist(..., recursive = FALSE):

# Flatten nested list
unlist(blam, recursive = FALSE);
#$`0.25_0.05`
#[1] 80.11677 60.42781 83.07715
#
#$`0.25_0.1`
#[1] 34.98122 13.24191 64.38831
#
#$`0.5_0.05`
#[1] 56.466308  7.158086 66.655274
#
#$`0.5_0.1`
#[1] 66.88615 16.05237 43.16896


问:
Is angular.io is advance version of angularjs?
It seems angular.io is completely different in the way of coding than angularJS. Which one do I choose to learn and why?</p>

答:
angular.io is angular (without the js at the end) its also called angularjs 2 or angularjs 3,4 which adds to the confusion

Uses typescript, or ES5/ES6

Is newer

AngularJS 1.6 (https://angularjs.org/)

The original angularjs

More popular

Has more libraries and frameworks already established for it

Uses javascript

I recommend using AngularJS due to its easier learning curve and diverse collection of libraries and community.


问:
Changing java file
Can I change a java file, when I'm running it on JVM, using this file?

For example:
I run abc.java. In this program I've a textarea and I want to paste text from the text area into abc.java and save the changes. Is it possible?

答: No. Maybe what you want is dynamic define classes at runtime. If so, you could choose dynamic language like Groovy.</p>

Title: Changing java file


问:
Yii2 console app - cookieValidationKey config errors
I have configured the cookieValidationKey inside my backend\config\main.php and frontend\config\main.php and removed it from common\config\main.php. But when I run php yii inside command line. I get this error.
Even before I set it inside to my backend config the error showed up when I used the command line.

```<code>$ php yii
Exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\console\Request:
:cookieValidationKey'

in D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Component.php:201

Stack trace:
#0 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\BaseYii.php(525): yii\base\Component->__set('cook
ieValidatio...', '9H2hvsco52yQ0N2...')
#1 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Object.php(105): yii\BaseYii::configure(Obje
ct(yii\console\Request), Array)
#2 [internal function]: yii\base\Object->__construct(Array)
#3 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\Container.php(381): ReflectionClass->newInstan
ceArgs(Array)
#4 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\Container.php(156): yii\di\Container->build('y
ii\\console\\Req...', Array, Array)
#5 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\BaseYii.php(344): yii\di\Container->get('yii\\con
sole\\Req...', Array, Array)
#6 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\ServiceLocator.php(135): yii\BaseYii::createOb
ject(Array)
#7 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\console\Application.php(219): yii\di\ServiceLocat
or->get('request')
#8 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Application.php(380): yii\console\Applicatio
n->getRequest()
#9 D:\web\wamp64\www\html\royall.dev\yii(27): yii\base\Application->run()
#10 {main}
</code>```

Why is this happening? I did not have cookieValidationKey inside my console\config\main.php so it should not Popup this error.

I use windows and wamp-server but I tested it on an Ubuntu server and it's returning the same error.

答:
That's because your console command combined all configs before executing the actual action. There are some config params which are invalid to console actions but useful to web requests. The solution is to remove these params before executing console actions.

Add the following line

```<code>unset($config['components']['request']);
</code>```

before

```<code>$application = new yii\console\Application($config);
</code>```

in file yii.

Because I run web server via vagrant, I didn't test if there's side effect to web app run via yii command.

Body:
I have configured the cookieValidationKey inside my backend\config\main.php and frontend\config\main.php and removed it from common\config\main.php. But when I run php yii inside command line. I get this error.
Even before I set it inside to my backend config the error showed up when I used the command line.

$ php yii
Exception 'yii\base\UnknownPropertyException' with message 'Setting unknown property: yii\console\Request:
:cookieValidationKey'

in D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Component.php:201

Stack trace:
#0 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\BaseYii.php(525): yii\base\Component->__set('cook
ieValidatio...', '9H2hvsco52yQ0N2...')
#1 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Object.php(105): yii\BaseYii::configure(Obje
ct(yii\console\Request), Array)
#2 [internal function]: yii\base\Object->__construct(Array)
#3 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\Container.php(381): ReflectionClass->newInstan
ceArgs(Array)
#4 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\Container.php(156): yii\di\Container->build('y
ii\\console\\Req...', Array, Array)
#5 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\BaseYii.php(344): yii\di\Container->get('yii\\con
sole\\Req...', Array, Array)
#6 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\di\ServiceLocator.php(135): yii\BaseYii::createOb
ject(Array)
#7 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\console\Application.php(219): yii\di\ServiceLocat
or->get('request')
#8 D:\web\wamp64\www\html\royall.dev\vendor\yiisoft\yii2\base\Application.php(380): yii\console\Applicatio
n->getRequest()
#9 D:\web\wamp64\www\html\royall.dev\yii(27): yii\base\Application->run()
#10 {main}

Why is this happening? I did not have cookieValidationKey inside my console\config\main.php so it should not Popup this error.

I use windows and wamp-server but I tested it on an Ubuntu server and it's returning the same error.

Body:
That's because your console command combined all configs before executing the actual action. There are some config params which are invalid to console actions but useful to web requests. The solution is to remove these params before executing console actions.

Add the following line

unset($config['components']['request']);

before

$application = new yii\console\Application($config);

in file yii.

Because I run web server via vagrant, I didn't test if there's side effect to web app run via yii command.


问:
When to use 'npm start' and when to use 'ng serve'?

ng serve serves an Angular project via a development server

npm start runs an arbitrary command specified in the package's "start"
  property of its "scripts" object. If no "start" property is specified
  on the "scripts" object, it will run node server.js.

It seems like ng serve starts the embedded server whereas npm start starts the Node servers.

Can someone throw some light on it?

答:
For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

```<code>ng new app-name
</code>```

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

```<code>   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",
</code>```

In this case, 'npm start' will result in the following commands to be run:

```<code>concurrently "npm run build:watch" "npm run serve"
</code>```

This will concurrently  run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)

Body:
For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

ng new app-name

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

In this case, 'npm start' will result in the following commands to be run:

concurrently "npm run build:watch" "npm run serve"

This will concurrently  run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)


问:
Role Based Access Authorization in perfect
Being new to perfect server side swift, I cannot find any packages that help with role based access authorization. In Spring there is for example,

```<code>.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")
</code>```

Is there something already existing in perfect to help with this? Is there a recommended way of handling access control in perfect?

答:
Perfect provides system level of authentication.

Firstly, you can go to github and search PerfectlySoft/Perfect-LocalAuthentication for user identity validation, however, it doesn't contain the role control as you asked.

It can be done in other approaches. For example, you can use Perfect-LDAP to access an LDAP server for all kinds of roles and groups.

Body:
Being new to perfect server side swift, I cannot find any packages that help with role based access authorization. In Spring there is for example,

.antMatchers("/homePage").access("hasRole('ROLE_USER') or hasRole('ROLE_ADMIN')")
.antMatchers("/adminPage").access("hasRole('ROLE_ADMIN')")

Is there something already existing in perfect to help with this? Is there a recommended way of handling access control in perfect?


问:
get post excerpt in WordPress
I am trying to get this wordpress page template to display an excerpt from a specific post. When the post was created I was sure to insert the  link in the place that I want. I am able to grab the title, the thumbnail, the permalink, etc... but for whatever reason I can not get the excerpt. I have tried:

```<code>the_excerpt();
get_the_excerpt();
the_content('',FALSE);
get_the_content('', FALSE, '');
get_the_content('', TRUE);
</code>```

Among other things. When I try get_the_content('', TRUE) it gives me the content from everything AFTER the  link but I want what is BEFORE the link.

Any ideas?

```<code>   <?php
        $query = 'cat=23&posts_per_page=1';
        $queryObject = new WP_Query($query);
    ?>

    <?php if($queryObject->have_posts()) : ?>

        <div>

            <?php while($queryObject->have_posts()) : $queryObject->the_post() ?>

                <div>

                    <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>

                    <br>

                    <?php the_post_thumbnail() ?>

                    <?php #the_excerpt(); ?>

                    <div>

                        <a href="<?php the_permalink(); ?>">Read More</a>

                    </div>

                </div>

            <?php endwhile ?>

        </div>

    <?php endif; wp_reset_query();
</code>```

?>

答:
Here's a pretty neat solution that'll do the trick for you!</p>

```<code>    <div class="post">
      <h3 class="title"><?php echo $post->post_title ?></h3>
      <?
        // Making an excerpt of the blog post content
        $excerpt = strip_tags($post->post_content);
        if (strlen($excerpt) > 100) {
          $excerpt = substr($excerpt, 0, 100);
          $excerpt = substr($excerpt, 0, strrpos($excerpt, ' '));
          $excerpt .= '...';
        }
      ?>
      <p class="excerpt"><?php echo $excerpt ?></p>
      <a class="more-link" href="<?php echo get_post_permalink($post->ID); ?>">Read more</a>
    </div>
</code>```

Title: get post excerpt in WordPress

Body:
I am trying to get this wordpress page template to display an excerpt from a specific post. When the post was created I was sure to insert the  link in the place that I want. I am able to grab the title, the thumbnail, the permalink, etc... but for whatever reason I can not get the excerpt. I have tried:

the_excerpt();
get_the_excerpt();
the_content('',FALSE);
get_the_content('', FALSE, '');
get_the_content('', TRUE);

Among other things. When I try get_the_content('', TRUE) it gives me the content from everything AFTER the  link but I want what is BEFORE the link.

Any ideas?

   <?php
        $query = 'cat=23&posts_per_page=1';
        $queryObject = new WP_Query($query);
    ?>

    <?php if($queryObject->have_posts()) : ?>

            <?php while($queryObject->have_posts()) : $queryObject->the_post() ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                    <?php the_post_thumbnail() ?>

                    <?php #the_excerpt(); ?>

                        <a href="<?php the_permalink(); ?>">Read More

            <?php endwhile ?>

    <?php endif; wp_reset_query();

?>

Body:
Here's a pretty neat solution that'll do the trick for you!

    <div class="post">
      <h3 class="title"><?php echo $post->post_title ?></h3>
      <?
        // Making an excerpt of the blog post content
        $excerpt = strip_tags($post->post_content);
        if (strlen($excerpt) > 100) {
          $excerpt = substr($excerpt, 0, 100);
          $excerpt = substr($excerpt, 0, strrpos($excerpt, ' '));
          $excerpt .= '...';
        }
      ?>
      <p class="excerpt"><?php echo $excerpt ?></p>
      <a class="more-link" href="<?php echo get_post_permalink($post->ID); ?>">Read more</a>
    </div>


问:
How to avoid child div inheriting parent div class
I am trying to make a dashboard to represent a few charts and some numbers. I have a parent div which has a class for it. Inside this div their are divs for charts and numbers. Now if the div for charts inherits the class from the parent that is fine considering the size of the charts. However the divs which display number should be of smaller size and I have applied another class for it. But the divs for numbers always take the parents div style . Is their a way the child divs would not take the parents div class.
Below are the images on how I am getting it now and how I am trying to get to.

CURRENTLY :

HOW IT SHOULD BE:

Below is the code on how it is currently.

      <dash-board ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

```

答: Either specifically override the inherited propert, or look into the :not() pseudo selector</p>


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答:
tree and node is your case are type names and should not be used as variable names later on.

```<code>tree *initTree() {
    tree *myTree = (tree*) malloc(sizeof(tree));
    node *myNode = (node*) malloc(sizeof(node));
    myTree->nodes[0] = myNode;
    return myTree;
}
</code>```

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?

Body:
tree and node is your case are type names and should not be used as variable names later on.

tree *initTree() {
    tree *myTree = (tree*) malloc(sizeof(tree));
    node *myNode = (node*) malloc(sizeof(node));
    myTree->nodes[0] = myNode;
    return myTree;
}


问:
automatically share the contents into the facebook after the data is stored in our database in laravel
How can we share on facebook immediately after inserting data in our database: the title, description, images and other fields. in php more specifically laravel5.5 </p>

答: There is no auto-share content in fb anymore, unless you call the fb-content graph api.</p>


答:
I think there is a problem with your column structure. I can show you how your structure can be - </p>

```<code><div class="col-md-6">
 *charts*
</div>
<div class="col-md-6">
    <div class="row">
        <div class="col-md-6">
            *number*
        </div>
        <div class="col-md-6">
            *number*
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            *number*
        </div>
        <div class="col-md-6">
            *number*
        </div>
    </div>
</div>
</code>```

Title: How to avoid child div inheriting parent div class

Body:
I am trying to make a dashboard to represent a few charts and some numbers. I have a parent div which has a class for it. Inside this div their are divs for charts and numbers. Now if the div for charts inherits the class from the parent that is fine considering the size of the charts. However the divs which display number should be of smaller size and I have applied another class for it. But the divs for numbers always take the parents div style . Is their a way the child divs would not take the parents div class.
Below are the images on how I am getting it now and how I am trying to get to.

CURRENTLY :

HOW IT SHOULD BE:

Below is the code on how it is currently.

      <dash-board ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

    <bars-chart ng-if="obj.chart_data" chart-data="obj.chart_data" />

Body:
I think there is a problem with your column structure. I can show you how your structure can be -

<div class="col-md-6">
 *charts*
</div>
<div class="col-md-6">
    <div class="row">
        <div class="col-md-6">
            *number*
        </div>
        <div class="col-md-6">
            *number*
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            *number*
        </div>
        <div class="col-md-6">
            *number*
        </div>
    </div>
</div>