问:
AWS ECS container can't specify a region

First, I use the server environment:

sever: django + nginx + uwsgi

cloud: docker + AWS ECS

logging: AWS CloudWatch log service + watchtower third party app

This is project code

https://github.com/byunghyunpark/django-log-test

Question

I am using the django watchtower third party app to use the AWS Cloudwatch log service. If I set the logging handler to watchtower and upload the docker image to the ECS service and run the task, it will still return 500 error.

500 error If you check the log

/tmp/uwsgi.log

```<code>*** Operational MODE: single process ***
DEBUG = False
DEV = False
TEST = False
LMS_MESSAGE = False
STATIC_S3 = True
DJANGO_LOG_LEVEL = INFO
Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler
    result = factory(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/watchtower/__init__.py", line 78, in __init__
    self.cwl_client = (boto3_session or boto3).client("logs")
  File "/usr/local/lib/python3.5/dist-packages/boto3/__init__.py", line 83, in client
    return _get_default_session().client(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/boto3/session.py", line 263, in client
    aws_session_token=aws_session_token, config=config)
  File "/usr/local/lib/python3.5/dist-packages/botocore/session.py", line 836, in create_client
    client_config=config, api_version=api_version)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 70, in create_client
    verify, credentials, scoped_config, client_config, endpoint_bridge)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 224, in _get_client_args
    verify, credentials, scoped_config, client_config, endpoint_bridge)
  File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 45, in get_client_args
    endpoint_url, is_secure, scoped_config)
  File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 103, in compute_client_args
    service_name, region_name, endpoint_url, is_secure)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 297, in resolve
    service_name, region_name)
  File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 122, in construct_endpoint
    partition, service_name, region_name)
  File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 135, in _endpoint_for_partition
    raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./mysite/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    django.setup(set_prefix=False)
  File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/lib/python3.5/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'watchtower': You must specify a region.
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 22)
spawned uWSGI worker 1 (pid: 33, cores: 1)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/1] 123.212.195.148 () {40 vars in 738 bytes} [Mon Jun  5 10:43:13 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/2] 123.212.195.148 () {40 vars in 756 bytes} [Mon Jun  5 10:43:13 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/3] 54.167.97.82 () {36 vars in 515 bytes} [Mon Jun  5 11:22:42 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/4] 91.196.50.33 () {38 vars in 613 bytes} [Mon Jun  5 12:03:20 2017] GET /testproxy.php => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/5] 123.212.195.148 () {40 vars in 738 bytes} [Mon Jun  5 14:01:04 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/6] 123.212.195.148 () {40 vars in 756 bytes} [Mon Jun  5 14:01:04 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/7] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:48 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/8] 123.212.195.148 () {44 vars in 809 bytes} [Mon Jun  5 14:06:48 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/9] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:49 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/10] 123.212.195.148 () {44 vars in 809 bytes} [Mon Jun  5 14:06:49 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/11] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:49 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
</code>```

task IAM role was assigned to administrator when task definition was created.

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}
</code>```

However, the container still does not talk to credentials.

If I change logging handler to default(console), the nginx server will work normally. If I run a docker conatiner with docker run -v $ HOME / .aws: /root/.aws --rm -it -p 9090: 80 image_name in local, nginx will work normally and the logging will work normally do in Cloudwatch log service.

Only in ECS environment fails authentication.

Do I need to do other settings besides IAM roles?

答:
I do not like this..
As a temporary resolution,

when I build docker, I passed the credentials information with the Dockerfile ARG variable. and I removed Task IAM.

Dockerfile's code like this

```<code>ARG         AWS_ACCESS_KEY_ID
ARG         AWS_SECRET_ACCESS_KEY
ARG         AWS_DEFAULT_REGION

ENV         AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} \
            AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} \
            AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}
</code>```

Body:
First, I use the server environment:

sever: django + nginx + uwsgi

cloud: docker + AWS ECS

logging: AWS CloudWatch log service + watchtower third party app

This is project code

https://github.com/byunghyunpark/django-log-test

Question

I am using the django watchtower third party app to use the AWS Cloudwatch log service. If I set the logging handler to watchtower and upload the docker image to the ECS service and run the task, it will still return 500 error.

500 error If you check the log

/tmp/uwsgi.log

*** Operational MODE: single process ***
DEBUG = False
DEV = False
TEST = False
LMS_MESSAGE = False
STATIC_S3 = True
DJANGO_LOG_LEVEL = INFO
Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler
    result = factory(**kwargs)
  File "/usr/local/lib/python3.5/dist-packages/watchtower/__init__.py", line 78, in __init__
    self.cwl_client = (boto3_session or boto3).client("logs")
  File "/usr/local/lib/python3.5/dist-packages/boto3/__init__.py", line 83, in client
    return _get_default_session().client(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/boto3/session.py", line 263, in client
    aws_session_token=aws_session_token, config=config)
  File "/usr/local/lib/python3.5/dist-packages/botocore/session.py", line 836, in create_client
    client_config=config, api_version=api_version)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 70, in create_client
    verify, credentials, scoped_config, client_config, endpoint_bridge)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 224, in _get_client_args
    verify, credentials, scoped_config, client_config, endpoint_bridge)
  File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 45, in get_client_args
    endpoint_url, is_secure, scoped_config)
  File "/usr/local/lib/python3.5/dist-packages/botocore/args.py", line 103, in compute_client_args
    service_name, region_name, endpoint_url, is_secure)
  File "/usr/local/lib/python3.5/dist-packages/botocore/client.py", line 297, in resolve
    service_name, region_name)
  File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 122, in construct_endpoint
    partition, service_name, region_name)
  File "/usr/local/lib/python3.5/dist-packages/botocore/regions.py", line 135, in _endpoint_for_partition
    raise NoRegionError()
botocore.exceptions.NoRegionError: You must specify a region.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "./mysite/wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "/usr/local/lib/python3.5/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application
    django.setup(set_prefix=False)
  File "/usr/local/lib/python3.5/dist-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/usr/local/lib/python3.5/dist-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/lib/python3.5/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'watchtower': You must specify a region.
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 22)
spawned uWSGI worker 1 (pid: 33, cores: 1)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/1] 123.212.195.148 () {40 vars in 738 bytes} [Mon Jun  5 10:43:13 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/2] 123.212.195.148 () {40 vars in 756 bytes} [Mon Jun  5 10:43:13 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/3] 54.167.97.82 () {36 vars in 515 bytes} [Mon Jun  5 11:22:42 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/4] 91.196.50.33 () {38 vars in 613 bytes} [Mon Jun  5 12:03:20 2017] GET /testproxy.php => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/5] 123.212.195.148 () {40 vars in 738 bytes} [Mon Jun  5 14:01:04 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/6] 123.212.195.148 () {40 vars in 756 bytes} [Mon Jun  5 14:01:04 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/7] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:48 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/8] 123.212.195.148 () {44 vars in 809 bytes} [Mon Jun  5 14:06:48 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/9] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:49 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/10] 123.212.195.148 () {44 vars in 809 bytes} [Mon Jun  5 14:06:49 2017] GET /favicon.ico => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)
--- no python application found, check your startup logs for errors ---
[pid: 33|app: -1|req: -1/11] 123.212.195.148 () {42 vars in 769 bytes} [Mon Jun  5 14:06:49 2017] GET / => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)

task IAM role was assigned to administrator when task definition was created.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

However, the container still does not talk to credentials.

If I change logging handler to default(console), the nginx server will work normally. If I run a docker conatiner with docker run -v $ HOME / .aws: /root/.aws --rm -it -p 9090: 80 image_name in local, nginx will work normally and the logging will work normally do in Cloudwatch log service.

Only in ECS environment fails authentication.

Do I need to do other settings besides IAM roles?

Body:
I do not like this..
As a temporary resolution,

when I build docker, I passed the credentials information with the Dockerfile ARG variable. and I removed Task IAM.

Dockerfile's code like this

ARG         AWS_ACCESS_KEY_ID
ARG         AWS_SECRET_ACCESS_KEY
ARG         AWS_DEFAULT_REGION

ENV         AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} \
            AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} \
            AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION}


来源: stackexchange

问:
Requet Tracker RT4.4, Change Queue of existing ticket using REST API
I am having two Queues Q1, Q2. User U1 has access to Q1 ad user U2 has access to Q2. Finally I have a ticket T whose owner is U1 in queue Q1.
I am logged in as U1 and want to change the ticket T1's queue to Q2 and assign it(change owner) to U2. And I want to use RT REST API to get this done in one operation of edit ticket. I have given all kind of access to U1/U2 user in their respective queues. But eveytime try editing the ticket with new queue(Q2) and new user(U2) I get exception/error message from RT stating "# queue: Permission Denied".
Any way I can achieve what I want or I am expecting something which is breaking very basic ACL of RT. Please help me understand this.
How does the plugin "Extension - Queue Change On Update" works internally can any one help me understand it.</p>

答:
I assume you have read the REST API documentation so you don't make any mistake by calling the proper commands. According to the description it seems to me that you don't have set the CreateTicket right of U1 in Q2 and vice versa. When you need U1 to change owner to U2 in target queue, you need also to set ReassignTicket right of U1 in Q2 and vice versa.

Sorry, I don't know the mentioned extension.

ContentLicense: CC BY-SA 3.0


问:
Parsing XML to Java List
I want to parse below xml file which has huge data, Here is my xml.

what is the best way to parse from XML to java List? can i use SAXParser for parsing the XML or any other efficient way? I expect , i would have data more than 1 million.

```<code><root>
    <Company>
        <name>TATA</name>
        <Location>
          <id>1</id>
          <name>India</name>
            <branchesList>
                <branches>
                <name>Chennai</name>
                <id>Ch-1</id>
                <status>Active</status>
            </branches>
            <branches>
                <name>Hyderabad</name>
                <id>Hy-1</id>
            <status>In-Active</status>
            </branches>
            <branches>
                <name>Delhi</name>
                <id>De-1</id>
                <status>Active</status>
            </branches>
        </branchesList>
        </Location>
         <Location>
          <id>1</id>
          <name>USA</name>
            <branchesList>
                <branches>
                <name>NewYork</name>
                <id>Nw-1</id>
                <status>Active</status>
            </branches>
            <branches>
                <name>NewJersy</name>
                <id>Ne-1</id>
            <status>In-Active</status>
            </branches>
            <branches>
                <name>Denver</name>
                <id>De-1</id>
                <status>Active</status>
            </branches>
        </branchesList>
        </Location>
      </Company>

    </root>
</code>```

答:
I would suggest you look at this answer.

It recommends using SAXParser for big XMLs.

As of having 1 million + Strings in a list in java, in principle there is no issue. You could have as many as Integer.MAX_VALUE-5 iirc.

Documentation for SAXParser is here and is quite complete. You should have no issue taking the elements you want and putting them in a list.

Finally, if you want to have more than a simple list of strings in memory, I would look at other collections like Dictionary.

Title: Parsing XML to Java List

Body:
I want to parse below xml file which has huge data, Here is my xml.

what is the best way to parse from XML to java List? can i use SAXParser for parsing the XML or any other efficient way? I expect , i would have data more than 1 million.

<root>
    <Company>
        <name>TATA</name>
        <Location>
          <id>1</id>
          <name>India</name>
            <branchesList>
                <branches>
                <name>Chennai</name>
                <id>Ch-1</id>
                <status>Active</status>
            </branches>
            <branches>
                <name>Hyderabad</name>
                <id>Hy-1</id>
            <status>In-Active</status>
            </branches>
            <branches>
                <name>Delhi</name>
                <id>De-1</id>
                <status>Active</status>
            </branches>
        </branchesList>
        </Location>
         <Location>
          <id>1</id>
          <name>USA</name>
            <branchesList>
                <branches>
                <name>NewYork</name>
                <id>Nw-1</id>
                <status>Active</status>
            </branches>
            <branches>
                <name>NewJersy</name>
                <id>Ne-1</id>
            <status>In-Active</status>
            </branches>
            <branches>
                <name>Denver</name>
                <id>De-1</id>
                <status>Active</status>
            </branches>
        </branchesList>
        </Location>
      </Company>

    </root>


问:
Passe data in bundle to the activity of the gallery
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

```<code>Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);
</code>```

this is onActivityResult :

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);
</code>```

and in onSelectFromGalleryResult(data) I had this :

```<code>       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}
</code>```

答:
On activity result is called in the activity from which you are calling the startActivityForResult();

As you are using the chooser in this case it is not necessary that the result intent will contain the same information as you are adding.

Hope this helps.

Body:
I had this code, without the bundle it works very well, but when I add the bundle in the intent, in my onActivityResult I don't found this id_q in data, I found just the path of the chosen picture.

Intent intent = new Intent();
        Bundle b = new Bundle();
        b.putInt("id_q", q.getId());
        intent.putExtras(b);
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select File"), SELECT_IMAGE);

this is onActivityResult :

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == SELECT_IMAGE)
                onSelectFromGalleryResult(data);

and in onSelectFromGalleryResult(data) I had this :

       if (data != null && data.getExtras() != null) {
            Bundle b = data.getExtras();
            int id_q = b.getInt("id_q");}


问:
Adding Font color and No fill to a sub routine
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!</p>

```<code>Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub
</code>```

答:
Avoid using Select and ActiveWorkbook. Instead, simply reference the ranges directly. Try this:

```<code>Sub forEachWs()
Dim ws As Worksheet
Dim wb As Workbook

'Opens new workbook for formatting
Set wb = Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In wb.Worksheets
    Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)

With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    .Range("A2:BB" & .Cells(.Rows.Count, 1).End(xlUp).Row).Font.Color = vbBlack
    .Range("A2:BB" & .Cells(.Rows.Count, 1).End(xlUp).Row).Interior.ColorIndex = xlNone
End With

End Sub
</code>```

Body:
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!

Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub

Body:
Avoid using Select and ActiveWorkbook. Instead, simply reference the ranges directly. Try this:

Sub forEachWs()
Dim ws As Worksheet
Dim wb As Workbook

'Opens new workbook for formatting
Set wb = Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In wb.Worksheets
    Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)

With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    .Range("A2:BB" & .Cells(.Rows.Count, 1).End(xlUp).Row).Font.Color = vbBlack
    .Range("A2:BB" & .Cells(.Rows.Count, 1).End(xlUp).Row).Interior.ColorIndex = xlNone
End With

End Sub


问:
how can I redirect to https which require certain sertificate for access
There's a payment server. I can successfully send data via cURL and set appropriate key and certificate and payment server successfully answers. But now I need to make a redirect to that server so that client can enter credit card data. How can I make that redirect?

Is there a possibility to add key/certificate as a part of headers in function header("Location: https://...."); ?

答:
Unless the provider has a very weird setup, I don't think you can. There are two clients cpnnecting to the server - first your PHP code which is using the client certificate, then you expect a browser somewhere to be able to bind to the same session without the client certificate? The only way this would make any sense is if the payment provider sends back a surrogate authentication token - and if they did that they'd provide detailled documentation. Obviously that is not the case.

While you could proxy the data on your server, I'd strongly recommend you switch to a different payment provider which handles the entire payment process for you.

ContentLicense: CC BY-SA 2.5


问:
Colouring one column of pandas dataframe
I have a dataframe and would like to use the .style to highlight the first column.

I wasn't sure if there is a loop I have to use or a function

答:
I think you need custom function which return DataFrame with color for first column:

```<code>np.random.seed(100)
df =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def highlight_col(x):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[:, 0] = r
    return df1
df.style.apply(highlight_col, axis=None)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I think you need custom function which return DataFrame with color for first column:

np.random.seed(100)
df =  pd.DataFrame(np.random.randn(5, 3), columns=list('ABC'))

def highlight_col(x):
    r = 'background-color: red'
    df1 = pd.DataFrame('', index=x.index, columns=x.columns)
    df1.iloc[:, 0] = r
    return df1
df.style.apply(highlight_col, axis=None)


问:
Handlebars - Concat string parameters when calling partial
I would like to know if it is possible to concat a variable with another string when loading a partial using Handlebars.

```<code>{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}
</code>```

I'd like to concat id+"something" and storing it into id, which would be sent to the template.

I'm using a custom helper to load partials (partial) which merge this with the options.hash provided by handlebars.

答:
In ES6 this is possible using this helper:
concat : (...strs) => strs.join('')

You may also want to skip parameters given by Handlebars, which is:
concat : (...strs) => strs.filter( arg => typeof arg !== 'object' ).join('')

Body:
I would like to know if it is possible to concat a variable with another string when loading a partial using Handlebars.

{{partial logos this ns=../ns nsr=../nsr id=id+"something"}}

I'd like to concat id+"something" and storing it into id, which would be sent to the template.

I'm using a custom helper to load partials (partial) which merge this with the options.hash provided by handlebars.


问:
Css images on the right side of the footer
I am trying to create a footer with 2 Images who link to a page.

The two links / Images shall stay on the right side of the footer.

The Images shall stand next to each other with a Little margin.

How to I manage this with css?

```<code><footer>
    <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
</footer>
</code>```

答:
Wrap them in a div and float it.

CSS:

```<code>.images-container {
   float: right;
}

.images-container a {
    margin-left: 5px;
}
</code>```

HTML:

```<code><footer>
<div class="images-container">
    <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
</div>
</footer>
</code>```

Body:
Wrap them in a div and float it.

CSS:

.images-container {
   float: right;
}

.images-container a {
    margin-left: 5px;
}

HTML:

<footer>
<div class="images-container">
    <a href="http://www.google.de/" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
    <a href="http://www.google.de" target="_blank">
        <img src="test.jpg" alt="logo.jpg">
    </a>
</div>
</footer>


问:
Plotting Venn diagram in Jupyter after changes (matplotlib-venn)
By following the commands in the matplotlib-venn README I can produce the initial plots in the examples.  However, when I change the settings of the Venn diagram (label text etc.) I cannot work out how to replot the figure.  Running:

```<code>%matplotlib inline
from matplotlib_venn import venn3
v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))
</code>```

gives the Venn diagram inline.  I then proceed to change a label

```<code>v.get_label_by_id('100').set_text('Arbitrary1')
</code>```

but I cannot then replot the figure.  I have tried

```<code># from matplotlib import pyplot as plt
plt.plot()
plt.plot(v)
v
v()
</code>```

but I am really feeling around in the dark.  I feel like I am missing something very basic about %matplotlib or the matplotlib plot function, but I have not been able to find an answer yet online.

How do I plot this figure again in Jupyter?

答:
The state of the pyplot statemachine gets lost after the jupyter cell is evaluated. Thus in a new cell pyplot is unaware of the previously created figure.

The solution is to obtain a reference to the figure before leaving the cell. This is either done by

explicitely assigning the figure to a variable fig=plt.figure() or

storing the figure in a variable at the end of a cell, fig = plt.gcf()

In both cases you will have a figure object to show in later cells, by simply typing fig.
Since this is general to using matplotlib in jupyter notebook, the following example does not take venn diagrams into account.

Body:
By following the commands in the matplotlib-venn README I can produce the initial plots in the examples.  However, when I change the settings of the Venn diagram (label text etc.) I cannot work out how to replot the figure.  Running:

%matplotlib inline
from matplotlib_venn import venn3
v = venn3([set1, set2, set3], ('Set1', 'Set2', 'Set3'))

gives the Venn diagram inline.  I then proceed to change a label

v.get_label_by_id('100').set_text('Arbitrary1')

but I cannot then replot the figure.  I have tried

# from matplotlib import pyplot as plt
plt.plot()
plt.plot(v)
v
v()

but I am really feeling around in the dark.  I feel like I am missing something very basic about %matplotlib or the matplotlib plot function, but I have not been able to find an answer yet online.

How do I plot this figure again in Jupyter?


问:
Yii2 How to save same file name but different file or content?
How to save same name but different content for example, samplename.docx. Now i want to save it again but the result the same. When i create a new report and use the name samplename it will overwrite the other same name. So in the uploads folder the samplename.docx is only one. But in the dgView is more than one.

This is my controller:

```<code>public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project =$model->doc_name;
        $model->upload_file= UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {
        return $this ->render('create', [
            'model'=>$model,
        ]);
    }
}
</code>```

This is my model:

```<code>public $upload_file;
public function rules()
{
    return [
        [['reference_no', 'subject', 'doc_for', 'doc_from', 'doc_date', 'doc_file', 'doc_name', 'drawer_id'], 'required'],
        [['doc_date'], 'safe'],
        [['drawer_id'], 'integer'],
        [['reference_no', 'doc_for', 'doc_from'], 'string', 'max' => 200],
        [['subject'], 'string', 'max' => 255],
        [['doc_file', 'doc_name'], 'string', 'max' => 50],
        [['user_id'],'string'],

    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'report_id' => 'Report ID',
        'reference_no' => 'Reference No:',
        'subject' => 'Subject:',
        'doc_for' => 'For:',
        'doc_from' => 'From:',
        'doc_date' => 'Document Entry Date:',
        'doc_file' => 'Document File:',
        'doc_name' => 'Document Name:',
        'drawer_id' => 'Drawer ID:',
        'user_id' => 'Encoder Name:',
    ];
}
</code>```

And this is my form:

```<code> <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button('<i class="fa fa-plus"></i> Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>
        </br>
        </br>
  <?php Pjax::begin(['id' => 'for_from']) ?>
      <div class="col-sm-6">
     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>
      </div>
      <div class="col-sm-6">
    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>
      </div>
        </br>
        </br></br></br>
      <div class="broder" style=" border-radius: 5px; padding: 12px; ">
      </div>
  <div class="col-sm-6">
      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>
      <br>
      <br>
      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>
  </div>
  <div class="col-sm-6" style="padding-top: 14px; ">
         </br>
         </br>
         </br></br>
    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>
</code>```

答:
Try this one</p>

```<code>if (file_exists($fileFullPath)) {
 unlink ($fileFullPath);
 echo "delete existing file creating new <br />";
 }else{
  echo "file not exists creating new <br />";
}
</code>```

Body:
How to save same name but different content for example, samplename.docx. Now i want to save it again but the result the same. When i create a new report and use the name samplename it will overwrite the other same name. So in the uploads folder the samplename.docx is only one. But in the dgView is more than one.

This is my controller:

public function actionCreate()
{
    $model = new reportDetails();
    if ($model->load(Yii::$app->request->post()))
    {
        $project =$model->doc_name;
        $model->upload_file= UploadedFile::getInstance($model,'doc_file');
        $model->upload_file->saveAs('uploads/'.$project.'.'.$model->upload_file->extension);
        $model->doc_file='uploads/'.$project.'.'.$model->upload_file->extension;
        $model->doc_name=$project.'.'.$model->upload_file->extension;
        $model->save();

        Yii::$app->getSession()->setFlash('success','Data saved!');
        return $this->redirect(['view','id'=> $model->report_id]);
    }

    else {
        return $this ->render('create', [
            'model'=>$model,
        ]);
    }
}

This is my model:

public $upload_file;
public function rules()
{
    return [
        [['reference_no', 'subject', 'doc_for', 'doc_from', 'doc_date', 'doc_file', 'doc_name', 'drawer_id'], 'required'],
        [['doc_date'], 'safe'],
        [['drawer_id'], 'integer'],
        [['reference_no', 'doc_for', 'doc_from'], 'string', 'max' => 200],
        [['subject'], 'string', 'max' => 255],
        [['doc_file', 'doc_name'], 'string', 'max' => 50],
        [['user_id'],'string'],

    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels()
{
    return [
        'report_id' => 'Report ID',
        'reference_no' => 'Reference No:',
        'subject' => 'Subject:',
        'doc_for' => 'For:',
        'doc_from' => 'From:',
        'doc_date' => 'Document Entry Date:',
        'doc_file' => 'Document File:',
        'doc_name' => 'Document Name:',
        'drawer_id' => 'Drawer ID:',
        'user_id' => 'Encoder Name:',
    ];
}

And this is my form:

 <?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
        <?= Html::button(' Add Person', ['value' => Url::to('index.php?r=name/create'), 'class' => 'btn btn-custom-pos btn-success', 'id' => 'officialsfor']) ?>

  <?php Pjax::begin(['id' => 'for_from']) ?>

     <?= $form->field($model, 'doc_for')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
            'name_id',
            function($model, $defaultValue){
              return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
             ],
            ]); ?>

    <?= $form->field($model, 'doc_from')->widget(Select2::classname(), [
           'data' => ArrayHelper::map(Name::find()->asArray()->all(),
           'name_id',
            function($model, $defaultValue){
            return $model['position'].' '.$model['fname'].' '.$model['mname'].' '.$model['lname'];
            }),
            'language' => 'en',
            'options' => ['placeholder' => 'Choose a person ...'],
            'pluginOptions' => [
                'allowClear' => true,
                'width' => 500,
            ],
            ]); ?>
 <?php Pjax::end(); ?>

      <?= $form->field($model, 'user_id')->textInput(['type' => 'hidden','style'=>'width:500px;','placeholder' => 'Enter a Reference No....','value' =>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name)]) ?>
       <?= Html::activeLabel($model, 'user_id', ['label'=>ucfirst(Yii::$app->user->identity->first_name) . ' ' . ucfirst(Yii::$app->user->identity->middle_name) . ' ' . ucfirst(Yii::$app->user->identity->last_name),'style' => 'font-size: 21px;','class' => 'color']) ?>

      <?= $form->field($model, 'reference_no')->textInput(['style'=>'width:500px','placeholder' => 'Enter a Reference No....']) ?>
      <?= $form->field($model, 'subject')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Subject....']) ?>
    <?= $form->field($model, 'doc_date')->widget(
        DatePicker::className(), [
            'inline' => false,
            'options' => ['placeholder' => 'Choose a Entry Date ...'],
            'clientOptions' => [
            'autoclose' => true,
            'format' => 'yyyy-mm-dd'
              ]
             ]);?>

    <?= $form->field($model, 'drawer_id')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Drawer ID....', ]) ?>
    <?= $form->field($model, 'doc_name')->textInput(['maxlength'=>true,'style'=>'width:500px','placeholder' => 'Enter a Document Name....']) ?>
      <?= $form->field($model, 'doc_file')-> widget(
        FileInput::classname(),[
      'name' => 'doc_file',
      'options' => ['accept' => '.docx','.doc','.docs'],
      'pluginOptions' => [
          'showPreview' => false,
          'showCaption' => true,
          'showRemove' => true,
          'showUpload' => false
            ]
        ]);
      ?>

Body:
Try this one

if (file_exists($fileFullPath)) {
 unlink ($fileFullPath);
 echo "delete existing file creating new <br />";
 }else{
  echo "file not exists creating new <br />";
}


问:
Out of Array size element values
How dangerous is it to access an array out of bounds? This does not tell what is the value stored.

When i try to print the out of array size elements as shown in the program, It is printing 0. Will it be always 0 or some garbage values.

Program

```<code>#include<stdio.h>
int main()
{
    int a[5] = {10};
    printf("\n\ra[6] = %d",a[6]);
    printf("\n\ra[7] = %d",a[7]);
    printf("\n\ra[8] = %d",a[8]);
    printf("\n\ra[9] = %d",a[9]);
    return 0;
}
</code>```

Output

a[6] = 0 a[7] = 0 a[8] = 0 a[9] = 0

My question is what will be value of out of array size elements? Is it always garbage value or zero?

答:
When i try to print the out of array size elements....

Wait, stop!! Anything over a value of 4 for value of i (index) [C arrays use 0-based indexing] in case of an array defined like int a[5] = {10}; is invalid memory access which leads to  undefined behavior. You cannot expect anything, at all.

If you're lucky, you'll probably receive a segmentation fault while running the program which strongly indicates some sort of invalid memory access.

If you're unlucky, the program might read the credit card number stored on your laptop and order pizza any pony for your team and transfer rest of the money to some anonymous account for ISIS. Iff you're willing to face that only then access out of bound memory, otherwise, refrain from doing it.

Summary: Just don't write code because you can, or the syntax is allowed. Try to make sense of the code to write. The array size is mentioned for a reson. If we did not have to regard the size, why's that size there, in fort place?

Title: Out of Array size element values

Body:
How dangerous is it to access an array out of bounds? This does not tell what is the value stored.

When i try to print the out of array size elements as shown in the program, It is printing 0. Will it be always 0 or some garbage values.

Program

#include<stdio.h>
int main()
{
    int a[5] = {10};
    printf("\n\ra[6] = %d",a[6]);
    printf("\n\ra[7] = %d",a[7]);
    printf("\n\ra[8] = %d",a[8]);
    printf("\n\ra[9] = %d",a[9]);
    return 0;
}

Output

a[6] = 0 a[7] = 0 a[8] = 0 a[9] = 0

My question is what will be value of out of array size elements? Is it always garbage value or zero?


问:
Can I use the generic logging.Logger() in Celery tasks?
the doc says

A special logger is available named “celery.task”, you can inherit from this logger to automatically get the task name and unique id as part of the logs.

This is hardly enough. Is there a more detailed info available? Specifically, what handlers and format strings it defines by default? Why would I want to inherit from it? Can I use a generic logging.Logger() instead? What are the best practices for logging to a file from celery tasks (not Django)? etc. Thank you.

答:
Can I use a generic logging.Logger() instead?

Yes, you can use the generic Python/Django logger.
Instead of logger = get_task_logger(__name__) just choose the getLogger:

```<code>import logging
logger = logging.getLogger(__name__)
</code>```

Why would I want to inherit from it?

The advantage of using celery.task is:

automatically get the task name and unique id as part of the logs.

which itself uses the standard Python logging lib.

This is hardly enough. Is there a more detailed info available?
  Specifically, what handlers and format strings it defines by default?

By default it's using the WatchedFileHandler from logging.handlers
You can check in the celery.app.log documentation, it's getting set in the setup_handler method.

What are the best practices for logging to a file from celery tasks
  (not Django)? etc

1. Directly in the module - You can simply put everything at the top of your module - define a handler, and while getting the logger assign it:

```<code>import logging

# ---- set up logging to file ---
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# --- define a Handler ---
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# --- set a format which is simpler for console use ---
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# --- tell the handler to use this format ---
console.setFormatter(formatter)
# --- add the handler to the logger ---
logging.getLogger('').addHandler(console)
</code>```

2. Use logging_config dictionary - dictConfig: a much more good looking practice.

```<code>import logging
from logging.config import dictConfig

logging_config = dict(
    version = 1,
    formatters = {
        'f': {'format':
              '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
        },
    handlers = {
        'h': {'class': 'logging.StreamHandler',
              'formatter': 'f',
              'level': logging.DEBUG}
        },
    root = {
        'handlers': ['h'],
        'level': logging.DEBUG,
        },
)

dictConfig(logging_config)

logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')
</code>```

3. Using a separate logging format file - *.ini:

```<code>[loggers]
# list of loggers
keys=root,log02

[handlers]
# list of handlers
keys=hand01,hand02

[formatters]
# list of formatters
keys=form01,form02

[logger_root]
# config for 'root' logger
level=NOTSET
handlers=hand01

[handler_hand01]
# config for handler hand01
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)

[handler_hand02]
## config for handler hand02
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')

[formatter_form01]
# config for formatter form01
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
</code>```

4. A separate class -
Last but not least, a more elegant solution is to have all this as separate module (Class), and just import it with specific flags where ever required:

```<code>import logging
from config import LOG, LOGGING

class Logger:
    def __init__(self, logf=None, logger_name=None, debug=None, rotation=None):
        self.logfile = logf
        self.logger_name = logger_name if logger_name else logf
        self.logger = self.get_logger(rotation=rotation) if rotation else self.get_logger()
        self.debug = debug if debug else False
        self.debug = debug if debug else LOG["debug"]

    def logf(self, filename=None):
        if filename is None:
            filename = LOG["file"]
        return "%s%s" % (LOG["dir"], filename)

    def get_logger(self, rotation=False):
        logger = logging.getLogger(self.logger_name)
        logf = self.logf(self.logfile)
        if rotation:
            from logging.handlers import TimedRotatingFileHandler
            self.handler = TimedRotatingFileHandler(logf, when='midnight', interval=1, backupCount=10)
        else:
            self.handler = logging.FileHandler(logf)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        #formatter = "%(asctime)s - %(levelname)s - %(filename)s:%(funcName)s - %(message)s",
        self.handler.setFormatter(formatter)
        logger.addHandler(self.handler)
        logger.setLevel(logging.DEBUG)
        return logger
</code>```

Body:
Can I use a generic logging.Logger() instead?

Yes, you can use the generic Python/Django logger.
Instead of logger = get_task_logger(__name__) just choose the getLogger:

import logging
logger = logging.getLogger(__name__)

Why would I want to inherit from it?

The advantage of using celery.task is:

automatically get the task name and unique id as part of the logs.

which itself uses the standard Python logging lib.

This is hardly enough. Is there a more detailed info available?
  Specifically, what handlers and format strings it defines by default?

By default it's using the WatchedFileHandler from logging.handlers
You can check in the celery.app.log documentation, it's getting set in the setup_handler method.

What are the best practices for logging to a file from celery tasks
  (not Django)? etc

1. Directly in the module - You can simply put everything at the top of your module - define a handler, and while getting the logger assign it:

import logging

# ---- set up logging to file ---
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
                    datefmt='%m-%d %H:%M',
                    filename='/temp/myapp.log',
                    filemode='w')
# --- define a Handler ---
console = logging.StreamHandler()
console.setLevel(logging.INFO)
# --- set a format which is simpler for console use ---
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
# --- tell the handler to use this format ---
console.setFormatter(formatter)
# --- add the handler to the logger ---
logging.getLogger('').addHandler(console)

2. Use logging_config dictionary - dictConfig: a much more good looking practice.

import logging
from logging.config import dictConfig

logging_config = dict(
    version = 1,
    formatters = {
        'f': {'format':
              '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'}
        },
    handlers = {
        'h': {'class': 'logging.StreamHandler',
              'formatter': 'f',
              'level': logging.DEBUG}
        },
    root = {
        'handlers': ['h'],
        'level': logging.DEBUG,
        },
)

dictConfig(logging_config)

logger = logging.getLogger()
logger.debug('often makes a very good meal of %s', 'visiting tourists')

3. Using a separate logging format file - *.ini:

[loggers]
# list of loggers
keys=root,log02

[handlers]
# list of handlers
keys=hand01,hand02

[formatters]
# list of formatters
keys=form01,form02

[logger_root]
# config for 'root' logger
level=NOTSET
handlers=hand01

[handler_hand01]
# config for handler hand01
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)

[handler_hand02]
## config for handler hand02
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')

[formatter_form01]
# config for formatter form01
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter

4. A separate class -
Last but not least, a more elegant solution is to have all this as separate module (Class), and just import it with specific flags where ever required:

import logging
from config import LOG, LOGGING

class Logger:
    def __init__(self, logf=None, logger_name=None, debug=None, rotation=None):
        self.logfile = logf
        self.logger_name = logger_name if logger_name else logf
        self.logger = self.get_logger(rotation=rotation) if rotation else self.get_logger()
        self.debug = debug if debug else False
        self.debug = debug if debug else LOG["debug"]

    def logf(self, filename=None):
        if filename is None:
            filename = LOG["file"]
        return "%s%s" % (LOG["dir"], filename)

    def get_logger(self, rotation=False):
        logger = logging.getLogger(self.logger_name)
        logf = self.logf(self.logfile)
        if rotation:
            from logging.handlers import TimedRotatingFileHandler
            self.handler = TimedRotatingFileHandler(logf, when='midnight', interval=1, backupCount=10)
        else:
            self.handler = logging.FileHandler(logf)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
        #formatter = "%(asctime)s - %(levelname)s - %(filename)s:%(funcName)s - %(message)s",
        self.handler.setFormatter(formatter)
        logger.addHandler(self.handler)
        logger.setLevel(logging.DEBUG)
        return logger


问:
Binding Angular component with specific type
I'm currently working with Angular and TypeScript and I want to know if it's possible to bind component @Inputs to use specific types?

Example

```<code>@Component({selector: 'foobar'})
export class FooComponent {
    @Input() foo: number;
    @Input() bar: boolean;
}

<foobar foo="123" bar="true"></foobar>
</code>```

When the component is bound, both foo and bar are string. Does angular provide a way to enforce the specified type?

I tried this, but I don't like it...(it seems dirty and not very elegant)

```<code>@Component({selector: 'foobar'})
export class FooComponent {
    foo: number;
    bar: boolean;

    @Input('foo') set _foo(value: string) {
        this.foo = Number(value);
    }

    @Input('bar') set _bar(value: string) {
        this.bar = value === 'true';
    }
}
</code>```

It would be nice if there was something in Angular's Input that could act as a binding delegate; For example:

```<code>@Input('foo', (value: string) => Number(value)) foo: number = 123;
</code>```

答:
If you use a binding like fuu="123" the value will always be a string. But if you bind like this:

```<code>[fuu]="123"
</code>```

The value will be of type number.
This means, that the values are treated like in normal JS:

```<code>[fuu]="true"   -> boolean
[fuu]="'true'" -> string
[fuu]="123"    -> number
</code>```

Body:
I'm currently working with Angular and TypeScript and I want to know if it's possible to bind component @Inputs to use specific types?

Example

@Component({selector: 'foobar'})
export class FooComponent {
    @Input() foo: number;
    @Input() bar: boolean;
}

<foobar foo="123" bar="true"></foobar>

When the component is bound, both foo and bar are string. Does angular provide a way to enforce the specified type?

I tried this, but I don't like it...(it seems dirty and not very elegant)

@Component({selector: 'foobar'})
export class FooComponent {
    foo: number;
    bar: boolean;

    @Input('foo') set _foo(value: string) {
        this.foo = Number(value);
    }

    @Input('bar') set _bar(value: string) {
        this.bar = value === 'true';
    }
}

It would be nice if there was something in Angular's Input that could act as a binding delegate; For example:

@Input('foo', (value: string) => Number(value)) foo: number = 123;

Body:
If you use a binding like fuu="123" the value will always be a string. But if you bind like this:

[fuu]="123"

The value will be of type number.
This means, that the values are treated like in normal JS:

[fuu]="true"   -> boolean
[fuu]="'true'" -> string
[fuu]="123"    -> number


问:
env file keeps deleting after deploying with Envoyer
I'm using Laravel 5.4, Envoyer and Forge. Every time I deploy master branch on Envoyer, my .env file gets deleted. It has no content.

What should I do? Is it maybe my configuration faulty?

答:
Let's breakdown the way Envoyer works:

Clones the git repository to a new release folder - found under /releases.

Runs composer install on this new cloned directory (to bring your vendor folder up to date).

Overwrites the symlink for /path/to/project/current from /path/to/project/releases/[first release folder] to /path/to/project/releases/[second release folder.

Clears out old release folders.

When a new version is deployed, it does a fresh clone of the git repository. Unless you have changed your .gitignore, your .env file is NOT tracked in git so is never in the new folder.

By using the environment capability built-in to Envoyer, this places an .env file here /path/to/project/.env and symlinks from /path/to/project/.env to /path/to/project/current/.env.


问:
Excel does not indicate right values from HTML table from Web Query
I never 'coded' with Excel. So I do not have a code that shows my problem. But as you will see it is a very basic problem and can be reproduced very fast. I am trying right now to implement an HTML table in Excel, which should be fairly simple. But the result is not showing the right value.

Go on https://coinmarketcap.com/#EUR and copy the link.

I open an Excel file, go on Data > From Web > an insert the URL and press Ok and Load Table.

Unfortunately, the table shows now the values in US currency and not in EURO which is pre-selected in the URL. Can someone tell me why this happens and how to display the EURO values?

答:
Edit I see now that the source is written in USD and there is a conversion table at the bottom of the source.

data-eur="1.1268405531885644" I guess USD times that equals to euro.
It's possible to use this method but it depends on what you are trying to do.

End of edit;

Maybe you can try and "download" the source of the page an manipulate the data from there?

EDIT 2;

It seems it was harder than I thought.

You need to use the get from web, but I made a conversion macro that will grab the conversion rate used on the page and update all the prices on the table.

Since you asked for Euro currency I assume you are European, your profile does not give any clues either.

But that means I made the macro to suit European version of Excel where you use , as fraction separator.

If this is incorrect it's an easy fix.

Open Excel and press ALT+ F11.

Insert -> Module.

Big white "notepad" opens on your right.

Paste the code below  in the window.

Close the VBA editor.

Save the workbook as Excel file with macro .xlsm

Do the web query and place it in A1. Or at least in A-column.

In Excel Ribbon menu, View, and all the way to the right "Macro".

Run Euro.

Hopefully that should do it.

```<code>Sub euro()
    Dim LastRow As Long
    Dim HTML As String
    Dim REeuro As Object
    Set REeuro = CreateObject("vbscript.regexp")
    'ActiveWorkbook.RefreshAll

    HTML = GetHTML("https://coinmarketcap.com/")
    REeuro.Pattern = "data-eur=\" & Chr(34) & "(\d+\.\d+)"
    REeuro.Global = True
    REeuro.IgnoreCase = True
    Set Matches = REeuro.Execute(HTML)

    EuroConversion = Matches.Item(0).submatches.Item(0)
    LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row
    FirstRow = ActiveSheet.Cells(LastRow, "C").End(xlUp).Row + 1

    For i = FirstRow To LastRow
        Range("C" & i).Value = Mid(Range("C" & i).Value, 2) / EuroConversion
        Range("D" & i).Value = Mid(Range("D" & i).Value, 2) / EuroConversion
        Range("F" & i).Value = Mid(Range("F" & i).Value, 2) / EuroConversion

    Next i

    'Columns("C:F").NumberFormat = "#,##0.00"

End Sub

Function GetHTML(URL As String) As String
    Dim HTML As String
    With CreateObject("MSXML2.XMLHTTP")
       .Open "GET", URL, False
       .Send
        GetHTML = .ResponseText
    End With
End Function
</code>```

What if it does not work...

Go back to VBA editor (Alt + F11) and check the references.

I use these in the image.

Body:
Edit I see now that the source is written in USD and there is a conversion table at the bottom of the source.

data-eur="1.1268405531885644" I guess USD times that equals to euro.
It's possible to use this method but it depends on what you are trying to do.

End of edit;

Maybe you can try and "download" the source of the page an manipulate the data from there?

EDIT 2;

It seems it was harder than I thought.

You need to use the get from web, but I made a conversion macro that will grab the conversion rate used on the page and update all the prices on the table.

Since you asked for Euro currency I assume you are European, your profile does not give any clues either.

But that means I made the macro to suit European version of Excel where you use , as fraction separator.

If this is incorrect it's an easy fix.

Open Excel and press ALT+ F11.

Insert -> Module.

Big white "notepad" opens on your right.

Paste the code below  in the window.

Close the VBA editor.

Save the workbook as Excel file with macro .xlsm

Do the web query and place it in A1. Or at least in A-column.

In Excel Ribbon menu, View, and all the way to the right "Macro".

Run Euro.

Hopefully that should do it.

Sub euro()
    Dim LastRow As Long
    Dim HTML As String
    Dim REeuro As Object
    Set REeuro = CreateObject("vbscript.regexp")
    'ActiveWorkbook.RefreshAll

    HTML = GetHTML("https://coinmarketcap.com/")
    REeuro.Pattern = "data-eur=\" & Chr(34) & "(\d+\.\d+)"
    REeuro.Global = True
    REeuro.IgnoreCase = True
    Set Matches = REeuro.Execute(HTML)

    EuroConversion = Matches.Item(0).submatches.Item(0)
    LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row
    FirstRow = ActiveSheet.Cells(LastRow, "C").End(xlUp).Row + 1

    For i = FirstRow To LastRow
        Range("C" & i).Value = Mid(Range("C" & i).Value, 2) / EuroConversion
        Range("D" & i).Value = Mid(Range("D" & i).Value, 2) / EuroConversion
        Range("F" & i).Value = Mid(Range("F" & i).Value, 2) / EuroConversion

    Next i

    'Columns("C:F").NumberFormat = "#,##0.00"

End Sub

Function GetHTML(URL As String) As String
    Dim HTML As String
    With CreateObject("MSXML2.XMLHTTP")
       .Open "GET", URL, False
       .Send
        GetHTML = .ResponseText
    End With
End Function

What if it does not work...

Go back to VBA editor (Alt + F11) and check the references.

I use these in the image.


问:
Image at center
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

```
</div>
</div>
</p>

<p>The above code couldn't give me success.</p>

<p>Please help me out!</p>

<p>Please share your codes for the same.</p>

<p>I am not able to center the image with my code so please help me out.</p>

<p>CSS is:-</p>

```
```

答:
Add text-align: center; to pg class and add margin: 0 auto; to the img tags.

```<code>.pg {
  text-align: center;
}

.pg img{
  margin: 0 auto;
}
</code>```

Here is a fiddle.

Title: Image at center

Body:
I am coding a website in which I want the image to be in the center at all size of screens.

I tried:-

    <title></title>

    <form id="form1">

    </form>

The above code couldn't give me success.

Please help me out!

Please share your codes for the same.

I am not able to center the image with my code so please help me out.

CSS is:-

Body:
Add text-align: center; to pg class and add margin: 0 auto; to the img tags.

.pg {
  text-align: center;
}

.pg img{
  margin: 0 auto;
}

Here is a fiddle.


答:
You can use float:right for your hyperlinks

footer a {
float:right;
}
footer a:first-child {
margin-left: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

        <img src="http://placehold.it/50" alt="logo.jpg">

        <img src="http://placehold.it/50" alt="logo.jpg">

</footer></code>```

Title: Css images on the right side of the footer

Body:
I am trying to create a footer with 2 Images who link to a page.

The two links / Images shall stay on the right side of the footer.

The Images shall stand next to each other with a Little margin.

How to I manage this with css?

Body:
You can use float:right for your hyperlinks

footer a {
float:right;
}
footer a:first-child {
margin-left: 10px;
}

<footer>
    <a href="http://www.google.de/" target="_blank">
        <img src="http://placehold.it/50" alt="logo.jpg">
    </a>
    <a href="http://www.google.de" target="_blank">
        <img src="http://placehold.it/50" alt="logo.jpg">
    </a>
</footer>


问:
Return bool value from web api
I am using Web Api 2 to create 1 user. Below is code

```<code>[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{
    try
    {
        //Code
        .
        .
        user.Update();
        return Request.CreateResponse(HttpStatusCode.OK, true);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}
</code>```

I trying to call this method from code behind like

```<code>using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:65486/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = client.PostAsJsonAsync("api/Stock/UpdateUserData", userObject).Result;

    if (response.IsSuccessStatusCode)
    {
        using (HttpContent content = response.Content)
        {
            Task<string> result = content.ReadAsStringAsync();
            string final = result.Result;
        }
    }
    else
    {
        //code
    }
}
</code>```

Now I have few queries

Can we return Boolean value true/false in HttpResponseMessage. I mean
in CreateErrorResponse .

What is best way to check if user get updated or not ?

Can this code be improved?

答:
1) Can we return Boolean value true/false in HttpResponseMessage. I mean in CreateErrorResponse?

Technically you have following options

a) CreateErrorResponse will create HttpError object.

```<code>return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, false.ToString());
</code>```

Serialized response will be

```<code> {"Message":"False"}
</code>```

b) Or you can

```<code>return Request.CreateResponse(HttpStatusCode.InternalServerError, false.ToString());
</code>```

Response will be

```<code>"False"
</code>```

2) What is best way to check if user get updated or not ?
3) Can this code be improved?

In my opinion, it is best to align your api with REST recommendation
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Generally REST post api returns the resource created. Ex-

```<code>[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{
    try
    {
        // Validate user
        // if invalid request return Request.CreateErrorResponse(HttpStatusCode.BadRequest, validationErrorMessage);

        //Code to change user
        user.Update();
        return Request.CreateResponse(HttpStatusCode.Created, user);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}
</code>```

If response is anything except 201, that means error creating user. Error details should be in message.

Title: Return bool value from web api

Body:
I am using Web Api 2 to create 1 user. Below is code

[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{
    try
    {
        //Code
        .
        .
        user.Update();
        return Request.CreateResponse(HttpStatusCode.OK, true);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}

I trying to call this method from code behind like

using (HttpClient client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:65486/");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var response = client.PostAsJsonAsync("api/Stock/UpdateUserData", userObject).Result;

    if (response.IsSuccessStatusCode)
    {
        using (HttpContent content = response.Content)
        {
            Task<string> result = content.ReadAsStringAsync();
            string final = result.Result;
        }
    }
    else
    {
        //code
    }
}

Now I have few queries

Can we return Boolean value true/false in HttpResponseMessage. I mean
in CreateErrorResponse .

What is best way to check if user get updated or not ?

Can this code be improved?

Body:
1) Can we return Boolean value true/false in HttpResponseMessage. I mean in CreateErrorResponse?

Technically you have following options

a) CreateErrorResponse will create HttpError object.

return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, false.ToString());

Serialized response will be

 {"Message":"False"}

b) Or you can

return Request.CreateResponse(HttpStatusCode.InternalServerError, false.ToString());

Response will be

"False"

2) What is best way to check if user get updated or not ?
3) Can this code be improved?

In my opinion, it is best to align your api with REST recommendation
http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Generally REST post api returns the resource created. Ex-

[HttpPost]
public HttpResponseMessage UpdateUserData(User user)
{
    try
    {
        // Validate user
        // if invalid request return Request.CreateErrorResponse(HttpStatusCode.BadRequest, validationErrorMessage);

        //Code to change user
        user.Update();
        return Request.CreateResponse(HttpStatusCode.Created, user);
    }
    catch (Exception ex)
    {
        ExceptionLogger.LogException(ex);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "error");
    }
}

If response is anything except 201, that means error creating user. Error details should be in message.


问:
A Typical Issue with login using Zend_Form
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

```<code>Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)
</code>```

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?

答:
You need to set the URL of your action like this:

If you're on the view

```<code>$this->form->setAction($this->url(array('params here or'), 'the route name'));
</code>```

If you're on the controller

```<code>$form->setAction($this->_helper->url(array('params or...'), 'the route name'));
</code>```

or

```<code>$form->setAction($this->getRequest()->getBaseUrl() . '/index/login');
</code>```

See this related question:

Zend Form SetAction Using Named Routes

Body:
Iam facing a typical issue with a form submit using Zend framework. Basically I have written a simple code to login a user, but this came out of the blue.

The code to show the form is pretty standard

$loginform = new Application_Form_Login();
        $loginform->setMethod('post');
        $loginform->setAction('login');
        $this->view->form = $loginform;

When I use my home page url as - http://localhost.ruin.com/public/

I get an exception

Page not found
Exception information:

Message: Invalid controller specified (login)
Stack trace:

#0 C:\domains\ruin\library\Zend\Controller\Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 C:\domains\ruin\library\Zend\Application\Bootstrap\Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 C:\domains\ruin\library\Zend\Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 C:\domains\ruin\public\index.php(27): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'login',
  'action' => 'index',
  'module' => 'default',
  'username' => 'fsdf',
  'password' => 'fdsf',
  'submit' => 'submit',
)

However if I use the base url as http://localhost.ruin.com/public/index/ , the same code works perfectly.

I also know that its due to the fact that in first url the zend router is messing up the index controller with login since its not able to append the login action to the default index controller.

Do you guys think this is by design of Zend Framework and I shall have to forcefully send my users to this url
http://localhost.ruin.com/public/index/ whenever they hit the home page or is there a way I can make my code work with
http://localhost.ruin.com/public/

Any suggestions?

Body:
You need to set the URL of your action like this:

If you're on the view

$this->form->setAction($this->url(array('params here or'), 'the route name'));

If you're on the controller

$form->setAction($this->_helper->url(array('params or...'), 'the route name'));

or

$form->setAction($this->getRequest()->getBaseUrl() . '/index/login');

See this related question:

Zend Form SetAction Using Named Routes


问:
jQuery - Calculate sum of two numbers inside one td and display inside new td?
Hello Stackoverflowers,

I have this code:

```<code>    <table class="table">
        <tbody>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">12-11      </a></td>
            </tr>
            <tr>
                <td><a href="#">New thing</a></td>
                <td>2017/06/04 08:00</td>
                <td><a href="#">One Thing</a><span>Another thing</span></td>
                <td class="random">R</td>
                <td><a href="#">22-23      </a></td>
            </tr>
        </tbody>
    </table>
</code>```

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

```<code><table class="table">
    <tbody>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">12-11      </a></td>
            <td>[ 23 ]</td>
        </tr>
        <tr>
            <td><a href="#">New thing</a></td>
            <td>2017/06/04 08:00</td>
            <td><a href="#">One Thing</a><span>Another thing</span></td>
            <td class="random">R</td>
            <td><a href="#">22-23      </a></td>
            <td>[ 45 ]</td>
        </tr>
    </tbody>
</table>
</code>```

thank you in advance.

答:
use .each() to iterate all tr

use .text() to get the text

use .append() to write new td at last of tr

Use parseInt() or parseFloat() or Number() depending on needs

//iterate all tr in table
$('.table tr').each(function() {
  // using this context to point to each tr get the last td using .last().
  // use .text() to get its text
  var tdval = $(this).find('td').last().text();

  // use split and get the first value using index 0
  var first = parseInt(tdval.split('-')[0])

  // use split and get the second value using index 1
  var second = parseInt(tdval.split('-')[1])

  // use append to append the td where you will show the sum of two number.
  // append will put the td in last
  $(this).append("" + (first + second) + "	")
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
  <tbody>
    <tr>
      <td>New thing</td>
      <td>2017/06/04 08:00</td>
      <td>One Thing<span>Another thing</span></td>
      <td class="random">R</td>
      <td>12-11      </td>
    </tr>
    <tr>
      <td>New thing</td>
      <td>2017/06/04 08:00</td>
      <td>One Thing<span>Another thing</span></td>
      <td class="random">R</td>
      <td>22-23      </td>
    </tr>
  </tbody>
</table></code>```

Body:
Hello Stackoverflowers,

I have this code:

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                12-11

                New thing
                2017/06/04 08:00
                One ThingAnother thing
                R
                22-23

In the result I want to use jQuery to get a sum of numbers inside last table TD and display it into new TD. Like in the following code:

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            12-11
            [ 23 ]

            New thing
            2017/06/04 08:00
            One ThingAnother thing
            R
            22-23
            [ 45 ]

thank you in advance.

Body:
use .each() to iterate all tr

use .text() to get the text

use .append() to write new td at last of tr

Use parseInt() or parseFloat() or Number() depending on needs

//iterate all tr in table
$('.table tr').each(function() {
  // using this context to point to each tr get the last td using .last().
  // use .text() to get its text
  var tdval = $(this).find('td').last().text();

  // use split and get the first value using index 0
  var first = parseInt(tdval.split('-')[0])

  // use split and get the second value using index 1
  var second = parseInt(tdval.split('-')[1])

  // use append to append the td where you will show the sum of two number.
  // append will put the td in last
  $(this).append("<td>" + (first + second) + "</td>")
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
  <tbody>
    <tr>
      <td><a href="#">New thing</a></td>
      <td>2017/06/04 08:00</td>
      <td><a href="#">One Thing</a><span>Another thing</span></td>
      <td class="random">R</td>
      <td><a href="#">12-11      </a></td>
    </tr>
    <tr>
      <td><a href="#">New thing</a></td>
      <td>2017/06/04 08:00</td>
      <td><a href="#">One Thing</a><span>Another thing</span></td>
      <td class="random">R</td>
      <td><a href="#">22-23      </a></td>
    </tr>
  </tbody>
</table>


问:
Call to a member function query() on a non-object error in PDO
This is my sql connection code

```<code>$config['db'] = array('host' => 'localhost', 'username' =>  'root', 'password' => '', 'dbname' => 'reputize');

try
{
    $db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    echo "Database connected successfully";
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}
</code>```

and this is the code i am using to fetch data from the table

```<code>$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $ptitle=$row['MetaTitle'];
    $desc=$row['MetaDisc'];
    $kwords=$row['MetaKwd'];
}
</code>```

but the error keeps on showing

Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14

I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem

答: you have an error here dbname'.$config['db']['dbname'] it should be dbname='.$config['db']['dbname']

Body:
This is my sql connection code

$config['db'] = array('host' => 'localhost', 'username' =>  'root', 'password' => '', 'dbname' => 'reputize');

try
{
    $db = new PDO('mysql:host='.$config['db']['host'].';dbname'.$config['db']['dbname'], $config['db']['username'], $config['db']['password']);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    echo "Database connected successfully";
}
catch(PDOException $e)
{
    echo $sql . "
" . $e->getMessage();
}

and this is the code i am using to fetch data from the table

$query = $db->query("select * from metaTags where filename='index'");
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    $ptitle=$row['MetaTitle'];
    $desc=$row['MetaDisc'];
    $kwords=$row['MetaKwd'];
}

but the error keeps on showing

Call to a member function query() on a non-object in C:\xampp\htdocs\template OOP\include\class\websiteClasses.php on line 14

I have tried many solutions here and on other sites as well but of no use.
Please help me out with this problem


问:
Keychain sharing between two apps
Apple has provided Generic Keychain sample which is written in Swift, I want to go ahead with Objective-C.

I have enabled keychain sharing in both the apps and on canOpenUrl I am able to invoke application B from A, now I want to share username and password from app A to app B. App ID is same for both the applications.

I have looked at various tutorials also don't want to use any third party project.
Could not came to know how to pass the parameter from app A to app B.

答:
Enable Keychain sharing:

Turn on the Keychain Sharing capability.

Select developer team

Specify Keychain group name to something meaningful (for example testKeychainG1)

Open .entitlements file and replace $(AppIdentifierPrefix) with your APP ID (for example AB123CDE45.testKeychainG1)

Accessing Keychain (Retrieve shared items):

```<code>let itemKey = "Item Key"

let keychainAccessGroupName = "AB123CDE45.testKeychainG1"

let query:[String:Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey,
    kSecReturnData as String: kCFBooleanTrue,
    kSecMatchLimit as String: kSecMatchLimitOne,
    kSecAttrAccessGroup as String: keychainAccessGroupName
]

var result: AnyObject?

let resultCodeLoad = withUnsafeMutablePointer(to: &result) {
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}

if resultCodeLoad == noErr {
    if let result = result as? Data,
        let keyValue = NSString(data: result,
                                encoding: String.Encoding.utf8.rawValue) as? String {

        // Found successfully
        print(keyValue)
    }
} else {
    print("Error: \(resultCodeLoad)")
}
</code>```

Title: Keychain sharing between two apps

Body:
Enable Keychain sharing:

Turn on the Keychain Sharing capability.

Select developer team

Specify Keychain group name to something meaningful (for example testKeychainG1)

Open .entitlements file and replace $(AppIdentifierPrefix) with your APP ID (for example AB123CDE45.testKeychainG1)

Accessing Keychain (Retrieve shared items):

let itemKey = "Item Key"

let keychainAccessGroupName = "AB123CDE45.testKeychainG1"

let query:[String:Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrAccount as String: itemKey,
    kSecReturnData as String: kCFBooleanTrue,
    kSecMatchLimit as String: kSecMatchLimitOne,
    kSecAttrAccessGroup as String: keychainAccessGroupName
]

var result: AnyObject?

let resultCodeLoad = withUnsafeMutablePointer(to: &result) {
    SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}

if resultCodeLoad == noErr {
    if let result = result as? Data,
        let keyValue = NSString(data: result,
                                encoding: String.Encoding.utf8.rawValue) as? String {

        // Found successfully
        print(keyValue)
    }
} else {
    print("Error: \(resultCodeLoad)")
}


问:
Adding Font color and No fill to a sub routine
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!</p>

```<code>Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub
</code>```

答:
You need to fully qualify the cell's object

Work with variables. See how I have used it to find the last row

Avoid the use of .Select

Is this what you are trying?

```<code>With ws
    .Columns("A:BB").EntireColumn.AutoFit
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("A2:BB" & lrow)
        .Font.Color = vbBlack
        .Interior.ColorIndex = xlNone
    End With
End Withh
</code>```

Body:
hopefully a quick fix on this one. I have a sub routine that I am using to amend the column sizes for all the sheets in a workbook which works absolutely fine but I wanted to add to this sub so that it will change the font color black for all cells within my ranges and remove any fill color from them also. I have written the code below but it doesn't seem to perform the way I want. Any ideas as to how I can correct this would be awesome!

Sub forEachWs()
Dim ws As Worksheet

'Opens new workbook for formatting
Workbooks.Open "C:\Users\XNEID\Desktop\Test MPAN Destination
Folder\Shell_MPANs_Test1.xlsx"

For Each ws In ActiveWorkbook.Worksheets
Call resizingColumns(ws)
Next

End Sub

Sub resizingColumns(ws As Worksheet)
With ws
    .Range("A1:BB1").EntireColumn.AutoFit
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Font.Color = vbBlack
    Range("A2:BB2", Range("A2:BB2").End(xlDown)).Select
    Selection.Interior.ColorIndex = xlNone

End With
End Sub

Body:
You need to fully qualify the cell's object

Work with variables. See how I have used it to find the last row

Avoid the use of .Select

Is this what you are trying?

With ws
    .Columns("A:BB").EntireColumn.AutoFit
    lrow = .Range("A" & .Rows.Count).End(xlUp).Row

    With .Range("A2:BB" & lrow)
        .Font.Color = vbBlack
        .Interior.ColorIndex = xlNone
    End With
End Withh


问:
Run a script on PythonAnywhere within a html file
I'm trying to run a python script using Flask framework.
The main goal is to:

Submit data (keyword) + click a button

Put the keyword on python script

Run it on the server

Return back a response

Request the result (Json)

Print result on html page

Some notes:

The script is a request from a third party API
The result that I want to print in the html page is just a number.

API Script:

```<code>import indicoio
indicoio.config.api_key = 'YOUR_API_KEY'

# single example
print.indicoio.sentiment("Keyword")
</code>```

After some research I found 2 solutions to my problem but I don't know how to implement the code. I'm a beginner, easy on me please.

My App.py

```<code>from flask import Flask

app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/static')

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

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

First Approach:

```<code>pip install requests
import requests
data = {"keyword":"LoremIpsum"}
r = requests.put("Request_Page_Link/",data = data )
data = r.json
print("data")
</code>```

Second Approach:

```<code>from flask import Flask, render_template
app = Flask(__name__)

@app.route('/my-link/')
def my_link():
  print 'I got clicked!'

  return 'Click.'

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

Code to handle POST and GET request:

```<code><input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">
<script>
$('#id').click(function(){

 $.ajax({
      type:'get',
      url:<YOUR SERVERSIDE PAGE URL>,
      cache:false,
      data:<if any arguments>,
      async:asynchronous,
      dataType:json, //if you want json
      success: function(data) {
        <put your custom validation here using the response from data structure >
      },
      error: function(request, status, error) {
        <put your custom code here to handle the call failure>
      }
   });
});
</script>
</code>```

Let me know if I need to add more informations. Thanks!

答:
I suggest to use fetch it's pure javascript to make the url call in js. And you can do the GET call like fetch('/my-link')

```<code>fetch('/my-link')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })
</code>```

In your view do some processing and return jsonify(dict) output/

Body:
I'm trying to run a python script using Flask framework.
The main goal is to:

Submit data (keyword) + click a button

Put the keyword on python script

Run it on the server

Return back a response

Request the result (Json)

Print result on html page

Some notes:

The script is a request from a third party API
The result that I want to print in the html page is just a number.

API Script:

import indicoio
indicoio.config.api_key = 'YOUR_API_KEY'

# single example
print.indicoio.sentiment("Keyword")

After some research I found 2 solutions to my problem but I don't know how to implement the code. I'm a beginner, easy on me please.

My App.py

from flask import Flask

app = Flask(__name__, static_url_path="/static", static_folder='/home/dubspher/mysite/static')

@app.route('/')
def static_file():
    return app.send_static_file('index.html')

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

First Approach:

pip install requests
import requests
data = {"keyword":"LoremIpsum"}
r = requests.put("Request_Page_Link/",data = data )
data = r.json
print("data")

Second Approach:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/my-link/')
def my_link():
  print 'I got clicked!'

  return 'Click.'

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

Code to handle POST and GET request:

<input type="text" name="name" id="name">
<button type="button" id="home" onclick="validate()" value="checkvalue">

Let me know if I need to add more informations. Thanks!

Body:
I suggest to use fetch it's pure javascript to make the url call in js. And you can do the GET call like fetch('/my-link')

fetch('/my-link')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

In your view do some processing and return jsonify(dict) output/


问:
How can I declare an empty variable?
Here's my code:

```<code>private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }
</code>```

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?

答:
string y = null;

var x = y;

this will work

Title: How can I declare an empty variable?

Body:
Here's my code:

private void button1_Click(object sender, EventArgs e)
    {
        var api = RiotApi.GetInstance("KEY");

        try
        {
            var game = api.GetCurrentGame(RiotSharp.Platform.EUW1, 79200188);
        }

        catch (RiotSharpException ex)
        {
            throw;
        }

        foreach (var player in game.Participants) // Can't find game variable
        {

        }
    }

I can't call game.Participants in my foreach loop because i initialize game inside the try statement. I can't initialize game outside the try statement either though because to do that i would have to give it a temporary value and I don't know what kind of value it will be.

Is there a way to declare a variable as null? Or is there potentially a different way to solve this?