问:
Update columns ONLY with properties from JSON
How i can update only fields with non-null value?

I have a class:

```<code>@Entity
@Table(name = "persons",
    schema = "persons_info")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "first_name",
        nullable = false)
    @JsonProperty("first_name")
    private String firstName;

    @Column(name = "last_name",
        nullable = false)
    @JsonProperty("last_name")
    private String lastName;

    @Column(nullable = false)
    private Integer age;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address_id",
        referencedColumnName = "id")
    private Address address;

    // setters and getters
}
</code>```

My buisness logic: i want update some fields of class in table, and need ignore null values of mapped from JSON (example: i need update ONLY columns first_name, last_name, and city (in Address)):

```<code>{
  "id": 4,
  "first_name" : "John",
  "last_name" : "Smith",
  "address" : {
    "city" : "New-York"
  }
}
</code>```

But when i tried send JSON i took exception:

```<code>org.hibernate.PropertyValueException: not-null property references a null or transient value : ru.jankbyte.autopolice.entity.Address.flat
</code>```

I tried to remove nulable = false from columns and setting @DynamicUpdate annotation under classes but thats didnt work

My rest controller and service methods:

```<code>//controller
@PostMapping(value = {"/{id}"},
    consumes = {MediaType.APPLICATION_JSON_VALUE},
    produces = {MediaType.APPLICATION_JSON_VALUE})
public Person update(@PathVariable("id") Long id,
@RequestBody Person person) {
    return service.update(id, person);
}

// service
public Person update(Long id, Person person) {
  person.setId(id);
  return save(person);
}
</code>```

Body:
How i can update only fields with non-null value?

I have a class:

@Entity
@Table(name = "persons",
    schema = "persons_info")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "first_name",
        nullable = false)
    @JsonProperty("first_name")
    private String firstName;

    @Column(name = "last_name",
        nullable = false)
    @JsonProperty("last_name")
    private String lastName;

    @Column(nullable = false)
    private Integer age;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "address_id",
        referencedColumnName = "id")
    private Address address;

    // setters and getters
}

My buisness logic: i want update some fields of class in table, and need ignore null values of mapped from JSON (example: i need update ONLY columns first_name, last_name, and city (in Address)):

{
  "id": 4,
  "first_name" : "John",
  "last_name" : "Smith",
  "address" : {
    "city" : "New-York"
  }
}

But when i tried send JSON i took exception:

org.hibernate.PropertyValueException: not-null property references a null or transient value : ru.jankbyte.autopolice.entity.Address.flat

I tried to remove nulable = false from columns and setting @DynamicUpdate annotation under classes but thats didnt work

My rest controller and service methods:

//controller
@PostMapping(value = {"/{id}"},
    consumes = {MediaType.APPLICATION_JSON_VALUE},
    produces = {MediaType.APPLICATION_JSON_VALUE})
public Person update(@PathVariable("id") Long id,
@RequestBody Person person) {
    return service.update(id, person);
}

// service
public Person update(Long id, Person person) {
  person.setId(id);
  return save(person);
}


来源: stackexchange

问:
How to use a variable in Openrowset command With SQL Commands
I want to update database from a .sql file which contain some commands like update and edit and delete.

I try hard to pass the .sql file to the procedure to make it run.

This is my code which only shows me the file instead of running it:

```<code>DECLARE @filePath nvarchar(1000)
DECLARE @command nvarchar(1000)
DECLARE @query nvarchar(1000)

SET @filePath = 'd:\amz\update_price001.sql'
SET @command = '(SELECT * FROM OPENROWSET(BULK '''+@filePath+''', SINGLE_CLOB) AS Contents)'

SELECT @command
SET @query = @command

EXEC sp_executesql @query
</code>```

This is the result of the select @command:

```<code>(SELECT * FROM OPENROWSET(BULK 'd:\amz\update_price001.sql', SINGLE_CLOB) AS Contents)
</code>```

but the result of the EXEC sp_executesql @query is the filecontent - not the execution result.

ContentLicense: CC BY-SA 4.0

Body:
I want to update database from a .sql file which contain some commands like update and edit and delete.

I try hard to pass the .sql file to the procedure to make it run.

This is my code which only shows me the file instead of running it:

DECLARE @filePath nvarchar(1000)
DECLARE @command nvarchar(1000)
DECLARE @query nvarchar(1000)

SET @filePath = 'd:\amz\update_price001.sql'
SET @command = '(SELECT * FROM OPENROWSET(BULK '''+@filePath+''', SINGLE_CLOB) AS Contents)'

SELECT @command
SET @query = @command

EXEC sp_executesql @query

This is the result of the select @command:

(SELECT * FROM OPENROWSET(BULK 'd:\amz\update_price001.sql', SINGLE_CLOB) AS Contents)

but the result of the EXEC sp_executesql @query is the filecontent - not the execution result.


问:
Printing Values in the Same Cluster Python
I am working on a 'songs' dataset that has 2973 records and 2973 unique genres. In the end, I want to create a function that takes as input one genre and print other similar genres.

I thought about doing this by applying label or one-hot encoding and then cluster using K-Means. Then the ultimate idea is that the function called 'genre_recommender' searches the input genre within the clusters and print other values within this cluster. I have done the encoding and the clustering but I can't progress even 1% in the function. How can I do it?

```<code>kmeans = KMeans(n_clusters=4, init='k-means++', max_iter=300, n_init=10, random_state=0)
cluster_labels = kmeans.fit_predict(scaled_data)

# As it's difficult to visualise clusters when the data is high-dimensional - we'll use
# boxplots to help us see how the clusters are grouping the samples

df_bonus["cluster"] = cluster_labels
</code>```

I clustered using kmeans upon 4 clusters after doing an elbow method. after this point, I am stuck.

Body:
I am working on a 'songs' dataset that has 2973 records and 2973 unique genres. In the end, I want to create a function that takes as input one genre and print other similar genres.

I thought about doing this by applying label or one-hot encoding and then cluster using K-Means. Then the ultimate idea is that the function called 'genre_recommender' searches the input genre within the clusters and print other values within this cluster. I have done the encoding and the clustering but I can't progress even 1% in the function. How can I do it?

kmeans = KMeans(n_clusters=4, init='k-means++', max_iter=300, n_init=10, random_state=0)
cluster_labels = kmeans.fit_predict(scaled_data)

# As it's difficult to visualise clusters when the data is high-dimensional - we'll use
# boxplots to help us see how the clusters are grouping the samples

df_bonus["cluster"] = cluster_labels

I clustered using kmeans upon 4 clusters after doing an elbow method. after this point, I am stuck.


问:
RequestFileSystem alternative
I use window.requestFileSystem to store video files and playing offline (like https://www.youtube.com/feed/downloads)

```<code>window.requestFileSystem(LocalFileSystem.PERSISTENT, ...)
</code>```

but as requestFileSystem is deprecated, how to store blob files correctly, which API could cover the same functionality?

Title: RequestFileSystem alternative

Body:
I use window.requestFileSystem to store video files and playing offline (like https://www.youtube.com/feed/downloads)

window.requestFileSystem(LocalFileSystem.PERSISTENT, ...)

but as requestFileSystem is deprecated, how to store blob files correctly, which API could cover the same functionality?


问:
problem in bootstrap 5 theming in rtl version
i don't know should i place bootstrap.rtl.min.css before or after app.scss theming in reactjs

```<code>

@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/maps";
@import "../node_modules/bootstrap/scss/utilities";

$font-sizes: (
  1: 12px,
  2: 14px,
  3: 16px,
  4: 18px,
  5: 20px,
  6: 22px,
  7: 24px,
  8: 26,
);

$utilities: map-merge(
  $utilities,
  (
    "font-size":
      map-merge(
        map-get($utilities, "font-size"),
        (
          values: $font-sizes,
        )
      ),
    "rounded": (
      property: border-radius,
      class: rounded,
      values: (
        null: 4px,
        0: 0,
        "sm": 3px,
        "md": 8px,
        circle: 50%,
      ),
    ),
  )
);

@import "../node_modules/bootstrap/scss/bootstrap";

</code>```

placing it after app.scss rtl override and in before ltr version override because it's called in app.scss

Body:
i don't know should i place bootstrap.rtl.min.css before or after app.scss theming in reactjs

@import "../node_modules/bootstrap/scss/functions";
@import "../node_modules/bootstrap/scss/variables";
@import "../node_modules/bootstrap/scss/maps";
@import "../node_modules/bootstrap/scss/utilities";

$font-sizes: (
  1: 12px,
  2: 14px,
  3: 16px,
  4: 18px,
  5: 20px,
  6: 22px,
  7: 24px,
  8: 26,
);

$utilities: map-merge(
  $utilities,
  (
    "font-size":
      map-merge(
        map-get($utilities, "font-size"),
        (
          values: $font-sizes,
        )
      ),
    "rounded": (
      property: border-radius,
      class: rounded,
      values: (
        null: 4px,
        0: 0,
        "sm": 3px,
        "md": 8px,
        circle: 50%,
      ),
    ),
  )
);

@import "../node_modules/bootstrap/scss/bootstrap";

placing it after app.scss rtl override and in before ltr version override because it's called in app.scss


问:
I have a task to get a list of likes from a Facebook post. Is it possible to use graph-api for this?
I am writing a desktop application for PC in C#. I'm trying to do it on Graph-API. After authorization oauth2 - there is a token. The method that is documented https://developers.facebook.com/docs/graph-api/reference/v15.0/object/likes

"https://graph.facebook.com/{object-id}
?fields=likes.summary(true)
&access_token={access-token}"

```<code>    internal class Get
    {
        public string Response { get; set; }
        public int StatusCode { get; set; }
        public Get(string uri)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            request.ContentType = "application/json; charset=utf-8";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                StatusCode = (int)response.StatusCode;
                Stream stream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream))
                {
                    Response = reader.ReadToEnd();
                }
            }
        }
    }

Get get = new Get($"https://graph.facebook.com/3475961399339788?fields=likes.summary(true)&access_token={access_token}");
</code>```

Does not work. Returns an error, 400 (Bad Request)

"(#12) singular statuses API is deprecated for versions v2.4 and higher"

Tried using the old version v2.3.

"https://graph.facebook.com/v2.3/{object-id}
?fields=likes.summary(true)
&access_token={access-token}"

Same! Who dealt with Facebook, tell me how to solve this seemingly simple task? Solution with Selenium ChromeDriver - not suitable. It does not allow you to normally get a large list of likes.
I will be glad for any information. Thanks

Body:
I am writing a desktop application for PC in C#. I'm trying to do it on Graph-API. After authorization oauth2 - there is a token. The method that is documented https://developers.facebook.com/docs/graph-api/reference/v15.0/object/likes

"https://graph.facebook.com/{object-id}
?fields=likes.summary(true)
&access_token={access-token}"

    internal class Get
    {
        public string Response { get; set; }
        public int StatusCode { get; set; }
        public Get(string uri)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            request.ContentType = "application/json; charset=utf-8";

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                StatusCode = (int)response.StatusCode;
                Stream stream = response.GetResponseStream();
                using (StreamReader reader = new StreamReader(stream))
                {
                    Response = reader.ReadToEnd();
                }
            }
        }
    }

Get get = new Get($"https://graph.facebook.com/3475961399339788?fields=likes.summary(true)&access_token={access_token}");

Does not work. Returns an error, 400 (Bad Request)

"(#12) singular statuses API is deprecated for versions v2.4 and higher"

Tried using the old version v2.3.

"https://graph.facebook.com/v2.3/{object-id}
?fields=likes.summary(true)
&access_token={access-token}"

Same! Who dealt with Facebook, tell me how to solve this seemingly simple task? Solution with Selenium ChromeDriver - not suitable. It does not allow you to normally get a large list of likes.
I will be glad for any information. Thanks


问:
How to handle ruby arrays of structs in ruby ffi gem?
This is in reference to this question but with structs instead.

I want to use the ruby ffi gem to call a c function which has an array of structs and its length as input variables.

struct MyStruct {
    char a;
    int b;
    float c;
    double d;
};

void my_function(struct MyStruct *arr, unsigned int num);
```
<p>I have created the ruby binding as:</p>
<pre class="lang-rb prettyprint-override"><code>module MyModule
    extend FFI::Library
    ffi_lib FFI::Library::LIBC
    ffi_lib "my_c_lib"

    class MyStruct < FFI::Struct
      layout(
          :a, :char,
          :b, :int,
          :c, :float,
          :d, :double
      )
    end

    attach_function :my_function, [ MyStruct.ptr, :uint ], :void
end
</code>```

I will like to make a call in ruby code like:

MyModule.my_function([#<MyModule::MyStruct>, #<MyModule::MyStruct>, #<MyModule::MyStruct>], 3)
```
<p>How do I go about this?</p>
<p>The closest I could get to solving this issue is:</p>
<pre class="lang-rb prettyprint-override"><code># Make the assumption that `arr` is a ruby array populated with `MyStruct` instances
ptr = FFI::MemoryPointer.new(MyModule::MyStruct, arr.size)
arr.size.times do | i |
    ptr.put(MyModule::MyStruct, i, arr[i]) # ERROR in `put': unsupported type 'MyModule::MyStruct' (ArgumentError)
end
MyModule.my_function(ptr, arr.length)
</code>```

I also replaced the forth line since the put function ask that the first argument be a type where FFI::StructByValue should be returning the type (based on the documentation), but another error appears:

    ptr.put(MyModule::MyStruct.by_value, i, arr[i]) # ERROR in `put': unsupported type '#<FFI::StructByValue:0x0123456789abcdef' (ArgumentError)
```

Body:
This is in reference to this question but with structs instead.

I want to use the ruby ffi gem to call a c function which has an array of structs and its length as input variables.

struct MyStruct {
    char a;
    int b;
    float c;
    double d;
};

void my_function(struct MyStruct *arr, unsigned int num);

I have created the ruby binding as:

module MyModule
    extend FFI::Library
    ffi_lib FFI::Library::LIBC
    ffi_lib "my_c_lib"

    class MyStruct < FFI::Struct
      layout(
          :a, :char,
          :b, :int,
          :c, :float,
          :d, :double
      )
    end

    attach_function :my_function, [ MyStruct.ptr, :uint ], :void
end

I will like to make a call in ruby code like:

MyModule.my_function([#<MyModule::MyStruct>, #<MyModule::MyStruct>, #<MyModule::MyStruct>], 3)

How do I go about this?

The closest I could get to solving this issue is:

# Make the assumption that `arr` is a ruby array populated with `MyStruct` instances
ptr = FFI::MemoryPointer.new(MyModule::MyStruct, arr.size)
arr.size.times do | i |
    ptr.put(MyModule::MyStruct, i, arr[i]) # ERROR in `put': unsupported type 'MyModule::MyStruct' (ArgumentError)
end
MyModule.my_function(ptr, arr.length)

I also replaced the forth line since the put function ask that the first argument be a type where FFI::StructByValue should be returning the type (based on the documentation), but another error appears:

    ptr.put(MyModule::MyStruct.by_value, i, arr[i]) # ERROR in `put': unsupported type '#<FFI::StructByValue:0x0123456789abcdef' (ArgumentError)


问:
Although I use the same services in 2 different places, I cannot pull data from the database
While I can do anything I want in the database on the free https://volkanguder.000webhostapp.com/envanterler/tum_envanterler.php site, I cannot pull the data on the paid https://volkanguder.info/envanterler/tum_envanterler.php site. When I explained the problem to the relevant place, they stated that there was a problem in the codes I wrote, but the problem was still not solved. Please help.

My Php Service Code;

```<code>
<?php
// array for JSON response
$response = array();

//DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE değişkenleri alınır.
require_once __DIR__ . '/db_config.php';

// Bağlantı oluşturuluyor.
$baglanti = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// Bağlanti kontrolü yapılır.
if (!$baglanti) {
    die("Hatalı bağlantı : " . mysqli_connect_error());
}

$sqlsorgu = "SELECT * FROM envanterler";
$result = mysqli_query($baglanti, $sqlsorgu);

// result kontrolü yap
if (mysqli_num_rows($result) > 0) {

    $response["envanterler"] = array();

    while ($row = mysqli_fetch_assoc($result)) {
        // temp user array
        $envanterler = array();

        $envanterler["envanterId"] = $row["envanterId"];
        $envanterler["envanterKategori"] = $row["envanterKategori"];
        $envanterler["envanterAdi"] = $row["envanterAdi"];
        $envanterler["envanterMarka"] = $row["envanterMarka"];
        $envanterler["envanterModel"] = $row["envanterModel"];
        $envanterler["envanterSerino"] = $row["envanterSerino"];
        $envanterler["envanterRfid"] = $row["envanterRfid"];
        $envanterler["envanterMahal"] = $row["envanterMahal"];

        // push single product into final response array
        array_push($response["envanterler"], $envanterler);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);

} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No data found";

    // echo no users JSON
    echo json_encode($response);
}
//bağlantı koparılır.
mysqli_close($baglanti);
?>

</code>```

MySQL JSON ;

```<code>[
{"type":"header","version":"4.9.7","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"volkangu_envatool"},
{"type":"table","name":"envanterler","database":"volkangu_envatool","data":
[
{"envanterId":"1","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Bilgisayar","envanterMarka":"Dell","envanterModel":"Optiplex 3050 MicroPc","envanterSerino":"12345","envanterRfid":"VG458250","envanterMahal":"MH0102030004"},
{"envanterId":"2","envanterKategori":"Pc ve Donanımlar","envanterAdi":"Monitör","envanterMarka":"Dell","envanterModel":"E2218S","envanterSerino":"12345","envanterRfid":"VG458251","envanterMahal":"MH0102030005"},
{"envanterId":"3","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Klavye","envanterMarka":"Dell","envanterModel":"KB-124-TUR","envanterSerino":"123456789","envanterRfid":"VG458252","envanterMahal":"MH0102030006"}
]
}
]

</code>```

Free Demo site Service (Working) ;
enter image description here

Hostinger Main site (Not Working) ;
enter image description here

All Hostinger Customer service recommendations

Body:
While I can do anything I want in the database on the free https://volkanguder.000webhostapp.com/envanterler/tum_envanterler.php site, I cannot pull the data on the paid https://volkanguder.info/envanterler/tum_envanterler.php site. When I explained the problem to the relevant place, they stated that there was a problem in the codes I wrote, but the problem was still not solved. Please help.

My Php Service Code;

<?php
// array for JSON response
$response = array();

//DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE değişkenleri alınır.
require_once __DIR__ . '/db_config.php';

// Bağlantı oluşturuluyor.
$baglanti = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// Bağlanti kontrolü yapılır.
if (!$baglanti) {
    die("Hatalı bağlantı : " . mysqli_connect_error());
}

$sqlsorgu = "SELECT * FROM envanterler";
$result = mysqli_query($baglanti, $sqlsorgu);

// result kontrolü yap
if (mysqli_num_rows($result) > 0) {

    $response["envanterler"] = array();

    while ($row = mysqli_fetch_assoc($result)) {
        // temp user array
        $envanterler = array();

        $envanterler["envanterId"] = $row["envanterId"];
        $envanterler["envanterKategori"] = $row["envanterKategori"];
        $envanterler["envanterAdi"] = $row["envanterAdi"];
        $envanterler["envanterMarka"] = $row["envanterMarka"];
        $envanterler["envanterModel"] = $row["envanterModel"];
        $envanterler["envanterSerino"] = $row["envanterSerino"];
        $envanterler["envanterRfid"] = $row["envanterRfid"];
        $envanterler["envanterMahal"] = $row["envanterMahal"];

        // push single product into final response array
        array_push($response["envanterler"], $envanterler);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);

} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No data found";

    // echo no users JSON
    echo json_encode($response);
}
//bağlantı koparılır.
mysqli_close($baglanti);
?>

MySQL JSON ;

[
{"type":"header","version":"4.9.7","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"volkangu_envatool"},
{"type":"table","name":"envanterler","database":"volkangu_envatool","data":
[
{"envanterId":"1","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Bilgisayar","envanterMarka":"Dell","envanterModel":"Optiplex 3050 MicroPc","envanterSerino":"12345","envanterRfid":"VG458250","envanterMahal":"MH0102030004"},
{"envanterId":"2","envanterKategori":"Pc ve Donanımlar","envanterAdi":"Monitör","envanterMarka":"Dell","envanterModel":"E2218S","envanterSerino":"12345","envanterRfid":"VG458251","envanterMahal":"MH0102030005"},
{"envanterId":"3","envanterKategori":"Bilgisayar ve Çevre Ekipmanları","envanterAdi":"Klavye","envanterMarka":"Dell","envanterModel":"KB-124-TUR","envanterSerino":"123456789","envanterRfid":"VG458252","envanterMahal":"MH0102030006"}
]
}
]

Free Demo site Service (Working) ;
enter image description here

Hostinger Main site (Not Working) ;
enter image description here

All Hostinger Customer service recommendations


问:
How to run docker containers on another machine, like virtual box?
I am a new docker user, so some things may be not correctly explained.
I have a php project (on Windows 10), and I created docker containers and images for it. All project files, like html and css are located in src folder. Near src folder I created Dockerfile and docker-compose.yml, and they are working good. After that, I created tags to all my images, and uploaded them to dockerhub. I did that to be able to run my containers on another machine using images from repository. So, in virtual box I installed linux mint, and installed docker on it. Using console, I logged into my dockerhub account, and pulled all images from it. After that I copied my docker-compose.yml file from windows to linux on virtual box, and modiffied the path of images to take them directly from docker hub, and run docker-compose up command. Everything worked fine, all images were downloaded, but when I opened localhost:8000, I saw error 403 forbidden, and also I observed that automatically was created src folder, but it was empty. So, I think that error 403 appeared because there were nothing in src folder.
So, the question is: How to upload my src folder with all project files into docker image, to be able to use them on any other machines by using only docker-compose.yml and docker-compose up command (it is impoartant, because that was the condition) ?

On windows:

Docker file code:

```<code>FROM php:8.0-apache
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
RUN apt-get update && apt-get upgrade -y
</code>```

docker-compose.yml code:

```<code>version: '3.8'
services:
  php-apache-environment:
    container_name: myPHProject
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
      - db
    volumes:
      - ./src:/var/www/html/
    ports:
      - 8000:80
  db:
    container_name: db
    image: mysql
    restart: always
    environment:
        MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
        MYSQL_DATABASE: MY_DATABASE
        MYSQL_USER: MYSQL_USER
        MYSQL_PASSWORD: MYSQL_PASSWORD
    ports:
        - "9906:3306"
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    ports:
        - '8080:80'
    restart: always
    environment:
        PMA_HOST: db
    depends_on:
        - db
</code>```

docker-compose.yml that I used on linux(without dockerfile, it is important, because that was the condition):

```<code>version: '3.8'
services:
  php-apache-environment:
    container_name: myPHProject
    image: <my dockerhub name>/project-lab4-php-apache-environment
    build:
      context: ./
    depends_on:
      - db
    volumes:
      - ./src:/var/www/html/
    ports:
      - 8000:80
  db:
    container_name: db
    image: <my dockerhub name>/mysql
    restart: always
    environment:
        MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
        MYSQL_DATABASE: MY_DATABASE
        MYSQL_USER: MYSQL_USER
        MYSQL_PASSWORD: MYSQL_PASSWORD
    ports:
        - "9906:3306"
  phpmyadmin:
    image: <my dockerhub name>/phpmyadmin
    ports:
        - '8080:80'
    restart: always
    environment:
        PMA_HOST: db
    depends_on:
        - db
</code>```

Body:
I am a new docker user, so some things may be not correctly explained.
I have a php project (on Windows 10), and I created docker containers and images for it. All project files, like html and css are located in src folder. Near src folder I created Dockerfile and docker-compose.yml, and they are working good. After that, I created tags to all my images, and uploaded them to dockerhub. I did that to be able to run my containers on another machine using images from repository. So, in virtual box I installed linux mint, and installed docker on it. Using console, I logged into my dockerhub account, and pulled all images from it. After that I copied my docker-compose.yml file from windows to linux on virtual box, and modiffied the path of images to take them directly from docker hub, and run docker-compose up command. Everything worked fine, all images were downloaded, but when I opened localhost:8000, I saw error 403 forbidden, and also I observed that automatically was created src folder, but it was empty. So, I think that error 403 appeared because there were nothing in src folder.
So, the question is: How to upload my src folder with all project files into docker image, to be able to use them on any other machines by using only docker-compose.yml and docker-compose up command (it is impoartant, because that was the condition) ?

On windows:

Docker file code:

FROM php:8.0-apache
RUN docker-php-ext-install mysqli && docker-php-ext-enable mysqli
RUN apt-get update && apt-get upgrade -y

docker-compose.yml code:

version: '3.8'
services:
  php-apache-environment:
    container_name: myPHProject
    build:
      context: ./
      dockerfile: Dockerfile
    depends_on:
      - db
    volumes:
      - ./src:/var/www/html/
    ports:
      - 8000:80
  db:
    container_name: db
    image: mysql
    restart: always
    environment:
        MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
        MYSQL_DATABASE: MY_DATABASE
        MYSQL_USER: MYSQL_USER
        MYSQL_PASSWORD: MYSQL_PASSWORD
    ports:
        - "9906:3306"
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    ports:
        - '8080:80'
    restart: always
    environment:
        PMA_HOST: db
    depends_on:
        - db

docker-compose.yml that I used on linux(without dockerfile, it is important, because that was the condition):

version: '3.8'
services:
  php-apache-environment:
    container_name: myPHProject
    image: <my dockerhub name>/project-lab4-php-apache-environment
    build:
      context: ./
    depends_on:
      - db
    volumes:
      - ./src:/var/www/html/
    ports:
      - 8000:80
  db:
    container_name: db
    image: <my dockerhub name>/mysql
    restart: always
    environment:
        MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
        MYSQL_DATABASE: MY_DATABASE
        MYSQL_USER: MYSQL_USER
        MYSQL_PASSWORD: MYSQL_PASSWORD
    ports:
        - "9906:3306"
  phpmyadmin:
    image: <my dockerhub name>/phpmyadmin
    ports:
        - '8080:80'
    restart: always
    environment:
        PMA_HOST: db
    depends_on:
        - db


问:
404 Not Found Nginx Error After SFTP Changes via FireZilla
I just updated my site's (Django; deployed via AWS Lightsail) files via FileZilla but my website won't load now, giving me a 404 error.

I've done some research and they're telling me it is an error with Nginx's conf file, but I'm not sure how I should change it to resolve the issue.

Here is the conf file:

```<code>user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
 worker_connections 768;
 # multi_accept on;
}

http {

 ##
 # Basic Settings
 ##

sendfile on;
 tcp_nopush on;
 tcp_nodelay on;
 keepalive_timeout 65;
 types_hash_max_size 2048;
 # server_tokens off;

 # server_names_hash_bucket_size 64;
 # server_name_in_redirect off;

include /etc/nginx/mime.types;
 default_type application/octet-stream;
</code>```

I've attempted to return to a previous snapshot (that used to function) by creating a new instance, but when I try to load the backup via its public IP it seems to still give me a 404.

Body:
I just updated my site's (Django; deployed via AWS Lightsail) files via FileZilla but my website won't load now, giving me a 404 error.

I've done some research and they're telling me it is an error with Nginx's conf file, but I'm not sure how I should change it to resolve the issue.

Here is the conf file:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
 worker_connections 768;
 # multi_accept on;
}

http {

 ##
 # Basic Settings
 ##

sendfile on;
 tcp_nopush on;
 tcp_nodelay on;
 keepalive_timeout 65;
 types_hash_max_size 2048;
 # server_tokens off;

 # server_names_hash_bucket_size 64;
 # server_name_in_redirect off;

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

I've attempted to return to a previous snapshot (that used to function) by creating a new instance, but when I try to load the backup via its public IP it seems to still give me a 404.


问:
How to managing mecanim animation event more efficiently?
I'm usually using the parent script object and child is a model and animator. However, this is inconvenient to use animation events because I need to retrieve a script from the parent. Is there a way to manage mecanim events more efficiently?


问:
Auto-Tuning of DBSCAN hyperparameters for clustering users' behaviours
I have to make a "behavioural model" upon a huge transactions dataset, able to return a "behavioral score" given to every new transaction of a user, comparing to the historical data of that user.

I am looking for advices on how I can run the DBSCAN with every user without manually setting every hyperparameter for each one (there are thousands).

My idea is:

extrapolate the transactions from a single user

since the datas are in 15 dimensions, I am putting MinPts = 30

i want to plot the distance of the K (= MinPts) neighbours curve and set eps = the point of maximum curvature of the curve .

The automation of the third point is giving me some difficulties. I have tried to use a library called KneeLocator, but did not give results.

I am looking for any suggestion


问:
Faild to install nokogiri 1.8.2 with native extensions
```<code>NameError: uninitialized constant Gem::Command

      Gem::Command.build_args
         ^^^^^^^^^
An error occurred while installing nokogiri (1.8.2), and Bundler cannot continue.
Make sure that `gem install nokogiri -v '1.8.2'` succeeds before bundling.
</code>```

I've tried:

```<code>gem install nokogiri -v '1.8.2'
sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev
apt-get install openssl ruby-openssl libssl-dev
gem install nokogiri -- --use-system-libraries
gem install nokogiri -- --with-xml2-config=/path/to/xml2-config
gem install nokogiri -- --with-xslt-config=/path/to/xslt-config
bundle config build.nokogiri --use-system-libraries (command that caused this new error. The error before was another, but in essence it was an error when installing nokogiri)
</code>```

Current OS: Ubuntu 22.04.1 LTS

Ruby version: ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux] (installed using RVM)

Rails version: Rails 7.0.4

Body:
NameError: uninitialized constant Gem::Command

      Gem::Command.build_args
         ^^^^^^^^^
An error occurred while installing nokogiri (1.8.2), and Bundler cannot continue.
Make sure that `gem install nokogiri -v '1.8.2'` succeeds before bundling.

I've tried:

gem install nokogiri -v '1.8.2'
sudo apt-get install build-essential patch ruby-dev zlib1g-dev liblzma-dev
apt-get install openssl ruby-openssl libssl-dev
gem install nokogiri -- --use-system-libraries
gem install nokogiri -- --with-xml2-config=/path/to/xml2-config
gem install nokogiri -- --with-xslt-config=/path/to/xslt-config
bundle config build.nokogiri --use-system-libraries (command that caused this new error. The error before was another, but in essence it was an error when installing nokogiri)

Current OS: Ubuntu 22.04.1 LTS

Ruby version: ruby 3.1.3p185 (2022-11-24 revision 1a6b16756e) [x86_64-linux] (installed using RVM)

Rails version: Rails 7.0.4


问:
Node - Do I need a centralised error handling when barely throwing any errors to prevent app from crashing?
I was implementing a centralized error handling in node and wonder: Most of the time I am not throwing errors as I do not want the app to crash in most cases (for 404 cases for example such as user not found etc). For 3xx or 4xx errors I just send it to my client instead of throwing any errors on backend. Only for 500 I would throw, however, if its a 500 it doesnt matter if I throw it or not, it would end up in my centralized handler anyways.

I wonder if I even need a centralized error handing? I feel like if I dont throw anything whats the point? Am I wrong?

```<code>class ErrorHandler extends Error {
    constructor(statusCode, message) {
        super();
        this.statusCode = statusCode;
        this.message = message;
        this.stack = Error.stack;
    };
};

const handleError = (err, res) => {
    if (!error.statusCode) {
        error.statusCode= 500;
    }
    if (error.statusCode === 301) {
        return res.status(301).redirect('/not-found');
    };
    let { statusCode, message } = err;
    res.status(statusCode).json({
        status: "error",
        statusCode,
        message
    });
};

module.exports = {
    ErrorHandler,
    handleError
};

  try {
        const user = await UserService.signup(email, password);
       ...
        res.status(200).send({userId: user._id});
    } catch (err){
        next(err);
    }
</code>```

Body:
I was implementing a centralized error handling in node and wonder: Most of the time I am not throwing errors as I do not want the app to crash in most cases (for 404 cases for example such as user not found etc). For 3xx or 4xx errors I just send it to my client instead of throwing any errors on backend. Only for 500 I would throw, however, if its a 500 it doesnt matter if I throw it or not, it would end up in my centralized handler anyways.

I wonder if I even need a centralized error handing? I feel like if I dont throw anything whats the point? Am I wrong?

class ErrorHandler extends Error {
    constructor(statusCode, message) {
        super();
        this.statusCode = statusCode;
        this.message = message;
        this.stack = Error.stack;
    };
};

const handleError = (err, res) => {
    if (!error.statusCode) {
        error.statusCode= 500;
    }
    if (error.statusCode === 301) {
        return res.status(301).redirect('/not-found');
    };
    let { statusCode, message } = err;
    res.status(statusCode).json({
        status: "error",
        statusCode,
        message
    });
};

module.exports = {
    ErrorHandler,
    handleError
};

  try {
        const user = await UserService.signup(email, password);
       ...
        res.status(200).send({userId: user._id});
    } catch (err){
        next(err);
    }


问:
NESTjs mongoose how to seed provided initial data to DB
I have a problem how to exactly seed provided initial data to DB using NEST and mogoose.
Any ideas how to do it ;D?</p>


问:
Passing a vector as va_list as a function args in C++ 17
I have the following function that sprintf format with a given vector list. The vector consist of uint64_t with the first index as hex values (%lx) always and the rest are decimal (%d):

```<code>#include <iostream>
#include <vector>
#include <string>
#include <cstdarg>
#include <cstring>
#include <memory>

std::string printVector(const char* format, ...) {
  va_list args;
  va_start(args, format);

  int size = std::vsnprintf(nullptr, 0, format, args) + 1; // Extra space for '\0'
  std::unique_ptr<char[]> buf(new char[size]);
  std::vsnprintf(buf.get(), size, format, args);

  va_end(args);
  return std::string(buf.get());
}

int main() {
  const char* format = "SMEM = %lx smId = %u abId = %u";
  std::vector<uint64_t> vec = {0x1234567890ABCDEF, 2, 4};
  std::string output = printVector(format, vec.data(), vec.size());
  std::cout << output << '\n';

  vec = {0x1234567890ABCD01, 6, 5};
  output = printVector(format, vec.data(), vec.size());
  std::cout << output << '\n';
  return 0;
}
</code>```

I want to be able to print out like this:

```<code>SMEM = 0x1234567890ABCDEF smId = 2 abId = 4
SMEM = 0x1234567890ABCD01 smId = 6 abId = 6
</code>```

but im getting this:

```<code>SMEM = 7fc24b103ec0 smId = 1259401216 abId = 3
SMEM = 0 smId = 1259401216 abId = 374
</code>```

Can someone help?

Body:
I have the following function that sprintf format with a given vector list. The vector consist of uint64_t with the first index as hex values (%lx) always and the rest are decimal (%d):

#include <iostream>
#include <vector>
#include <string>
#include <cstdarg>
#include <cstring>
#include <memory>

std::string printVector(const char* format, ...) {
  va_list args;
  va_start(args, format);

  int size = std::vsnprintf(nullptr, 0, format, args) + 1; // Extra space for '\0'
  std::unique_ptr<char[]> buf(new char[size]);
  std::vsnprintf(buf.get(), size, format, args);

  va_end(args);
  return std::string(buf.get());
}

int main() {
  const char* format = "SMEM = %lx smId = %u abId = %u";
  std::vector<uint64_t> vec = {0x1234567890ABCDEF, 2, 4};
  std::string output = printVector(format, vec.data(), vec.size());
  std::cout << output << '\n';

  vec = {0x1234567890ABCD01, 6, 5};
  output = printVector(format, vec.data(), vec.size());
  std::cout << output << '\n';
  return 0;
}

I want to be able to print out like this:

SMEM = 0x1234567890ABCDEF smId = 2 abId = 4
SMEM = 0x1234567890ABCD01 smId = 6 abId = 6

but im getting this:

SMEM = 7fc24b103ec0 smId = 1259401216 abId = 3
SMEM = 0 smId = 1259401216 abId = 374

Can someone help?


问:
get elements that are not in common between two tables
How can I from django's ORM get elements that are not in common between two tables.
For example I have a table 1 with a primary key c1 and a table 2 with a column c1.

I tried to do this but I get an error

```<code>Table1.objects.exclude(c1=Table2.objects.all()).values_list('c1', flat=True)
*** ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.
</code>```

Body:
How can I from django's ORM get elements that are not in common between two tables.
For example I have a table 1 with a primary key c1 and a table 2 with a column c1.

I tried to do this but I get an error

Table1.objects.exclude(c1=Table2.objects.all()).values_list('c1', flat=True)
*** ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.


问:
React - Dragging a file drags text/plain instead
I'm working on an Image Uploader that allows the user to drag and drop images. It works some of the time, but once in a few it just decides not to work. I checked the e.dataTransfer of the drag and drop events, and when it doesn't work, the types array is either empty or has text/plain instead of Files, and the files is empty.

I assumed this might be because of where I grab the file when I start dragging it, but there doesn't seem to be a difference - sometimes it works and sometimes it just doesn't. Also, seems to me like there has to be some way to ensure that it works...

Tried screwing around with the dataTransfer.effectAllowed and dataTransfer.dropEffect to no avail...

Here is my Drag Event handler

(onDragEnter, onDragOver, onDragLeave)

const handleDrag = (e: React.DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  // some stuff to set styling of the component
}
```
<p>And my drop handler:</p>
<pre class="lang-js prettyprint-override"><code>const handleDrop = (e: React.DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  // more styling stuff

  // temporary warning I have displayed so I can see when it doesn't work more easily
  if (!e.dataTransfer.types.includes("Files") setError();

  // handles the displaying of the image
  if (e.dataTransfer.files && e.dataTransfer.files[0]) onFileDrop(e.dataTransfer.files[0]);
}

</code>```

I checked, and when it doesn't work, the path to the image - like file:///home/USERNAME/Pictures/fantastic_mr_fox_2.jpg... I tried to simply display the image at that path but got an error message that reads Not allowed to load local resource.

Is there any way to either prevent the path from being the dragged item or to use that path and display the image?

Would highly appreciate help!

Body:
I'm working on an Image Uploader that allows the user to drag and drop images. It works some of the time, but once in a few it just decides not to work. I checked the e.dataTransfer of the drag and drop events, and when it doesn't work, the types array is either empty or has text/plain instead of Files, and the files is empty.

I assumed this might be because of where I grab the file when I start dragging it, but there doesn't seem to be a difference - sometimes it works and sometimes it just doesn't. Also, seems to me like there has to be some way to ensure that it works...

Tried screwing around with the dataTransfer.effectAllowed and dataTransfer.dropEffect to no avail...

Here is my Drag Event handler

(onDragEnter, onDragOver, onDragLeave)

const handleDrag = (e: React.DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  // some stuff to set styling of the component
}

And my drop handler:

const handleDrop = (e: React.DragEvent) => {
  e.preventDefault();
  e.stopPropagation();
  // more styling stuff

  // temporary warning I have displayed so I can see when it doesn't work more easily
  if (!e.dataTransfer.types.includes("Files") setError();

  // handles the displaying of the image
  if (e.dataTransfer.files && e.dataTransfer.files[0]) onFileDrop(e.dataTransfer.files[0]);
}

I checked, and when it doesn't work, the path to the image - like file:///home/USERNAME/Pictures/fantastic_mr_fox_2.jpg... I tried to simply display the image at that path but got an error message that reads Not allowed to load local resource.

Is there any way to either prevent the path from being the dragged item or to use that path and display the image?

Would highly appreciate help!


问:
Multivariate LSTM cross feature dependencies
I was working myself through handson-ml2, and chapter 15 in particular.

I want to generalize the multiple steps ahead approach to multiple features and one target. In order to test my understanding I create some series, which are either following a sin wave or a cos wave with some frequency.
`

```<code>import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

start = -10
stop = 10
n_steps = 2*(stop-start) #40
forecast_horizon = 10
num_features = 4

x_axis = np.linspace(start, stop, n_steps+forecast_horizon)
series_sin = np.stack([np.sin(np.random.rand() * x_axis) for i in range(10000)])
series_cos = np.stack([np.cos(np.random.rand() * x_axis) for i in range(10000)])

rand = np.random.rand(10000, n_steps + forecast_horizon).round()

target = np.where(rand, series_sin, series_cos)
series = np.stack([target, rand, series_sin, series_cos], axis = 2)

X_train = series[:7000,:n_steps]
X_valid = series[7000:9000,:n_steps]
X_test = series[9000:,:n_steps]
Y = np.empty([10000, n_steps, forecast_horizon])
for step_ahead in range(1, n_steps + 1):
  Y[:, step_ahead - 1, :] = \
  target[:, step_ahead:step_ahead + forecast_horizon] \
  .reshape(10000, forecast_horizon)
y_train = Y[:7000]
y_valid = Y[7000:9000]
y_test = Y[9000:]
</code>```

`
When plotting the target, sin and cos waves for some sample one sees that according to the rand array the target is either the sin wave or cos wave.
time series plot

Now I want to train a neural network forecasting the time series.

```<code>model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(512, activation = "linear"),
  tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
          128,
          input_shape=(n_steps,num_features),
          return_sequences=True,
          activation="sigmoid")),
  tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
          64,
          input_shape=(n_steps,num_features),
          return_sequences=True,
          activation="sigmoid")),
  tf.keras.layers.Dense(256, activation = "linear"),
  tf.keras.layers.Dense(
      forecast_horizon,
      activation = "linear")
])

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
    loss=tf.keras.losses.MeanSquaredError()
    )
model.fit(X_train, y_train,
    validation_data=(X_valid, y_valid),
    epochs=2)
</code>```

My assumption would be that it is very easy for the model to learn the task since feature 2,3,4 are perfect predictors for the target. But as one can see on the plot below the model does not learn any cross feature dependencies.

time series plot with forecast

Any ideas?

cheers,
Felix

Body:
I was working myself through handson-ml2, and chapter 15 in particular.

I want to generalize the multiple steps ahead approach to multiple features and one target. In order to test my understanding I create some series, which are either following a sin wave or a cos wave with some frequency.
`

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

start = -10
stop = 10
n_steps = 2*(stop-start) #40
forecast_horizon = 10
num_features = 4

x_axis = np.linspace(start, stop, n_steps+forecast_horizon)
series_sin = np.stack([np.sin(np.random.rand() * x_axis) for i in range(10000)])
series_cos = np.stack([np.cos(np.random.rand() * x_axis) for i in range(10000)])

rand = np.random.rand(10000, n_steps + forecast_horizon).round()

target = np.where(rand, series_sin, series_cos)
series = np.stack([target, rand, series_sin, series_cos], axis = 2)

X_train = series[:7000,:n_steps]
X_valid = series[7000:9000,:n_steps]
X_test = series[9000:,:n_steps]
Y = np.empty([10000, n_steps, forecast_horizon])
for step_ahead in range(1, n_steps + 1):
  Y[:, step_ahead - 1, :] = \
  target[:, step_ahead:step_ahead + forecast_horizon] \
  .reshape(10000, forecast_horizon)
y_train = Y[:7000]
y_valid = Y[7000:9000]
y_test = Y[9000:]

`
When plotting the target, sin and cos waves for some sample one sees that according to the rand array the target is either the sin wave or cos wave.
time series plot

Now I want to train a neural network forecasting the time series.

model = tf.keras.models.Sequential([
  tf.keras.layers.Dense(512, activation = "linear"),
  tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
          128,
          input_shape=(n_steps,num_features),
          return_sequences=True,
          activation="sigmoid")),
  tf.keras.layers.Bidirectional(
      tf.keras.layers.LSTM(
          64,
          input_shape=(n_steps,num_features),
          return_sequences=True,
          activation="sigmoid")),
  tf.keras.layers.Dense(256, activation = "linear"),
  tf.keras.layers.Dense(
      forecast_horizon,
      activation = "linear")
])

model.compile(
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),
    loss=tf.keras.losses.MeanSquaredError()
    )
model.fit(X_train, y_train,
    validation_data=(X_valid, y_valid),
    epochs=2)

My assumption would be that it is very easy for the model to learn the task since feature 2,3,4 are perfect predictors for the target. But as one can see on the plot below the model does not learn any cross feature dependencies.

time series plot with forecast

Any ideas?

cheers,
Felix


问:
I want writerow to export the data to THREE columns, not One as it is doing
My data is exporting to CSV but it is going to just one column. I want it to go to the three columns that I named in the header</p>
```<code>    for i in range (len(tieList)):
        db.writerow([myList[0][i]])
    for i in range (len(youWinList)):
        db.writerow([myList[1][i]])
    for i in range (len(computerWinsList)):
        db.writerow([myList[2][i]])

    # Single Player

    import random
    import csv

    header = ['tieList','youWinList', 'computerWinsList']
    file = open("rps.csv", "w", newline = "")

    # Print an introduction
    print("Welcome to Rock, Paper, Scissors!")

    # Create a list of choices
    choices = ["rock", "paper", "scissors"]

    #mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()

    def single_player():
        # Ask the player for their choice
        player_choice = input("Enter your choice (rock/paper/scissors): ").lower()

        # Check if the player's choice is valid
        if player_choice not in choices:
          print("Invalid choice. Please try again.")
          player_choice = input("Enter your choice (rock/paper/scissors): ").lower()

        # Choose a random option for the computer
        computer_choice = random.choice(choices)

        # Print the choices
        print(f"You chose {player_choice} and the computer chose {computer_choice}.")

        # Determine the winner
        if player_choice == computer_choice:
          print("It's a tie!")
        elif player_choice == "rock" and computer_choice == "scissors":
          print("You win!")
        elif player_choice == "paper" and computer_choice == "rock":
          print("You win!")
        elif player_choice == "scissors" and computer_choice == "paper":
          print("You win!")
        else:
          print("You lose :(")

    def multiple_players():
            # Ask the players for their choices
        player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
        player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()

        # Check if the players' choices are valid
        if player1_choice not in choices:
          print("Player 1, invalid choice. Please try again.")
          player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
        if player2_choice not in choices:
          print("Player 2, invalid choice. Please try again.")
          player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()

        # Print the choices
        print(f"Player 1 chose {player1_choice} and player 2 chose {player2_choice}.")

        # Determine the winner
        if player1_choice == player2_choice:
          print("It's a tie!")
        elif player1_choice == "rock" and player2_choice == "scissors":
          print("Player 1 wins!")
        elif player1_choice == "paper" and player2_choice == "rock":
          print("Player 1 wins!")
        elif player1_choice == "scissors" and player2_choice == "paper":
          print("Player 1 wins!")
        else:
          print("Player 2 wins!")

    tieList = []
    youWinList = []
    computerWinsList = []
    myList = [tieList, youWinList, computerWinsList]

    def simulation():
        tie = 0
        youWin = 0
        computerWins = 0
        for i in range(1000):
            choices = ['rock', 'paper', 'scissors']
            player_choice = random.choice(choices)
            computer_choice = random.choice(choices)
            print(f"You chose {player_choice} and the computer chose {computer_choice}.")

            if player_choice == computer_choice:
                tie =tie + 1
                tieList.append(1)
                print("It's a tie!")
            elif player_choice == 'rock' and computer_choice == 'scissors':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            elif player_choice == 'paper' and computer_choice == 'rock':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            elif player_choice == 'scissors' and computer_choice == 'paper':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            else:
                print("The computer wins!")
                computerWins +=1
                computerWinsList.append(1)
        print(f'You Win: {youWin}  Computer Wins: {computerWins}  Tie: {tie}')
        print(f'TieList.................................:{tieList}')

        db = csv.writer(file)
        db.writerow(header)

        for i in range (len(tieList)):
            db.writerow([myList[0][i]])
        for i in range (len(youWinList)):
            db.writerow([myList[1][i]])
        for i in range (len(computerWinsList)):
            db.writerow([myList[2][i]])

        file.close()

    while True:
        again = input("Do you want to play a game: (yes/no)? ")
        if again.lower() == 'yes':
            mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()
        if mode == 'single':
            single_player()
        if mode == 'multiple':
            multiple_players()
        if mode == 'simulation':
            simulation()

    def play_Game():
      print("Welcome to Rock, Paper, Scissors!")
      player_score = 0
      computer_score = 0

      while True:
        simulation()
        again = input("Do you want to play again (yes/no)? ")
        if again.lower() != 'yes':
          break

    play_Game()
</code>```

Body:
My data is exporting to CSV but it is going to just one column. I want it to go to the three columns that I named in the header

    for i in range (len(tieList)):
        db.writerow([myList[0][i]])
    for i in range (len(youWinList)):
        db.writerow([myList[1][i]])
    for i in range (len(computerWinsList)):
        db.writerow([myList[2][i]])

    # Single Player

    import random
    import csv

    header = ['tieList','youWinList', 'computerWinsList']
    file = open("rps.csv", "w", newline = "")

    # Print an introduction
    print("Welcome to Rock, Paper, Scissors!")

    # Create a list of choices
    choices = ["rock", "paper", "scissors"]

    #mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()

    def single_player():
        # Ask the player for their choice
        player_choice = input("Enter your choice (rock/paper/scissors): ").lower()

        # Check if the player's choice is valid
        if player_choice not in choices:
          print("Invalid choice. Please try again.")
          player_choice = input("Enter your choice (rock/paper/scissors): ").lower()

        # Choose a random option for the computer
        computer_choice = random.choice(choices)

        # Print the choices
        print(f"You chose {player_choice} and the computer chose {computer_choice}.")

        # Determine the winner
        if player_choice == computer_choice:
          print("It's a tie!")
        elif player_choice == "rock" and computer_choice == "scissors":
          print("You win!")
        elif player_choice == "paper" and computer_choice == "rock":
          print("You win!")
        elif player_choice == "scissors" and computer_choice == "paper":
          print("You win!")
        else:
          print("You lose :(")

    def multiple_players():
            # Ask the players for their choices
        player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
        player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()

        # Check if the players' choices are valid
        if player1_choice not in choices:
          print("Player 1, invalid choice. Please try again.")
          player1_choice = input("Player 1, enter your choice (rock/paper/scissors): ").lower()
        if player2_choice not in choices:
          print("Player 2, invalid choice. Please try again.")
          player2_choice = input("Player 2, enter your choice (rock/paper/scissors): ").lower()

        # Print the choices
        print(f"Player 1 chose {player1_choice} and player 2 chose {player2_choice}.")

        # Determine the winner
        if player1_choice == player2_choice:
          print("It's a tie!")
        elif player1_choice == "rock" and player2_choice == "scissors":
          print("Player 1 wins!")
        elif player1_choice == "paper" and player2_choice == "rock":
          print("Player 1 wins!")
        elif player1_choice == "scissors" and player2_choice == "paper":
          print("Player 1 wins!")
        else:
          print("Player 2 wins!")

    tieList = []
    youWinList = []
    computerWinsList = []
    myList = [tieList, youWinList, computerWinsList]

    def simulation():
        tie = 0
        youWin = 0
        computerWins = 0
        for i in range(1000):
            choices = ['rock', 'paper', 'scissors']
            player_choice = random.choice(choices)
            computer_choice = random.choice(choices)
            print(f"You chose {player_choice} and the computer chose {computer_choice}.")

            if player_choice == computer_choice:
                tie =tie + 1
                tieList.append(1)
                print("It's a tie!")
            elif player_choice == 'rock' and computer_choice == 'scissors':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            elif player_choice == 'paper' and computer_choice == 'rock':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            elif player_choice == 'scissors' and computer_choice == 'paper':
                print("You win!")
                youWin +=1
                youWinList.append(1)
            else:
                print("The computer wins!")
                computerWins +=1
                computerWinsList.append(1)
        print(f'You Win: {youWin}  Computer Wins: {computerWins}  Tie: {tie}')
        print(f'TieList.................................:{tieList}')

        db = csv.writer(file)
        db.writerow(header)

        for i in range (len(tieList)):
            db.writerow([myList[0][i]])
        for i in range (len(youWinList)):
            db.writerow([myList[1][i]])
        for i in range (len(computerWinsList)):
            db.writerow([myList[2][i]])

        file.close()

    while True:
        again = input("Do you want to play a game: (yes/no)? ")
        if again.lower() == 'yes':
            mode = input('Mode: Enter "single" or "multiple" or "simulation" ').lower()
        if mode == 'single':
            single_player()
        if mode == 'multiple':
            multiple_players()
        if mode == 'simulation':
            simulation()

    def play_Game():
      print("Welcome to Rock, Paper, Scissors!")
      player_score = 0
      computer_score = 0

      while True:
        simulation()
        again = input("Do you want to play again (yes/no)? ")
        if again.lower() != 'yes':
          break

    play_Game()


问:
VScode Remote SSH: Terminal exited with output 1 when connecting to known host
Until yesterday I was able to connect without any problems to the remote host using the remote ssh extension.

Today, before there was any prompt to enter my password, I got an error popup Visual Studio Code: Could not establish connection to "lxplus.cern.ch".

Also, there was this vscode notification

```<code>The terminal process "C:\WINDOWS\System32\cmd.exe /c (type "C:\Users\George\AppData\Local\Temp\vscode-linux-multi-line-command-lxplus.cern.ch-916464892.sh" | ssh -T -D 53187 "lxplus.cern.ch" bash) & exit /b 0" terminated with exit code: 1.
</code>```

Also, here is the SSH output:

```<code>[14:56:29.907] Log Level: 2
[14:56:29.912] remote-ssh@0.94.0
[14:56:29.913] win32 x64
[14:56:29.987] SSH Resolver called for "ssh-remote+lxplus.cern.ch", attempt 1
[14:56:29.987] "remote.SSH.useLocalServer": false
[14:56:29.988] "remote.SSH.showLoginTerminal": false
[14:56:29.988] "remote.SSH.remotePlatform": {"lxplus.cern.ch":"linux","raspberrypi.local":"linux"}
[14:56:29.988] "remote.SSH.path": undefined
[14:56:29.988] "remote.SSH.configFile": undefined
[14:56:29.989] "remote.SSH.useFlock": true
[14:56:29.989] "remote.SSH.lockfilesInTmp": false
[14:56:29.989] "remote.SSH.localServerDownload": auto
[14:56:29.989] "remote.SSH.remoteServerListenOnSocket": false
[14:56:29.989] "remote.SSH.showLoginTerminal": false
[14:56:29.990] "remote.SSH.defaultExtensions": []
[14:56:29.990] "remote.SSH.loglevel": 2
[14:56:29.990] "remote.SSH.enableDynamicForwarding": true
[14:56:29.991] "remote.SSH.enableRemoteCommand": false
[14:56:29.991] "remote.SSH.serverPickPortsFromRange": {}
[14:56:29.991] "remote.SSH.serverInstallPath": {}
[14:56:29.996] SSH Resolver called for host: lxplus.cern.ch
[14:56:29.996] Setting up SSH remote "lxplus.cern.ch"
[14:56:30.002] Using commit id "1ad8d514439d5077d2b0b7ee64d2ce82a9308e5a" and quality "stable" for server
[14:56:30.007] Install and start server if needed
[14:56:30.010] Checking ssh with "ssh -V"
[14:56:30.056] > OpenSSH_for_Windows_8.1p1, LibreS
[14:56:30.057] > SL 3.0.2

[14:56:30.061] Running script with connection command: ssh -T -D 53187 "lxplus.cern.ch" bash
[14:56:30.064] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[14:56:30.516] > & was unexpected at this time.
> ]0;C:\WINDOWS\System32\cmd.exe
[14:56:30.516] Got some output, clearing connection timeout
[14:56:31.716] "install" terminal command done
[14:56:31.717] Install terminal quit with output: ]0;C:\WINDOWS\System32\cmd.exe
[14:56:31.717] Received install output: ]0;C:\WINDOWS\System32\cmd.exe
[14:56:31.718] Failed to parse remote port from server output
[14:56:31.719] Resolver error: Error:
    at g.Create (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:583926)
    at t.handleInstallOutput (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:582540)
    at t.tryInstall (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:680469)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:642848
    at async t.withShowDetailsEvent (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:646166)
    at async t.resolve (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:643898)
    at async c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:723024
[14:56:31.725] ------
</code>```

I can connect without an issue from the terminal using ssh, and I can connect from another device using the Remote SSH extension wituout any problems.

The issue seems to be the terminal(?)

VScode suggested I check out https://code.visualstudio.com/docs/supporting/troubleshoot-terminal-launch, but I could not find something to help me.

I tried deleting the .vscode-server folder on the remote machine, but it did not fix the issue.

I believe the problem comes before trying to even contact the server.

Body:
Until yesterday I was able to connect without any problems to the remote host using the remote ssh extension.

Today, before there was any prompt to enter my password, I got an error popup Visual Studio Code: Could not establish connection to "lxplus.cern.ch".

Also, there was this vscode notification

The terminal process "C:\WINDOWS\System32\cmd.exe /c (type "C:\Users\George\AppData\Local\Temp\vscode-linux-multi-line-command-lxplus.cern.ch-916464892.sh" | ssh -T -D 53187 "lxplus.cern.ch" bash) & exit /b 0" terminated with exit code: 1.

Also, here is the SSH output:

[14:56:29.907] Log Level: 2
[14:56:29.912] remote-ssh@0.94.0
[14:56:29.913] win32 x64
[14:56:29.987] SSH Resolver called for "ssh-remote+lxplus.cern.ch", attempt 1
[14:56:29.987] "remote.SSH.useLocalServer": false
[14:56:29.988] "remote.SSH.showLoginTerminal": false
[14:56:29.988] "remote.SSH.remotePlatform": {"lxplus.cern.ch":"linux","raspberrypi.local":"linux"}
[14:56:29.988] "remote.SSH.path": undefined
[14:56:29.988] "remote.SSH.configFile": undefined
[14:56:29.989] "remote.SSH.useFlock": true
[14:56:29.989] "remote.SSH.lockfilesInTmp": false
[14:56:29.989] "remote.SSH.localServerDownload": auto
[14:56:29.989] "remote.SSH.remoteServerListenOnSocket": false
[14:56:29.989] "remote.SSH.showLoginTerminal": false
[14:56:29.990] "remote.SSH.defaultExtensions": []
[14:56:29.990] "remote.SSH.loglevel": 2
[14:56:29.990] "remote.SSH.enableDynamicForwarding": true
[14:56:29.991] "remote.SSH.enableRemoteCommand": false
[14:56:29.991] "remote.SSH.serverPickPortsFromRange": {}
[14:56:29.991] "remote.SSH.serverInstallPath": {}
[14:56:29.996] SSH Resolver called for host: lxplus.cern.ch
[14:56:29.996] Setting up SSH remote "lxplus.cern.ch"
[14:56:30.002] Using commit id "1ad8d514439d5077d2b0b7ee64d2ce82a9308e5a" and quality "stable" for server
[14:56:30.007] Install and start server if needed
[14:56:30.010] Checking ssh with "ssh -V"
[14:56:30.056] > OpenSSH_for_Windows_8.1p1, LibreS
[14:56:30.057] > SL 3.0.2

[14:56:30.061] Running script with connection command: ssh -T -D 53187 "lxplus.cern.ch" bash
[14:56:30.064] Terminal shell path: C:\WINDOWS\System32\cmd.exe
[14:56:30.516] > & was unexpected at this time.
> ]0;C:\WINDOWS\System32\cmd.exe
[14:56:30.516] Got some output, clearing connection timeout
[14:56:31.716] "install" terminal command done
[14:56:31.717] Install terminal quit with output: ]0;C:\WINDOWS\System32\cmd.exe
[14:56:31.717] Received install output: ]0;C:\WINDOWS\System32\cmd.exe
[14:56:31.718] Failed to parse remote port from server output
[14:56:31.719] Resolver error: Error:
    at g.Create (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:583926)
    at t.handleInstallOutput (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:582540)
    at t.tryInstall (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:680469)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:642848
    at async t.withShowDetailsEvent (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:646166)
    at async t.resolve (c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:643898)
    at async c:\Users\George\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:723024
[14:56:31.725] ------

I can connect without an issue from the terminal using ssh, and I can connect from another device using the Remote SSH extension wituout any problems.

The issue seems to be the terminal(?)

VScode suggested I check out https://code.visualstudio.com/docs/supporting/troubleshoot-terminal-launch, but I could not find something to help me.

I tried deleting the .vscode-server folder on the remote machine, but it did not fix the issue.

I believe the problem comes before trying to even contact the server.


问:
react is working on development but error with production.min?
This is a runtime error, not a compile time error。
When I reference umd/react.development.js, the page is normal. However, when i change it to umd/react.production.min.js, I got error message

!! (dist\react.production.min.js, line:9, col:173) - ReferenceError: self is not defined
!! (dist\main.js, line:26, col:21) - ReferenceError: React is not defined
```

Because it is a UMD, the registration of react to global variables is done through self executing anonymous functions. I tried to change the statement of self to that in 'development. js', but it didn't work. The web still couldn't find the React

I tried react@16.1 @17 @18，

im sure react.*.js is inculded befor main.js,by console.log

Body:
This is a runtime error, not a compile time error。
When I reference umd/react.development.js, the page is normal. However, when i change it to umd/react.production.min.js, I got error message

!! (dist\react.production.min.js, line:9, col:173) - ReferenceError: self is not defined
!! (dist\main.js, line:26, col:21) - ReferenceError: React is not defined

Because it is a UMD, the registration of react to global variables is done through self executing anonymous functions. I tried to change the statement of self to that in 'development. js', but it didn't work. The web still couldn't find the React

I tried react@16.1 @17 @18，

im sure react.*.js is inculded befor main.js,by console.log


问:
Swift $sort order for BSON RealmSwift document
TLDR:
how can I write a document with a definitive order for the key value pairs to pass as key to the $sort stage?

I stumbled across very strange behaviour in my aggregate query that I am running in Swift (using RealmSwift package) through:

db.collection(withName: "Example")..aggregate(pipeline: aggregatePipeline) { ... }
```
<p>This is the stage that is behaving very strangely:</p>
<pre class="lang-swift prettyprint-override"><code>let aggregatePipeline: [Document] = [
                [
                    "$sort": [ "seen": 1 , "score": -1, "_id": -1 ]
                ]
]
</code>```

The results I get are sorted by these three keys, but in seemingly arbitrary sorting order each time I run the query. So sometimes the "seen" sorting is prioritised (as it should be) but sometimes it sorts first by "_id", or "score". When I print the stage right after defining it by running:

print(aggregatePipeline[0])
```
<p>I do see a the probable reason for those odd results...
first run:</p>
<pre class="lang-swift prettyprint-override"><code>["$sort": Optional(RealmSwift.AnyBSON.document(["_id": Optional(RealmSwift.AnyBSON.int64(-1)), "seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1))]))]
</code>```

second run:

["$sort": Optional(RealmSwift.AnyBSON.document(["seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1)), "_id": Optional(RealmSwift.AnyBSON.int64(-1))]))]
```

how can I write this query with a definitive sorting order? Or more simply: how can I write a document with a definitive order for the key value pairs to pass as key to the $sort stage? I found nothing in the relevant docs or especially this where it should definitely be stated how this could be accomplished, since this would be the most sensible way, but obviously is the wrong way of doing it.

Body:
TLDR:
how can I write a document with a definitive order for the key value pairs to pass as key to the $sort stage?

I stumbled across very strange behaviour in my aggregate query that I am running in Swift (using RealmSwift package) through:

db.collection(withName: "Example")..aggregate(pipeline: aggregatePipeline) { ... }

This is the stage that is behaving very strangely:

let aggregatePipeline: [Document] = [
                [
                    "$sort": [ "seen": 1 , "score": -1, "_id": -1 ]
                ]
]

The results I get are sorted by these three keys, but in seemingly arbitrary sorting order each time I run the query. So sometimes the "seen" sorting is prioritised (as it should be) but sometimes it sorts first by "_id", or "score". When I print the stage right after defining it by running:

print(aggregatePipeline[0])

I do see a the probable reason for those odd results...
first run:

["$sort": Optional(RealmSwift.AnyBSON.document(["_id": Optional(RealmSwift.AnyBSON.int64(-1)), "seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1))]))]

second run:

["$sort": Optional(RealmSwift.AnyBSON.document(["seen": Optional(RealmSwift.AnyBSON.int64(1)), "score": Optional(RealmSwift.AnyBSON.int64(-1)), "_id": Optional(RealmSwift.AnyBSON.int64(-1))]))]

how can I write this query with a definitive sorting order? Or more simply: how can I write a document with a definitive order for the key value pairs to pass as key to the $sort stage? I found nothing in the relevant docs or especially this where it should definitely be stated how this could be accomplished, since this would be the most sensible way, but obviously is the wrong way of doing it.


问:
Access a character device from kernel space
I've edited this question to generalize it a big deal.

Questions about opening/interacting with a file from kernel space have been asked a number of times already, e.g. here or here. Especially this one had a very useful answer to me, with pointers to other resources why it's usually a bad idea and how to do it anyway. Any of these solutions ("how to do it anyway") date back a few years, before set_fs() was deprecated. Now this question can be read in two parts.

First, out of curiosity, because I couldn't find any explanation, is there another technique to still do what above resources did using set_fs()?

And second, there might be use cases, where a kernel module only provides a file-based interface and doesn't export anything else. It might still be useful to interact with it from another kernel module. Assuming I can't patch the original module, I'd need to communicate with this file then, from within the kernel. Let's take kcov as an example, it uses a debugfs file for its IO, but doesn't do much more with it than to store its central struct kcov in filp->private_data. In such cases it seems like a full-featured open etc. might not even be necessary, it could suffice to get the pointers from struct file_operations and to get/assemble file/inode/dentry to have appropriate parameters for these functions.

Why don't you simply patch the original thing? - I might still do this when the answer to this question tells me there is no reasonable other option.


问:
Keycloak per-client keys
A Keycloak realm has a single active keypair at a time, which is used to sign and verify tokens of any realm client. How can I make sure that each client uses their own set of active/passive keypairs? More particularly:

When issuing a JWT, only a private key that is specific to the requesting client should be used to compute the signature.

When authenticating a JWT, the public key used to verify the signature should be retrieved based on the key id and the client id.

I'm guessing that this cannot be achieved without implementing a custom provider. If that is the case, could you briefly outline what the implementation would look like?

Title: Keycloak per-client keys


问:
Statsmodels: How to add numbers in the formula
How can I  add numbers in the formula? ex:</p>
```<code>sm.ols(formula = 'weight ~ 2.30 + mpg*2 + horsepower', data=mpg).fit()
</code>```

Body:
How can I  add numbers in the formula? ex:

sm.ols(formula = 'weight ~ 2.30 + mpg*2 + horsepower', data=mpg).fit()


问:
How to get GCP sign-up credits?
I have received the sign-up verification email from gcp saying that: "Verify your business email address today to receive up to $700 USD in additional credit to use during your free trial.". But there are no instructions on where/how-to to do it. Any idea anyone?

I have tried looking into billing and profile details. My business email is already in there --I had supplied that while signing up.

Title: How to get GCP sign-up credits?


问:
how to convert latitude longitude to address data in jupyter
I have a latitude longitude csv file.
The csv file that I have is look like this below and this data has over 100,000.

```<code>destination_latitidue destination_latitude
37.514623             37.514623
37.506767             37.506767
35.534793             35.534793
37.444741             37.444741
37.495687             37.495687
...
</code>```

I want to change the latitude and longitude in this file to Korean addresses and save it again as a csv file. I tried to solve this code with geolocoder.reverse but I couldn't... anyone knows how to solve this?

Body:
I have a latitude longitude csv file.
The csv file that I have is look like this below and this data has over 100,000.

destination_latitidue destination_latitude
37.514623             37.514623
37.506767             37.506767
35.534793             35.534793
37.444741             37.444741
37.495687             37.495687
...

I want to change the latitude and longitude in this file to Korean addresses and save it again as a csv file. I tried to solve this code with geolocoder.reverse but I couldn't... anyone knows how to solve this?


问:
How to compile ebitengine for a specific version of android?
In help to the command, the only line, it collects, as I understand it:

```<code>ebitenmobile bind [-target android|ios] [-bootclasspath ] [-classpath ] [-o output] [build flags] [package]
</code>```

The minimum android version that I have is 19, the goal is 30-33, there is a place in the command for this [build flags]. I try like this but it doesn’t work:

```<code>./ebitenmobile bind -target android -javapkg my.game . -o . -androidapi 30
</code>```

I tried to arrange them differently, the error is the same - version 16 was not found, so it does not see -androidapi 30 / -androidapi=30, gomobile collects everything, yes, but they say that this is only for tests. If you run this application on the device, it will not work at all, or at least not normally.

How do I tell the team that I want to change the api version?

The main problem why I'm doing this is the error I get after installing and running the application stating that the version of the application is for an earlier version of android, even if you install an application with API 33 on Android 11 with API 30.

https://ebitengine.org/en/documents/mobile.html

Body:
In help to the command, the only line, it collects, as I understand it:

ebitenmobile bind [-target android|ios] [-bootclasspath ] [-classpath ] [-o output] [build flags] [package]

The minimum android version that I have is 19, the goal is 30-33, there is a place in the command for this [build flags]. I try like this but it doesn’t work:

./ebitenmobile bind -target android -javapkg my.game . -o . -androidapi 30

I tried to arrange them differently, the error is the same - version 16 was not found, so it does not see -androidapi 30 / -androidapi=30, gomobile collects everything, yes, but they say that this is only for tests. If you run this application on the device, it will not work at all, or at least not normally.

How do I tell the team that I want to change the api version?

The main problem why I'm doing this is the error I get after installing and running the application stating that the version of the application is for an earlier version of android, even if you install an application with API 33 on Android 11 with API 30.

https://ebitengine.org/en/documents/mobile.html


问:
Vfx graph does not play in Unity editor
I installed the VFX graph for use in Unity, created an effect in the VFX graph, and inserted it into the Hierarchy as a GameObject.

However, no matter how many times I pressed the play() button in the editor and ran the game, Vfx did not run.
How do I get Vfx running? I would appreciate it if you could let me know.

I tried pressing the Play button several times to run the VFX and even running the game, but it didn't run at all. The game's Render pipeline is built-in.

Title: Vfx graph does not play in Unity editor


问:
When I click back button the account is log out in java in android
I have 4 (four) activity in my project. Main Activity, LoginActivity, DashboardAdmin Activity and CategoryAdd Activity.

I am using login system in the LoginActivity and I am logining. After that I am adding a category with userid in my app to firebase. I able to do this but without adding category or after adding category in the CategoryAddActivity I click to back navigation button the account is logout. (normally it must go to DashboardAdminActivity but goes to MainActivity) Everytime I must login again. I want to click back button without logout.

here is the problem: after logging in, there is no problem navigating through activities.  but when I press the back button on the Add category page, it exits my account and redirects it to the login page again.  normally it should have taken me to the admin page without logging out of my account.  I have to re-login every time I press the back button after adding a category.  I want it to not exit until I click the logout button.

what can i do to fix this problem?

DashboardAdmin Activity

```<code>
public class DashboardAdminActivity extends AppCompatActivity {

 private ActivityDashboardAdminBinding binding;

    //firebase auth
    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityDashboardAdminBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //init firebase auth
        firebaseAuth=FirebaseAuth.getInstance();
        checkUser();

        binding.logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                firebaseAuth.signOut();
                checkUser();
            }
        });

        //handle click, start category add screen
        binding.addCategoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DashboardAdminActivity.this,CategoryAddActivity.class));
                finish();
            }
        });
    }

    private void checkUser() {
        //get current user
        FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
        if (firebaseUser == null){
            //not logged in go to main screen
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }
        else{
            //logged in get user info
            String email= firebaseUser.getEmail();
            //set in textview of toolbar
            binding.subtitleTv.setText(email);
        }
    }
</code>```

CategoryAddActivity

```<code>public class CategoryAddActivity extends AppCompatActivity {

    private ActivityCategoryAddBinding binding;

    //firebase auth
    private FirebaseAuth firebaseAuth;

    //progress dialog
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityCategoryAddBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //init firebase auth
        firebaseAuth=FirebaseAuth.getInstance();

        //configure progress dialog
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("please wait!");
        progressDialog.setCanceledOnTouchOutside(false);

        //handle click go back
        binding.backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        //handle click begin upload category
        binding.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                validateData();
            }
        });
    }

    private String category="";
    private void validateData() {
        /*Before adding validate data*/

        //get data
        category=binding.categoryEt.getText().toString().trim();
        //validate if not empty
        if (TextUtils.isEmpty(category)){
            Toast.makeText(this, "please wriete a category name..", Toast.LENGTH_SHORT).show();
        }
        else{
            addCategoryFirebase();
        }
    }

    private void addCategoryFirebase() {
        //show progress
        progressDialog.setMessage("category adding..");
        progressDialog.show();

        //get timestamp
        Long timestamp=System.currentTimeMillis();
        //setup info to add in firebase db
        HashMap<String, Object> hashMap=new HashMap<>();
        hashMap.put("id",""+timestamp);
        hashMap.put("category",""+category);
        hashMap.put("timestamp",timestamp);
        hashMap.put("uid",""+firebaseAuth.getUid());

        //set data to db
        DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Categories");
        ref.child(""+timestamp)
                .setValue(hashMap)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        //data added to db
                        progressDialog.dismiss();
                        Toast.makeText(CategoryAddActivity.this, "category added succesfully.", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //data not added to db
                        progressDialog.dismiss();
                        Toast.makeText(CategoryAddActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }
</code>```

Body:
I have 4 (four) activity in my project. Main Activity, LoginActivity, DashboardAdmin Activity and CategoryAdd Activity.

I am using login system in the LoginActivity and I am logining. After that I am adding a category with userid in my app to firebase. I able to do this but without adding category or after adding category in the CategoryAddActivity I click to back navigation button the account is logout. (normally it must go to DashboardAdminActivity but goes to MainActivity) Everytime I must login again. I want to click back button without logout.

here is the problem: after logging in, there is no problem navigating through activities.  but when I press the back button on the Add category page, it exits my account and redirects it to the login page again.  normally it should have taken me to the admin page without logging out of my account.  I have to re-login every time I press the back button after adding a category.  I want it to not exit until I click the logout button.

what can i do to fix this problem?

DashboardAdmin Activity

public class DashboardAdminActivity extends AppCompatActivity {

 private ActivityDashboardAdminBinding binding;

    //firebase auth
    private FirebaseAuth firebaseAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityDashboardAdminBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //init firebase auth
        firebaseAuth=FirebaseAuth.getInstance();
        checkUser();

        binding.logoutBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                firebaseAuth.signOut();
                checkUser();
            }
        });

        //handle click, start category add screen
        binding.addCategoryBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(DashboardAdminActivity.this,CategoryAddActivity.class));
                finish();
            }
        });
    }

    private void checkUser() {
        //get current user
        FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
        if (firebaseUser == null){
            //not logged in go to main screen
            startActivity(new Intent(this,MainActivity.class));
            finish();
        }
        else{
            //logged in get user info
            String email= firebaseUser.getEmail();
            //set in textview of toolbar
            binding.subtitleTv.setText(email);
        }
    }

CategoryAddActivity

public class CategoryAddActivity extends AppCompatActivity {

    private ActivityCategoryAddBinding binding;

    //firebase auth
    private FirebaseAuth firebaseAuth;

    //progress dialog
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding=ActivityCategoryAddBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        //init firebase auth
        firebaseAuth=FirebaseAuth.getInstance();

        //configure progress dialog
        progressDialog=new ProgressDialog(this);
        progressDialog.setTitle("please wait!");
        progressDialog.setCanceledOnTouchOutside(false);

        //handle click go back
        binding.backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        //handle click begin upload category
        binding.submitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                validateData();
            }
        });
    }

    private String category="";
    private void validateData() {
        /*Before adding validate data*/

        //get data
        category=binding.categoryEt.getText().toString().trim();
        //validate if not empty
        if (TextUtils.isEmpty(category)){
            Toast.makeText(this, "please wriete a category name..", Toast.LENGTH_SHORT).show();
        }
        else{
            addCategoryFirebase();
        }
    }

    private void addCategoryFirebase() {
        //show progress
        progressDialog.setMessage("category adding..");
        progressDialog.show();

        //get timestamp
        Long timestamp=System.currentTimeMillis();
        //setup info to add in firebase db
        HashMap<String, Object> hashMap=new HashMap<>();
        hashMap.put("id",""+timestamp);
        hashMap.put("category",""+category);
        hashMap.put("timestamp",timestamp);
        hashMap.put("uid",""+firebaseAuth.getUid());

        //set data to db
        DatabaseReference ref= FirebaseDatabase.getInstance().getReference("Categories");
        ref.child(""+timestamp)
                .setValue(hashMap)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        //data added to db
                        progressDialog.dismiss();
                        Toast.makeText(CategoryAddActivity.this, "category added succesfully.", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        //data not added to db
                        progressDialog.dismiss();
                        Toast.makeText(CategoryAddActivity.this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
    }


问:
using data retrieved from firebase repositry outside of function in Kotlin
I take the base64 data type image from firebase and assign it to the "decoded_card2" variable as a bitmap. However, I cannot use this variable outside of the "fromFirebase_card2.get()" function I created. How can I do that ?

NOTE: My goal is to create a bitmap array of images like this one and shuffle all of them.

```<code>val fromFirebase_card2 = collection_cards.document("albus")
fromFirebase_card2.get()
    .addOnSuccessListener{ document ->

        var Cards_b64 = document.data!!["image"].toString()
        var Cards_bytes = Base64.decode(Cards_b64, Base64.DEFAULT)
        var decoded_card2 = BitmapFactory.decodeByteArray(Cards_bytes, 0, Cards_bytes.size)

    }.addOnFailureListener{exception ->
        Toast.makeText(this,"Failed",Toast.LENGTH_LONG).show()
    }
</code>```

Thanks for the help!

I tried to define the decoded_card2 variable as Bitmap?=null before the get function, but the program does not detect this change when it exits the function, its value remains null.

Body:
I take the base64 data type image from firebase and assign it to the "decoded_card2" variable as a bitmap. However, I cannot use this variable outside of the "fromFirebase_card2.get()" function I created. How can I do that ?

NOTE: My goal is to create a bitmap array of images like this one and shuffle all of them.

val fromFirebase_card2 = collection_cards.document("albus")
fromFirebase_card2.get()
    .addOnSuccessListener{ document ->

        var Cards_b64 = document.data!!["image"].toString()
        var Cards_bytes = Base64.decode(Cards_b64, Base64.DEFAULT)
        var decoded_card2 = BitmapFactory.decodeByteArray(Cards_bytes, 0, Cards_bytes.size)

    }.addOnFailureListener{exception ->
        Toast.makeText(this,"Failed",Toast.LENGTH_LONG).show()
    }

Thanks for the help!

I tried to define the decoded_card2 variable as Bitmap?=null before the get function, but the program does not detect this change when it exits the function, its value remains null.


问:
How I Can Get The Real Time & Date Of User with php
I have an Android App linked to an SQL database,

Now when the user posts a comment from the app, I want to get his real time and date (based on user's timezone).

I've already tried functions like date() and time() but these functions get the remote server time not the user's time.

Is there an api or similar, that I can use to do that - such as get time from IP address ?