问:
build array of object from tree object
I'm trying to get into javascript's built-in reduce function and with the help of that build objects inside array.
But you can use whatever function or method you want.

Expected output

```<code>[
  { 'team1': [14697807552, 6858384], '2021': [14697807552, 6858384], 'pepsi': [null, null], 'cola': [14697807552, 6858384] },
  { 'team2': [10268029152, 6922128], '2021': [10268029152, 6922128], 'pepsi': [null, 4800], 'cola': [10268029152, 6917328] },
]
</code>```

What I tried to do

I created a function which takes array as an argument and calls reduce for each array's element.

function transform(arr, obj = {}) {
  return arr.reduce((acc, item) => {
    const newObj = {};
    newObj[item.name] = item.metrics;
    acc.push(newObj);

    if (item.children) {
      transform(item.children, newObj);
    }

    return acc;
  }, []);
}
console.log(transform(arr))```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script>
  const arr = [{
      "name": "team1",
      "metrics": [
        14697807552,
        6858384
      ],
      "children": [{
        "name": "2021",
        "metrics": [
          14697807552,
          6858384
        ],
        "children": [{
            "name": "pepsi",
            "metrics": [
              null,
              null
            ]
          },
          {
            "name": "cola",
            "metrics": [
              14697807552,
              6858384
            ]
          }
        ]
      }]
    },
    {
      "name": "team2",
      "metrics": [
        10268029152,
        6922128
      ],
      "children": [{
        "name": "2021",
        "metrics": [
          10268029152,
          6922128
        ],
        "children": [{
            "name": "pepsi",
            "metrics": [
              null,
              4800
            ]
          },
          {
            "name": "cola",
            "metrics": [
              10268029152,
              6917328
            ]
          }
        ]
      }]
    }
  ]
</script></code>```

But it gives me output that I don't want:

```<code>[
  { team1: [ 14697807552, 6858384 ] },
  { team2: [ 10268029152, 6922128 ] }
]
</code>```

If you didn't understand my question or you have question, ask me. Thanks for paying attention!

答:
This approahc returns a different result and uses all previous information to get a denormalization of the data.

const
    flat = array => array.flatMap(({ name, metrics, children }) => children
        ? flat(children).map(q => ({ [name]: metrics, ...q }))
        : { [name]: metrics }),
    data = [{ name: "team1", metrics: [14697807552, 6858384], children: [{ name: "2021", metrics: [14697807552, 6858384], children: [{ name: "pepsi", metrics: [null, null] }, { name: "cola", metrics: [14697807552, 6858384] }] }] }, { name: "team2", metrics: [10268029152, 6922128], children: [{ name: "2021", metrics: [10268029152, 6922128], children: [{ name: "pepsi", metrics: [null, 4800] }, { name: "cola", metrics: [10268029152, 6917328] }] }] }],
    result = flat(data);

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: build array of object from tree object

Body:
I'm trying to get into javascript's built-in reduce function and with the help of that build objects inside array.
But you can use whatever function or method you want.

Expected output

[
  { 'team1': [14697807552, 6858384], '2021': [14697807552, 6858384], 'pepsi': [null, null], 'cola': [14697807552, 6858384] },
  { 'team2': [10268029152, 6922128], '2021': [10268029152, 6922128], 'pepsi': [null, 4800], 'cola': [10268029152, 6917328] },
]

What I tried to do

I created a function which takes array as an argument and calls reduce for each array's element.

function transform(arr, obj = {}) {
  return arr.reduce((acc, item) => {
    const newObj = {};
    newObj[item.name] = item.metrics;
    acc.push(newObj);

    if (item.children) {
      transform(item.children, newObj);
    }

    return acc;
  }, []);
}
console.log(transform(arr))

But it gives me output that I don't want:

[
  { team1: [ 14697807552, 6858384 ] },
  { team2: [ 10268029152, 6922128 ] }
]

If you didn't understand my question or you have question, ask me. Thanks for paying attention!

Body:
This approahc returns a different result and uses all previous information to get a denormalization of the data.

const
    flat = array => array.flatMap(({ name, metrics, children }) => children
        ? flat(children).map(q => ({ [name]: metrics, ...q }))
        : { [name]: metrics }),
    data = [{ name: "team1", metrics: [14697807552, 6858384], children: [{ name: "2021", metrics: [14697807552, 6858384], children: [{ name: "pepsi", metrics: [null, null] }, { name: "cola", metrics: [14697807552, 6858384] }] }] }, { name: "team2", metrics: [10268029152, 6922128], children: [{ name: "2021", metrics: [10268029152, 6922128], children: [{ name: "pepsi", metrics: [null, 4800] }, { name: "cola", metrics: [10268029152, 6917328] }] }] }],
    result = flat(data);

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


来源: stackexchange

问:
no persister for: Fluent nHibernate Exception
i m getting the exception "No persister for: MVCTemplate.Common.Entities.User" . I Google this issue and apply all the solution i found. but all are useless for me.
Does anyone know what i m doing wrong ?

my User Class code is

```<code>public class User
{
    public virtual Guid UserID { get; private set; }
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual string FullName { get; set; }
    public virtual string Email { get; set; }
    public virtual TimeSpan LastLogin { get; set; }
    public virtual bool IsActive { get; set; }
    public virtual DateTime CreationDate { get; set; }
    public virtual IList<UserInRole> UserInRoles { get; set; }
}
</code>```

User Mapping :

```<code>public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("tblUsers");
        Id(user => user.UserID).GeneratedBy.GuidComb();
        Map(user => user.UserName).Not.Nullable();
        Map(user => user.Password).Not.Nullable();
        Map(user => user.FullName).Not.Nullable();
        Map(user => user.Email).Not.Nullable();
        Map(user => user.LastLogin).Not.Nullable();
        Map(user => user.IsActive).Nullable();
        Map(user => user.CreationDate).Not.Nullable();
        HasMany(user => user.UserInRoles);
    }
}
</code>```

FNH Configuration :

```<code>return Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
            .ConnectionString(c => c.FromConnectionStringWithKey("FNHConnection"))
            )
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<User>())
            .BuildSessionFactory();
</code>```

Thanks

答:
The following will cause this error in simple terms:</p>
```<code>private static void MainFN()
{
    using (var session = sessionFactory.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {
            Data[] balance = new Data[12];
            for (int i = 0; i < 12; i++)
            {
                balance[i] = new Data();
                balance[i].Test1 = "Example Data " + (i + 1).ToString();
                balance[i].Test2 = i + 11;
                balance[i].Test3 = (i % 2 == 0);
                session.SaveOrUpdate(balance[i]); //Should be like this
            }
            //session.SaveOrUpdate(balance); //This will give the error
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i m getting the exception "No persister for: MVCTemplate.Common.Entities.User" . I Google this issue and apply all the solution i found. but all are useless for me.
Does anyone know what i m doing wrong ?

my User Class code is

public class User
{
    public virtual Guid UserID { get; private set; }
    public virtual string UserName { get; set; }
    public virtual string Password { get; set; }
    public virtual string FullName { get; set; }
    public virtual string Email { get; set; }
    public virtual TimeSpan LastLogin { get; set; }
    public virtual bool IsActive { get; set; }
    public virtual DateTime CreationDate { get; set; }
    public virtual IList<UserInRole> UserInRoles { get; set; }
}

User Mapping :

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("tblUsers");
        Id(user => user.UserID).GeneratedBy.GuidComb();
        Map(user => user.UserName).Not.Nullable();
        Map(user => user.Password).Not.Nullable();
        Map(user => user.FullName).Not.Nullable();
        Map(user => user.Email).Not.Nullable();
        Map(user => user.LastLogin).Not.Nullable();
        Map(user => user.IsActive).Nullable();
        Map(user => user.CreationDate).Not.Nullable();
        HasMany(user => user.UserInRoles);
    }
}

FNH Configuration :

return Fluently.Configure()
            .Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.MsSql2008
            .ConnectionString(c => c.FromConnectionStringWithKey("FNHConnection"))
            )
            .Mappings(m =>
                m.FluentMappings.AddFromAssemblyOf<User>())
            .BuildSessionFactory();

Thanks

Body:
The following will cause this error in simple terms:

private static void MainFN()
{
    using (var session = sessionFactory.OpenSession())
    {
        using (var transaction = session.BeginTransaction())
        {
            Data[] balance = new Data[12];
            for (int i = 0; i < 12; i++)
            {
                balance[i] = new Data();
                balance[i].Test1 = "Example Data " + (i + 1).ToString();
                balance[i].Test2 = i + 11;
                balance[i].Test3 = (i % 2 == 0);
                session.SaveOrUpdate(balance[i]); //Should be like this
            }
            //session.SaveOrUpdate(balance); //This will give the error

ContentLicense: CC BY-SA 4.0


问:
Azure Logic App HTTP Request Authentication Scope
We have an API hosted in Azure as an Azure Web App that we need to trigger via http on a schedule.

Our API requires a valid Azure AD Access Token be sent with each request.

Azure Logic Apps gives us the option to authenticate our request with Azure AD. However, we do not see the option of including scope in the request. If we send a request without specified scope or role, we get the following error:

```<code>System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.
</code>```

How can we authenticate an http request from an Azure Logic App when scope/role is required in the access token by the API?

答:
Parameter "Audience" is the scope. Depending on how you built your target api and what is expected there as audience in token you could probably have there somehting like: api://<yoru_app_id>/.default, but you should know it best.
E.g. when you call Graph MS your scope/resource/audience here is: https://graph.microsoft.com/.default, but different APIs have different needs for scopes.

Body:
We have an API hosted in Azure as an Azure Web App that we need to trigger via http on a schedule.

Our API requires a valid Azure AD Access Token be sent with each request.

Azure Logic Apps gives us the option to authenticate our request with Azure AD. However, we do not see the option of including scope in the request. If we send a request without specified scope or role, we get the following error:

System.UnauthorizedAccessException: IDW10201: Neither scope or roles claim was found in the bearer token.

How can we authenticate an http request from an Azure Logic App when scope/role is required in the access token by the API?


问:
Use Onclick to change an image
I have two DIVs on the left are thumbnail images and on the right I have one image. I am trying to click an image on the left side and have it replace the image on the right side. Currently when I select a thumbnail image I get the swirly indicator that the function has been called but the image isn't updated. Can this be completed with normal javascript or should JQuery be used.</p>
```<code><script type="text/javascript">

    //  This function will display photos selected by user
     function showDirectory(){
         var myFiles = document.getElementById("files");
         for(var i=0;i<=myFiles.files.length; i++){
            var x = myFiles.files[i].name;
            document.getElementById("demo1").innerHTML += "<img onclick='switchImage("+x+")' src='"+x+"' style='width:40px; height:40px; margin:5px'>"
         }
     }

    function switchImage(e){
       document.getElementById("rightside").src=e;
    }
</script>
</code>```

            Show files in the Directory
            </p>

```<code>    <div class="item" style="width: 70%; background-color: bisque; padding: 5px;">
       <img id="rightside" src="RightSide.jpg" alt="Picture of " style="height: 720px; width:720px">
        <p  style="color: #000; text-align: right;">Slide1.jpg</p>
    </div>
</div>
</code>```

答:
Setting the innerHTML of an img element is not going to display the image. You need to create a link to the image to display it.

<input type="file" id="files" multiple="" accept="image/*" onchange="showDirectory()">

```
<pre class="lang-js prettyprint-override"><code>function showDirectory(){
     var myFiles = document.getElementById("files");
     for(let i=0;i<=myFiles.files.length; i++){
        let f = myFiles.files[i];
        let e = document.createElement('img');
        e.src = URL.createObjectURL(f);
        e.onclick = () => {
            document.getElementById("rightside").src = (window.URL || window.webkitURL).createObjectURL(f);
        };
        document.getElementById("demo1").append(e);
     }
}
</code>```

(This works on a blank about:blank page with minimal HTML)

Helpful Links:

https://developer.mozilla.org/en-US/docs/Web/API/File

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

Title: Use Onclick to change an image

Body:
I have two DIVs on the left are thumbnail images and on the right I have one image. I am trying to click an image on the left side and have it replace the image on the right side. Currently when I select a thumbnail image I get the swirly indicator that the function has been called but the image isn't updated. Can this be completed with normal javascript or should JQuery be used.

            Show files in the Directory

Slide1.jpg

Body:
Setting the innerHTML of an img element is not going to display the image. You need to create a link to the image to display it.

<input type="file" id="files" multiple="" accept="image/*" onchange="showDirectory()">
<p id="demo1"></p>
<img id="rightside" style="height:720px; width:720px">

function showDirectory(){
     var myFiles = document.getElementById("files");
     for(let i=0;i<=myFiles.files.length; i++){
        let f = myFiles.files[i];
        let e = document.createElement('img');
        e.src = URL.createObjectURL(f);
        e.onclick = () => {
            document.getElementById("rightside").src = (window.URL || window.webkitURL).createObjectURL(f);
        };
        document.getElementById("demo1").append(e);
     }
}

(This works on a blank about:blank page with minimal HTML)

Helpful Links:

https://developer.mozilla.org/en-US/docs/Web/API/File

https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL


问:
How do I use Python to do the mouse hover action in selenium using javascript?
How can I go to an element and perform mouse hover action using only javascript and Python?
for instance This is my code:</p>
```<code>from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path = "chromedriver.exe")
driver.get(url)

btns = driver.find_elements_by_css_selector('il[class="reactions"]')

for btn in btns:
    **(I Want to Hover all 'btn' Element Using only "driver.execute_script" Method)**
    time.sleep(5)
    btn.click()
click()
</code>```

答:
To perform mouse hover with Selenium you should use ActionChains library.

Also you should use Expected Conditions explicit wait to load all btns the elements.

With it your code will be as following:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome(executable_path = "chromedriver.exe")
wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)
driver.get(url)
wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'il[class="reactions"]')))
time.sleep(1)
btns = driver.find_elements_by_css_selector('il[class="reactions"]')

for btn in btns:
    actions.move_to_element(btn).perform()
    time.sleep(0.5)
    btn.click()
```

Body:
How can I go to an element and perform mouse hover action using only javascript and Python?
for instance This is my code:

from selenium import webdriver
import time
driver = webdriver.Chrome(executable_path = "chromedriver.exe")
driver.get(url)

btns = driver.find_elements_by_css_selector('il[class="reactions"]')

for btn in btns:
    **(I Want to Hover all 'btn' Element Using only "driver.execute_script" Method)**
    time.sleep(5)
    btn.click()
click()


问:
What would happen if git repository of maven { url "https://jitpack.io" } is deleted?
So maven { url "https://jitpack.io" } is used to link github libraries to your android project. My question is what would happen if you create an app with implementations of github projects like "implementation 'com.github.authorproject:version'" and that project one day is deleted by the author. Would the app continue to work as before? Or if the app deppended of that github repository and that repository is deleted by the author your app will be obsolete? Thanks</p>

答:
If an external dependency is removed, you will fail to be able to build your app unless the dependency is still in cache on your local machine.

Existing apps will still work but once you do a clean build with an empty local gradle cache, the build will fail.

If a dependency's source code is hosted on git, it makes sense to fork it if you think that the code could disappear.


问:
Add tailwind classes manually
I use a tailwind class, which is only add with JS afterwards.
However, when I generate the css from tailwind this CSS class is of course not included. Therefore the question how I can add this class.</p>

答:
You will need to configure Tailwind so that it will also scan your JS files that are adding these additional classes. This can be done by modifying tailwind.config.js file and add additional entries/glob patterns to the content array, as per documentation.

Under the hood Tailwind CSS uses regex to simply search for possible classname uses in JS files. This also means that you need to be mindful of how you're adding classes in JS. You cannot use dynamically composited class names, e.g. const className = 'px-' + SOME_NUMBER, because Tailwind CSS cannot guess the class name.

Title: Add tailwind classes manually


答: You can customize Tailwind CSS by changing lines under themes section in your tailwind.config.js file. About more details: Tailwind Custom Styles

Title: Add tailwind classes manually

Body:
I use a tailwind class, which is only add with JS afterwards.
However, when I generate the css from tailwind this CSS class is of course not included. Therefore the question how I can add this class.


问:
Select all values in Row "B" and "C" and move 1 step up
My Intention:

I wanna select all values in Rows "B" and "C" and move these 1 and 2 steps up.

The Example for what I have:

A
B
C

AA

Two

AA

Three

Two

AA

Three

Two

Three

X

yy

CC

The Example for what I would: If in Column-A find "X" should YY and CC delet

A
B
C

AA
Two
Three

AA
Two
Three

AA
Two
Three

My Code:

```<code>Sub test()

ActiveSheet.Select
Range("B:B").Select Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C:C").Select Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove

End Sub
</code>```

I would be happy if somebody help me

答:
Align Data

Option Explicit

Sub AlignData()

    Const Cols As String = "A:C"
    Const fRow As Long = 1
    Const ExceptionsList As String = "XX" ' comma-separated, no spaces!
    Const Gap As Long = 1 ' number of empty rows in-between

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!

    ' Reference the source range.
    Dim srg As Range
    Dim srCount As Long
    With ws.Rows(fRow).Columns(Cols).Resize(ws.Rows.Count - fRow + 1)
        Dim lrCell As Range
        Set lrCell = .Find("*", , xlFormulas, , xlByRows, xlPrevious)
        If lrCell Is Nothing Then Exit Sub ' no data
        srCount = lrCell.Row - fRow + 1
        Set srg = .Resize(srCount)
    End With

    Dim cCount As Long: cCount = srg.Columns.Count
    ' 1 to hold each column array
    ' 2 to hold a collection of each column's matching values
    Dim jArr As Variant: ReDim jArr(1 To cCount, 1 To 2)

    Dim Exceptions() As String: Exceptions = Split(ExceptionsList, ",")

    Dim crg As Range
    Dim c As Long
    Dim r As Long
    Dim sValue As Variant

    ' Write the column arrays to the jagged array.
    For c = 1 To cCount
        jArr(c, 1) = srg.Columns(c).Value ' column arrays
        Set jArr(c, 2) = New Collection ' to hold the matching values
    Next c

    ' Use a dictionary to hold the indexes of (unwanted) exception matches.
    Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")

    Dim dStep As Long: dStep = Gap + 1

    Dim dData As Variant
    Dim drCount As Long
    Dim dr As Long
    Dim sr As Long

    For c = 1 To cCount
        dr = 0
        For sr = 1 To srCount
            sValue = jArr(c, 1)(sr, 1)
            If Not IsEmpty(sValue) Then ' exclude empty values
                dr = dr + 1
                If c = 1 Then ' 1st array
                    If IsError(Application.Match(sValue, Exceptions, 0)) Then
                        jArr(c, 2).Add sValue
                    Else ' found in exceptions
                        dict(dr) = Empty ' add the index
                    End If
                Else ' all but the 1st array
                    If Not dict.Exists(dr) Then
                        jArr(c, 2).Add sValue
                    End If
                End If
            End If
        Next sr
        ' Write the values from the collection to the destination array.
        If c = 1 Then
            drCount = jArr(c, 2).Count * dStep - 1
            ReDim dData(1 To drCount, 1 To cCount)
        End If
        For sr = 1 To drCount Step dStep
            dData(sr, c) = jArr(c, 2)(Int(sr / dStep) + 1)
        Next sr
        Set jArr(c, 2) = Nothing
    Next c

    ' Write the values from the destination array to the range and clear below.
    With srg.Resize(drCount)
        .Value = dData
        .Resize(ws.Rows.Count - .Row - drCount + 1).Offset(drCount).Clear
    End With

End Sub
```

Body:
My Intention:

I wanna select all values in Rows "B" and "C" and move these 1 and 2 steps up.

The Example for what I have:

A
B
C

AA

Two

AA

Three

Two

AA

Three

Two

Three

X

yy

CC

The Example for what I would: If in Column-A find "X" should YY and CC delet

A
B
C

AA
Two
Three

AA
Two
Three

AA
Two
Three

My Code:

Sub test()

ActiveSheet.Select
Range("B:B").Select Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove
Range("C:C").Select Shift:=xlUp, CopyOrigin:=xlFormatFromLeftOrAbove

End Sub

I would be happy if somebody help me


问:
Understand the use of dx and dy commands in NetLogo?
I'm new to NetLogo and I'm in doubt about 2 Netlogo commands.

Could someone help me understand the dx and dy commands? I read the description in the NetLogo dictionary. But, I didn't quite understand what it does.

What's the difference between using a move with dx and dy and without?

Thanks in advance!

A simplified example taken from a book with application in NetLogo:

```<code>turtles-own
[
  real_x ;; the real x coordinate dist from origin ie ignoring wrapping around world
  real_y ;; the real y coordinate dist from origin ie ignoring wrapping around world
]

to setup
  here
  create-turtles 1
  ask turtles
  [
    setxy random-xcor random-ycor
   ; set real-x xcor
   ; set real-y ycor
  ]
  reset ticks
end

to go
  move
  tick
end

to move
  ;; using dy and dx
  ; ask turtles
  ; [
  ; set heading random-float 360
  ; set real_x real_x + dx
  ; set real_y real_y + dy
  ; fd 1
  ; ]

   ask turtles
  [
    set heading random-float 360
    fd 1
  ]
end
</code>```

答:
dx is the difference in the x-coordinate if the turtle move forward 1 unit at its current heading. Same thing for dy and the y-coordinate.

Mathematically: tan(heading) = dy/dx

Geometrically:

Body:
I'm new to NetLogo and I'm in doubt about 2 Netlogo commands.

Could someone help me understand the dx and dy commands? I read the description in the NetLogo dictionary. But, I didn't quite understand what it does.

What's the difference between using a move with dx and dy and without?

Thanks in advance!

A simplified example taken from a book with application in NetLogo:

turtles-own
[
  real_x ;; the real x coordinate dist from origin ie ignoring wrapping around world
  real_y ;; the real y coordinate dist from origin ie ignoring wrapping around world
]

to setup
  here
  create-turtles 1
  ask turtles
  [
    setxy random-xcor random-ycor
   ; set real-x xcor
   ; set real-y ycor
  ]
  reset ticks
end

to go
  move
  tick
end

to move
  ;; using dy and dx
  ; ask turtles
  ; [
  ; set heading random-float 360
  ; set real_x real_x + dx
  ; set real_y real_y + dy
  ; fd 1
  ; ]

   ask turtles
  [
    set heading random-float 360
    fd 1
  ]
end


问:
How To Save Canvas As An Image With canvas.toDataURL()?
I'm currently building a HTML5 web app/Phonegap native app and I can't seem to figure out how to save my canvas as an image with canvas.toDataURL(). Can somebody help me out?

Here's the code, what's wrong with it?

//My canvas was named "canvasSignature"

JavaScript:

```<code>function putImage()
{
  var canvas1 = document.getElementById("canvasSignature");
  if (canvas1.getContext) {
     var ctx = canvas1.getContext("2d");
     var myImage = canvas1.toDataURL("image/png");
  }
  var imageElement = document.getElementById("MyPix");
  imageElement.src = myImage;

}
</code>```

HTML5:

```<code><div id="createPNGButton">
    <button onclick="putImage()">Save as Image</button>
</div>
</code>```

答:
One can also use element reference to downloaded image:

HTML:

```<code><a download style="display:none" ref="imageDownloadRef"></a>
</code>```

JAVASCRIPT:

```<code>  this.$refs['imageDownloadRef'].href = this.canvas.toDataURL({
  format: 'jpeg',
  quality: 1.0,
  })
  const imageDownloadLink = this.$refs.imageDownloadRef as HTMLElement
  imageDownloadLink.click()
</code>```

Body:
I'm currently building a HTML5 web app/Phonegap native app and I can't seem to figure out how to save my canvas as an image with canvas.toDataURL(). Can somebody help me out?

Here's the code, what's wrong with it?

//My canvas was named "canvasSignature"

JavaScript:

function putImage()
{
  var canvas1 = document.getElementById("canvasSignature");
  if (canvas1.getContext) {
     var ctx = canvas1.getContext("2d");
     var myImage = canvas1.toDataURL("image/png");
  }
  var imageElement = document.getElementById("MyPix");
  imageElement.src = myImage;

}

HTML5:

    <button onclick="putImage()">Save as Image</button>

Body:
One can also use element reference to downloaded image:

HTML:

<a download style="display:none" ref="imageDownloadRef"></a>

JAVASCRIPT:

  this.$refs['imageDownloadRef'].href = this.canvas.toDataURL({
  format: 'jpeg',
  quality: 1.0,
  })
  const imageDownloadLink = this.$refs.imageDownloadRef as HTMLElement
  imageDownloadLink.click()


问:
Round trip through cv::dft() and cv::DFT_INVERSE leads to doubling magnitude of 1d samples
I'm playing with some toy code, to try to verify that I understand how discrete fourier transforms work in OpenCV.  I've found a rather perplexing case, and I believe the reason is that the flags I'm calling cv::dft() with, are incorrect.

I start with a 1-dimensional array of real-valued (e.g. audio) samples.  (Stored in a cv::Mat as a column.)

I use cv::dft() to get a complex-valued array of fourier buckets.

I use cv::dft(), with cv::DFT_INVERSE, to convert it back.

I do this several times, printing the results.  The results seem to be the correct shape but the wrong magnitude.

Code:

```<code>cv::Mat samples(1, 2, CV_64F);
samples.at<double>(0, 0) = -1;
samples.at<double>(0, 1) = 1;
std::cout << "samples(" << samples.type() << "):" << samples << std::endl;
for (int i = 0; i < 3; ++i) {
  cv::Mat buckets;
  cv::dft(samples, buckets, cv::DFT_COMPLEX_OUTPUT);
  samples = cv::Mat();
  cv::dft(buckets, samples,
          cv::DFT_INVERSE | cv::DFT_COMPLEX_INPUT | cv::DFT_REAL_OUTPUT);

  std::cout << "buckets(" << buckets.type() << "):" << buckets << std::endl;
  std::cout << "samples(" << samples.type() << "):" << samples << std::endl;
}
</code>```

Output:

```<code>samples(6):[-1, 1]
buckets(14):[0, 0, -2, 0]
samples(6):[-2, 2]
buckets(14):[0, 0, -4, 0]
samples(6):[-4, 4]
buckets(14):[0, 0, -8, 0]
samples(6):[-8, 8]
</code>```

I would have expected the above output to repeat.  E.g. [-1, 1], [0, 0, -1, 0], ....  Instead, the magnitude is doubling on each round-trip.

Is my understanding wrong?  Or am I using the wrong flags?  Etc.

答:
The inverse DFT in opencv will not scale the result by default, so you get your input times the length of the array.
This is a common optimization, because the scaling is not always needed and the most efficient algorithms for the inverse DFT just use the forward DFT which does not produce the scaling.
You can solve this by adding the cv::DFT_SCALE flag to your inverse DFT.

Some libraries scale both forward and backward transformation with 1/sqrt(N), so it is often useful to check the documentation (or write quick test code) when working with Fourier Transformations.

Body:
I'm playing with some toy code, to try to verify that I understand how discrete fourier transforms work in OpenCV.  I've found a rather perplexing case, and I believe the reason is that the flags I'm calling cv::dft() with, are incorrect.

I start with a 1-dimensional array of real-valued (e.g. audio) samples.  (Stored in a cv::Mat as a column.)

I use cv::dft() to get a complex-valued array of fourier buckets.

I use cv::dft(), with cv::DFT_INVERSE, to convert it back.

I do this several times, printing the results.  The results seem to be the correct shape but the wrong magnitude.

Code:

cv::Mat samples(1, 2, CV_64F);
samples.at<double>(0, 0) = -1;
samples.at<double>(0, 1) = 1;
std::cout << "samples(" << samples.type() << "):" << samples << std::endl;
for (int i = 0; i < 3; ++i) {
  cv::Mat buckets;
  cv::dft(samples, buckets, cv::DFT_COMPLEX_OUTPUT);
  samples = cv::Mat();
  cv::dft(buckets, samples,
          cv::DFT_INVERSE | cv::DFT_COMPLEX_INPUT | cv::DFT_REAL_OUTPUT);

  std::cout << "buckets(" << buckets.type() << "):" << buckets << std::endl;
  std::cout << "samples(" << samples.type() << "):" << samples << std::endl;
}

Output:

samples(6):[-1, 1]
buckets(14):[0, 0, -2, 0]
samples(6):[-2, 2]
buckets(14):[0, 0, -4, 0]
samples(6):[-4, 4]
buckets(14):[0, 0, -8, 0]
samples(6):[-8, 8]

I would have expected the above output to repeat.  E.g. [-1, 1], [0, 0, -1, 0], ....  Instead, the magnitude is doubling on each round-trip.

Is my understanding wrong?  Or am I using the wrong flags?  Etc.


问:
How would I be able to give a GUI a username, then have it affect a dummy avatar via changing it to that users avatar?
I'm making a ROBLOX FNaF 6 True Ending, but you can enter player names and make them replace the burning animatronics.

https://www.roblox.com/games/8281431812/d4dj-meme

Pretty much like the game above ^^.

the thing

答: i'm not sure if you're still looking for an answer, but you could easily do this by creating a remoteevent then firing it after a player enters the required information in a gui</p>


问:
"Content type 'application/json;charset=UTF-8' not supported" in Spring Rest application
When I do a POST request on localhost:8080/api/users to create a new user I get the following error :

```<code>{
    "timestamp": "2018-05-28T09:44:55.704+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/json;charset=UTF-8' not supported",
    "path": "/api/users/"
}
</code>```

Here is the request's body, JSON (application/json) is selected.

It gives the same error even if I remove the Roles and keep it null.

The header's content type is application/json as well.

This is my controller :

```<code>@PostMapping("/api/users" )
public User createUser(@Valid @RequestBody User user) {
    securityService.autologin(user.getUsername(), user.getPassword());
    return userService.createUser(user);
}
</code>```

createUser function in UserService :

```<code>public User createUser(@Valid @RequestBody User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setRoles(new HashSet<>(roleRepository.findAll()));
    return userRepository.save(user);
}
</code>```

edit

This is my User class :

```<code>@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
                      allowGetters = true)
public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

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

    @Column(name = "user_name")
    private String name;

    @Column(name = "user_email")
    private String email;

    @Column(name = "user_password")
    @NotBlank
    private String password;

    @Column(name = "user_status")
    private String status;

    @Column(name = "user_tel")
    private String tel;

    @Column(name = "user_confirmation")
    private String confirmation;

    @Column(name = "user_birth_date")
    @Temporal(TemporalType.DATE)
    private Date birth_date;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    @JsonManagedReference
    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    @Column(name = "username")
    @NotBlank
    private String username;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getConfirmation() {
        return confirmation;
    }

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public Date getBirth_date() {
        return birth_date;
    }

    public void setBirth_date(Date birth_date) {
        this.birth_date = birth_date;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}
</code>```

答: Try removing charset from header Content-type, application json only, and it will probably work.</p>

Body:
When I do a POST request on localhost:8080/api/users to create a new user I get the following error :

{
    "timestamp": "2018-05-28T09:44:55.704+0000",
    "status": 415,
    "error": "Unsupported Media Type",
    "message": "Content type 'application/json;charset=UTF-8' not supported",
    "path": "/api/users/"
}

Here is the request's body, JSON (application/json) is selected.

It gives the same error even if I remove the Roles and keep it null.

The header's content type is application/json as well.

This is my controller :

@PostMapping("/api/users" )
public User createUser(@Valid @RequestBody User user) {
    securityService.autologin(user.getUsername(), user.getPassword());
    return userService.createUser(user);
}

createUser function in UserService :

public User createUser(@Valid @RequestBody User user) {
    user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
    user.setRoles(new HashSet<>(roleRepository.findAll()));
    return userRepository.save(user);
}

edit

This is my User class :

@Entity
@Table(name = "user")
@EntityListeners(AuditingEntityListener.class)
@JsonIgnoreProperties(value = {"createdAt", "updatedAt"},
                      allowGetters = true)
public class User implements Serializable{

    private static final long serialVersionUID = 1L;

    public User() {
        super();
        // TODO Auto-generated constructor stub
    }

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

    @Column(name = "user_name")
    private String name;

    @Column(name = "user_email")
    private String email;

    @Column(name = "user_password")
    @NotBlank
    private String password;

    @Column(name = "user_status")
    private String status;

    @Column(name = "user_tel")
    private String tel;

    @Column(name = "user_confirmation")
    private String confirmation;

    @Column(name = "user_birth_date")
    @Temporal(TemporalType.DATE)
    private Date birth_date;

    @Column(nullable = false, updatable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @CreatedDate
    private Date createdAt;

    @Column(nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    @LastModifiedDate
    private Date updatedAt;

    @JsonManagedReference
    @ManyToMany
    @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles;

    @Column(name = "username")
    @NotBlank
    private String username;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getConfirmation() {
        return confirmation;
    }

    public void setConfirmation(String confirmation) {
        this.confirmation = confirmation;
    }

    public Date getBirth_date() {
        return birth_date;
    }

    public void setBirth_date(Date birth_date) {
        this.birth_date = birth_date;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public Date getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(Date updatedAt) {
        this.updatedAt = updatedAt;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}


问:
Trying to make a discord but I keep getting the error "required is not defined"
I'm really new at this and I'm trying to get the bot to come online but no matter what I do the error message comes up, I also downloaded requirejs but it doesn't seem to be working. basically, I have no idea what I'm doing and need help.</p>
```<code>const {Clients, Intents} = require(discord.js);
const TOKEN = '************************************************'
const client = new Client({
    intents: [
        Inents.FLAGS.GUILDS,
        Intents.FLags.GUILD_MESSAGES,
    ]
});

client.once('ready', () => {
    console.log('Logged in as ${client.user.tag}')
});
client.login(TOKEN);
</code>```

答:
A couple things. Don't give out your token on public websites. Discord has probably dmed you saying you gave out your token here, but still. I'd recommend creating a .env file with the 'dotenv' package (if you know what that is.) just to keep your token private.

On your 5th line, Intents has a typo, it says Inents. So, make sure that's fixed, and same with the 6th line. It should be FLAGS not FLags

The reason "require" isn't defined is because you need to put discord.js in quotations like this.

const {Clients, Intents} = require('discord.js');

If you have any other errors, feel free to reply with it. Have a great day.

Body:
I'm really new at this and I'm trying to get the bot to come online but no matter what I do the error message comes up, I also downloaded requirejs but it doesn't seem to be working. basically, I have no idea what I'm doing and need help.

const {Clients, Intents} = require(discord.js);
const TOKEN = '************************************************'
const client = new Client({
    intents: [
        Inents.FLAGS.GUILDS,
        Intents.FLags.GUILD_MESSAGES,
    ]
});

client.once('ready', () => {
    console.log('Logged in as ${client.user.tag}')
});
client.login(TOKEN);


问:
How to implement mongoose discriminators?
I want to use mongoose discriminator for my project to create a collection of users in which there is a document of owner which I want to implement using discriminators. But I am getting an error of

throw new Error('The 2nd parameter to mongoose.model() should be a ' +
^

Error: The 2nd parameter to mongoose.model() should be a schema or a POJO
at Mongoose.model (D:\Github\Food-Delivery-Website\node_modules\mongoose\lib\index.js:473:11)
at Object. (D:\Github\Food-Delivery-Website\models\Owner.js:21:27)

Code is given below:

```<code>// This file is models/User.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const options = { discriminatorKey: 'kind' };

const UserSchema = new Schema(
  {
    userName: {
      type: String,
      required: true,
      unique: true,
    },
    restOwned: {
      // type: [Schema.Types.ObjectId],
      type: Number,
    },
  },
  options,
);

module.exports = mongoose.model('User', UserSchema);
</code>```

Below is the next file

```<code>// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

const OwnerSchema = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

module.exports = mongoose.model('Owner', OwnerSchema);
</code>```

Then I import these two files in userController.js

```<code>//This file is controllers/userController.js

const User = require('../models/User');
const Owner = require('../models/Owner');

exports.addUser = async (req, res) => {
  try {
    const newUser = new User({
      userName: req.body.userName,
      restOwned: req.body.restOwned,
    });

    const user = await newUser.save();

    res.status(201).json({
      status: 'Success',
      user,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};

exports.addOwner = async (req, res) => {
  try {
    const newOwner = new Owner({
      isOwner: req.body.isOwner,
      restName: req.body.restName,
    });

    const owner = await newOwner.save();

    res.status(201).json({
      status: 'Success',
      owner,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};
</code>```

What am I doing wrong here?

enter image description here

答:
The Model.discriminator() method returns a Model.

So you can directly export the discriminator and use it as the model

```<code>// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

//Directly export the discriminator and use it as the model
module.exports = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

//module.exports = mongoose.model('Owner', OwnerSchema);
</code>```

Body:
I want to use mongoose discriminator for my project to create a collection of users in which there is a document of owner which I want to implement using discriminators. But I am getting an error of

throw new Error('The 2nd parameter to mongoose.model() should be a ' +
^

Error: The 2nd parameter to mongoose.model() should be a schema or a POJO
at Mongoose.model (D:\Github\Food-Delivery-Website\node_modules\mongoose\lib\index.js:473:11)
at Object. (D:\Github\Food-Delivery-Website\models\Owner.js:21:27)

Code is given below:

// This file is models/User.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const options = { discriminatorKey: 'kind' };

const UserSchema = new Schema(
  {
    userName: {
      type: String,
      required: true,
      unique: true,
    },
    restOwned: {
      // type: [Schema.Types.ObjectId],
      type: Number,
    },
  },
  options,
);

module.exports = mongoose.model('User', UserSchema);

Below is the next file

// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

const OwnerSchema = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

module.exports = mongoose.model('Owner', OwnerSchema);

Then I import these two files in userController.js

//This file is controllers/userController.js

const User = require('../models/User');
const Owner = require('../models/Owner');

exports.addUser = async (req, res) => {
  try {
    const newUser = new User({
      userName: req.body.userName,
      restOwned: req.body.restOwned,
    });

    const user = await newUser.save();

    res.status(201).json({
      status: 'Success',
      user,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};

exports.addOwner = async (req, res) => {
  try {
    const newOwner = new Owner({
      isOwner: req.body.isOwner,
      restName: req.body.restName,
    });

    const owner = await newOwner.save();

    res.status(201).json({
      status: 'Success',
      owner,
    });
  } catch (err) {
    res.status(500).json({
      status: 'failed',
      message: 'Server Error: Failed Storing the Data.',
      err,
    });
  }
};

What am I doing wrong here?

enter image description here

Body:
The Model.discriminator() method returns a Model.

So you can directly export the discriminator and use it as the model

// This file is models/Owner.js
const mongoose = require('mongoose');
const { Schema } = mongoose;

const User = require('./User');

//Directly export the discriminator and use it as the model
module.exports = User.discriminator(
  'Owner',
  new Schema({
    isOwner: {
      type: Boolean,
      required: true,
    },
    restName: {
      type: String,
      required: true,
    },
  }),
);

//module.exports = mongoose.model('Owner', OwnerSchema);


问:
My Python Script can't find a JSON file in the same directory
I am practicing some API work in python 3.7 using API star 0.5.X and my python script can't find the .json file that is in the same folder as the python file.  I am working on and running the script with Atom editor and I am working in a venv, which is fairly new to me.

I am using a helper function to load in the JSON data using a "with open()" statement.  I have tried using the relative and absolute file paths, and in both instances it is unable to locate the file.  I have tried launching the file in Atom using terminal and the MacOS finder.
This is what I have so far:

```<code>import json
from typing import List
import os
from apistar import App, Route, types, validators
from apistar.http import JSONResponse

print(os.getcwd())
os.chdir('/Users/{myusernamehere}/100days/apistar')
print(os.getcwd())

#helpers
def _load_employee_data():
   with open('employees.json') as f:
       employees = json.loads(f.read())
       return employees
</code>```

the second print statement prints the correct file path, being the one that 'employees.json' and 'app.py' are located in.

答:
Okay, So i had the same issue with i.c.w. VScode :

```<code>file = open('file.txt')
print(file.name)
</code>```

resulted in
FileNotFoundError

file.txt was 100% in the same folder... According to finder on my Mac, ánd the folder column in VS code!

i was pulling out my hair. Switched a lot of interpreters, local python and Conda, to Python 3.8 instead of 3.9, back to python 2.8.
Nothing mattered.

Till I changed :
file = open('file.txt') to: file = open('file.txt', 'a')
It didn't suddenly work, but I saw immediately in the "folder column" of VScode a new file.txt file popping up. In an entirely different folder then where the pythonfile.py was located. So after that; I pushed all local repo's to their remotes; deleted the whole caboodle, and installed them one by one in a new folder through git clone. I opened a new workspace added those project folders and since then it works like a charm.

What exactly went wrong ; im sorry, I have no idea. But for me, a fresh install of the repo's and VScode workspace is what did the trick.

Body:
I am practicing some API work in python 3.7 using API star 0.5.X and my python script can't find the .json file that is in the same folder as the python file.  I am working on and running the script with Atom editor and I am working in a venv, which is fairly new to me.

I am using a helper function to load in the JSON data using a "with open()" statement.  I have tried using the relative and absolute file paths, and in both instances it is unable to locate the file.  I have tried launching the file in Atom using terminal and the MacOS finder.
This is what I have so far:

import json
from typing import List
import os
from apistar import App, Route, types, validators
from apistar.http import JSONResponse

print(os.getcwd())
os.chdir('/Users/{myusernamehere}/100days/apistar')
print(os.getcwd())

#helpers
def _load_employee_data():
   with open('employees.json') as f:
       employees = json.loads(f.read())
       return employees

the second print statement prints the correct file path, being the one that 'employees.json' and 'app.py' are located in.

Body:
Okay, So i had the same issue with i.c.w. VScode :

file = open('file.txt')
print(file.name)

resulted in
FileNotFoundError

file.txt was 100% in the same folder... According to finder on my Mac, ánd the folder column in VS code!

i was pulling out my hair. Switched a lot of interpreters, local python and Conda, to Python 3.8 instead of 3.9, back to python 2.8.
Nothing mattered.

Till I changed :
file = open('file.txt') to: file = open('file.txt', 'a')
It didn't suddenly work, but I saw immediately in the "folder column" of VScode a new file.txt file popping up. In an entirely different folder then where the pythonfile.py was located. So after that; I pushed all local repo's to their remotes; deleted the whole caboodle, and installed them one by one in a new folder through git clone. I opened a new workspace added those project folders and since then it works like a charm.

What exactly went wrong ; im sorry, I have no idea. But for me, a fresh install of the repo's and VScode workspace is what did the trick.


问:
Regex Pattern for checking the first letter of each word in a string if its Uppercase in Javascript
for example my string is Foo Bar.
this string should match the pattern.

if the string is Foo bar.
the string should not match.

if the string is Foo Bar Foobar
the string should match

if the string is Foo. it should also match.

so far I only have this pattern

```<code> (^[A-Z]{1}.*(\s)?$)+
</code>```

Basically I will only accept a string where each First letter of each word is Uppercase

答:
I used this:

/(^[a-z]| [a-z])/ig

Body:
for example my string is Foo Bar.
this string should match the pattern.

if the string is Foo bar.
the string should not match.

if the string is Foo Bar Foobar
the string should match

if the string is Foo. it should also match.

so far I only have this pattern

 (^[A-Z]{1}.*(\s)?$)+

Basically I will only accept a string where each First letter of each word is Uppercase

Body:
I used this:

/(^[a-z]| [a-z])/ig


问:
Xcode 12 & SwiftUI: Cannot preview in this file — Failed to update preview
Seems like previews stopped working on Xcode 12! Trying to preview the SwiftUI file template and getting the error below. Any ideas how to fix this? Tried cleaning the build folder, deleting derived data and restarting Xcode to no avail!

On Catalina 10.15.6.

```<code>RemoteHumanReadableError: Failed to update preview.

The preview process appears to have crashed.

Error encountered when sending 'prepare' message to agent.

==================================

|  RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)
|
|  BSServiceConnectionErrorDomain (3):
|  ==BSErrorCodeDescription: OperationFailed
</code>```

The code I am trying to preview (from SwiftUI new file template):

```<code>import SwiftUI

struct SwiftUIView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}
</code>```

答: I managed to solve this problem. It is enough to comment everything in the didFinishLaunchingWithOptions method. Then when you preview SwiftUI it will work.

Body:
Seems like previews stopped working on Xcode 12! Trying to preview the SwiftUI file template and getting the error below. Any ideas how to fix this? Tried cleaning the build folder, deleting derived data and restarting Xcode to no avail!

On Catalina 10.15.6.

RemoteHumanReadableError: Failed to update preview.

The preview process appears to have crashed.

Error encountered when sending 'prepare' message to agent.

==================================

|  RemoteHumanReadableError: The operation couldn’t be completed. (BSServiceConnectionErrorDomain error 3.)
|
|  BSServiceConnectionErrorDomain (3):
|  ==BSErrorCodeDescription: OperationFailed

The code I am trying to preview (from SwiftUI new file template):

import SwiftUI

struct SwiftUIView: View {
    var body: some View {
        Text("Hello, World!")
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }
}


问:
Passing <textarea> string to Bootstrap Modal using Javascript
Learning Javascript and trying to learn how to pass values. In this example, I have a  where a user types a message, for example, and that string is stored and displayed in a Bootstrap Modal. The problem...the last character is cut off unless you press return or spacebar. I have tried adding an empty space at the end of my document.getElementById (line 38)...tried adding a carriage return and new line....I have found several very simple Jquery solutions but it would be nice if I could figure this one out using JS first. Or maybe I should just switch the script to JQuery? I also know my character count isn't working correctly but I'll figure that out later.

Thanks!

//Write a function that shows how many characters are left in the textarea
function charCount() {

//Retrieve the stored value of the string from textarea
var txt = document.getElementById("text-area").value;

//Determine how many characters are in the textarea
var chars = txt.length;

//Subtract the max number of characters from the number of characters entered
var maxLength = 140-chars;

//Show how many characters remain in textarea
document.getElementById("char-count").innerHTML = maxLength + " characters remaining";

//Write textarea string to modal
document.getElementById("modal-body").innerHTML = txt + " ";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Textarea -->
        <div class="row">
          <div class="col-xl-12">
            <textarea id="text-area" maxlength="140" onkeypress="charCount()"></textarea>
          </div>
        </div>
        <div class="row">
          <div class="col-1">
            <button class="btn btn-secondary d-inline" data-bs-toggle="modal" data-bs-target="#myModal">Submit</button>

          </div>
          <div class="col">
            <div id="char-count"><!--140 Characters Remaining--></div>
          </div>
        </div>
        <div class="modal" id="myModal">
          <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">

              <!-- Modal Header -->
              <div class="modal-header">
                <h4 class="modal-title">Your Message:</h4>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>

              <!-- Modal body -->
              <div class="modal-body" id="modal-body">

              </div>

              <!-- Modal footer -->
              <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>
              </div>

            </div>
          </div>
        </div></code>```

答:
According to MDN (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeypress), the onkeypress event handler has been deprecated.

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes

So, in order to avoid the cut of the last character, you can use the onkeyup event handler, which fires when the user releases a key that was previously pressed.

<textarea id="text-area" maxlength="140" onkeyup="charCount()"></textarea>
```

Fiddle: https://jsfiddle.net/kongallis/e087vdgL/12/

Body:
Learning Javascript and trying to learn how to pass values. In this example, I have a  where a user types a message, for example, and that string is stored and displayed in a Bootstrap Modal. The problem...the last character is cut off unless you press return or spacebar. I have tried adding an empty space at the end of my document.getElementById (line 38)...tried adding a carriage return and new line....I have found several very simple Jquery solutions but it would be nice if I could figure this one out using JS first. Or maybe I should just switch the script to JQuery? I also know my character count isn't working correctly but I'll figure that out later.

Thanks!

//Write a function that shows how many characters are left in the textarea
function charCount() {

//Retrieve the stored value of the string from textarea
var txt = document.getElementById("text-area").value;

//Determine how many characters are in the textarea
var chars = txt.length;

//Subtract the max number of characters from the number of characters entered
var maxLength = 140-chars;

//Show how many characters remain in textarea
document.getElementById("char-count").innerHTML = maxLength + " characters remaining";

//Write textarea string to modal
document.getElementById("modal-body").innerHTML = txt + " ";
}

            <textarea id="text-area" maxlength="140" onkeypress="charCount()"></textarea>

            <button class="btn btn-secondary d-inline" data-bs-toggle="modal" data-bs-target="#myModal">Submit</button>

Your Message:

                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>

                <button type="button" class="btn btn-danger" data-bs-dismiss="modal">Close</button>

Body:
According to MDN (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeypress), the onkeypress event handler has been deprecated.

Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes

So, in order to avoid the cut of the last character, you can use the onkeyup event handler, which fires when the user releases a key that was previously pressed.

<textarea id="text-area" maxlength="140" onkeyup="charCount()"></textarea>

Fiddle: https://jsfiddle.net/kongallis/e087vdgL/12/


问:
using Jquery to get page content each second
How is the right way to get page content each second?
I have one page which got a music player (using flash player) and other that generates the name of the song(php file). I have set the php file to ECHO only the name, so the only thing is to get that echo and put it at main page where is the player. But it must refresh each second(or 2-3max) because the songs are changing and so are the names.
I hope you can understand my need , ask me for other details if you need.</p>

答:
I wouldnt advise using setInterval with an AJAX request, as if an ajax request is taking a long time to respond, then it will still keep sending subsequent requests. Instead I would have a complete callback which triggered the next setTimeout, e.g:</p>

```<code>function setRefreshTimeout() {
    setTimeout(loadSongs, 1000);
}

function loadSongs() {
    $('#title').load('/songtitle.php', function() {
        setRefreshTimeout();
    });
}

setRefreshTimeout();
</code>```

Body:
I wouldnt advise using setInterval with an AJAX request, as if an ajax request is taking a long time to respond, then it will still keep sending subsequent requests. Instead I would have a complete callback which triggered the next setTimeout, e.g:

function setRefreshTimeout() {
    setTimeout(loadSongs, 1000);
}

function loadSongs() {
    $('#title').load('/songtitle.php', function() {
        setRefreshTimeout();
    });
}

setRefreshTimeout();


问:
Duplicate instance returned in QuerySet
I'm attempting to create a method that filters questions based on tags which are only found in a particular user's questions. There is an issue with the QuerySet where it returns Queryset([Question13, Question 14, Question13]). Yet when the .distinct() is added it returns the desired result of QuerySet([Question13, Question 14]).

Why does the second chained .filter() method add the duplicate instance in the QuerySet?

```<code>class Post(Model):

    body = TextField()
    date = DateField(default=date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    score = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )

    class Meta:
        abstract = True

class Question(Post):

    title = CharField(max_length=75)
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    objects = Manager()
    postings = QuestionSearchManager()

</code>```
```<code>class QuestionSearchManager(Manager):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def by_week(self, profile):
        today = date.today()
        weekago = today - timedelta(days=7)
        queryset = self.get_queryset().filter(
            date__range=(weekago, today)
        ).filter(tags__name__in=profile.questions.values_list(
            "tags__name", flat=True
        ))
        return queryset
</code>```

postings.json

```<code>{
    "model": "posts.question",
    "pk": 13,
    "fields": {
        "body": "Content of Question 005",
        "date": "2022-02-12",
        "comment": null,
        "profile": 2,
        "title": "Question__005",
        "tags": [
            1,
            7
        ]
    }
},
{
    "model": "posts.question",
    "pk": 14,
    "fields": {
        "body": "Content of Question 006",
        "date": "2022-02-12",
        "comment": null,
        "profile": 3,
        "title": "Question__006",
        "tags": [
            1,
            2
        ]
    }
}
</code>```

答:
This baffled me for a while also, but it is because of the related tags if the filter references multiple tags and those tags's property name you are now going to return a row per tag reference

distinct is your best friend when filtering using this tags__name style query.

No doubt that because it's a many to many relationship, this will be a common thing you need to be aware of when filtering on that relationship.

This is similar to this question:
Logical or of Django many to many queries returns duplicate results

You can also read this section of Django's docs to get a better idea how their queries work:
https://docs.djangoproject.com/en/4.0/topics/db/queries/#spanning-multi-valued-relationships

Title: Duplicate instance returned in QuerySet

Body:
I'm attempting to create a method that filters questions based on tags which are only found in a particular user's questions. There is an issue with the QuerySet where it returns Queryset([Question13, Question 14, Question13]). Yet when the .distinct() is added it returns the desired result of QuerySet([Question13, Question 14]).

Why does the second chained .filter() method add the duplicate instance in the QuerySet?

class Post(Model):

    body = TextField()
    date = DateField(default=date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    score = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )

    class Meta:
        abstract = True

class Question(Post):

    title = CharField(max_length=75)
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    objects = Manager()
    postings = QuestionSearchManager()

class QuestionSearchManager(Manager):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def by_week(self, profile):
        today = date.today()
        weekago = today - timedelta(days=7)
        queryset = self.get_queryset().filter(
            date__range=(weekago, today)
        ).filter(tags__name__in=profile.questions.values_list(
            "tags__name", flat=True
        ))
        return queryset

postings.json

{
    "model": "posts.question",
    "pk": 13,
    "fields": {
        "body": "Content of Question 005",
        "date": "2022-02-12",
        "comment": null,
        "profile": 2,
        "title": "Question__005",
        "tags": [
            1,
            7
        ]
    }
},
{
    "model": "posts.question",
    "pk": 14,
    "fields": {
        "body": "Content of Question 006",
        "date": "2022-02-12",
        "comment": null,
        "profile": 3,
        "title": "Question__006",
        "tags": [
            1,
            2
        ]
    }
}


问:
Landing page URL should be redirected to "/home"
Current landing page URL after login - 'www.website.com'. But I want it to be redirected to "www.website.com/home" upon login. So it has to be redirected to home component.</p>

答: Maybe you can just change your path from "/" to "/home"?</p>


问:
Depth First Search in Prolog
```<code>subtrees([]).
subtrees([(Cost,T)|Rest]) :−
   number(Cost),
   istree(T),
   subtrees(Rest).

istree(tree(_,Children)) :− subtrees(Children).

dfs(GoalValue,tree(GoalValue,_),GoalValue,0).
dfs(GoalValue,tree(Value,[(Cost,T)|Rest]),Path,FinalCost) :−
   T = tree(IV,_),
   write(IV ),
   dfs(GoalValue, T,P,C),
   string_concat(Value,P,Path),
   FinalCost is C+Cost
; % go down one depth level
   dfs(GoalValue,tree(Value,Rest),Path,FinalCost). % next child
</code>```

Can someone help me understand this Prolog implementation of Depth First Search? A subpart of my question also includes how to interpret splitting within the Head part.

subtrees([(Cost,T)|Rest])

I am aware that each list is considered [Heads|Tails], but how does one interpret (Cost, T )? Is it a 2D list?

答:
The builtin predicate write_canonical/1 is very useful for interpreting terms as it will remove syntactic sugar. So for your query:

```<code>?- write_canonical(subtrees([(Cost,T)|Rest])).
subtrees('.'(','(Cost, T), Rest)).
</code>```

This means you have a subtrees/1 predicate that contains a list (a list without syntactic sugar is: '.'(Head, Tail)). The first element of that list is the term ','(Cost, T):

```<code>?- write_canonical((Cost, T)).
','(Cost, T)
</code>```

This kind of ','/2 term is actually a Prolog conjunctive clause. It appears the author is abusing the homoiconic nature of Prolog here to mimic a tuple, which becomes inefficient for "tuples" with a length greater than 2 ((a, b, c) is actually ','(a, ',',(b, c)); better with an unnested term like f(a, b, c)), and so is best to avoid. The reading of (Cost, T) is "Cost and T".

Title: Depth First Search in Prolog

Body:
subtrees([]).
subtrees([(Cost,T)|Rest]) :−
   number(Cost),
   istree(T),
   subtrees(Rest).

istree(tree(_,Children)) :− subtrees(Children).

dfs(GoalValue,tree(GoalValue,_),GoalValue,0).
dfs(GoalValue,tree(Value,[(Cost,T)|Rest]),Path,FinalCost) :−
   T = tree(IV,_),
   write(IV ),
   dfs(GoalValue, T,P,C),
   string_concat(Value,P,Path),
   FinalCost is C+Cost
; % go down one depth level
   dfs(GoalValue,tree(Value,Rest),Path,FinalCost). % next child

Can someone help me understand this Prolog implementation of Depth First Search? A subpart of my question also includes how to interpret splitting within the Head part.

subtrees([(Cost,T)|Rest])

I am aware that each list is considered [Heads|Tails], but how does one interpret (Cost, T )? Is it a 2D list?

Body:
The builtin predicate write_canonical/1 is very useful for interpreting terms as it will remove syntactic sugar. So for your query:

?- write_canonical(subtrees([(Cost,T)|Rest])).
subtrees('.'(','(Cost, T), Rest)).

This means you have a subtrees/1 predicate that contains a list (a list without syntactic sugar is: '.'(Head, Tail)). The first element of that list is the term ','(Cost, T):

?- write_canonical((Cost, T)).
','(Cost, T)

This kind of ','/2 term is actually a Prolog conjunctive clause. It appears the author is abusing the homoiconic nature of Prolog here to mimic a tuple, which becomes inefficient for "tuples" with a length greater than 2 ((a, b, c) is actually ','(a, ',',(b, c)); better with an unnested term like f(a, b, c)), and so is best to avoid. The reading of (Cost, T) is "Cost and T".


问:
Hold button -> repeat function
I'm trying to achieve something which souldn't be hard to do, but everything I've tried so far hasn't worked.

I have a function that changes a value every time I click a button, and what I want is: when I hold this button, the value should keep changing.

This is what I've tried and hasn't worked, setInterval and setTimeout won't "wait" (the function get's called right away thousands of times and the website crashes):

```<code>    $('.buttonPlus').mousedown(function() {
        timeoutID =setTimeout(distribucionPorcentual($(this)),1000);
    }).bind('mouseup mouseleave', function() {
        clearTimeout(timeoutID);
    });
</code>```

Any help will be greately appreciated. Thanks!

答:
I know this is a really old thread, but if someone stumbles upon it (I just did), you might find this useful. I needed to be able to do a simple increment, but if the mouse is held for a full second, then it goes into a rapid increment. Which is similar to how a keypress behaves on many systems.</p>
```<code>    $('#forward-step').mousedown(function() {
    adjustPosition(1)
    var cancel = false;
    repeatDelayTimer = setTimeout( function() {
        if (!cancel) {
            repeatTimer = setInterval(function() {adjustPosition(1); },50);
        }
    },1000 )

    t.bind('mouseup mouseleave', function() {
        cancel = true;
        console.log("Mouseup");
        clearInterval(repeatTimer);
        clearTimeout(repeatDelayTimer);
    });
});
</code>```

Title: Hold button -> repeat function

Body:
I'm trying to achieve something which souldn't be hard to do, but everything I've tried so far hasn't worked.

I have a function that changes a value every time I click a button, and what I want is: when I hold this button, the value should keep changing.

This is what I've tried and hasn't worked, setInterval and setTimeout won't "wait" (the function get's called right away thousands of times and the website crashes):

    $('.buttonPlus').mousedown(function() {
        timeoutID =setTimeout(distribucionPorcentual($(this)),1000);
    }).bind('mouseup mouseleave', function() {
        clearTimeout(timeoutID);
    });

Any help will be greately appreciated. Thanks!

Body:
I know this is a really old thread, but if someone stumbles upon it (I just did), you might find this useful. I needed to be able to do a simple increment, but if the mouse is held for a full second, then it goes into a rapid increment. Which is similar to how a keypress behaves on many systems.

    $('#forward-step').mousedown(function() {
    adjustPosition(1)
    var cancel = false;
    repeatDelayTimer = setTimeout( function() {
        if (!cancel) {
            repeatTimer = setInterval(function() {adjustPosition(1); },50);
        }
    },1000 )

    t.bind('mouseup mouseleave', function() {
        cancel = true;
        console.log("Mouseup");
        clearInterval(repeatTimer);
        clearTimeout(repeatDelayTimer);
    });
});


问:
React: Card component share same state
Created RenderCard component which creates multiple cards for given data.

I am creating bulk selection of card means selecting multiple cards. So when user click on circle present at the top left then that circle become check circle

So here the issue is that all card gets selected when user click on any card. So I want only that card select which users click

```<code>const Card = () => {
  const [cardSelect, setCardSelect] = useState(false)
  const onMouseEnter =  () => {
    console.log("onMouseEnter1")
  }

  const onMouseLeave =  () => {
    console.log("onMouseLeave1")
  }

  const logMessage =  () => {
    setCardSelect(prevCheck => !prevCheck);
  }
  const RenderCard = () => {
    return album.map(item => {
      return (
        <Col className='container' onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} key={item.title} md='2'>
          <Card>
            <div>
              <Link to={`/pages/blog/detail/${item.id}`}>
                <CardImg className='img-fluid image' src={item.img} alt={item.title} top />
              </Link>
            </div>
              <div className='select-card'>
              {cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />}
            </div>
            <CardBody>
              <CardTitle className="image2 te" >
                  <b>{item.title}</b>
              </CardTitle>
              <CardText>{item.comment} Comments</CardText>
            </CardBody>
          </Card>
        </Col>
      )
    })
  }
  return (
    <>
      <Row>
        <RenderCard />
      </Row>
    </>
  )
}
</code>```

Anyone can point me in the right direction where I am doing mistakes.

Thanks

答:
With this line of code  :
cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />

You are saying : "If cardSelect is true, then render CheckCircle component, otherwise, render Circle component and do that for all items in album list". So when the state changes, it will render only one type of object CheckCircles, or Circles as many times as there are elements in the album list for which you are calling the map method.

That is why you are seeing all checked circles when you set your variable cardSelect to true.

Title: React: Card component share same state

Body:
Created RenderCard component which creates multiple cards for given data.

I am creating bulk selection of card means selecting multiple cards. So when user click on circle present at the top left then that circle become check circle

So here the issue is that all card gets selected when user click on any card. So I want only that card select which users click

const Card = () => {
  const [cardSelect, setCardSelect] = useState(false)
  const onMouseEnter =  () => {
    console.log("onMouseEnter1")
  }

  const onMouseLeave =  () => {
    console.log("onMouseLeave1")
  }

  const logMessage =  () => {
    setCardSelect(prevCheck => !prevCheck);
  }
  const RenderCard = () => {
    return album.map(item => {
      return (
        <Col className='container' onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} key={item.title} md='2'>
          <Card>

              <Link to={`/pages/blog/detail/${item.id}`}>
                <CardImg className='img-fluid image' src={item.img} alt={item.title} top />
              </Link>

              {cardSelect ? <CheckCircle onClick={logMessage} /> : <Circle onClick={logMessage}  />}

            <CardBody>
              <CardTitle className="image2 te" >
                  {item.title}
              </CardTitle>
              <CardText>{item.comment} Comments</CardText>
            </CardBody>
          </Card>
        </Col>
      )
    })
  }
  return (
    <>
      <Row>
        <RenderCard />
      </Row>
    </>
  )
}

Anyone can point me in the right direction where I am doing mistakes.

Thanks


问:
How can I split an xts object in by-monthly periods?
For example if I create the following xts object:
index <- seq(from = Sys.Date(), by = "day", length.out = 100)
xts_object <- xts(rnorm(100), order.by = index)

I can split into one-month period with the "split" function:
list_object <- split(xts_object, f = "months")

And I can find the endpoints in my index that correspond to the last by-monthly points with "endpoints":
endpoints <- endpoints(xts_object, on = "months", k = 2)

But I how can I split my time series based on those endpoints?

Your help is greatly appreciated!

答:
Ok, I just figured it out. Split also has k argument, so it's straightforward:

```<code>list_object <- split(xts_object, f = "months", k = 2)
</code>```

Body:
Ok, I just figured it out. Split also has k argument, so it's straightforward:

list_object <- split(xts_object, f = "months", k = 2)


问:
Loop to sum weekly rolling average
I am new to coding. I have a data set of daily stream flow averages over 20 years. Following is an example:

```<code>          DATE   FLOW
1    10/1/2001   88.2
2    10/2/2001   77.6
3    10/3/2001   68.4
4    10/4/2001   61.5
5    10/5/2001   55.3
6    10/6/2001   52.5
7    10/7/2001   49.7
8    10/8/2001   46.7
9    10/9/2001   43.3
10  10/10/2001   41.3
11  10/11/2001   39.3
12  10/12/2001   37.7
13  10/13/2001   35.8
14  10/14/2001   34.1
15  10/15/2001   39.8
</code>```

I need to create a loop summing the previous 6 days as well as the current day (rolling weekly average), and print it to an array for the designated water year. I have already created an aggregate function to separate yearly average daily means into their designated water years.

```<code># Separating dates into specific water years

wtr_yr <- function(dates, start_month=9)
  # Convert dates into POSIXlt
  POSIDATE = as.POSIXlt(NEW_DATE)
  # Year offset
  offset = ifelse(POSIDATE$mon >= start_month - 1, 1, 0)
  # Water year
  adj.year = POSIDATE$year + 1900 + offset

# Aggregating the water year function to take the mean

mean.FLOW=aggregate(data_set$FLOW,list(adj.year), mean)
</code>```

答:
It seems that it can be done much more easily.
But first I need to prepare a bit more data.

```<code>library(tidyverse)
library(lubridate)

df = tibble(
  DATE = seq(mdy("1/1/2010"), mdy("12/31/2022"), 1),
  FLOW = rnorm(length(DATE), 40, 10)
)
</code>```

output

```<code># A tibble: 4,748 x 2
   DATE        FLOW
   <date>     <dbl>
 1 2010-01-01  34.4
 2 2010-01-02  37.7
 3 2010-01-03  55.6
 4 2010-01-04  40.7
 5 2010-01-05  41.3
 6 2010-01-06  57.2
 7 2010-01-07  44.6
 8 2010-01-08  27.3
 9 2010-01-09  33.1
10 2010-01-10  35.5
# ... with 4,738 more rows
</code>```

Now let's do the aggregation by year and week number

```<code>df %>%
  group_by(year(DATE), week(DATE)) %>%
  summarise(mean = mean(FLOW))
</code>```

output

```<code># A tibble: 689 x 3
# Groups:   year(DATE) [13]
   `year(DATE)` `week(DATE)`  mean
          <dbl>        <dbl> <dbl>
 1         2010            1  44.5
 2         2010            2  39.6
 3         2010            3  38.5
 4         2010            4  35.3
 5         2010            5  44.1
 6         2010            6  39.4
 7         2010            7  41.3
 8         2010            8  43.9
 9         2010            9  38.5
10         2010           10  42.4
# ... with 679 more rows
</code>```

Note, for the function week, the first week starts on January 1st. If you want to number the weeks according to the ISO 8601 standard, use the isoweek function. Alternatively, you can also use an epiweek compatible with the US CDC.

```<code>df %>%
  group_by(year(DATE), isoweek(DATE)) %>%
  summarise(mean = mean(FLOW))
</code>```

output

```<code># A tibble: 681 x 3
# Groups:   year(DATE) [13]
   `year(DATE)` `isoweek(DATE)`  mean
          <dbl>           <dbl> <dbl>
 1         2010               1  40.0
 2         2010               2  45.5
 3         2010               3  33.2
 4         2010               4  38.9
 5         2010               5  45.0
 6         2010               6  40.7
 7         2010               7  38.5
 8         2010               8  42.5
 9         2010               9  37.1
10         2010              10  42.4
# ... with 671 more rows
</code>```

If you want to better understand how these functions work, please follow the code below

```<code>df %>%
  mutate(
    w1 = week(DATE),
    w2 = isoweek(DATE),
    w3 = epiweek(DATE)
  )
</code>```

output

```<code># A tibble: 4,748 x 5
   DATE        FLOW    w1    w2    w3
   <date>     <dbl> <dbl> <dbl> <dbl>
 1 2010-01-01  34.4     1    53    52
 2 2010-01-02  37.7     1    53    52
 3 2010-01-03  55.6     1    53     1
 4 2010-01-04  40.7     1     1     1
 5 2010-01-05  41.3     1     1     1
 6 2010-01-06  57.2     1     1     1
 7 2010-01-07  44.6     1     1     1
 8 2010-01-08  27.3     2     1     1
 9 2010-01-09  33.1     2     1     1
10 2010-01-10  35.5     2     1     2
# ... with 4,738 more rows
</code>```

Title: Loop to sum weekly rolling average

Body:
I am new to coding. I have a data set of daily stream flow averages over 20 years. Following is an example:

          DATE   FLOW
1    10/1/2001   88.2
2    10/2/2001   77.6
3    10/3/2001   68.4
4    10/4/2001   61.5
5    10/5/2001   55.3
6    10/6/2001   52.5
7    10/7/2001   49.7
8    10/8/2001   46.7
9    10/9/2001   43.3
10  10/10/2001   41.3
11  10/11/2001   39.3
12  10/12/2001   37.7
13  10/13/2001   35.8
14  10/14/2001   34.1
15  10/15/2001   39.8

I need to create a loop summing the previous 6 days as well as the current day (rolling weekly average), and print it to an array for the designated water year. I have already created an aggregate function to separate yearly average daily means into their designated water years.

# Separating dates into specific water years

wtr_yr <- function(dates, start_month=9)
  # Convert dates into POSIXlt
  POSIDATE = as.POSIXlt(NEW_DATE)
  # Year offset
  offset = ifelse(POSIDATE$mon >= start_month - 1, 1, 0)
  # Water year
  adj.year = POSIDATE$year + 1900 + offset

# Aggregating the water year function to take the mean

mean.FLOW=aggregate(data_set$FLOW,list(adj.year), mean)

Body:
It seems that it can be done much more easily.
But first I need to prepare a bit more data.

library(tidyverse)
library(lubridate)

df = tibble(
  DATE = seq(mdy("1/1/2010"), mdy("12/31/2022"), 1),
  FLOW = rnorm(length(DATE), 40, 10)
)

output

# A tibble: 4,748 x 2
   DATE        FLOW
   <date>     <dbl>
 1 2010-01-01  34.4
 2 2010-01-02  37.7
 3 2010-01-03  55.6
 4 2010-01-04  40.7
 5 2010-01-05  41.3
 6 2010-01-06  57.2
 7 2010-01-07  44.6
 8 2010-01-08  27.3
 9 2010-01-09  33.1
10 2010-01-10  35.5
# ... with 4,738 more rows

Now let's do the aggregation by year and week number

df %>%
  group_by(year(DATE), week(DATE)) %>%
  summarise(mean = mean(FLOW))

output

# A tibble: 689 x 3
# Groups:   year(DATE) [13]
   `year(DATE)` `week(DATE)`  mean
          <dbl>        <dbl> <dbl>
 1         2010            1  44.5
 2         2010            2  39.6
 3         2010            3  38.5
 4         2010            4  35.3
 5         2010            5  44.1
 6         2010            6  39.4
 7         2010            7  41.3
 8         2010            8  43.9
 9         2010            9  38.5
10         2010           10  42.4
# ... with 679 more rows

Note, for the function week, the first week starts on January 1st. If you want to number the weeks according to the ISO 8601 standard, use the isoweek function. Alternatively, you can also use an epiweek compatible with the US CDC.

df %>%
  group_by(year(DATE), isoweek(DATE)) %>%
  summarise(mean = mean(FLOW))

output

# A tibble: 681 x 3
# Groups:   year(DATE) [13]
   `year(DATE)` `isoweek(DATE)`  mean
          <dbl>           <dbl> <dbl>
 1         2010               1  40.0
 2         2010               2  45.5
 3         2010               3  33.2
 4         2010               4  38.9
 5         2010               5  45.0
 6         2010               6  40.7
 7         2010               7  38.5
 8         2010               8  42.5
 9         2010               9  37.1
10         2010              10  42.4
# ... with 671 more rows

If you want to better understand how these functions work, please follow the code below

df %>%
  mutate(
    w1 = week(DATE),
    w2 = isoweek(DATE),
    w3 = epiweek(DATE)
  )

output

# A tibble: 4,748 x 5
   DATE        FLOW    w1    w2    w3
   <date>     <dbl> <dbl> <dbl> <dbl>
 1 2010-01-01  34.4     1    53    52
 2 2010-01-02  37.7     1    53    52
 3 2010-01-03  55.6     1    53     1
 4 2010-01-04  40.7     1     1     1
 5 2010-01-05  41.3     1     1     1
 6 2010-01-06  57.2     1     1     1
 7 2010-01-07  44.6     1     1     1
 8 2010-01-08  27.3     2     1     1
 9 2010-01-09  33.1     2     1     1
10 2010-01-10  35.5     2     1     2
# ... with 4,738 more rows


问:
What does 0b1 mean in C++?
I came across a part of code that I cannot understand.

```<code>for (unsigned int i = (x & 0b1); i < x; i+= 2)
    {
        // body
    }
</code>```

Here, x is from 0 to 5.

What is meant by 0b1? and what would be the answers for eg: (0 & 0b1), (4 & 0b1) etc?

答:
0b... is a binary number, just like 0x... is hex and 0... is octal.

Thus 0b1 is same as 1.

1b0 is illegal, the first digit in those must always be 0.

Title: What does 0b1 mean in C++?

Body:
I came across a part of code that I cannot understand.

for (unsigned int i = (x & 0b1); i < x; i+= 2)
    {
        // body
    }

Here, x is from 0 to 5.

What is meant by 0b1? and what would be the answers for eg: (0 & 0b1), (4 & 0b1) etc?


问:
Connector/J: MysqlDataSource.setConnectionTimeZone() doesn't exist
MySQL Connector/J 8.0.23 (2021-01-18) added 3 new connection properties: connectionTimeZone, preserveInstants, and forceConnectionTimeZoneToSession.

I have been creating the connection using:

```<code>DriverManager.getConnection("jdbc:mysql://" + hostname
   + ":" + port
   + "/" + databaseName
   + "?user=" + username
   + "&password=" + password
   + "&preserveInstants=false"
   + "&connectionTimeZone=UTC"
   + "&serverTimeZone=UTC"
   + "&forceConnectionTimeZoneToSession=true";
</code>```

I want to switch to using MysqlDataSource, and have gotten this far:

```<code>MysqlDataSource source = new MysqlDataSource();
source.setServerName(hostname);
source.setPort(port);
source.setDatabaseName(databaseName);
source.setUser(username);
source.getPassword(password);
source.setPreserveInstants(false);
source.???;   // Something like .setConnectionTimeZone() does not exist
source.setServerTimezone("UTC");
source.setForceConnectionTimeZoneToSession(true);
</code>```

I don't see how to set connectionTimeZone, unless I skip setting everything individually and just use source.setUrl(url).

There are no other .setX methods having to do with timezones, other than the 2 I'm already using, so it doesn't appear to just be named differently.

I'm using mysql-connector-java 8.0.27.  I do see 8.0.28 is released, but its release notes don't mention any changes for MysqlDataSource.

(For anyone who wonders, my goal is to have MySQL Connector/J always operate in UTC, period, and never touch any dates or times.)

答:
I may have figured out the answer.  https://docs.oracle.com/cd/E17952_01/connector-j-8.0-en/connector-j-time-instants.html mentions:

Note

For Connector/J 8.0.23 and later, serverTimezone is an alias for connectionTimeZone. For Connector/J 8.0.22 and earlier, serverTimezone was used to override the session time zone setting on the server.

That leads me to believe I was being redundant providing both (on 8.0.23+) connectionTimeZone=UTC and serverTimeZone=UTC, and the left the older MysqlDataSource.setServerTimezone() be without adding a new method for the same thing.

So, perhaps all I need to do is remove the source.???; line in my original post, since maybe source.setServerTimezone("UTC"); covers it.

Body:
MySQL Connector/J 8.0.23 (2021-01-18) added 3 new connection properties: connectionTimeZone, preserveInstants, and forceConnectionTimeZoneToSession.

I have been creating the connection using:

DriverManager.getConnection("jdbc:mysql://" + hostname
   + ":" + port
   + "/" + databaseName
   + "?user=" + username
   + "&password=" + password
   + "&preserveInstants=false"
   + "&connectionTimeZone=UTC"
   + "&serverTimeZone=UTC"
   + "&forceConnectionTimeZoneToSession=true";

I want to switch to using MysqlDataSource, and have gotten this far:

MysqlDataSource source = new MysqlDataSource();
source.setServerName(hostname);
source.setPort(port);
source.setDatabaseName(databaseName);
source.setUser(username);
source.getPassword(password);
source.setPreserveInstants(false);
source.???;   // Something like .setConnectionTimeZone() does not exist
source.setServerTimezone("UTC");
source.setForceConnectionTimeZoneToSession(true);

I don't see how to set connectionTimeZone, unless I skip setting everything individually and just use source.setUrl(url).

There are no other .setX methods having to do with timezones, other than the 2 I'm already using, so it doesn't appear to just be named differently.

I'm using mysql-connector-java 8.0.27.  I do see 8.0.28 is released, but its release notes don't mention any changes for MysqlDataSource.

(For anyone who wonders, my goal is to have MySQL Connector/J always operate in UTC, period, and never touch any dates or times.)


问:
Add a 1-hour expiration to the current time/date
```<code>//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration
</code>```

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

```<code>$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");
</code>```

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

答:
```<code>$one_hour_from_now = strtotime('+1 hour');
</code>```

So, all you need is:

```<code>$expire = date('F j, Y, G:i', strtotime('+1 hour'));
</code>```

Body:
//expiration
$datetoday = date("F j, Y, G:i");

$expquery = mysql_query("SELECT a_expire FROM regform_admin WHERE status = 'Pending for payment'");
$row = mysql_fetch_array($expquery);
$expirydate = $row['a_expire'];
echo "$datetoday";
echo "$expirydate";
if ($datetoday == $expirydate) {
    $expirequery = mysql_query("UPDATE regform_admin SET status = 'Expired' WHERE status = 'Pending'");
    $expirequery2 = mysql_query("UPDATE regform SET status = 'Expired' WHERE status = 'Pending'");
}
//end expiration

Hi, I have an expiration of reservation code here. My problem is that if a customer makes a reservation on 23:30 and the reservation will expire at 00:30 (1 hour), I made this code:

$currentdate = date("F j, Y, G:i");
$onehour = date("G") + 1;
$expire = date("F j, Y, $onehour:i");

The $onehour must increment, but the problem is that the 23:30 reservation must expire at 24:30. But after incrementing the $onehour, the 23:30 results into 24:40. Which my program cannot read since military time of 12am is 00:00 and not 24:00. Can anyone have suggestions in my problem? Thanks. Sorry for the lazy english I was tired of thinking

Body:
$one_hour_from_now = strtotime('+1 hour');

So, all you need is:

$expire = date('F j, Y, G:i', strtotime('+1 hour'));


问:
PostgreSQL conditional select throwing error
I have a PostgreSQL database hosted on Heroku which is throwing me this error that I can't wrap my head around.

```<code>CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, age SMALLINT, right_handed BOOLEAN)
SELECT 1 id FROM people WHERE age IN (1) AND right_handed IN (1)
</code>```

It gives me the error:

Error in query: ERROR: syntax error at or near "IN"

Don't know how to proceed, any help would be greatly appreciated.

答:
AUTOINCREMENT is not a valid option for CREATE TABLE in Postgres

You can use SERIAL or BIGSERIAL:

```<code>ALTER TABLE myTable ADD COLUMN myColumn BIGSERIAL PRIMARY KEY;
</code>```

Body:
I have a PostgreSQL database hosted on Heroku which is throwing me this error that I can't wrap my head around.

CREATE TABLE people (id INTEGER PRIMARY KEY AUTOINCREMENT, age SMALLINT, right_handed BOOLEAN)
SELECT 1 id FROM people WHERE age IN (1) AND right_handed IN (1)

It gives me the error:

Error in query: ERROR: syntax error at or near "IN"

Don't know how to proceed, any help would be greatly appreciated.

Body:
AUTOINCREMENT is not a valid option for CREATE TABLE in Postgres

You can use SERIAL or BIGSERIAL:

ALTER TABLE myTable ADD COLUMN myColumn BIGSERIAL PRIMARY KEY;


问:
is there a way to run a .s file in geany (its not in the available selections)?
I noticed that the .s extension is not in the new file creation for Geany. How can assembly language run in Geany then?

Please see image in the hyperlink below.

Geany New File (does not have .s or assembly file selection)

答:
You can add file-type extensions in Geany's preferences following:

Tools -> Configuration Files -> filetype_extensions.conf

Full settings of a (new) file extension is described in filetype-extensions part of Geany's documentaction.