问:
Conditional Statements are not Executing?
I have written a Program that adds and multiples first ten Natural Numbers on user input. I have made two separate functions for Addition and Multiplication and called both functions in a while loop using if-else statement in it. But it is taking input from user but not performing any further operations. Code is Below:

```<code>print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=input()

plus=0
mul=1

for a2 in range(11):
    if a2>0:
        plus=plus + a2
        mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
    print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
        add()
    elif user == 2:
        product()
</code>```

Output:

答:
user=input() returns a string.

So that in your if-statement you should compare with a string literal '1'.

Alternatively write user=int(input()) to cast input() value to int. But here exception can be thrown if you enter not valid int.

Body:
I have written a Program that adds and multiples first ten Natural Numbers on user input. I have made two separate functions for Addition and Multiplication and called both functions in a while loop using if-else statement in it. But it is taking input from user but not performing any further operations. Code is Below:

print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=input()

plus=0
mul=1

for a2 in range(11):
    if a2>0:
        plus=plus + a2
        mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
    print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
        add()
    elif user == 2:
        product()

Output:


来源: stackexchange

问:
EACCES (Permission denied) Android
GOAL: To perform compression on image/content, retrieved through external sources (ex: sd-card, internal or drive) using intent.

I was able to get actual path for the retrieved content, but when i am trying to compress it using compression library (zetbaitsu/Compressor) its throwing error

open failed: EACCES (Permission denied).

I have cross checked my permissions and tried multiple way to confirm permission access, still its throwing error.

Here is my function:

```<code>void handleSendImage(Intent intent) {
    try {
        Uri imageUri =  intent.getParcelableExtra(Intent.EXTRA_STREAM);
        Log.d(TAG, "handleSendImage: " + imageUri.toString());
        File imageFile = new File(getFilePath(this, imageUri));
        Log.d(TAG, "handleSendImage: " + Uri.fromFile(imageFile));
        File compressedFile = new Compressor(this).compressToFile(imageFile);

    } catch (Exception e) {
        Log.e(TAG, "handleSendImage: " + e.getMessage());
    }
}
</code>```

Here are my logs outputs:

```<code>handleSendImage: content://com.android.providers.media.documents/document/image%3A30

handleSendImage: file:///storage/emulated/0/Download/4c568534307d605ed94878dc06d933ee.jpg

handleSendImage: /storage/emulated/0/Download/4c568534307d605ed94878dc06d933ee.jpg: open failed: EACCES (Permission denied)
</code>```

答:
android:requestLegacyExternalStorage="true"

Add this in Manifest file but this won't work in android 11

ContentLicense: CC BY-SA 4.0

Title: EACCES (Permission denied) Android

Body:
GOAL: To perform compression on image/content, retrieved through external sources (ex: sd-card, internal or drive) using intent.

I was able to get actual path for the retrieved content, but when i am trying to compress it using compression library (zetbaitsu/Compressor) its throwing error

open failed: EACCES (Permission denied).

I have cross checked my permissions and tried multiple way to confirm permission access, still its throwing error.

Here is my function:

void handleSendImage(Intent intent) {
    try {
        Uri imageUri =  intent.getParcelableExtra(Intent.EXTRA_STREAM);
        Log.d(TAG, "handleSendImage: " + imageUri.toString());
        File imageFile = new File(getFilePath(this, imageUri));
        Log.d(TAG, "handleSendImage: " + Uri.fromFile(imageFile));
        File compressedFile = new Compressor(this).compressToFile(imageFile);

    } catch (Exception e) {
        Log.e(TAG, "handleSendImage: " + e.getMessage());
    }
}

Here are my logs outputs:

handleSendImage: content://com.android.providers.media.documents/document/image%3A30

handleSendImage: file:///storage/emulated/0/Download/4c568534307d605ed94878dc06d933ee.jpg

handleSendImage: /storage/emulated/0/Download/4c568534307d605ed94878dc06d933ee.jpg: open failed: EACCES (Permission denied)


问:
How to get all Saturdays in year with format as "Saturday, dd.MM.YYYY"?
I want to add all Saturdays of 2020/2021 into an object like following:</p>

```<code>saturdays = {
   "Saturday, 22.02.2020" : "Saturday, 22.02.2020" ,
   "Saturday, 29.02.2020" : "Saturday, 29.02.2020"
}
</code>```

答:
1) First find out number of days in year (daysInYear method)

2) Find out first saturday date (firstSatDate method)

3) Go over for loop from first saturday to end of the year day and build the date string requirement format.

const daysInYear = year =>
  (new Date(year + 1, 0, 1) - new Date(year, 0, 1)) / (24 * 60 * 60 * 1000);

const firstSatDate = year => {
  const week_day = new Date(year, 0, 1).getDay();
  const satDate = new Date(year, 0, 7 - week_day);
  return satDate.getDate();
};

const getSaturdays = year => {
  const yearDays = daysInYear(year);
  const first = firstSatDate(year);
  const saturdays = {};
  for (let day = first; day <= yearDays; day = day + 7) {
    const date = new Date(year, 0, day);
    const day_str = String(date.getDate()).padStart(2, '0');
    const month_str = String(date.getMonth() + 1).padStart(2, '0');
    const date_str = `Saturday, ${day_str}.${month_str}.${date.getFullYear()}`;
    saturdays[date_str] = date_str;
  }
  return saturdays;
};

console.log(getSaturdays(2020));
console.log(getSaturdays(2021));```

Body:
I want to add all Saturdays of 2020/2021 into an object like following:

saturdays = {
   "Saturday, 22.02.2020" : "Saturday, 22.02.2020" ,
   "Saturday, 29.02.2020" : "Saturday, 29.02.2020"
}


问:
How to use dynamic SQL for updating the query with multiple conditions?
I am trying to execute below procedure:

```<code>ALTER PROCEDURE UFP_PROCEDURE
    (@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

    SET @sql = 'UPDATE' + @table_name1 +
               'SET' + QUOTENAME(operation) +  '=' + 'U' + 'where' + QUOTENAME(last_updated_time) + 'IS NOT NULL' + 'AND' + QUOTENAME(last_created_date) + 'IS NOT NULL' + 'AND'  + QUOTENAME(delete_flag) + 'IS NULL'

    EXEC(@SQL)
END
</code>```

I am not getting how to use dynamic SQL with all the single quotes and the columns which are in QUOTENAME is giving as invalid columns.

Here @table_name1 is the table name which I am passing from Azure pipeline.

If anyone can give solution..... it would be very helpful.

答:
```<code>ALTER PROCEDURE UFP_PROCEDURE
    (@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

    SET @sql = 'UPDATE ' + QUOTENAME(@table_name1) +
               'SET operation= ''U'' where last_updated_time IS NOT NULL AND last_created_date IS NOT NULL AND delete_flag IS NULL'

    EXEC(@SQL)
END
</code>```

Body:
I am trying to execute below procedure:

ALTER PROCEDURE UFP_PROCEDURE
    (@table_name1 varchar(100))
AS
BEGIN
    DECLARE @sql varchar(200);

    SET @sql = 'UPDATE' + @table_name1 +
               'SET' + QUOTENAME(operation) +  '=' + 'U' + 'where' + QUOTENAME(last_updated_time) + 'IS NOT NULL' + 'AND' + QUOTENAME(last_created_date) + 'IS NOT NULL' + 'AND'  + QUOTENAME(delete_flag) + 'IS NULL'

    EXEC(@SQL)
END

I am not getting how to use dynamic SQL with all the single quotes and the columns which are in QUOTENAME is giving as invalid columns.

Here @table_name1 is the table name which I am passing from Azure pipeline.

If anyone can give solution..... it would be very helpful.


问:
Django + Heroku: KeyError when accessing Heroku's config vars
I'm trying to get all the environment variables from Heroku's config vars by following this page. So in settings.py I wrote:

import os

from dotenv import load_dotenv
from boto.s3.connection import S3Connection
# ...
load_dotenv(verbose=True)
# ...
s3 = S3Connection(os.environ['SECRET_KEY'],
                  os.environ['DATABASE_URL'],
                  os.environ['SENDGRID_API_KEY'])
SECRET_KEY = os.getenv('SECRET_KEY')
# ...

if os.environ.get('DEBUG') is None:
    DEBUG = False
else:
    DEBUG = True
# ...
# Sending emails
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# ...
```

<p>I want to have a local <code>.env</code> that contains those vars, and use Heroku's config vars in production. But when I deploy, I get an <code>Application Error</code>, and this is the result of <code>heroku logs --tail</code>:</p>

```2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/smart_toilet_system/settings.py", line 34, in <module>
2020-02-19T04:09:27.730183+00:00 app[web.1]: os.environ['SENDGRID_API_KEY'])
2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/s3/connection.py", line 194, in __init__
2020-02-19T04:09:27.730184+00:00 app[web.1]: validate_certs=validate_certs, profile_name=profile_name)
2020-02-19T04:09:27.730184+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/connection.py", line 502, in __init__
2020-02-19T04:09:27.730185+00:00 app[web.1]: self.port = PORTS_BY_SECURITY[is_secure]
2020-02-19T04:09:27.730185+00:00 app[web.1]: KeyError: '<SENDGRID_API_KEY>'
2020-02-19T04:09:27.730911+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-02-19T04:09:27.838786+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Shutting down: Master
2020-02-19T04:09:27.839030+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-02-19T04:09:28.081341+00:00 heroku[web.1]: State changed from up to crashed
2020-02-19T04:09:28.062132+00:00 heroku[web.1]: Process exited with status 3
```

What is causing this error? Is it to do with escaping special characters?

答:
I think you are not able to access them because they are not in that environment(it means that they are not in your normal environment).
For accessing those .env config variables you can use python-decouple(install it) and access those variable like this:

```<code>from decouple import config
s3 = S3Connection(config('SECRET_KEY'),
              config('DATABASE_URL'),
              config('SENDGRID_API_KEY'))
</code>```

I hope this will woek for you

Body:
I'm trying to get all the environment variables from Heroku's config vars by following this page. So in settings.py I wrote:

import os

from dotenv import load_dotenv
from boto.s3.connection import S3Connection
# ...
load_dotenv(verbose=True)
# ...
s3 = S3Connection(os.environ['SECRET_KEY'],
                  os.environ['DATABASE_URL'],
                  os.environ['SENDGRID_API_KEY'])
SECRET_KEY = os.getenv('SECRET_KEY')
# ...

if os.environ.get('DEBUG') is None:
    DEBUG = False
else:
    DEBUG = True
# ...
# Sending emails
SENDGRID_API_KEY = os.getenv('SENDGRID_API_KEY')

EMAIL_HOST = 'smtp.sendgrid.net'
EMAIL_HOST_USER = 'apikey'
EMAIL_HOST_PASSWORD = SENDGRID_API_KEY
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# ...

I want to have a local .env that contains those vars, and use Heroku's config vars in production. But when I deploy, I get an Application Error, and this is the result of heroku logs --tail:

2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/smart_toilet_system/settings.py", line 34, in <module>
2020-02-19T04:09:27.730183+00:00 app[web.1]: os.environ['SENDGRID_API_KEY'])
2020-02-19T04:09:27.730183+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/s3/connection.py", line 194, in __init__
2020-02-19T04:09:27.730184+00:00 app[web.1]: validate_certs=validate_certs, profile_name=profile_name)
2020-02-19T04:09:27.730184+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.7/site-packages/boto/connection.py", line 502, in __init__
2020-02-19T04:09:27.730185+00:00 app[web.1]: self.port = PORTS_BY_SECURITY[is_secure]
2020-02-19T04:09:27.730185+00:00 app[web.1]: KeyError: '<SENDGRID_API_KEY>'
2020-02-19T04:09:27.730911+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [10] [INFO] Worker exiting (pid: 10)
2020-02-19T04:09:27.838786+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Shutting down: Master
2020-02-19T04:09:27.839030+00:00 app[web.1]: [2020-02-19 04:09:27 +0000] [4] [INFO] Reason: Worker failed to boot.
2020-02-19T04:09:28.081341+00:00 heroku[web.1]: State changed from up to crashed
2020-02-19T04:09:28.062132+00:00 heroku[web.1]: Process exited with status 3

What is causing this error? Is it to do with escaping special characters?

Body:
I think you are not able to access them because they are not in that environment(it means that they are not in your normal environment).
For accessing those .env config variables you can use python-decouple(install it) and access those variable like this:

from decouple import config
s3 = S3Connection(config('SECRET_KEY'),
              config('DATABASE_URL'),
              config('SENDGRID_API_KEY'))

I hope this will woek for you


问:
Regex to Filter string with unicode characters and emojis for java
I'm developing a Spring boot chat application. How can I create a regex to achieve followings,

Remove special characters

remove newlines tabs etc..

Accept Unicode characters

Accept for emojis

further,
DB tables CHARACTER SET utf8mb4 and COLLATE utf8mb4_bin.

答:
Remove special characters

```<code>s = s.replaceAll("[\\p{P}\\p{S}]", "")
</code>```

remove newlines tabs etc..

```<code>s = s.replaceAll("[\\p{C}\\p{Zl}\\p{Zp}]", "")
</code>```

Accept Unicode characters

Java already does this.

Accept for emojis

Emojis are Unicode characters, so Java already does this.

All-in-all:

```<code>s = s.replaceAll("[\\p{P}\\p{S}\\p{C}\\p{Zl}\\p{Zp}]", "")
</code>```

For list of Unicode Categories and the Characters in each Category, see Unicode Character Categories.

With the above regex, the following categories are retained: L (Letter), M (Mark), N (Number), Zs (Separator, Space).

Body:
Remove special characters

s = s.replaceAll("[\\p{P}\\p{S}]", "")

remove newlines tabs etc..

s = s.replaceAll("[\\p{C}\\p{Zl}\\p{Zp}]", "")

Accept Unicode characters

Java already does this.

Accept for emojis

Emojis are Unicode characters, so Java already does this.

All-in-all:

s = s.replaceAll("[\\p{P}\\p{S}\\p{C}\\p{Zl}\\p{Zp}]", "")

For list of Unicode Categories and the Characters in each Category, see Unicode Character Categories.

With the above regex, the following categories are retained: L (Letter), M (Mark), N (Number), Zs (Separator, Space).


问:
Django mptt recursetree with get_cached_trees in template
In View:

```<code>context['categories'] =  = models.Category.objects.all().get_cached_trees()
</code>```

In template:

```<code>{% load mptt_tags %}
<ul>
    {% recursetree categories %}
        <li>
            {{ node.name }}
            {% if not node.is_leaf_node %}
                <ul class="children">
                    {{ children }}
                </ul>
            {% endif %}
        </li>
    {% endrecursetree %}
</ul>
</code>```

As a result, it renders only first level of queryset. If remove get_cached_trees it renders all tree. How to render all tree with get_cached_trees?

答:
You don't actually need to call get_cached_trees() in this situation because recursetree already does the caching for you.

From the documentation:

```<code>Iterates over the nodes in the tree, and renders the contained block for each node.
This tag will recursively render children into the template variable {{ children }}.
Only one database query is required (children are cached for the whole tree)
</code>```

Body:
In View:

context['categories'] =  = models.Category.objects.all().get_cached_trees()

In template:

{% load mptt_tags %}

    {% recursetree categories %}

            {{ node.name }}
            {% if not node.is_leaf_node %}

                    {{ children }}

            {% endif %}

    {% endrecursetree %}

As a result, it renders only first level of queryset. If remove get_cached_trees it renders all tree. How to render all tree with get_cached_trees?

Body:
You don't actually need to call get_cached_trees() in this situation because recursetree already does the caching for you.

From the documentation:

Iterates over the nodes in the tree, and renders the contained block for each node.
This tag will recursively render children into the template variable {{ children }}.
Only one database query is required (children are cached for the whole tree)


问:
PHP or Perl PDF Library that provides DRM with offline expiry/sharing prevention
Does anybody know of a PDF library that provides DRM functionality to cover offline expiry and sharing prevention?  Needs to be PHP or Perl based.</p>

答:
I remember doing some research on this a year or so back.  A lot of the DRM features provided in the PDF format are vendor specific extensions.  The main DRM features are locked to the Adobe Acrobat Reader by a key/certificate embedded into the documents themselves.  When I researched it, the only software capable of generating this key/certificate was Adobe's own.  A quick look suggests this hasn't changed.

In summary, I don't think there's any software out there, besides Adobes (LiveCycle for example), which can unlock these features for you.

ContentLicense: CC BY-SA 3.0


问:
cannot get the relationship data in laravel
this is my function

```<code>public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

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

newproject model

```<code>public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }
</code>```

it always getting the error

```<code>message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
</code>```

please help my to solve my problem please.

答:
found the problem in my model

in user model

```<code>public function newproject()
    {
        return $this->belongsTo(Newproject::class,'user_id','id');
    }
</code>```

in newproject model

```<code>public function user()
    {
        return $this->hasOne(User::class,'id' , 'user_id');
    }
</code>```

thanks all

Body:
this is my function

public function show($id)
    {
        $newproject = Newproject::find($id);
        $data = [

            'name' => $newproject->user->name
        ];

        return $data;
    }

newproject model

public function user()
    {
        return $this->hasOne(User::class,'user_id' ,'id');
    }

it always getting the error

message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669

please help my to solve my problem please.

Body:
found the problem in my model

in user model

public function newproject()
    {
        return $this->belongsTo(Newproject::class,'user_id','id');
    }

in newproject model

public function user()
    {
        return $this->hasOne(User::class,'id' , 'user_id');
    }

thanks all


Title: Fit Path to SVG

Body:
I have a SVG from fontawesome, but there is space around the path content inside the SVG window.

<svg aria-hidden="true" focusable="false" data-prefix="fab" data-icon="youtube" class="svg-inline--fa fa-youtube fa-w-18" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
<path fill="currentColor" d="M549.655 124.083c-6.281-23.65-24.787-42.276-48.284-48.597C458.781 64 288 64 288 64S117.22 64 74.629 75.486c-23.497 6.322-42.003 24.947-48.284 48.597-11.412 42.867-11.412 132.305-11.412 132.305s0 89.438 11.412 132.305c6.281 23.65 24.787 41.5 48.284 47.821C117.22 448 288 448 288 448s170.78 0 213.371-11.486c23.497-6.321 42.003-24.171 48.284-47.821 11.412-42.867 11.412-132.305 11.412-132.305s0-89.438-11.412-132.305zm-317.51 213.508V175.185l142.739 81.205-142.739 81.201z"></path>
</svg>

How would I remove this space and have the path edges touch the SVG window?
CSS preferable but open to other solutions.

Body:
I haven't found a CSS solution, but you can do it in JavaScript by setting the SVG's view box dimensions to those of the bounding box:

const svg = document.querySelector("svg");
const {x, y, width, height} = svg.getBBox();

svg.setAttribute("viewBox", `${x} ${y} ${width} ${height}`);

body {
  margin: 0;
  padding: 0;
}

<svg aria-hidden="true" focusable="false" class="svg-inline--fa fa-instagram fa-w-14" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512">
<path
fill="currentColor"
d="M224.1 141c-63.6 0-114.9 51.3-114.9 114.9s51.3 114.9 114.9 114.9S339 319.5 339 255.9 287.7 141 224.1 141zm0 189.6c-41.1 0-74.7-33.5-74.7-74.7s33.5-74.7 74.7-74.7 74.7 33.5 74.7 74.7-33.6 74.7-74.7 74.7zm146.4-194.3c0 14.9-12 26.8-26.8 26.8-14.9 0-26.8-12-26.8-26.8s12-26.8 26.8-26.8 26.8 12 26.8 26.8zm76.1 27.2c-1.7-35.9-9.9-67.7-36.2-93.9-26.2-26.2-58-34.4-93.9-36.2-37-2.1-147.9-2.1-184.9 0-35.8 1.7-67.6 9.9-93.9 36.1s-34.4 58-36.2 93.9c-2.1 37-2.1 147.9 0 184.9 1.7 35.9 9.9 67.7 36.2 93.9s58 34.4 93.9 36.2c37 2.1 147.9 2.1 184.9 0 35.9-1.7 67.7-9.9 93.9-36.2 26.2-26.2 34.4-58 36.2-93.9 2.1-37 2.1-147.8 0-184.8zM398.8 388c-7.8 19.6-22.9 34.7-42.6 42.6-29.5 11.7-99.5 9-132.1 9s-102.7 2.6-132.1-9c-19.6-7.8-34.7-22.9-42.6-42.6-11.7-29.5-9-99.5-9-132.1s-2.6-102.7 9-132.1c7.8-19.6 22.9-34.7 42.6-42.6 29.5-11.7 99.5-9 132.1-9s102.7-2.6 132.1 9c19.6 7.8 34.7 22.9 42.6 42.6 11.7 29.5 9 99.5 9 132.1s2.7 102.7-9 132.1z">
</path>
</svg>


问:
Send HTTP Post request in Xamarin Forms C#
Before I start, I would like to say that I have googled solutions to this problem but have either not understood them (I am a newbie) or they do not work.

What I want to do is send JSON data to a REST API on localhost:8000, in this format:

```<code>{
    "username" : "myusername",
    "password" : "mypass"
}
</code>```

Then, I expect a response which holds a string token, like the following,

```<code>{
    "token" : "rgh2ghgdsfds"
}
</code>```

How do send the json data and then parse the token from the response?
I have seen synchronous methods of doing this but for some reason, they do not work (or simply because I do not know what namespace it is in). If you apply an async way of doing this, could you please explain to me how it works?

Thanks in advance.

答:
try this code.</p>

```<code>HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(APIAddress); // Insert your API URL Address here.
            string serializedObject = JsonConvert.SerializeObject(data);
            HttpContent contentPost = new StringContent(serializedObject, Encoding.UTF8, "application/json");
            try
            {
                HttpResponseMessage response = await httpClient.PostAsync(ControllerWithMethod, contentPost);
                return response;
            }
            catch (TaskCanceledException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage();
            }
</code>```

Body:
Before I start, I would like to say that I have googled solutions to this problem but have either not understood them (I am a newbie) or they do not work.

What I want to do is send JSON data to a REST API on localhost:8000, in this format:

{
    "username" : "myusername",
    "password" : "mypass"
}

Then, I expect a response which holds a string token, like the following,

{
    "token" : "rgh2ghgdsfds"
}

How do send the json data and then parse the token from the response?
I have seen synchronous methods of doing this but for some reason, they do not work (or simply because I do not know what namespace it is in). If you apply an async way of doing this, could you please explain to me how it works?

Thanks in advance.

Body:
try this code.

HttpClient httpClient = new HttpClient();

            httpClient.BaseAddress = new Uri(APIAddress); // Insert your API URL Address here.
            string serializedObject = JsonConvert.SerializeObject(data);
            HttpContent contentPost = new StringContent(serializedObject, Encoding.UTF8, "application/json");
            try
            {
                HttpResponseMessage response = await httpClient.PostAsync(ControllerWithMethod, contentPost);
                return response;
            }
            catch (TaskCanceledException ex)
            {
                throw;
            }
            catch (Exception ex)
            {
                return new HttpResponseMessage();
            }


问:
How to view GoogleDrive changes in StackDriver
I've just started using StackDriver and I'm failing to get GoogleDrive logs (or any GSuite logs for that matter).

From the documentation (https://cloud.google.com/resource-manager/docs/audit-logging) I understand that I need to read the Audit Logs in SD, but I'm not sure how to connect them to SD.

答:
I think a less granular approach is to use the GSuite Exporter (link below) to export user activity events from the Admin SDK Reports API into StackDriver. You'll need to grant extra IAM roles for the service account to have visibility, but it is possible.

GSuite-Exporter: https://github.com/GoogleCloudPlatform/professional-services/tree/master/tools/gsuite-exporter


问:
bottom sheet scrolling issue
I'm using BottomSheet (bs) and and google maps I need to make the bs and googlemaps fit in sizes

Then when the bs is expanded the map will show in small size and when the bs is collapsed the map will be displayed in original size

thank you in advance

here is the class & layouts

```<code> ConstraintLayout linearLayoutBSheet = view.findViewById(R.id.bottomSheet);
    bottomSheetBehavior = BottomSheetBehavior.from(linearLayoutBSheet);
    bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            switch (newState){
                case BottomSheetBehavior.STATE_COLLAPSED:

                    break;
                case BottomSheetBehavior.STATE_DRAGGING:

                    break;

                case BottomSheetBehavior.STATE_EXPANDED:

                    break;

            }
        }
</code>```

map layout

```<code><androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".z_version2.MenuFragments.UnitMap.view.UnitMapViewImpl">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <com.google.android.gms.maps.MapView
            android:id="@+id/map"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar_maps" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <include
        layout="@layout/bottom_sheet_map"
        android:visibility="visible" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

bottom sheet layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:background="@drawable/round_bottom_shet"
    app:behavior_peekHeight="150dp"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nestedScrollViewVehiclesList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
</code>```

答: load googlemap, after successfully changed bottomsheet.</p>

Title: bottom sheet scrolling issue

Body:
I'm using BottomSheet (bs) and and google maps I need to make the bs and googlemaps fit in sizes

Then when the bs is expanded the map will show in small size and when the bs is collapsed the map will be displayed in original size

thank you in advance

here is the class & layouts

 ConstraintLayout linearLayoutBSheet = view.findViewById(R.id.bottomSheet);
    bottomSheetBehavior = BottomSheetBehavior.from(linearLayoutBSheet);
    bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
        @Override
        public void onStateChanged(@NonNull View bottomSheet, int newState) {
            switch (newState){
                case BottomSheetBehavior.STATE_COLLAPSED:

                    break;
                case BottomSheetBehavior.STATE_DRAGGING:

                    break;

                case BottomSheetBehavior.STATE_EXPANDED:

                    break;

            }
        }

map layout

<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".z_version2.MenuFragments.UnitMap.view.UnitMapViewImpl">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/constraintMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white">

        <com.google.android.gms.maps.MapView
            android:id="@+id/map"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@id/toolbar_maps" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <include
        layout="@layout/bottom_sheet_map"
        android:visibility="visible" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

bottom sheet layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/bottomSheet"
    android:layout_width="match_parent"
    android:layout_height="400dp"
    android:background="@drawable/round_bottom_shet"
    app:behavior_peekHeight="150dp"
    app:layout_behavior="@string/bottom_sheet_behavior">

    <androidx.core.widget.NestedScrollView
        android:id="@+id/nestedScrollViewVehiclesList"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="20dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:visibility="visible"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


问:
Reading Excel file dynamically in Python
I am trying to read an excel which has some blank rows as well as columns. The process becomes more complicated as it has some junk values before the header as well.

Currently, I am hardcoding a column name to extract the table.  This has two drawbacks what if the column is not present in the table and what if the column name repeats in the column value. Is there a way to dynamically write a program that automatically detects the table header and reads the table?

snippet of the code:

```<code>raw_data = pd.read_excel('test_data1.xlsx','Sheet8',header=None)

data_duplicate = pd.DataFrame()

for row in range(raw_data.shape[0]):
    for col in range(raw_data.shape[1]):
        if raw_data.iloc[row,col] == 'Currency':
            data_duplicate = raw_data.iloc[(row+1):].reset_index(drop=True)
            data_duplicate.columns = list(raw_data.iloc[row])
            break
data_duplicate.dropna(axis=1, how='all',inplace=True)
data_duplicate

</code>```

Also, the number of bank rows + garbage rows before the header is not fixed.

答:
Here's my way: You can drop all rows and all columns containing Nan

```<code>data = pd.read_excel('test.xlsx')
data = data.dropna(how='all', axis = 1)
data = data.dropna(how='all', axis = 0)
data = data.reset_index(drop = True)
</code>```

better if you put it into a function if you need to open multiple DataFrame in the same code:

```<code>data = pd.read_excel('test.xlsx')

def remove_nans(df):
    x = df.dropna(how = 'all', axis = 1)
    x = x.dropna(how = 'all', axis = 0)
    x = x.reset_index(drop = True)
    return x

df = remove_nans(data)
print(df)
</code>```

Body:
I am trying to read an excel which has some blank rows as well as columns. The process becomes more complicated as it has some junk values before the header as well.

Currently, I am hardcoding a column name to extract the table.  This has two drawbacks what if the column is not present in the table and what if the column name repeats in the column value. Is there a way to dynamically write a program that automatically detects the table header and reads the table?

snippet of the code:

raw_data = pd.read_excel('test_data1.xlsx','Sheet8',header=None)

data_duplicate = pd.DataFrame()

for row in range(raw_data.shape[0]):
    for col in range(raw_data.shape[1]):
        if raw_data.iloc[row,col] == 'Currency':
            data_duplicate = raw_data.iloc[(row+1):].reset_index(drop=True)
            data_duplicate.columns = list(raw_data.iloc[row])
            break
data_duplicate.dropna(axis=1, how='all',inplace=True)
data_duplicate

Also, the number of bank rows + garbage rows before the header is not fixed.

Body:
Here's my way: You can drop all rows and all columns containing Nan

data = pd.read_excel('test.xlsx')
data = data.dropna(how='all', axis = 1)
data = data.dropna(how='all', axis = 0)
data = data.reset_index(drop = True)

better if you put it into a function if you need to open multiple DataFrame in the same code:

data = pd.read_excel('test.xlsx')

def remove_nans(df):
    x = df.dropna(how = 'all', axis = 1)
    x = x.dropna(how = 'all', axis = 0)
    x = x.reset_index(drop = True)
    return x

df = remove_nans(data)
print(df)


问:
Writing a class in javascript
I want to create a class based on this object structure:

```<code>var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2)
</code>```

Basically, I want to be able to access the object contents via this style since I will be working a lot on parameter modifications:

ourStorage[accessStr][drawerPart].folder2

So my questions are:

How do I convert this to class while maintaining this kind of structure? Is it possible?

If I want to insert another item/object (e.g. variableItem3) - how do I do that?

If I also want to insert another item/object on the deeper level (e.g. middle drawer), how do I also do that?

Thanks much!!

答:
One option is to create a "Model" class that has a data property which stores all values assigned to it. Use a get/set/unset API to modify the data properties. Use a parse method to get a plain object representation of the model. This allows you to create nested models.

If you are creating an application I recommend creating an API rather than accessing properties directly on the data model. The syntax may seem a little bit longer, but in the long run if you need to perform data transformations it will be easier to add methods to the class. As it stands with your initial approach, if you want to add other methods to the class then you risk overwriting them with actual data. Better to have a data property that stores all the values. Otherwise, you would not necessarily need to create a class, you could just use a plain object as you are doing.

https://jsfiddle.net/cnu6ryab/

Class

```<code>const Model = class {
  constructor() {}
  get data() {
    if(!this._data) this._data = {}
    return this._data
  }
  setDataProperty(key, value) {
    if(!this.data[key]) {
      Object.defineProperties(this.data, {
        ['_'.concat(key)]: {
          configurable: true,
          writable: true,
          enumerable: false,
        },
        [key]: {
          configurable: true,
          enumerable: true,
          get() { return this['_'.concat(key)] },
          set(value) { this['_'.concat(key)] = value }
        },
      })
    }
    this.data[key] = value
    return this
  }
  unsetDataProperty(key) {
    if(this.data[key]) {
      delete this.data[key]
    }
    return this
  }
  get() {
    if(arguments[0]) return this.data[arguments[0]]
    return Object.entries(this.data)
      .reduce((_data, [key, value]) => {
        _data[key] = value
        return _data
      }, {})
  }
  set() {
    if(arguments.length === 2) {
      this.setDataProperty(arguments[0], arguments[1])
    } else if(
      arguments.length === 1 &&
      !Array.isArray(arguments[0]) &&
      typeof arguments[0] === 'object'
    ) {
      Object.entries(arguments[0]).forEach(([key, value]) => {
        this.setDataProperty(key, value)
      })
    }
    return this
  }
  unset() {
    if(arguments[0]) {
      this.unsetDataProperty(arguments[0])
    } else {
      Object.keys(this.data).forEach((key) => {
        this.unsetDataProperty(key)
      })
    }
    return this
  }
  parse(data = this.data) {
    return Object.entries(data).reduce((_data, [key, value]) => {
      if(value instanceof Model) {
        _data[key] = value.parse()
      } else {
        _data[key] = value
      }
      return _data
    }, {})
  }
}
</code>```

Usage

```<code>let model = new Model()
// Add a property
model.set('a', 1)
console.log(model.get())

/*
{
  "a": 1
}
*/

// Add multiple properties
model.set({
  'b': 2,
  'c': { a: 1, b: 2, }
})
console.log(model.get())
/*
{
  "a": 1,
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Replace a property
model.set({
  a: ['meh', 'heh',]
})
console.log(model.get())
/*
{
  "a": [
    "meh",
    "heh"
  ],
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Remove a single properties
model.unset('a')
console.log(model.get())
/*
{
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Remove all properties
model.unset()
console.log(model.get())
/*
{}
*/

// Add another property
model.set('a', 2354234)

// Create a nested model
let nestedModel = new Model()
nestedModel.set('nestedValue', 35234534254)
model.set('nestedModel', nestedModel)
console.log(model.parse())
/*
{
  "a": 2354234,
  "nestedModel": {
    "nestedValue": 35234534254
  }
}
*/

// Update the nested model
model.get('nestedModel').set('someNewValue', 'asdfasgaerwkjghak')
console.log(model.parse())
/*
{
  "a": 2354234,
  "nestedModel": {
    "nestedValue": 35234534254,
    "someNewValue": "asdfasgaerwkjghak"
  }
}
*/
</code>```

Title: Writing a class in javascript

Body:
I want to create a class based on this object structure:

var ourStorage = {
"variableItem1":    {
    "drawer": ""
  },
"variableItem2": {
    "top drawer": {
      "folder1": "",
      "folder2": "harhar"
    },
    "bottom drawer": ""
  }
};

var accessStr = 'variableItem2'
var drawerPart = 'top drawer'
console.log(ourStorage[accessStr][drawerPart].folder2)

Basically, I want to be able to access the object contents via this style since I will be working a lot on parameter modifications:

ourStorage[accessStr][drawerPart].folder2

So my questions are:

How do I convert this to class while maintaining this kind of structure? Is it possible?

If I want to insert another item/object (e.g. variableItem3) - how do I do that?

If I also want to insert another item/object on the deeper level (e.g. middle drawer), how do I also do that?

Thanks much!!

Body:
One option is to create a "Model" class that has a data property which stores all values assigned to it. Use a get/set/unset API to modify the data properties. Use a parse method to get a plain object representation of the model. This allows you to create nested models.

If you are creating an application I recommend creating an API rather than accessing properties directly on the data model. The syntax may seem a little bit longer, but in the long run if you need to perform data transformations it will be easier to add methods to the class. As it stands with your initial approach, if you want to add other methods to the class then you risk overwriting them with actual data. Better to have a data property that stores all the values. Otherwise, you would not necessarily need to create a class, you could just use a plain object as you are doing.

https://jsfiddle.net/cnu6ryab/

Class

const Model = class {
  constructor() {}
  get data() {
    if(!this._data) this._data = {}
    return this._data
  }
  setDataProperty(key, value) {
    if(!this.data[key]) {
      Object.defineProperties(this.data, {
        ['_'.concat(key)]: {
          configurable: true,
          writable: true,
          enumerable: false,
        },
        [key]: {
          configurable: true,
          enumerable: true,
          get() { return this['_'.concat(key)] },
          set(value) { this['_'.concat(key)] = value }
        },
      })
    }
    this.data[key] = value
    return this
  }
  unsetDataProperty(key) {
    if(this.data[key]) {
      delete this.data[key]
    }
    return this
  }
  get() {
    if(arguments[0]) return this.data[arguments[0]]
    return Object.entries(this.data)
      .reduce((_data, [key, value]) => {
        _data[key] = value
        return _data
      }, {})
  }
  set() {
    if(arguments.length === 2) {
      this.setDataProperty(arguments[0], arguments[1])
    } else if(
      arguments.length === 1 &&
      !Array.isArray(arguments[0]) &&
      typeof arguments[0] === 'object'
    ) {
      Object.entries(arguments[0]).forEach(([key, value]) => {
        this.setDataProperty(key, value)
      })
    }
    return this
  }
  unset() {
    if(arguments[0]) {
      this.unsetDataProperty(arguments[0])
    } else {
      Object.keys(this.data).forEach((key) => {
        this.unsetDataProperty(key)
      })
    }
    return this
  }
  parse(data = this.data) {
    return Object.entries(data).reduce((_data, [key, value]) => {
      if(value instanceof Model) {
        _data[key] = value.parse()
      } else {
        _data[key] = value
      }
      return _data
    }, {})
  }
}

Usage

let model = new Model()
// Add a property
model.set('a', 1)
console.log(model.get())

/*
{
  "a": 1
}
*/

// Add multiple properties
model.set({
  'b': 2,
  'c': { a: 1, b: 2, }
})
console.log(model.get())
/*
{
  "a": 1,
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Replace a property
model.set({
  a: ['meh', 'heh',]
})
console.log(model.get())
/*
{
  "a": [
    "meh",
    "heh"
  ],
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Remove a single properties
model.unset('a')
console.log(model.get())
/*
{
  "b": 2,
  "c": {
    "a": 1,
    "b": 2
  }
}
*/

// Remove all properties
model.unset()
console.log(model.get())
/*
{}
*/

// Add another property
model.set('a', 2354234)

// Create a nested model
let nestedModel = new Model()
nestedModel.set('nestedValue', 35234534254)
model.set('nestedModel', nestedModel)
console.log(model.parse())
/*
{
  "a": 2354234,
  "nestedModel": {
    "nestedValue": 35234534254
  }
}
*/

// Update the nested model
model.get('nestedModel').set('someNewValue', 'asdfasgaerwkjghak')
console.log(model.parse())
/*
{
  "a": 2354234,
  "nestedModel": {
    "nestedValue": 35234534254,
    "someNewValue": "asdfasgaerwkjghak"
  }
}
*/


问:
codeigniter changes the results of the foreach into an array
I have an output like the one below, how do you loop the results into an array?

```<code>16
PT. QWERT
62218501053
JL. MAYJEN SUTOYO

16
PT. ABCD
62218501053
JL. MAYJEN SUTOYO
</code>```

how to change into this ?

```<code>Array
(
    [id_cs] => 16
    [nama] => PT. QWERT
    [tlp] => 87878
    [alamat_detail] => JL. MAYJEN SUTOYO
)
1

Array
(
    [id_cs] => 16
    [nama] => PT. ABCD
    [tlp] => 123
    [alamat_detail] => JL. MAYJEN SUTOYO
)
1
</code>```

This my code

```<code>$array = array(
    'id_cs' => $row['AN'],
    'nama' => $row['AO'],
    'tlp' => $row['AP'],
    'alamat_detail' => $row['AQ'],
);
foreach($array as $key => $value) {
    if (empty($value))
        unset($array[$key]);
}
foreach($array as $key => $value) {
    echo($array[$key]."<br>");
}
//$this->db->insert('customer_address',$array);
</code>```

how to implement the code? thank you for answering

答:
Write this code.</p>

```<code>$array[] = array(
'id_cs' => $row['AN'],
'nama' => $row['AO'],
'tlp' => $row['AP'],
'alamat_detail' => $row['AQ'] );

foreach($array as $key => $value) {
if (empty($value))
    unset($array[$key]); }

foreach($array as $row){
$this->db->insert('customer_address',$row); }
</code>```

Body:
I have an output like the one below, how do you loop the results into an array?

16
PT. QWERT
62218501053
JL. MAYJEN SUTOYO

16
PT. ABCD
62218501053
JL. MAYJEN SUTOYO

how to change into this ?

Array
(
    [id_cs] => 16
    [nama] => PT. QWERT
    [tlp] => 87878
    [alamat_detail] => JL. MAYJEN SUTOYO
)
1

Array
(
    [id_cs] => 16
    [nama] => PT. ABCD
    [tlp] => 123
    [alamat_detail] => JL. MAYJEN SUTOYO
)
1

This my code

$array = array(
    'id_cs' => $row['AN'],
    'nama' => $row['AO'],
    'tlp' => $row['AP'],
    'alamat_detail' => $row['AQ'],
);
foreach($array as $key => $value) {
    if (empty($value))
        unset($array[$key]);
}
foreach($array as $key => $value) {
    echo($array[$key]."
");
}
//$this->db->insert('customer_address',$array);

how to implement the code? thank you for answering

Body:
Write this code.

$array[] = array(
'id_cs' => $row['AN'],
'nama' => $row['AO'],
'tlp' => $row['AP'],
'alamat_detail' => $row['AQ'] );

foreach($array as $key => $value) {
if (empty($value))
    unset($array[$key]); }

foreach($array as $row){
$this->db->insert('customer_address',$row); }


问:
Re-generate new x509 certificates with an updated CommonName
I have an encoded x509 certificate and I want to update the CommonName (aka Subject or host name).

Here's the code that I have thus far (simplified):

```<code>import (
    "crypto/tls",
    "crypto/x509"
)

...

// parses a public/private key pair from a pair of PEM encoded data
c, _ := tls.X509KeyPair(certPEMBlock, keyPEMBlock)

// parse into a x509 cert object
cert, _ := x509.ParseCertificate(c.Certificate[0])

// I want to modify the Subject here

// I want to encode it back to PEM encoded data of type []bytes

...
</code>```

Any idea how to update the subject and encoded it back to PEM encoded data of type []bytes?

答:
You can create a new certificate, with code that looks like the following. You'll need the CA private key for this:

```<code>func GenerateCertificate(ca *x509.Certificate, caKey crypto.PrivateKey, req x509.CertificateRequest, durYear, durMonth int, keyUsage x509.KeyUsage, extKeyUsage []x509.ExtKeyUsage, rsaKeySize int) (certificate, key *pem.Block, err error) {

    cert := &x509.Certificate{
        Version:         req.Version,
        SerialNumber:    RandomBigInt(),
        Subject:         req.Subject,
        Extensions:      req.Extensions,
        ExtraExtensions: req.ExtraExtensions,
        DNSNames:        req.DNSNames,
        EmailAddresses:  req.EmailAddresses,
        IPAddresses:     req.IPAddresses,
        URIs:            req.URIs,
        NotBefore:       time.Now(),
        NotAfter:        time.Now().AddDate(durYear, durMonth, 0),
        ExtKeyUsage:     extKeyUsage,
        KeyUsage:        keyUsage,
    }
    priv, _ := rsa.GenerateKey(rand.Reader, rsaKeySize)
    pub := &priv.PublicKey

    var data []byte
    data, err = x509.CreateCertificate(rand.Reader, cert, ca, pub, caKey)
    if err != nil {
        return
    }
    // Public key
    certificate = &pem.Block{Type: "CERTIFICATE", Bytes: data}
    // Private key
    key = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}
    return
}
</code>```

Use it as:

```<code>    subject := pkix.Name{CommonName:"name"}
    cert, certKey, err := GenerateCertificate(caCert, key, x509.CertificateRequest{Subject: subject}, 1, 0, x509.KeyUsageDigitalSignature,
        []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 2048)
</code>```

You need to find out the key usage, ext key usage, etc. or copy them from the old cert. You can initialize the certificate request passed into GenerateCertificate from the old certificate you have.

If you need a self-signed cert, you can use something like below (I use this to generate a self-signed CA). You have to copy information from the old cert into this one.

```<code>func GenerateCA(subject pkix.Name, duryear, durmonth int, rsaKeySize int) (certificate, key *pem.Block, err error) {
    ca := &x509.Certificate{
        SerialNumber:          RandomBigInt(),
        Subject:               subject,
        NotBefore:             time.Now(),
        NotAfter:              time.Now().AddDate(duryear, durmonth, 0),
        IsCA:                  false, // or true?
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
        KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
        BasicConstraintsValid: true,
    }

    priv, _ := rsa.GenerateKey(rand.Reader, rsaKeySize)
    pub := &priv.PublicKey
    var data []byte
    data, err = x509.CreateCertificate(rand.Reader, ca, ca, pub, priv)
    if err != nil {
        return
    }

    // Public key
    certificate = &pem.Block{Type: "CERTIFICATE", Bytes: data}
    // Private key
    key = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}
    return
}
</code>```

Body:
I have an encoded x509 certificate and I want to update the CommonName (aka Subject or host name).

Here's the code that I have thus far (simplified):

import (
    "crypto/tls",
    "crypto/x509"
)

...

// parses a public/private key pair from a pair of PEM encoded data
c, _ := tls.X509KeyPair(certPEMBlock, keyPEMBlock)

// parse into a x509 cert object
cert, _ := x509.ParseCertificate(c.Certificate[0])

// I want to modify the Subject here

// I want to encode it back to PEM encoded data of type []bytes

...

Any idea how to update the subject and encoded it back to PEM encoded data of type []bytes?

Body:
You can create a new certificate, with code that looks like the following. You'll need the CA private key for this:

func GenerateCertificate(ca *x509.Certificate, caKey crypto.PrivateKey, req x509.CertificateRequest, durYear, durMonth int, keyUsage x509.KeyUsage, extKeyUsage []x509.ExtKeyUsage, rsaKeySize int) (certificate, key *pem.Block, err error) {

    cert := &x509.Certificate{
        Version:         req.Version,
        SerialNumber:    RandomBigInt(),
        Subject:         req.Subject,
        Extensions:      req.Extensions,
        ExtraExtensions: req.ExtraExtensions,
        DNSNames:        req.DNSNames,
        EmailAddresses:  req.EmailAddresses,
        IPAddresses:     req.IPAddresses,
        URIs:            req.URIs,
        NotBefore:       time.Now(),
        NotAfter:        time.Now().AddDate(durYear, durMonth, 0),
        ExtKeyUsage:     extKeyUsage,
        KeyUsage:        keyUsage,
    }
    priv, _ := rsa.GenerateKey(rand.Reader, rsaKeySize)
    pub := &priv.PublicKey

    var data []byte
    data, err = x509.CreateCertificate(rand.Reader, cert, ca, pub, caKey)
    if err != nil {
        return
    }
    // Public key
    certificate = &pem.Block{Type: "CERTIFICATE", Bytes: data}
    // Private key
    key = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}
    return
}

Use it as:

    subject := pkix.Name{CommonName:"name"}
    cert, certKey, err := GenerateCertificate(caCert, key, x509.CertificateRequest{Subject: subject}, 1, 0, x509.KeyUsageDigitalSignature,
        []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, 2048)

You need to find out the key usage, ext key usage, etc. or copy them from the old cert. You can initialize the certificate request passed into GenerateCertificate from the old certificate you have.

If you need a self-signed cert, you can use something like below (I use this to generate a self-signed CA). You have to copy information from the old cert into this one.

func GenerateCA(subject pkix.Name, duryear, durmonth int, rsaKeySize int) (certificate, key *pem.Block, err error) {
    ca := &x509.Certificate{
        SerialNumber:          RandomBigInt(),
        Subject:               subject,
        NotBefore:             time.Now(),
        NotAfter:              time.Now().AddDate(duryear, durmonth, 0),
        IsCA:                  false, // or true?
        ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
        KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
        BasicConstraintsValid: true,
    }

    priv, _ := rsa.GenerateKey(rand.Reader, rsaKeySize)
    pub := &priv.PublicKey
    var data []byte
    data, err = x509.CreateCertificate(rand.Reader, ca, ca, pub, priv)
    if err != nil {
        return
    }

    // Public key
    certificate = &pem.Block{Type: "CERTIFICATE", Bytes: data}
    // Private key
    key = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}
    return
}


问:
What is the more correct position for the error argument in a javascript callback?
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}
</code>```

or this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}
</code>```

or this:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}
</code>```

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

答:
Most node.js apps either use the 'error-first' pattern or the EventEmitter pattern. viz:

```<code>// more common
if (error) {
  cb({make:'better'})
} else {
  cb(undefined, stronger)
}
</code>```

or

```<code>// cleaner, perhaps, but more keystrokes
var ee = new EventEmitter
process.nextTick(function () {
  ...
  if (error) {
    ee.emit('error', {msg:'delicious'})
  } else {
    ee.emit('success', bacon)
  }
})
return ee
</code>```

Body:
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}

or this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}

or this:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

Body:
Most node.js apps either use the 'error-first' pattern or the EventEmitter pattern. viz:

// more common
if (error) {
  cb({make:'better'})
} else {
  cb(undefined, stronger)
}

or

// cleaner, perhaps, but more keystrokes
var ee = new EventEmitter
process.nextTick(function () {
  ...
  if (error) {
    ee.emit('error', {msg:'delicious'})
  } else {
    ee.emit('success', bacon)
  }
})
return ee


问:
How to .Scan() a MySQL TIMESTAMP value into a time.Time variable?
I have this Go code:

```<code>package main

import (
    "fmt"
    "database/sql"
    _"github.com/go-sql-driver/mysql"
    "time"
)

type User struct {
    id                  uint32
    name                string
    email               string
    rating              uint8
    subscription        uint8
    date_registered     time.Time
    online              string
}

// main entry point
func main() {
    // setup db connection
    db, err := sql.Open("mysql", "user:@tcp(127.0.0.1:3306)/c9?parseTime=true")
    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()

    // query
    rows, err := db.Query("SELECT * FROM users WHERE id = ?", 1)
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    usr := User{}
    for rows.Next() {
        err := rows.Scan(&usr.id, &usr.name, &usr.email, &usr.rating, &usr.subscription, &usr.date_registered, &usr.online)
        if err != nil {
            fmt.Println(err)
        }
    }
    fmt.Println(usr)
    err = rows.Err()
    if err != nil {
        fmt.Println(err)
    }
}
</code>```

This is what I get from MySQL console:

```<code>mysql> describe users;
+-----------------+---------------------+------+-----+-------------------+----------------+
| Field           | Type                | Null | Key | Default           | Extra          |
+-----------------+---------------------+------+-----+-------------------+----------------+
| id              | int(10) unsigned    | NO   | PRI | NULL              | auto_increment |
| name            | varchar(50)         | NO   |     | NULL              |                |
| email           | varchar(50)         | NO   |     | NULL              |                |
| rating          | tinyint(3) unsigned | YES  |     | NULL              |                |
| subscription    | tinyint(3) unsigned | NO   |     | 0                 |                |
| date_registered | timestamp           | NO   |     | CURRENT_TIMESTAMP |                |
| online          | char(1)             | NO   |     | N                 |                |
+-----------------+---------------------+------+-----+-------------------+----------------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM users;
+----+------------+-----------------------+--------+--------------+---------------------+--------+
| id | name       | email                 | rating | subscription | date_registered     | online |
+----+------------+-----------------------+--------+--------------+---------------------+--------+
|  1 | alakhazamm | abcdefghhhh@gmail.com |   NULL |            0 | 2014-10-28 15:37:44 | N      |
+----+------------+-----------------------+--------+--------------+---------------------+--------+
1 row in set (0.00 sec)
</code>```

After .Scan(), fmt.Println(usr) prints

```<code>{1 alakhazamm abcdefghhhh@gmail.com 0 0 {0 0 <nil>} }
</code>```

The last two fields of the struct are wrong but I have no idea why.
I've tried using date_registered string in the struct definition, but I get an empty string after .Scan().
I've also read in the driver's docs that ?parseTime=true parses MySQL DATE and DATETIME values into time.Time, but they don't mention TIMESTAMP which is what I'm currently using.

Am I missing something important or is it a bug/missing feature of the library?

答:
In addition to answer by @incognick, here is exactly you can do (add parseTime=true):

```<code>db, err := sqlx.Connect("mysql", "myuser:mypass@tcp(127.0.0.1:3306)/mydb?parseTime=true")
</code>```

If there is a possibility of timestamp/datetime be null, in that case you should use scan parameter as sql.NullTime instead of time.Time.

Using sql.NullTime will provide you option to check if scanned time is null or not using var.Valid flag. You can use time with var.Time if it is valid and not null.

Body:
I have this Go code:

package main

import (
    "fmt"
    "database/sql"
    _"github.com/go-sql-driver/mysql"
    "time"
)

type User struct {
    id                  uint32
    name                string
    email               string
    rating              uint8
    subscription        uint8
    date_registered     time.Time
    online              string
}

// main entry point
func main() {
    // setup db connection
    db, err := sql.Open("mysql", "user:@tcp(127.0.0.1:3306)/c9?parseTime=true")
    if err != nil {
        fmt.Println(err)
    }
    defer db.Close()

    // query
    rows, err := db.Query("SELECT * FROM users WHERE id = ?", 1)
    if err != nil {
        fmt.Println(err)
    }
    defer rows.Close()

    usr := User{}
    for rows.Next() {
        err := rows.Scan(&usr.id, &usr.name, &usr.email, &usr.rating, &usr.subscription, &usr.date_registered, &usr.online)
        if err != nil {
            fmt.Println(err)
        }
    }
    fmt.Println(usr)
    err = rows.Err()
    if err != nil {
        fmt.Println(err)
    }
}

This is what I get from MySQL console:

mysql> describe users;
+-----------------+---------------------+------+-----+-------------------+----------------+
| Field           | Type                | Null | Key | Default           | Extra          |
+-----------------+---------------------+------+-----+-------------------+----------------+
| id              | int(10) unsigned    | NO   | PRI | NULL              | auto_increment |
| name            | varchar(50)         | NO   |     | NULL              |                |
| email           | varchar(50)         | NO   |     | NULL              |                |
| rating          | tinyint(3) unsigned | YES  |     | NULL              |                |
| subscription    | tinyint(3) unsigned | NO   |     | 0                 |                |
| date_registered | timestamp           | NO   |     | CURRENT_TIMESTAMP |                |
| online          | char(1)             | NO   |     | N                 |                |
+-----------------+---------------------+------+-----+-------------------+----------------+
7 rows in set (0.00 sec)

mysql> SELECT * FROM users;
+----+------------+-----------------------+--------+--------------+---------------------+--------+
| id | name       | email                 | rating | subscription | date_registered     | online |
+----+------------+-----------------------+--------+--------------+---------------------+--------+
|  1 | alakhazamm | abcdefghhhh@gmail.com |   NULL |            0 | 2014-10-28 15:37:44 | N      |
+----+------------+-----------------------+--------+--------------+---------------------+--------+
1 row in set (0.00 sec)

After .Scan(), fmt.Println(usr) prints

{1 alakhazamm abcdefghhhh@gmail.com 0 0 {0 0 <nil>} }

The last two fields of the struct are wrong but I have no idea why.
I've tried using date_registered string in the struct definition, but I get an empty string after .Scan().
I've also read in the driver's docs that ?parseTime=true parses MySQL DATE and DATETIME values into time.Time, but they don't mention TIMESTAMP which is what I'm currently using.

Am I missing something important or is it a bug/missing feature of the library?

Body:
In addition to answer by @incognick, here is exactly you can do (add parseTime=true):

db, err := sqlx.Connect("mysql", "myuser:mypass@tcp(127.0.0.1:3306)/mydb?parseTime=true")

If there is a possibility of timestamp/datetime be null, in that case you should use scan parameter as sql.NullTime instead of time.Time.

Using sql.NullTime will provide you option to check if scanned time is null or not using var.Valid flag. You can use time with var.Time if it is valid and not null.


问:
ping from docker container cannot reach outside hosts
I am trying to ping from a docker container running along with other services controlled with docker-compose.
Basic requirement is to connect to external db servers, which is not working. To debug I tried to ping the external box, which as expected don't return. I can however ping the external box from vm host.

The /etc/hosts has entry as I have provided following line in docker-compose.yml

```<code>extra_hosts:
     - "externalhostname:10.40.154.27"
</code>```

From docker inspect the following is the network details

```<code>"Networks": {
        "echo_service_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "python-interpreter",
                "3767f3a7ad80"
            ],
            "NetworkID": "10ca2ec9a1dbc3659cef91014c2c64c8df17e9d720350d1bdd198a53c6c0a946",
            "EndpointID": "c920443c34ff00ffefe2c669bc4b80e121c27d1b8ebc44fa9f5efb16e71561a4",
            "Gateway": "172.19.0.1",
            "IPAddress": "172.19.0.6",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:13:00:06",
            "DriverOpts": null
        }
</code>```

ifconfig in host gives

```<code>docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:b6ff:fe86:fb71  prefixlen 64  scopeid 0x20<link>
        ether 02:42:b6:86:fb:71  txqueuelen 0  (Ethernet)
        RX packets 204  bytes 90455 (88.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5080  bytes 459752 (448.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>```

The service entry from docker-compose.yml

```<code>  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
 - /scratch/share:/var/python-interpreter/data:ro
 - shared:/var/shared
extra_hosts:
 - "externalhostname:10.40.154.27"
</code>```

so the service is running with bridge network with no -p option

答:
In the docker-compose.yml you shared, the python-interpreter service has a extra_hosts definition but not a network definition, you need to define a network, for example:

```<code>  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
- /scratch/share:/var/python-interpreter/data:ro
- shared:/var/shared
networks:
  - backend
</code>```

And define the network at the end of your docker-compose.yml :

```<code>    networks:
  backend:
    driver: bridge
</code>```

Body:
I am trying to ping from a docker container running along with other services controlled with docker-compose.
Basic requirement is to connect to external db servers, which is not working. To debug I tried to ping the external box, which as expected don't return. I can however ping the external box from vm host.

The /etc/hosts has entry as I have provided following line in docker-compose.yml

extra_hosts:
     - "externalhostname:10.40.154.27"

From docker inspect the following is the network details

"Networks": {
        "echo_service_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "python-interpreter",
                "3767f3a7ad80"
            ],
            "NetworkID": "10ca2ec9a1dbc3659cef91014c2c64c8df17e9d720350d1bdd198a53c6c0a946",
            "EndpointID": "c920443c34ff00ffefe2c669bc4b80e121c27d1b8ebc44fa9f5efb16e71561a4",
            "Gateway": "172.19.0.1",
            "IPAddress": "172.19.0.6",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:13:00:06",
            "DriverOpts": null
        }

ifconfig in host gives

docker0: flags=4099<UP,BROADCAST,MULTICAST>  mtu 1500
        inet 172.17.0.1  netmask 255.255.0.0  broadcast 172.17.255.255
        inet6 fe80::42:b6ff:fe86:fb71  prefixlen 64  scopeid 0x20<link>
        ether 02:42:b6:86:fb:71  txqueuelen 0  (Ethernet)
        RX packets 204  bytes 90455 (88.3 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 5080  bytes 459752 (448.9 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

The service entry from docker-compose.yml

  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
 - /scratch/share:/var/python-interpreter/data:ro
 - shared:/var/shared
extra_hosts:
 - "externalhostname:10.40.154.27"

so the service is running with bridge network with no -p option

Body:
In the docker-compose.yml you shared, the python-interpreter service has a extra_hosts definition but not a network definition, you need to define a network, for example:

  python-interpreter:
image: image name
hostname: python-interpreter
volumes:
- /scratch/share:/var/python-interpreter/data:ro
- shared:/var/shared
networks:
  - backend

And define the network at the end of your docker-compose.yml :

    networks:
  backend:
    driver: bridge


问:
Getting an empty JQuery object
In the following code I set up a change handler on a select box to show and hide some follow up questions based on the value of the selection.

Further, for some values of the selection there is an extra message that is displayed.

In order to check to see if I need to hide the extra message, I keep a variable called Previous.  Upon execution of the handler I check to see if Previous is null or if the size is 0.

It would be nice to initialize Previous to an empty JQuery object so as not to have to do the extra check for null.

Doing a $() returns an object with the size of 1.

Is there a way to create an empty Jquery object?

```
//Init function.
$(function(){
//Hold the previously selected object for the account type selection.

var Previous = null;  //Here is where I would like to initialize.
                      //something like Previous = $();

$("SELECT[name='AccountType']").change(
    function () {
        //Hide Previous message if there was one.
        if(Previous == null || Previous.size() > 0){
            Previous.hide();
        }

        //Show the message if found and save it as previous.
        Previous = $("#"+this.value+"_Msg").show();

        //Get fisrt question
        var FirstQuestion = $(".FirstQuestion");
        if(this.value === ''){
            FirstQuestion.hide();
        }else{
            //Manually show FirstQuestion.
            FirstQuestion.show();
        }
    });
}
```

In the worst case I could do something like this:

```
    var Previous = { size : function () { return 0; } };
```

but that seems like overkill.

答:
try this

```<code> var new = $([]);
</code>```

I ain't a good programmer but it gives u empty object :))

ContentLicense: CC BY-SA 2.5

Title: Getting an empty JQuery object

Body:
In the following code I set up a change handler on a select box to show and hide some follow up questions based on the value of the selection.

Further, for some values of the selection there is an extra message that is displayed.

In order to check to see if I need to hide the extra message, I keep a variable called Previous.  Upon execution of the handler I check to see if Previous is null or if the size is 0.

It would be nice to initialize Previous to an empty JQuery object so as not to have to do the extra check for null.

Doing a $() returns an object with the size of 1.

Is there a way to create an empty Jquery object?

//Init function.
$(function(){
//Hold the previously selected object for the account type selection.

var Previous = null;  //Here is where I would like to initialize.
                      //something like Previous = $();

$("SELECT[name='AccountType']").change(
    function () {
        //Hide Previous message if there was one.
        if(Previous == null || Previous.size() > 0){
            Previous.hide();
        }

        //Show the message if found and save it as previous.
        Previous = $("#"+this.value+"_Msg").show();

        //Get fisrt question
        var FirstQuestion = $(".FirstQuestion");
        if(this.value === ''){
            FirstQuestion.hide();
        }else{
            //Manually show FirstQuestion.
            FirstQuestion.show();
        }
    });
}

In the worst case I could do something like this:

    var Previous = { size : function () { return 0; } };

but that seems like overkill.

Body:
try this

 var new = $([]);

I ain't a good programmer but it gives u empty object :))


问:
Trying to import xml into Google Sheet but not pulling any data
I'm trying to pull the "followers" from this page https://www.kickstarter.com/projects/two19/kingless into a google sheet using the importxml function.

This isn't pulling any data back:

```<code>=importxml("https://www.kickstarter.com/projects/two19/kingless", "//span[@class='type-14 block text-center text-left-md']")
</code>```

Am I missing something here?

答: The provided link https://www.kickstarter.com/projects/two19/kingless is not initially loaded the "follower" detail at begin, so you wouldn't get the detail through importxml function.

Body:
I'm trying to pull the "followers" from this page https://www.kickstarter.com/projects/two19/kingless into a google sheet using the importxml function.

This isn't pulling any data back:

=importxml("https://www.kickstarter.com/projects/two19/kingless", "//span[@class='type-14 block text-center text-left-md']")

Am I missing something here?


问:
Conditional Statements are not Executing?
I have written a Program that adds and multiples first ten Natural Numbers on user input. I have made two separate functions for Addition and Multiplication and called both functions in a while loop using if-else statement in it. But it is taking input from user but not performing any further operations. Code is Below:

```<code>print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=input()

plus=0
mul=1

for a2 in range(11):
    if a2>0:
        plus=plus + a2
        mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
    print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
        add()
    elif user == 2:
        product()
</code>```

Output:

答:
add int in user = input()
and put break in while loop</p>

```<code>print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=int(input())

plus=0
mul=1

for a2 in range(11):
  if a2>0:
    plus=plus + a2
    mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
   print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
         add()
         break;
     elif user == 2:
        product()
        break;
</code>```

Body:
I have written a Program that adds and multiples first ten Natural Numbers on user input. I have made two separate functions for Addition and Multiplication and called both functions in a while loop using if-else statement in it. But it is taking input from user but not performing any further operations. Code is Below:

print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=input()

plus=0
mul=1

for a2 in range(11):
    if a2>0:
        plus=plus + a2
        mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
    print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
        add()
    elif user == 2:
        product()

Output:

Body:
add int in user = input()
and put break in while loop

print("Please select one of the Following Functions:")
print("1. Add First Ten Numbers")
print("2. Multiply first ten Numbers")
user=int(input())

plus=0
mul=1

for a2 in range(11):
  if a2>0:
    plus=plus + a2
    mul=mul * a2

def add():
    print("Sum of First Ten Numbers is",plus)

def product():
   print("Product of First Ten Numbers is",mul)

while True:
    if user == 1 and user !=2:
         add()
         break;
     elif user == 2:
        product()
        break;


问:
How to fetch record from table based on post ip address in laravel using eloquent ORM
I am want to fetch record based on user post ip address. I am using eloquent ORM.
in such case which format ip address should be stored in database.

```<code>$ip = '192.255.365.25';
$employee = Employee::find($ip);
</code>```

not able to fetch full record for respective rows

答:
find()used to retrieve a model by its primary key, you can use first() as below

```<code>$ip = '192.255.365.25';
$employee = Employee::where('ip', $ip)->first();
</code>```

for more see documentation

Body:
I am want to fetch record based on user post ip address. I am using eloquent ORM.
in such case which format ip address should be stored in database.

$ip = '192.255.365.25';
$employee = Employee::find($ip);

not able to fetch full record for respective rows

Body:
find()used to retrieve a model by its primary key, you can use first() as below

$ip = '192.255.365.25';
$employee = Employee::where('ip', $ip)->first();

for more see documentation


问:
R tidyverse mutate with all combinations of subset of columns in grouped dataframe
I'd like to run a mutate for all combinations of a subset of columns of a grouped dataframe via tidyverse.

Here's the setup:

```<code>library(tidyverse)
a <- c(2018, 2019, 2020) #years
b <- c(23, 24, 25, 26) #cities
c <- c(45, 46, 47, 48, 49) #jobs
rows <- expand.grid(a, b, c)
colnames(rows) <- c('a', 'b', 'c')
d <-  sample(c(0,1), nrow(rows), replace = TRUE)
obs <- cbind(rows, d) %>% group_by(a, b) %>% mutate(c = str_c("J", c))
wide <- obs %>% spread(c, d)
</code>```

Which produces this:

```<code>A grouped_df: 12 × 7
a       b   J45 J46 J47 J48 J49
2018    23  1   0   1   1   1
2018    24  0   0   1   1   0
2018    25  0   1   0   1   1
2018    26  1   0   1   1   1
2019    23  0   0   1   1   1
2019    24  0   1   0   0   1
2019    25  1   0   0   1   0
2019    26  0   1   1   1   1
2020    23  0   1   0   1   0
2020    24  1   0   1   0   1
2020    25  1   0   0   1   0
2020    26  0   1   0   0   0
</code>```

The dataframe data is grouped by a and b, and I want to find the sum of all combinations of the J* columns.

I've been referring to this [tidyverse: Chi Square for all combinations of columns for guidance, but it doesn't use grouping.

I've expanded the dataframe to include all combinations with

```<code>combos <- data.frame(t(combn(unique(obs$c), 2)))
data <- merge(wide, combos) %>% mutate(X1 = as.character(X1), X2 = as.character(X2))
</code>```

and head(data, 10) produces this:

```<code>    a       b   J45 J46 J47 J48 J49 X1  X2
1   2018    23  1   0   1   1   1   J45 J46
2   2018    24  0   0   1   1   0   J45 J46
3   2018    25  0   1   0   1   1   J45 J46
4   2018    26  1   0   1   1   1   J45 J46
5   2019    23  0   0   1   1   1   J45 J46
6   2019    24  0   1   0   0   1   J45 J46
7   2019    25  1   0   0   1   0   J45 J46
8   2019    26  0   1   1   1   1   J45 J46
9   2020    23  0   1   0   1   0   J45 J46
10  2020    24  1   0   1   0   1   J45 J46
</code>```

Now I want the sum for each row of the value in the X1 column and the value in the X2 column. I can't seem to make either map2 or unquoted eval work. What am I missing?

Thank you for your attention.

EDIT: Some additional info, results of what I've tried and desired output (@camille).

With data %>% mutate(d = map2(X1, X2, sum(.x, .y))) I get

```<code>Error in as_mapper(.f, ...): object '.x' not found
</code>```

and with data %>% mutate(d = sum(!!sym(X1), !!sym(X2))) I get

```<code>Error in is_symbol(x): object 'X1' not found.
</code>```

I don't understand why it can't find these elements, esp in the map2 case.

As output, I need to retain the grouping values and column combinations with the sum value (ultimately a weighted edge list). Both outputs from the responses by @andrew_reece and @42- are fine, but I am curious as to why something more straightforward along the lines of "add the values in these two columns row wise" doesn't work.

答:
Here's one approach: pivot_longer to filter down to only the combo values you want, then group_by and sum:

```<code>data %>%
  pivot_longer(starts_with("J"), names_to = "var", values_to = "val") %>%
  filter(var == X1 | var == X2) %>%
  group_by(a, b, X1, X2) %>%
  summarise(combo_val = sum(val))
</code>```

You could also pivot_wider after filtering, and get combo sums via rowSums:

```<code>data %>%
  pivot_longer(starts_with("J"), names_to = "var", values_to = "val") %>%
  filter(var == X1 | var == X2) %>%
  pivot_wider (id_cols = c(a, b, X1, X2),
               names_from = "var",
               values_from = "val",
               values_fill = list(val = 0)) %>%
  mutate(combo_val = rowSums(select(., starts_with("J")))) %>%
  select(a, b, X1, X2, combo_val)
</code>```

In either case, the output is the same:

```<code># A tibble: 120 x 5
       a     b X1    X2    combo_val
   <dbl> <dbl> <chr> <chr>     <dbl>
 1  2018    23 J45   J46           1
 2  2018    24 J45   J46           2
 3  2018    25 J45   J46           0
 4  2018    26 J45   J46           2
 5  2019    23 J45   J46           2
 6  2019    24 J45   J46           0
 7  2019    25 J45   J46           0
 8  2019    26 J45   J46           0
 9  2020    23 J45   J46           0
10  2020    24 J45   J46           2
# … with 110 more rows
</code>```

Body:
I'd like to run a mutate for all combinations of a subset of columns of a grouped dataframe via tidyverse.

Here's the setup:

library(tidyverse)
a <- c(2018, 2019, 2020) #years
b <- c(23, 24, 25, 26) #cities
c <- c(45, 46, 47, 48, 49) #jobs
rows <- expand.grid(a, b, c)
colnames(rows) <- c('a', 'b', 'c')
d <-  sample(c(0,1), nrow(rows), replace = TRUE)
obs <- cbind(rows, d) %>% group_by(a, b) %>% mutate(c = str_c("J", c))
wide <- obs %>% spread(c, d)

Which produces this:

A grouped_df: 12 × 7
a       b   J45 J46 J47 J48 J49
2018    23  1   0   1   1   1
2018    24  0   0   1   1   0
2018    25  0   1   0   1   1
2018    26  1   0   1   1   1
2019    23  0   0   1   1   1
2019    24  0   1   0   0   1
2019    25  1   0   0   1   0
2019    26  0   1   1   1   1
2020    23  0   1   0   1   0
2020    24  1   0   1   0   1
2020    25  1   0   0   1   0
2020    26  0   1   0   0   0

The dataframe data is grouped by a and b, and I want to find the sum of all combinations of the J* columns.

I've been referring to this [tidyverse: Chi Square for all combinations of columns for guidance, but it doesn't use grouping.

I've expanded the dataframe to include all combinations with

combos <- data.frame(t(combn(unique(obs$c), 2)))
data <- merge(wide, combos) %>% mutate(X1 = as.character(X1), X2 = as.character(X2))

and head(data, 10) produces this:

    a       b   J45 J46 J47 J48 J49 X1  X2
1   2018    23  1   0   1   1   1   J45 J46
2   2018    24  0   0   1   1   0   J45 J46
3   2018    25  0   1   0   1   1   J45 J46
4   2018    26  1   0   1   1   1   J45 J46
5   2019    23  0   0   1   1   1   J45 J46
6   2019    24  0   1   0   0   1   J45 J46
7   2019    25  1   0   0   1   0   J45 J46
8   2019    26  0   1   1   1   1   J45 J46
9   2020    23  0   1   0   1   0   J45 J46
10  2020    24  1   0   1   0   1   J45 J46

Now I want the sum for each row of the value in the X1 column and the value in the X2 column. I can't seem to make either map2 or unquoted eval work. What am I missing?

Thank you for your attention.

EDIT: Some additional info, results of what I've tried and desired output (@camille).

With data %>% mutate(d = map2(X1, X2, sum(.x, .y))) I get

Error in as_mapper(.f, ...): object '.x' not found

and with data %>% mutate(d = sum(!!sym(X1), !!sym(X2))) I get

Error in is_symbol(x): object 'X1' not found.

I don't understand why it can't find these elements, esp in the map2 case.

As output, I need to retain the grouping values and column combinations with the sum value (ultimately a weighted edge list). Both outputs from the responses by @andrew_reece and @42- are fine, but I am curious as to why something more straightforward along the lines of "add the values in these two columns row wise" doesn't work.

Body:
Here's one approach: pivot_longer to filter down to only the combo values you want, then group_by and sum:

data %>%
  pivot_longer(starts_with("J"), names_to = "var", values_to = "val") %>%
  filter(var == X1 | var == X2) %>%
  group_by(a, b, X1, X2) %>%
  summarise(combo_val = sum(val))

You could also pivot_wider after filtering, and get combo sums via rowSums:

data %>%
  pivot_longer(starts_with("J"), names_to = "var", values_to = "val") %>%
  filter(var == X1 | var == X2) %>%
  pivot_wider (id_cols = c(a, b, X1, X2),
               names_from = "var",
               values_from = "val",
               values_fill = list(val = 0)) %>%
  mutate(combo_val = rowSums(select(., starts_with("J")))) %>%
  select(a, b, X1, X2, combo_val)

In either case, the output is the same:

# A tibble: 120 x 5
       a     b X1    X2    combo_val
   <dbl> <dbl> <chr> <chr>     <dbl>
 1  2018    23 J45   J46           1
 2  2018    24 J45   J46           2
 3  2018    25 J45   J46           0
 4  2018    26 J45   J46           2
 5  2019    23 J45   J46           2
 6  2019    24 J45   J46           0
 7  2019    25 J45   J46           0
 8  2019    26 J45   J46           0
 9  2020    23 J45   J46           0
10  2020    24 J45   J46           2
# … with 110 more rows


问:
Union type in DDD model and in the database
In the NBA basketball game I want to store play-by-play data. One Game has its StartTime, two Teams and the list of plays. Each Play has its occurrence in time and (depends on the play) different properties. There are 8 different play types, for example: "Rebound", "FieldGoalAttempt":

Rebound:

team

player

reboundType

Field Goal Attempt:

team

shootingPlayer

assistingPlayer

blockingPlayer

shotType

distanceFeet

points

location

result

As you can see, these two are totally different plays - and there are 6 more types. Which brings me to my first problem.

Question 1: How do I implement it in C#?

My idea is to create a type Play, and then 8 classes representing play types, like Rebound, FieldGoalAttempt, JumpBall like this:

```<code>public class Play
{
    public int PlayId { get; set; }
    public int GameId { get; set; }
    public int PlayerId { get; set; }

    public Rebound Rebound { get; set; }
    public FieldGoalAttempt FieldGoalAttempt { get; set; }
    public Turnover Turnover { get; set; }
    public Foul Foul { get; set; }
    ...
    public JumpBall JumpBall { get; set; }

    public Game Game { get; set; }
    public Player Player { get; set; }
}
</code>```

But I wasn't sure if this is a "code smell". I had a few more ideas: A list of objects? or a custom built C# class that acts like "Union"? So first question is How should I handle this situation in C#? Is my first idea good?

Question 2: After all, I want to store these plays in the database. In my architecture I use Models that represents tables in the database. For my logic I create Service, so models are "anemic" which some people call "anti-pattern", but I don't want to talk about it. I have Services for my logic and it works for me.

If I decide to create Union like class - How do I store these plays in the database?

答:
You can use inheritance for this. Like:

```<code>public class BasePlay
{
    public DateTimeOffset StartTime { get; set; }
    public Team TeamA { get; set; }
    public Team TeamB { get; set; }
}

public class JumpBallPlay : BasePlay
{
    public string ExtraProperty1 { get; set; }
}

public class FieldGoalAttemptPlay : BasePlay
{
    public string ExtraProperty2 { get; set; }
}
</code>```

Then, you can map this classes with EntityFramework using Table Inheritance:

```<code>protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BasePlay>()
        .HasDiscriminator<string>("PlayType")
        .HasValue<JumpBallPlay>("jumpBall")
        .HasValue<FieldGoalAttemptPlay>("fieldGoalAttemptPlay");
}
</code>```

All your objects will be stored in the same table, but mapped to a different columns (with some common for all columns from BasePlay, see Shared columns section). Extra column PlayType will contain the type of a play.

Body:
In the NBA basketball game I want to store play-by-play data. One Game has its StartTime, two Teams and the list of plays. Each Play has its occurrence in time and (depends on the play) different properties. There are 8 different play types, for example: "Rebound", "FieldGoalAttempt":

Rebound:

team

player

reboundType

Field Goal Attempt:

team

shootingPlayer

assistingPlayer

blockingPlayer

shotType

distanceFeet

points

location

result

As you can see, these two are totally different plays - and there are 6 more types. Which brings me to my first problem.

Question 1: How do I implement it in C#?

My idea is to create a type Play, and then 8 classes representing play types, like Rebound, FieldGoalAttempt, JumpBall like this:

public class Play
{
    public int PlayId { get; set; }
    public int GameId { get; set; }
    public int PlayerId { get; set; }

    public Rebound Rebound { get; set; }
    public FieldGoalAttempt FieldGoalAttempt { get; set; }
    public Turnover Turnover { get; set; }
    public Foul Foul { get; set; }
    ...
    public JumpBall JumpBall { get; set; }

    public Game Game { get; set; }
    public Player Player { get; set; }
}

But I wasn't sure if this is a "code smell". I had a few more ideas: A list of objects? or a custom built C# class that acts like "Union"? So first question is How should I handle this situation in C#? Is my first idea good?

Question 2: After all, I want to store these plays in the database. In my architecture I use Models that represents tables in the database. For my logic I create Service, so models are "anemic" which some people call "anti-pattern", but I don't want to talk about it. I have Services for my logic and it works for me.

If I decide to create Union like class - How do I store these plays in the database?

Body:
You can use inheritance for this. Like:

public class BasePlay
{
    public DateTimeOffset StartTime { get; set; }
    public Team TeamA { get; set; }
    public Team TeamB { get; set; }
}

public class JumpBallPlay : BasePlay
{
    public string ExtraProperty1 { get; set; }
}

public class FieldGoalAttemptPlay : BasePlay
{
    public string ExtraProperty2 { get; set; }
}

Then, you can map this classes with EntityFramework using Table Inheritance:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<BasePlay>()
        .HasDiscriminator<string>("PlayType")
        .HasValue<JumpBallPlay>("jumpBall")
        .HasValue<FieldGoalAttemptPlay>("fieldGoalAttemptPlay");
}

All your objects will be stored in the same table, but mapped to a different columns (with some common for all columns from BasePlay, see Shared columns section). Extra column PlayType will contain the type of a play.


问:
Is there another way pushing data to array in js
here is my code pushing data to an array variable, but I am getting a blank array. what am I doing wrong?

```<code>let users = []

//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
  users.push(response[i].user_name)
}
</code>```

when I run console.log this is what I got

```<code>console.log(users) // Array[]
</code>```

答:
Seems you are missing the i variable value in response.

```<code>var response=[{user_name:'abc'},{user_name:'def'}]

let users = [];

for(var i = 0; i < response.length; i++ ) {
users.push(response[i].user_name)
}
</code>```

After using this code you should get the result in users array.

Body:
here is my code pushing data to an array variable, but I am getting a blank array. what am I doing wrong?

let users = []

//looping ajax response here
for(var i = 0; i < response.length; i++ ) {
  users.push(response[i].user_name)
}

when I run console.log this is what I got

console.log(users) // Array[]

Body:
Seems you are missing the i variable value in response.

var response=[{user_name:'abc'},{user_name:'def'}]

let users = [];

for(var i = 0; i < response.length; i++ ) {
users.push(response[i].user_name)
}

After using this code you should get the result in users array.


问:
query sql SUM only 1 value on duplicate value with JOIN
I have problem again with query of sql.

I have 2 table. 'transactions' table and 'transactaion_detail' tabel.

transactions as trx

```<code>ID    TOTAL
1     2000
2     10000
3     5000
</code>```

transactions_details as td

```<code>ID    trx_id     PRICE
1       1        2000
2       2        5000
3       2        5000
4       3        1000
5       3        2000
6       3        2000
</code>```

when I query like this

```<code>select sum(trx.total) from transactions as trx
join transaction_details as td
on trx.id = td.trx_id
</code>```

I got result

37000

thats result that is not what I meant.

because when I change sum(trx.total) to trx.*

the data show like this

```<code>ID    TOTAL
1     2000
2     10000
2     10000
3     5000
3     5000
3     5000
</code>```

I want get result 17000 from that query.

I know I can just sum price on table transaction_detail or sum total on transcations without join another table. but in my case I have to join 2 table and SUM.

please help me

答:
You can first aggregate second table and then join -</p>

```<code>SELECT SUM(PRC)
FROM transactions T
JOIN (SELECT trx_id, SUM(PRICE) PRC
      FROM transactions_details
      GROUP BY trx_id) TD ON T.id = TD.trx_id
</code>```

Body:
I have problem again with query of sql.

I have 2 table. 'transactions' table and 'transactaion_detail' tabel.

transactions as trx

ID    TOTAL
1     2000
2     10000
3     5000

transactions_details as td

ID    trx_id     PRICE
1       1        2000
2       2        5000
3       2        5000
4       3        1000
5       3        2000
6       3        2000

when I query like this

select sum(trx.total) from transactions as trx
join transaction_details as td
on trx.id = td.trx_id

I got result

37000

thats result that is not what I meant.

because when I change sum(trx.total) to trx.*

the data show like this

ID    TOTAL
1     2000
2     10000
2     10000
3     5000
3     5000
3     5000

I want get result 17000 from that query.

I know I can just sum price on table transaction_detail or sum total on transcations without join another table. but in my case I have to join 2 table and SUM.

please help me

Body:
You can first aggregate second table and then join -

SELECT SUM(PRC)
FROM transactions T
JOIN (SELECT trx_id, SUM(PRICE) PRC
      FROM transactions_details
      GROUP BY trx_id) TD ON T.id = TD.trx_id


问:
Prompting an input in bash script should executes an bash function
I would like to get an output based on the input we provided. For Example,

if I selected 1 it should take the 1st element in the array and the output should be My name is test

if I selected 2 it should take the 2nd element in the array and the output should be My name is test1

similarly, if I select all the output should be My name is test
My name is test1
My name is test2
My name is test3

```<code> a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $a
}

echo "Enter a number"
select number in "test" "test1" "test2" "tes3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            testfunction "${a[@]}"; break;;
    esac
done
</code>```

Can someone please help me with this?

答:
You should be printing $1 instead of $a in your testfunction.

```<code>testfunction() {
        echo My name is $*
}
</code>```

EDIT: Changing it to consider "all" case as well.

Body:
I would like to get an output based on the input we provided. For Example,

if I selected 1 it should take the 1st element in the array and the output should be My name is test

if I selected 2 it should take the 2nd element in the array and the output should be My name is test1

similarly, if I select all the output should be My name is test
My name is test1
My name is test2
My name is test3

 a=("test" "test1" "test2" "test3")

testfunction() {
        echo My name is $a
}

echo "Enter a number"
select number in "test" "test1" "test2" "tes3" "all"; do
    case "$number" in
        test)
            testfunction "${a[0]}"; break;;
        test1)
            testfunction "${a[1]}"; break;;
        test2)
            testfunction "${a[2]}"; break;;
        test3)
            testfunction "${a[3]}"; break;;
        all)
            testfunction "${a[@]}"; break;;
    esac
done

Can someone please help me with this?

Body:
You should be printing $1 instead of $a in your testfunction.

testfunction() {
        echo My name is $*
}

EDIT: Changing it to consider "all" case as well.