问:
How do you recode a variable whilst keeping the value labels in Stata?
I have a variable 'gender' that is coded 1=Male 2=Female. I just want to recode it so Male=0 and Female=1.

I tried this:

```<code>recode gender 1=0 2=1
</code>```

which gives me the right code but now Males just come up as '0s' and Females come up as 'Male'. I am assuming because Stata associates the value label 'Male' with the numeric code 1 and as it has no associated value label for 0, it just comes up as 0.

So I tried this:

```<code>label define gender 0 "Male" 1 "Female", modify
</code>```

and

```<code>label define gender 0 "Male" 1 "Female", replace
</code>```

Neither do anything.

I want to recode whilst keeping the value labels please or at least be able to rename them so it can go back to Male and Female. How do I do this?

Body:
I have a variable 'gender' that is coded 1=Male 2=Female. I just want to recode it so Male=0 and Female=1.

I tried this:

recode gender 1=0 2=1

which gives me the right code but now Males just come up as '0s' and Females come up as 'Male'. I am assuming because Stata associates the value label 'Male' with the numeric code 1 and as it has no associated value label for 0, it just comes up as 0.

So I tried this:

label define gender 0 "Male" 1 "Female", modify

and

label define gender 0 "Male" 1 "Female", replace

Neither do anything.

I want to recode whilst keeping the value labels please or at least be able to rename them so it can go back to Male and Female. How do I do this?


来源: stackexchange

问:
Firebase JS db._checkNotDeleted is not a function
I'm writing a program that needs to add JSON data to my realtime firebase database, however I keep getting TypeError: db._checkNotDeleted is not a function at the ref() statement.

```<code>const { firebaseConfig } = require("./key");
const { EMAIL, PASSWORD } = require("./login");
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
const { getDatabase, ref, update } = require("firebase/database");

async function setupFirebase(firebaseConfig, email, password) {
  const app = initializeApp(firebaseConfig);
  const auth = getAuth(app);
  try {
    await signInWithEmailAndPassword(auth, email, password);
  } catch (e) {
    console.error(e.message);
  }
  return getDatabase(app);
}

const db = setupFirebase(firebaseConfig, EMAIL, PASSWORD);

try {
  const jsonData = require("foldername/filename");
  update(ref(db, "machines/" + jsonData.MachineID), {
    timestamp: jsonData.DateTimeMessage,
    status: jsonData.Status,
  });
} catch (e) {
  console.error(e);
}
</code>```

I have already tried to use set() or split my update to mimic the firebase docs as closely as possible but without any success. The problem seems to originate from the ref() statement itself as I cannot seem to use it in any way.

ContentLicense: CC BY-SA 4.0

Body:
I'm writing a program that needs to add JSON data to my realtime firebase database, however I keep getting TypeError: db._checkNotDeleted is not a function at the ref() statement.

const { firebaseConfig } = require("./key");
const { EMAIL, PASSWORD } = require("./login");
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
const { getDatabase, ref, update } = require("firebase/database");

async function setupFirebase(firebaseConfig, email, password) {
  const app = initializeApp(firebaseConfig);
  const auth = getAuth(app);
  try {
    await signInWithEmailAndPassword(auth, email, password);
  } catch (e) {
    console.error(e.message);
  }
  return getDatabase(app);
}

const db = setupFirebase(firebaseConfig, EMAIL, PASSWORD);

try {
  const jsonData = require("foldername/filename");
  update(ref(db, "machines/" + jsonData.MachineID), {
    timestamp: jsonData.DateTimeMessage,
    status: jsonData.Status,
  });
} catch (e) {
  console.error(e);
}

I have already tried to use set() or split my update to mimic the firebase docs as closely as possible but without any success. The problem seems to originate from the ref() statement itself as I cannot seem to use it in any way.


问:
What is the actual proper new way of implementing the Facebook login in an Android app in Java?
The Facebook guide still shows Overridden onActivityResult method, which is deprecated now. This method is not working for me as after the login this method is not overridden and the app just goes back to the login page.

Facebook mentions that if I'm using AndroidX, then there's no need to override this method but I couldn't find any useful articles/documentation on how to do go about implementing this. Yes, I know there are many questions about this, but none of them have a working answer.

I tried the method with LogicButton class and LoginManager class but it seems like these are old methods of doing this as these are not even present in latest SDK release.


问:
Getting django accept phpBB users
My Problem is, I want to create a extra website on a phpBB forum to provide extra stuff and registration for meeting. No problem I know django and python, so this is no problem.

But I would be nice, if I could accept a session from a user or import the phpBB users so that they can login to my app.

I found django-phpBB, but I don't want to access the data. If I read correctly, my case is not the use case of django-phpBB.

Can anybody give me a good advice?

Title: Getting django accept phpBB users


问:
How to specify which Gradle version is used in a freestyle pipeline Jenkins
I wanted to change the version of Gradle used in Jenkins Pipeline.

It keeps reverting to 6.8 although 7.5 is installed on machine.
I tried using sdkman and that works in terminal but I couldn't get it working on Jenkins Pipeline.


问:
Is there any recursion here? Can i make a better performance code? Bot Telegram made in Node.Js
I realized that after a few days of running this code it starts to generate duplicate console.log, would that be some recursive action or something in the code that I wrote in an ineffective way that causes this situation?

Here is my code, to make a loop I used the setTimeout function, but I don't know if this is the best solution for long term performance mainly being a 24/7 online bot on a weak home computer that I will be using as a server.

```<code>const momentTimeZone = require('moment-timezone');

function timezoneRecifeFormated() {
  return momentTimeZone.tz("America/Recife").format('HH:mm');
}

function timezoneRecifeHour() {
  return momentTimeZone.tz("America/Recife").hour();
}

const minimumRangeMinute = 3;
const maxRangeMinute = 6;

function foo_interval_action() {
  if (pauseBot == false) {
    let RedOrGreen = Math.random();

    let onlinePeriod = timezoneRecifeHour() > 7 || timezoneRecifeHour() < 3;
    let offlinePeriod = timezoneRecifeHour() >= 3 && timezoneRecifeHour() <= 7

    console.log('red or green math random = ' + RedOrGreen);
    console.log('ONLINE period = ' + onlinePeriod);
    console.log('OFFLINE period = ' + offlinePeriod);

    if (RedOrGreen < 0.7 && onlinePeriod) {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log('GREEN aposte agora!' + timezoneRecifeFormated());
    } else if (RedOrGreen >= 0.7 && onlinePeriod) {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log(('RED CUIDADO!') + timezoneRecifeFormated());
    } else {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log('Bot offline, fora do periodo de trabalho. Agora são ' + timezoneRecifeFormated());
    }
  }
}

setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
next();
});

function getRandomInterval(min, max) {
  let randomInterval = Math.floor(Math.random() * (max - min) + min); // Not include the max value
  console.log('randomInterval = Daqui a ' + randomInterval + ' minutos.timeZone Recife agora = ' + timezoneRecifeFormated());
  return randomInterval * 60000;
};
</code>```

Body:
I realized that after a few days of running this code it starts to generate duplicate console.log, would that be some recursive action or something in the code that I wrote in an ineffective way that causes this situation?

Here is my code, to make a loop I used the setTimeout function, but I don't know if this is the best solution for long term performance mainly being a 24/7 online bot on a weak home computer that I will be using as a server.

const momentTimeZone = require('moment-timezone');

function timezoneRecifeFormated() {
  return momentTimeZone.tz("America/Recife").format('HH:mm');
}

function timezoneRecifeHour() {
  return momentTimeZone.tz("America/Recife").hour();
}

const minimumRangeMinute = 3;
const maxRangeMinute = 6;

function foo_interval_action() {
  if (pauseBot == false) {
    let RedOrGreen = Math.random();

    let onlinePeriod = timezoneRecifeHour() > 7 || timezoneRecifeHour() < 3;
    let offlinePeriod = timezoneRecifeHour() >= 3 && timezoneRecifeHour() <= 7

    console.log('red or green math random = ' + RedOrGreen);
    console.log('ONLINE period = ' + onlinePeriod);
    console.log('OFFLINE period = ' + offlinePeriod);

    if (RedOrGreen < 0.7 && onlinePeriod) {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log('GREEN aposte agora!' + timezoneRecifeFormated());
    } else if (RedOrGreen >= 0.7 && onlinePeriod) {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log(('RED CUIDADO!') + timezoneRecifeFormated());
    } else {
      setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
      console.log('Bot offline, fora do periodo de trabalho. Agora são ' + timezoneRecifeFormated());
    }
  }
}

setTimeout(foo_interval_action, getRandomInterval(minimumRangeMinute, maxRangeMinute));
next();
});

function getRandomInterval(min, max) {
  let randomInterval = Math.floor(Math.random() * (max - min) + min); // Not include the max value
  console.log('randomInterval = Daqui a ' + randomInterval + ' minutos.timeZone Recife agora = ' + timezoneRecifeFormated());
  return randomInterval * 60000;
};


问:
Why does reborrowing an `impl Read` allow it to be copied
Consider the following function (using ZlibDecoder). It reads some data (just a random f64 in this case) from a reader that may or not be compressed. I use &mut dyn Read to erase the fact that compression is used (or not).

    fn read_data(reader: &mut (impl Read + Seek), is_compressed: bool) -> Result<f64> {
        let start_pos = reader.stream_position()?;
        let mut zlib_decoder;

        let mut compressed_reader: &mut dyn Read = if !is_compressed {
            reader
        } else {
            zlib_decoder = ZlibDecoder::new(reader);
            &mut zlib_decoder
        };

        let data = compressed_reader.read_f64()?;

        // Skip to next bit of data.
        reader.seek(SeekFrom::Start(start_pos + 100))?;

        Ok(data)
    }
```
<p>It almost works but it gives an error like this:</p>
```error[E0382]: borrow of moved value: `reader`
    |
604 |     fn read_data(reader: &mut (impl Read + Seek), is_compressed: bool) -> Result<f64> {
    |                  ------ move occurs because `reader` has type `&mut impl Read + Seek`, which does not implement the `Copy` trait
...
621 |             zlib_decoder = ZlibDecoder::new(reader);
    |                                             ------ value moved here
...
653 |         reader.seek(SeekFrom::Start(start_pos + 100))?;
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move
```
<p>Ok fair enough you can't just copy a <code>&mut impl Read</code> - I guess that would give you two <code>&mut</code>s to the same data which isn't allowed. But if I change the <code>ZlibDecoder::new(reader)</code> line to this:</p>
<pre class="lang-rust prettyprint-override"><code>            zlib_decoder = ZlibDecoder::new(&mut *reader);
</code>```

Then it works! Can anyone tell me what is going on here? I kind of just guessed the solution and got lucky. I vaguely recall reading something about reborrowing and maybe it's something to do with that?

Body:
Consider the following function (using ZlibDecoder). It reads some data (just a random f64 in this case) from a reader that may or not be compressed. I use &mut dyn Read to erase the fact that compression is used (or not).

    fn read_data(reader: &mut (impl Read + Seek), is_compressed: bool) -> Result<f64> {
        let start_pos = reader.stream_position()?;
        let mut zlib_decoder;

        let mut compressed_reader: &mut dyn Read = if !is_compressed {
            reader
        } else {
            zlib_decoder = ZlibDecoder::new(reader);
            &mut zlib_decoder
        };

        let data = compressed_reader.read_f64()?;

        // Skip to next bit of data.
        reader.seek(SeekFrom::Start(start_pos + 100))?;

        Ok(data)
    }

It almost works but it gives an error like this:

error[E0382]: borrow of moved value: `reader`
    |
604 |     fn read_data(reader: &mut (impl Read + Seek), is_compressed: bool) -> Result<f64> {
    |                  ------ move occurs because `reader` has type `&mut impl Read + Seek`, which does not implement the `Copy` trait
...
621 |             zlib_decoder = ZlibDecoder::new(reader);
    |                                             ------ value moved here
...
653 |         reader.seek(SeekFrom::Start(start_pos + 100))?;
    |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ value borrowed here after move

Ok fair enough you can't just copy a &mut impl Read - I guess that would give you two &muts to the same data which isn't allowed. But if I change the ZlibDecoder::new(reader) line to this:

            zlib_decoder = ZlibDecoder::new(&mut *reader);

Then it works! Can anyone tell me what is going on here? I kind of just guessed the solution and got lucky. I vaguely recall reading something about reborrowing and maybe it's something to do with that?


问:
Refresh/redraw a div without animations and keypress working
I'm currently using jQuery to try and refresh a div without completely refreshing the page. So far I am doing it with

```<code>$("#game").load(" #game > *");
</code>```

This keeps my animation and prevents a duplicate div creation but any key input is then broken. Here is my HTML div

```<code><div class="game" id="game">
    <div id="dino"></div>
    <div id="cactus"></div>
</div>
</code>```

I want to refresh the game div ideally. Is this possible to do? Or does the entire page need to be reloaded? Thanks.

Edit: I am using the code from this repository: https://github.com/mdbootstrap/knowledge-base/tree/main/JS/games/dino-game

I have not made any changes regarding it.

https://codepen.io/michaeljgilson/pen/MWBjdJE

Edit: I've tried this as well with no luck

```<code>    $( "#game" ).load(window.location.href + " #game" );
</code>```

Body:
I'm currently using jQuery to try and refresh a div without completely refreshing the page. So far I am doing it with

$("#game").load(" #game > *");

This keeps my animation and prevents a duplicate div creation but any key input is then broken. Here is my HTML div

I want to refresh the game div ideally. Is this possible to do? Or does the entire page need to be reloaded? Thanks.

Edit: I am using the code from this repository: https://github.com/mdbootstrap/knowledge-base/tree/main/JS/games/dino-game

I have not made any changes regarding it.

https://codepen.io/michaeljgilson/pen/MWBjdJE

Edit: I've tried this as well with no luck

    $( "#game" ).load(window.location.href + " #game" );


问:
How i can pass parameter to (Get-PnPUser | ? Email -eq ($SPUserEmail));
I have the following PnP PowerShell script:

```<code>$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=True;Initial Catalog=$DBName")
$conn.Open();
$query = $Query
$dap = new-object System.Data.SqlClient.SqlDataAdapter($query,$conn);
$dt = new-object System.Data.DataTable;
$null = $dap.Fill($dt)
      foreach($r in $dt.Rows )   {
$SPUserEmail = $r["email_address"];
$SPuser = (Get-PnPUser | ? Email -eq ($SPUserEmail));}
</code>```

but i will always get this error:

```<code>The specified user  could not be found.
</code>```

but if I type the email address manually i will get the user:

```<code>$SPuser = (Get-PnPUser | ? Email -eq test@test.com);
</code>```

although when I do Write-Host $SPUserEmail I will get test@test.com

So what could be the reason?

Thanks

Body:
I have the following PnP PowerShell script:

$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$DBServer;Integrated Security=True;Initial Catalog=$DBName")
$conn.Open();
$query = $Query
$dap = new-object System.Data.SqlClient.SqlDataAdapter($query,$conn);
$dt = new-object System.Data.DataTable;
$null = $dap.Fill($dt)
      foreach($r in $dt.Rows )   {
$SPUserEmail = $r["email_address"];
$SPuser = (Get-PnPUser | ? Email -eq ($SPUserEmail));}

but i will always get this error:

The specified user  could not be found.

but if I type the email address manually i will get the user:

$SPuser = (Get-PnPUser | ? Email -eq test@test.com);

although when I do Write-Host $SPUserEmail I will get test@test.com

So what could be the reason?

Thanks


问:
Kotlin Android Retrofit model will null attributes
I need to make some request to an API using retrofit for an Android App, and i'm getting a response with null serialiced attributes.

I'm getting the Response object from the dataclass but with null attributes.

This is the retrofit config class

```<code>class RetrofitConfig {
    companion object {
        var URL_API = "I cant share the api link"

        fun getRetrofit(): Retrofit {
            return Retrofit.Builder()
                .baseUrl(URL_API)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
    }
}
</code>```

This is the interface client

```<code>interface LoginAPIClient {
    @GET("/RS_Usuarios")
    suspend fun getLoginByUserandPass (
        @Query("idUser") userId : String,
        @Query("clave") userPass : String
    ): Response<LoginResponse>
}
</code>```

This is the response data class

```<code>data class LoginResponse (
    @SerializedName("id") var id : String,
    @SerializedName("nombre") var uname : String,
    @SerializedName("apellido") var ulastname : String,
    @SerializedName("acceso") var uaccess : Boolean,
    @SerializedName("admin") var uadmin : Boolean
)
</code>```

The endpoint receives an idUser and clave (password) as parameters in the query. This is the response object structure with 200 http response code.

```<code>{
  "id": "string",
  "nombre": "string",
  "apellido": "string",
  "acceso": true,
  "admin": true
}
</code>```

I'm calling the Get method in this login function

```<code>    fun login(email: String, password: String, activity: AppCompatActivity) {
        CoroutineScope(Dispatchers.IO).launch {
            val call = RetrofitConfig.getRetrofit().create(LoginAPIClient::class.java)
                .getLoginByUserandPass(email, password)

            if (call.isSuccessful) {
                val body = call.body()

                body?.let {
                    println(call.code())
                    println(body)

                    if (body.uaccess) {
                        println("User has access")
                    } else {
                        println("User hasn't access")
                    }
                }
            }
        }
    }
</code>```

When i run the app and the login function, i get this with the prints

```<code>I/System.out: 200
I/System.out: LoginResponse(id=null, uname=null, ulastname=null, uaccess=false, uadmin=false)
I/System.out: User can't access
</code>```

I'm getting the LoginResponse object from the dataclass but with null attributes.

Body:
I need to make some request to an API using retrofit for an Android App, and i'm getting a response with null serialiced attributes.

I'm getting the Response object from the dataclass but with null attributes.

This is the retrofit config class

class RetrofitConfig {
    companion object {
        var URL_API = "I cant share the api link"

        fun getRetrofit(): Retrofit {
            return Retrofit.Builder()
                .baseUrl(URL_API)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
    }
}

This is the interface client

interface LoginAPIClient {
    @GET("/RS_Usuarios")
    suspend fun getLoginByUserandPass (
        @Query("idUser") userId : String,
        @Query("clave") userPass : String
    ): Response<LoginResponse>
}

This is the response data class

data class LoginResponse (
    @SerializedName("id") var id : String,
    @SerializedName("nombre") var uname : String,
    @SerializedName("apellido") var ulastname : String,
    @SerializedName("acceso") var uaccess : Boolean,
    @SerializedName("admin") var uadmin : Boolean
)

The endpoint receives an idUser and clave (password) as parameters in the query. This is the response object structure with 200 http response code.

{
  "id": "string",
  "nombre": "string",
  "apellido": "string",
  "acceso": true,
  "admin": true
}

I'm calling the Get method in this login function

    fun login(email: String, password: String, activity: AppCompatActivity) {
        CoroutineScope(Dispatchers.IO).launch {
            val call = RetrofitConfig.getRetrofit().create(LoginAPIClient::class.java)
                .getLoginByUserandPass(email, password)

            if (call.isSuccessful) {
                val body = call.body()

                body?.let {
                    println(call.code())
                    println(body)

                    if (body.uaccess) {
                        println("User has access")
                    } else {
                        println("User hasn't access")
                    }
                }
            }
        }
    }

When i run the app and the login function, i get this with the prints

I/System.out: 200
I/System.out: LoginResponse(id=null, uname=null, ulastname=null, uaccess=false, uadmin=false)
I/System.out: User can't access

I'm getting the LoginResponse object from the dataclass but with null attributes.


问:
Arduino IDE: "No such file or directory" but file exist
I'm trying to compile a sketch in Arduino IDE that was originally written for PlatformIO.

I'm getting a "No such file or directory" error for a file that actually exists. Indeed, I added the file to the sketch.

How can I fix that error?

enter image description here

I already tried to copy the file to the standard Arduino's Library path and also to use the Sketch > Add File function


问:
How to Mock a method that derives from the MAP interface using Java & JMockit?
Currently trying to create a mock of a method called containsKey that derives from the java MAP interface, this is how it is defined:

//Creation
Map<String, ProviderServiceKey> providerService
```
<p>Usage:</p>
<pre class="lang-java prettyprint-override"><code>[providerService.containsKey(object.method)](https://www.stackoverflow.com/)
</code>```

Here the mock, that is being recognized but the return of this method is not fully covered:

[new MockUp<java.util.Map<String, ProviderServiceKey>>(){
   @Mock
   public boolean containsKey(Object key){
      return true; //This is not covered
   }
}](https://www.stackoverflow.com/)
```

I tried opening the type hierarchy of the containsKey method in Eclipse, but the thing is a lot of classes are being displayed. (This are the classes that are implementing the Map interface and its methods). With this said there are too many. Is there a way to slim down the search of the correct class that uses the containsKey method as it is being used above?

Body:
Currently trying to create a mock of a method called containsKey that derives from the java MAP interface, this is how it is defined:

//Creation
Map<String, ProviderServiceKey> providerService

Usage:

[providerService.containsKey(object.method)](https://www.stackoverflow.com/)

Here the mock, that is being recognized but the return of this method is not fully covered:

[new MockUp<java.util.Map<String, ProviderServiceKey>>(){
   @Mock
   public boolean containsKey(Object key){
      return true; //This is not covered
   }
}](https://www.stackoverflow.com/)

I tried opening the type hierarchy of the containsKey method in Eclipse, but the thing is a lot of classes are being displayed. (This are the classes that are implementing the Map interface and its methods). With this said there are too many. Is there a way to slim down the search of the correct class that uses the containsKey method as it is being used above?


问:
UnboundLocalError: cannot access local variable 'initial_data' where it is not associated with a value
i'm creating a tool, and in that tool, it gets some data from an API that it firsts stores on a json. and then I use a py function to store the values on a tuple, but when I try to access it, I get this error. It's a tool for discord to fetch information from a videogame, hosted on my machine

```<code>Traceback (most recent call last):
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/scoreposter.py", line 251, in scoreposter
    await interaction.response.send_message(f"```{scorepost(osu_user,mode , False)}```", ephemeral=False)
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/scoreposter.py", line 168, in scorepost
    beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = extract_initial_data(initial_data)
                                                                                ^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'initial_data' where it is not associated with a value

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'scorepost' raised an exception: UnboundLocalError: cannot access local variable 'initial_data' where it is not associated with a value

</code>```

The parts of the code that should be relevant

...
def int_to_santised_int(value: int) -> int:
    if value == 0:
        return 0
    else:
        mods_to_check = [1024, 512, 256, 64, 16, 8, 2] # FL, NC, HT, DT, HR, HD, EZ
        combined_value = 0
        for mod in mods_to_check:
            if value & mod:
                combined_value |= mod
        return combined_value

def extract_initial_data(initial_data):
    try:
        beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = (
            initial_data[0]["beatmap_id"],
            initial_data[0]["rank"],
            int(initial_data[0]["maxcombo"]),
            int(initial_data[0]["count300"]),
            int(initial_data[0]["count100"]),
            int(initial_data[0]["count50"]),
            int(initial_data[0]["countmiss"]),
            initial_data[0]["perfect"],
            int_to_santised_int(int(initial_data[0]["enabled_mods"])),
            initial_data[0]["score_id"]
        )
    except IndexError as e:
        print(f"an exception occurred: '{e}'; that user probably doesn't have any data available.")
        raise
    return beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id

...

def scorepost(username : str, link : bool, mode : str):
 # make a request to the osu! API to retrieve the user's most recent play
    if link == False:
        try:
            print(f"making initial score request for {username}...")
            inital_response_user = requests.get(f"https://osu.ppy.sh/api/get_user_recent?k={osu_api_key}&u={username}&m={gamemode}&limit=1")
            print(inital_response_user)
        except:
            return "No plays done by that player recently"
        else:
            # parse the response as JSON
            initial_data = inital_response_user.json()

    beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = extract_initial_data(initial_data)
```

I've tried moving the line of the error inside of the if and inside of the else in the try except part and making initial_data a global variable before adding a value in initial_data = inital_response_user.json() and before the if link == False:

Body:
i'm creating a tool, and in that tool, it gets some data from an API that it firsts stores on a json. and then I use a py function to store the values on a tuple, but when I try to access it, I get this error. It's a tool for discord to fetch information from a videogame, hosted on my machine

Traceback (most recent call last):
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/scoreposter.py", line 251, in scoreposter
    await interaction.response.send_message(f"```{scorepost(osu_user,mode , False)}```", ephemeral=False)
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/scoreposter.py", line 168, in scorepost
    beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = extract_initial_data(initial_data)
                                                                                ^^^^^^^^^^^^
UnboundLocalError: cannot access local variable 'initial_data' where it is not associated with a value

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/pufferpanel/servers/bd502203/.local/lib/python3.11/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'scorepost' raised an exception: UnboundLocalError: cannot access local variable 'initial_data' where it is not associated with a value

The parts of the code that should be relevant

...
def int_to_santised_int(value: int) -> int:
    if value == 0:
        return 0
    else:
        mods_to_check = [1024, 512, 256, 64, 16, 8, 2] # FL, NC, HT, DT, HR, HD, EZ
        combined_value = 0
        for mod in mods_to_check:
            if value & mod:
                combined_value |= mod
        return combined_value

def extract_initial_data(initial_data):
    try:
        beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = (
            initial_data[0]["beatmap_id"],
            initial_data[0]["rank"],
            int(initial_data[0]["maxcombo"]),
            int(initial_data[0]["count300"]),
            int(initial_data[0]["count100"]),
            int(initial_data[0]["count50"]),
            int(initial_data[0]["countmiss"]),
            initial_data[0]["perfect"],
            int_to_santised_int(int(initial_data[0]["enabled_mods"])),
            initial_data[0]["score_id"]
        )
    except IndexError as e:
        print(f"an exception occurred: '{e}'; that user probably doesn't have any data available.")
        raise
    return beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id

...

def scorepost(username : str, link : bool, mode : str):
 # make a request to the osu! API to retrieve the user's most recent play
    if link == False:
        try:
            print(f"making initial score request for {username}...")
            inital_response_user = requests.get(f"https://osu.ppy.sh/api/get_user_recent?k={osu_api_key}&u={username}&m={gamemode}&limit=1")
            print(inital_response_user)
        except:
            return "No plays done by that player recently"
        else:
            # parse the response as JSON
            initial_data = inital_response_user.json()

    beatmap_id, rank, score_max, n300, n100, n50, nmiss, perfect, int_mods, score_id = extract_initial_data(initial_data)

I've tried moving the line of the error inside of the if and inside of the else in the try except part and making initial_data a global variable before adding a value in initial_data = inital_response_user.json() and before the if link == False:


问:
SqlAlchemy, AttributeError: after_update
Hi guys I have 3 Tables (Traces, Components, Datasets)
In the Traces table, I am trying to add an event where if the dataset_id is set to be NULL the active_columns will automatically be set to Null.

this is the code I have:

from datetime import datetime

from sqlalchemy import Column, Integer, DateTime, String, JSON, ForeignKey, UniqueConstraint, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Traces(Base):
    __tablename__ = 'traces'
    id = Column(Integer, primary_key=True)
    component_id = Column(Integer, ForeignKey('components.id', ondelete='CASCADE'), nullable=False)
    trace_name = Column(String)
    dataset_id = Column(Integer, ForeignKey('datasets.id', ondelete='SET NULL'))
    created_at = Column(DateTime, default=datetime.utcnow)
    args = Column(JSON)
    active_columns = Column(JSON, default=None)
    __table_args__ = (UniqueConstraint('component_id', 'trace_name', name='uix_1'),)
    component = relationship("Components", back_populates="traces")
    dataset = relationship("Datasets", back_populates="traces")

class Components(Base):
    __tablename__ = 'components'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    traces = relationship("Traces", back_populates="component", cascade="all, delete-orphan")

class Datasets(Base):
    __tablename__ = 'datasets'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    data = Column(JSON)
    traces = relationship("Traces", back_populates="dataset")

@event.listens_for(Traces.__table__, 'after_update')
def set_active_columns_to_null(mapper, connection, target):
    if target.dataset_id is None:
        connection.execute(
            Traces.__table__.update().where(Traces.__table__.c.id == target.id).values(active_columns=None)
        )
```

I am also using alembic to control the db
when running the alembic revision commend I get

AttributeError: after_update

Any idea why?

Body:
Hi guys I have 3 Tables (Traces, Components, Datasets)
In the Traces table, I am trying to add an event where if the dataset_id is set to be NULL the active_columns will automatically be set to Null.

this is the code I have:

from datetime import datetime

from sqlalchemy import Column, Integer, DateTime, String, JSON, ForeignKey, UniqueConstraint, event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship

Base = declarative_base()

class Traces(Base):
    __tablename__ = 'traces'
    id = Column(Integer, primary_key=True)
    component_id = Column(Integer, ForeignKey('components.id', ondelete='CASCADE'), nullable=False)
    trace_name = Column(String)
    dataset_id = Column(Integer, ForeignKey('datasets.id', ondelete='SET NULL'))
    created_at = Column(DateTime, default=datetime.utcnow)
    args = Column(JSON)
    active_columns = Column(JSON, default=None)
    __table_args__ = (UniqueConstraint('component_id', 'trace_name', name='uix_1'),)
    component = relationship("Components", back_populates="traces")
    dataset = relationship("Datasets", back_populates="traces")

class Components(Base):
    __tablename__ = 'components'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    traces = relationship("Traces", back_populates="component", cascade="all, delete-orphan")

class Datasets(Base):
    __tablename__ = 'datasets'
    id = Column(Integer, primary_key=True)
    name = Column(String, unique=True)
    created_at = Column(DateTime, default=datetime.utcnow)
    data = Column(JSON)
    traces = relationship("Traces", back_populates="dataset")

@event.listens_for(Traces.__table__, 'after_update')
def set_active_columns_to_null(mapper, connection, target):
    if target.dataset_id is None:
        connection.execute(
            Traces.__table__.update().where(Traces.__table__.c.id == target.id).values(active_columns=None)
        )

I am also using alembic to control the db
when running the alembic revision commend I get

AttributeError: after_update

Any idea why?


问:
Variable from Autosys that indicate current run is for which scheduled time
I have a job that run multiple times in a day and I would like to get the info that whether the current run is for which run in that day.

E.g. Run schedule: 2,4,6,8 am on Monday

If the job starts at 4:00 am (or 5:10 am if there are delay on autosys or dependency reason), I can use that variable/info from autosys to identify that run is for 4 am run.

I use JIL command to pass in the script I use and the job_id name by variable %AUTO_JOB_NAME%

Is there any environment variable can be pulled from Autosys and can be used in my script, without depending on the current timestamp that run the job?


问:
How do multiple Target Metric Aurora Autoscaling Policies interact?
I don't see anything in the docs about multiple target metric rules interacting, and if there is any sort of preference or logic involved:

https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.Integrating.AutoScaling.html

For instance, do multiple target rules:

apply so as to not violate the rule that needs to create a scale-out (more instance)?  e.g if I have a rule that tries to maintain 20% CPU usage, and one that tries to maintain 25 connections, and my servers have 10% CPU utilization but 100 connections each, will my instances a) scale in (become fewer), due to the CPU rule, or b) scale out, due to the connections rule?  I would hope scale out, since we clearly need them in this case.

apply based on the order in which they're created/listed in the console?

apply in order to respect/prioritize the scale in rule?

ignore more than one rule?


问:
get untruncated Line-based text data with timestamps with tshark
I have established a WebSocket connection with Binance to receive updates about order books. Every ~10ms I receive an update through the WebSocket protocol and each packet contains Line-based text data with the update. I capture the traffic with tcpdump and save it on a file .pcap called "traffic.pcap".

I need to extract each of this information together with the timestamp at which they are received from my side.
I have tried with

tshark -nr traffic.pcap -T fields -e frame.time_epoch -e text  -Y "tcp.stream eq
11" -o tls.keylog_file:$SSLKEYLOGFILE

to extract, for example, the stream 11. The result is quite what I want, except that the Line-based text data is truncated, e.g.

1671613818.220136000  Timestamps, [truncated]{"stream":"btcusdt@depth5@100ms","data":{"lastUpdateId":29427350596,"bids":[["16879.24000000","0.03281000"],["16879.23000000","0.03073000"],["16879.21000000","0.02180000"],["16879.20000000","0.00580000"],["16878.93000000","0.0

To avoid truncation, I know that I can reconstruct the stream by using the following command

tshark -nr traffic.pcap -z
follow,tls,ascii,13 -q

but I lose any information about the timestamp of each message.

How can I solve this problem?


问:
I want make calculator convert from hexadecimal to decimal
hello guys I want make calculator convert from hexadecimal to decimal by '16d' button this is the code of the button

```<code>    else if(txtBtn == '16d'){
  result=(int.tryParse(result,radix:16)).toString();
  finalResult=result;
}
</code>```

but in emulator if i convert 15 to f and the wanted to convert f to 15 again the result is null I tried tryParse instead of parse but the result is null also what shall i do? this is the entire code

```<code>    import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MyCalculator());

class MyCalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'calculator',
      home: Calculator(),
    );
  }
}

class FibonacciNumbers {
  final cache = {0: BigInt.from(1), 1: BigInt.from(1)};

  BigInt get(int i) {
    if (!cache.containsKey(i)) {
      cache[i] = get(i - 1) + get(i - 2);
    }

    return cache[i]!;
  }
}

class Calculator extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Calculator();
  }
}

class _Calculator extends State<Calculator> {
  String text = '0';
  double numOne = 0;
  double numTwo = 0;

  String result = '0';
  String finalResult = '0';

  String opr = '';
  String preOpr = '';
  double fact(double n) {
    double fac = 1.0;
    for (double i = 1.0; i <= n; i++) {
      fac = fac * i;
    }
    return fac;
  }

  double roundDouble(double value, int places) {
    double mod = pow(10.0, places).toDouble();
    return ((value * mod).round().toDouble() / mod);
  }

  double sinh(double x) {
    return (exp(numOne) - exp(-numOne)) / 2;
  }

  double tanh(double angle) {
    if (angle > 19.1) {
      return 1.0;
    }

    if (angle < -19.1) {
      return -1.0;
    }

    var e1 = exp(angle);
    var e2 = exp(-angle);
    return (e1 - e2) / (e1 + e2);
  }

  double sinh1(double angle) {
    double gg = angle + sqrt(pow(angle, 2) + 1);
    return log(gg);
  }

  double cosh1(double angle) {
    double gg = angle + sqrt(pow(angle, 2) - 1);
    return log(gg);
  }

  double tanh1(double angle) {
    return 0.5 * log((1 + angle) / (1 - angle));
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: null,
      backgroundColor: Colors.black,
      body: Container(
        margin: EdgeInsets.only(bottom: 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            Row(
              children: <Widget>[
                button("...", Color(0xffff9800), 2),
                Expanded(
                  child: Text(
                    text,
                    style: TextStyle(color: Colors.white, fontSize: 30),
                    maxLines: 1,
                    textAlign: TextAlign.right,
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("Sin", Color(0xffff9800), 1),
                button("Cos", Color(0xffff9800), 1),
                button("tan", Color(0xffff9800), 1),
                button("pow", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("C", Color(0xffa5a5a5), 1),
                button("+/-", Color.fromRGBO(165, 165, 165, 1), 1),
                button("%", Color(0xffa5a5a5), 1),
                button("/", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("7", Color(0xff323232), 1),
                button("8", Color(0xff323232), 1),
                button("9", Color(0xff323232), 1),
                button("X", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("4", Color(0xff323232), 1),
                button("5", Color(0xff323232), 1),
                button("6", Color(0xff323232), 1),
                button("-", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("1", Color(0xff323232), 1),
                button("2", Color(0xff323232), 1),
                button("3", Color(0xff323232), 1),
                button("+", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("0", Color(0xff323232), 1),
                button(".", Color(0xff323232), 1),
                button("=", Color(0xffff9800), 1),
                button("<-", Color(0xffff9800), 1)
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget button(String btnTxt, Color color, int num) {
    late Container container;

    if (num == 0) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.only(left: 81, top: 20, right: 81, bottom: 20),
            shape: StadiumBorder(),
          ));
    } else if (num == 1) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(),
          ));
    } else if (num == 2) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              showModalBottomSheet(
                  context: context,
                  builder: (context) {
                    return Container(
                        color: Colors.black,
                        child: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("Sin-1", Color(0xffff9800), 3),
                                  button("Cos-1", Color(0xffff9800), 3),
                                  button("tan-1", Color(0xffff9800), 3),
                                  button("pi", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("!", Color(0xffff9800), 3),
                                  button("e", Color(0xffff9800), 3),
                                  button("fay", Color(0xffff9800), 3),
                                  button("ln", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("log", Color(0xffff9800), 3),
                                  button("sinh", Color(0xffff9800), 3),
                                  button("cosh", Color(0xffff9800), 3),
                                  button("tanh", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("|x|", Color(0xffff9800), 3),
                                  button("sinh-1", Color(0xffff9800), 3),
                                  button("cosh-1", Color(0xffff9800), 3),
                                  button("tanh-1", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("Fibonacci", Color(0xffff9800), 4),
                                  button("sinh-1", Color(0xffff9800), 3),
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("nCk", Color(0xffff9800), 3),
                                  button("m", Color(0xffff9800), 3),
                                  button("16d", Color(0xffff9800), 3),
                                  button("tanh-1", Color(0xffff9800), 3)
                                ],
                              ),
                            ],
                          ),
                        ),
                        height: 500);
                  });
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(), // يجعل شكل الزر دائري
          ));
    } else if (num == 3) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 15)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(),
          ));
    } else if (num == 4) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              FibonacciNumbers? numbers = FibonacciNumbers();
              numbers.get(numOne.toInt());
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return FibonacciListView(numbers);
              }));
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 15)),
            color: color,
            padding: EdgeInsets.only(left: 81, top: 20, right: 81, bottom: 20),
            shape: StadiumBorder(),
          ));
    }

    return container;
  }

  void calculate(txtBtn) {
    if (txtBtn == 'C') {
      text = '0';
      numOne = 0;
      numTwo = 0;
      result = '';
      finalResult = '0';
      opr = '';
      preOpr = '';
    } else if (opr == '=' && txtBtn == '=') {
      switch (preOpr) {
        case '+':
          finalResult = add();
          break;
        case '-':
          finalResult = sub();
          break;
        case 'X':
          finalResult = mul();
          break;
        case '/':
          finalResult = div();
          break;
        case 'pow':
          finalResult = power();
          break;
        case 'nCk':
          finalResult = nck();
          break;
        case 'm':
          finalResult = mck();
          break;
      }
    } else if (txtBtn == '+' ||
        txtBtn == '-' ||
        txtBtn == 'X' ||
        txtBtn == '/' ||
        txtBtn == '=' ||
        txtBtn == 'pow' ||
        txtBtn == 'nCk' ||
        txtBtn == 'm') {
      if (numOne == 0) {
        numOne = double.parse(result);
      } else {
        numTwo = double.parse(result);
      }

      switch (opr) {
        case '+':
          finalResult = add();
          break;
        case '-':
          finalResult = sub();
          break;
        case 'X':
          finalResult = mul();
          break;
        case '/':
          finalResult = div();
          break;
        case 'pow':
          finalResult = power();
          break;
        case 'nCk':
          finalResult = nck();
          break;
        case 'm':
          finalResult = mck();
          break;
      }

      preOpr = opr;
      opr = txtBtn;
      result = '';
    } else if (txtBtn == '%') {
      numOne = double.parse(result);

      result = (numOne / 100).toString();
      finalResult = result;
    } else if (txtBtn == '.') {
      if (!result.contains('.')) result += '.';
      finalResult = result;
    } else if (txtBtn == '+/-') {
      result.startsWith('-')
          ? result = result.substring(1)
          : result = '-' + result;

      finalResult = result;
    } else if (txtBtn == 'Sin') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = (roundDouble(sin(numOne * pi / 180), 5)).toString();
      finalResult = result;
    } else if (txtBtn == 'Cos') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = (roundDouble(cos(numOne * pi / 180), 5)).toString();
      finalResult = result;
    } else if (txtBtn == 'tan') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = ('${tan(numOne * pi / 180)}');
      finalResult = result;
    } else if (txtBtn == '0' ||
        txtBtn == '1' ||
        txtBtn == '2' ||
        txtBtn == '3' ||
        txtBtn == '4' ||
        txtBtn == '5' ||
        txtBtn == '6' ||
        txtBtn == '7' ||
        txtBtn == '8' ||
        txtBtn == '9') {
      if (result == '0')
        result = txtBtn;
      else
        result = result + txtBtn;
      finalResult = result;
    } else if (txtBtn == '!') {
      numOne = double.parse(result);
      result = fact(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'Sin-1') {
      numOne = double.parse(result);
      result = (asin(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'Cos-1') {
      numOne = double.parse(result);
      result = (acos(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'tan-1') {
      numOne = double.parse(result);
      result = (atan(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'pi') {
      result = 3.1415926535897932.toString();
      finalResult = result;
    } else if (txtBtn == 'e') {
      result = 2.718281828459045.toString();
      finalResult = result;
    } else if (txtBtn == 'fay') {
      result = 1.6180339887.toString();
      finalResult = result;
    } else if (txtBtn == 'ln') {
      numOne = double.parse(result);
      result = (log(numOne)).toString();
      finalResult = result;
    } else if (txtBtn == 'log') {
      numOne = double.parse(result);
      result = ((log(numOne) / ln10).round()).toString();
      finalResult = result;
    } else if (txtBtn == '<-') {
      result = result.substring(0, result.length - 1);
      finalResult = result;
    } else if (txtBtn == 'sinh') {
      numOne = double.parse(result);
      result = ((exp(numOne) - exp(-numOne)) / 2).toString();
      finalResult = result;
    } else if (txtBtn == 'cosh') {
      numOne = double.parse(result);
      result = sqrt(1 + pow(sinh(numOne), 2)).toString();
      finalResult = result;
    } else if (txtBtn == 'tanh') {
      numOne = double.parse(result);
      result = tanh(numOne).toString();
      finalResult = result;
    } else if (txtBtn == '|x|') {
      numOne = double.parse(result);
      numOne < 0
          ? result = (numOne * (-1)).toString()
          : result = numOne.toString();

      finalResult = result;
    } else if (txtBtn == 'sinh-1') {
      numOne = double.parse(result);
      result = sinh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'cosh-1') {
      numOne = double.parse(result);
      result = cosh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'tanh-1') {
      numOne = double.parse(result);
      result = tanh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == '16d') {
      result = (int.tryParse(result, radix: 16)).toString();
      finalResult = result;
    }
    setState(() {
      text = finalResult;
    });
  }

/*
  */
  String add() {
    result = (numOne + numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String sub() {
    result = (numOne - numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String mul() {
    result = (numOne * numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String div() {
    result = (numOne / numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String power() {
    result = pow(numOne, numTwo).toString();
    numOne = double.parse(result);
    return result;
  }

  String nck() {
    result = (fact(numOne) / (fact(numTwo) * fact(numOne - numTwo))).toString();
    numOne = double.parse(result);
    return result;
  }

  String mck() {
    var a = numOne.toInt();
    var b = numTwo.toInt();
    result = (a.toRadixString(b)).toString();
    if (result.contains('a') ||
        result.contains('b') ||
        result.contains('c') ||
        result.contains('d') ||
        result.contains('e') ||
        result.contains('f') ||
        result.contains('A') ||
        result.contains('B') ||
        result.contains('C') ||
        result.contains('D') ||
        result.contains('E') ||
        result.contains('F')) {
      var i = int.parse(result, radix: 16);
      result = result.toUpperCase();
      numOne = i.toDouble();
    } else {
      numOne = double.parse(result);
    }
    return result;
  }

  String m16() {
    var a = numOne.toInt();
    var b = numTwo.toInt();
    result = (a.toRadixString(b)).toString();

    return result;
  }

  String decimalRemove(String _result) {
    if (_result.contains('.')) {
      List<String> split = _result.split('.');
      //[11, 0]
      if (!(int.parse(split[1]) > 0)) return split[0];
    }
    return _result;
  }
}

class FibonacciListView extends StatelessWidget {
  final FibonacciNumbers numbers;
  const FibonacciListView(this.numbers);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text('Fibonacci List'),
      ),
      body: ListView.builder(
        itemBuilder: (context, i) {
          return ListTile(
            title: Text('${numbers.get(i).toString()}'),
            onTap: () {
              final snack = SnackBar(
                content:
                    Text('${numbers.get(i)} is #$i in the Fibonacci sequence!'),
              );
              ScaffoldMessenger.of(context).showSnackBar(snack);
            },
          );
        },
      ),
    );
  }
}
</code>```

Body:
hello guys I want make calculator convert from hexadecimal to decimal by '16d' button this is the code of the button

    else if(txtBtn == '16d'){
  result=(int.tryParse(result,radix:16)).toString();
  finalResult=result;
}

but in emulator if i convert 15 to f and the wanted to convert f to 15 again the result is null I tried tryParse instead of parse but the result is null also what shall i do? this is the entire code

    import 'package:flutter/material.dart';
import 'dart:math';

void main() => runApp(MyCalculator());

class MyCalculator extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'calculator',
      home: Calculator(),
    );
  }
}

class FibonacciNumbers {
  final cache = {0: BigInt.from(1), 1: BigInt.from(1)};

  BigInt get(int i) {
    if (!cache.containsKey(i)) {
      cache[i] = get(i - 1) + get(i - 2);
    }

    return cache[i]!;
  }
}

class Calculator extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _Calculator();
  }
}

class _Calculator extends State<Calculator> {
  String text = '0';
  double numOne = 0;
  double numTwo = 0;

  String result = '0';
  String finalResult = '0';

  String opr = '';
  String preOpr = '';
  double fact(double n) {
    double fac = 1.0;
    for (double i = 1.0; i <= n; i++) {
      fac = fac * i;
    }
    return fac;
  }

  double roundDouble(double value, int places) {
    double mod = pow(10.0, places).toDouble();
    return ((value * mod).round().toDouble() / mod);
  }

  double sinh(double x) {
    return (exp(numOne) - exp(-numOne)) / 2;
  }

  double tanh(double angle) {
    if (angle > 19.1) {
      return 1.0;
    }

    if (angle < -19.1) {
      return -1.0;
    }

    var e1 = exp(angle);
    var e2 = exp(-angle);
    return (e1 - e2) / (e1 + e2);
  }

  double sinh1(double angle) {
    double gg = angle + sqrt(pow(angle, 2) + 1);
    return log(gg);
  }

  double cosh1(double angle) {
    double gg = angle + sqrt(pow(angle, 2) - 1);
    return log(gg);
  }

  double tanh1(double angle) {
    return 0.5 * log((1 + angle) / (1 - angle));
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: null,
      backgroundColor: Colors.black,
      body: Container(
        margin: EdgeInsets.only(bottom: 20),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: <Widget>[
            Row(
              children: <Widget>[
                button("...", Color(0xffff9800), 2),
                Expanded(
                  child: Text(
                    text,
                    style: TextStyle(color: Colors.white, fontSize: 30),
                    maxLines: 1,
                    textAlign: TextAlign.right,
                  ),
                ),
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("Sin", Color(0xffff9800), 1),
                button("Cos", Color(0xffff9800), 1),
                button("tan", Color(0xffff9800), 1),
                button("pow", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("C", Color(0xffa5a5a5), 1),
                button("+/-", Color.fromRGBO(165, 165, 165, 1), 1),
                button("%", Color(0xffa5a5a5), 1),
                button("/", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("7", Color(0xff323232), 1),
                button("8", Color(0xff323232), 1),
                button("9", Color(0xff323232), 1),
                button("X", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("4", Color(0xff323232), 1),
                button("5", Color(0xff323232), 1),
                button("6", Color(0xff323232), 1),
                button("-", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("1", Color(0xff323232), 1),
                button("2", Color(0xff323232), 1),
                button("3", Color(0xff323232), 1),
                button("+", Color(0xffff9800), 1)
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                button("0", Color(0xff323232), 1),
                button(".", Color(0xff323232), 1),
                button("=", Color(0xffff9800), 1),
                button("<-", Color(0xffff9800), 1)
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget button(String btnTxt, Color color, int num) {
    late Container container;

    if (num == 0) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.only(left: 81, top: 20, right: 81, bottom: 20),
            shape: StadiumBorder(),
          ));
    } else if (num == 1) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(),
          ));
    } else if (num == 2) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              showModalBottomSheet(
                  context: context,
                  builder: (context) {
                    return Container(
                        color: Colors.black,
                        child: Container(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("Sin-1", Color(0xffff9800), 3),
                                  button("Cos-1", Color(0xffff9800), 3),
                                  button("tan-1", Color(0xffff9800), 3),
                                  button("pi", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("!", Color(0xffff9800), 3),
                                  button("e", Color(0xffff9800), 3),
                                  button("fay", Color(0xffff9800), 3),
                                  button("ln", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("log", Color(0xffff9800), 3),
                                  button("sinh", Color(0xffff9800), 3),
                                  button("cosh", Color(0xffff9800), 3),
                                  button("tanh", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("|x|", Color(0xffff9800), 3),
                                  button("sinh-1", Color(0xffff9800), 3),
                                  button("cosh-1", Color(0xffff9800), 3),
                                  button("tanh-1", Color(0xffff9800), 3)
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("Fibonacci", Color(0xffff9800), 4),
                                  button("sinh-1", Color(0xffff9800), 3),
                                ],
                              ),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: <Widget>[
                                  button("nCk", Color(0xffff9800), 3),
                                  button("m", Color(0xffff9800), 3),
                                  button("16d", Color(0xffff9800), 3),
                                  button("tanh-1", Color(0xffff9800), 3)
                                ],
                              ),
                            ],
                          ),
                        ),
                        height: 500);
                  });
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 30)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(), // يجعل شكل الزر دائري
          ));
    } else if (num == 3) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              calculate(btnTxt);
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 15)),
            color: color,
            padding: EdgeInsets.all(20),
            shape: CircleBorder(),
          ));
    } else if (num == 4) {
      container = Container(
          padding: EdgeInsets.only(bottom: 10),
          child: RaisedButton(
            onPressed: () {
              FibonacciNumbers? numbers = FibonacciNumbers();
              numbers.get(numOne.toInt());
              Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                return FibonacciListView(numbers);
              }));
            },
            child: Text(btnTxt, style: TextStyle(fontSize: 15)),
            color: color,
            padding: EdgeInsets.only(left: 81, top: 20, right: 81, bottom: 20),
            shape: StadiumBorder(),
          ));
    }

    return container;
  }

  void calculate(txtBtn) {
    if (txtBtn == 'C') {
      text = '0';
      numOne = 0;
      numTwo = 0;
      result = '';
      finalResult = '0';
      opr = '';
      preOpr = '';
    } else if (opr == '=' && txtBtn == '=') {
      switch (preOpr) {
        case '+':
          finalResult = add();
          break;
        case '-':
          finalResult = sub();
          break;
        case 'X':
          finalResult = mul();
          break;
        case '/':
          finalResult = div();
          break;
        case 'pow':
          finalResult = power();
          break;
        case 'nCk':
          finalResult = nck();
          break;
        case 'm':
          finalResult = mck();
          break;
      }
    } else if (txtBtn == '+' ||
        txtBtn == '-' ||
        txtBtn == 'X' ||
        txtBtn == '/' ||
        txtBtn == '=' ||
        txtBtn == 'pow' ||
        txtBtn == 'nCk' ||
        txtBtn == 'm') {
      if (numOne == 0) {
        numOne = double.parse(result);
      } else {
        numTwo = double.parse(result);
      }

      switch (opr) {
        case '+':
          finalResult = add();
          break;
        case '-':
          finalResult = sub();
          break;
        case 'X':
          finalResult = mul();
          break;
        case '/':
          finalResult = div();
          break;
        case 'pow':
          finalResult = power();
          break;
        case 'nCk':
          finalResult = nck();
          break;
        case 'm':
          finalResult = mck();
          break;
      }

      preOpr = opr;
      opr = txtBtn;
      result = '';
    } else if (txtBtn == '%') {
      numOne = double.parse(result);

      result = (numOne / 100).toString();
      finalResult = result;
    } else if (txtBtn == '.') {
      if (!result.contains('.')) result += '.';
      finalResult = result;
    } else if (txtBtn == '+/-') {
      result.startsWith('-')
          ? result = result.substring(1)
          : result = '-' + result;

      finalResult = result;
    } else if (txtBtn == 'Sin') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = (roundDouble(sin(numOne * pi / 180), 5)).toString();
      finalResult = result;
    } else if (txtBtn == 'Cos') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = (roundDouble(cos(numOne * pi / 180), 5)).toString();
      finalResult = result;
    } else if (txtBtn == 'tan') {
      preOpr = opr;
      opr = txtBtn;
      numOne = double.parse(result);

      result = ('${tan(numOne * pi / 180)}');
      finalResult = result;
    } else if (txtBtn == '0' ||
        txtBtn == '1' ||
        txtBtn == '2' ||
        txtBtn == '3' ||
        txtBtn == '4' ||
        txtBtn == '5' ||
        txtBtn == '6' ||
        txtBtn == '7' ||
        txtBtn == '8' ||
        txtBtn == '9') {
      if (result == '0')
        result = txtBtn;
      else
        result = result + txtBtn;
      finalResult = result;
    } else if (txtBtn == '!') {
      numOne = double.parse(result);
      result = fact(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'Sin-1') {
      numOne = double.parse(result);
      result = (asin(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'Cos-1') {
      numOne = double.parse(result);
      result = (acos(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'tan-1') {
      numOne = double.parse(result);
      result = (atan(numOne) * 180 / pi).toString();
      finalResult = result;
    } else if (txtBtn == 'pi') {
      result = 3.1415926535897932.toString();
      finalResult = result;
    } else if (txtBtn == 'e') {
      result = 2.718281828459045.toString();
      finalResult = result;
    } else if (txtBtn == 'fay') {
      result = 1.6180339887.toString();
      finalResult = result;
    } else if (txtBtn == 'ln') {
      numOne = double.parse(result);
      result = (log(numOne)).toString();
      finalResult = result;
    } else if (txtBtn == 'log') {
      numOne = double.parse(result);
      result = ((log(numOne) / ln10).round()).toString();
      finalResult = result;
    } else if (txtBtn == '<-') {
      result = result.substring(0, result.length - 1);
      finalResult = result;
    } else if (txtBtn == 'sinh') {
      numOne = double.parse(result);
      result = ((exp(numOne) - exp(-numOne)) / 2).toString();
      finalResult = result;
    } else if (txtBtn == 'cosh') {
      numOne = double.parse(result);
      result = sqrt(1 + pow(sinh(numOne), 2)).toString();
      finalResult = result;
    } else if (txtBtn == 'tanh') {
      numOne = double.parse(result);
      result = tanh(numOne).toString();
      finalResult = result;
    } else if (txtBtn == '|x|') {
      numOne = double.parse(result);
      numOne < 0
          ? result = (numOne * (-1)).toString()
          : result = numOne.toString();

      finalResult = result;
    } else if (txtBtn == 'sinh-1') {
      numOne = double.parse(result);
      result = sinh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'cosh-1') {
      numOne = double.parse(result);
      result = cosh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == 'tanh-1') {
      numOne = double.parse(result);
      result = tanh1(numOne).toString();
      finalResult = result;
    } else if (txtBtn == '16d') {
      result = (int.tryParse(result, radix: 16)).toString();
      finalResult = result;
    }
    setState(() {
      text = finalResult;
    });
  }

/*
  */
  String add() {
    result = (numOne + numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String sub() {
    result = (numOne - numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String mul() {
    result = (numOne * numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String div() {
    result = (numOne / numTwo).toString();
    numOne = double.parse(result);
    return decimalRemove(result);
  }

  String power() {
    result = pow(numOne, numTwo).toString();
    numOne = double.parse(result);
    return result;
  }

  String nck() {
    result = (fact(numOne) / (fact(numTwo) * fact(numOne - numTwo))).toString();
    numOne = double.parse(result);
    return result;
  }

  String mck() {
    var a = numOne.toInt();
    var b = numTwo.toInt();
    result = (a.toRadixString(b)).toString();
    if (result.contains('a') ||
        result.contains('b') ||
        result.contains('c') ||
        result.contains('d') ||
        result.contains('e') ||
        result.contains('f') ||
        result.contains('A') ||
        result.contains('B') ||
        result.contains('C') ||
        result.contains('D') ||
        result.contains('E') ||
        result.contains('F')) {
      var i = int.parse(result, radix: 16);
      result = result.toUpperCase();
      numOne = i.toDouble();
    } else {
      numOne = double.parse(result);
    }
    return result;
  }

  String m16() {
    var a = numOne.toInt();
    var b = numTwo.toInt();
    result = (a.toRadixString(b)).toString();

    return result;
  }

  String decimalRemove(String _result) {
    if (_result.contains('.')) {
      List<String> split = _result.split('.');
      //[11, 0]
      if (!(int.parse(split[1]) > 0)) return split[0];
    }
    return _result;
  }
}

class FibonacciListView extends StatelessWidget {
  final FibonacciNumbers numbers;
  const FibonacciListView(this.numbers);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text('Fibonacci List'),
      ),
      body: ListView.builder(
        itemBuilder: (context, i) {
          return ListTile(
            title: Text('${numbers.get(i).toString()}'),
            onTap: () {
              final snack = SnackBar(
                content:
                    Text('${numbers.get(i)} is #$i in the Fibonacci sequence!'),
              );
              ScaffoldMessenger.of(context).showSnackBar(snack);
            },
          );
        },
      ),
    );
  }
}


问:
Copy range of data to new workbook, but make it a csv
I want to take a range of data from my current xlsm workbook and have a macro that copies and pastes-values to a new csv file, but currently it is creating an xlsx file.

What I currently have successfully copies my data from my Original Doc file on Sheet1 to a new standard xlsx sheet. I want to add the functionality to make that new file a csv file instead. Here is my code so far:

```<code>Sub CopyPasteRange()

  Dim WB_SourceFile As Workbook
  Dim WB_New As Workbook

'Select file and range
    Set WB_SourceFile = Workbooks("Original Doc.xlsm")
    WB_SourceFile.Worksheets("Sheet1").Range("A1:E1000").Copy

'Paste to new sheet (Paste values)
    Set WB_New = Workbooks.Add
    WB_New.ActiveSheet.Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
         :=False, Transpose:=False

End Sub

</code>```

Body:
I want to take a range of data from my current xlsm workbook and have a macro that copies and pastes-values to a new csv file, but currently it is creating an xlsx file.

What I currently have successfully copies my data from my Original Doc file on Sheet1 to a new standard xlsx sheet. I want to add the functionality to make that new file a csv file instead. Here is my code so far:

Sub CopyPasteRange()

  Dim WB_SourceFile As Workbook
  Dim WB_New As Workbook

'Select file and range
    Set WB_SourceFile = Workbooks("Original Doc.xlsm")
    WB_SourceFile.Worksheets("Sheet1").Range("A1:E1000").Copy

'Paste to new sheet (Paste values)
    Set WB_New = Workbooks.Add
    WB_New.ActiveSheet.Range("A1").Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
         :=False, Transpose:=False

End Sub


问:
There's some way to convert string (html) to DOM with Puppeteer?
Like the opposite of .innerHtml or what happens inside page.setContent()...

I want to make a string with HTML formatting to be interpreted as ElementHandle and allow this set of actions:
VSCode Menu

With DOMParser it is possible, but I believe that Puppeteer has some function that allows this without the need to import another library to the project.

Another approach would be to use page.setContent() and then a page.$(), but I think that would be a work around.


问:
How does a desktop python application typically get run in a isolated environment like javascript's npm package
I am curious how a typical python desktop application gets executed with a isolated environment. I know Nodejs has npm and all the dependencies are stored under the same folder when executed. And Python has venv and the requirements.txt files available, but having to create the virtual environment feel like an extra step that can be eliminated. And that means there isn't a simple one line command equivalent of npm start because python requires the virtual environment to be created first. Is this the correct understanding or am I missing something??

I looked into Python venv but didn't see anything that makes creating a virtual environment and execute a python program in that virtual environment one liner.


问:
Unexpected behaviour of r11 register
Today I've written the assembly code that is used for printing the debug string in this pattern:

"rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = -8     r10 = 9      r11 = 0      r12 = 11     r13 = -12    r14 = 13     r15 = -14"

But to test this code I just wrote it repeatedly like this:

```<code>    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    mov r11, -24
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _exit
</code>```

In my subroutine _getDebugString I push all used registers to safe them. But there's problem with register r11. After a subroutine completed its always 582.

You can check this out, here's the respond:

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = -8     r10 = 9      r11 = 0      r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = 582    r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = -24    r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = 582    r12 = 11     r13 = -12    r14 = 13     r15 = -14

Insights what would it be? Maybe I don't know smth about this register and there's a mystery about number 582?

Title: Unexpected behaviour of r11 register

Body:
Today I've written the assembly code that is used for printing the debug string in this pattern:

"rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = -8     r10 = 9      r11 = 0      r12 = 11     r13 = -12    r14 = 13     r15 = -14"

But to test this code I just wrote it repeatedly like this:

    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    mov r11, -24
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _getDebugString
    mov r9, debugString
    call _printTextSafe
    call _exit

In my subroutine _getDebugString I push all used registers to safe them. But there's problem with register r11. After a subroutine completed its always 582.

You can check this out, here's the respond:

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = -8     r10 = 9      r11 = 0      r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = 582    r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = -24    r12 = 11     r13 = -12    r14 = 13     r15 = -14

rax = 1      rbx = -2     rcx = 3      rdx = -4     rsi = 5      rdi = -6      r8 = 7       r9 = 4202678r10 = 9      r11 = 582    r12 = 11     r13 = -12    r14 = 13     r15 = -14

Insights what would it be? Maybe I don't know smth about this register and there's a mystery about number 582?


问:
How to measure Time Dilation in Nanoseconds on iOS?
Disclaimer: This a very theoretical idea that I'm experimenting with and I get that there are hard limits to CPU hardware and physics; this is more about seeing how far I can get.

The Question:
How do you measure the difference in Nanoseconds between the host device and the standard time the device would be synced to.

According to this article you experience "Nanoseconds" of Time Dilation relative to something like sea level every time you fly on an airplane.

The idea is that you have the app before you get on a plane and when you land, you get a notification saying: "You've Time Traveled XXX Nanoseconds!"

I assume that any standard time duration utilities in Swift are subject to the system clock and automatically synced to an NTP Server.

I'm wondering if there's a way to measure a time duration separate from any time that's synced to a remote server or carrier.

If not, can this be accomplished with lower-level language like Rust?

I've seen iOS APIs that can parse Nanoseconds I just can't find any resources on other factors you would have mitigate to actually measure Time Dilation.


问:
Climbing a ladder with a character controller?
I have an empty object that contains a number of cubes resulting in a ladder. With the help of debugging I ended up adding a rigidbody to each relevant cube and turned both 'Is Kinematic' and 'Is Trigger' on. I adjusted the box collider boundaries and I have this for my trigger:

```<code>// Trigger inside my player movement script
private void OnTriggerEnter(Collider other)
    {
        // Collider name equals Ladder
        if (other.tag == "Ladder")
        {
            transform.position += Vector3.up * Time.deltaTime;
            Debug.Log("Player is climbing.");
        }
    }
</code>```

I tried using my controller.move aswell, but that resulted in no results at all coming back from my debugging. I used an if statement to determine if player 'isClimbing' and using an input, but climbing was still not possible. I believe I am missing flags but I can't figure out what else is required.

Body:
I have an empty object that contains a number of cubes resulting in a ladder. With the help of debugging I ended up adding a rigidbody to each relevant cube and turned both 'Is Kinematic' and 'Is Trigger' on. I adjusted the box collider boundaries and I have this for my trigger:

// Trigger inside my player movement script
private void OnTriggerEnter(Collider other)
    {
        // Collider name equals Ladder
        if (other.tag == "Ladder")
        {
            transform.position += Vector3.up * Time.deltaTime;
            Debug.Log("Player is climbing.");
        }
    }

I tried using my controller.move aswell, but that resulted in no results at all coming back from my debugging. I used an if statement to determine if player 'isClimbing' and using an input, but climbing was still not possible. I believe I am missing flags but I can't figure out what else is required.


问:
Error with creating an apache tomcat server in eclipse for a dynamic web page
I keep receiving this error while trying to start my apache tomcat server in eclipse:

```<code>-Djava.endorsed.dirs=D:\user\apache-tomcat-8.0.36\apache-tomcat-8.0.36\endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules.
</code>```

I have tried to remove the line from the VM arguments, but it keeps adding itself back after I try to start the server.

This is a similar error to the one discussed in the following link, but I cannot seem to find the solution: https://bugs.eclipse.org/bugs/show_bug.cgi?id=507338

Body:
I keep receiving this error while trying to start my apache tomcat server in eclipse:

-Djava.endorsed.dirs=D:\user\apache-tomcat-8.0.36\apache-tomcat-8.0.36\endorsed is not supported. Endorsed standards and standalone APIs
in modular form will be supported via the concept of upgradeable modules.

I have tried to remove the line from the VM arguments, but it keeps adding itself back after I try to start the server.

This is a similar error to the one discussed in the following link, but I cannot seem to find the solution: https://bugs.eclipse.org/bugs/show_bug.cgi?id=507338


问:
Algorithm for matching a filename to buckets based on pre defined identifiers
I'm looking into finding an algorithm where files should be matched to specific "buckets" based on some identifier properties on those buckets.

Example:

```<code>const buckets = [
  { id: 1, identifiers: ['jhdi753hhdy', 'foo', 'u-123'] },
  { id: 2, identifiers: ['hasd834kasd', 'bar', 'u-112'] },
  { id: 3, identifiers: ['adf8wersbay', 'buz', 'u-234', 'u-112'] },
]

bestMatch('file-jhdi7-53hhdy', buckets) // => [{ id: 1, ... }]
bestMatch('file-u112', buckets) // => [{ id: 2, ... }, { id: 3, ... }]
bestMatch('isBUZZfile', buckets) // => [{ id: 3, ... }]
</code>```

The algorithm tries to find one or more matches (sorted), based on the given filename, and the best matches of the identifiers of the buckets.

I've already considered a naive implementation based on string matches, but that will only get me so far.

I'm fairly open to any type of solution. Either based purely on the client side (in memory) or server side using the capabilities of specific search engines.

Some considerations for the algorithm:

Buckets may have identifiers duplicated

Tokens may not be an exact match, but exact matches should be considered "better"

If the algorithm can say witch identifiers it used to match a result, that would be very nice plus

Having a "confidence" or "weight" for each match would be a very nice plus

Body:
I'm looking into finding an algorithm where files should be matched to specific "buckets" based on some identifier properties on those buckets.

Example:

const buckets = [
  { id: 1, identifiers: ['jhdi753hhdy', 'foo', 'u-123'] },
  { id: 2, identifiers: ['hasd834kasd', 'bar', 'u-112'] },
  { id: 3, identifiers: ['adf8wersbay', 'buz', 'u-234', 'u-112'] },
]

bestMatch('file-jhdi7-53hhdy', buckets) // => [{ id: 1, ... }]
bestMatch('file-u112', buckets) // => [{ id: 2, ... }, { id: 3, ... }]
bestMatch('isBUZZfile', buckets) // => [{ id: 3, ... }]

The algorithm tries to find one or more matches (sorted), based on the given filename, and the best matches of the identifiers of the buckets.

I've already considered a naive implementation based on string matches, but that will only get me so far.

I'm fairly open to any type of solution. Either based purely on the client side (in memory) or server side using the capabilities of specific search engines.

Some considerations for the algorithm:

Buckets may have identifiers duplicated

Tokens may not be an exact match, but exact matches should be considered "better"

If the algorithm can say witch identifiers it used to match a result, that would be very nice plus

Having a "confidence" or "weight" for each match would be a very nice plus


问:
Working with PageBreaks in Excel Javascript API
I'm trying to figure out PageBreaks in Excel w/ the Javascript API.

My goal is to put blank lines on the end of the last page, filling up the unknown amount of blank space.

I've been reading the docs on PageBreaks and noticed a funciton getCellAfterBreak() which seems like a good starting point. I'd need to get the offset range of the cell above that to the bottom of my UsedRange.

I can't really seem to get any useful information from the console or docs, here is what I've been trying, can anybody point me how to use these funcitons?

https://learn.microsoft.com/en-us/javascript/api/excel/excel.pagebreak?view=excel-js-preview

https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.pagebreak?view=office-scripts

Code:

```<code>var ws = context.workbook.worksheets.getActiveWorksheet();
var PageBKs = ws.horizontalPageBreaks
PageBKs.load('items')
await context.sync()
console.log('PageBKs')
console.log(PageBKs)
var Count = PageBKs.getCount()
console.log('Count')
console.log(Count)
</code>```

Body:
I'm trying to figure out PageBreaks in Excel w/ the Javascript API.

My goal is to put blank lines on the end of the last page, filling up the unknown amount of blank space.

I've been reading the docs on PageBreaks and noticed a funciton getCellAfterBreak() which seems like a good starting point. I'd need to get the offset range of the cell above that to the bottom of my UsedRange.

I can't really seem to get any useful information from the console or docs, here is what I've been trying, can anybody point me how to use these funcitons?

https://learn.microsoft.com/en-us/javascript/api/excel/excel.pagebreak?view=excel-js-preview

https://learn.microsoft.com/en-us/javascript/api/office-scripts/excelscript/excelscript.pagebreak?view=office-scripts

Code:

var ws = context.workbook.worksheets.getActiveWorksheet();
var PageBKs = ws.horizontalPageBreaks
PageBKs.load('items')
await context.sync()
console.log('PageBKs')
console.log(PageBKs)
var Count = PageBKs.getCount()
console.log('Count')
console.log(Count)


问:
Rest API Get call is failing
I am new in Flutter. while I am making GET call for the Rest API( https://execute-api.us-east-1.amazonaws.com/Card/urn:CardAcctId:Headers.CardAcctId/Retrieve), getting XMLHttpRequest error as error message. Any thought will be helpful. Thanks.

Title: Rest API Get call is failing


问:
Error in "names": incorrect number of layer names
I have in my script the following instructions:

```<code>library(raster)
wc25 <- stack(list.files(path="./Rhaebo/Bio_PresWC1.4/", pattern = "\\.asc$", full.names = TRUE))
names(wc25) <- c("bio1","bio4", "bio8", "bio9","bio10", "bio11", "bio12", "bio13", "bio14", "bio15", "bio16", "bio17", "bio18", "bio19")
</code>```

but when I run it, it throws me the following message:

```<code>Error in `names<-`(`*tmp*`, value = c("bio1", "bio4", "bio8", "bio9",  :
  incorrect number of layer names
</code>```

Does anyone know what could cause this problem?

Body:
I have in my script the following instructions:

library(raster)
wc25 <- stack(list.files(path="./Rhaebo/Bio_PresWC1.4/", pattern = "\\.asc$", full.names = TRUE))
names(wc25) <- c("bio1","bio4", "bio8", "bio9","bio10", "bio11", "bio12", "bio13", "bio14", "bio15", "bio16", "bio17", "bio18", "bio19")

but when I run it, it throws me the following message:

Error in `names<-`(`*tmp*`, value = c("bio1", "bio4", "bio8", "bio9",  :
  incorrect number of layer names

Does anyone know what could cause this problem?


问:
How do I implement role based access with express and vuejs
I have an app with express backend and vue frontend, I have implemented use authentication.

Now I want to restrict certain users from access certain routes when registering the user.

I have created a default user with admin email as the only person allow to make crud operations, but I don’t think that’s the best way to go about it.


问:
How to manage dynamic/configuration file inside application in more cloud-native way?
Good morning folks,

I would like to extend my architecture for microservice on Node.JS which is responsible for authorization to specific resource. I need to use some pattern will allow me to read dynamic configuration (list of roles/permissions) then allow for access to the specific endpoint inside Node.JS application

At this time being, I have simple database in Firestore (GCP NoSQL database) where configuration with roles and permissions are stored there but it would be great to have it dynamic managed from the file under git control, it will give me couple of benefits because roles/permissions will be under history and easy-handled by people more familiarize with git (user doesn't have to learn new firestore interface etc).

Currently I use API Gateway where Cloud Run is main backend for Node.JS application.
Do you have any ideas how to design solution with dynamic roles/permission file under the git  which can be changed anytime? I need have up-to-date file with permissions inside application therefore I need to find the way with loading latest file (maybe using cache for the this file and then flushing cache after updating file)?

there is possibility to have some API endpoint where this file would be located and would be read everytime Node.js app will want to check but I don't think if it's really effective approach