问:
Android Picasso resize() not consistent
I am using Picasso to resize my background images on my Android interface.

I am stretching the width of the image to fill the width, but I cannot adjust the height, as the background image needs to line up with the circular image in the middle.

Problem is that on different devices, the height appears to adjust as the background is not positioned consistently. I would post an example but I can't as I dont have 10 reputation yet.

Here is my java

```<code>ImageView imgBackground = (ImageView) v.findViewById(R.id.imgBackground);
aParent = (MainActivity) getActivity();

//Picasso.with(getActivity()).load(R.drawable.morn_blur_bg).fetch();
Picasso.with(aParent.getApplicationContext())
        .load(R.drawable.morn_blur_bg)
        .resize(aParent.getBackgroundWidth(), aParent.getBackgroundHeight())
        .into(imgBackground);
</code>```

And this is my XML

```<code><ImageView
    android:id="@+id/imgBackground"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:layout_alignParentTop="true" />
</code>```

Any help is greatly appreciated.

答: In my case, I put android:scaleType="centerCrop" on my ImageView and then no need to apply centerCrop() through Picasso.</p>

Title: Android Picasso resize() not consistent

Body:
I am using Picasso to resize my background images on my Android interface.

I am stretching the width of the image to fill the width, but I cannot adjust the height, as the background image needs to line up with the circular image in the middle.

Problem is that on different devices, the height appears to adjust as the background is not positioned consistently. I would post an example but I can't as I dont have 10 reputation yet.

Here is my java

ImageView imgBackground = (ImageView) v.findViewById(R.id.imgBackground);
aParent = (MainActivity) getActivity();

//Picasso.with(getActivity()).load(R.drawable.morn_blur_bg).fetch();
Picasso.with(aParent.getApplicationContext())
        .load(R.drawable.morn_blur_bg)
        .resize(aParent.getBackgroundWidth(), aParent.getBackgroundHeight())
        .into(imgBackground);

And this is my XML

<ImageView
    android:id="@+id/imgBackground"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:scaleType="center"
    android:layout_alignParentTop="true" />

Any help is greatly appreciated.


来源: stackexchange

问:
How to disable or readonly select input angular
If the cardSelect variable is true, just let [readonly]="cardSelect"

```<code><select name="card-exp-month" #validateMonth formControlName="digiMes" class="form-
 control" name="validade" id="validade"   >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>
</code>```

When is input text its works

```<code><label for="nomeimpresso">Nome <b>impresso</b> no cartão<span class="text-danger"> *
</span></label>
<input #nomeImpresso formControlName="digiNome"  name="holder-name" id="nomeimpresso"
class="form-control col-lg-6" type="text"  [readonly]="cardSelect" >
</code>```

答: try [disabled]="cardSelect" or if that didn't work  [attr.disabled]="!editable ? '' : null" as a workaround.

ContentLicense: CC BY-SA 4.0

Body:
If the cardSelect variable is true, just let [readonly]="cardSelect"

<select name="card-exp-month" #validateMonth formControlName="digiMes" class="form-
 control" name="validade" id="validade"   >
<option value="">Mês</option>
<option value="01">01 Jan</option>
<option value="02">02 Fev</option>
<option value="03">03 Mar</option>
<option value="04">04 Abr</option>
<option value="05">05 Mai</option>
<option value="06">06 Jun</option>
<option value="07">07 Jul</option>
<option value="08">08 Ago</option>
<option value="09">09 Set</option>
<option value="10">10 Out</option>
<option value="11">11 Nov</option>
<option value="12">12 Dez</option>
</select>

When is input text its works

Nome impresso no cartão *

<input #nomeImpresso formControlName="digiNome"  name="holder-name" id="nomeimpresso"
class="form-control col-lg-6" type="text"  [readonly]="cardSelect" >


问:
prepare segue - destination View Controller is called twice
In Xcode 13.1 I programmed the following code into my source view controller. It's working so well that it's calling the destination view controller twice (instead of once).

This is my code:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToNextViewControllerSegue" {
        let destVC = segue.destination as! DestinationViewController
        destVC.categoryTag = tag
    }
}
</code>```

Any idea what I'm doing wrong?

Let me include the IBAction code as well (This doesn't seem to be the problem, though.)

```<code>@IBAction func startButtonTapped(_ sender: UIButton) {

    if tag == 1 || tag == 2 {
    self.performSegue(withIdentifier: "goToNextViewControllerSegue", sender: nil)
    } else {
        createAlert()
    }
}
</code>```

Thanks for any help!

答: Add a breakpoint to prepare(for segue: sender:) and look at the backtrace to see where it is being called from. My guess is that you have connected the button to the segue in the storyboard, and then also to the action method mentioned in your question, so the segue is being performed twice.

Body:
In Xcode 13.1 I programmed the following code into my source view controller. It's working so well that it's calling the destination view controller twice (instead of once).

This is my code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "goToNextViewControllerSegue" {
        let destVC = segue.destination as! DestinationViewController
        destVC.categoryTag = tag
    }
}

Any idea what I'm doing wrong?

Let me include the IBAction code as well (This doesn't seem to be the problem, though.)

@IBAction func startButtonTapped(_ sender: UIButton) {

    if tag == 1 || tag == 2 {
    self.performSegue(withIdentifier: "goToNextViewControllerSegue", sender: nil)
    } else {
        createAlert()
    }
}

Thanks for any help!


问:
Is it possible to change size of minimized window in MDI C# Winforms

Users complain that when they have several minimized windows in MDI container it's impossible to distinguish them unless they resore each. I wonder if it's possible to make minimized window a little bit wider so the text in the caption can contain 6 characters?

Thanks in advance!

答:
[Although this post is 11 years old, i'm trying...:
I'm facing an issue with in-app minimized windows, which are broken on my Windows11 (certainly by a software, but I don't know which one...). Those in-app minimized windows are much more narrower that it should be. Instead of having the minimized title bar containing title and 3 buttons, I can only see the close button. You said here it wasn't possible to change this size for a unique software, but I assume you know(knew) where to change it for the whole system? Here is a capture of the issue in ultraedit 1 and here in 3dsMax for example 2</p>

ContentLicense: CC BY-SA 2.5


问:
How to make log10 ONLY first y-axis (not secondary y-axis) in ggplot in R
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

```<code>data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))
</code>```

答:
I think the easiest way is to have the primary axis be the linear one, but put it on the right side of the plot. Then, you can have the secondary one be your log-transformed axis.

library(ggplot2)

data<- data.frame(
  Day=c(1,2,3,1,2,3,1,2,3),
  Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
  Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
  Var2= c(4,16,39,2,22,39,41,10,3))

# Max of secondary divided by max of primary
upper <- log10(3e6) / 80

breakfun <- function(x) {
  10^scales::extended_breaks()(log10(x))
}

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2, x=Day),
           stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=log10(Var1) / upper),
            stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, log10(Var1) / upper), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    position = "right",
    name = "Var2",
    sec.axis = sec_axis(~10^ (. * upper), name= expression(paste("Var1")),
                        breaks = breakfun)
  )+
  theme_classic() +
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))
```

Created on 2022-02-09 by the reprex package (v2.0.1)

Body:
I would like to plot ONLY y-axis1 DATA (left axis, Var1, dotted line) as a log10 scale. The dotted line would therefore look higher on the y-axis and differences between 1 and 2 would be noticeable.

I have tried several things, but does not work ( I believe I am using them in the wrong order/place) such as:

+coord_trans(y='log10')--> empty plot

scale_y_continuous(trans = log10_trans(),... --> makes both Var1 and Var 2 log10

scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x),labels = trans_format("log10", math_format(10^.x)))--> makes both y axis log10 and removes y-axis2 (Var2)

data<- data.frame(
      Day=c(1,2,3,1,2,3,1,2,3),
      Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
      Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
      Var2= c(4,16,39,2,22,39,41,10,3))

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2*1000, x=Day),stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=Var1),stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, Var1), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    sec.axis=sec_axis(~./1000, name= expression(paste("Var2"))))+
  theme_classic()+
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))

Body:
I think the easiest way is to have the primary axis be the linear one, but put it on the right side of the plot. Then, you can have the secondary one be your log-transformed axis.

library(ggplot2)

data<- data.frame(
  Day=c(1,2,3,1,2,3,1,2,3),
  Name=rep(c(rep("a",3),rep("b",3),rep("c",3))),
  Var1=c(1090,484,64010,1090,484,64010,1090,484,64010),
  Var2= c(4,16,39,2,22,39,41,10,3))

# Max of secondary divided by max of primary
upper <- log10(3e6) / 80

breakfun <- function(x) {
  10^scales::extended_breaks()(log10(x))
}

ggplot(data)  +
  geom_bar(aes(fill=Name, y=Var2, x=Day),
           stat="identity", colour="black", position= position_stack(reverse = TRUE))+
  geom_line(aes(x=Day, y=log10(Var1) / upper),
            stat="identity",color="black", linetype="dotted", size=0.8)+
  geom_point(aes(Day, log10(Var1) / upper), shape=8)+
  labs(title= "",
       x="",y=expression('Var1'))+
  scale_y_continuous(
    position = "right",
    name = "Var2",
    sec.axis = sec_axis(~10^ (. * upper), name= expression(paste("Var1")),
                        breaks = breakfun)
  )+
  theme_classic() +
  scale_fill_grey(start = 1, end=0.1,name = "", labels = c("a", "b", "c"))

Created on 2022-02-09 by the reprex package (v2.0.1)


问:
Unexpected square appear in pure python, but occasionally when pyinstaller-packed
My simple wx app has only one wx.lib.FileBrowseButton & a wx.TextCtrl. It functions normal, but always with a unexpected square appear in the left-top corner, which covers the 'HEX' label, see below screen-shot.

And if I pack my app with pyinstaller, this square will not always appear. See pic below (nothing over the 'HEX' label).

Here is the app code:

```<code>import logging
import os
import time
import sys

import wx
import wx.lib.filebrowsebutton as filebrowse

class FWScripterPanel(wx.Panel):
    def __init__(self, parent, ID):
        wx.Panel.__init__(self, parent, ID)

        self.fbb = filebrowse.FileBrowseButton(self, wx.ID_ANY, size=(450, -1), changeCallback = self.fbbCallback, labelText='HEX', buttonText='Select HEX', fileMask='*.hex', toolTip='Select & transfer a HEX file to script')

        style = wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL
        self.log = wx.TextCtrl(self, wx.ID_ANY, '', size=(-1, -1), style=style)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.fbb, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(self.log, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

    def fbbCallback(self, evt):
        path = evt.GetString()
        logging.info(path)
        self.make_script(path)

    def make_script(self, hex_path):
        pass

class FWScripterFrame(wx.Frame):
    """
    """

    def __init__(
            self, parent, ID, title, pos=wx.DefaultPosition,
            size=(800,600), style=wx.DEFAULT_FRAME_STYLE
            ):

        wx.Frame.__init__(self, parent, ID, title, pos, size, style)
        panel = FWScripterPanel(self, -1)

class App(wx.App):
    def OnInit(self):
        frame = FWScripterFrame(parent=None, ID=-1, title='20220208')
        frame.Show()
        return True

def main():
    app = App()
    app.MainLoop()

if __name__ == '__main__':
    main()
</code>```

And if I remove the wx.TextCtrl, leaving only the filebrowsebutton, then this strage little square will not appeared at all.
Same issue when I add a new filebrowsebutton before the first filebrowsebutton (the 2nd filebrowsebutton will be covered by a little square)

答:
Finally I solved the problem by adding one line 'self.Layout()' in the FWScripterPanel.init(), see below.

```<code>class FWScripterPanel(wx.Panel):
    def __init__(self, parent, ID):
        wx.Panel.__init__(self, parent, ID)

        self.fbb = filebrowse.FileBrowseButton(self, wx.ID_ANY, size=(450, -1), changeCallback = self.fbbCallback, labelText='HEX', buttonText='Select HEX', fileMask='*.hex', toolTip='Select & transfer a HEX file to script')

        style = wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL
        self.log = wx.TextCtrl(self, wx.ID_ANY, '', size=(-1, -1), style=style)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.fbb, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(self.log, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)
        self.Layout()  # Add this line to solve the 'square' issue
</code>```

WhenAndHowToCallLayout
The above link provides quite a lot helpful information. Hope it helps.

Body:
My simple wx app has only one wx.lib.FileBrowseButton & a wx.TextCtrl. It functions normal, but always with a unexpected square appear in the left-top corner, which covers the 'HEX' label, see below screen-shot.

And if I pack my app with pyinstaller, this square will not always appear. See pic below (nothing over the 'HEX' label).

Here is the app code:

import logging
import os
import time
import sys

import wx
import wx.lib.filebrowsebutton as filebrowse

class FWScripterPanel(wx.Panel):
    def __init__(self, parent, ID):
        wx.Panel.__init__(self, parent, ID)

        self.fbb = filebrowse.FileBrowseButton(self, wx.ID_ANY, size=(450, -1), changeCallback = self.fbbCallback, labelText='HEX', buttonText='Select HEX', fileMask='*.hex', toolTip='Select & transfer a HEX file to script')

        style = wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL
        self.log = wx.TextCtrl(self, wx.ID_ANY, '', size=(-1, -1), style=style)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.fbb, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(self.log, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

    def fbbCallback(self, evt):
        path = evt.GetString()
        logging.info(path)
        self.make_script(path)

    def make_script(self, hex_path):
        pass

class FWScripterFrame(wx.Frame):
    """
    """

    def __init__(
            self, parent, ID, title, pos=wx.DefaultPosition,
            size=(800,600), style=wx.DEFAULT_FRAME_STYLE
            ):

        wx.Frame.__init__(self, parent, ID, title, pos, size, style)
        panel = FWScripterPanel(self, -1)

class App(wx.App):
    def OnInit(self):
        frame = FWScripterFrame(parent=None, ID=-1, title='20220208')
        frame.Show()
        return True

def main():
    app = App()
    app.MainLoop()

if __name__ == '__main__':
    main()

And if I remove the wx.TextCtrl, leaving only the filebrowsebutton, then this strage little square will not appeared at all.
Same issue when I add a new filebrowsebutton before the first filebrowsebutton (the 2nd filebrowsebutton will be covered by a little square)

Body:
Finally I solved the problem by adding one line 'self.Layout()' in the FWScripterPanel.init(), see below.

class FWScripterPanel(wx.Panel):
    def __init__(self, parent, ID):
        wx.Panel.__init__(self, parent, ID)

        self.fbb = filebrowse.FileBrowseButton(self, wx.ID_ANY, size=(450, -1), changeCallback = self.fbbCallback, labelText='HEX', buttonText='Select HEX', fileMask='*.hex', toolTip='Select & transfer a HEX file to script')

        style = wx.TE_MULTILINE | wx.TE_READONLY | wx.HSCROLL
        self.log = wx.TextCtrl(self, wx.ID_ANY, '', size=(-1, -1), style=style)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.fbb, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(self.log, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)
        self.Layout()  # Add this line to solve the 'square' issue

WhenAndHowToCallLayout
The above link provides quite a lot helpful information. Hope it helps.


问:
How to implement something like Terracota?
How Terracotta knows that object is changed inside one JVM to propagate this change to another JVM? I.e. how can I code similar behavior?

I want to be able to watch changes in instances of some classes, without changing them at all.

答: Shouldn't a observer pattern help. If you implement your class as observable and have an oberver , the observer will be notified when ever the observable class goes through some change.</p>

ContentLicense: CC BY-SA 3.0


问:
Laravel binding params
I am using below query to get results of 4 id's, but it shows only one result</p>
```<code>$id = array(6,7,8,9);
        $params = array(
            'connection' => 'redis',
            'id' => implode(',',$id)
        );

        $result =  DB::select(
            DB::raw("
                SELECT
                    *
                FROM
                    failed_jobs
                WHERE
                    id IN (:id) AND
                    connection = :connection
            "), $params);
</code>```

答:
The best way to go about it is to use the query builder instead. This is much cleaner since it provides the whereIn clause:

```<code>$id = array(6,7,8,9);

$result = DB::table('failed_jobs')
    ->where('connection', 'redis')
    ->whereIn('id', $id)
    ->get();
</code>```

Title: Laravel binding params

Body:
I am using below query to get results of 4 id's, but it shows only one result

$id = array(6,7,8,9);
        $params = array(
            'connection' => 'redis',
            'id' => implode(',',$id)
        );

        $result =  DB::select(
            DB::raw("
                SELECT
                    *
                FROM
                    failed_jobs
                WHERE
                    id IN (:id) AND
                    connection = :connection
            "), $params);

Body:
The best way to go about it is to use the query builder instead. This is much cleaner since it provides the whereIn clause:

$id = array(6,7,8,9);

$result = DB::table('failed_jobs')
    ->where('connection', 'redis')
    ->whereIn('id', $id)
    ->get();


问:
Android Management API Delegate scope PACKAGE_ACCESS setPackageSuspended admin null?
I'm trying to make a companion app for disable not used packages. Device is in "fully managed device mode" an my app has delegated scope for PACKAGE_ACCESS.
Acording to Googles documentation PACKAGE_ACCESS this give access to setPackagesSuspended(ComponentName, String[], boolean).

But when you read documentation for setPackagesSuspended it says:

Parameters
Description

admin: ComponentName
The name of the admin component to check, or null if the caller is a package access delegate. This value cannot be null.

packageNames: String
The package names to suspend or unsuspend. This value cannot be null.

suspended: boolean
If set to true than the packages will be suspended, if set to false the packages will be unsuspended.

My app is a package access delegate and I shoud use null as admin, but compiler don't let me use null.

When I try:

```<code>dpm.getDelegatedScopes(null, "my app package name")
</code>```

I get:
delegation-permission-grant, delegation-enable-system-app, delegation-block-uninstall, delegation-package-access

I have tryed:

Not compiling:

```<code>var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(null, arrayOf("packageName to suspend"), true)
</code>```

Compiling but getting a runtime error:

```<code>var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(null as ComponentName, arrayOf("packageName to suspend"), true)
</code>```

Getting error

```<code>var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(dpm.activeAdmins!![0], arrayOf("packageName to suspend"), true)
</code>```

Admin ComponentInfo{com.google.android.apps.work.clouddpc/com.google.android.apps.work.clouddpc.receivers.CloudDeviceAdminReceiver} is not owned by uid 10255

How can I use setPackagesSuspended()?

答: It cannot be done in Kotlin (or at least I don't know how) but in Java you can just use null for admin param and it works</p>

Body:
I'm trying to make a companion app for disable not used packages. Device is in "fully managed device mode" an my app has delegated scope for PACKAGE_ACCESS.
Acording to Googles documentation PACKAGE_ACCESS this give access to setPackagesSuspended(ComponentName, String[], boolean).

But when you read documentation for setPackagesSuspended it says:

Parameters
Description

admin: ComponentName
The name of the admin component to check, or null if the caller is a package access delegate. This value cannot be null.

packageNames: String
The package names to suspend or unsuspend. This value cannot be null.

suspended: boolean
If set to true than the packages will be suspended, if set to false the packages will be unsuspended.

My app is a package access delegate and I shoud use null as admin, but compiler don't let me use null.

When I try:

dpm.getDelegatedScopes(null, "my app package name")

I get:
delegation-permission-grant, delegation-enable-system-app, delegation-block-uninstall, delegation-package-access

I have tryed:

Not compiling:

var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(null, arrayOf("packageName to suspend"), true)

Compiling but getting a runtime error:

var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(null as ComponentName, arrayOf("packageName to suspend"), true)

Getting error

var dpm = mContext.getSystemService(DEVICE_POLICY_SERVICE) as DevicePolicyManager
dpm.setPackagesSuspended(dpm.activeAdmins!![0], arrayOf("packageName to suspend"), true)

Admin ComponentInfo{com.google.android.apps.work.clouddpc/com.google.android.apps.work.clouddpc.receivers.CloudDeviceAdminReceiver} is not owned by uid 10255

How can I use setPackagesSuspended()?


问:
Bash for loop containing python script
New here!

I'm trying to loop a python script in bash that gets stats from fastq files. I want it to loop through all the fastq files in a directory and save the outputs in a text file. Ideally don't want to edit the python script

This is the script that works when I'm not looping it:

```<code>python pythonscript.py -i fastqfile1.fq -q > stats1.txt
</code>```

This is the loop that doesn't work for me:

```<code>for f in *.fq; do python pythonscript.py -i "$f" -q;
do echo "${f%.*}" > "stats${f%.fq}.txt" done
</code>```

Thank you

EDIT I have put the loop in a bash .sh script. The error message I get is " looping_script.sh: line 5: syntax error near unexpected token do' looping_script.sh: line 5: do' "

答:
Like this if you want all results in a single file:</p>
```<code>for f in *.fq; do
   python pythonscript.py -i "$f" -q
done > results.txt
</code>```

Title: Bash for loop containing python script

Body:
New here!

I'm trying to loop a python script in bash that gets stats from fastq files. I want it to loop through all the fastq files in a directory and save the outputs in a text file. Ideally don't want to edit the python script

This is the script that works when I'm not looping it:

python pythonscript.py -i fastqfile1.fq -q > stats1.txt

This is the loop that doesn't work for me:

for f in *.fq; do python pythonscript.py -i "$f" -q;
do echo "${f%.*}" > "stats${f%.fq}.txt" done

Thank you

EDIT I have put the loop in a bash .sh script. The error message I get is " looping_script.sh: line 5: syntax error near unexpected token do' looping_script.sh: line 5: do' "

Body:
Like this if you want all results in a single file:

for f in *.fq; do
   python pythonscript.py -i "$f" -q
done > results.txt


问:
Environment variable are undefined inside the child/imported file in node/express
I am using dotenv package in my node/express project.

I have an root/index file where I am importing different files.

I imported dotenv in index file only. There within index file environment variable are accessible but in the imported file these are not accessible.
How can I make it accessible inside other file imported inside indes.js?

Here's a glimpse of my code

index.js

```<code>import dotenv from "dotenv";
dotenv.config();
import { sync, getImages, downloadImage } from "./api/controllers/shutterstock";
console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>Working gives me the access token
</code>```

api/controllers/shutterstock.js

```<code>console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>undefined
</code>```

This is how my directory structure looks like

答:
import { default as dotenv } from "dotenv";
dotenv.config({ path: '../.env' });
This worked for me when other solutions did not, tried the seperate file import, and everything else in this thread, https://github.com/motdotla/dotenv/issues/133
Also tried other stack articles, this one did the trick with a standard node setup with es6 style imports.</p>

Body:
I am using dotenv package in my node/express project.

I have an root/index file where I am importing different files.

I imported dotenv in index file only. There within index file environment variable are accessible but in the imported file these are not accessible.
How can I make it accessible inside other file imported inside indes.js?

Here's a glimpse of my code

index.js

import dotenv from "dotenv";
dotenv.config();
import { sync, getImages, downloadImage } from "./api/controllers/shutterstock";
console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>Working gives me the access token

api/controllers/shutterstock.js

console.log(process.env.SHUTTERSTOCK_ACCESS_TOKEN); //===>undefined

This is how my directory structure looks like


问:
bypass a load balancer rule
i have pod on which an app is running and exposing the port 6006

this pod is exposed by a service where i have :

```<code>- nodePort: 30017
    port: 6006
    protocol: TCP
    targetPort: 6006
</code>```

The problem is that the url i use to access this app is based on a LB that only exposes externalIP:443 and i can't add a new policy for 6006.

My question is how can i do on my pod and/or service to match the pod's 6006 to the LB's 443 ?

答:
change your service type to loadblancer

```<code> spec:
  type: loadblancer
  ports:
    - port: 6006
      targetPort: 6006
      protocol: TCP
      name: http
</code>```

you can also add the option internal if you want to expose your service internally

```<code>annotations:
    cloud.google.com/load-balancer-type: Internal
</code>```

Title: bypass a load balancer rule

Body:
i have pod on which an app is running and exposing the port 6006

this pod is exposed by a service where i have :

- nodePort: 30017
    port: 6006
    protocol: TCP
    targetPort: 6006

The problem is that the url i use to access this app is based on a LB that only exposes externalIP:443 and i can't add a new policy for 6006.

My question is how can i do on my pod and/or service to match the pod's 6006 to the LB's 443 ?

Body:
change your service type to loadblancer

 spec:
  type: loadblancer
  ports:
    - port: 6006
      targetPort: 6006
      protocol: TCP
      name: http

you can also add the option internal if you want to expose your service internally

annotations:
    cloud.google.com/load-balancer-type: Internal


问:
websocket-client python no data from the binance api
I had the problem that the websocket didn't respond and there was no data coming. Empty terminal without anything printed out.

I downgraded the python websocket-client to 0.57.0 version and now I am getting 'close' printed out but still no messages coming in.

I have no idea about what is wrong. Any clue why?

import websocket

cc = 'btcusdt'
interval = '1m'
socket = f'wss://stream.binance.com:9443/ws/{cc}@kline_{interval}'

def on_close(ws):
    print('close')

def on_message(ws, message):
    print('message')
    print(message)

ws = websocket.WebSocketApp(
    socket,
    on_message=on_message,
    on_close=on_close)

websocket.enableTrace(True)

ws.run_forever()```

答:
this worked for me ... it printed messages
you might have in import problem, try reinstalling python with all the packages, or make sure you are using the correct</p>


问:
git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054
I'm having trouble cloning a repo on git. I've been trying for to days and have tried quite a few solutions (in most the problem was slightly different but seemed to apply) but nothing has done anything to make a difference.

I've tried switching off the anti-virus and firewall but that didn't help.
I've also tried uninstalling and reinstalling the network adapter drivers (and restarting the computer) and that didn't work.

From what I understand it's a network issue somewhere as the remote server keeps hanging up but I'm not managing to get anywhere with the issue.

Using git clone -v --progress seemed to give the same output as git clone.
Output from git clone -v --progress https://github.com/mit-cml/appinventor-sources.git

Cloning into 'appinventor-sources'...

  POST git-upload-pack (gzip 1425 to 774 bytes)

  remote: Counting objects: 41649, done.

  remote: Compressing objects: 100% (7/7), done.

  error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

  fatal: The remote end hung up unexpectedly

  fatal: early EOF

  fatal: index-pack failed

I've now tried increasing the buffer again

git config --global http.postBuffer 1048576000

but still nothing.

I'm following the solution from The remote end hung up unexpectedly while git cloning for troubleshooting.

答:
This is what works for me.

git config --global http.sslVerify "false"


问:
iReport java.lang.Float hide decimals if zero
From IBM iSeries DB2 I recieve a ordered quantity DEC 11,4.

In iReport I use java.lang.Float to print the value. Also I have a pattern #,##0.0000;-#,##0.0000 (4 Decmimal places, 1000 separator).

When something is ordered in Metric Tons, this is no problem, but when something is ordered in pieces, it also prints "2,0000". This is confusing, how do I hide the ",0000"?

答:
You can use two fields (Text Field, for example) for showing value. You can set visibility for fields (with help of "Print when expression" property) - show one field with #,##0.0000 pattern (for metric tons) and hide another with #,##0 pattern (for pieces).

Expression can check parameter or field, for example:

$F{valueUnit}.equalsIgnoreCase("metricTon")


问:
Automatically replacing with var using IntelliJ
I'm migrating some pre Java 10 code and I'm wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it's possible.

The code is full of stuff like:

```<code>String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);
</code>```

And I would prefer:

```<code>var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);
</code>```

I already looked in IntelliJ's settings (Code Style/Inspections) and couldn't find anything.

答:
I'm using IntelliJ IDEA 2021.3.2, but don't think the setting is new.

I've been struggling with this one myself.

It seems that the first time to install IntelliJ locally, by default, it will fall back to using traditional defining of variables (i.e. String s = new String();)

How I managed to change it into using var is after I declared something, for example new String(), either I pressed ⌥ Alt/Option+Enter to declare a variable for that declaration or by using ⌘ Command+⇧ Shift+V shortcut (I'm using Mac and classic Intellij key mapping, so YMMV) which activates declaration of a variable, this would show as follows:

As you see, it suggest to hit that key combination shortcut or clicking on the settings button that would open a pop up like this one:

Make sure you have Declare var type selected and you should be good to go.

Body:
I'm migrating some pre Java 10 code and I'm wondering if IntelliJ offers a way to automatically refactor the code to replace the variable declarations that uses the actual type with var wherever it's possible.

The code is full of stuff like:

String status = "empty";
BigDecimal interest = BigDecimal.ZERO;
List<Future<Boolean>> results = es.invokeAll(tasks);
LocalDate start = LocalDate.of(2020, 1, 1);

And I would prefer:

var status = "empty";
var interest = BigDecimal.ZERO;
var results = es.invokeAll(tasks);
var start = LocalDate.of(2020, 1, 1);

I already looked in IntelliJ's settings (Code Style/Inspections) and couldn't find anything.


问:
Syndication Feed View RSS to File
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django.

The current setup has some basic well known primitives:

```<code>    path('podcast.xml', SubscribeFeed(), name='episode_feed'),
</code>```

Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators

And it looks somewhat like:

```<code>class iTunesFeed(Rss201rev2Feed):
    content_type = 'application/xml; charset=utf-8'

    def root_attributes(self):
        attrs = super().root_attributes()
        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        return attrs
    < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... >

 class SubscribeFeed(Feed):
    title = "My Cool Podcast"
    description = About.objects.first().about
    author_email = "podcast@gmail.com"
    author_name = "John Doe"
    feed_type = iTunesFeed

    def item_pubdate(self, item):
        return item.pub_date
    < ... More stuff that isn't relevant ... >
</code>```

Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice.

My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on a separate feeds.mypodcast.com CDN. In this way, the django app could go down but the feed and media would still be accessible via CDN. The django app is only in the critical path for; episode descriptions, contact forms, web ui episode browsing, etc.

I am already running celery to release the episodes at a given interval so my plan is the following:

Create an async function run after a model save() function that

Generates a new feed to a file or string

Compares what's on the CDN

Replaces the CDN RSS feed file and invalidates CDN cache.

Step 2 and 3 are very simple but I'm struggling with generating to a file.

Things I have tried:

"Mocking" requests and running get_feed podcast_feed.get_feed(podcast_feed.items(), <mocked request object>)
** This certainly "works" but calling my own REST resources feels bad and is not great.

Creating a "hidden" URL dispatcher. Then on a celery beat schedule, I hit this URL from my celery task. Generate the view via requests, compare and redistribute on CDN.
** This also "works" but similarly feels bad.

Writing my own get_feed() type of function.
** This didn't really work. Reading the source I found it rather dependent on a valid request and I didn't think I was architecturally doing it in the right place. (creating my own feedgenerator)

render_to_string but for Syndication Feeds. ** This stopped almost immediately. Worked well on a normal view but couldn't figure it out on feeds.

I've been banging my head on this for quite a while. The "hidden" dispatch feels like the safest and most efficacious hack, but I'd prefer to do it the right way.

What my question is really looking for is architectural guidance. What is the right way to do this? I was hoping to find something obvious like render_to_string but for syndication feeds. Implementing my own feedgenerator was not working well.

What is the best path forward to solve the use case of simply; Rendering a Syndication Feed View to a text file?

Thanks.

答:
you could just do it in a seperate view:

```<code>   def rss_feed_to_file():

      response = SubscribeFeed()

      # response is a HttpResponse object
      # response.content contains the feed content which you could then save as whatever you like
</code>```

does this answer your qeustion?

Title: Syndication Feed View RSS to File

Body:
I'm using django as my web frontend for my podcast. I use a CDN for hosting all my media, and lately I have wanted that same CDN to host my RSS Feed, not directly django.

The current setup has some basic well known primitives:

    path('podcast.xml', SubscribeFeed(), name='episode_feed'),

Some additional context; SubscribeFeed is a Syndication Feed (https://github.com/django/django/blob/main/django/contrib/syndication/views.py#L27) that is based off of the https://docs.djangoproject.com/en/4.0/ref/contrib/syndication/#custom-feed-generators

And it looks somewhat like:

class iTunesFeed(Rss201rev2Feed):
    content_type = 'application/xml; charset=utf-8'

    def root_attributes(self):
        attrs = super().root_attributes()
        attrs['xmlns:itunes'] = 'http://www.itunes.com/dtds/podcast-1.0.dtd'
        return attrs
    < ... Ripped right from the custom feed generators with a ton of extra elements for the specific podcast category and such ... >

 class SubscribeFeed(Feed):
    title = "My Cool Podcast"
    description = About.objects.first().about
    author_email = "podcast@gmail.com"
    author_name = "John Doe"
    feed_type = iTunesFeed

    def item_pubdate(self, item):
        return item.pub_date
    < ... More stuff that isn't relevant ... >

Just to be clear this view works perfectly with Django serving the podcast RSS. It works in all major platforms and is very nice.

My problem/question is that: I want to generate/render this view to a text file, the purpose being; I host media on a CDN, I would also benefit myself to put this RSS Feed on a separate feeds.mypodcast.com CDN. In this way, the django app could go down but the feed and media would still be accessible via CDN. The django app is only in the critical path for; episode descriptions, contact forms, web ui episode browsing, etc.

I am already running celery to release the episodes at a given interval so my plan is the following:

Create an async function run after a model save() function that

Generates a new feed to a file or string

Compares what's on the CDN

Replaces the CDN RSS feed file and invalidates CDN cache.

Step 2 and 3 are very simple but I'm struggling with generating to a file.

Things I have tried:

"Mocking" requests and running get_feed podcast_feed.get_feed(podcast_feed.items(), <mocked request object>)
** This certainly "works" but calling my own REST resources feels bad and is not great.

Creating a "hidden" URL dispatcher. Then on a celery beat schedule, I hit this URL from my celery task. Generate the view via requests, compare and redistribute on CDN.
** This also "works" but similarly feels bad.

Writing my own get_feed() type of function.
** This didn't really work. Reading the source I found it rather dependent on a valid request and I didn't think I was architecturally doing it in the right place. (creating my own feedgenerator)

render_to_string but for Syndication Feeds. ** This stopped almost immediately. Worked well on a normal view but couldn't figure it out on feeds.

I've been banging my head on this for quite a while. The "hidden" dispatch feels like the safest and most efficacious hack, but I'd prefer to do it the right way.

What my question is really looking for is architectural guidance. What is the right way to do this? I was hoping to find something obvious like render_to_string but for syndication feeds. Implementing my own feedgenerator was not working well.

What is the best path forward to solve the use case of simply; Rendering a Syndication Feed View to a text file?

Thanks.

Body:
you could just do it in a seperate view:

   def rss_feed_to_file():

      response = SubscribeFeed()

      # response is a HttpResponse object
      # response.content contains the feed content which you could then save as whatever you like

does this answer your qeustion?


问:
How to test for word boundries, if the pattern starts or ends with punctuation?
I'm having a hard time testing whether a provided string (that likely starts with !) is surrounded by word boundries.

// found in Mozilla's RegExp guide.
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

let msg = "a b c !test1 d e f";
let cmd = "!test1";

let re = new RegExp("\\b" + escapeRegExp(cmd) + "\\b");

console.log(`re: ${re.test(msg)}`);        // re: false
```

I assume this behaviour occurs, because punctuation itself is counted as a word boundry?

At least escaping the punctuation seems not to solve the problem. (I've tested a modified version of escapeRegExp() that includes !, same result.)

As an workaround I've used a version that splits msg at the white space and compares the elements with cmd. I'm not very happy with this solution as it breaks when cmd itself includes whitespace.

答:
You can use adaptive dynamic word boundaries:

// found in Mozilla's RegExp guide.
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

let msg = "a b c !test1 d e f";
let cmd = "!test1";

let re = new RegExp("(?!\\B\\w)" + escapeRegExp(cmd) + "(?<!\\w\\B)");
// console.log(re.source);// => (?!\B\w)!test1(?<!\w\B)
console.log(`re: ${re.test(msg)}`);
// => re: true```

The (?!\B\w)!test1(?<!\w\B) regex matches !test1 and

(?!\B\w) - checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required

(?<!\w\B) - checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required.

See some more details about adaptive dynamic word boundaries in my YT video.

Body:
I'm having a hard time testing whether a provided string (that likely starts with !) is surrounded by word boundries.

// found in Mozilla's RegExp guide.
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

let msg = "a b c !test1 d e f";
let cmd = "!test1";

let re = new RegExp("\\b" + escapeRegExp(cmd) + "\\b");

console.log(`re: ${re.test(msg)}`);        // re: false

I assume this behaviour occurs, because punctuation itself is counted as a word boundry?

At least escaping the punctuation seems not to solve the problem. (I've tested a modified version of escapeRegExp() that includes !, same result.)

As an workaround I've used a version that splits msg at the white space and compares the elements with cmd. I'm not very happy with this solution as it breaks when cmd itself includes whitespace.

Body:
You can use adaptive dynamic word boundaries:

// found in Mozilla's RegExp guide.
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

let msg = "a b c !test1 d e f";
let cmd = "!test1";

let re = new RegExp("(?!\\B\\w)" + escapeRegExp(cmd) + "(?<!\\w\\B)");
// console.log(re.source);// => (?!\B\w)!test1(?<!\w\B)
console.log(`re: ${re.test(msg)}`);
// => re: true

The (?!\B\w)!test1(?<!\w\B) regex matches !test1 and

(?!\B\w) - checks if the next char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required

(?<!\w\B) - checks if the previous char is a word char, and if it is, a word boundary is required at the current location, else, the word boundary is not required.

See some more details about adaptive dynamic word boundaries in my YT video.


问:
How do i allow 'Access-Control-Allow-Origin' in Node.JS Http Server?
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:</p>
```<code>var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});
</code>```

答:
Install cors package in your application

npm install cors

And then add these two lines in there

```<code>var cors = require("cors");
app.use(cors())
</code>```

Else there are ways that set through header or you could use a proxy in your frontend but using cors package is simpler

Body:
Im trying to send a POST from a client connected to this server to a external URL. I get a lot of 'CORS' errors. Im pretty sure that it's because i haven't allowed 'Access-Control-Allow-Origin' and etc on my Node.JS server. But i don't know how to do it. I have found another answers on the web, but none of them solved my problem.
Here is my server:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
const { instrument } = require('@socket.io/admin-ui')
var bodyParser = require('body-parser')
var clientesConectados = [];

app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.get('/', function(req, res){

  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');

});

app.post('/', (request, res) => {
  console.log("********************");
  console.log(" >POST RECEBIDO!!");
 console.log(res);

postData = request.body;
io.emit('message',postData);
 console.log(postData);

});

http.listen(3000, function(){

  console.log('listening on *:3000');

});

Body:
Install cors package in your application

npm install cors

And then add these two lines in there

var cors = require("cors");
app.use(cors())

Else there are ways that set through header or you could use a proxy in your frontend but using cors package is simpler


问:
Postgres function: return multiple tables
Is it possible to return several result sets of different types from postgres function?

Something like:

```<code>CREATE OR REPLACE FUNCTION getUserById()
RETURNS setof ???
AS
$$
BEGIN

return query select id, name /* and other columns */ from users where id = 1;
return query select id, phone_number from user_phones where user_id = 1

END
$$
LANGUAGE plpgsql;
</code>```

I don't want to use joins because several phones for user are possible. Also it would be great to avoid using cursors.
It's possible in MS SQL and I want to do the same thing in postgres.

答:
this works

```<code>CREATE OR REPLACE FUNCTION public.func_test(id integer ,ref1 refcursor,ref2 refcursor)
 RETURNS SETOF refcursor
 LANGUAGE plpgsql
AS $function$
BEGIN
    OPEN ref1 FOR SELECT * FROM table1;
    RETURN NEXT ref1;
    OPEN ref2 FOR SELECT * FROM table2;
    RETURN NEXT ref2;
END;
$function$
;
</code>```

execute in sql

```<code>BEGIN;
    SELECT func_test(69, 'Ref1', 'Ref2');
    FETCH ALL IN "Ref1";
    FETCH ALL IN "Ref2";
COMMIT;
</code>```

execute in python

```<code>import psycopg2

conn = psycopg2.connect(database = "name", user = "user", password = "pass", host = "127.0.0.1", port = "5432")
cur = conn.cursor()
cur.execute("SELECT * FROM func_test(69, 'Ref1', 'Ref2');")
cur.execute('FETCH ALL IN "Ref1";')
tbl1 = cur.fetchall()
print(tbl1)
cur.execute('FETCH ALL IN "Ref1";')
tbl2 = cur.fetchall()
print(tbl2)
</code>```

Cheers!

سلامتی کپی کارا

Body:
Is it possible to return several result sets of different types from postgres function?

Something like:

CREATE OR REPLACE FUNCTION getUserById()
RETURNS setof ???
AS
$$
BEGIN

return query select id, name /* and other columns */ from users where id = 1;
return query select id, phone_number from user_phones where user_id = 1

END
$$
LANGUAGE plpgsql;

I don't want to use joins because several phones for user are possible. Also it would be great to avoid using cursors.
It's possible in MS SQL and I want to do the same thing in postgres.

Body:
this works

CREATE OR REPLACE FUNCTION public.func_test(id integer ,ref1 refcursor,ref2 refcursor)
 RETURNS SETOF refcursor
 LANGUAGE plpgsql
AS $function$
BEGIN
    OPEN ref1 FOR SELECT * FROM table1;
    RETURN NEXT ref1;
    OPEN ref2 FOR SELECT * FROM table2;
    RETURN NEXT ref2;
END;
$function$
;

execute in sql

BEGIN;
    SELECT func_test(69, 'Ref1', 'Ref2');
    FETCH ALL IN "Ref1";
    FETCH ALL IN "Ref2";
COMMIT;

execute in python

import psycopg2

conn = psycopg2.connect(database = "name", user = "user", password = "pass", host = "127.0.0.1", port = "5432")
cur = conn.cursor()
cur.execute("SELECT * FROM func_test(69, 'Ref1', 'Ref2');")
cur.execute('FETCH ALL IN "Ref1";')
tbl1 = cur.fetchall()
print(tbl1)
cur.execute('FETCH ALL IN "Ref1";')
tbl2 = cur.fetchall()
print(tbl2)

Cheers!

سلامتی کپی کارا


问:
Loadavg over possible value
Due to my simplified knowledge loadavg on N-core CPU should show max value N.

I've maximized CPU usage to 100% (8 x Temrminal with: $ node --eval 'while(1){}'

Linux built-in loadavg differs from my expectations and my own implementation (details on image)

Question - is my CPU really fully used?:

On my 8-core CPU native linux loadavg shows value over 9 (expected max is 8)

During test my PC was still working smoothly (youtube video run smoothly).

Check details below: .. Thread(s) per core: 2 .. - it still tells nothing because I was able to achievie bigger loadavg than 16, even 20:

Does it means that during test I used only 50% of my CPU potential? That /proc/loadavg tells the truth and system monitor (UI tool) lied about CPU usage?

PC details:

```<code>$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal
</code>```
```<code>$ cat /proc/version
Linux version 5.13.0-27-generic (buildd@lgw01-amd64-045) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #29~20.04.1-Ubuntu SMP Fri Jan 14 00:32:30 UTC 2022
</code>```
```<code>$ lscpu
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   39 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           140
Model name:                      11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Stepping:                        1
CPU MHz:                         1700.000
CPU max MHz:                     4700,0000
CPU min MHz:                     400,0000
BogoMIPS:                        3379.20
Virtualization:                  VT-x
L1d cache:                       192 KiB
L1i cache:                       128 KiB
L2 cache:                        5 MiB
L3 cache:                        12 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constan
                                 t_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sd
                                 bg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 i
                                 nvpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rd
                                 t_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect
                                 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bit
                                 alg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities
</code>```

答:
@Fusho

Posts you mentioned told me nothing new at all:

See this for good answers about loadavg.

However thak you for your answer because it pushed me to investigate topic one more time - I found article that explains loadavg and helps with deep understanding of this topic:
https://www.brendangregg.com/blog/2017-08-08/linux-load-averages.html

My custom loadavg implementation is loadavg-windows for nodejs - now I can see that name cpu-loadavg fits it better.

My conclusion:

To monitor application performance and bottlenecks we should measure two different statistics:

CPU load

HD I/O load (I have not found any tools that allows you to measure "disk I/O load" from OS perspective. From OS perspective means time that OS awaits for hard drive I/O divided by total time passed).

Optionally we should take care of network I/O but this topic should be part of other post.

Imo. the need of monitoring of other I/O-s (other than HD and Network) from perspective of Application development is to be discussed in future because it have no such big impact on performance as CPU load and mentioned I/O-s.

Title: Loadavg over possible value

Body:
Due to my simplified knowledge loadavg on N-core CPU should show max value N.

I've maximized CPU usage to 100% (8 x Temrminal with: $ node --eval 'while(1){}'

Linux built-in loadavg differs from my expectations and my own implementation (details on image)

Question - is my CPU really fully used?:

On my 8-core CPU native linux loadavg shows value over 9 (expected max is 8)

During test my PC was still working smoothly (youtube video run smoothly).

Check details below: .. Thread(s) per core: 2 .. - it still tells nothing because I was able to achievie bigger loadavg than 16, even 20:

Does it means that during test I used only 50% of my CPU potential? That /proc/loadavg tells the truth and system monitor (UI tool) lied about CPU usage?

PC details:

$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 20.04.3 LTS
Release:    20.04
Codename:   focal

$ cat /proc/version
Linux version 5.13.0-27-generic (buildd@lgw01-amd64-045) (gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #29~20.04.1-Ubuntu SMP Fri Jan 14 00:32:30 UTC 2022

$ lscpu
Architecture:                    x86_64
CPU op-mode(s):                  32-bit, 64-bit
Byte Order:                      Little Endian
Address sizes:                   39 bits physical, 48 bits virtual
CPU(s):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           140
Model name:                      11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
Stepping:                        1
CPU MHz:                         1700.000
CPU max MHz:                     4700,0000
CPU min MHz:                     400,0000
BogoMIPS:                        3379.20
Virtualization:                  VT-x
L1d cache:                       192 KiB
L1i cache:                       128 KiB
L2 cache:                        5 MiB
L3 cache:                        12 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constan
                                 t_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sd
                                 bg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l2 i
                                 nvpcid_single cdp_l2 ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rd
                                 t_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves split_lock_detect
                                 dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bit
                                 alg avx512_vpopcntdq rdpid movdiri movdir64b fsrm avx512_vp2intersect md_clear flush_l1d arch_capabilities


问:
truncated output parameter from executenonquery
I am trying to implement ExecuteNonQuery in C#.
The storedProcedure on its own is working fine when I execute in SQL. It is returning a GUID for SubmissionId and the text 'submit sequence' for SubmitSequence. But in .net, it's returning one character as output for SubmitSequence

```<code>ALTER PROC [dbo].[test_SP]
(
    @FormId uniqueidentifier,
    @FormCode varchar(10),
    @FormTitle nvarchar(200),
    @User nvarchar(50),
    @Url nvarchar(255) = NULL,
    @Host nvarchar(50),
    @RemoteHost nvarchar(50) = NULL,
    @UserAgent nvarchar(255) = NULL,
    @Referrer nvarchar(255) = NULL,
    @SubmissionId uniqueidentifier out,
    @SubmitSequence varchar(30) out
) AS

BEGIN

SET @SubmissionId = newid();
set @SubmitSequence = 'submit sequence'

-- INSERT Query
SELECT
    @SubmissionId as SubmissionId,  @SubmitSequence  as SubmitSequence
END
</code>```

But in the .net, I am getting the GUID for SubmissionId(which is correct) and the text 's' for SubmitSequence.

```<code>public SubmissionHeaderDTO GetRefNo()
        {
            var inPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase)
                            {
                                {"FormId", Guid.NewGuid()},
                                {"FormCode", "TST"},
                                {"FormTitle", "Test form"},
                                {"User", "test"},
                                {"Host", "iisserver"}
                            };
            var outPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase) {
                            { "SubmissionId", Guid.NewGuid() },
                            { "SubmitSequence", "two"}
                            };
            var result = DBHelper.ExecSP(Constants.SPNames.SubmissionHeaderInsert, inPrms, outPrms);
            SubmissionHeaderDTO refNo = DictionaryToObject<SubmissionHeaderDTO>(result);
            return refNo;
        }
</code>```

DBHelper.cs

```<code>public static Dictionary<string, object> ExecSP(string sp, Dictionary<string, object> paramIn, Dictionary<string, object> paramOut)
        {
            var dbAccess = new DBAccess();
            var results = dbAccess.ExecuteQuery(sp, paramIn, paramOut);
            return results;
        }
</code>```

DBAccess.cs

```<code>public class DBAccess
    {
        public Dictionary<string, object> ExecuteQuery(string storedProcedure, Dictionary<string, object> parameters,
                                          Dictionary<string, object> outParameters)
        {

            using (var sqlConn = new SqlConnection(Configuration.DBConnection))
            {
                sqlConn.Open();
                using(var transaction = sqlConn.BeginTransaction("Results"))
                {
                    using(var sqlcmd = new SqlCommand(storedProcedure, sqlConn, transaction))
                    {
                        sqlcmd.CommandType = CommandType.StoredProcedure;
                        foreach(var kv in parameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value);
                        }
                        foreach(var kv in outParameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value).Direction = ParameterDirection.Output;
                        }

                        try
                        {
                            sqlcmd.ExecuteNonQuery();
                            var result = GetOutputParameters(sqlcmd.Parameters);
                            transaction.Commit();
                            return result;
                        }
                        catch(Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }

        }

        private Dictionary<string, object> GetOutputParameters(SqlParameterCollection paramCollection)
        {
            var returnParameters = new Dictionary<string, object>();
            foreach (SqlParameter par in paramCollection)
            {
                if ((par.Direction == ParameterDirection.Output) || (par.Direction == ParameterDirection.ReturnValue))
                {
                    returnParameters.Add(par.ParameterName, par.Value);
                }
            }
            return returnParameters;
        }
    }
</code>```

答:
Basically you need to give the correct SQLDbType and Size to your parameter. Especially if you omit the Size, your output will be truncated to 1 character.

SQL:

```<code>    @szError nvachar(max) output
</code>```

C#:

```<code>    SqlParameter szError = new SqlParameter("szError", System.Data.SqlDbType.NVarChar)
    {
      Direction = System.Data.ParameterDirection.Output,
      Size = 4000
    };
</code>```

Body:
I am trying to implement ExecuteNonQuery in C#.
The storedProcedure on its own is working fine when I execute in SQL. It is returning a GUID for SubmissionId and the text 'submit sequence' for SubmitSequence. But in .net, it's returning one character as output for SubmitSequence

ALTER PROC [dbo].[test_SP]
(
    @FormId uniqueidentifier,
    @FormCode varchar(10),
    @FormTitle nvarchar(200),
    @User nvarchar(50),
    @Url nvarchar(255) = NULL,
    @Host nvarchar(50),
    @RemoteHost nvarchar(50) = NULL,
    @UserAgent nvarchar(255) = NULL,
    @Referrer nvarchar(255) = NULL,
    @SubmissionId uniqueidentifier out,
    @SubmitSequence varchar(30) out
) AS

BEGIN

SET @SubmissionId = newid();
set @SubmitSequence = 'submit sequence'

-- INSERT Query
SELECT
    @SubmissionId as SubmissionId,  @SubmitSequence  as SubmitSequence
END

But in the .net, I am getting the GUID for SubmissionId(which is correct) and the text 's' for SubmitSequence.

public SubmissionHeaderDTO GetRefNo()
        {
            var inPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase)
                            {
                                {"FormId", Guid.NewGuid()},
                                {"FormCode", "TST"},
                                {"FormTitle", "Test form"},
                                {"User", "test"},
                                {"Host", "iisserver"}
                            };
            var outPrms = new Dictionary<string, object>(StringComparer.InvariantCultureIgnoreCase) {
                            { "SubmissionId", Guid.NewGuid() },
                            { "SubmitSequence", "two"}
                            };
            var result = DBHelper.ExecSP(Constants.SPNames.SubmissionHeaderInsert, inPrms, outPrms);
            SubmissionHeaderDTO refNo = DictionaryToObject<SubmissionHeaderDTO>(result);
            return refNo;
        }

DBHelper.cs

public static Dictionary<string, object> ExecSP(string sp, Dictionary<string, object> paramIn, Dictionary<string, object> paramOut)
        {
            var dbAccess = new DBAccess();
            var results = dbAccess.ExecuteQuery(sp, paramIn, paramOut);
            return results;
        }

DBAccess.cs

public class DBAccess
    {
        public Dictionary<string, object> ExecuteQuery(string storedProcedure, Dictionary<string, object> parameters,
                                          Dictionary<string, object> outParameters)
        {

            using (var sqlConn = new SqlConnection(Configuration.DBConnection))
            {
                sqlConn.Open();
                using(var transaction = sqlConn.BeginTransaction("Results"))
                {
                    using(var sqlcmd = new SqlCommand(storedProcedure, sqlConn, transaction))
                    {
                        sqlcmd.CommandType = CommandType.StoredProcedure;
                        foreach(var kv in parameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value);
                        }
                        foreach(var kv in outParameters)
                        {
                            sqlcmd.Parameters.AddWithValue(kv.Key, kv.Value).Direction = ParameterDirection.Output;
                        }

                        try
                        {
                            sqlcmd.ExecuteNonQuery();
                            var result = GetOutputParameters(sqlcmd.Parameters);
                            transaction.Commit();
                            return result;
                        }
                        catch(Exception)
                        {
                            transaction.Rollback();
                            throw;
                        }
                    }
                }
            }

        }

        private Dictionary<string, object> GetOutputParameters(SqlParameterCollection paramCollection)
        {
            var returnParameters = new Dictionary<string, object>();
            foreach (SqlParameter par in paramCollection)
            {
                if ((par.Direction == ParameterDirection.Output) || (par.Direction == ParameterDirection.ReturnValue))
                {
                    returnParameters.Add(par.ParameterName, par.Value);
                }
            }
            return returnParameters;
        }
    }

Body:
Basically you need to give the correct SQLDbType and Size to your parameter. Especially if you omit the Size, your output will be truncated to 1 character.

SQL:

    @szError nvachar(max) output

C#:

    SqlParameter szError = new SqlParameter("szError", System.Data.SqlDbType.NVarChar)
    {
      Direction = System.Data.ParameterDirection.Output,
      Size = 4000
    };


问:
while updating document with mongoose, adds _id
I was trying to make practise with mongoose model-methods. I was trying to update some part of my document with the method findByIdAndUpdate and it works actually, but creates some extra _id which I dont want to see it.

here it from server.js:

```<code> app.use("/update", updateRoute);
</code>```

here ist from the updateRoute

```<code>router.patch("/grades/:id", searchGradeAndUpdate);
</code>```

from controller

```<code>exports.searchGradeAndUpdate = async (req, res) => {
  try {
    const result = await Restaurant.findByIdAndUpdate(req.params.id, { grades: req.body.grades }, { new: true }).lean()
    res.status(200).json({ msg: "restaurant found! SUCCESS!!!", result })
  } catch (error) {
    res.status(404).json({ msg: "restaurant NOT found!! FAIL!!!" })
  }
};
</code>```

here is the schema and model

```<code>    const { Schema, model } = require("mongoose");

const restaurantSchema = new Schema({
  address: {
    building: String,
    coord: [Number],
    street: String,
    zipcode: String
  },
  borough: String,
  cuisine: String,
  grades: [
    {
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
    }
  ],
  name: String,
  restaurant_id: String
})

exports.Restaurant = model("restaurant", restaurantSchema);
</code>```

that's my URL and JSON as a body

```<code>http://localhost:3001/update/grades/5eb3d668b31de5d588f4292a

{"grades": [
            {

                "grade": "f",
                "score": 52
            },
            {

                "grade": "A",
                "score": 100
            }
        ]
}
</code>```

here is the result

```<code>{
    "msg": "restaurant found! SUCCESS!!!",
    "result": {
        "_id": "5eb3d668b31de5d588f4292a",
        "address": "berlin",
        "borough": "spandau",
        "cuisine": "Anatolian",
        "grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00b",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00c",
                "grade": "A",
                "score": 100
            }
        ],
        "name": "Ramazan's Kitchen ",
        "restaurant_id": "40356018"
    }
}
</code>```

I dont want the get the _id key inside of the array of objects. I wanted them to be like

```<code>...
"grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "grade": "A",
                "score": 100
            }
        ]
...
</code>```

答:
if you want to delete them from your query response only use .select in your query like so:

```<code>    const result = await Restaurant.findByIdAndUpdate(req.params.id, {grades:req.body.grades }, { new: true }).select('-grades._id').lean()
</code>```

this will make the result exclude all _id properties from the elements of your array.
if you want to delete _id from your elements completely you can define your schema like so:

```<code>  subschema =  mongoose.Schema({
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
  }, { _id : false });
  const restaurantSchema = new Schema({
    address: {
      building: String,
      coord: [Number],
      street: String,
      zipcode: String
    },
    borough: String,
    cuisine: String,
    grades: [subschema],
    name: String,
    restaurant_id: String
  })
</code>```

Body:
I was trying to make practise with mongoose model-methods. I was trying to update some part of my document with the method findByIdAndUpdate and it works actually, but creates some extra _id which I dont want to see it.

here it from server.js:

 app.use("/update", updateRoute);

here ist from the updateRoute

router.patch("/grades/:id", searchGradeAndUpdate);

from controller

exports.searchGradeAndUpdate = async (req, res) => {
  try {
    const result = await Restaurant.findByIdAndUpdate(req.params.id, { grades: req.body.grades }, { new: true }).lean()
    res.status(200).json({ msg: "restaurant found! SUCCESS!!!", result })
  } catch (error) {
    res.status(404).json({ msg: "restaurant NOT found!! FAIL!!!" })
  }
};

here is the schema and model

    const { Schema, model } = require("mongoose");

const restaurantSchema = new Schema({
  address: {
    building: String,
    coord: [Number],
    street: String,
    zipcode: String
  },
  borough: String,
  cuisine: String,
  grades: [
    {
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
    }
  ],
  name: String,
  restaurant_id: String
})

exports.Restaurant = model("restaurant", restaurantSchema);

that's my URL and JSON as a body

http://localhost:3001/update/grades/5eb3d668b31de5d588f4292a

{"grades": [
            {

                "grade": "f",
                "score": 52
            },
            {

                "grade": "A",
                "score": 100
            }
        ]
}

here is the result

{
    "msg": "restaurant found! SUCCESS!!!",
    "result": {
        "_id": "5eb3d668b31de5d588f4292a",
        "address": "berlin",
        "borough": "spandau",
        "cuisine": "Anatolian",
        "grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00b",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "_id": "6203c2e9fbf39efe8e5cf00c",
                "grade": "A",
                "score": 100
            }
        ],
        "name": "Ramazan's Kitchen ",
        "restaurant_id": "40356018"
    }
}

I dont want the get the _id key inside of the array of objects. I wanted them to be like

...
"grades": [
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "grade": "f",
                "score": 52
            },
            {
                "date": "Wed Feb 09 2022 14:29:44 GMT+0100 (Central European Standard Time)",
                "grade": "A",
                "score": 100
            }
        ]
...

Body:
if you want to delete them from your query response only use .select in your query like so:

    const result = await Restaurant.findByIdAndUpdate(req.params.id, {grades:req.body.grades }, { new: true }).select('-grades._id').lean()

this will make the result exclude all _id properties from the elements of your array.
if you want to delete _id from your elements completely you can define your schema like so:

  subschema =  mongoose.Schema({
      date: { type: String, default: new Date() },
      grade: String,
      score: Number
  }, { _id : false });
  const restaurantSchema = new Schema({
    address: {
      building: String,
      coord: [Number],
      street: String,
      zipcode: String
    },
    borough: String,
    cuisine: String,
    grades: [subschema],
    name: String,
    restaurant_id: String
  })


问:
PHP. Create value for unchecked box in the array
I have following table:

```<code><form action="update-table.php" method="post">
<table class="table-data" border="1">
    <thead>
        <tr>
            <td>ID</td>
            <td>Live</td>
            <td>User</td>
            <td>Last Update</td>
            <td>Title</td>
            <td>Content</td>
            <td>Edit</td>
            <td>Delete</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="1" /></td>
            <td><input name="live[]" type="checkbox" checked="checked" value="1"/></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:10 am</td>
            <td>Title1</td>
            <td>Content1</td>
            <td><a href="edit-news.php?editID=1">Edit</a></td>
            <td><a href="delete-news.php?deleteID=1">Delete</a></td>
        </tr>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="2" /></td>
            <td><input name="live[]" type="checkbox" /></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:11 am</td>
            <td>Title2</td>
            <td>Content2</td>
            <td><a href="edit-news.php?editID=2">Edit</a></td>
            <td><a href="delete-news.php?deleteID=2">Delete</a></td>
        </tr>
        <tr>
            <td><input name="id[]" type="text" readonly="readonly" value="3" /></td>
            <td><input name="live[]" type="checkbox"/></td>
            <td>admin@website.com</td>
            <td>August 18, 2011, 10:10 am</td>
            <td>Title3</td>
            <td>Content3</td>
            <td><a href="edit-news.php?editID=3">Edit</a></td>
            <td><a href="delete-news.php?deleteID=3">Delete</a></td>
        </tr>
    </tbody>
</table>
<input type="submit" />
</code>```

What I'm trying to do is  display the array send with $_POST.

The problem is when checkbox is not checked - nothing is being send.

How to check if the $_POST['live'] is set, and if not - set it's value to 0?

The following code does not work. Why?

```<code>if (!isset($_POST['live'])) {
            $_POST['live'] = "0";
        }

        for ($i=0;$i<count($_POST['id']);$i++) {

          echo "<p>".$_POST['id'][$i]."</p>";
          echo "<p>".$_POST['live'][$i]."</p>";
          echo "<hr />";

        }
</code>```

Body:
I have following table:

<form action="update-table.php" method="post">

            ID
            Live
            User
            Last Update
            Title
            Content
            Edit
            Delete

            <input name="id[]" type="text" readonly="readonly" value="1" />
            <input name="live[]" type="checkbox" checked="checked" value="1"/>
            admin@website.com
            August 18, 2011, 10:10 am
            Title1
            Content1
            Edit
            Delete

            <input name="id[]" type="text" readonly="readonly" value="2" />
            <input name="live[]" type="checkbox" />
            admin@website.com
            August 18, 2011, 10:11 am
            Title2
            Content2
            Edit
            Delete

            <input name="id[]" type="text" readonly="readonly" value="3" />
            <input name="live[]" type="checkbox"/>
            admin@website.com
            August 18, 2011, 10:10 am
            Title3
            Content3
            Edit
            Delete

<input type="submit" />

What I'm trying to do is  display the array send with $_POST.

The problem is when checkbox is not checked - nothing is being send.

How to check if the $_POST['live'] is set, and if not - set it's value to 0?

The following code does not work. Why?

if (!isset($_POST['live'])) {
            $_POST['live'] = "0";
        }

        for ($i=0;$i<count($_POST['id']);$i++) {

          echo "
".$_POST['id'][$i]."
";
          echo "
".$_POST['live'][$i]."
";
          echo "
";

        }

Body:
Try this:

for ($i=0;$i<count($_POST['id']);$i++) {

    if(!isset($_POST['live'][$i])){
        $_POST['live'][$i] = "0";
    }

    echo "<p>".$_POST['id'][$i]."</p>";
    echo "<p>".$_POST['live'][$i]."</p>";
    echo "<hr />";
}


问:
else if not working in KeyCode events javascript
I am trying to make me character moving left and up and I think  jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?

Code snippet:

var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;

function jump() {
  if (isJumping) return
  let timerUpId = setInterval(function() {
    if (bottom > 250) {
      clearInterval(timerUpId);

      let timerDownId = setInterval(function() {
        if (bottom < 0) {
          clearInterval(timerDownId);
          isJumping = false;
        }
        bottom -= 5;
        square.style.bottom = bottom + 'px';
      }, 20)
    }
    isJumping = true;
    bottom += 30;
    square.style.bottom = bottom + 'px';
  }, 20)
}

function slideLeft() {
  console.log('da');
  isGoingLeft = true;
  leftTimerId = setInterval(function() {
    left -= 5;
    square.style.left = left + 'px';
  }, 20)
}

function controller(e) {
  if (e.keyCode === 32)
    jump();
  else if (e.KeyCode === 37)
    slideLeft();
}

document.addEventListener('keydown', controller);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.grid {
  position: absolute;
  background-color: chartreuse;
  height: 20px;
  width: 500px;
  bottom: 100px;
  left: 100px;
}

.square {
  position: absolute;
  background-color: darkblue;
  height: 100px;
  width: 100px;
  bottom: 0px;
  left: 150px;
}

`</code>```

```

答:
EDIT:
There is a typo:
The second time you've written KeyCode

```<code>function controller(e) {
    if(e.keyCode===32) {
        jump();
    }
    else if(e.keyCode===37) {
        slideLeft();
    }
}
</code>```

I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:

```<code>if ( isNotOnGround() ) {
    fall()
}
</code>```

Body:
I am trying to make me character moving left and up and I think  jump() and slideLeft()
functions are working properly and the problem is in the controller(e) function (else if (e.KeyCode===37)) . The first function is avaible but it isn't able to acces the second conditon function. Also, I would want to make the grid solid after I will make an slideRight() similar function ,so if my character is jumping on it, the platform would sustain the square . Has anyone any ideea for either of my questions ?

Code snippet:

var square = document.querySelector('.square');
var grid = document.querySelector('.grid');
var bottom = 0;
let isJumping = false;
let isGoingLeft = false;
var newBottom;
let left = 0;
let leftTimerId;

function jump() {
  if (isJumping) return
  let timerUpId = setInterval(function() {
    if (bottom > 250) {
      clearInterval(timerUpId);

      let timerDownId = setInterval(function() {
        if (bottom < 0) {
          clearInterval(timerDownId);
          isJumping = false;
        }
        bottom -= 5;
        square.style.bottom = bottom + 'px';
      }, 20)
    }
    isJumping = true;
    bottom += 30;
    square.style.bottom = bottom + 'px';
  }, 20)
}

function slideLeft() {
  console.log('da');
  isGoingLeft = true;
  leftTimerId = setInterval(function() {
    left -= 5;
    square.style.left = left + 'px';
  }, 20)
}

function controller(e) {
  if (e.keyCode === 32)
    jump();
  else if (e.KeyCode === 37)
    slideLeft();
}

document.addEventListener('keydown', controller);

.grid {
  position: absolute;
  background-color: chartreuse;
  height: 20px;
  width: 500px;
  bottom: 100px;
  left: 100px;
}

.square {
  position: absolute;
  background-color: darkblue;
  height: 100px;
  width: 100px;
  bottom: 0px;
  left: 150px;
}

`

Body:
EDIT:
There is a typo:
The second time you've written KeyCode

function controller(e) {
    if(e.keyCode===32) {
        jump();
    }
    else if(e.keyCode===37) {
        slideLeft();
    }
}

I don't really understand what you mean by the second part of your question. If you want a character to have the ability to jump on a square, you'll have to implement a collision detection. Something like this:

if ( isNotOnGround() ) {
    fall()
}


问:
String replace in Twig
I have this code:

```<code>{% set foto = 'photo_gallery/' ~ {{ image.id }} ~ '/' %}
{% set thumbs = 'photo_gallery/thumbs/' ~ {{ image.id }} ~ '/' %}

<img src="{{ pageTemplate.pageHeader.mainUrl }}{{ image.image |replace({foto: thumbs}) }}">
</code>```

This is give me error:

```<code>Fatal error: Uncaught Twig_Error_Syntax: A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{". in ......
</code>```

How repair it?

答:
In Twig you have to enclose expressions in parentheses to use them as keys. Try this:

```<code>{{ image.image |replace({(foto): thumbs}) }}
</code>```

Otherwise the key is going to be 'foto' and of course the replace is going to fail.

See https://twig.symfony.com/doc/3.x/templates.html#literals.

Title: String replace in Twig

Body:
I have this code:

{% set foto = 'photo_gallery/' ~ {{ image.id }} ~ '/' %}
{% set thumbs = 'photo_gallery/thumbs/' ~ {{ image.id }} ~ '/' %}

This is give me error:

Fatal error: Uncaught Twig_Error_Syntax: A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{". in ......

How repair it?

Body:
In Twig you have to enclose expressions in parentheses to use them as keys. Try this:

{{ image.image |replace({(foto): thumbs}) }}

Otherwise the key is going to be 'foto' and of course the replace is going to fail.

See https://twig.symfony.com/doc/3.x/templates.html#literals.


问:
Change animation duration without reset on framer-motion
I'm trying to slow down an infinite animation using framer-motion by changing the duration value in the transition prop. I'm using the useMotionValue hook and the animate function:

```<code>const [count, setCount] = useState(1);

const scale = useMotionValue(1);

React.useEffect(() => {
  // the [1, 2] is for [from, to]
  const controls = animate(scale, [1, 2], {
    repeat: Infinity,
    ease: "linear",
    duration: count
  });

  return controls.stop;
}, [scale, count]);
</code>```

The problem here is that my animation reset from the beginning.

If I don't set any from value (animate(scale, 2, ...)) it doesn't reset, but the beginning on the next repeat will be the last value just before the duration changes.
(eg. I reset when scale is value is 1.5 and my animation will loop between 1.5 and 2 instead of 1 and 2)

I've made a repro here: https://codesandbox.io/s/framer-motion-simple-animation-forked-n8pbb?file=/src/index.tsx

答:
I don't think that there's an easy solution.

But it is possible to stop the infinite loop, perform the rest of the animation with the new speed and then start the infinite loop again.

I've implemented this functionality here:

```<code>const App = () => {
  const [count, setCount] = useState(1); // speed of animation

  const scale = useMotionValue(1); // the animating motion value

  // when we increase count, this will be set to true
  // and it will finish the remaining part of the animation
  const hasToFinish = useRef(false);

  const [triggerRerender, setTriggerRerender] = useState(false); // this is for triggering a rerender - see implementation below

  const performResetAnimation = useRef(false); // this is for performing an animation from scale 2 to scale 1

  React.useEffect(() => {
    let controls;
    // check if the animation has to finish, after count has been increased
    if (hasToFinish.current) {
      if (!performResetAnimation.current) {
        // check the target of the running animation - bigger or smaller
        if (scale.getPrevious() >= scale.get()) {
          // it's getting smaller
          // finish the animation from current scale to 1
          controls = animate(scale, [scale.get(), 1], {
            ease: "linear",
            duration: count * (scale.get() - 1), // calculate remaining duration with new speed
            onComplete: () => {
              hasToFinish.current = false;
              setTriggerRerender(!triggerRerender); // then trigger a rerender to go back to the infinite animation
            }
          });
        } else {
          // it's getting bigger
          // finish the animation from current scale to 2
          controls = animate(scale, [scale.get(), 2], {
            ease: "linear",
            duration: count * (2 - scale.get()), // calculate remaining duration with new speed
            onComplete: () => {
              // it has to animate back once to scale 1 because the infinite animation starts there
              performResetAnimation.current = true;
              setTriggerRerender(!triggerRerender); // trigger rerender to go to the reset animation
            }
          });
        }
      } else {
        // perform reset animation
        // if the count is increased while the reset animation plays, it should just proceed as usual
        // and not go into the reset animation again, so we set performResetAnimation to false
        performResetAnimation.current = false;
        controls = animate(scale, [2, 1], {
          ease: "linear",
          duration: count,
          onComplete: () => {
            hasToFinish.current = false;
            setTriggerRerender(!triggerRerender); // trigger rerender to go back to infinite animation
          }
        });
      }
    } else {
      // if it doesn't have to finish, perform the infinite animation
      controls = animate(scale, [1, 2], {
        repeat: Infinity,
        repeatType: "reverse",
        ease: "linear",
        duration: count
      });
    }

    return controls.stop;
  }, [triggerRerender, scale, count]);

  return (
    <>
      <Add
        onClick={() => {
          hasToFinish.current = true; // set hasToFinish to true, so that it finishes the animation with the new duration
          setCount(count + 1); // triggers a rerender with new duration
        }}
      />
      <div className="count">{count}</div>
      <div className="example-container">
        <motion.div style={{ scale }} key={count} />
      </div>
    </>
  );
};
</code>```

Check this forked codesandbox out

Body:
I'm trying to slow down an infinite animation using framer-motion by changing the duration value in the transition prop. I'm using the useMotionValue hook and the animate function:

const [count, setCount] = useState(1);

const scale = useMotionValue(1);

React.useEffect(() => {
  // the [1, 2] is for [from, to]
  const controls = animate(scale, [1, 2], {
    repeat: Infinity,
    ease: "linear",
    duration: count
  });

  return controls.stop;
}, [scale, count]);

The problem here is that my animation reset from the beginning.

If I don't set any from value (animate(scale, 2, ...)) it doesn't reset, but the beginning on the next repeat will be the last value just before the duration changes.
(eg. I reset when scale is value is 1.5 and my animation will loop between 1.5 and 2 instead of 1 and 2)

I've made a repro here: https://codesandbox.io/s/framer-motion-simple-animation-forked-n8pbb?file=/src/index.tsx

Body:
I don't think that there's an easy solution.

But it is possible to stop the infinite loop, perform the rest of the animation with the new speed and then start the infinite loop again.

I've implemented this functionality here:

const App = () => {
  const [count, setCount] = useState(1); // speed of animation

  const scale = useMotionValue(1); // the animating motion value

  // when we increase count, this will be set to true
  // and it will finish the remaining part of the animation
  const hasToFinish = useRef(false);

  const [triggerRerender, setTriggerRerender] = useState(false); // this is for triggering a rerender - see implementation below

  const performResetAnimation = useRef(false); // this is for performing an animation from scale 2 to scale 1

  React.useEffect(() => {
    let controls;
    // check if the animation has to finish, after count has been increased
    if (hasToFinish.current) {
      if (!performResetAnimation.current) {
        // check the target of the running animation - bigger or smaller
        if (scale.getPrevious() >= scale.get()) {
          // it's getting smaller
          // finish the animation from current scale to 1
          controls = animate(scale, [scale.get(), 1], {
            ease: "linear",
            duration: count * (scale.get() - 1), // calculate remaining duration with new speed
            onComplete: () => {
              hasToFinish.current = false;
              setTriggerRerender(!triggerRerender); // then trigger a rerender to go back to the infinite animation
            }
          });
        } else {
          // it's getting bigger
          // finish the animation from current scale to 2
          controls = animate(scale, [scale.get(), 2], {
            ease: "linear",
            duration: count * (2 - scale.get()), // calculate remaining duration with new speed
            onComplete: () => {
              // it has to animate back once to scale 1 because the infinite animation starts there
              performResetAnimation.current = true;
              setTriggerRerender(!triggerRerender); // trigger rerender to go to the reset animation
            }
          });
        }
      } else {
        // perform reset animation
        // if the count is increased while the reset animation plays, it should just proceed as usual
        // and not go into the reset animation again, so we set performResetAnimation to false
        performResetAnimation.current = false;
        controls = animate(scale, [2, 1], {
          ease: "linear",
          duration: count,
          onComplete: () => {
            hasToFinish.current = false;
            setTriggerRerender(!triggerRerender); // trigger rerender to go back to infinite animation
          }
        });
      }
    } else {
      // if it doesn't have to finish, perform the infinite animation
      controls = animate(scale, [1, 2], {
        repeat: Infinity,
        repeatType: "reverse",
        ease: "linear",
        duration: count
      });
    }

    return controls.stop;
  }, [triggerRerender, scale, count]);

  return (
    <>
      <Add
        onClick={() => {
          hasToFinish.current = true; // set hasToFinish to true, so that it finishes the animation with the new duration
          setCount(count + 1); // triggers a rerender with new duration
        }}
      />
      <div className="count">{count}</div>
      <div className="example-container">
        <motion.div style={{ scale }} key={count} />
      </div>
    </>
  );
};

Check this forked codesandbox out