问:
docker exec command not running on docker container
I am trying to run a zip command from my local machine onto a running docker container but it seems to run the zip command on my host machine and not on the container.

Command: docker exec CONTAINER zip -r /root/python.zip *

答:
This should work:

```<code>docker exec -it CONTAINER /bin/bash -c "zip -r /root/python.zip *"
</code>```

OR

```<code>docker exec -it CONTAINER /bin/sh -c "zip -r /root/python.zip *"
</code>```

Body:
This should work:

docker exec -it CONTAINER /bin/bash -c "zip -r /root/python.zip *"

OR

docker exec -it CONTAINER /bin/sh -c "zip -r /root/python.zip *"


来源: stackexchange

问:
Objective-C and sqlite's DATETIME type
I have a sqlite3 table that I'm trying to map to an object in objective-C. One attribute of the table is 'completed_at' which is stored as a DATETIME.

I want to create a property on my objective-C class (which inherits from NSObject) that will map well to the 'completed_at' attribute.

Objective-C has an NSDate type but I'm not sure if that will map directly?

答:
I am sharing here just the core things regarding date formatting for saving and retrieving the data for presentation. If you have any problem with this code snippet then I will share the full code that I used for my project.

When you save your data, bind your date value in the sql statement like this way:

```<code>    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString=[dateFormat stringFromDate:[NSDate date]];

    sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);
</code>```

and when you retrieve data you have to write this code:

```<code>    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];
</code>```

now you have a variable myDate of NSDate type which you can render in your way:

```<code>    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
    NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);
</code>```

You must have to remember three things:

In your SQLite date field type should be DATETIME

Date format should be same when you store and when you retrieve

Now you can show in your own way but following the format. Below the format details is given.

Format:

```<code>   'dd' = Day 01-31
   'MM' = Month 01-12
   'yyyy' = Year 2000
   'HH' = Hour in 24 hour
   'hh' = Hour in 12 hour
   'mm' = Minute 00-59
   'ss' = Second 00-59
   'a' = AM / PM
</code>```

ContentLicense: CC BY-SA 2.5

Title: Objective-C and sqlite's DATETIME type

LastEditorDisplayName: Ned Batchelder

Body:
I am sharing here just the core things regarding date formatting for saving and retrieving the data for presentation. If you have any problem with this code snippet then I will share the full code that I used for my project.

When you save your data, bind your date value in the sql statement like this way:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateString=[dateFormat stringFromDate:[NSDate date]];

    sqlite3_bind_text(saveStmt, 1, [dateString UTF8String] , -1, SQLITE_TRANSIENT);

and when you retrieve data you have to write this code:

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *myDate =[dateFormat dateFromString:[NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]];

now you have a variable myDate of NSDate type which you can render in your way:

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy hh:mm:ss a"];
    NSLog(@"My Date was : %@", [formatter stringFromDate:myDate]);

You must have to remember three things:

In your SQLite date field type should be DATETIME

Date format should be same when you store and when you retrieve

Now you can show in your own way but following the format. Below the format details is given.

Format:

   'dd' = Day 01-31
   'MM' = Month 01-12
   'yyyy' = Year 2000
   'HH' = Hour in 24 hour
   'hh' = Hour in 12 hour
   'mm' = Minute 00-59
   'ss' = Second 00-59
   'a' = AM / PM

ContentLicense: CC BY-SA 3.0


问:
How to add the optimum threshold to the ROC curve plot in R
I got this example below and wondering how to get the optimal threshold (Youden's index = sensitivity+specificity-1) for each method and plot that value on the ROC curve to know the coordinate obtained from that optimal threshold. How to do that? My real ROC curves consist of 4 roc curves (see the example below) for four different methods and I want to plot the optimum threshold for each method on each corresponding method. For simplicity, I use the example below instead.

```<code>library(ROCR)
data(ROCR.simple)
df <- data.frame(ROCR.simple)
pred <- prediction(df$predictions, df$labels)
perf <- performance(pred,"tpr","for")
plot(perf,colorize=FALSE)
</code>```

This is an example of my ROC curve.

答:
You can do that easily with the pROC package (disclaimer: I am the author and maintainer of this package). Setting the print.thres

```<code>library(pROC)
my_curve <- roc(df$predictions, df$labels)
plot(my_curve, print.thres=TRUE)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I got this example below and wondering how to get the optimal threshold (Youden's index = sensitivity+specificity-1) for each method and plot that value on the ROC curve to know the coordinate obtained from that optimal threshold. How to do that? My real ROC curves consist of 4 roc curves (see the example below) for four different methods and I want to plot the optimum threshold for each method on each corresponding method. For simplicity, I use the example below instead.

library(ROCR)
data(ROCR.simple)
df <- data.frame(ROCR.simple)
pred <- prediction(df$predictions, df$labels)
perf <- performance(pred,"tpr","for")
plot(perf,colorize=FALSE)

This is an example of my ROC curve.

Body:
You can do that easily with the pROC package (disclaimer: I am the author and maintainer of this package). Setting the print.thres

library(pROC)
my_curve <- roc(df$predictions, df$labels)
plot(my_curve, print.thres=TRUE)


问:
Discord.py How can I create a channel with the nickname of user who clicked the emoji in message?
```<code>    self.ticket_creator = user_id

    message = await channel.fetch_message(message_id)
    await message.remove_reaction("",user)

ticket_nr = random.randint(100,999)
self.channel_ticket = await category.create_text_channel(f'bilet-{ticket_nr}',
overwrites=overwrites)
</code>```

Here, when a user clicks on the emoji, it deletes the emoji and creates a text channel whose title consists of random numbers.How can i make the discord nickname of user who clicked the emoji instead of these random numbers ?

答: Change self.channel_ticket = await category.create_text_channel(f'bilet-{ticket_nr}',  overwrites=overwrites) to self.channel_ticket = await category.create_text_channel(user.name,  overwrites=overwrites). This should do what you want.

Body:
    self.ticket_creator = user_id

    message = await channel.fetch_message(message_id)
    await message.remove_reaction("",user)

ticket_nr = random.randint(100,999)
self.channel_ticket = await category.create_text_channel(f'bilet-{ticket_nr}',
overwrites=overwrites)

Here, when a user clicks on the emoji, it deletes the emoji and creates a text channel whose title consists of random numbers.How can i make the discord nickname of user who clicked the emoji instead of these random numbers ?


问:
Trying to access an internal page from browser which doesn't have a url format ex: chrome://settings
I am trying to analyze the html of chrome://settings and create a pop out window with toggled settings as a floating sidebar. I can't seem to link to chrome://settings because its not in URL format I have tried using requests , selenium , and beautiful soup.

How should I go about accessing the html documents from an internal page such as chrome://settings

答:
You need to pass chrome://settings as the url: str through get()as an argument as follows:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('chrome://settings')
</code>```

Browser Snapshot:

Body:
You need to pass chrome://settings as the url: str through get()as an argument as follows:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

options = Options()
options.add_argument("start-maximized")
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
driver.get('chrome://settings')

Browser Snapshot:


问:
Why am i not able to click on open icon in Jmeter?
Below is the error i get,while clicking on open icon:</p>
```<code>2021-05-20 12:11:25,651 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[AWT-EventQueue-0,6,main]
java.lang.IllegalAccessError: class com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel (in unnamed module @0x21507a04) cannot access class sun.awt.shell.ShellFolder (in module java.desktop) because module java.desktop does not export sun.awt.shell to unnamed module @0x21507a04
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel.updateColumnInfo(DarkFilePaneUIBridge.java:1128) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel.<init>(DarkFilePaneUIBridge.java:1115) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.getDetailsTableModel(DarkFilePaneUIBridge.java:576) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$SortableListModel.<init>(DarkFilePaneUIBridge.java:1079) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePane.createList(DarkFilePane.java:137) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFileChooserUIBridge.createList(DarkFileChooserUIBridge.java:585) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFileChooserUIBridge$MetalFileChooserUIAccessor.createList(DarkFileChooserUIBridge.java:750) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.setViewType(DarkFilePaneUIBridge.java:376) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.propertyChange(DarkFilePaneUIBridge.java:890) ~[darklaf-core-2.5.4.jar:2.5.4]
    at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:342) ~[?:?]
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:334) ~[?:?]
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:267) ~[?:?]
    at java.awt.Component.firePropertyChange(Component.java:8713) ~[?:?]
    at javax.swing.JComponent.setUI(JComponent.java:688) ~[?:?]
    at javax.swing.JFileChooser.updateUI(JFileChooser.java:1838) ~[?:?]
    at javax.swing.JFileChooser.setup(JFileChooser.java:395) ~[?:?]
    at javax.swing.JFileChooser.<init>(JFileChooser.java:361) ~[?:?]
    at javax.swing.JFileChooser.<init>(JFileChooser.java:308) ~[?:?]
    at org.apache.jmeter.gui.util.FileDialoger.<clinit>(FileDialoger.java:42) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.Load.doActionAfterCheck(Load.java:75) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.AbstractActionWithNoRunningTest.doAction(AbstractActionWithNoRunningTest.java:44) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:87) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:69) ~[ApacheJMeter_core.jar:5.4.1]
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:316) ~[?:?]
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770) ~[?:?]
    at java.awt.EventQueue$4.run(EventQueue.java:721) ~[?:?]
    at java.awt.EventQueue$4.run(EventQueue.java:715) ~[?:?]
    at java.security.AccessController.doPrivileged(AccessController.java:391) ~[?:?]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) ~[?:?]
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:740) ~[?:?]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) [?:?]
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) [?:?]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) [?:?]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) [?:?]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:?]
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) [?:?]
</code>```

答:
I was able to open jmetter on Windows in the following way:

Open cmd shell of windows.

Go to path where bin directory of jmetter is. Path example:

C:\Users\xxxx\Documents\PROYECTOS\apache-jmeter-5.4.3\bin

Write jmeter word and click Enter.

Note: Jmetter will open automatically.

Click on: > Options -> Look and Feel -> Windows Classic (Example)

Picture

Restart jmetter and then repeat 1, 2 and 3 steps.

Body:
Below is the error i get,while clicking on open icon:

2021-05-20 12:11:25,651 ERROR o.a.j.JMeter: Uncaught exception in thread Thread[AWT-EventQueue-0,6,main]
java.lang.IllegalAccessError: class com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel (in unnamed module @0x21507a04) cannot access class sun.awt.shell.ShellFolder (in module java.desktop) because module java.desktop does not export sun.awt.shell to unnamed module @0x21507a04
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel.updateColumnInfo(DarkFilePaneUIBridge.java:1128) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$DetailsTableModel.<init>(DarkFilePaneUIBridge.java:1115) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.getDetailsTableModel(DarkFilePaneUIBridge.java:576) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge$SortableListModel.<init>(DarkFilePaneUIBridge.java:1079) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePane.createList(DarkFilePane.java:137) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFileChooserUIBridge.createList(DarkFileChooserUIBridge.java:585) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFileChooserUIBridge$MetalFileChooserUIAccessor.createList(DarkFileChooserUIBridge.java:750) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.setViewType(DarkFilePaneUIBridge.java:376) ~[darklaf-core-2.5.4.jar:2.5.4]
    at com.github.weisj.darklaf.ui.filechooser.DarkFilePaneUIBridge.propertyChange(DarkFilePaneUIBridge.java:890) ~[darklaf-core-2.5.4.jar:2.5.4]
    at java.beans.PropertyChangeSupport.fire(PropertyChangeSupport.java:342) ~[?:?]
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:334) ~[?:?]
    at java.beans.PropertyChangeSupport.firePropertyChange(PropertyChangeSupport.java:267) ~[?:?]
    at java.awt.Component.firePropertyChange(Component.java:8713) ~[?:?]
    at javax.swing.JComponent.setUI(JComponent.java:688) ~[?:?]
    at javax.swing.JFileChooser.updateUI(JFileChooser.java:1838) ~[?:?]
    at javax.swing.JFileChooser.setup(JFileChooser.java:395) ~[?:?]
    at javax.swing.JFileChooser.<init>(JFileChooser.java:361) ~[?:?]
    at javax.swing.JFileChooser.<init>(JFileChooser.java:308) ~[?:?]
    at org.apache.jmeter.gui.util.FileDialoger.<clinit>(FileDialoger.java:42) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.Load.doActionAfterCheck(Load.java:75) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.AbstractActionWithNoRunningTest.doAction(AbstractActionWithNoRunningTest.java:44) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.ActionRouter.performAction(ActionRouter.java:87) ~[ApacheJMeter_core.jar:5.4.1]
    at org.apache.jmeter.gui.action.ActionRouter.lambda$actionPerformed$0(ActionRouter.java:69) ~[ApacheJMeter_core.jar:5.4.1]
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:316) ~[?:?]
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770) ~[?:?]
    at java.awt.EventQueue$4.run(EventQueue.java:721) ~[?:?]
    at java.awt.EventQueue$4.run(EventQueue.java:715) ~[?:?]
    at java.security.AccessController.doPrivileged(AccessController.java:391) ~[?:?]
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85) ~[?:?]
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:740) ~[?:?]
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203) [?:?]
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124) [?:?]
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113) [?:?]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109) [?:?]
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) [?:?]
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:90) [?:?]


问:
Get default browser settings like TimeZone, Dateformat, timeFormat and language using javascript
How we can get all of the default browser/system/country settings using javascript or any other js library?

Like what is the default timezone format of the browser?
(UTC+05:30 or UTC+01:00, etc)

What is the default Date format according to timezone? ('DD/MM/YYYY' or
'MM/DD/YYYY' or 'YYYY/MM/DD')

What is the default Time format according to a browser? ('AM/PM' or '24 Hour')

Default language of browser?

If we do navigator.language using javascript we get "en-GB" but can we get a full form? like English, Spanish, Sweedish or etc

Default temperature unit? (Celsius or Fahrenheit)

答:
Like what is the default timezone format of the browser? (UTC+05:30 or UTC+01:00, etc)

Timezone is a preference, there is no default. Be careful about what you assume

To get the timezone offset, which is the number of minutes you need to subtract from UTC, use the following. This will usually be a negative number for users in Asia and Australia, and usually a positive number for users in the Americas.

```<code>new Date().getTimezoneOffset()
</code>```

If you want to know the timezone, you can get it with

Intl.DateTimeFormat().resolvedOptions().timeZone
// => "Atlantic/Reykjavik"
// => "Americas/New_York"
// => "Asia/Shanghai"
```

Be careful if you translate this to a 3 character abbreviation. "Americas/New_York" could be "EST" or "EDT" depending on the time of year. "CST" could be China standard time, or Cuba standard time, or Central Australia standard time, or Central America standard time.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl

Body:
Like what is the default timezone format of the browser? (UTC+05:30 or UTC+01:00, etc)

Timezone is a preference, there is no default. Be careful about what you assume

To get the timezone offset, which is the number of minutes you need to subtract from UTC, use the following. This will usually be a negative number for users in Asia and Australia, and usually a positive number for users in the Americas.

new Date().getTimezoneOffset()

If you want to know the timezone, you can get it with

Intl.DateTimeFormat().resolvedOptions().timeZone
// => "Atlantic/Reykjavik"
// => "Americas/New_York"
// => "Asia/Shanghai"

Be careful if you translate this to a 3 character abbreviation. "Americas/New_York" could be "EST" or "EDT" depending on the time of year. "CST" could be China standard time, or Cuba standard time, or Central Australia standard time, or Central America standard time.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl


问:
Axios put method doesn't send data in vuejs application
When I use axios.put method it doesn't work and there is no data is sent to the backend, in the same time when I change the axios.put method to axios.post it works well, what is the wrong? is there any mistake in the code below?

1- update component:

```<code><template>
  <Form @submit="update" enctype="multipart/form-data">
    <Field type="hidden" name="_token" :value="category.csrf" />
    <Field type="hidden" name="_method" value="put" />
    <div class="form-group pb-2">
      <label for="title">title</label>
      <Field
        type="text"
        class="form-control bordered"
        id="title"
        placeholder="Enter title"
        name="title"
        v-model="category.title"
        :validateOnInput="true"
        :rules="validateTitle"
      />
      <ErrorMessage name="title" />
    </div>
    <div class="form-group pb-2">
      <label for="photo">photo</label>
      <Field
        type="file"
        class="form-control"
        id="photo"
        name="photo"
        accept="image/jpeg ,image/jpg , image/png "
        @change="atFileChange"
        :validateOnInput="true"
      />
    </div>
    <button type="submit" class="btn btn-success">Update</button>
  </Form>
</template>

<script>
import { Form, Field, ErrorMessage } from "vee-validate";
import { mapActions } from "vuex";
export default {
  components: {
    Form,
    Field,
    ErrorMessage,
  },
  props: ["category"],

  methods: {
    ...mapActions(["updateCategory"]),
    atFileChange(event) {
      this.category.photo = event.target.files[0];
    },
    update() {
      //send form data to api
      const data = new FormData();
      data.append("title", this.category.title);
      data.append("photo", this.category.photo);
      data.append(
        "_token",
        document
          .querySelector('meta[name="csrf-token"]')
          .getAttribute("content")
      );
      data.append("_method", "PUT");
      const categoryId = this.category.id;
      // This is a Vuex action which commit the the update mutation
      this.updateCategory({ data: data, id: categoryId });

  },
};
</script>
</code>```

2- Vuex update action method:

```<code>    updateCategory(context, category) {
        context.commit('updateCategory', category);
    }
</code>```

3- Vuex update mutation method:

```<code>    updateCategory(state, category) {
        axios.put('api/categories/' + category.id + '/update',
        category.data);
    },
</code>```

4- Backend controller update method:

```<code>public function update(CategoryRequest $request, $id)
    {
        try {
            $category = Category::find($id);

            // 1- Start uploading file
            $path = "";
            if ($request->has('photo') && $request->photo != null &&
                getType($request->photo) !== 'string') {
                $folder = 'categories';
                $file = $request->photo;
                $file->store('/', $folder);
                $filename = $file->hashName();
                $path = 'images/' . $folder . '/' . $filename;
            }
            // End uploading file

            // 2- start Creating Slug
            $slug = str_replace(' ', '-', $request->title);
            // End Creating Slug

            // 3- Start Updating category

            $category->title = $request->title;
            $category->slug = $slug;
            $category->photo = $path;
            $category->save();
            // End Updating category

            return response()->json(['message' => 'Category Updated Successfully'], 200);
         } catch (\Exception $exp) {
            return response()->json(['message' => 'error on Updating Category'], 422);
       }
    }
</code>```

答:
Your api route is incorrect. It should be</p>
```<code>axios.put(`/api/categories/${category.data.id}`, category.data);
</code>```
```<code>Route::group(['middleware' => 'auth:sanctum'], function () {
    Route::apiResources([
        'categories' => 'App\Http\Controllers\API\CategoryController',
    ]);
});
</code>```

Body:
When I use axios.put method it doesn't work and there is no data is sent to the backend, in the same time when I change the axios.put method to axios.post it works well, what is the wrong? is there any mistake in the code below?

1- update component:

<template>
  <Form @submit="update" enctype="multipart/form-data">
    <Field type="hidden" name="_token" :value="category.csrf" />
    <Field type="hidden" name="_method" value="put" />

      title
      <Field
        type="text"
        class="form-control bordered"
        id="title"
        placeholder="Enter title"
        name="title"
        v-model="category.title"
        :validateOnInput="true"
        :rules="validateTitle"
      />
      <ErrorMessage name="title" />

      photo
      <Field
        type="file"
        class="form-control"
        id="photo"
        name="photo"
        accept="image/jpeg ,image/jpg , image/png "
        @change="atFileChange"
        :validateOnInput="true"
      />

    <button type="submit" class="btn btn-success">Update</button>
  </Form>
</template>

2- Vuex update action method:

    updateCategory(context, category) {
        context.commit('updateCategory', category);
    }

3- Vuex update mutation method:

    updateCategory(state, category) {
        axios.put('api/categories/' + category.id + '/update',
        category.data);
    },

4- Backend controller update method:

public function update(CategoryRequest $request, $id)
    {
        try {
            $category = Category::find($id);

            // 1- Start uploading file
            $path = "";
            if ($request->has('photo') && $request->photo != null &&
                getType($request->photo) !== 'string') {
                $folder = 'categories';
                $file = $request->photo;
                $file->store('/', $folder);
                $filename = $file->hashName();
                $path = 'images/' . $folder . '/' . $filename;
            }
            // End uploading file

            // 2- start Creating Slug
            $slug = str_replace(' ', '-', $request->title);
            // End Creating Slug

            // 3- Start Updating category

            $category->title = $request->title;
            $category->slug = $slug;
            $category->photo = $path;
            $category->save();
            // End Updating category

            return response()->json(['message' => 'Category Updated Successfully'], 200);
         } catch (\Exception $exp) {
            return response()->json(['message' => 'error on Updating Category'], 422);
       }
    }

Body:
Your api route is incorrect. It should be

axios.put(`/api/categories/${category.data.id}`, category.data);

Route::group(['middleware' => 'auth:sanctum'], function () {
    Route::apiResources([
        'categories' => 'App\Http\Controllers\API\CategoryController',
    ]);
});


问:
How does variable assignment works in ruby?

Ruby version: ruby 2.6.7p197 (2021-04-05 revision 67941) [x86_64-linux]

Rails gem version: 6.0.1

Simple question, I have this example on rails console

As expected, if I try to call a non existent variable, I got an error

irb(main):007:0> value
# Traceback (most recent call last):
#         2: from (irb):7
#        1: from (irb):7:in `rescue in irb_binding'
# NameError (undefined local variable or method `value' for main:Object)
```
<p>But if I try to do the following example</p>
<pre class="lang-rb prettyprint-override"><code>(value = 1) if value.present?
</code>```

It returns nil for some reason, the first scenario this happenned there was no parenthesis, I thought it was defining the variable and then returning a value of nil, but then I tried with it and just happened again (I tried other variable because ruby counted that as a defined variable)

OBS: I tried the same scenario on raw irb and it raised me an error, <s>this only happens on rails console</s>

EDIT: It only raised an error because I didn't realized that '.present?' is a rails method, but if I change my syntax to

(value = 1) if value
```

the same behaviour happens

Why does that happen? Shouldn't a NameError be raised?

答:
Ruby works such way, please look the docs

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

```<code>a = 0 if false # does not assign to a

p local_variables # prints [:a]

p a # prints nil
</code>```

And other interesting thing:

Another commonly confusing case is when using a modifier if:

```<code>p a if a = 0.zero?
</code>```

Rather than printing “true” you receive a NameError, “undefined local variable or method 'a'”. Since ruby parses the bare a left of the if first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a and will assume you are referencing a local method.

The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to call a nonexistent method.

So you can

Body:
Ruby version: ruby 2.6.7p197 (2021-04-05 revision 67941) [x86_64-linux]

Rails gem version: 6.0.1

Simple question, I have this example on rails console

As expected, if I try to call a non existent variable, I got an error

irb(main):007:0> value
# Traceback (most recent call last):
#         2: from (irb):7
#        1: from (irb):7:in `rescue in irb_binding'
# NameError (undefined local variable or method `value' for main:Object)

But if I try to do the following example

(value = 1) if value.present?

It returns nil for some reason, the first scenario this happenned there was no parenthesis, I thought it was defining the variable and then returning a value of nil, but then I tried with it and just happened again (I tried other variable because ruby counted that as a defined variable)

OBS: I tried the same scenario on raw irb and it raised me an error, <s>this only happens on rails console</s>

EDIT: It only raised an error because I didn't realized that '.present?' is a rails method, but if I change my syntax to

(value = 1) if value

the same behaviour happens

Why does that happen? Shouldn't a NameError be raised?

Body:
Ruby works such way, please look the docs

The local variable is created when the parser encounters the assignment, not when the assignment occurs:

a = 0 if false # does not assign to a

p local_variables # prints [:a]

p a # prints nil

And other interesting thing:

Another commonly confusing case is when using a modifier if:

p a if a = 0.zero?

Rather than printing “true” you receive a NameError, “undefined local variable or method 'a'”. Since ruby parses the bare a left of the if first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a and will assume you are referencing a local method.

The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to call a nonexistent method.

So you can


问:
Removing conjunctions from a .txt file using words in an array
I was trying to remove conjunctions and punctuations from a txt file. Punctuations are removed successfully but some conjunctions remained. Here is my code:

```<code>public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string words = File.ReadAllText(@"C:\Users\...\Desktop\data_protection_law.txt").ToLower(new CultureInfo("en-US", false));

            string[] punctuation = { ".", "!", "?", "–", "-", "-", "/", "_", ",", ";", ":", "(", ")", "[", "]", "“", "”", "\"", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            string[] con_art = { "the", "a", "an", "for", "and", "or", "nor", "but", "yet", "so", "of", "to", "in", "are", "is", "on", "be", "by", "we", "he", "that", "he", "that", "because", "as", "it", "about", "were", "i", "our", "they", "with", "these", "there", "then", "them" };

            foreach (string s in punctuation)
            {
                words = words.Replace(s, "");
            }

            foreach (string s in con_art)
            {
                words = words.Replace(" " + s + " ", " ");
            }

            richTextBox1.Text = words;
        }

    }
</code>```

I printed the words in richTextBox just to be sure. When I checked the original text, I found that some conjunctions were deleted but not all.
Here is the proof of the remaining conjunctions

Original Text File

I'm going crazy, I've been trying to find the mistake myself for days, but I couldn't find it.

So where is my mistake in this code?
Btw I'm just a beginner so don't be angry if I made a big mistake :)

答:
because sometimes the word is not surrounded by spaces on both sides.

The ones you fail to replace are all at the beginning or end of line, this means that have a newline not a space

Body:
I was trying to remove conjunctions and punctuations from a txt file. Punctuations are removed successfully but some conjunctions remained. Here is my code:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string words = File.ReadAllText(@"C:\Users\...\Desktop\data_protection_law.txt").ToLower(new CultureInfo("en-US", false));

            string[] punctuation = { ".", "!", "?", "–", "-", "-", "/", "_", ",", ";", ":", "(", ")", "[", "]", "“", "”", "\"", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            string[] con_art = { "the", "a", "an", "for", "and", "or", "nor", "but", "yet", "so", "of", "to", "in", "are", "is", "on", "be", "by", "we", "he", "that", "he", "that", "because", "as", "it", "about", "were", "i", "our", "they", "with", "these", "there", "then", "them" };

            foreach (string s in punctuation)
            {
                words = words.Replace(s, "");
            }

            foreach (string s in con_art)
            {
                words = words.Replace(" " + s + " ", " ");
            }

            richTextBox1.Text = words;
        }

    }

I printed the words in richTextBox just to be sure. When I checked the original text, I found that some conjunctions were deleted but not all.
Here is the proof of the remaining conjunctions

Original Text File

I'm going crazy, I've been trying to find the mistake myself for days, but I couldn't find it.

So where is my mistake in this code?
Btw I'm just a beginner so don't be angry if I made a big mistake :)


问:
recommend a Flash MP3 player supporting starting playing from a specific time
I need a Flash player which can start my mp3 file from a specific time based on the embedding properties or on URL or just anything. </p>

答:
Try this, it should work
Flash player with JS support

use method

```<code>method:setPosition
</code>```

on event

```<code>onInit
</code>```

Body:
Try this, it should work
Flash player with JS support

use method

method:setPosition

on event

onInit


问:
Using a custom UUID when connecting an Android phone and a Raspberry Pi through bluetooth
I created a custom app to connect via bluetooth to my Raspberry Pi. All it does is it scans for bluetooth devices and connects to them through an RFCOMM socket.

As per this Android documentation I have the following code when creating the socket on my app, by using the well-known SPP UUID.

val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
device.createRfcommSocketToServiceRecord(uuid)
```

Everything works great!

The thing is, I would like it if only those using my app (i.e. those who have been authenticated by me) could connect to my Raspberry Pi.

Is it possible to set a custom UUID for the Raspberry's RFCOMM server?

EDIT:

I've made some progress by using this example code from the pybluez module. However, what happens now is that I can establish a connection by using two different UUIDs, the one I set on the python script and the default well-known SPP UUID.

How could I make it so that it works exclusively with the one I set?

答:
I have once again answered my own question. I am glad it didn't take me too long this time.

I was running sdptool add SP as part of my bluetooth setup process on my Raspberry Pi, I had seen that command as a recommendation on multiple different threads. It's interesting because the expected UUID does not get overriden, it just waits for either of them on the same RFCOMM channel.

Anyways, avoid using that command if you are trying to establish a bluetooth connection using your own UUID.

Body:
I created a custom app to connect via bluetooth to my Raspberry Pi. All it does is it scans for bluetooth devices and connects to them through an RFCOMM socket.

As per this Android documentation I have the following code when creating the socket on my app, by using the well-known SPP UUID.

val uuid: UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb")
device.createRfcommSocketToServiceRecord(uuid)

Everything works great!

The thing is, I would like it if only those using my app (i.e. those who have been authenticated by me) could connect to my Raspberry Pi.

Is it possible to set a custom UUID for the Raspberry's RFCOMM server?

EDIT:

I've made some progress by using this example code from the pybluez module. However, what happens now is that I can establish a connection by using two different UUIDs, the one I set on the python script and the default well-known SPP UUID.

How could I make it so that it works exclusively with the one I set?


问:
Getting url on first render
I'n new to next.js

I'm trying to get the url on first render. I have a json file with allot of url's from an old website that redirects to what the url in on the new website.

So if first render url is a.mywebsite.com/hello i need to check if that url is in my redirect.json file. If a match it should redirect to fx mywebsite.com/a/hello.

I have no luck getting the first render url in my _documents.tsx or slug.tsx file. It it not possible inside the SSR with getServerSideProps?

答:
You should easily be able to get that using the context object that exposed to you.

https://nextjs.org/docs/api-reference/data-fetching/get-server-side-props#context-parameter

Seems you can either get it from context.resolvedUrl or find it inside context.req

Title: Getting url on first render


问:
converting time to local timezone not working with moment.js in React
I am converting a timestamp on a DB object using moment:

```<code>{moment(comment.created_at).local(true).format('h:mm a')}
</code>```

My time is outputting in UTC time because that is how it gets created in my DB.
So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?

My DB object

```<code>{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}
</code>```

答:
I converted your DB timestamp into ISO format and then passed into your implementation

let t = "2022-02-11 17:41:39.330443"

let utcISOTimestamp = moment.utc(t).toDate()
console.log(utcISOTimestamp)

//let res = moment(utcISOTimestamp).local(true).format('h:mm a');
let res = moment(moment.utc(t).toDate()).local(true).format('h:mm a');

console.log(res)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script></code>```

Body:
I am converting a timestamp on a DB object using moment:

{moment(comment.created_at).local(true).format('h:mm a')}

My time is outputting in UTC time because that is how it gets created in my DB.
So I am seeing '6:45 PM' for example, when I want to see the time in MY timezone (EST) or the user's relative timezone. According to the moment docs local() will convert to your current timezone? Calling the local() method as shown in my code aboven does not change the time zone. Am I using this incorrectly?

My DB object

{
  client_id: 24
  created_at: "2022-02-11 17:41:39.330443"
  id: 22
  report: "sfsf"
  report_category: "Client Assigned"
  volunteer_id: 23
}

Body:
I converted your DB timestamp into ISO format and then passed into your implementation

let t = "2022-02-11 17:41:39.330443"

let utcISOTimestamp = moment.utc(t).toDate()
console.log(utcISOTimestamp)

//let res = moment(utcISOTimestamp).local(true).format('h:mm a');
let res = moment(moment.utc(t).toDate()).local(true).format('h:mm a');

console.log(res)

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


问:
ERROR: Could not find specified Maven installation 'maven_5_6_2'
I have a Jenkinsfile (see below) which runs a number of commands. I have the 'Pipeline Maven Integration' plugin installed in my Jenkins server (I have version 3_10_0 of Pipeline Maven Integration installed in Jenkins). But when I try to run my pipeline I get the error below in the console. Am I missing something? Is the error complaining about the Jenkins Maven plugin or the version of Maven in my Java solution?

Jenkinsfile:-

```<code>pipeline {
    agent any

    stages {
        stage ('Compile Stage') {
            steps {
                withMaven(maven: 'maven_3_8_4') {
                    sh 'mvn clean install'
                }
            }
        }

        stage ('Test Stage') {
            steps {
                withMaven(maven: 'maven_3_8_4') {
                    sh 'mvn test'
                }
            }
        }
        stage ('Cucumber Reports') {
            steps {
                cucumber buildStatus: "UNSTABLE",
                fileIncludePattern: "**/cucumber-report.json",
                jsonReportDirectory: 'target'
            }
        }
    }
}
</code>```

Error in console:-

ERROR: Could not find specified Maven installation 'maven_3_10_0'.
Finished: FAILURE

Further information I have version 3.8.4 of Maven installed on the machine running the Jenkins server. I have also updated the Jenkins global tools config to reference version 3.8.4 of Maven, bit I still get the same error when running the pipeline.

答: I worked it out, the reference should have been as follows in the Jenkinsfile (as this is what is n my global tools):-

Body:
I have a Jenkinsfile (see below) which runs a number of commands. I have the 'Pipeline Maven Integration' plugin installed in my Jenkins server (I have version 3_10_0 of Pipeline Maven Integration installed in Jenkins). But when I try to run my pipeline I get the error below in the console. Am I missing something? Is the error complaining about the Jenkins Maven plugin or the version of Maven in my Java solution?

Jenkinsfile:-

pipeline {
    agent any

    stages {
        stage ('Compile Stage') {
            steps {
                withMaven(maven: 'maven_3_8_4') {
                    sh 'mvn clean install'
                }
            }
        }

        stage ('Test Stage') {
            steps {
                withMaven(maven: 'maven_3_8_4') {
                    sh 'mvn test'
                }
            }
        }
        stage ('Cucumber Reports') {
            steps {
                cucumber buildStatus: "UNSTABLE",
                fileIncludePattern: "**/cucumber-report.json",
                jsonReportDirectory: 'target'
            }
        }
    }
}

Error in console:-

ERROR: Could not find specified Maven installation 'maven_3_10_0'.
Finished: FAILURE

Further information I have version 3.8.4 of Maven installed on the machine running the Jenkins server. I have also updated the Jenkins global tools config to reference version 3.8.4 of Maven, bit I still get the same error when running the pipeline.


答:
Try using:</p>
```<code>moment.utc('2022-02-11 17:41:39').local().format('YYYY-MM-DD HH:mm:ss')
</code>```

Title: converting time to local timezone not working with moment.js in React

Body:
Try using:

moment.utc('2022-02-11 17:41:39').local().format('YYYY-MM-DD HH:mm:ss')


问:
Does FileInputStream incorrectly implement InputStream?
The docs for InputStream.read(bytes) say "This method blocks until input data is available, end of file is detected, or an exception is thrown."

However, java.io.FileInputStream extends java.io.InputStream
and the docs for FileInputStream.read(bytes) state no such guarantee:

```<code> * Reads up to {@code b.length} bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.
</code>```

In practice, FileInputStream can indeed return before all the input is available, so it seems both the docs and the implementation do not follow the contract of InputStream.

Is this a bug? Is it a known bug?

UPDATE: to clarify: System.in is a FileInputStream. I am seeing System.in.read(buf) return a nonzero int that is neither all of the bytes, nor -1. If I use System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) then I get all the bytes the sender is sending.

答:
It is not a contract violation, and is therefore not a bug.

The doc for InputStream specifies that it blocks until "input data is available," which is not the same thing as "all the input is available."

If you're referring to the "end of file" aspect, continue to read the Javadoc for FileInputStream.read, which specifies

the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

Body:
The docs for InputStream.read(bytes) say "This method blocks until input data is available, end of file is detected, or an exception is thrown."

However, java.io.FileInputStream extends java.io.InputStream
and the docs for FileInputStream.read(bytes) state no such guarantee:

 * Reads up to {@code b.length} bytes of data from this input
 * stream into an array of bytes. This method blocks until some input
 * is available.

In practice, FileInputStream can indeed return before all the input is available, so it seems both the docs and the implementation do not follow the contract of InputStream.

Is this a bug? Is it a known bug?

UPDATE: to clarify: System.in is a FileInputStream. I am seeing System.in.read(buf) return a nonzero int that is neither all of the bytes, nor -1. If I use System.in.readNBytes(buf, 0, theNumberOfBytesIAmExpecting) then I get all the bytes the sender is sending.


问:
SwiftUI @StateObject nested @State value not updating
I've run into an issue whilst trying to learn SwiftUI's binding and I'm struggling to understand why a @StateObject value can't be updated from its parent.

Here's what I've put together and I can open and close a SheetView successfully using it the .show enum but $isPresented still outputs as false, as if it's not being sent. $isPresented is being used inside SheetView on a button to close the SheetView from inside. How can I update isPresented from inside ContentView and inside SheetView?

```<code>class Presenter: ObservableObject {
enum Show: Equatable {
    case none, login, register
}

@Published var show: Show = .none
@State var isPresented: Bool = false

@ViewBuilder
func makeView() -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}
}

struct ContentView: View {

@StateObject var presenter = Presenter()

var body: some View {
    ZStack {
        Color("White")
        HomeView().environmentObject(presenter) // Has button which changes presenter to login via presenter.show = .login
        .overlay {
            switch presenter.show {
            case .none:
                EmptyView().onAppear {
                    presenter.isPresented.toggle() // Has no effect
                    presenter.show = .none
                }
            default:
                ZStack {
                    Color("Black").opacity(0.1).onTapGesture {
                        withAnimation(.interactiveSpring()) {
                            presenter.isPresented.toggle() // Has no effect
                            presenter.show = .none
                        }
                    }.transition(.opacity)
                }.edgesIgnoringSafeArea(.all)
            }
        }
    }.overlay {
        presenter.makeView()
    }
}

}
</code>```

To include a MRE would take around 200 lines of code, hence the abridged version above. The main issue is how do you change a @State property from inside view which is already inside the @StateObject. SheetView needs to toggle $isPresented

答:
I see at least two problems in your code.

First, SwiftUI discards EmptyView early enough in the rendering pipeline that it never “appears”. So an onAppear attached to an EmptyView will never be called. You can test it out in a playground:

```<code>import PlaygroundSupport
import SwiftUI

PlaygroundPage.current.setLiveView(VStack {
    Text("hello")
        .onAppear { print("Text onAppear") }

    EmptyView()
        .onAppear { print("EmptyView onAppear") }
}.frame(width: 300, height: 300))
</code>```

This prints Text onAppear but does not print EmptyView onAppear. In the context of the code you posted, you can replace EmptyView with Color.clear.

Second, @State only works when applied to a property of a View, a ViewModifier, a Scene, or an App. It doesn't work when applied to a property of an ObservableObject. You need to change @State var isPresented to @Published var isPresented.

But after you fix that, you won't be able to say $isPresented to get a Binding<Bool>. You could change makeView to take that Binding as an argument:

```<code>@ViewBuilder
func makeView(@Binding isPresented: Bool) -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}
</code>```

But at this point, it's probably better to move makeView into ContentView instead:

```<code>class Presenter: ObservableObject {
    enum Show: Equatable {
        case none, login, register
    }

    @Published var show: Show = .none
    @Published var isPresented: Bool = false
}

struct ContentView: View {
    @StateObject var presenter = Presenter()

    @ViewBuilder
    func makeView() -> some View {
        switch presenter.show {
        case .none:
            Color.clear.onAppear {
                presenter.isPresented.toggle()
            }
        case .login:
            // SheetView replaced with Toggle to make this compile.
            Toggle("login", isOn: $presenter.isPresented)
        case .register:
            // SheetView replaced with Toggle to make this compile.
            Toggle("register", isOn: $presenter.isPresented)
        }
    }

    // body simplified because it's not important for this example.
    var body: some View { EmptyView() }
}
</code>```

Body:
I've run into an issue whilst trying to learn SwiftUI's binding and I'm struggling to understand why a @StateObject value can't be updated from its parent.

Here's what I've put together and I can open and close a SheetView successfully using it the .show enum but $isPresented still outputs as false, as if it's not being sent. $isPresented is being used inside SheetView on a button to close the SheetView from inside. How can I update isPresented from inside ContentView and inside SheetView?

class Presenter: ObservableObject {
enum Show: Equatable {
    case none, login, register
}

@Published var show: Show = .none
@State var isPresented: Bool = false

@ViewBuilder
func makeView() -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}
}

struct ContentView: View {

@StateObject var presenter = Presenter()

var body: some View {
    ZStack {
        Color("White")
        HomeView().environmentObject(presenter) // Has button which changes presenter to login via presenter.show = .login
        .overlay {
            switch presenter.show {
            case .none:
                EmptyView().onAppear {
                    presenter.isPresented.toggle() // Has no effect
                    presenter.show = .none
                }
            default:
                ZStack {
                    Color("Black").opacity(0.1).onTapGesture {
                        withAnimation(.interactiveSpring()) {
                            presenter.isPresented.toggle() // Has no effect
                            presenter.show = .none
                        }
                    }.transition(.opacity)
                }.edgesIgnoringSafeArea(.all)
            }
        }
    }.overlay {
        presenter.makeView()
    }
}

}

To include a MRE would take around 200 lines of code, hence the abridged version above. The main issue is how do you change a @State property from inside view which is already inside the @StateObject. SheetView needs to toggle $isPresented

Body:
I see at least two problems in your code.

First, SwiftUI discards EmptyView early enough in the rendering pipeline that it never “appears”. So an onAppear attached to an EmptyView will never be called. You can test it out in a playground:

import PlaygroundSupport
import SwiftUI

PlaygroundPage.current.setLiveView(VStack {
    Text("hello")
        .onAppear { print("Text onAppear") }

    EmptyView()
        .onAppear { print("EmptyView onAppear") }
}.frame(width: 300, height: 300))

This prints Text onAppear but does not print EmptyView onAppear. In the context of the code you posted, you can replace EmptyView with Color.clear.

Second, @State only works when applied to a property of a View, a ViewModifier, a Scene, or an App. It doesn't work when applied to a property of an ObservableObject. You need to change @State var isPresented to @Published var isPresented.

But after you fix that, you won't be able to say $isPresented to get a Binding<Bool>. You could change makeView to take that Binding as an argument:

@ViewBuilder
func makeView(@Binding isPresented: Bool) -> some View {
    switch show {
    case .none:
        EmptyView().onAppear {
            isPresented.toggle()
        }
    case .login:
        SheetView(isOpen: $isPresented) { // SheetView has a button which fails to close using isPresented.toggle() or isPresented = false
            LoginView()
        }
    case .register:
        SheetView(isOpen: $isPresented) {
            RegisterView()
        }
    }
}

But at this point, it's probably better to move makeView into ContentView instead:

class Presenter: ObservableObject {
    enum Show: Equatable {
        case none, login, register
    }

    @Published var show: Show = .none
    @Published var isPresented: Bool = false
}

struct ContentView: View {
    @StateObject var presenter = Presenter()

    @ViewBuilder
    func makeView() -> some View {
        switch presenter.show {
        case .none:
            Color.clear.onAppear {
                presenter.isPresented.toggle()
            }
        case .login:
            // SheetView replaced with Toggle to make this compile.
            Toggle("login", isOn: $presenter.isPresented)
        case .register:
            // SheetView replaced with Toggle to make this compile.
            Toggle("register", isOn: $presenter.isPresented)
        }
    }

    // body simplified because it's not important for this example.
    var body: some View { EmptyView() }
}


问:
Parsing an array of string to MVC method
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

```<code>$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });
</code>```

and looks alright.
then i try to convert it to JSON

```<code>$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});
</code>```

My controller method looks as following:

```<code>public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)
</code>```

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

```<code>{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}
</code>```

}

答:
I think you are serializing one too many times, and you have one too many layers.  Try this:

I removed one of the SelectedQuantities, and change the ajax call.

```<code>$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/QuantitySummaryView/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json'
        });
    });
});
</code>```

Also, try Firebug, it will show you want was passed to the server, so you can make sure the json created and passed is correct.

Body:
Im trying to parse a simple array of guids/strings to json
the json is used as a parameter on a post call to my controller.

I have been trying a lot of different things but i simply cant make the controller method see my List.

The array is built from checkbox values:

$('input:checkbox').click(function () {
        if ($(this).attr("checked") == true) {
            selected.push($(this).val());
        }
    });

and looks alright.
then i try to convert it to JSON

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }
        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/SelectQuantities/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json',
            success: function (result) {
                debugger;
                if (result.status == 200)
                    location.replace = "/MVC/Physical/QuantitySummaryView/@Model.TopID"
                else {
                    //Handle error
                }

            }
        });
    });
});

My controller method looks as following:

public ActionResult QuantitySummaryView(Guid id, List<String> SelectedQuantities)

But the list is always null. I figured it was because the JSON list doesnt contain the array of GUIDs directly underneath it.

Can you help me get it nudged in place?

JSON (as seen by Chromes  dev tools) looks as following:

{
"SelectedQuantities": {
    "0": "707c40bd-4434-41ed-80fd-4ac541a81e85",
    "1": "a8d78a4b-b107-4e1c-97b5-5d8abf530ba8",
    "2": "a19226cc-9b22-4174-97e3-bb003d4b2746"
}

}

Body:
I think you are serializing one too many times, and you have one too many layers.  Try this:

I removed one of the SelectedQuantities, and change the ajax call.

$(document).ready(function () {
    $('#Summarize').click(function () {
        var arrayJson = {};
        for (i in selected) {
            arrayJson[i] = selected[i];
        }

        var json = {
            SelectedQuantities: arrayJson
        };

        $.ajax({
            url: "/MVC/Physical/QuantitySummaryView/@Model.TopID",
            type: "POST",
            data: JSON.stringify(json),
            dataType: "json",
            contentType: 'application/json'
        });
    });
});

Also, try Firebug, it will show you want was passed to the server, so you can make sure the json created and passed is correct.


问:
using multiple api calls, after first api others return undefined
Everyone does a weather app for api practice so I decided to do something different I'm using Pokeapi to make a small app. I have to call a few different apis to make it work how I want which is being done like this

```<code>const api = "https://pokeapi.co/api/v2/pokemon";
const apiMoves = "https://pokeapi.co/api/v2/move";
const apiSpecies = "https://pokeapi.co/api/v2/pokemon-species"

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
  }
}
function getResults(query) {
  const pokemonData = fetch(`${api}/${query}`)
  .then((data) => {
     return data.json();
  });
  pokemonData.then(displayResults)

  pokemonData.then(data => {
      return fetch(`${apiMoves}/${data.moves[0].move.name}`)
      .then(data => data.json())
      .then(move => {
          console.log(move)
      })
  })
  pokemonData.then(data => {
      return fetch(`${apiSpecies}/${query}`)
      .then(data => data.json())
      .then(species => {
          console.log(species)
      })
  })
}

</code>```

all 3 of the end points are being logged in the console so I can see them. However looking at api call 2 I'm passing info from the first api call to get more info and that logs fine. When I'm trying to display the info from that 2nd api call it just returns undefined but in the console I can see all the endpoints.

the display results looks something like this.

```<code>function displayResults(pokemon) {
  let name = document.querySelector('h2')
name.innerText = pokemon.name <-- this works.
  let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.
}

</code>```

I've tried to replace the pokemon.power with move.power but that gives an error saying "move" is not defined.

I'm thinking that I'm simply calling the 2nd and 3rd api wrong? I'm not sure and trying to search for this issue is a bit rough.

any help is appreciated!

答:
Here this line is not working because you are trying to access the attribute which does not exist in the object.

```<code>let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.

</code>```

What might work for you is:

```<code>dmg1.innerText = pokemon.moves[0].move.name

</code>```

Body:
Everyone does a weather app for api practice so I decided to do something different I'm using Pokeapi to make a small app. I have to call a few different apis to make it work how I want which is being done like this

const api = "https://pokeapi.co/api/v2/pokemon";
const apiMoves = "https://pokeapi.co/api/v2/move";
const apiSpecies = "https://pokeapi.co/api/v2/pokemon-species"

const searchBox = document.querySelector(".search-box");
searchBox.addEventListener("keypress", setQuery);

function setQuery(e) {
  if (e.keyCode == 13) {
    getResults(searchBox.value);
    searchBox.value = "";
  }
}
function getResults(query) {
  const pokemonData = fetch(`${api}/${query}`)
  .then((data) => {
     return data.json();
  });
  pokemonData.then(displayResults)

  pokemonData.then(data => {
      return fetch(`${apiMoves}/${data.moves[0].move.name}`)
      .then(data => data.json())
      .then(move => {
          console.log(move)
      })
  })
  pokemonData.then(data => {
      return fetch(`${apiSpecies}/${query}`)
      .then(data => data.json())
      .then(species => {
          console.log(species)
      })
  })
}

all 3 of the end points are being logged in the console so I can see them. However looking at api call 2 I'm passing info from the first api call to get more info and that logs fine. When I'm trying to display the info from that 2nd api call it just returns undefined but in the console I can see all the endpoints.

the display results looks something like this.

function displayResults(pokemon) {
  let name = document.querySelector('h2')
name.innerText = pokemon.name <-- this works.
  let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.
}

I've tried to replace the pokemon.power with move.power but that gives an error saying "move" is not defined.

I'm thinking that I'm simply calling the 2nd and 3rd api wrong? I'm not sure and trying to search for this issue is a bit rough.

any help is appreciated!

Body:
Here this line is not working because you are trying to access the attribute which does not exist in the object.

let dmg1 = document.querySelector('.dmg1')
dmg1.innerText = pokemon.power <-- this is returning undefined but in the console "power" shows a number.

What might work for you is:

dmg1.innerText = pokemon.moves[0].move.name


问:
How to upload an image to imgur using an image URL with python
I'm using the pyimgur module to upload to imgur. It works fine with local files but is there a way to upload to imgur using a image URL(jpg,png). I looked around but couldn't find a solid answer. Current code I'm using is this(for local images),

```<code>import pyimgur

CLIENT_ID = "<id>"
im = pyimgur.Imgur(CLIENT_ID)
image = '<local-image>'
uploaded_image = im.upload_image(image, title='title')
</code>```

Thank you

答:
```<code>import requests

img_url = 'https://my/image/url.jpg'

api = 'https://api.imgur.com/3/image'

params = dict(
    client_id='546c25a59c58ad7'
)

files = dict(
    image=(None, img_url),
    name=(None, ''),
    type=(None, 'URL'),
)

r = requests.post(api, files=files, params=params)
</code>```

Body:
I'm using the pyimgur module to upload to imgur. It works fine with local files but is there a way to upload to imgur using a image URL(jpg,png). I looked around but couldn't find a solid answer. Current code I'm using is this(for local images),

import pyimgur

CLIENT_ID = "<id>"
im = pyimgur.Imgur(CLIENT_ID)
image = '<local-image>'
uploaded_image = im.upload_image(image, title='title')

Thank you


问:
The AppLovin' nightmare in Xcode, impossible to build the project
it's been weeks that I'm blocked because I can't build my project in Xcode on iOS. I looked all over the internet, none of the suggestions worked for me. I really hope I'm not a rare exception because this problem is painful and prevents me from moving forward..

Here is a the error that i have in Xcode

"#import <AppLovinSDK/AppLovinSDK.h' file not found"

答:
Try to Build from Unity and not Build and Run:

And then open the .xworkspace file and not the .xcodeproj file:


问:
Creating a function to search for a value in an array and return it's position index using a loop
I'm very new to JavaScript.
I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not
found, it should return -1.
I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

```<code>function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}
</code>```

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

答:
Your logic is wrong here. First, you return -1 when the function fails to search the right value. Thus, the function is paused and no longer executing. You can learn more about the return statement at MDN. To solve this problem, you need to put the return statement outside the loop. Here is the working code:

```<code><script>
function getIndex(arr, value){
for(let i =0; i<arr.length; i++){
if(arr[i] === value){
return i;
}
}
return -1;
}
document.write(getIndex([1,2,3,4], 21));
</script>
</code>```

The reason why this piece of code works is because when the value is found, it returns the positions where the value is. Thus, terminates the function. But if it is not, the loop will go forever until I is less than arr.length. Once I is less than arr.length, the loop is done and the return statement is executed.

Body:
I'm very new to JavaScript.
I'm trying to create a function that can two take two arguments, an array and a value. The function should return the index where the value is found but ff the value is not
found, it should return -1.
I want to this using a loop and not a method like for example indexOf.

So this is what I got by now:

function getIndex(arr, value) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] === value) {
      return i;
    } else {
      return -1;
    }
  }
}

For some reason it keeps returning -1 even if the value if found. What am I doing wrong?

Body:
Your logic is wrong here. First, you return -1 when the function fails to search the right value. Thus, the function is paused and no longer executing. You can learn more about the return statement at MDN. To solve this problem, you need to put the return statement outside the loop. Here is the working code:

<script>
function getIndex(arr, value){
for(let i =0; i<arr.length; i++){
if(arr[i] === value){
return i;
}
}
return -1;
}
document.write(getIndex([1,2,3,4], 21));
</script>

The reason why this piece of code works is because when the value is found, it returns the positions where the value is. Thus, terminates the function. But if it is not, the loop will go forever until I is less than arr.length. Once I is less than arr.length, the loop is done and the return statement is executed.


问:
flutter video_player(or chewie) enter full screen on landscape mode like youtube
I need a video player that enters full screen when the device is rotated to landscape mode and back. Just like how the video player in apps like YouTube and Udemy. I am using chewie and there is an open issue about it in
https://github.com/brianegan/chewie/issues/15
From that, I found this solution
https://gist.github.com/ihrankouski/0a353a8de649b648b3ceff0d8e97f1d7
which has a problem that it won't come back to the normal position on portrait mode.

also, there is a file in the chewie example

https://github.com/brianegan/chewie/blob/master/example/lib/auto_rotate.dart
that does this(maybe. I don't know what the code is for) but is not working when I tried. Does this have any problem? If yes then what is the problem?

Is there another library that has this functionality,  If yes how can this be done with that library.

答:
Regarding fullscreen you can added it as a parameter to your ChewieController

```<code>_chewieController = ChewieController(
  _videoPlayerController: videoPlayerController,
  fullScreenByDefault: true);
</code>```

Regarding Orientation you can set that in the initiState()

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

  @override
  void initState() {
    super.initState();
    initializePlayer();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
    ]);
  }
</code>```

Body:
Regarding fullscreen you can added it as a parameter to your ChewieController

_chewieController = ChewieController(
  _videoPlayerController: videoPlayerController,
  fullScreenByDefault: true);

Regarding Orientation you can set that in the initiState()

import 'package:flutter/services.dart';

  @override
  void initState() {
    super.initState();
    initializePlayer();
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeRight,
    ]);
  }


问:
Row height setting is not reflected correctly in dash-bootstrap-components
I want to change row height using dash-bootstrap-components, but it is not reflected correctly on the page.

Specifically, even if I execute the code posted below, I will see a page like the one below.

But the simple structure of the page is as follows

Whole page: height as 95% of view point, background color as grey

First line: one column in html.H1, className="h-10"

Line 2: 2 columns in html.Div, className="h-40"

Line 3: 2 columns in html.Div, className="h-40"

In the code, the overall size of the page is set to 95% of the view point and the background color to grey, which I can see reflected in the following figure.

H1 element with "Title" is also 10% of the total size (className="h-10"), which is exactly as set, but the height of the second and subsequent lines is not as set.

I saw the following discussion at the beginning, and I think my code implements the same way.
https://github.com/facultyai/dash-bootstrap-components/issues/286

These were not resolved by refreshing the page or restarting the server.
How can I get the height of each row to reflect the size I specify?

Thank you.

here is my source code

```<code>import dash
import dash_bootstrap_components as dbc
from dash import html, dcc
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        dbc.Row(
            dbc.Col(
                html.H1("タイトル"),
                width=12,
                style={"height": "100%", "background-color": "pink"},
            ),
            className="h-10"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.Div("This is column 1"),
                    width=8,
                    style={"height": "100%", "background-color": "red"},
                ),
                dbc.Col(
                    html.Div("This is column 2"),
                    width=4,
                    style={"height": "100%", "background-color": "green"},
                ),
            ],
            className="h-40",
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.Div("This is column 3"),
                    width=8,
                    style={"height": "100%", "background-color": "blue"},
                ),
                dbc.Col(
                    html.Div("This is column 4"),
                    width=4,
                    style={"height": "100%", "background-color": "cyan"},
                ),
            ],
            className="h-40",
        ),
    ],
    style={"height": "95vh", "background-color": "grey"},
)

if __name__ == "__main__":
    app.run_server(debug=True)

</code>```

答:
Width and height utilities are generated from the $sizes Sass map in _variables.scss. Includes support for 25%, 50%, 75%, 100%, and auto by default. Modify those values as you need to generate different utilities here.

https://getbootstrap.com/docs/4.1/utilities/sizing/

So the sizes you've specified (like: h-40 are not supported by default).

You can simply set the height of each row to a percentage using its style property or via css files, no utility functions needed

```<code>dbc.Row(
  dbc.Col(
    html.H1("タイトル"),
    width=12,
    style={"height": "100%", "background-color": "pink"},
  ),
  style={"height": "10%"}
),
</code>```

Body:
I want to change row height using dash-bootstrap-components, but it is not reflected correctly on the page.

Specifically, even if I execute the code posted below, I will see a page like the one below.

But the simple structure of the page is as follows

Whole page: height as 95% of view point, background color as grey

First line: one column in html.H1, className="h-10"

Line 2: 2 columns in html.Div, className="h-40"

Line 3: 2 columns in html.Div, className="h-40"

In the code, the overall size of the page is set to 95% of the view point and the background color to grey, which I can see reflected in the following figure.

H1 element with "Title" is also 10% of the total size (className="h-10"), which is exactly as set, but the height of the second and subsequent lines is not as set.

I saw the following discussion at the beginning, and I think my code implements the same way.
https://github.com/facultyai/dash-bootstrap-components/issues/286

These were not resolved by refreshing the page or restarting the server.
How can I get the height of each row to reflect the size I specify?

Thank you.

here is my source code

import dash
import dash_bootstrap_components as dbc
from dash import html, dcc
import plotly.express as px
import plotly.graph_objects as go
from dash.dependencies import Input, Output

app = dash.Dash(external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = dbc.Container(
    [
        dbc.Row(
            dbc.Col(
                html.H1("タイトル"),
                width=12,
                style={"height": "100%", "background-color": "pink"},
            ),
            className="h-10"
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.Div("This is column 1"),
                    width=8,
                    style={"height": "100%", "background-color": "red"},
                ),
                dbc.Col(
                    html.Div("This is column 2"),
                    width=4,
                    style={"height": "100%", "background-color": "green"},
                ),
            ],
            className="h-40",
        ),
        dbc.Row(
            [
                dbc.Col(
                    html.Div("This is column 3"),
                    width=8,
                    style={"height": "100%", "background-color": "blue"},
                ),
                dbc.Col(
                    html.Div("This is column 4"),
                    width=4,
                    style={"height": "100%", "background-color": "cyan"},
                ),
            ],
            className="h-40",
        ),
    ],
    style={"height": "95vh", "background-color": "grey"},
)

if __name__ == "__main__":
    app.run_server(debug=True)

Body:
Width and height utilities are generated from the $sizes Sass map in _variables.scss. Includes support for 25%, 50%, 75%, 100%, and auto by default. Modify those values as you need to generate different utilities here.

https://getbootstrap.com/docs/4.1/utilities/sizing/

So the sizes you've specified (like: h-40 are not supported by default).

You can simply set the height of each row to a percentage using its style property or via css files, no utility functions needed

dbc.Row(
  dbc.Col(
    html.H1("タイトル"),
    width=12,
    style={"height": "100%", "background-color": "pink"},
  ),
  style={"height": "10%"}
),


问:
What choice of naming for this kind of units?
[EDIT]

The question was a bit over-explained.

Cumulative

Consumption

Instantaneous

Average

What would you name this kind of units?

The listed options is used to specify how to calculate values in a table.

I.e.

Cumulative = 53 (sum of all)

Consumption = 8 (gap between two values)

Instantaneous = 20 (at asked time)

Average = 13,25 (sum 53/4 values)

The question is only for me to make a clear and understandable naming convention in the system.

答: I would name it CalculationMode, because it is "used to specify how to calculate values in a table".


问:
Expanding the touch area of a ViewPager
My App uses the following ViewPager:

The ViewPager has the same width as the display.

I added margins to the ViewPager in xml so that I can see the left(blue) and right(gray) page.
As a result everything works fine but I can only touch onto the green area to move the pages.

I want to expand the touch area to the whole screen so that I am able to touch anywhere to move the ViewPager.

I tried to add a TouchDelegate:

```<code>binding.pagerContainer.post {
        val rect = Rect()
        binding.touchArea.getHitRect(rect)
        binding.pagerContainer.touchDelegate = TouchDelegate(rect, binding.viewPager)
    }
</code>```

And in the xml:

```<code> <FrameLayout
        android:id="@+id/pager_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:clipChildren="false">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_marginBottom="150dp"
            android:layout_marginLeft="70dp"
            android:layout_marginRight="70dp"
            android:layout_marginTop="150dp"
            android:clipChildren="false"/>

        <View
            android:id="@+id/touchArea"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:alpha="0">
        </View>
    </FrameLayout>
</code>```

The Rect has the correct size.
I am posting a Runnable to be sure that the views are laid out.
I read the documentation of the TouchDelegate.

I have no idea why it's not working.

答:
My viewpager had a view behind it acting as a background. I noticed that touch events sent to the inactive items to the left and right of the active item in the viewpager were sent to the background view. That gave me the idea to intercept touches there and use the viewpager's fake drag api.

I built an extension function for ViewPager2 like this:

```<code>fun ViewPager2.receiveFakeDragsFrom(view: View) {
    view.setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                requestDisallowInterceptTouchEvent(true)
                beginFakeDrag()
                true
            }
            MotionEvent.ACTION_MOVE -> {
                if (event.historySize > 0) {
                    fakeDragBy(
                        event.x - event.getHistoricalX(0)
                    )
                }
                true
            }
            MotionEvent.ACTION_UP -> {
                endFakeDrag()
                requestDisallowInterceptTouchEvent(false)
                performClick()
                true
            }
            else -> {
                false
            }
        }
    }
}
</code>```

Then in my fragment while setting up the viewpager, I just called that function with the background view as the argument:

```<code>myViewPager.receiveFakeDragsFrom(vpBackgroundView)
</code>```

Title: Expanding the touch area of a ViewPager

Body:
My App uses the following ViewPager:

The ViewPager has the same width as the display.

I added margins to the ViewPager in xml so that I can see the left(blue) and right(gray) page.
As a result everything works fine but I can only touch onto the green area to move the pages.

I want to expand the touch area to the whole screen so that I am able to touch anywhere to move the ViewPager.

I tried to add a TouchDelegate:

binding.pagerContainer.post {
        val rect = Rect()
        binding.touchArea.getHitRect(rect)
        binding.pagerContainer.touchDelegate = TouchDelegate(rect, binding.viewPager)
    }

And in the xml:

 <FrameLayout
        android:id="@+id/pager_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:clipChildren="false">

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_gravity="center"
            android:layout_marginBottom="150dp"
            android:layout_marginLeft="70dp"
            android:layout_marginRight="70dp"
            android:layout_marginTop="150dp"
            android:clipChildren="false"/>

        <View
            android:id="@+id/touchArea"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:alpha="0">
        </View>
    </FrameLayout>

The Rect has the correct size.
I am posting a Runnable to be sure that the views are laid out.
I read the documentation of the TouchDelegate.

I have no idea why it's not working.

Body:
My viewpager had a view behind it acting as a background. I noticed that touch events sent to the inactive items to the left and right of the active item in the viewpager were sent to the background view. That gave me the idea to intercept touches there and use the viewpager's fake drag api.

I built an extension function for ViewPager2 like this:

fun ViewPager2.receiveFakeDragsFrom(view: View) {
    view.setOnTouchListener { _, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                requestDisallowInterceptTouchEvent(true)
                beginFakeDrag()
                true
            }
            MotionEvent.ACTION_MOVE -> {
                if (event.historySize > 0) {
                    fakeDragBy(
                        event.x - event.getHistoricalX(0)
                    )
                }
                true
            }
            MotionEvent.ACTION_UP -> {
                endFakeDrag()
                requestDisallowInterceptTouchEvent(false)
                performClick()
                true
            }
            else -> {
                false
            }
        }
    }
}

Then in my fragment while setting up the viewpager, I just called that function with the background view as the argument:

myViewPager.receiveFakeDragsFrom(vpBackgroundView)


问:
GCP - retrieve cloud composer proxy url - throws error Expected OAuth 2 access toke
I am trying to get the cloud composer proxy url to trigger dags from cloud function. I am following below blog. however it's failing while retrieving this url.

https://medium.com/google-cloud/calling-cloud-composer-to-cloud-functions-and-back-again-securely-8e65d783acce

Command

```<code>curl -s  -H "Authorization: Bearer `gcloud auth application-default print-access-token`" https://composer.googleapis.com/v1/projects/test/locations/us-east1/environments/test-environment
</code>```

I tried gcloud auth print-access-token but same error

error

```<code>{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "method": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment",
          "service": "composer.googleapis.com"
        }
      }
    ]
  }
}
</code>```

答:
I followed the medium post that you shared. NOTE (where my_project_id is, you have to set your project id).

First I created the project (My user has an owner role in the project) and the environment.

```<code>export GOOGLE_PROJECT_ID=`gcloud config get-value core/project`

export PROJECT_NUMBER=`gcloud projects describe my_project_id --format='value(projectNumber)'

gcloud composer environments create composer1  --location us-central1

gcloud composer environments  list --locations us-central1
</code>```

After these steps I didn’t configure the requirements.txt. But I configured the connection.

```<code>gcloud composer environments update composer1  \
 --update-env-variables=AIRFLOW_CONN_MY_GCF_CONN=https://us-central1-my_project_id.cloudfunctions.net --location us-central1

gcloud composer environments describe composer1 --location us-central1

gcloud composer environments describe composer1 --location us-central1 --format="get(config.dagGcsPrefix)"
</code>```

Then I went to Composer and I set the python packages manually.

You have to click on EDIT and add the name of the packages.

After the packages are installed you need to know if you have access to your token. Here is some documentation on how to create the a service account. Then you need to set your credential in the terminal,command prompt or shell that you are using. And here is some documentation on how to obtain the access token. You need to have a Service Account to have the token.

Then I follow step 3 where it brings you an error message.

```<code>curl -s  -H "Authorization: Bearer `gcloud auth print-access-token`" https://composer.googleapis.com/v1beta1/projects/my_project_id/locations/us-central1/environments/composer1 | jq [.config.airflowUri]
</code>```

And this brings me, my URL for airflow that look like:

[

"https://url-tp.appspot.com"

]

Body:
I am trying to get the cloud composer proxy url to trigger dags from cloud function. I am following below blog. however it's failing while retrieving this url.

https://medium.com/google-cloud/calling-cloud-composer-to-cloud-functions-and-back-again-securely-8e65d783acce

Command

curl -s  -H "Authorization: Bearer `gcloud auth application-default print-access-token`" https://composer.googleapis.com/v1/projects/test/locations/us-east1/environments/test-environment

I tried gcloud auth print-access-token but same error

error

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.ErrorInfo",
        "reason": "CREDENTIALS_MISSING",
        "domain": "googleapis.com",
        "metadata": {
          "method": "google.cloud.orchestration.airflow.service.v1.Environments.GetEnvironment",
          "service": "composer.googleapis.com"
        }
      }
    ]
  }
}

Body:
I followed the medium post that you shared. NOTE (where my_project_id is, you have to set your project id).

First I created the project (My user has an owner role in the project) and the environment.

export GOOGLE_PROJECT_ID=`gcloud config get-value core/project`

export PROJECT_NUMBER=`gcloud projects describe my_project_id --format='value(projectNumber)'

gcloud composer environments create composer1  --location us-central1

gcloud composer environments  list --locations us-central1

After these steps I didn’t configure the requirements.txt. But I configured the connection.

gcloud composer environments update composer1  \
 --update-env-variables=AIRFLOW_CONN_MY_GCF_CONN=https://us-central1-my_project_id.cloudfunctions.net --location us-central1

gcloud composer environments describe composer1 --location us-central1

gcloud composer environments describe composer1 --location us-central1 --format="get(config.dagGcsPrefix)"

Then I went to Composer and I set the python packages manually.

You have to click on EDIT and add the name of the packages.

After the packages are installed you need to know if you have access to your token. Here is some documentation on how to create the a service account. Then you need to set your credential in the terminal,command prompt or shell that you are using. And here is some documentation on how to obtain the access token. You need to have a Service Account to have the token.

Then I follow step 3 where it brings you an error message.

curl -s  -H "Authorization: Bearer `gcloud auth print-access-token`" https://composer.googleapis.com/v1beta1/projects/my_project_id/locations/us-central1/environments/composer1 | jq [.config.airflowUri]

And this brings me, my URL for airflow that look like:

[

"https://url-tp.appspot.com"

]


问:
Changing the child's useState from Parent component react hooks
I have e child component named Window and I have this useState in Window component:

```<code>Window Component:
      const [showWindow, setShowWindow] = useState(false);
</code>```

Imagine this is the parent component

```<code>Parent component :
/////
////
////
<Window/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>
/////
/////
</code>```

As it can be seen I have a Button component here and I want to set the showWindow to 'true' through it.

How can I change the useState in the child component from its parent component like this example? How can I access to it?

答:
If I understand the question correctly, you would like to have the parent, able to change state that is defined in the child.

I don't believe this is possible exactly as described. A better solution might be to define the state inside the parent, then pass down the state to the child.

```<code>Parent component :
 const [showWindow, setShowWindow] = useState(false);

<Window showWindow = {showWindow} setShowWindow = {setShowWindow}/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>

</code>```

that should produce the functionality I think you are after. Furthermore, you can also pass the setter if you need to change the window within the window component ( which you likely do if this is a popup type component)

As another answer suggested, a further solution would be to use global state/context. This would allow you to avoid passing state around, but has more overhead

Body:
I have e child component named Window and I have this useState in Window component:

Window Component:
      const [showWindow, setShowWindow] = useState(false);

Imagine this is the parent component

Parent component :
/////
////
////
<Window/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>
/////
/////

As it can be seen I have a Button component here and I want to set the showWindow to 'true' through it.

How can I change the useState in the child component from its parent component like this example? How can I access to it?

Body:
If I understand the question correctly, you would like to have the parent, able to change state that is defined in the child.

I don't believe this is possible exactly as described. A better solution might be to define the state inside the parent, then pass down the state to the child.

Parent component :
 const [showWindow, setShowWindow] = useState(false);

<Window showWindow = {showWindow} setShowWindow = {setShowWindow}/>
<Button/ onClick={()=>{
setShowWindow(true)
}}>

that should produce the functionality I think you are after. Furthermore, you can also pass the setter if you need to change the window within the window component ( which you likely do if this is a popup type component)

As another answer suggested, a further solution would be to use global state/context. This would allow you to avoid passing state around, but has more overhead


问:
Remove surrounding array from array of object
does anyone know how I can remove a surrounding array from an array of objects? In my case, I only have one object in this array. [{"id":"6","email":"test@test.com"}] Also, would the solution work in the case of multiple objects in the array? Thanks!

答:
You have an array of objects.  That's great, because it's the easiest way to store and manipulate lists of records.

You can use array methods like .map that allow you to treat each record separately, telling it what to do individually with each element.  That's also great, because it basically "removes the element from the array" while still processing the whole array, which is what I think you're after.

Simple example to create a dropdown:

const data = [{"id":"6","email":"test@test.com"}, {"id":"12","email":"test2@test.com"}];
const drawEmailDropdown = () => {
  let options = data.map(d => `<option value='${d.id}'>${d.email}</option>`);
  return `<select>` + options.join("") + `</select>`;
};

document.querySelector("#container").innerHTML = drawEmailDropdown();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container"></div></code>```

Body:
You have an array of objects.  That's great, because it's the easiest way to store and manipulate lists of records.

You can use array methods like .map that allow you to treat each record separately, telling it what to do individually with each element.  That's also great, because it basically "removes the element from the array" while still processing the whole array, which is what I think you're after.

Simple example to create a dropdown:

const data = [{"id":"6","email":"test@test.com"}, {"id":"12","email":"test2@test.com"}];
const drawEmailDropdown = () => {
  let options = data.map(d => `<option value='${d.id}'>${d.email}</option>`);
  return `<select>` + options.join("") + `</select>`;
};

document.querySelector("#container").innerHTML = drawEmailDropdown();

<div id="container"></div>