问:
mvc : Want to use one property in the object and not all of it
I have a method that I only use in one property where I upload photos so I only use the Photo property
I don't want to put the object as a parameter but a string that will be a replacement for the object and overwrite the Photo or in another way when using a Dto that fails to do gets null.

It's a function that works for me but I use the whole object as a parameter when I only use the PHOTO URL:

```<code>public async Task<string> UploadPhotos(IFormFile file, Product product)
        {
            string wwwPath = _environment.WebRootPath;
            var path = Path.Combine(wwwPath, "images", file.FileName);
            if (file.Length > 0)
            {
                using var stream = new FileStream(path, FileMode.Create);
                await file.CopyToAsync(stream);
            }
            return product.PhotoUrl = file.FileName;
        }
</code>```

What I tried to do:

```<code>public async Task<string> UploadPhotos(IFormFile file, string photoUrl)
        {

            Product product = new()
            {
                PhotoUrl = photoUrl
            };

            string wwwPath = _environment.WebRootPath;
            var path = Path.Combine(wwwPath, "images", file.FileName);
            if (file.Length > 0)
            {
                using var stream = new FileStream(path, FileMode.Create);
                await file.CopyToAsync(stream);
            }
            return product.PhotoUrl = file.FileName;
        }
</code>```

It doesn't work for me when I try to upload it doesn't show me the picture

Controller:

```<code>[HttpPost]
        [ValidateAntiForgeryToken]

    public async Task<IActionResult> AddProduct([FromForm] ProductViewModel model)
    {

        ModelState.Clear();

        await _photoService.UploadPhotos(model.Photo,model.PhotoUrl);

        if (ModelState.IsValid)
        {
            await _productRepository.AddProduct(model.Product!);
            return RedirectToAction(nameof(Index));
        }

        return View();
    }
</code>```

ViewModel:

```<code>  public class ProductViewModel
    {
        public Product Product { get; set; } = null!;
        public string PhotoUrl { get; set; } = string.Empty;
        public IFormFile Photo { get; set; } = null!;
    }
</code>```

View:

```<code>@model Solid_Project.Models.ProductViewModel

@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<article>

    <section>

        <form asp-action="AddProduct" enctype="multipart/form-data" method="post">
            <div asp-validation-summary="ModelOnly"></div>
            <div class="form-group">
                <label asp-for="@Model.Product!.Name"></label>
                <input asp-for="@Model.Product!.Name" class="form-control" placeholder="Enter Name" style="width:30%">
                <span asp-validation-for="@Model.Product!.Name" class="validation"></span>
            </div>
            <br />
            <div class="form-group">
                <label asp-for="@Model.Product!.Description"></label>
                <input asp-for="@Model.Product!.Description" class="form-control" placeholder="Enter Description" style="width:30%">
                <span asp-validation-for="@Model.Product!.Description" class="validation"></span>
            </div>
            <br />
            <div class="form-group">
                <label asp-for="@Model.Product!.CategoryId"></label>
                <div>
                    <select asp-for="@Model.Product!.CategoryId" asp-items="ViewBag.Category" style="width:30%" class="dropdown-toggle dropdown-toggle-design"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></select>
                </div>
                <span asp-validation-for="@Model.Product!.CategoryId" class="validation"></span>
            </div>
            <br />
            <div class="form-group">
                <label asp-for="@Model.Photo"></label>
                <input type="file" asp-for="@Model.Photo" accept="image/*" class="form-control" style="width:30%" />
                <span asp-validation-for="@Model.Photo" class="validation"></span>
            </div>
            <br />
            <input type="submit" value="Create" class="btn btn-primary" />
        </form>

    </section>

</article>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
 }
</code>```

Body:
I have a method that I only use in one property where I upload photos so I only use the Photo property
I don't want to put the object as a parameter but a string that will be a replacement for the object and overwrite the Photo or in another way when using a Dto that fails to do gets null.

It's a function that works for me but I use the whole object as a parameter when I only use the PHOTO URL:

public async Task<string> UploadPhotos(IFormFile file, Product product)
        {
            string wwwPath = _environment.WebRootPath;
            var path = Path.Combine(wwwPath, "images", file.FileName);
            if (file.Length > 0)
            {
                using var stream = new FileStream(path, FileMode.Create);
                await file.CopyToAsync(stream);
            }
            return product.PhotoUrl = file.FileName;
        }

What I tried to do:

public async Task<string> UploadPhotos(IFormFile file, string photoUrl)
        {

            Product product = new()
            {
                PhotoUrl = photoUrl
            };

            string wwwPath = _environment.WebRootPath;
            var path = Path.Combine(wwwPath, "images", file.FileName);
            if (file.Length > 0)
            {
                using var stream = new FileStream(path, FileMode.Create);
                await file.CopyToAsync(stream);
            }
            return product.PhotoUrl = file.FileName;
        }

It doesn't work for me when I try to upload it doesn't show me the picture

Controller:

[HttpPost]
        [ValidateAntiForgeryToken]

    public async Task<IActionResult> AddProduct([FromForm] ProductViewModel model)
    {

        ModelState.Clear();

        await _photoService.UploadPhotos(model.Photo,model.PhotoUrl);

        if (ModelState.IsValid)
        {
            await _productRepository.AddProduct(model.Product!);
            return RedirectToAction(nameof(Index));
        }

        return View();
    }

ViewModel:

  public class ProductViewModel
    {
        public Product Product { get; set; } = null!;
        public string PhotoUrl { get; set; } = string.Empty;
        public IFormFile Photo { get; set; } = null!;
    }

View:

@model Solid_Project.Models.ProductViewModel

@{
    ViewBag.Title = "AddProduct";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

        <form asp-action="AddProduct" enctype="multipart/form-data" method="post">

                <input asp-for="@Model.Product!.Name" class="form-control" placeholder="Enter Name" style="width:30%">

                <input asp-for="@Model.Product!.Description" class="form-control" placeholder="Enter Description" style="width:30%">

                    <select asp-for="@Model.Product!.CategoryId" asp-items="ViewBag.Category" style="width:30%" class="dropdown-toggle dropdown-toggle-design"
                            data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></select>

                <input type="file" asp-for="@Model.Photo" accept="image/*" class="form-control" style="width:30%" />

            <input type="submit" value="Create" class="btn btn-primary" />
        </form>

@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
 }


来源: stackexchange

问:
ract-native-video, video in mkv format goes black but the sound is heard
I am developing an application capable of playing an IPTV list. All the contents are in mkv format and most are reproduced correctly but in some the image remains black while the sound is heard.

This is the metadata of the video:

```<code>{
  "audioTracks": Array [
    Object {
      "bitrate": "",
      "index": 0,
      "language": "und",
      "title": "2",
      "type": "audio/mpeg",
    },
  ],
  "canPlayFastForward": true,
  "canPlayReverse": true,
  "canPlaySlowForward": true,
  "canPlaySlowReverse": true,
  "canStepBackward": true,
  "canStepForward": true,
  "currentTime": 0,
  "duration": 7097.049,
  "naturalSize": Object {
    "height": 0,
    "orientation": "portrait",
    "width": 0,
  },
  "textTracks": Array [],
  "trackId": "-1",
  "videoTracks": Array [
    Object {
      "bitrate": 0,
      "codecs": "",
      "height": 404,
      "trackId": "1",
      "width": 720,
    },
  ],
}
</code>```

This is the code I use with the react-native-video library:

```<code><Video
        key={keyload}
        ref={(ref) => {setVideo(ref)}}
        style={styles.video}
        onLoad={(data) => setMetadata(data)}//
        source={{
          uri: uriLoad, initOptions: ['--codec=avcodec']
        }}
        onProgress={progress => {setProgress(progress.currentTime)}}
        controls={false}
        fullscreen={true}
        paused={paused}
        volume={volumen}
        fullscreenAutorotate={true}
        selectedVideoTrack={videoTrack}
        selectedAudioTrack={audioTrack}
        selectedTextTrack={textTrack}
        resizeMode={resizemode}
        onEnd={() => end()}
        isLooping
        onError={error => playerError(error)}
        onPlaybackStatusUpdat
        allowsExternalPlayback
        e={status => setStatus(() => status)}//setStatus(() => status)
    />
</code>```

package.json

```<code>{
  "name": "someiptv",
  "version": "1.0.0",
  "scripts": {
    "start": "expo start --dev-client",
    "android": "expo run:android",
    "ios": "expo run:ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-native-community/slider": "4.2.3",
    "@react-navigation/native": "^6.0.12",
    "@react-navigation/native-stack": "^6.8.0",
    "expo": "~46.0.9",
    "expo-av": "~12.0.4",
    "expo-font": "~10.2.0",
    "expo-linear-gradient": "~11.4.0",
    "expo-screen-orientation": "~4.3.0",
    "expo-splash-screen": "~0.16.2",
    "expo-sqlite": "~10.3.0",
    "expo-status-bar": "~1.4.0",
    "lodash.filter": "^4.6.0",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "react-native": "0.69.5",
    "react-native-marquee": "^0.4.0",
    "react-native-paper": "^5.0.0-rc.4",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-system-setting": "^1.7.6",
    "react-native-video": "^6.0.0-alpha.3",
    "react-native-web": "~0.18.7",
    "react-navigation": "^4.4.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}
</code>```

I have tried with different versions of the library and with different buffer configurations, but nothing works. Does anyone know why this error occurs and how to fix it? Thanks.

ContentLicense: CC BY-SA 4.0

Body:
I am developing an application capable of playing an IPTV list. All the contents are in mkv format and most are reproduced correctly but in some the image remains black while the sound is heard.

This is the metadata of the video:

{
  "audioTracks": Array [
    Object {
      "bitrate": "",
      "index": 0,
      "language": "und",
      "title": "2",
      "type": "audio/mpeg",
    },
  ],
  "canPlayFastForward": true,
  "canPlayReverse": true,
  "canPlaySlowForward": true,
  "canPlaySlowReverse": true,
  "canStepBackward": true,
  "canStepForward": true,
  "currentTime": 0,
  "duration": 7097.049,
  "naturalSize": Object {
    "height": 0,
    "orientation": "portrait",
    "width": 0,
  },
  "textTracks": Array [],
  "trackId": "-1",
  "videoTracks": Array [
    Object {
      "bitrate": 0,
      "codecs": "",
      "height": 404,
      "trackId": "1",
      "width": 720,
    },
  ],
}

This is the code I use with the react-native-video library:

<Video
        key={keyload}
        ref={(ref) => {setVideo(ref)}}
        style={styles.video}
        onLoad={(data) => setMetadata(data)}//
        source={{
          uri: uriLoad, initOptions: ['--codec=avcodec']
        }}
        onProgress={progress => {setProgress(progress.currentTime)}}
        controls={false}
        fullscreen={true}
        paused={paused}
        volume={volumen}
        fullscreenAutorotate={true}
        selectedVideoTrack={videoTrack}
        selectedAudioTrack={audioTrack}
        selectedTextTrack={textTrack}
        resizeMode={resizemode}
        onEnd={() => end()}
        isLooping
        onError={error => playerError(error)}
        onPlaybackStatusUpdat
        allowsExternalPlayback
        e={status => setStatus(() => status)}//setStatus(() => status)
    />

package.json

{
  "name": "someiptv",
  "version": "1.0.0",
  "scripts": {
    "start": "expo start --dev-client",
    "android": "expo run:android",
    "ios": "expo run:ios",
    "web": "expo start --web"
  },
  "dependencies": {
    "@react-native-community/slider": "4.2.3",
    "@react-navigation/native": "^6.0.12",
    "@react-navigation/native-stack": "^6.8.0",
    "expo": "~46.0.9",
    "expo-av": "~12.0.4",
    "expo-font": "~10.2.0",
    "expo-linear-gradient": "~11.4.0",
    "expo-screen-orientation": "~4.3.0",
    "expo-splash-screen": "~0.16.2",
    "expo-sqlite": "~10.3.0",
    "expo-status-bar": "~1.4.0",
    "lodash.filter": "^4.6.0",
    "react": "18.0.0",
    "react-dom": "18.0.0",
    "react-native": "0.69.5",
    "react-native-marquee": "^0.4.0",
    "react-native-paper": "^5.0.0-rc.4",
    "react-native-safe-area-context": "4.3.1",
    "react-native-screens": "~3.15.0",
    "react-native-system-setting": "^1.7.6",
    "react-native-video": "^6.0.0-alpha.3",
    "react-native-web": "~0.18.7",
    "react-navigation": "^4.4.4"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
  "private": true
}

I have tried with different versions of the library and with different buffer configurations, but nothing works. Does anyone know why this error occurs and how to fix it? Thanks.


问:
iMacros: Why I have "undefined" value time to time?
I have the iMacros code bellow and I don't understand why sometime, not always {{draft18claim}} receive undefined Value or 0.0.0.2.

the script is made to go to a link once at 2 loops.

```<code>SET filterdraft18claim "videos/upload?filter=%5B%7B"name"%3A"VISIBILITY"%2C"value"%3A%5B"DRAFT"%5D%7D%2C%7B"name"%3A"AGE_RESTRICTION"%2C"value"%3A"NOT_AGE_RESTRICTED"%7D%2C%7B"name"%3A"HAS_COPYRIGHT_CLAIM"%2C"value"%3A"VIDEO_HAS_COPYRIGHT_CLAIM"%7D%5D&sort=%7B"columnType"%3A"date"%2C"sortOrder"%3A"DESCENDING"%7D"

SET draft18claim EVAL("var n='{{!LOOP}}'; var z; if((n%2)==1){z=\"https://studio.youtube.com/channel/{{idcanal}}/video/{{filterdraft18claim}}\";} else{z=\"javascript:window.scrollBy(0,5)\";}; z;")

URL GOTO={{draft18claim}}
</code>```

Error

```<code>RuntimeError: Navigation error occured while loading url http://undefined/, details: net::ERR_NAME_NOT_RESOLVED, line: 65
</code>```

thank you

I am using (FCI): iMacros for CR v10.1.1 'PE', CR v105.0.5195.102 (_x64), Win10_x64. ('CR' = 'Chrome' / 'PE' = 'Personal Edition')

Body:
I have the iMacros code bellow and I don't understand why sometime, not always {{draft18claim}} receive undefined Value or 0.0.0.2.

the script is made to go to a link once at 2 loops.

SET filterdraft18claim "videos/upload?filter=%5B%7B"name"%3A"VISIBILITY"%2C"value"%3A%5B"DRAFT"%5D%7D%2C%7B"name"%3A"AGE_RESTRICTION"%2C"value"%3A"NOT_AGE_RESTRICTED"%7D%2C%7B"name"%3A"HAS_COPYRIGHT_CLAIM"%2C"value"%3A"VIDEO_HAS_COPYRIGHT_CLAIM"%7D%5D&sort=%7B"columnType"%3A"date"%2C"sortOrder"%3A"DESCENDING"%7D"

SET draft18claim EVAL("var n='{{!LOOP}}'; var z; if((n%2)==1){z=\"https://studio.youtube.com/channel/{{idcanal}}/video/{{filterdraft18claim}}\";} else{z=\"javascript:window.scrollBy(0,5)\";}; z;")

URL GOTO={{draft18claim}}

Error

RuntimeError: Navigation error occured while loading url http://undefined/, details: net::ERR_NAME_NOT_RESOLVED, line: 65

thank you

I am using (FCI): iMacros for CR v10.1.1 'PE', CR v105.0.5195.102 (_x64), Win10_x64. ('CR' = 'Chrome' / 'PE' = 'Personal Edition')


问:
Trouble with Google Protobuf Serializer dependency when upgrading from Python2 to Python3
I have some old Python2 code I have to upgrade to Python3 and it's currently using the google.protobuf library to serialize data to be sent to rabbitMQ. Java code then picks this up on the other end and deserializes. I can't update the Java code with a newly generated pb2 file that's supported by Python3. Python3 won't allow me to use the old Python2.7 pb2 file as the old google protobuf dependency has many errors.

Example:

```<code>  File , line 6, in <module>
    from google.protobuf import descriptor_pb2
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pb2.py", line 7, in <module>
    from google.protobuf import descriptor_pool as _descriptor_pool
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pool.py", line 1291, in <module>
    _DEFAULT = DescriptorPool()
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pool.py", line 140, in __init__
    self._internal_db = descriptor_database.DescriptorDatabase()
AttributeError: module 'google.protobuf.descriptor_database' has no attribute 'DescriptorDatabase'
</code>```

I've tried adding future dependency to the protobuf file but this doesn't help at all. What should I do here? Does it even matter if I upgrade the serializer file but leave the deserializer code the same? If so, how should I get this old library to work on python3.9?

Body:
I have some old Python2 code I have to upgrade to Python3 and it's currently using the google.protobuf library to serialize data to be sent to rabbitMQ. Java code then picks this up on the other end and deserializes. I can't update the Java code with a newly generated pb2 file that's supported by Python3. Python3 won't allow me to use the old Python2.7 pb2 file as the old google protobuf dependency has many errors.

Example:

  File , line 6, in <module>
    from google.protobuf import descriptor_pb2
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pb2.py", line 7, in <module>
    from google.protobuf import descriptor_pool as _descriptor_pool
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pool.py", line 1291, in <module>
    _DEFAULT = DescriptorPool()
  File "venv/lib/python3.9/site-packages/google/protobuf/descriptor_pool.py", line 140, in __init__
    self._internal_db = descriptor_database.DescriptorDatabase()
AttributeError: module 'google.protobuf.descriptor_database' has no attribute 'DescriptorDatabase'

I've tried adding future dependency to the protobuf file but this doesn't help at all. What should I do here? Does it even matter if I upgrade the serializer file but leave the deserializer code the same? If so, how should I get this old library to work on python3.9?


问:
ZF2 to Laminas migration when using Twig for rendering
I'm migrating my application from ZF2 to Laminas because I need to upgrade to PHP8.1.  My issue is that with Zend Framework we were using ZfcTwig to have Twig be the renderer instead of the standard PhpRenderer.  And I'm having trouble figuring out how to get a new TwigRenderer to be operational.
I've added mezzio/mezzio-twigrenderer to my composer json and it's downloading the proper vendor files, but it isn't putting the parts into the service manager factories and aliases like ZfcTwig did, and it isn't setting the TwigStrategy in the view_manager.

For ZfcTwig this was done with the following application.config.php:

```<code>return \Zend\Stdlib\ArrayUtils::merge([
    'modules' => [
        'DoctrineModule',
        'DoctrineORMModule',
        'SwissEngine\Tools\Doctrine\Extension',

        'Zend\Form',
        'Zend\I18n',
...

        // Must be at the end so that JsonStrategy has a higher priority
        'ZfcTwig',

    ],

</code>```

What am I missing that will allow me to get the Mezzio\Twig\TwigRenderer to take the place of ZfcTwig?

I've tried manually adjusting the composer.lock file to put a laminas component:

```<code>"extra": {
    "laminas": {
        "component": "Mezzio\\Twig\\TwigRenderer"
        "config-provider": "Mezzio\\Twig\\ConfigProvider"
    }
},

</code>```

I thought this would add the Mezzio packages to the service manager, but it didn't.

Body:
I'm migrating my application from ZF2 to Laminas because I need to upgrade to PHP8.1.  My issue is that with Zend Framework we were using ZfcTwig to have Twig be the renderer instead of the standard PhpRenderer.  And I'm having trouble figuring out how to get a new TwigRenderer to be operational.
I've added mezzio/mezzio-twigrenderer to my composer json and it's downloading the proper vendor files, but it isn't putting the parts into the service manager factories and aliases like ZfcTwig did, and it isn't setting the TwigStrategy in the view_manager.

For ZfcTwig this was done with the following application.config.php:

return \Zend\Stdlib\ArrayUtils::merge([
    'modules' => [
        'DoctrineModule',
        'DoctrineORMModule',
        'SwissEngine\Tools\Doctrine\Extension',

        'Zend\Form',
        'Zend\I18n',
...

        // Must be at the end so that JsonStrategy has a higher priority
        'ZfcTwig',

    ],

What am I missing that will allow me to get the Mezzio\Twig\TwigRenderer to take the place of ZfcTwig?

I've tried manually adjusting the composer.lock file to put a laminas component:

"extra": {
    "laminas": {
        "component": "Mezzio\\Twig\\TwigRenderer"
        "config-provider": "Mezzio\\Twig\\ConfigProvider"
    }
},

I thought this would add the Mezzio packages to the service manager, but it didn't.


问:
How to store user entered qty's per PageView page when navigating to next page Flutter
I have several pages using PageView builder.

The pages are built using data from an API and gathered using HIVE boxes. Within each page there is a Qty box that i require the user to enter a figure but when i swipe to the next page and then back the user entered Qty is lost.

I'm new to using Flutter/Dart and wondered what's the best approach to solve such an issue.

I also have a flutter_switch within the PageView too but it if i toggle the switch ON(true) it's also the same state on each subsequent pages of my PageView builder.  Can this be solved too?

Many thanks.


问:
$wp_customize->add_control() Textarea in wordpress Customizer Section does not Update in Preview pane in Realtime
I have created a textarea in WordPress Customizer in the following way.

```<code>$wp_customize->add_setting( "stylesheet_setting", array(
    'default' => '',
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'transport' => 'postMessage',
    'sanitize_callback' => 'sanitize_textarea_field',
) );

$wp_customize->add_control( "stylesheet_setting", array(
    'section' => "stylesheet_section",
    'type' => 'textarea',
) );
</code>```

Problem

The Problem I am having is that, when I write CSS code in this textarea, it does not update the preview pane in realtime, instead, if I use the refresh method for transfer, it updates after refreshing.

I want to update in real-time just like I enter CSS in WordPress Custom CSS Textbox.

Body:
I have created a textarea in WordPress Customizer in the following way.

$wp_customize->add_setting( "stylesheet_setting", array(
    'default' => '',
    'type' => 'theme_mod',
    'capability' => 'edit_theme_options',
    'transport' => 'postMessage',
    'sanitize_callback' => 'sanitize_textarea_field',
) );

$wp_customize->add_control( "stylesheet_setting", array(
    'section' => "stylesheet_section",
    'type' => 'textarea',
) );

Problem

The Problem I am having is that, when I write CSS code in this textarea, it does not update the preview pane in realtime, instead, if I use the refresh method for transfer, it updates after refreshing.

I want to update in real-time just like I enter CSS in WordPress Custom CSS Textbox.


问:
Improving memory allocation when the array size is only known at run time
My question is similar to this one but there is an important subtlety.

Consider the following functions

```<code>using Distributions

function test_function_create_state_list(state_n)
    states = []
    for i in 1:state_n
        push!(states, (sample(1:3), sample(1:3), sample(1:3)))
    end

    return states
end

function test_function(state, M, new_number)
    M[state..., 1] = new_number
end

function test_loop(loop_n)
    states = test_function_create_state_list(loop_n)
    M     = randn(10,10,10,10)
    for state in states
        test_function(state, M, 1.0)
    end
end
</code>```

Here, state is a vector of length k = 3 and M is an array of dimension k+1 = 4. I learned from the linked question that if I knew k when I'm writing my code, I can make state a tuple to improve allocation. However, what if I want to write the following function

```<code>function test_function_user(states, M)
    for state in states
        test_function(state, M, 1.0)
    end
end
</code>```

such that states and M are provided at run time (by the user)? When I'm writing the program, I would not know the array sizes of state and M. Is there a way to improve the allocation? I don't know how to use tuples for this, since tuples are not mutable. If I were to use StaticArrays, I would need to know the array size when I'm writing the program.

Body:
My question is similar to this one but there is an important subtlety.

Consider the following functions

using Distributions

function test_function_create_state_list(state_n)
    states = []
    for i in 1:state_n
        push!(states, (sample(1:3), sample(1:3), sample(1:3)))
    end

    return states
end

function test_function(state, M, new_number)
    M[state..., 1] = new_number
end

function test_loop(loop_n)
    states = test_function_create_state_list(loop_n)
    M     = randn(10,10,10,10)
    for state in states
        test_function(state, M, 1.0)
    end
end

Here, state is a vector of length k = 3 and M is an array of dimension k+1 = 4. I learned from the linked question that if I knew k when I'm writing my code, I can make state a tuple to improve allocation. However, what if I want to write the following function

function test_function_user(states, M)
    for state in states
        test_function(state, M, 1.0)
    end
end

such that states and M are provided at run time (by the user)? When I'm writing the program, I would not know the array sizes of state and M. Is there a way to improve the allocation? I don't know how to use tuples for this, since tuples are not mutable. If I were to use StaticArrays, I would need to know the array size when I'm writing the program.


问:
c# Background Task only runs 1 time?
Hi so i wane do a background task with my code but the code only runs 1 time when i startup my application. i have put a break point already in my infinity loop but that doesn't get triggerd. So i was wondering what can be the issue. my task is doing a test if my data is coming in my google calendar. Its a check. I hope somebody can help me out.</p>
```<code>protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            string DbConnectionString = _configuration.GetValue<string>("Site:ConnectionString");

            using (IDbConnection conn = OpenConnection(DbConnectionString))
            {
                List<GoogleAccess> googleCredentials = conn.Query<Domain.GoogleAccess>("Select g.Id, g.CalendarId, g.RefreshToken, convert(nvarchar(36), g.CompanyUserId) as CompanyUserId from [dbo].[googleAccess] g", null, commandType: CommandType.Text).ToList();

                // list with all users

                foreach (var credential in googleCredentials.Where(e => e.RefreshToken is not null).ToList())
                {
                    var accessToken = RefreshToken(credential.RefreshToken);

                    // search all events Where that contain CompanyUserTreatmentId From that user
                    var allReservations = await TurnUp.Admin.Infrastructure.RestAPI.Reservation.GetAll(new Models.RestAPI.Reservation.PostModel.GetAllReservationPostModel() { });

                    var covertedList = new List<EventModel>();

                    foreach (var reservation in allReservations.result.items.Where(e => e.isCancelled == false).ToList())
                    {
                        covertedList.Add(new EventModel
                        {
                            Id = reservation.id.ToString(),
                            Description = reservation.description,
                            Start = new EventDateTime { DateTime = DateTime.Parse(reservation.startTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
                            End = new EventDateTime { DateTime = DateTime.Parse(reservation.endTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
                            Summary = reservation.description
                        });
                    }

                    //Retrieving all Google Events from google api
                    var allGoogleEvents = new List<EventModel>();
                    RestClient restClient = new RestClient(new Uri("https://www.googleapis.com/calendar/v3/calendars/primary/events"));
                    RestRequest restRequest = new RestRequest();

                    //Send parameters with the request
                    restRequest.AddQueryParameter("key", $"{ApiKeys}");
                    restRequest.AddParameter("maxResults", 2500);
                    restRequest.AddParameter("OrderBy", "startTime");
                    restRequest.AddParameter("showDeleted", "false");
                    restRequest.AddParameter("timeMin", DateTime.UtcNow.AddMonths(-1).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
                    restRequest.AddParameter("timeMax", DateTime.UtcNow.AddMonths(6).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
                    restRequest.AddHeader("Authorization", "Bearer " + accessToken);
                    restRequest.AddHeader("Accept", "application/json");

                    try
                    {
                        //Get request to server
                        var response = restClient.Get(restRequest);

                        //check if response is ok
                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            //change response to an class that can be used
                            JObject calendarEvents = JObject.Parse(response.Content);
                            var test = calendarEvents["nextSyncToken"].ToString();
                            allGoogleEvents = calendarEvents["items"].ToObject<List<EventModel>>();

                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Coulden't connect to google agenda.");
                    }

                    //list with reservations that arn't in google
                    var newList = covertedList.Except(allGoogleEvents).Concat(allGoogleEvents.Except(covertedList));
                    //var newList = googleEventList.Except(covertedList).Concat(covertedList.Except(googleEventList));

                    foreach (var ev in newList)
                    {
                        var restClientForAddingEvents = new RestClient();
                        var restRequestForAddingEvents = new RestRequest();
                        restClientForAddingEvents.BaseUrl = new System.Uri($"https://www.googleapis.com/calendar/v3/calendars/{credential.CalendarId}/events");

                        EventModel newEvent = new EventModel();

                        newEvent.Start.DateTime = DateTime.Parse(ev.Start.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
                        newEvent.End.DateTime = DateTime.Parse(ev.End.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
                        newEvent.Description = ev.Description;
                        newEvent.Id = Guid.NewGuid().ToString().Replace("-", "");

                        var model = JsonConvert.SerializeObject(newEvent, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });

                        //Send parameters with the request
                        restRequest.AddQueryParameter("key", $"{ApiKeys}");
                        restRequest.AddHeader("Authorization", "Bearer " + accessToken);
                        restRequest.AddHeader("Accept", "application/json");
                        restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
                        restRequest.AddParameter("application/json", model, ParameterType.RequestBody);

                        //RestClient restClient = new RestClient(new Uri($"https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/" + ev.Id.ToString().Replace("-", "")));
                        //RestRequest restRequest = new RestRequest();

                        ////Send parameters with the request
                        //restRequest.AddQueryParameter("key", $"{ApiKeys}");
                        //restRequest.AddHeader("Authorization", "Bearer " + accestoken);
                        //restRequest.AddHeader("Accept", "application/json");

                        try
                        {
                            //Post request to server
                            var restResponse = restClient.Post(restRequest);

                            //check if response is ok
                            if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
                            {

                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Coulden't Create an event in google agenda.");
                        }

                    }
                }
            }
            await Task.Delay(5000, stoppingToken);
        }
    }
</code>```

Title: c# Background Task only runs 1 time?

Body:
Hi so i wane do a background task with my code but the code only runs 1 time when i startup my application. i have put a break point already in my infinity loop but that doesn't get triggerd. So i was wondering what can be the issue. my task is doing a test if my data is coming in my google calendar. Its a check. I hope somebody can help me out.

protected async override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            string DbConnectionString = _configuration.GetValue<string>("Site:ConnectionString");

            using (IDbConnection conn = OpenConnection(DbConnectionString))
            {
                List<GoogleAccess> googleCredentials = conn.Query<Domain.GoogleAccess>("Select g.Id, g.CalendarId, g.RefreshToken, convert(nvarchar(36), g.CompanyUserId) as CompanyUserId from [dbo].[googleAccess] g", null, commandType: CommandType.Text).ToList();

                // list with all users

                foreach (var credential in googleCredentials.Where(e => e.RefreshToken is not null).ToList())
                {
                    var accessToken = RefreshToken(credential.RefreshToken);

                    // search all events Where that contain CompanyUserTreatmentId From that user
                    var allReservations = await TurnUp.Admin.Infrastructure.RestAPI.Reservation.GetAll(new Models.RestAPI.Reservation.PostModel.GetAllReservationPostModel() { });

                    var covertedList = new List<EventModel>();

                    foreach (var reservation in allReservations.result.items.Where(e => e.isCancelled == false).ToList())
                    {
                        covertedList.Add(new EventModel
                        {
                            Id = reservation.id.ToString(),
                            Description = reservation.description,
                            Start = new EventDateTime { DateTime = DateTime.Parse(reservation.startTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
                            End = new EventDateTime { DateTime = DateTime.Parse(reservation.endTime.ToString()).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"), TimeZone = "Europe/Zurich" },
                            Summary = reservation.description
                        });
                    }

                    //Retrieving all Google Events from google api
                    var allGoogleEvents = new List<EventModel>();
                    RestClient restClient = new RestClient(new Uri("https://www.googleapis.com/calendar/v3/calendars/primary/events"));
                    RestRequest restRequest = new RestRequest();

                    //Send parameters with the request
                    restRequest.AddQueryParameter("key", $"{ApiKeys}");
                    restRequest.AddParameter("maxResults", 2500);
                    restRequest.AddParameter("OrderBy", "startTime");
                    restRequest.AddParameter("showDeleted", "false");
                    restRequest.AddParameter("timeMin", DateTime.UtcNow.AddMonths(-1).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
                    restRequest.AddParameter("timeMax", DateTime.UtcNow.AddMonths(6).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK"));
                    restRequest.AddHeader("Authorization", "Bearer " + accessToken);
                    restRequest.AddHeader("Accept", "application/json");

                    try
                    {
                        //Get request to server
                        var response = restClient.Get(restRequest);

                        //check if response is ok
                        if (response.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            //change response to an class that can be used
                            JObject calendarEvents = JObject.Parse(response.Content);
                            var test = calendarEvents["nextSyncToken"].ToString();
                            allGoogleEvents = calendarEvents["items"].ToObject<List<EventModel>>();

                        }
                    }
                    catch (Exception ex)
                    {
                        throw new Exception("Coulden't connect to google agenda.");
                    }

                    //list with reservations that arn't in google
                    var newList = covertedList.Except(allGoogleEvents).Concat(allGoogleEvents.Except(covertedList));
                    //var newList = googleEventList.Except(covertedList).Concat(covertedList.Except(googleEventList));

                    foreach (var ev in newList)
                    {
                        var restClientForAddingEvents = new RestClient();
                        var restRequestForAddingEvents = new RestRequest();
                        restClientForAddingEvents.BaseUrl = new System.Uri($"https://www.googleapis.com/calendar/v3/calendars/{credential.CalendarId}/events");

                        EventModel newEvent = new EventModel();

                        newEvent.Start.DateTime = DateTime.Parse(ev.Start.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
                        newEvent.End.DateTime = DateTime.Parse(ev.End.DateTime).ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
                        newEvent.Description = ev.Description;
                        newEvent.Id = Guid.NewGuid().ToString().Replace("-", "");

                        var model = JsonConvert.SerializeObject(newEvent, new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver()
                        });

                        //Send parameters with the request
                        restRequest.AddQueryParameter("key", $"{ApiKeys}");
                        restRequest.AddHeader("Authorization", "Bearer " + accessToken);
                        restRequest.AddHeader("Accept", "application/json");
                        restRequest.AddHeader("Content-Type", "application/json; charset=utf-8");
                        restRequest.AddParameter("application/json", model, ParameterType.RequestBody);

                        //RestClient restClient = new RestClient(new Uri($"https://www.googleapis.com/calendar/v3/calendars/{calendarId}/events/" + ev.Id.ToString().Replace("-", "")));
                        //RestRequest restRequest = new RestRequest();

                        ////Send parameters with the request
                        //restRequest.AddQueryParameter("key", $"{ApiKeys}");
                        //restRequest.AddHeader("Authorization", "Bearer " + accestoken);
                        //restRequest.AddHeader("Accept", "application/json");

                        try
                        {
                            //Post request to server
                            var restResponse = restClient.Post(restRequest);

                            //check if response is ok
                            if (restResponse.StatusCode == System.Net.HttpStatusCode.OK)
                            {

                            }
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Coulden't Create an event in google agenda.");
                        }

                    }
                }
            }
            await Task.Delay(5000, stoppingToken);
        }
    }


问:
How can I send a DELETE request with parameters using Volley?
I want to send a DELETE request to an API to delete a city with the given id. In the API request documentation it says that the DELETE request requires as parameters the authentication token and the city id. When I run the code below I always get a com.android.volley.AuthFailureError.

Here's my code:

void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
    String url = baseUrl + "city";

    try {
        JSONObject params = new JSONObject();
        params.put("token", token);
        params.put("city_id", cityId);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.DELETE, url, params, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            String success = response.get("success").toString();
                            if(success.equals("true")){
                                volleyResponseListener.onResponse();
                            }else{
                                String errorMessage = response.get("errorMessage").toString();
                                throw new Exception(errorMessage);
                            }
                        } catch (Exception e) {
                            volleyResponseListener.onError(e.getMessage());
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println(error);
                        volleyResponseListener.onError("Volley Error");
                    }
                });
        requestQueue.add(jsonObjectRequest);
    }catch (JSONException e){
        volleyResponseListener.onError("Param error");
    }
}
```
<p>UPDATE:</p>
<p>I solved the problem by adding the city id as a query in the HTTP request and sent the authentication token in the header. Here is the final code:</p>
<pre class="lang-java prettyprint-override"><code>void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
    String url = baseUrl + "city?city_id="+cityId;

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            String success = response.get("success").toString();
                            if(success.equals("true")){
                                volleyResponseListener.onResponse();
                            }else{
                                String errorMessage = response.get("errorMessage").toString();
                                throw new Exception(errorMessage);
                            }
                        } catch (Exception e) {
                            volleyResponseListener.onError(e.getMessage());
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println(error);
                        volleyResponseListener.onError("Volley Error");
                    }
                }){

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = super.getHeaders();

                    if (headers == null || headers.equals(Collections.emptyMap())) {
                        headers = new HashMap<String, String>();
                    }

                    headers.put("token", token);

                    return headers;
                }

            };
        requestQueue.add(jsonObjectRequest);
}
</code>```

Body:
I want to send a DELETE request to an API to delete a city with the given id. In the API request documentation it says that the DELETE request requires as parameters the authentication token and the city id. When I run the code below I always get a com.android.volley.AuthFailureError.

Here's my code:

void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
    String url = baseUrl + "city";

    try {
        JSONObject params = new JSONObject();
        params.put("token", token);
        params.put("city_id", cityId);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.DELETE, url, params, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            String success = response.get("success").toString();
                            if(success.equals("true")){
                                volleyResponseListener.onResponse();
                            }else{
                                String errorMessage = response.get("errorMessage").toString();
                                throw new Exception(errorMessage);
                            }
                        } catch (Exception e) {
                            volleyResponseListener.onError(e.getMessage());
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println(error);
                        volleyResponseListener.onError("Volley Error");
                    }
                });
        requestQueue.add(jsonObjectRequest);
    }catch (JSONException e){
        volleyResponseListener.onError("Param error");
    }
}

UPDATE:

I solved the problem by adding the city id as a query in the HTTP request and sent the authentication token in the header. Here is the final code:

void deleteCity(String cityId, final VolleyResponseListener volleyResponseListener){
    String url = baseUrl + "city?city_id="+cityId;

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                (Request.Method.DELETE, url, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try{
                            String success = response.get("success").toString();
                            if(success.equals("true")){
                                volleyResponseListener.onResponse();
                            }else{
                                String errorMessage = response.get("errorMessage").toString();
                                throw new Exception(errorMessage);
                            }
                        } catch (Exception e) {
                            volleyResponseListener.onError(e.getMessage());
                        }

                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        System.out.println(error);
                        volleyResponseListener.onError("Volley Error");
                    }
                }){

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> headers = super.getHeaders();

                    if (headers == null || headers.equals(Collections.emptyMap())) {
                        headers = new HashMap<String, String>();
                    }

                    headers.put("token", token);

                    return headers;
                }

            };
        requestQueue.add(jsonObjectRequest);
}


问:
OpenModelica SimulationOptions 'variableFilter' not working with '^' exceptions
To reduce size of my simulation output files, I want to give variable name exceptions instead of a list of many certain variables to the simulationsOptions/outputFilter (cf. OpenModelica Users Guide / Output) of my model. I found the regexp operator "^" to fullfill my needs, but that didn't work as expected. So I think that something is wrong with the interpretation of connected character strings when negated.

Example:

When I have any derivatives der(...) in my model and use variableFilter=der.* the output file will contain all the filtered derivatives. Since there are no other varibles beginning with character d the same happens with variableFilter=d.*. For testing I also tried variableFilter=rde.* to confirm that every variable is filtered.

When I now try to except by variableFilter=^der.*, =^rde.* or =^d.*, I get exactly the same result as without using ^. So the operator seems to be ignored in this notation.

When I otherwise use variableFilter=[^der].*, =[^rde].* or even =[^d].*, all wanted derivation variables are filtered from the ouput, but there is no difference between those three expressions above. For me it seems that every character is interpretated standalone and not as as a connected string.

Did I understand and use the regexp usage right or could this be a code bug?

Side/follow-up question: Where can I officially report this for software revision?

_

OpenModelica v.1.19.2 (64-bit)


问:
Python: error when trying to import bezier library to the project
I'm trying to use the bezier library in a project. However, when trying to run the code, the following error appears:

```<code>ImportError                               Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_13584\714332593.py in <module>
----> 1 import bezier
      2 import numpy as np
      3 import tkinter as tk
      4
      5

~\anaconda3\lib\site-packages\bezier\__init__.py in <module>
     39     _HAS_SPEEDUP = True
     40 except ImportError as exc:  # pragma: NO COVER
---> 41     __config__.handle_import_error(exc, "_speedup")
     42     _HAS_SPEEDUP = False
     43 # NOTE: The ``__version__`` and ``__author__`` are hard-coded here, rather

~\anaconda3\lib\site-packages\bezier\__config__.py in handle_import_error(caught_exc, name)
    134         return
    135
--> 136     raise caught_exc
    137
    138

~\anaconda3\lib\site-packages\bezier\__init__.py in <module>
     35
     36 try:
---> 37     import bezier._speedup  # noqa: F401
     38
     39     _HAS_SPEEDUP = True

ImportError: DLL load failed while importing _speedup: Не найден указанный модуль.
</code>```

Library is installed. Python version 3.9.7.

Spent over an hour trying to find out what can cause this library to not to work. Unfortunately, unsuccessfully. Would be glad for a help.

Body:
I'm trying to use the bezier library in a project. However, when trying to run the code, the following error appears:

ImportError                               Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_13584\714332593.py in <module>
----> 1 import bezier
      2 import numpy as np
      3 import tkinter as tk
      4
      5

~\anaconda3\lib\site-packages\bezier\__init__.py in <module>
     39     _HAS_SPEEDUP = True
     40 except ImportError as exc:  # pragma: NO COVER
---> 41     __config__.handle_import_error(exc, "_speedup")
     42     _HAS_SPEEDUP = False
     43 # NOTE: The ``__version__`` and ``__author__`` are hard-coded here, rather

~\anaconda3\lib\site-packages\bezier\__config__.py in handle_import_error(caught_exc, name)
    134         return
    135
--> 136     raise caught_exc
    137
    138

~\anaconda3\lib\site-packages\bezier\__init__.py in <module>
     35
     36 try:
---> 37     import bezier._speedup  # noqa: F401
     38
     39     _HAS_SPEEDUP = True

ImportError: DLL load failed while importing _speedup: Не найден указанный модуль.

Library is installed. Python version 3.9.7.

Spent over an hour trying to find out what can cause this library to not to work. Unfortunately, unsuccessfully. Would be glad for a help.


问:
Octave changes scale of y axis when I change the x-axis
When I used this code, it plots two functions like this:

```<code>a = 2;
t0 = 1;
N = 100;
epsilon = 1e-5;

function t = metodoDeNewton(a, t0, N, epsilon)
  t = zeros(1, N+1);
  t(1) = t0;
  for i = 1:N
    t(i+1) = t(i) - (t(i).^2 - (a - sin(t(i)))) ./ (2 .* t(i) - cos(t(i)));
    if abs(t(i+1) - t(i)) < epsilon
      break;
    endif
  endfor
endfunction

t = metodoDeNewton(a, t0, N, epsilon);

x = 0:0.01:1;
y1 = t;
y2 = a - sin(t);

l = plot(x, y1, x, y2);
legend({'g(a)', 'h(a)'});
xlabel('a');
ylabel('y');
</code>```

But, when I try to change the x to x = 0:0.01:0.2 the graph's y-axis scale changes and I'm no longer able to see the functions I believe.

How can I fix this, any help would be appreciated!

Body:
When I used this code, it plots two functions like this:

a = 2;
t0 = 1;
N = 100;
epsilon = 1e-5;

function t = metodoDeNewton(a, t0, N, epsilon)
  t = zeros(1, N+1);
  t(1) = t0;
  for i = 1:N
    t(i+1) = t(i) - (t(i).^2 - (a - sin(t(i)))) ./ (2 .* t(i) - cos(t(i)));
    if abs(t(i+1) - t(i)) < epsilon
      break;
    endif
  endfor
endfunction

t = metodoDeNewton(a, t0, N, epsilon);

x = 0:0.01:1;
y1 = t;
y2 = a - sin(t);

l = plot(x, y1, x, y2);
legend({'g(a)', 'h(a)'});
xlabel('a');
ylabel('y');

But, when I try to change the x to x = 0:0.01:0.2 the graph's y-axis scale changes and I'm no longer able to see the functions I believe.

How can I fix this, any help would be appreciated!


问:
Amadeus SDK integration to Kotlin Compose crashed the app
I was following Amadeus SDK integration to my Composable app, but I am having the issues while running it. For example, if I run it in a Composable function it suddenly shuts down the app and there is no provided message of the error. During the debugging process it passes all the way to var amadeus variable, then shows the amadeus value, which is shown below and crashes. Maybe I am calling in the wrong way or could be problem of the passed context variable to Amadeus.Builder() that I am passing to it?

Code snippet

```<code>@Composable
fun HotelScreen(context: Context) {
    val job = SupervisorJob()
    val scope = CoroutineScope(Dispatchers.Main + job)

    var amadeus = Amadeus.Builder(context)
        .setClientId("sBil...")
        .setClientSecret("Zwgt...")
        .build()
 ...
}
</code>```

Snippet of amadeus variable error

Body:
I was following Amadeus SDK integration to my Composable app, but I am having the issues while running it. For example, if I run it in a Composable function it suddenly shuts down the app and there is no provided message of the error. During the debugging process it passes all the way to var amadeus variable, then shows the amadeus value, which is shown below and crashes. Maybe I am calling in the wrong way or could be problem of the passed context variable to Amadeus.Builder() that I am passing to it?

Code snippet

@Composable
fun HotelScreen(context: Context) {
    val job = SupervisorJob()
    val scope = CoroutineScope(Dispatchers.Main + job)

    var amadeus = Amadeus.Builder(context)
        .setClientId("sBil...")
        .setClientSecret("Zwgt...")
        .build()
 ...
}

Snippet of amadeus variable error


问:
This function was used in class components, now I want to change that in functional component. How can I do that?
`

```<code>if (sInd === dInd) {
        const reorderCardItems = reorderCard(items[sInd], source.index, destination.index);
       const newState = [...items];
        newState[sInd].card = reorderCardItems;
        seState({newState: newState});
</code>```

`

```<code>if (sInd === dInd) {
        const reorderCardItems = reorderCard(items[sInd], source.index, destination.index);
        let newState = [...items];
        newState[sInd].card = reorderCardItems;
        newState= newState;
</code>```

it's giving me error that 'newState' is assigned to itself.

Body:
`

if (sInd === dInd) {
        const reorderCardItems = reorderCard(items[sInd], source.index, destination.index);
       const newState = [...items];
        newState[sInd].card = reorderCardItems;
        seState({newState: newState});

`

if (sInd === dInd) {
        const reorderCardItems = reorderCard(items[sInd], source.index, destination.index);
        let newState = [...items];
        newState[sInd].card = reorderCardItems;
        newState= newState;

it's giving me error that 'newState' is assigned to itself.


问:
Barplot with significant differences and interactions in python?
I started to use python 6 months ago and may be my question is a naive one. I would like to visualize my data and ANOVA statistics. It is common to do this using a barplot with added lines indicating significant differences and interactions. How do you make plot like this using python ?

enter image description here

Here is a simple dataframe, with 3 columns (A,B and the p_values already calculated with a t-test)

```<code>mport pandas as pd
import matplotlib.pyplot as plt
import numpy as np

ar = np.array([  [565.0, 81.0, 1.630947e-02],
                    [1006.0, 311.0, 1.222740e-27],
                    [2929.0, 1292.0, 5.559912e-12],
                    [3365.0, 1979.0, 2.507474e-22],
                    [2260.0, 1117.0, 1.540305e-01]])
df = pd.DataFrame(ar,columns = ['A', 'B', 'p_value'])

ax = plt.subplot()

# I calculate the percentage
(df.iloc[:,0:2]/df.iloc[:,0:2].sum()*100).plot.bar(ax=ax)

for container, p_val in zip(ax.containers,df['p_value']):
    labels = [f"{round(v,1)}%" if (p_val > 0.05) else f"(**)\n{round(v,1)}%" for v in container.datavalues]
    ax.bar_label(container,labels=labels, fontsize=10,padding=8)

plt.show()
</code>```

Initially I just wanted to add a "**" each time a significant difference is observed between the 2 columns A & B. But the initial code above is not really working.

Now I would prefer having the added lines indicating significant differences and interactions between the A&B columns. But I have no ideas how to make it happen.

Regards
JYK

Body:
I started to use python 6 months ago and may be my question is a naive one. I would like to visualize my data and ANOVA statistics. It is common to do this using a barplot with added lines indicating significant differences and interactions. How do you make plot like this using python ?

enter image description here

Here is a simple dataframe, with 3 columns (A,B and the p_values already calculated with a t-test)

mport pandas as pd
import matplotlib.pyplot as plt
import numpy as np

ar = np.array([  [565.0, 81.0, 1.630947e-02],
                    [1006.0, 311.0, 1.222740e-27],
                    [2929.0, 1292.0, 5.559912e-12],
                    [3365.0, 1979.0, 2.507474e-22],
                    [2260.0, 1117.0, 1.540305e-01]])
df = pd.DataFrame(ar,columns = ['A', 'B', 'p_value'])

ax = plt.subplot()

# I calculate the percentage
(df.iloc[:,0:2]/df.iloc[:,0:2].sum()*100).plot.bar(ax=ax)

for container, p_val in zip(ax.containers,df['p_value']):
    labels = [f"{round(v,1)}%" if (p_val > 0.05) else f"(**)\n{round(v,1)}%" for v in container.datavalues]
    ax.bar_label(container,labels=labels, fontsize=10,padding=8)

plt.show()

Initially I just wanted to add a "**" each time a significant difference is observed between the 2 columns A & B. But the initial code above is not really working.

Now I would prefer having the added lines indicating significant differences and interactions between the A&B columns. But I have no ideas how to make it happen.

Regards
JYK


问:
Jackson YAMLFactory, how to allow/disable single quotes at a field level?
I'm using Spring Boot to return YAML via a controller. I have created a Jackson YAMLFactory ObjectMapper. However the consumer of the YAML from the endpoint is fussy about certain fields having single quotes but the majority should not, this is not something I can change.

I have my ObjectMapper set up as such:

```<code>public MappingJackson2YamlHttpMessageConverter yamlHttpMessageConverter() {
    return new MappingJackson2YamlHttpMessageConverter(new ObjectMapper(new YAMLFactory()
            .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES))
            .enable(SerializationFeature.INDENT_OUTPUT));
}
</code>```

This successfully returns me YAML with no double quotes which was the default. I can not however work out how to allow specific fields to be enclosed by single quotes. I have tried annotating the Getters with JsonRawValue and then adding the quote into the value set in the field:

```<code>@JsonRawValue
public String getSonarProjectKey() {
    return sonarProjectKey;
}
</code>```

But of course this does not work with YAML and I get an exception.

So I'm unsure about how to achieve this requirement.

Body:
I'm using Spring Boot to return YAML via a controller. I have created a Jackson YAMLFactory ObjectMapper. However the consumer of the YAML from the endpoint is fussy about certain fields having single quotes but the majority should not, this is not something I can change.

I have my ObjectMapper set up as such:

public MappingJackson2YamlHttpMessageConverter yamlHttpMessageConverter() {
    return new MappingJackson2YamlHttpMessageConverter(new ObjectMapper(new YAMLFactory()
            .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES))
            .enable(SerializationFeature.INDENT_OUTPUT));
}

This successfully returns me YAML with no double quotes which was the default. I can not however work out how to allow specific fields to be enclosed by single quotes. I have tried annotating the Getters with JsonRawValue and then adding the quote into the value set in the field:

@JsonRawValue
public String getSonarProjectKey() {
    return sonarProjectKey;
}

But of course this does not work with YAML and I get an exception.

So I'm unsure about how to achieve this requirement.


问:
how to get started with usps in laravel
hi there dev community,

i want to integrate usps services with my Laravel back end and vuejs front end web application i have see many documentations but cant find from where i have to stated my use case is:

"on completion of orders in laravel. i have to generate tracking id from usps"

Please help me out for this i am stucking in this problem from a long time and dont know from where i should started for complete integration in my project

thanks

i have found three main apis

validate address

citystatelookups

zipcodelookups

but none of these three are just for validating.
i want to integrate completely in my laravel project including these validation please send me any link or tutorials...

Title: how to get started with usps in laravel


问:
Encoding issue, failing with Assertion Error
I have a class with a function as follows
`

```<code>    private static Path compileNamedModuleTest() throws IOException {
        Path base = Paths.get(".", "named");
        Path src = base.resolve("src");
        Path classes = base.resolve("classes");

        ModuleInfoMaker maker = new ModuleInfoMaker(src);
        maker.writeJavaFiles("test",
                              "module test {}",
                              "package test; public sealed interface Base permits test.a.ImplA1, test.a.ImplA2, test.b.ImplB, test.c.ImplC {}",
                              "package test.a; public final class ImplA1 implements test.Base {}",
                              "package test.a; public final class ImplA2 implements test.Base {}",
                              "package test.b; public final class ImplB implements test.Base {}",
                              "package test.c; public final class ImplC implements test.Base {}"
                              );

         System.out.println("Default Charset: "
                           + Charset.defaultCharset());

        if (!CompilerUtils.compile(src, classes.resolve("test"), "--enable-preview", "-source", System.getProperty("java.specification.version"))) {
            throw new AssertionError("Compilation didn't succeed!");
        }

        Files.delete(classes.resolve("test").resolve("test").resolve("c").resolve("ImplC.class"));

        return classes;
    }
</code>```

`

and WriteJavaFiles function as

```<code>    /**
     * Create java source files of the given module
     */
    public void writeJavaFiles(String module, String moduleInfoJava, String... contents)
        throws IOException
    {
        Path msrc = dir.resolve(module);
        new JavaSource(moduleInfoJava).write(msrc);
        for (String c : contents) {
            new JavaSource(c).write(msrc);
        }
    }
</code>```

I am getting error as Error:

Java files created during execution have encoding issues due to which
compilation fails.

```<code>./named/src/test/test/a/ImplA1.java:1: error: illegal character: '\u009b'
/named/src/test/test/a/ImplA2.java:1: error: illegal character: '\u0080'
</code>```

Which I believe is an encoding issue and need to add charset.defaultCharset() somewhere. But I am unsure where to put it?

JavaSource class

```<code>static class JavaSource {
        final String source;
        JavaSource(String source) {
            this.source = source;
        }

        /**
         * Writes the source code to a file in a specified directory.
         * @param dir the directory
         * @throws IOException if there is a problem writing the file
         */
        public void write(Path dir) throws IOException {
            Path file = dir.resolve(getJavaFileNameFromSource(source));
            Files.createDirectories(file.getParent());
            try (BufferedWriter out = Files.newBufferedWriter(file)) {
                out.write(source.replace("\n", System.lineSeparator()));
            }
        }
</code>```

I tried adding Charset as argument in WriteJavaFiles but did not help.

Body:
I have a class with a function as follows
`

    private static Path compileNamedModuleTest() throws IOException {
        Path base = Paths.get(".", "named");
        Path src = base.resolve("src");
        Path classes = base.resolve("classes");

        ModuleInfoMaker maker = new ModuleInfoMaker(src);
        maker.writeJavaFiles("test",
                              "module test {}",
                              "package test; public sealed interface Base permits test.a.ImplA1, test.a.ImplA2, test.b.ImplB, test.c.ImplC {}",
                              "package test.a; public final class ImplA1 implements test.Base {}",
                              "package test.a; public final class ImplA2 implements test.Base {}",
                              "package test.b; public final class ImplB implements test.Base {}",
                              "package test.c; public final class ImplC implements test.Base {}"
                              );

         System.out.println("Default Charset: "
                           + Charset.defaultCharset());

        if (!CompilerUtils.compile(src, classes.resolve("test"), "--enable-preview", "-source", System.getProperty("java.specification.version"))) {
            throw new AssertionError("Compilation didn't succeed!");
        }

        Files.delete(classes.resolve("test").resolve("test").resolve("c").resolve("ImplC.class"));

        return classes;
    }

`

and WriteJavaFiles function as

    /**
     * Create java source files of the given module
     */
    public void writeJavaFiles(String module, String moduleInfoJava, String... contents)
        throws IOException
    {
        Path msrc = dir.resolve(module);
        new JavaSource(moduleInfoJava).write(msrc);
        for (String c : contents) {
            new JavaSource(c).write(msrc);
        }
    }

I am getting error as Error:

Java files created during execution have encoding issues due to which
compilation fails.

./named/src/test/test/a/ImplA1.java:1: error: illegal character: '\u009b'
/named/src/test/test/a/ImplA2.java:1: error: illegal character: '\u0080'

Which I believe is an encoding issue and need to add charset.defaultCharset() somewhere. But I am unsure where to put it?

JavaSource class

static class JavaSource {
        final String source;
        JavaSource(String source) {
            this.source = source;
        }

        /**
         * Writes the source code to a file in a specified directory.
         * @param dir the directory
         * @throws IOException if there is a problem writing the file
         */
        public void write(Path dir) throws IOException {
            Path file = dir.resolve(getJavaFileNameFromSource(source));
            Files.createDirectories(file.getParent());
            try (BufferedWriter out = Files.newBufferedWriter(file)) {
                out.write(source.replace("\n", System.lineSeparator()));
            }
        }

I tried adding Charset as argument in WriteJavaFiles but did not help.


问:
How to insert copyright symbol in images in CSS and HTML?
I'm a beginner in HTML and CSS. I'm trying to insert a copyright symbol (c) into an image on my website. I tried using a decimal code, ©, in the following code, but it is displayed as it is. Can you help me how to fix that?

CSS:

.image {
  border: 0;
  display: inline-block;
  position: relative; }
.image::after {
  content: "© My Name";
  position: absolute;
  bottom: 0;
  right: 0;
  opacity: 0.9;
  font-size: 0.7em;
  color:rgba(0, 0, 0, 0.175)}
  .image img {
    display: block;}
```
<p>HTML:</p>
<pre class="lang-html prettyprint-override"><code><span class="image">
   <img src="image1.png"/>
</span>

</code>```

This code shows © My Name on my image instead of "© My Name".

Body:
I'm a beginner in HTML and CSS. I'm trying to insert a copyright symbol (c) into an image on my website. I tried using a decimal code, ©, in the following code, but it is displayed as it is. Can you help me how to fix that?

CSS:

.image {
  border: 0;
  display: inline-block;
  position: relative; }
.image::after {
  content: "© My Name";
  position: absolute;
  bottom: 0;
  right: 0;
  opacity: 0.9;
  font-size: 0.7em;
  color:rgba(0, 0, 0, 0.175)}
  .image img {
    display: block;}

HTML:

This code shows © My Name on my image instead of "© My Name".


问:
Solve greatest-n-per-group problem using JPA Criteria API
I'm trying to write a Criteria API query which will return employees with current salary > N.
The problem is that I have to solve greatest-n-per-group problem because salaries table contains full history of employees's salaries and I have to select salary with greatest from_date.

My tables:

Employees, which look something like this

emp_no
first_name
last_name

10001
Georgi
Facello

10002
Chirstian
Koblick

And salaries table, with following format:

emp_no
salary
from_date
to_date

10001
60117
1986-06-26
1987-06-26

10001
62102
1987-06-26
1988-06-25

Employee.java:

```<code>@Entity
@Table(name="employees")
@Getter @Setter
public class Employee implements Serializable {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "emp_no")
    private long id;

    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
    List<Salary> salaries;

    @Column(name = "birth_date")
    private java.sql.Date birthDate;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    @Column(name = "hire_date")
    private java.sql.Date hireDate;

}
</code>```

Salary.java:

```<code>@Entity
@Getter @Setter
@Table(name = "salaries")
public class Salary implements Serializable {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "emp_no", insertable=false, updatable=false)
    private long id;

    @ManyToOne
    @JoinColumn(name="emp_no", insertable=false, updatable=false)
    private Employee employee;

    @Column(name = "salary")
    private int salary;

    @Column(name = "from_date")
    private java.sql.Date fromDate;

    @Column(name = "to_date")
    private java.sql.Date toDate;
}
</code>```

So, basically I'm just looking for Criteria API analogue of this SQL query

```<code>SELECT
    e1_0.emp_no,
    e1_0.birth_date,
    e1_0.first_name,
    e1_0.gender,
    e1_0.hire_date,
    e1_0.last_name,
    s1_0.salary
FROM
    employees e1_0
LEFT JOIN
    salaries s1_0 on e1_0.emp_no=s1_0.emp_no
INNER JOIN
    (SELECT emp_no, MAX(from_date) from_date
    FROM salaries s1_0
    GROUP BY emp_no)
    s2_0 ON s2_0.emp_no=s1_0.emp_no AND s2_0.from_date=s1_0.from_date
WHERE
    s1_0.salary > 100000
</code>```

Body:
I'm trying to write a Criteria API query which will return employees with current salary > N.
The problem is that I have to solve greatest-n-per-group problem because salaries table contains full history of employees's salaries and I have to select salary with greatest from_date.

My tables:

Employees, which look something like this

emp_no
first_name
last_name

10001
Georgi
Facello

10002
Chirstian
Koblick

And salaries table, with following format:

emp_no
salary
from_date
to_date

10001
60117
1986-06-26
1987-06-26

10001
62102
1987-06-26
1988-06-25

Employee.java:

@Entity
@Table(name="employees")
@Getter @Setter
public class Employee implements Serializable {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "emp_no")
    private long id;

    @OneToMany(mappedBy = "employee", fetch = FetchType.EAGER)
    List<Salary> salaries;

    @Column(name = "birth_date")
    private java.sql.Date birthDate;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Enumerated(EnumType.STRING)
    private Gender gender;

    @Column(name = "hire_date")
    private java.sql.Date hireDate;

}

Salary.java:

@Entity
@Getter @Setter
@Table(name = "salaries")
public class Salary implements Serializable {
    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "emp_no", insertable=false, updatable=false)
    private long id;

    @ManyToOne
    @JoinColumn(name="emp_no", insertable=false, updatable=false)
    private Employee employee;

    @Column(name = "salary")
    private int salary;

    @Column(name = "from_date")
    private java.sql.Date fromDate;

    @Column(name = "to_date")
    private java.sql.Date toDate;
}

So, basically I'm just looking for Criteria API analogue of this SQL query

SELECT
    e1_0.emp_no,
    e1_0.birth_date,
    e1_0.first_name,
    e1_0.gender,
    e1_0.hire_date,
    e1_0.last_name,
    s1_0.salary
FROM
    employees e1_0
LEFT JOIN
    salaries s1_0 on e1_0.emp_no=s1_0.emp_no
INNER JOIN
    (SELECT emp_no, MAX(from_date) from_date
    FROM salaries s1_0
    GROUP BY emp_no)
    s2_0 ON s2_0.emp_no=s1_0.emp_no AND s2_0.from_date=s1_0.from_date
WHERE
    s1_0.salary > 100000


问:
Incremental Static Regeneration doesn't work without redeploying
This is my very first time building and deploying a website so bear with me if this is a dumb question. I'm building a Heardle style clone. The idea is that every day there's a new song and people have 6 guesses to figure out which song it is from short clips of the song. Every part of this seems to work with one major exception -- I can't seem to reload today's song dynamically.

I have a function:

export async function getStaticProps() {
  const allSearchableSongs = songHelper.getSongData()
  const todaysSong = await songHelper.getTodaysSong()
  const songURLs: string[] = (todaysSong) ? await songHelper.getTodaysSongClips(todaysSong!) : []
  let valid = false
  if (songURLs) {
    valid = true
  }
  return {
    props: {
      allSearchableSongs,
      todaysSong,
      songURLs,
      valid
    },
    revalidate: 10
  };
}

```

Note that getTodaysSong() and getTodaysSongClips() both make calls to AWS to get data from S3. Whenever I rebuild the website this works well. However, I would like for this to refresh after 60 seconds so that nobody is ever looking at a stale website. But this doesn't change ever. The song is always out of date until I redeploy. I've checked to make sure that the data is changing daily and that's all well and good -- but the website doesn't ever reload.

I'm currently hosting this on Vercel.

What am I doing wrong? How can I ensure that this reloads after 60 seconds?

Body:
This is my very first time building and deploying a website so bear with me if this is a dumb question. I'm building a Heardle style clone. The idea is that every day there's a new song and people have 6 guesses to figure out which song it is from short clips of the song. Every part of this seems to work with one major exception -- I can't seem to reload today's song dynamically.

I have a function:

export async function getStaticProps() {
  const allSearchableSongs = songHelper.getSongData()
  const todaysSong = await songHelper.getTodaysSong()
  const songURLs: string[] = (todaysSong) ? await songHelper.getTodaysSongClips(todaysSong!) : []
  let valid = false
  if (songURLs) {
    valid = true
  }
  return {
    props: {
      allSearchableSongs,
      todaysSong,
      songURLs,
      valid
    },
    revalidate: 10
  };
}

Note that getTodaysSong() and getTodaysSongClips() both make calls to AWS to get data from S3. Whenever I rebuild the website this works well. However, I would like for this to refresh after 60 seconds so that nobody is ever looking at a stale website. But this doesn't change ever. The song is always out of date until I redeploy. I've checked to make sure that the data is changing daily and that's all well and good -- but the website doesn't ever reload.

I'm currently hosting this on Vercel.

What am I doing wrong? How can I ensure that this reloads after 60 seconds?


问:
Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_FIRAnalytics"
I know that this question has been asked before but I tried every possible solution shared online but still got the issue. First tried with pods and then moved the FirebaseAnalytics into SPM. "Build Active Architecture Only" is set NO. In framework search paths, $(inherited) value and $(PROJECT_DIR)/Frameworks are available due to the frameworks I use in pods and SPM.

This is the error I get when I import FirebaseAnalytics and call Analytics:

```<code>    Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FIRAnalytics", referenced from:
      objc-class-ref in SessionManager.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
</code>```

Body:
I know that this question has been asked before but I tried every possible solution shared online but still got the issue. First tried with pods and then moved the FirebaseAnalytics into SPM. "Build Active Architecture Only" is set NO. In framework search paths, $(inherited) value and $(PROJECT_DIR)/Frameworks are available due to the frameworks I use in pods and SPM.

This is the error I get when I import FirebaseAnalytics and call Analytics:

    Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_FIRAnalytics", referenced from:
      objc-class-ref in SessionManager.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)


问:
how to assign specific color to sunburst chart
how to assign specific color to sunburst chart

I have date in excel with colored cells
I want to let sunburst chart pickup colors from the cells

`

```<code>from pathlib import Path

import pandas as pd
import plotly
import plotly.express as px

from tkinter import messagebox
import plotly.graph_objects as go

import openpyxl

# Define excel file location
excel_file = Path(__file__).parent / "data.xlsx"

# Read Data from Excel
df = pd.read_excel(excel_file)

# Assign columns to variables
G1 = df["G1"]
G2 = df["G2"]
G3 = df["G3"]
G4 = df["G4"]
G5 = df["G5"]
G6 = df["G6"]
G7 = df["G7"]
G8 = df["G8"]
G9 = df["G9"]
G10 = df["G10"]

fig= px.sunburst(df ,path=[G1,G2,G3,G4,G5,G6,G7,G8,G9,G10]  )

output_path = Path(__file__).parent / "Treemap_xx.html"
plotly.offline.plot(fig, filename=str(output_path))
messagebox.showinfo("showinfo", "Done")
</code>```

`

Data(https://i.stack.imgur.com/FohO8.png)
Plot(https://i.stack.imgur.com/EaJEs.png)

Please fix the code to get done

Body:
how to assign specific color to sunburst chart

I have date in excel with colored cells
I want to let sunburst chart pickup colors from the cells

`

from pathlib import Path

import pandas as pd
import plotly
import plotly.express as px

from tkinter import messagebox
import plotly.graph_objects as go

import openpyxl

# Define excel file location
excel_file = Path(__file__).parent / "data.xlsx"

# Read Data from Excel
df = pd.read_excel(excel_file)

# Assign columns to variables
G1 = df["G1"]
G2 = df["G2"]
G3 = df["G3"]
G4 = df["G4"]
G5 = df["G5"]
G6 = df["G6"]
G7 = df["G7"]
G8 = df["G8"]
G9 = df["G9"]
G10 = df["G10"]

fig= px.sunburst(df ,path=[G1,G2,G3,G4,G5,G6,G7,G8,G9,G10]  )

output_path = Path(__file__).parent / "Treemap_xx.html"
plotly.offline.plot(fig, filename=str(output_path))
messagebox.showinfo("showinfo", "Done")

`

Data(https://i.stack.imgur.com/FohO8.png)
Plot(https://i.stack.imgur.com/EaJEs.png)

Please fix the code to get done


问:
How can I view the visualize TAB in Postman Collection Runner?
quick question
I have my Data formatted in excel table in the visualize  but when I run the collection Runner My visualize tab "gone" any way I can get the visualize tab on the Collection Runner or anyway I can get my console log in Excel format . thanks enter image description here

Everything is working fine , Visualize is working perfect , data comes in excel format but when run the collection my excel data gone I need to be able to export the collection in Excel to be able to process it .


问:
ggplot2 histogram with outlier bin from tibble?
Much like this previous question, I am trying to create some histograms with ggplot2 and would like to add a "greater than X"-bin that includes all values greater than some value.

In this particular case, I am dealing with a set of bike trip data with trip durations that vary from very small (under a minute) to very, very large (hours to days).  I have filter()ed the set to remove the truly extraneous rows, but I would still like to show some of the outliers on the plot.

I had already found the solution given there, the package ggoutlier, but it evidently requires the data be in a data.frame—I get an error message that "is.data.frame(x) is not TRUE".  This is correct, x is a tibble—is there another solution that works with a tibble?


问:
How can I reference a typescript interface property by its name as a variable?
I have an interface:

```<code>interface Things {
    Thing?: string
    Thing2?: string
}

const things: Things = {
    Thing: "1",
    Thing2: "2"
}
</code>```

How can I retrieve the value of a property by name through a variable that contains that name?

```<code>const indexer = "Thing";

const value = things[indexer]; // should return "1"
</code>```

Body:
I have an interface:

interface Things {
    Thing?: string
    Thing2?: string
}

const things: Things = {
    Thing: "1",
    Thing2: "2"
}

How can I retrieve the value of a property by name through a variable that contains that name?

const indexer = "Thing";

const value = things[indexer]; // should return "1"


问:
how do we keep employee requestor field as disabled in netsuite
I want to keep Employee requestor field as disabled mode when page loads.Can you help on below code.</p>
```<code>/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(["N/record", "N/ui/serverWidget"], function (record, serverWidget) {
  function myBeforeLoad(context) {
    if (context.type !== context.UserEventType.CREATE) return;
    var form = context.form;
    var notesField = form.getField({
      id: "employee",
    });
    notesField.updateDisplayType({
      displayType: serverWidget.FieldDisplayType.DISABLED,
    });
  }
  return {
    beforeLoad: myBeforeLoad,
  };
});

</code>```

Body:
I want to keep Employee requestor field as disabled mode when page loads.Can you help on below code.

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 */
define(["N/record", "N/ui/serverWidget"], function (record, serverWidget) {
  function myBeforeLoad(context) {
    if (context.type !== context.UserEventType.CREATE) return;
    var form = context.form;
    var notesField = form.getField({
      id: "employee",
    });
    notesField.updateDisplayType({
      displayType: serverWidget.FieldDisplayType.DISABLED,
    });
  }
  return {
    beforeLoad: myBeforeLoad,
  };
});


问:
Correct use of @Transient
I have a entity, something like this:

```<code>@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity(name = "warranties")
public class Warranty implements Comparable<Warranty> {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "warranty_pk")
  private Long id;

  @Column(nullable = false)
  private Date startDate;

  @Column(nullable = false)
  private Date expireDate;

  @Column
  private String note;

  @Transient
  private Date displayDate;
  }
}
</code>```

Notice that displayDate is annotated with @Transient.

I have two functionalities related to this entity, one is to fetch some of them, to do that I need to check expiration dates. So in my repository I have the following query:

```<code>  @Query(value =
      "SELECT "
          + "IF(expire_date < ((CURDATE() + INTERVAL 1 DAY) - INTERVAL 1 SECOND), expire_date, (expire_date - INTERVAL 90 day)) AS display_date, * "
          + "FROM warranties "
          + "WHERE expire_date < ((CURDATE() + INTERVAL 1 DAY) - INTERVAL 1 SECOND) + INTERVAL 90 DAY "
          + "AND expire_date <= :expire_date "
          + "AND start_date >= :startDate "
          + "AND expire_date <= :endDate + INTERVAL 90 DAY "
          + "ORDER BY display_date DESC",
      nativeQuery = true)
  List<Warranty> findWarranties(@Param("expire_date") Date expireDate,
      @Param("startDate") Date startDate, @Param("endDate") Date endDate);
</code>```

Its that way so I can retrieve the "displayDate" calculated by the database.

It works fine when I use the following import:

```<code>import org.springframework.data.annotation.Transient;
</code>```

And the other functionality is a save, where I save a given note.

For that case I get the following error:

```<code>Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'warranty0_.display_date' in 'field list'
</code>```

If I use the following import, the second functionality works fine:

```<code>import javax.persistence.Transient;
</code>```

But then the findWarranties doesn't return displayDate.

Any thoughts?

Title: Correct use of @Transient

Body:
I have a entity, something like this:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity(name = "warranties")
public class Warranty implements Comparable<Warranty> {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Column(name = "warranty_pk")
  private Long id;

  @Column(nullable = false)
  private Date startDate;

  @Column(nullable = false)
  private Date expireDate;

  @Column
  private String note;

  @Transient
  private Date displayDate;
  }
}

Notice that displayDate is annotated with @Transient.

I have two functionalities related to this entity, one is to fetch some of them, to do that I need to check expiration dates. So in my repository I have the following query:

  @Query(value =
      "SELECT "
          + "IF(expire_date < ((CURDATE() + INTERVAL 1 DAY) - INTERVAL 1 SECOND), expire_date, (expire_date - INTERVAL 90 day)) AS display_date, * "
          + "FROM warranties "
          + "WHERE expire_date < ((CURDATE() + INTERVAL 1 DAY) - INTERVAL 1 SECOND) + INTERVAL 90 DAY "
          + "AND expire_date <= :expire_date "
          + "AND start_date >= :startDate "
          + "AND expire_date <= :endDate + INTERVAL 90 DAY "
          + "ORDER BY display_date DESC",
      nativeQuery = true)
  List<Warranty> findWarranties(@Param("expire_date") Date expireDate,
      @Param("startDate") Date startDate, @Param("endDate") Date endDate);

Its that way so I can retrieve the "displayDate" calculated by the database.

It works fine when I use the following import:

import org.springframework.data.annotation.Transient;

And the other functionality is a save, where I save a given note.

For that case I get the following error:

Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'warranty0_.display_date' in 'field list'

If I use the following import, the second functionality works fine:

import javax.persistence.Transient;

But then the findWarranties doesn't return displayDate.

Any thoughts?


问:
Google Console OAuth Localhost
Is there a way to add http://somesite:8080 in order to use google's oauth on localhost?
I see that for example http://localhost:8080 is allowed.
I get this error:

```<code>Invalid Origin: This app has a publishing status of "In production". URI must use https:// as the scheme.
</code>```

Title: Google Console OAuth Localhost

Body:
Is there a way to add http://somesite:8080 in order to use google's oauth on localhost?
I see that for example http://localhost:8080 is allowed.
I get this error:

Invalid Origin: This app has a publishing status of "In production". URI must use https:// as the scheme.


问:
Hiding null output
I am trying to make an ioslides presentation with the scatter graphs on one slide. However I am getting these null outputs and they are pushing the scatter graphs off of my slides.

My code and the null outputs:

I have sliced all rows with na values as I thought that may be the problem but it didn't work. I also used the is.null function and all three datasets came back false. I just want to hide the null output.

Title: Hiding null output


问:
MongoDB slice behavior on array within an array within $addFields
I have the following mongo pipeline:

```<code>  {
    '$lookup': {
      'from': 'zones',
      'localField': 'zones.zoneID',
      'foreignField': 'zoneID',
      'as': 'zone'
    }
  }, {
    '$addFields': {
      'zone.assistantZoneContacts': {
        '$slice': [
          {
            '$ifNull': [
              '$zone.zoneContacts', [
                {
                  'userID': null
                }
              ]
            ]
          }, 1, 100
        ]
      }
    }
  }, {
    '$addFields': {
      'cz': {
        '$size': [
          '$zone.assistantZoneContacts'
        ]
      }
    }
  }
]
</code>```

Where the top level 'zones' property is an array of { zoneID: the zone id }. The lookup of the zone works fine, but the $addFields does not appear to return any data (i.e. the zone.assistantZoneContacts is always an empty array) although the cz value always shows a value of 1.

When I run the same $addFields expression on the the 'zones' collection directly (i.e. the collection that was used as the target for the lookup), it works without a problem.

$unwind'ing is not an option, because I want a single top level document (not multiple if there is more than one zone and/or zone contact). It is being used simply as a filter for the top level document.

Is this possible without resorting to more programmatic approaches (i.e. filtering through the data brought down to the app server)? I would prefer to handle this completely through MQL.

An example of what a fragment of the document in the collection may look like is:

```<code>{
   ...
   zones: [
     {
       zoneID: 1,
     }
   ]
   ...
}
</code>```

The corresponding zones collection would have the following content:

```<code>{
   zoneID: 1,
   ...
   zoneContacts: [
     {
       userID: X
     },
     {
       userID: y
     }
   ]
   ...
}
</code>```

Body:
I have the following mongo pipeline:

  {
    '$lookup': {
      'from': 'zones',
      'localField': 'zones.zoneID',
      'foreignField': 'zoneID',
      'as': 'zone'
    }
  }, {
    '$addFields': {
      'zone.assistantZoneContacts': {
        '$slice': [
          {
            '$ifNull': [
              '$zone.zoneContacts', [
                {
                  'userID': null
                }
              ]
            ]
          }, 1, 100
        ]
      }
    }
  }, {
    '$addFields': {
      'cz': {
        '$size': [
          '$zone.assistantZoneContacts'
        ]
      }
    }
  }
]

Where the top level 'zones' property is an array of { zoneID: the zone id }. The lookup of the zone works fine, but the $addFields does not appear to return any data (i.e. the zone.assistantZoneContacts is always an empty array) although the cz value always shows a value of 1.

When I run the same $addFields expression on the the 'zones' collection directly (i.e. the collection that was used as the target for the lookup), it works without a problem.

$unwind'ing is not an option, because I want a single top level document (not multiple if there is more than one zone and/or zone contact). It is being used simply as a filter for the top level document.

Is this possible without resorting to more programmatic approaches (i.e. filtering through the data brought down to the app server)? I would prefer to handle this completely through MQL.

An example of what a fragment of the document in the collection may look like is:

{
   ...
   zones: [
     {
       zoneID: 1,
     }
   ]
   ...
}

The corresponding zones collection would have the following content:

{
   zoneID: 1,
   ...
   zoneContacts: [
     {
       userID: X
     },
     {
       userID: y
     }
   ]
   ...
}


问:
Resize nifti images within R/oro.nifti
I struggle within R using package oro.nifti to resize loaded nifti images. The loaded images have different depths (z-axis), and now I want to resize the entire images to a specific input shape like (512, 512, 224). Any ideas how to resize nifti images in R?

Thanks in advance!

Title: Resize nifti images within R/oro.nifti


问:
ValueError: source code string cannot contain null bytes when importing a package in python
```<code>from pyModbusTCP.client import ModbusClient
</code>```

I am using pycharm and I have a class file which uses methods from pyModbusTCP package to communicate with devices over modbus. This class files exists as part of a directory in my project, where under the project folder I have a folder for device1 containing that particular class file along with some others. The idea was to simply duplicate the folder and title it device2, the intent being device2 functions as a backup to device1.

I created a device2 folder, made a main.py and copied most of the other contents from device1. The console is giving me only the error from the title at line 1, meaning the very first import statement that I linked is the cause for me receiving the error from the title. Given all that I have no idea what the error is even referring to, could anyone help me troubleshoot? Thanks!

EDIT:

```<code>Traceback (most recent call last):
  File "/home/env1/Simulation/main.py", line 11, in <module>
    import read_from_modbus
  File "/home/env1/Simulation/read_from_modbus.py", line 1, in <module>
    from pyModbusTCP.client import ModbusClient
ValueError: source code string cannot contain null bytes

</code>```

Body:
from pyModbusTCP.client import ModbusClient

I am using pycharm and I have a class file which uses methods from pyModbusTCP package to communicate with devices over modbus. This class files exists as part of a directory in my project, where under the project folder I have a folder for device1 containing that particular class file along with some others. The idea was to simply duplicate the folder and title it device2, the intent being device2 functions as a backup to device1.

I created a device2 folder, made a main.py and copied most of the other contents from device1. The console is giving me only the error from the title at line 1, meaning the very first import statement that I linked is the cause for me receiving the error from the title. Given all that I have no idea what the error is even referring to, could anyone help me troubleshoot? Thanks!

EDIT:

Traceback (most recent call last):
  File "/home/env1/Simulation/main.py", line 11, in <module>
    import read_from_modbus
  File "/home/env1/Simulation/read_from_modbus.py", line 1, in <module>
    from pyModbusTCP.client import ModbusClient
ValueError: source code string cannot contain null bytes