问:
How do I create a link to a Sitefinity page in content via API?
I am importing content from our old content management system. I'm trying to update the links located within the content (News article, Page control, etc.) to be Sitefinity-type links, linking to SF pages, news articles, etc. I've tried to recreate the structure of the anchor tag, including the sfref attribute, but publish doesn't remove the sfref attribute, and publish-and-sync doesn't update the URL to the new server. How can I properly do this with API?</p>

答:
Here is how you need to do this:

Let's say you have the following html from the old system:

```<code>Check our <a href="/about-us">About Us</a> page.
</code>```

Now, let's say you have created the About Us page in Sitefinity.

You need to find the page node object (sf_page_node table) and get its:
root_id and the id values.
Let's say they look like this:

```<code>rootId: f669d9a7-009d-4d83-ddaa-000000000002
Id: b5d84f10-3660-42e4-b2c0-b89db2d6c884
</code>```

Then the html snippet that needs to be saved to the database should be like this (tested in v.12.2)

```<code>Check our <a href="[f669d9a7-009d-4d83-ddaa-000000000002]b5d84f10-3660-42e4-b2c0-b89db2d6c884">About Us</a> page.
</code>```

For images, let's say you have this in your html:

```<code><img src="/images/image1.jpg">
</code>```

I assume you have uploaded image1.jpg to Sitefinity and you know its Content_Id (from sf_media_content table).

Then you need to save the following html to the database:

```<code><img src="[images|OpenAccessDataProvider]1dd75953-b4a8-46f6-93b9-6b29f5a62a04" data-displaymode="Original" alt="image1" title="image1.jpg">
</code>```

Here I am assuming you use the default provider - OpenAccessDataProvider and that the content_id of the LIVE image is 1dd75953-b4a8-46f6-93b9-6b29f5a62a04

Body:
Here is how you need to do this:

Let's say you have the following html from the old system:

Check our <a href="/about-us">About Us</a> page.

Now, let's say you have created the About Us page in Sitefinity.

You need to find the page node object (sf_page_node table) and get its:
root_id and the id values.
Let's say they look like this:

rootId: f669d9a7-009d-4d83-ddaa-000000000002
Id: b5d84f10-3660-42e4-b2c0-b89db2d6c884

Then the html snippet that needs to be saved to the database should be like this (tested in v.12.2)

Check our <a href="[f669d9a7-009d-4d83-ddaa-000000000002]b5d84f10-3660-42e4-b2c0-b89db2d6c884">About Us</a> page.

For images, let's say you have this in your html:

<img src="/images/image1.jpg">

I assume you have uploaded image1.jpg to Sitefinity and you know its Content_Id (from sf_media_content table).

Then you need to save the following html to the database:

<img src="[images|OpenAccessDataProvider]1dd75953-b4a8-46f6-93b9-6b29f5a62a04" data-displaymode="Original" alt="image1" title="image1.jpg">

Here I am assuming you use the default provider - OpenAccessDataProvider and that the content_id of the LIVE image is 1dd75953-b4a8-46f6-93b9-6b29f5a62a04


来源: stackexchange

问:
Display links from message as a link
I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the example.com as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")

Here is the message component.

```<code>import React from "react";
import moment from "moment";
import { Comment, Image } from "semantic-ui-react";

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

function linkify(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
      return '<a href="' + url + '">' + url + '</a>';
  });
}

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (
        <div>
<Comment.Text>{linkify(message.content)}</Comment.Text>
        <React.Fragment dangerouslySetInnerHTML={linkify(message.content)}>
        </React.Fragment>
        </div>
      )}
    </Comment.Content>
  </Comment>
);

export default Message;
</code>```

答:
you better treat your url variable first by your regex then return like a valid react element:

```<code>function linkify(text) {
  const urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  // extract your url by urlRegex something like
  const url = text.match(urlRegex)[0]
  return <a href={url} >{url}</a>
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Display links from message as a link

Body:
I'm trying to replay any occurrence of a link in a text as a link, but I only get it to show the example.com as text in the message. (Just to be clear, it shows other message content if there is other content in the message than the link, but the link gets "linkified(as seen below)")

Here is the message component.

import React from "react";
import moment from "moment";
import { Comment, Image } from "semantic-ui-react";

const isOwnMessage = (message, user) => {
  return message.user.id === user.uid ? "message__self" : "";
};

const isImage = message => {
  return message.hasOwnProperty("image");
};

const timeFromNow = timestamp => moment(timestamp).fromNow();

function linkify(text) {
  var urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  return text.replace(urlRegex, function(url) {
      return '' + url + '';
  });
}

const Message = ({ message, user }) => (
  <Comment>
    <Comment.Avatar src={message.user.avatar} />
    <Comment.Content className={isOwnMessage(message, user)}>
      <Comment.Author as="a">{message.user.name}</Comment.Author>
      <Comment.Metadata>{timeFromNow(message.timestamp)}</Comment.Metadata>
      {isImage(message) ? (
        <Image src={message.image} className="message__image" />
      ) : (

<Comment.Text>{linkify(message.content)}</Comment.Text>
        <React.Fragment dangerouslySetInnerHTML={linkify(message.content)}>
        </React.Fragment>

      )}
    </Comment.Content>
  </Comment>
);

export default Message;

Body:
you better treat your url variable first by your regex then return like a valid react element:

function linkify(text) {
  const urlRegex =/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
  // extract your url by urlRegex something like
  const url = text.match(urlRegex)[0]
  return <a href={url} >{url}</a>
}


问:
Creating a smooth jump animation
I have some basic jump code.  Once the player hits the space bar, the player will start jumping, and their jumpCount will be set to 20.  jumpCount is decremented along with the player's y until it reaches -20.  The main problem with this code is that after the player jumps they will end up slightly lower each time they reach the ground.

y = 100
jumpCount = 20

while True:
    if keys[pygame.K_SPACE]:
        isJump = True

    if isJump:
        if jumpCount >= -20:
            neg = 1
            if jumpCount < 0:
                neg = -1

            y -= (jumpCount ** 2) * 0.05 * neg
            jumpCount -= 1

        else:
            jumpCount = 20
            isJump = False
```

答:
I was confused by this before, but there is a solution: try to line it to the landing surface, change it before screen update, so people don't notice it, it will look like it move a bit shorter( really small amount).
for example:

```<code>if player.x < surface.x:
 player.x = surface.x
update()
</code>```

Little extra:

if you want gravity to work, you can use similar way to do that, on hitting any surface, set grav to 0 and change player's x axis to surface's x axis

Title: Creating a smooth jump animation

Body:
I was confused by this before, but there is a solution: try to line it to the landing surface, change it before screen update, so people don't notice it, it will look like it move a bit shorter( really small amount).
for example:

if player.x < surface.x:
 player.x = surface.x
update()

Little extra:

if you want gravity to work, you can use similar way to do that, on hitting any surface, set grav to 0 and change player's x axis to surface's x axis


问:
MySQL: Disable logging for table updates/inserts
Is there a way to disable logging of updates/inserts to a particular table in MySQL/MariaDB?

In our database we have multiple tables and we would like to disable the logging of INSERT and UPDATE events for a specific table only.  SET GLOBAL general_log = 1; and SET GLOBAL general_log = 0; provide a pretty coarse level control over logging.  We are looking for much finer-grained control over logging.

答: Use binary logging and put the particular table in its own database with binlog-ignore-db set for that database.</p>


问:
readLine for a variable number of Ints
Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

```<code>val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)
</code>```

Thanks in advance.

答:
If you want to just print each string, then you can use forEach

```<code>readLine()!!.split(' ').forEach{ println(it) }
</code>```

If you want to print as int, then you can use forEach with toInt()

```<code>readLine()!!.split(' ').forEach{ println(it.toInt()) }
</code>```

Or if you want sum you can use sumBy directly

```<code>readLine()!!.split(' ').sumBy{ it.toInt() }
</code>```

Title: readLine for a variable number of Ints

Body:
Is there a way to code something like this in kotlin for a variable number of ints? For example the input should be "1 3 5" or "3 2 2 7" (String with space-separated Ints). And I am not allowed to use java librarys.

val (x, y) = readLine()!!.split(' ').map(String::toInt)
println(x+y)

Thanks in advance.

Body:
If you want to just print each string, then you can use forEach

readLine()!!.split(' ').forEach{ println(it) }

If you want to print as int, then you can use forEach with toInt()

readLine()!!.split(' ').forEach{ println(it.toInt()) }

Or if you want sum you can use sumBy directly

readLine()!!.split(' ').sumBy{ it.toInt() }


问:
Some more explanation of Hibernate's merge
I need some clarification on Hibernate merge method. How does it exactly work. When i have an entity that is detached, and I want it to get reatached, does Hibernate look only un current session for same entity, or in all Hibernate sessions?

Is there any way to use merge on transistent entity?

答:
Hibernate's merge is to be used when you might have more than one instance of an object in the current memory at one time, and you want Hibernate to save any and all changes made to any instance of the object. This can happen, for example, when you've loaded the object through two different means during validation.

An issue that can cause confusion is the difference between an application session and a Hibernate session. It's possible to open and close more than one Hibernate session during an application session.

If you load an object instance in the first Hibernate session, then close the session, that instance becomes detached. If you open a new session, then load the same object (same ID), Hibernate will construct a new instance, and if you try to use saveOrUpdate on the object obtained in the first session, Hibernate will throw a NonUniqueObjectException.

So while the current Hibernate session is only concerned with itself, part of its infrastructure is to be aware of what objects exist in the larger application session that are mapped Hibernate entities and thus it should consider in operations like save or merge.

Merge is a way to tell Hibernate "I want you assume any changes I made to this Hibernate entity should be saved, even if I made them to a different instance of the object than the once I'm asking you to save." SaveOrUpdate is a way to tell Hibernate to be more conservative and throw an Exception instead.

There's some more specifics about the differences between Hibernate's saveOrUpdate and merge in this article in my blog.

ContentLicense: CC BY-SA 3.0


问:
Unexpected behavior from python tkinter double click bind
I wrote the following program intended to create a 3x3 grid of entry widgets which, when double clicked, toggle between white and black.

```<code>from tkinter import *

root = Tk()

temp = None

def changeColor(event, e):
    print("id(e) =", id(e))
    if e['bg'] == 'white':
        e['bg'] = 'black'
    elif e['bg'] == 'black':
        e['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()
</code>```

The grid creation works great but the toggling is misbehaving. Regardless of which of the entries you double click, its always the bottom right entry (the last one added in the loop) which is toggled.

The output in the terminal is

```<code>id(e) = 4376431536
id(e) = 4376431536
id(e) = 4376431536
...
</code>```

I'm very confused. In the bind statements we create a new specialised lambda for each of the entries and pass a reference to the relevant entry. Why is this happening??????

I found a work around, changing the bind function to

```<code>def changeColor(event, e):
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'
</code>```

I'm not asking for a solution to my issue, but asking for an explanation of why it is happening.

答:
The reason it is happening is because all of the entries are called e. If you notice, everytime you double click anywhere, the final one that is created changes, instead of the one you click on.

Hope this helps!

Edit: Take the following python code:

loop = 0
for i in range(10):
    loop = i
print(loop)
```

<p>The output would be: </p>

```9
```

<p>The same thing is happening in your code. You are creating the entry's through iteration. Therefore, the one entry that will be in effect is the last one created. </p>

<p>Hope this helps!</p>

<p>Edit: </p>

<p>The reason the lambda's are the same is because they are the same function. It applies to the last one because that is the final assignment. </p>

<p>This would be your code: </p>

<pre class="lang-py prettyprint-override"><code>from tkinter import *

root = Tk()

temp = None

def changeColor(event):
    if event.widget['bg'] == 'white':
        event.widget['bg'] = 'black'
    elif event.widget['bg'] == 'black':
        event.widget['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()
</code>```

Hope this helps!

Body:
I wrote the following program intended to create a 3x3 grid of entry widgets which, when double clicked, toggle between white and black.

from tkinter import *

root = Tk()

temp = None

def changeColor(event, e):
    print("id(e) =", id(e))
    if e['bg'] == 'white':
        e['bg'] = 'black'
    elif e['bg'] == 'black':
        e['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', bd=0, borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x, e))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()

The grid creation works great but the toggling is misbehaving. Regardless of which of the entries you double click, its always the bottom right entry (the last one added in the loop) which is toggled.

The output in the terminal is

id(e) = 4376431536
id(e) = 4376431536
id(e) = 4376431536
...

I'm very confused. In the bind statements we create a new specialised lambda for each of the entries and pass a reference to the relevant entry. Why is this happening??????

I found a work around, changing the bind function to

def changeColor(event, e):
    e2 = event.widget
    if e2['bg'] == 'white':
        e2['bg'] = 'black'
    elif e2['bg'] == 'black':
        e2['bg'] = 'white'

I'm not asking for a solution to my issue, but asking for an explanation of why it is happening.

Body:
The reason it is happening is because all of the entries are called e. If you notice, everytime you double click anywhere, the final one that is created changes, instead of the one you click on.

Hope this helps!

Edit: Take the following python code:

loop = 0
for i in range(10):
    loop = i
print(loop)

The output would be:

9

The same thing is happening in your code. You are creating the entry's through iteration. Therefore, the one entry that will be in effect is the last one created.

Hope this helps!

Edit:

The reason the lambda's are the same is because they are the same function. It applies to the last one because that is the final assignment.

This would be your code:

from tkinter import *

root = Tk()

temp = None

def changeColor(event):
    if event.widget['bg'] == 'white':
        event.widget['bg'] = 'black'
    elif event.widget['bg'] == 'black':
        event.widget['bg'] = 'white'
    global temp
    temp = event

entries = [[None for i in range(3)] for j in range(3)]

for y in range(3):
    for x in range(3):
        e = Entry(root, width=3, bg='white', borderwidth=3)
        e.bind('<Double-Button-1>', lambda x: changeColor(x))
        e.grid(column=x, row=y)
        entries[y][x] = e

root.mainloop()

Hope this helps!


问:
lxc-start: controller: lxccontainer.c: wait_on_daemonized_start: 842 Received container state "STOPPING" instead of "RUNNING"
when i run the config file

config file

sudo lxc-start -n controller -d

it gives me this error

lxc-start: controller: lxccontainer.c: wait_on_daemonized_start: 842 Received container state "STOPPING" instead of "RUNNING"

lxc-start: controller: tools/lxc_start.c: main: 330 The container failed to start

lxc-start: controller: tools/lxc_start.c: main: 333 To get more details, run the container in foreground mode

lxc-start: controller: tools/lxc_start.c: main: 336 Additional information can be obtained by setting the --logfile and --logpriority options

Additional information

lxc-start --version

3.0.3

uname -a

Linux shahrukh-VirtualBox 3.12.74-031274-generic #201705101001 SMP Wed May 10 14:04:20 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

答:
It turns out that there were old config files for apparmor in my system that didn't get updated along with apparmor. Simply doing this fixed it:

```<code>sudo -sH              # become root
apt purge apparmor*   # uninstall apparmor and its configs
apt install apparmor* # reinstall it
apparmor_status       # check if apparmor is running

# If the above status shows 0 for every profile or other error
# check first if apparmor is activated in the kernel through grub
cat /sys/module/apparmor/parameters/enabled

# if the above doesn't return "Y", then activate it first
mkdir -p /etc/default/grub.d
echo 'GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT apparmor=1 security=apparmor"' \
  | tee /etc/default/grub.d/apparmor.cfg
update-grub
reboot
</code>```

Body:
It turns out that there were old config files for apparmor in my system that didn't get updated along with apparmor. Simply doing this fixed it:

sudo -sH              # become root
apt purge apparmor*   # uninstall apparmor and its configs
apt install apparmor* # reinstall it
apparmor_status       # check if apparmor is running

# If the above status shows 0 for every profile or other error
# check first if apparmor is activated in the kernel through grub
cat /sys/module/apparmor/parameters/enabled

# if the above doesn't return "Y", then activate it first
mkdir -p /etc/default/grub.d
echo 'GRUB_CMDLINE_LINUX_DEFAULT="$GRUB_CMDLINE_LINUX_DEFAULT apparmor=1 security=apparmor"' \
  | tee /etc/default/grub.d/apparmor.cfg
update-grub
reboot


问:
PL/SQL procedure/function to show data from different tables dynamically alongwith the column names in first data row
I have a requirement like below.

There are 70 tables and I have to build 70 queries from those 70 different tables depending on some condition.

Let us say the table names are TAB_1,TAB_2,TAB_3.....,TAB_70.The number of columns and data type of the columns are different in each table. I will get user input and I have to pass that value to an Oracle PL/SQL function or procedure GET_RESULT() and get the output in tabular format(same as we get when we run a query).

Also, I have to show the column names in the 1st data row.

Example:

I am taking two tables, TAB_1 and TAB_2.

TAB_1

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

TAB_2

ID        Status

00001     ACTIVE

00002     PURGED

00003     ACTIVE

00004     ACTIVE

If I get user input 1, I will pass it to a procedure's parameter, GET_RESULTS(1) and get an output like below:

Col1      Col2      Col3

ID        Quarter   Risk

00001     Q0        2

00001     Q1        3

00001     Q2        1

00001     Q3        1

00001     Q4        2

If GET_RESULTS(2) then :

Col1      Col2

ID        STATUS

00001     ACTIVE

00002     PURGED

00003     ACTIVE

00004     ACTIVE

Can someone help?

答:
Use the data dictionary to build a SQL statement that selects the correct columns. Use dynamic SQL to open a refcursor to that statement, and return the cursor from the function.

Sample Schema

```<code>create table tab_1 as
select '00001' id, 'Q0' quarter, 2 risk from dual union all
select '00001' id, 'Q1' quarter, 3 risk from dual union all
select '00001' id, 'Q2' quarter, 1 risk from dual union all
select '00001' id, 'Q3' quarter, 1 risk from dual union all
select '00001' id, 'Q4' quarter, 2 risk from dual;

create table tab_2 as
select '00001' id, 'ACTIVE' status from dual union all
select '00002' id, 'PURGED' status from dual union all
select '00003' id, 'ACTIVE' status from dual union all
select '00004' id, 'ACTIVE' status from dual;
</code>```

Function

```<code>create or replace function get_results(p_id number) return sys_refcursor is
    v_sql varchar2(32767);
    v_refcursor sys_refcursor;
begin
    --Get SQL statement.
    select
        'select ' ||
        listagg(column_name, ',') within group (order by column_id) ||
        ' from ' || table_name
    into v_sql
    from user_tab_columns
    where table_name = 'TAB_' || p_id
        and column_id <= 2
    group by table_name;

    open v_refcursor for v_sql;

    return v_refcursor;
end;
/
</code>```

Calling the Function

The function should work as long as the application understands refcursors. Below is an example in a recent version of SQL*Plus:

```<code>SQL> select get_results(1) from dual;

GET_RESULTS(1)
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

ID    QU
----- --
00001 Q0
00001 Q1
00001 Q2
00001 Q3
00001 Q4
</code>```

Body:
Use the data dictionary to build a SQL statement that selects the correct columns. Use dynamic SQL to open a refcursor to that statement, and return the cursor from the function.

Sample Schema

create table tab_1 as
select '00001' id, 'Q0' quarter, 2 risk from dual union all
select '00001' id, 'Q1' quarter, 3 risk from dual union all
select '00001' id, 'Q2' quarter, 1 risk from dual union all
select '00001' id, 'Q3' quarter, 1 risk from dual union all
select '00001' id, 'Q4' quarter, 2 risk from dual;

create table tab_2 as
select '00001' id, 'ACTIVE' status from dual union all
select '00002' id, 'PURGED' status from dual union all
select '00003' id, 'ACTIVE' status from dual union all
select '00004' id, 'ACTIVE' status from dual;

Function

create or replace function get_results(p_id number) return sys_refcursor is
    v_sql varchar2(32767);
    v_refcursor sys_refcursor;
begin
    --Get SQL statement.
    select
        'select ' ||
        listagg(column_name, ',') within group (order by column_id) ||
        ' from ' || table_name
    into v_sql
    from user_tab_columns
    where table_name = 'TAB_' || p_id
        and column_id <= 2
    group by table_name;

    open v_refcursor for v_sql;

    return v_refcursor;
end;
/

Calling the Function

The function should work as long as the application understands refcursors. Below is an example in a recent version of SQL*Plus:

SQL> select get_results(1) from dual;

GET_RESULTS(1)
--------------------
CURSOR STATEMENT : 1

CURSOR STATEMENT : 1

ID    QU
----- --
00001 Q0
00001 Q1
00001 Q2
00001 Q3
00001 Q4


问:
Is there a way to merge two MatPlotLib plots together?
I have been trying to merge these two plots together but have not found a built-in in the documentation for MatPlotLib on how to do so. I want to show the two bar values next to each and for every new entry, add the new entry to the graph while shifting the other entries over to make space. The plots are below.

As stated prior, when I say merge, I do not simply mean just plop Plot A onto Plot B, but rather join the plots together so both bar values are shown in the same graph, like this:

The reasoning for this is that I will be able to log all the entries in a single plot without having to manually do so. By implementing something like this in my code, it would make entries go a lot quicker.

EDIT: I understand that I can graph these two together, but that is not what I am looking for. Once I get the necessary input, my program creates a graph of that data and saves it as a file. I am looking to append any new data to that original file by just shifting the original value over to the left in order to make space.

EDIT 2: How could I extract the data from each plot and after doing so, create a new graph? This would seem to be another acceptable workaround.

答:
Is there anything preventing you from plotting each of them side by side but changing the index?

```<code>a, b, c = 2, 5, 3
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
count = 0
ax.bar(count, a)
# if prgoram produces a new output then...
count += 1
ax.bar(count, b)  # index means new bar plot has shifted
# again
count += 1
ax.bar(count, c)  # shifted again
</code>```

This should automatically expand the x-axis anyway. You may have to alter this slightly if you've particularly concenred about the width of these bars.

If this isn't what you wanted you could consider replotting with the bar container or even just stripping the height to reuse.

```<code>fig, ax = plt.subplots(1, 1)
count = 0
bar_cont = ax.bar(count, a)  # reference to the bar container of interest
print(bar_cont.get_height())
</code>```

Body:
Is there anything preventing you from plotting each of them side by side but changing the index?

a, b, c = 2, 5, 3
import matplotlib.pyplot as plt
fig, ax = plt.subplots(1, 1)
count = 0
ax.bar(count, a)
# if prgoram produces a new output then...
count += 1
ax.bar(count, b)  # index means new bar plot has shifted
# again
count += 1
ax.bar(count, c)  # shifted again

This should automatically expand the x-axis anyway. You may have to alter this slightly if you've particularly concenred about the width of these bars.

If this isn't what you wanted you could consider replotting with the bar container or even just stripping the height to reuse.

fig, ax = plt.subplots(1, 1)
count = 0
bar_cont = ax.bar(count, a)  # reference to the bar container of interest
print(bar_cont.get_height())


问:
What is an easy way to put an element in the middle of a PHP array?
Say you have a 10 element indexed array and you want to place an element somewhere in the middle (say index 3). Then I want to have the rest of the array shift and thus be 11 elements long. Is there an easy way to do this?

I am surprised there is no put() function or something.

I know it would be easy enough to do this with a combination of array_splice and array_merge but I was just wondering if there an easier way.

答:
If you use array_splice(), PHP will still have to copy half the array to do the insert, which will be a performance hit for large array sizes.   Maybe you should be using a list or tree datastructure instead?

The only time I've ever needed to insert into the middle of an array was when I was doing some operation that's substantially similar to insertion sort.  Maybe you want to store the items unsorted in an array, and then sort them once you've added them all?

OwnerDisplayName: Andrew

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Andrew

OwnerDisplayName: slacy


问:
Can I run locally and debug a Web App that uses Google API's? [GWT+GAE]
I'm working on a web-app using Google App Engine with GWT, and I need to use Google API's (Google Calendar, Documents and so...).

As I know, I must configure a domain with Google to set my domain as callback of an OAuth Authentication. Am I right?

If so, am I forced to deploy on GAE to test? I mean, I can't run locally because my localhost can't be a valid callback.

Do you know any way to debug locally even using Google API's?

I have recommended to config a DynDNS, but isn't a solution in short term (incompatible router)...

答:
If you use AuthSub instead I don't think you need to register a domain. The user just need a google account.

I have in the past used AuthSub together with Google Docs/Spreadsheet APIs on GAE and also been able to test it locally.

I can unfortunately not give you my code and exact solution (it was a while ago). But one of the samples I used extensively to base my code on was the FetcherServlet, check this code out:

http://code.google.com/p/google-app-engine-samples/source/browse/trunk/retrieving-gdata-feeds-java/src/com/google/appengine/demo/web/FetcherServlet.java?r=122

Also, I guess you might already have read this page (but their FetcherServlet uses OAuth, not AuthSub), so maybe just use it for some background info:

http://code.google.com/appengine/articles/java/retrieving_gdata_feeds.html


问:
Why am I getting a Module Build Failed in my React?
If anyone can please help. I cannot figure this out. I keep getting an error:

Uncaught Error: Module build failed: Duplicate declaration "status"

I have a hook called hook.js in a file that reads this:

```<code>import React, { useState } from "react";

export const hook = () => {
  const [status, setStatus] = useState([
    { title: "Progress", view: 1, total: 20 },
    { title: "Pending Initial", view: 3, total: 1 },
    { title: "Pending Review", view: 3, total: 3 }
  ]);
  return { status };
};
</code>```

then the main.js where I am calling the hook and I get that error

```<code>import React from "react";
import { hook } from "./hook;

const StatusTable = ({ status }) => {
  const { status } = useComponentLogic(status);

  const StatusTableHeader = ({ status }) => {
    let header = Object.keys(status[0]);
    return header.map((key, index) => {
      return <th key={index}>{key.toUpperCase()}</th>;
    });
  };

  return (
    <div>
      <table id="status">
        <tbody>
          <tr>
            {StatusTableHeade()}
          </tr>
        </tbody>
      </table>
    </div>
  );
};

export default StatusTable;
</code>```

What am I doing wrong?

Thanks in advance!!

答:
That is because the descturtured props of your StatusTable component and the return value of the useComponentLogic  hook is sharing  the same variable name, status, and this will definitely not work as they are both declared on the same scope.

```<code>const StatusTable = ({ status }) => {
  const { status } = useComponentLogic(status);
...
}
</code>```

You should use different names for both of them. One approach would be to destructure the status props into a different property name.

```<code>const StatusTable = ({ status: inputStatus }) => {
  const { status } = useComponentLogic(status);

  ...

}
</code>```

Body:
If anyone can please help. I cannot figure this out. I keep getting an error:

Uncaught Error: Module build failed: Duplicate declaration "status"

I have a hook called hook.js in a file that reads this:

import React, { useState } from "react";

export const hook = () => {
  const [status, setStatus] = useState([
    { title: "Progress", view: 1, total: 20 },
    { title: "Pending Initial", view: 3, total: 1 },
    { title: "Pending Review", view: 3, total: 3 }
  ]);
  return { status };
};

then the main.js where I am calling the hook and I get that error

import React from "react";
import { hook } from "./hook;

const StatusTable = ({ status }) => {
  const { status } = useComponentLogic(status);

  const StatusTableHeader = ({ status }) => {
    let header = Object.keys(status[0]);
    return header.map((key, index) => {
      return {key.toUpperCase()}	;
    });
  };

  return (

            {StatusTableHeade()}

  );
};

export default StatusTable;

What am I doing wrong?

Thanks in advance!!

Body:
That is because the descturtured props of your StatusTable component and the return value of the useComponentLogic  hook is sharing  the same variable name, status, and this will definitely not work as they are both declared on the same scope.

const StatusTable = ({ status }) => {
  const { status } = useComponentLogic(status);
...
}

You should use different names for both of them. One approach would be to destructure the status props into a different property name.

const StatusTable = ({ status: inputStatus }) => {
  const { status } = useComponentLogic(status);

  ...

}


问:
How to get a random string of 32 hexadecimal digits through command line?
I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works:

```<code>python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in range(16)]))'
</code>```

This generates output like:

```<code>6EF6B30F9E557F948C402C89002C7C8A
</code>```

Which is what I need.

On a Mac, I can even do this:

```<code>uuidgen | tr -d '-'
</code>```

However, I don't have access to the more sophisticated scripting languages ruby and python, and I won't be on a Mac (so no uuidgen). I need to stick with more bash'ish tools like sed, awk, /dev/random because I'm on a limited platform. Is there a way to do this?

答:
Try:

```<code>xxd -u -l 16 -p /dev/urandom
</code>```

Example output:

```<code>C298212CD8B55F2E193FFA16165E95E3
</code>```

And to convert it back to binary:

```<code>echo -n C298212CD8B55F2E193FFA16165E95E3 | xxd -r -p
</code>```

Body:
I'd like to put together a command that will print out a string of 32 hexadecimal digits. I've got a Python script that works:

python -c 'import random ; print "".join(map(lambda t: format(t, "02X"), [random.randrange(256) for x in range(16)]))'

This generates output like:

6EF6B30F9E557F948C402C89002C7C8A

Which is what I need.

On a Mac, I can even do this:

uuidgen | tr -d '-'

However, I don't have access to the more sophisticated scripting languages ruby and python, and I won't be on a Mac (so no uuidgen). I need to stick with more bash'ish tools like sed, awk, /dev/random because I'm on a limited platform. Is there a way to do this?

Body:
Try:

xxd -u -l 16 -p /dev/urandom

Example output:

C298212CD8B55F2E193FFA16165E95E3

And to convert it back to binary:

echo -n C298212CD8B55F2E193FFA16165E95E3 | xxd -r -p


问:
How to increment a variable in functional programming?
How do you increment a variable in a functional programming language?

For example, I want to do:

```<code>main :: IO ()
main = do
    let i = 0
    i = i + 1
    print i
</code>```

Expected output:

```<code>1
</code>```

答:
Note: This is not an ideal answer but hey, sometimes it might be a little good to give anything at all.

A simple function to increase the variable would suffice.

For example:

```<code>incVal :: Integer -> Integer
incVal x = x + 1

main::IO()
main = do
   let i  = 1
   print (incVal i)
</code>```

Or even an anonymous function to do it.

Body:
How do you increment a variable in a functional programming language?

For example, I want to do:

main :: IO ()
main = do
    let i = 0
    i = i + 1
    print i

Expected output:

1

Body:
Note: This is not an ideal answer but hey, sometimes it might be a little good to give anything at all.

A simple function to increase the variable would suffice.

For example:

incVal :: Integer -> Integer
incVal x = x + 1

main::IO()
main = do
   let i  = 1
   print (incVal i)

Or even an anonymous function to do it.


问:
Laravel Livewire search button instead of live search
Is it possible to not live search but with a search button in Laravel Livewire?
My approach is to use Alpine together with Livewire.
But I don't get the search term injected into the $emit event :/</p>

```<code><div x-data="{ search: '' }">
  <input type="text" placeholder="Search ..." x-model="search" />
  <span x-text="search"></span>
  <button wire:click="$emit('test', search )">Search</button>
</div>
</code>```

答:
Or if you are using livewire component inside a loop. the above window.livewire.emit will call all the loop livewire component class with same function name.

so the best practice will be to use

```<code>x-on:click="@this.call('functionNameInLivewireComponent', search)"
</code>```

Body:
Is it possible to not live search but with a search button in Laravel Livewire?
My approach is to use Alpine together with Livewire.
But I don't get the search term injected into the $emit event :/

  <input type="text" placeholder="Search ..." x-model="search" />

  <button wire:click="$emit('test', search )">Search</button>

Body:
Or if you are using livewire component inside a loop. the above window.livewire.emit will call all the loop livewire component class with same function name.

so the best practice will be to use

x-on:click="@this.call('functionNameInLivewireComponent', search)"


问:
Is there a way to debug Apollo GraphQL subscriptions in Chrome DevTools?
In the Network tab of the Chrome DevTools, I can only find GraphQL queries and mutations requests:

While listening to a GraphQL subscription, and receiving a response, nothing appears in this tab. Is there another place to fetch GraphQL subscription from the Chrome DevTools?

For information, I am using apollo-client with apollo-angular.

答: In the Network tab of the Chrome DevTools, you should switch the filter to WS to see and debug your Apollo GraphQL subscription. You can see it in the pictures below:


问:
how to get data from jsonb column in postgres?
I have a database which have a table.There are two columns in my table id ,and description of type jsonb now I want to fetch all name in table.how to do that

I tried like this but not working

```<code>SELECT description::jsonb->name FROM Category
</code>```

expected output

```<code>["hello","test","world"]
</code>```

答:
You can use aggregation: json[b]_agg() can be used to generate a json array made of all 'name' attributes of the original objects, ordered by id.

```<code>select jsonb_agg(description ->> 'name' order by id) res from category
</code>```

Note that, since description is of jsonb datatype to start with, there is no need for an additional cast.

Body:
I have a database which have a table.There are two columns in my table id ,and description of type jsonb now I want to fetch all name in table.how to do that

I tried like this but not working

SELECT description::jsonb->name FROM Category

expected output

["hello","test","world"]

Body:
You can use aggregation: json[b]_agg() can be used to generate a json array made of all 'name' attributes of the original objects, ordered by id.

select jsonb_agg(description ->> 'name' order by id) res from category

Note that, since description is of jsonb datatype to start with, there is no need for an additional cast.


问:
How do you change column names to lowercase with linux and store the file as it is?
I am trying to change the column names to lowercase in a csv file. I found the code to do that online but I dont know how to replace the old column names(uppercase) with new column names(lowercase) in the original file. I did something like this:
$cat head -n1 xxx.csv | tr "[A-Z]" "[a-z]"

But it simply just prints out the column names in lowercase, which is not enough for me.
I tried to add sed -i but it did not do any good. Thanks!!

答:
Using perl:

```<code>perl -i -pe '$_=lc() if $.==1' file.csv
</code>```

It replace the file on the fly with -i switch

Body:
Using perl:

perl -i -pe '$_=lc() if $.==1' file.csv

It replace the file on the fly with -i switch


问:
Is there a way to test a css-selector query to an unappended element?
I have this code:

```<code>Element.prototype.queryTest = function(strQuery) {
 var _r;
 if (this.parentElement == null) {
  _r = Array.prototype.slice.call(document.querySelectorAll(strQuery)).indexOf(this);
 } else {
  _r = Array.prototype.slice.call(this.parentElement.querySelectorAll(strQuery)).indexOf(this);
 }
 return !!(_r+1);
}
</code>```

I am searching for some way to test a query to an unappended element.

I want to change the first code to make this work:

```<code>var t = document.createElement("span");
t.classList.add("asdfg");
console.log(t.queryTest("span.adsfg"));
</code>```

If there is a way to detect if the element isn't appended I could create a new temporary unappended one and append the target one to the temporary one to test the css-selector query.
Is there a way to detect if the element hasn't been appended jet? Could the target element be accessible even after freeing the temporary parent one? I have tested it on Chrome and it is accessible but I don't know if that is the case for firefox.

I know I can use document.querySelectorAll("*") to get a list of nodes but... isn't too CPU-demmanding the process to turn this NodeList to an Array? This is why I prefer not to use that way.

Thanks in advance.

答:
There is already a native Element.prototype.matches method which does that:

const el = document.createElement('span');
el.classList.add('test');
console.log(el.matches('span.test'));```

Note that to check if a node is connected or not, there is the Node.prototype.isConnected getter.

Body:
I have this code:

Element.prototype.queryTest = function(strQuery) {
 var _r;
 if (this.parentElement == null) {
  _r = Array.prototype.slice.call(document.querySelectorAll(strQuery)).indexOf(this);
 } else {
  _r = Array.prototype.slice.call(this.parentElement.querySelectorAll(strQuery)).indexOf(this);
 }
 return !!(_r+1);
}

I am searching for some way to test a query to an unappended element.

I want to change the first code to make this work:

var t = document.createElement("span");
t.classList.add("asdfg");
console.log(t.queryTest("span.adsfg"));

If there is a way to detect if the element isn't appended I could create a new temporary unappended one and append the target one to the temporary one to test the css-selector query.
Is there a way to detect if the element hasn't been appended jet? Could the target element be accessible even after freeing the temporary parent one? I have tested it on Chrome and it is accessible but I don't know if that is the case for firefox.

I know I can use document.querySelectorAll("*") to get a list of nodes but... isn't too CPU-demmanding the process to turn this NodeList to an Array? This is why I prefer not to use that way.

Thanks in advance.

Body:
There is already a native Element.prototype.matches method which does that:

const el = document.createElement('span');
el.classList.add('test');
console.log(el.matches('span.test'));

Note that to check if a node is connected or not, there is the Node.prototype.isConnected getter.


问:
Connecting Flask To AWS RDS using Flask-SQLAlchemy
I have been trying to connect my aws RDS database instance to a flask application I have downloaded. I have been following  https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80 and using the flask app on this github to connect to the database https://github.com/inkjet/flask-aws-tutorial. I have set the permissions on my RDS server correctly and have been using the following code to connect to the DB.

```<code># edit the URI below to add your RDS password and your AWS URL
# The other elements are the same as used in the tutorial
# format: (user):(password)@(db_identifier).amazonaws.com:3306/(db_name)

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{userName}:{password}@{endpoint}:3306/{dbName}'

# Uncomment the line below if you want to work with a local DB
#SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'

SQLALCHEMY_POOL_RECYCLE = 3600

WTF_CSRF_ENABLED = True
</code>```

I am still receiving a timeout error:

```<code>    {path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")

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

Traceback (most recent call last):
  File "db_create.py", line 4, in <module>
    db.create_all()
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/sql/schema.py", line 4465, in create_all
    ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2103, in _run_visitor
    with self._optional_conn_ctx_manager(connection) as conn:
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2095, in _optional_conn_ctx_manager
    with self._contextual_connect() as conn:
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2311, in _contextual_connect
    self._wrap_pool_connect(self.pool.connect, None),
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2349, in _wrap_pool_connect
    e, dialect, self
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1591, in _handle_dbapi_exception_noconnection
    sqlalchemy_exception, with_traceback=exc_info[2], from_=e
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")
(Background on this error at: http://sqlalche.me/e/e3q8
</code>```

If any more information is needed, please let me know!

答:
Based on the comments, the issue was that RDS's  public accessibility setting was not enabled.

The solution was to enable it.

Body:
I have been trying to connect my aws RDS database instance to a flask application I have downloaded. I have been following  https://medium.com/@rodkey/deploying-a-flask-application-on-aws-a72daba6bb80 and using the flask app on this github to connect to the database https://github.com/inkjet/flask-aws-tutorial. I have set the permissions on my RDS server correctly and have been using the following code to connect to the DB.

# edit the URI below to add your RDS password and your AWS URL
# The other elements are the same as used in the tutorial
# format: (user):(password)@(db_identifier).amazonaws.com:3306/(db_name)

SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://{userName}:{password}@{endpoint}:3306/{dbName}'

# Uncomment the line below if you want to work with a local DB
#SQLALCHEMY_DATABASE_URI = 'sqlite:///test.db'

SQLALCHEMY_POOL_RECYCLE = 3600

WTF_CSRF_ENABLED = True

I am still receiving a timeout error:

    {path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py:834: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
  'SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and '
Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 583, in connect
    **kwargs)
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 728, in create_connection
    raise err
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")

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

Traceback (most recent call last):
  File "db_create.py", line 4, in <module>
    db.create_all()
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1039, in create_all
    self._execute_for_all_tables(app, bind, 'create_all')
  File "{path_to_virt_env}/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 1031, in _execute_for_all_tables
    op(bind=self.get_engine(app, bind), **extra)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/sql/schema.py", line 4465, in create_all
    ddl.SchemaGenerator, self, checkfirst=checkfirst, tables=tables
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2103, in _run_visitor
    with self._optional_conn_ctx_manager(connection) as conn:
  File "/usr/local/Cellar/python/3.7.7/Frameworks/Python.framework/Versions/3.7/lib/python3.7/contextlib.py", line 112, in __enter__
    return next(self.gen)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2095, in _optional_conn_ctx_manager
    with self._contextual_connect() as conn:
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2311, in _contextual_connect
    self._wrap_pool_connect(self.pool.connect, None),
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2349, in _wrap_pool_connect
    e, dialect, self
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1591, in _handle_dbapi_exception_noconnection
    sqlalchemy_exception, with_traceback=exc_info[2], from_=e
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2345, in _wrap_pool_connect
    return fn()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 364, in connect
    return _ConnectionFairy._checkout(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 778, in _checkout
    fairy = _ConnectionRecord.checkout(pool)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 495, in checkout
    rec = pool._do_get()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 140, in _do_get
    self._dec_overflow()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/impl.py", line 137, in _do_get
    return self._create_connection()
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 309, in _create_connection
    return _ConnectionRecord(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 440, in __init__
    self.__connect(first_connect_check=True)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 661, in __connect
    pool.logger.debug("Error on connect(): %s", e)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
    exc_value, with_traceback=exc_tb,
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
    raise exception
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/pool/base.py", line 656, in __connect
    connection = pool._invoke_creator(self)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect
    return dialect.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 490, in connect
    return self.dbapi.connect(*cargs, **cparams)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/__init__.py", line 94, in Connect
    return Connection(*args, **kwargs)
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 325, in __init__
    self.connect()
  File "{path_to_virt_env}/lib/python3.7/site-packages/pymysql/connections.py", line 630, in connect
    raise exc
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on '{endpoint}' (timed out)")
(Background on this error at: http://sqlalche.me/e/e3q8

If any more information is needed, please let me know!


问:
CURRENT_ROLE() behaviour in procedure vs function
I'd like to validate my observation of getting different result from CURRENT_ROLE() when called from a procedure vs UDF..

For Example, from the UI, I create below procedure and function as role_A:

```<code>create or replace procedure tst_exec_owner_proc()
  returns VARCHAR
  language javascript
  as
  $$
  // Set the second session variable
  var stmt = snowflake.createStatement(
      {sqlText: "select CURRENT_ROLE();"}
      );
  var rs = stmt.execute();
  rs.next();

  return rs.getColumnValue(1);
  $$
  ;

create or replace function tst_exec_owner_func()
  returns VARCHAR
  as
  $$
  select current_role()
  $$;
</code>```

Now, invoking the procedure, and function returns "role_A";
But once I switch to role_B, call tst_exec_owner_proc() returns "role_A" whereas select tst_exec_owner_func() returns "role_B". Is this expected behaviour (assuming role_A and role_B have necessary USAGE grants)?

答:
A stored procedure can execute with the privileges of the owner (an “owner’s rights” stored procedure) or with the privileges of the caller (a “caller’s rights” stored procedure). If you execute the statement CREATE PROCEDURE ... EXECUTE AS CALLER, then in the future the procedure will execute as a caller’s rights procedure. If you execute CREATE PROCEDURE ... EXECUTE AS OWNER, then the procedure will execute as an owner’s rights procedure. By default (if neither OWNER nor CALLER is specified explicitly at the time the procedure is created), the procedure runs as an owner’s rights stored procedure.

Try include EXECUTE AS CALLER in your code.

Body:
I'd like to validate my observation of getting different result from CURRENT_ROLE() when called from a procedure vs UDF..

For Example, from the UI, I create below procedure and function as role_A:

create or replace procedure tst_exec_owner_proc()
  returns VARCHAR
  language javascript
  as
  $$
  // Set the second session variable
  var stmt = snowflake.createStatement(
      {sqlText: "select CURRENT_ROLE();"}
      );
  var rs = stmt.execute();
  rs.next();

  return rs.getColumnValue(1);
  $$
  ;

create or replace function tst_exec_owner_func()
  returns VARCHAR
  as
  $$
  select current_role()
  $$;

Now, invoking the procedure, and function returns "role_A";
But once I switch to role_B, call tst_exec_owner_proc() returns "role_A" whereas select tst_exec_owner_func() returns "role_B". Is this expected behaviour (assuming role_A and role_B have necessary USAGE grants)?


问:
Mat-icon: when pressing a button all the icons change
I'm using Mat-card to display a list using an array and *ngFor and when pressed on the button, it will change the icon (mat-icon) only on the selected card but it changes for all the buttons in the list.

here's an example:

it's before pressing on the button and the condition to change the icon is false

but when I press it all the icons change.

here's my code:

```<code><mat-card  *ngFor="let a of items ;let i = index" class="item-card mat-card">

        <mat-card-header class="card-mat-header" style="margin-top: 10px;">
          <div class="card-mat-header-text"></div>

          <mat-card-title class="card-mat-title">{{a.name}}</mat-card-title>
          <mat-card-subtitle>Price :{{a.price}}</mat-card-subtitle>
        </mat-card-header>
        <div class="img-wrapper">
            <img class="mat-card-image"  src={{a.image}} alt="Photo of a Shiba Inu">

        </div>
        <mat-card-content>
          <p>
            {{a.desc}}
          </p>
        </mat-card-content>

        <mat-card-actions class="right-button" >
          <button  mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
            <mat-icon>{{iconName}}</mat-icon>{{itemStatis}} {{a.addedToCart}}
          </button>

        </mat-card-actions>
      </mat-card>
</code>```

also the used function:

```<code>  itemStatus(i){

      this.items[i].addedToCart =  !this.items[i].addedToCart
      if(this.items[i].addedToCart)
      {
        this.iconName = "shopping_cart";
        this.itemStatis= "Added";
      }
      else{
        this.iconName = "add_shopping_cart";
        this.itemStatis= "Add To Cart";
      }
    }
</code>```

please if anyone is familiar with this kind of mistake help me.

答:
You are maintaining the  iconName and itemStatis at component level not at the item level

Check the Example below

https://stackblitz.com/edit/angular-ivy-moun8k

In XComponent.ts change itemStatus to

```<code>itemStatus(i){
  this.items[i].addedToCart =  !this.items[i].addedToCart
}
</code>```

In HTML change Button section to

```<code><button  mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
  <mat-icon>{{a.addedToCart ? 'shopping_cart' : 'add_shopping_cart'}}</mat-icon>
    {{a.addedToCart ? 'Added' : 'Add To Cart'}}
</button>
</code>```

Body:
I'm using Mat-card to display a list using an array and *ngFor and when pressed on the button, it will change the icon (mat-icon) only on the selected card but it changes for all the buttons in the list.

here's an example:

it's before pressing on the button and the condition to change the icon is false

but when I press it all the icons change.

here's my code:

<mat-card  *ngFor="let a of items ;let i = index" class="item-card mat-card">

        <mat-card-header class="card-mat-header" style="margin-top: 10px;">

          <mat-card-title class="card-mat-title">{{a.name}}</mat-card-title>
          <mat-card-subtitle>Price :{{a.price}}</mat-card-subtitle>
        </mat-card-header>

        <mat-card-content>

            {{a.desc}}

        </mat-card-content>

        <mat-card-actions class="right-button" >
          <button  mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
            <mat-icon>{{iconName}}</mat-icon>{{itemStatis}} {{a.addedToCart}}
          </button>

        </mat-card-actions>
      </mat-card>

also the used function:

  itemStatus(i){

      this.items[i].addedToCart =  !this.items[i].addedToCart
      if(this.items[i].addedToCart)
      {
        this.iconName = "shopping_cart";
        this.itemStatis= "Added";
      }
      else{
        this.iconName = "add_shopping_cart";
        this.itemStatis= "Add To Cart";
      }
    }

please if anyone is familiar with this kind of mistake help me.

Body:
You are maintaining the  iconName and itemStatis at component level not at the item level

Check the Example below

https://stackblitz.com/edit/angular-ivy-moun8k

In XComponent.ts change itemStatus to

itemStatus(i){
  this.items[i].addedToCart =  !this.items[i].addedToCart
}

In HTML change Button section to

<button  mat-button class="mat-button mat-button-base" (click)="itemStatus(i)" >
  <mat-icon>{{a.addedToCart ? 'shopping_cart' : 'add_shopping_cart'}}</mat-icon>
    {{a.addedToCart ? 'Added' : 'Add To Cart'}}
</button>


问:
Hawk Authentication using retrofit in android
I am building an app which uses hawk authentication for apis. I am using retrofit for implementing api in the app. One of the few articles I found which explains how to do use hawk auth in retrofit is https://futurestud.io/tutorials/retrofit-2-hawk-authentication-on-android. This article mentions a class HawkAuthenticationInterceptor which i couldn't find anywhere. Is there any other way of adding hawk authorization header using retrofit.

Update : I am currently computing hawk auth on separate thread and adding it through @Authorization header. Also, in the current implementation the hawk credentials is based on timestamp and uses Hawk.calculateMAC. The final authorization header consists of hawkId,timestamp, nonce and mac.

Ex : Hawk id="hawkId", ts="15912131366", nonce="CQMZ4B", mac="W0n/pffeysCnj20OEk4WoeO86W5r2Pi9ZgjR2kre6SU="

答:
Tauntz on Reddit referenced the following solution

```<code>package br.com.xplore.xploreretrofit1.interceptors;

import com.wealdtech.hawk.HawkClient;
import com.wealdtech.hawk.HawkCredentials;

import java.io.IOException;
import java.net.URI;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by r028367 on 29/11/2017.
 */

public class HawkAuthenticationInterceptor implements Interceptor{

    private HawkClient hawkClient;

    public HawkAuthenticationInterceptor(HawkCredentials hawkCredentials) {
        this.hawkClient = new HawkClient.Builder()
                .credentials(hawkCredentials).build();

    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        URI uri = original.url().uri();
        String method = original.method();
        String header = hawkClient
                .generateAuthorizationHeader(uri, method, null
                        , null, null, null);
        Request.Builder requestBuilder = original.newBuilder()
                .header("Authorization", header)
                .method(method, original.body());
        return chain.proceed(requestBuilder.build());
    }
}
</code>```

https://github.com/chrislucas/xplore-retrofit-android/blob/master/XploreRetrofit1/app/src/main/java/br/com/xplore/xploreretrofit1/interceptors/HawkAuthenticationInterceptor.java

Body:
Tauntz on Reddit referenced the following solution

package br.com.xplore.xploreretrofit1.interceptors;

import com.wealdtech.hawk.HawkClient;
import com.wealdtech.hawk.HawkCredentials;

import java.io.IOException;
import java.net.URI;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by r028367 on 29/11/2017.
 */

public class HawkAuthenticationInterceptor implements Interceptor{

    private HawkClient hawkClient;

    public HawkAuthenticationInterceptor(HawkCredentials hawkCredentials) {
        this.hawkClient = new HawkClient.Builder()
                .credentials(hawkCredentials).build();

    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request original = chain.request();
        URI uri = original.url().uri();
        String method = original.method();
        String header = hawkClient
                .generateAuthorizationHeader(uri, method, null
                        , null, null, null);
        Request.Builder requestBuilder = original.newBuilder()
                .header("Authorization", header)
                .method(method, original.body());
        return chain.proceed(requestBuilder.build());
    }
}

https://github.com/chrislucas/xplore-retrofit-android/blob/master/XploreRetrofit1/app/src/main/java/br/com/xplore/xploreretrofit1/interceptors/HawkAuthenticationInterceptor.java


问:
Spring Security Oauth oauth2UserService(works on github but doesn't work on google)
I am learning tutorial https://spring.io/guides/tutorials/spring-boot-oauth2/
in the last example there is an example of adding error message.
Everything seems work fine but i don't understand why when i login with github this bean works
but when i login with google it doesn't work.(When i debug it breakpoint stops on github login and doesn't stop when login via google).
Where is noticed that is only for github?
bean(fully from example):</p>

```<code>@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService(WebClient rest) {
    DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();// breakpoint here
    return request -> {
        OAuth2User user = delegate.loadUser(request); //and breakpoint here
        if (!"github".equals(request.getClientRegistration().getRegistrationId())) {
            return user;
        }

        OAuth2AuthorizedClient client = new OAuth2AuthorizedClient
                (request.getClientRegistration(), user.getName(), request.getAccessToken());
        String url = user.getAttribute("organizations_url");
        List<Map<String, Object>> orgs = rest
                .get().uri(url)
                .attributes(oauth2AuthorizedClient(client))
                .retrieve()
                .bodyToMono(List.class)
                .block();

        if (orgs.stream().anyMatch(org -> "spring-projects".equals(org.get("login")))) {
            return user;
        }

        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token", "Not in Spring Team", ""));
    };
}
</code>```

答:
You can use OidcUserService to hook google oauth authentication process.

Check the article below.

https://www.devglan.com/spring-security/spring-boot-security-google-oauth

wish this helps..

Body:
I am learning tutorial https://spring.io/guides/tutorials/spring-boot-oauth2/
in the last example there is an example of adding error message.
Everything seems work fine but i don't understand why when i login with github this bean works
but when i login with google it doesn't work.(When i debug it breakpoint stops on github login and doesn't stop when login via google).
Where is noticed that is only for github?
bean(fully from example):

@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService(WebClient rest) {
    DefaultOAuth2UserService delegate = new DefaultOAuth2UserService();// breakpoint here
    return request -> {
        OAuth2User user = delegate.loadUser(request); //and breakpoint here
        if (!"github".equals(request.getClientRegistration().getRegistrationId())) {
            return user;
        }

        OAuth2AuthorizedClient client = new OAuth2AuthorizedClient
                (request.getClientRegistration(), user.getName(), request.getAccessToken());
        String url = user.getAttribute("organizations_url");
        List<Map<String, Object>> orgs = rest
                .get().uri(url)
                .attributes(oauth2AuthorizedClient(client))
                .retrieve()
                .bodyToMono(List.class)
                .block();

        if (orgs.stream().anyMatch(org -> "spring-projects".equals(org.get("login")))) {
            return user;
        }

        throw new OAuth2AuthenticationException(new OAuth2Error("invalid_token", "Not in Spring Team", ""));
    };
}


问:
JSON file prints one character per line
I am trying to print the primary catchall but every time I do it it returns one character per line, how do I make it so it prints the whole catchall in one line.

Result:

```<code>@
g
m
a
i
l
.
c
o
m
</code>```

Expected result: @gmail.com

JSON Code:

```<code>{
    "primaryCatchall": "@gmail.com",
    "secondaryCatchall": "@gmail.com",
    "password": "password123",
    "repeat": 5
}
</code>```

Python code:

```<code>import json

with open('tempemail.txt', 'r') as myfile1:
    email1 = myfile1.read()
    with open('config.json', 'r') as config:
        PrimaryCatchall = json.load(config)
    for primaryCatchall in PrimaryCatchall['primaryCatchall']:
        with open('accounts.txt', 'a') as accounts:
            print(primaryCatchall)
            #accounts.write("\n")
            #accounts.write(email1)
            #accounts.write(primaryCatchall)
</code>```

答: In your code, you loaded your JSON as the variable PrimaryCatchall. Right afterward, you ran a for loop for PrimaryCatchall, which got each individual character. Get rid of that for loop to fix the problem

Title: JSON file prints one character per line

Body:
I am trying to print the primary catchall but every time I do it it returns one character per line, how do I make it so it prints the whole catchall in one line.

Result:

@
g
m
a
i
l
.
c
o
m

Expected result: @gmail.com

JSON Code:

{
    "primaryCatchall": "@gmail.com",
    "secondaryCatchall": "@gmail.com",
    "password": "password123",
    "repeat": 5
}

Python code:

import json

with open('tempemail.txt', 'r') as myfile1:
    email1 = myfile1.read()
    with open('config.json', 'r') as config:
        PrimaryCatchall = json.load(config)
    for primaryCatchall in PrimaryCatchall['primaryCatchall']:
        with open('accounts.txt', 'a') as accounts:
            print(primaryCatchall)
            #accounts.write("\n")
            #accounts.write(email1)
            #accounts.write(primaryCatchall)


问:
Move Image inside the Picturebox using mouse events
I have this code where I upload/place an image inside a pictureBox. What I want to do now is to drag it inside the pictureBox using MouseEvents. How do I do that when my Image is drawn using another class?

Image Class

```<code>public void ImageDrawing(Bitmap bm, RectangleF rect, PaintEventArgs e)
    {
        this.image = bm;
        this.width = rect.Width;
        this.height = rect.Height;
        this.rect = rect;
        Graphics g = e.Graphics;
        bm = ImageClass.GrayscaleImage(bm);
        bm.MakeTransparent(Color.White);
        g.DrawImage(bm, rect);
    }
</code>```

Main Form

```<code>private void btn_Browse_Click(object sender, EventArgs e)
    {
        PaintImage();
    }
    public void PaintImage()
    {
        buttons = (Shape.ShapeType)System.Enum.Parse(typeof(Shape.ShapeType), "image");
        // open file dialog
        OpenFileDialog open = new OpenFileDialog();
        // image filters
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";
        if (open.ShowDialog() == DialogResult.OK)
        {
            //Display image in picture box
            string strType = Path.GetExtension(open.FileName);
            FileInfo fs = new FileInfo(open.FileName);
            long fileSize = fs.Length / 1024;
            ImageBitmap = new Bitmap(open.FileName);
        }
        imageHeight = ImageBitmap.Height / 3f;
        imageWidth = ImageBitmap.Width / 3f;
        imageX = (shape.center.X - (imageWidth / 2));
        imageY = (shape.center.Y - (imageHeight / 2));
        imageRect = new RectangleF(imageX, imageY, imageWidth, imageHeight);
        pictureBox_Canvass.Refresh();
    }
</code>```

答:
I have implemented moving the image inside the picture box by mouse dragging using TaW's code as reference. Please see the events for the picturebox Mouse and Paint.</p>

```<code>
// Global Variables
private int _xPos;
private int _yPos;
private bool _dragging;
Image _img;
Rectangle _imgRect;

private void pictureBox1_MouseUp(
  object sender, MouseEventArgs e) {
  var c = sender as PictureBox;
  if (null == c) return;
  _dragging = false;
}

private void pictureBox1_MouseDown(
  object sender, MouseEventArgs e) {
  if (e.Button != MouseButtons.Left) return;
  _dragging = true;
  _xPos = e.X;
  _yPos = e.Y;
}

private void pictureBox1_MouseMove(
  object sender, MouseEventArgs e) {
  if (!_dragging || _img == null ) return;

  if (e.Button == MouseButtons.Left) {
    _imgRect = new Rectangle(-(_xPos-e.X), -(_yPos - e.Y), _img.Width, _img.Height);
    pictureBox1.Invalidate();
  }
}

private void pictureBox1_Paint(
object sender, PaintEventArgs e) {
  if (_img != null) {
    e.Graphics.DrawImage(_img, _imgRect);
  }
}
</code>```

Body:
I have this code where I upload/place an image inside a pictureBox. What I want to do now is to drag it inside the pictureBox using MouseEvents. How do I do that when my Image is drawn using another class?

Image Class

public void ImageDrawing(Bitmap bm, RectangleF rect, PaintEventArgs e)
    {
        this.image = bm;
        this.width = rect.Width;
        this.height = rect.Height;
        this.rect = rect;
        Graphics g = e.Graphics;
        bm = ImageClass.GrayscaleImage(bm);
        bm.MakeTransparent(Color.White);
        g.DrawImage(bm, rect);
    }

Main Form

private void btn_Browse_Click(object sender, EventArgs e)
    {
        PaintImage();
    }
    public void PaintImage()
    {
        buttons = (Shape.ShapeType)System.Enum.Parse(typeof(Shape.ShapeType), "image");
        // open file dialog
        OpenFileDialog open = new OpenFileDialog();
        // image filters
        open.Filter = "Image Files(*.jpg; *.jpeg; *.gif; *.bmp); *.PNG|*.jpg; *.jpeg; *.gif; *.bmp; *.PNG";
        if (open.ShowDialog() == DialogResult.OK)
        {
            //Display image in picture box
            string strType = Path.GetExtension(open.FileName);
            FileInfo fs = new FileInfo(open.FileName);
            long fileSize = fs.Length / 1024;
            ImageBitmap = new Bitmap(open.FileName);
        }
        imageHeight = ImageBitmap.Height / 3f;
        imageWidth = ImageBitmap.Width / 3f;
        imageX = (shape.center.X - (imageWidth / 2));
        imageY = (shape.center.Y - (imageHeight / 2));
        imageRect = new RectangleF(imageX, imageY, imageWidth, imageHeight);
        pictureBox_Canvass.Refresh();
    }

Body:
I have implemented moving the image inside the picture box by mouse dragging using TaW's code as reference. Please see the events for the picturebox Mouse and Paint.

// Global Variables
private int _xPos;
private int _yPos;
private bool _dragging;
Image _img;
Rectangle _imgRect;

private void pictureBox1_MouseUp(
  object sender, MouseEventArgs e) {
  var c = sender as PictureBox;
  if (null == c) return;
  _dragging = false;
}

private void pictureBox1_MouseDown(
  object sender, MouseEventArgs e) {
  if (e.Button != MouseButtons.Left) return;
  _dragging = true;
  _xPos = e.X;
  _yPos = e.Y;
}

private void pictureBox1_MouseMove(
  object sender, MouseEventArgs e) {
  if (!_dragging || _img == null ) return;

  if (e.Button == MouseButtons.Left) {
    _imgRect = new Rectangle(-(_xPos-e.X), -(_yPos - e.Y), _img.Width, _img.Height);
    pictureBox1.Invalidate();
  }
}

private void pictureBox1_Paint(
object sender, PaintEventArgs e) {
  if (_img != null) {
    e.Graphics.DrawImage(_img, _imgRect);
  }
}


问:
Cannot convert value of type '[array]' to expected argument type 'Range<Int>'
I can not understand what could be the problem

i have some Json
for example is

```<code>[
{
    "id": 1,
    "title": "Title",
    "info": "info",
    "brand": "brand",
    "model": "MODEL",
    "make_year": year,
    "properties": [
        {
                "id": 1,
                "icon": "ic_rgb",
                "label": "color",
                "value": "red"
            },
            {
                "id": 2,
                "icon": "ic_car",
                "label": "type",
                "value": "value"
            },
            {   "id": 3,
                "icon": "ic_fuel",
                "label": "fuel",
                "value": "gas"
            }
        ],
    },
{
    "id": 2,
    "title": "title2",
    "message": "massage2",
    "info": "wow you are amazing, thanks for the help",
    "properties": [
        {
                "id": 11,
                "icon": "ic_rgb",
                "label": "2color",
                "value": "2blue"
            },
            {
                "id": 21,
                "icon": "ic_car",
                "label": "2type",
                "value": "2cgh"
            },
            {   "id": 31,
                "icon": "ic_fuel",
                "label": "fuel",
                "value": "test"
            },
            ....
        ],
}
]
</code>```

and my model

```<code>struct Unicards: Hashable, Codable, Identifiable {
var id: Int
var title: String?
var info: String?
var brand: String?
var model: String?
var make_year: Int?
var messege: String?
var messege_color: String?
var price: String?
var price_currency: String?
var price_tooltip: String?

var properties: [HPropert]?
struct HPropert: Hashable, Codable, Identifiable {

    var id: Int
    var icon: String?
    var label: String
    var value: String

}
</code>```

and what the problem... i'm trying to create forEach method for horizontal collection for properties

I partially succeeded, I implemented this method with a nested array, and it even generates the number of cells correctly. wow!)

but when I want to assign values for the text by index it gives an error ...

I actually can not understand the problem, since the array has already been calculated and created by the number of cell objects.

but when I ask the formula to assign values I get

```<code>Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'
</code>```

my code below

```<code>struct Card_cell_rowOfCheracteristics: View {

var data2: Unicards

var body: some View {
    let properties = data2.properties!

    return    VStack() {
//            Text("thanx bro!. have a nice day")
//                .font(.system(size: 14))
//                .font(.headline)
//                .fontWeight(.light)
//                .multilineTextAlignment(.leading)

        ScrollView(Axis.Set.horizontal) {

            HStack {

                ForEach(properties) { card in <--- Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'
                    VStack {
                        Image()
                            .resizable()
                            .scaledToFit()
                            .frame(width: 34, height: 34)

                        VStack {

                            Text(properties[card].label)
                                .font(.system(size: 14))
                                .fontWeight(.medium)
                            Text(properties[card].value)
                                .font(.system(size: 14))
                        }

                    }
                }
            }
        }

    }
}

struct Card_cell_rowOfCheracteristics_Previews: PreviewProvider {
    static var previews: some View {
        Card_cell_rowOfCheracteristics(data2: PlatesData[0])
    }
}
}
</code>```

but if i say

```<code>properties[0].label
</code>```

no errors occur

答:
This error indicates your data2.properties!'s type does not conform to the Identifiable protocol.
Say, if your data2.properties!'s type is A, then try to do:

```<code>struct A: Identifiable {
    ...
    var id: String {
        return /*some ID*/
    }
    ...
}
</code>```

This should fix your problem "behind the hood".

Body:
I can not understand what could be the problem

i have some Json
for example is

[
{
    "id": 1,
    "title": "Title",
    "info": "info",
    "brand": "brand",
    "model": "MODEL",
    "make_year": year,
    "properties": [
        {
                "id": 1,
                "icon": "ic_rgb",
                "label": "color",
                "value": "red"
            },
            {
                "id": 2,
                "icon": "ic_car",
                "label": "type",
                "value": "value"
            },
            {   "id": 3,
                "icon": "ic_fuel",
                "label": "fuel",
                "value": "gas"
            }
        ],
    },
{
    "id": 2,
    "title": "title2",
    "message": "massage2",
    "info": "wow you are amazing, thanks for the help",
    "properties": [
        {
                "id": 11,
                "icon": "ic_rgb",
                "label": "2color",
                "value": "2blue"
            },
            {
                "id": 21,
                "icon": "ic_car",
                "label": "2type",
                "value": "2cgh"
            },
            {   "id": 31,
                "icon": "ic_fuel",
                "label": "fuel",
                "value": "test"
            },
            ....
        ],
}
]

and my model

struct Unicards: Hashable, Codable, Identifiable {
var id: Int
var title: String?
var info: String?
var brand: String?
var model: String?
var make_year: Int?
var messege: String?
var messege_color: String?
var price: String?
var price_currency: String?
var price_tooltip: String?

var properties: [HPropert]?
struct HPropert: Hashable, Codable, Identifiable {

    var id: Int
    var icon: String?
    var label: String
    var value: String

}

and what the problem... i'm trying to create forEach method for horizontal collection for properties

I partially succeeded, I implemented this method with a nested array, and it even generates the number of cells correctly. wow!)

but when I want to assign values for the text by index it gives an error ...

I actually can not understand the problem, since the array has already been calculated and created by the number of cell objects.

but when I ask the formula to assign values I get

Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'

my code below

struct Card_cell_rowOfCheracteristics: View {

var data2: Unicards

var body: some View {
    let properties = data2.properties!

    return    VStack() {
//            Text("thanx bro!. have a nice day")
//                .font(.system(size: 14))
//                .font(.headline)
//                .fontWeight(.light)
//                .multilineTextAlignment(.leading)

        ScrollView(Axis.Set.horizontal) {

            HStack {

                ForEach(properties) { card in <--- Cannot convert value of type '[Unicards.HPropert]' to expected argument type 'Range<Int>'
                    VStack {
                        Image()
                            .resizable()
                            .scaledToFit()
                            .frame(width: 34, height: 34)

                        VStack {

                            Text(properties[card].label)
                                .font(.system(size: 14))
                                .fontWeight(.medium)
                            Text(properties[card].value)
                                .font(.system(size: 14))
                        }

                    }
                }
            }
        }

    }
}

struct Card_cell_rowOfCheracteristics_Previews: PreviewProvider {
    static var previews: some View {
        Card_cell_rowOfCheracteristics(data2: PlatesData[0])
    }
}
}

but if i say

properties[0].label

no errors occur

Body:
This error indicates your data2.properties!'s type does not conform to the Identifiable protocol.
Say, if your data2.properties!'s type is A, then try to do:

struct A: Identifiable {
    ...
    var id: String {
        return /*some ID*/
    }
    ...
}

This should fix your problem "behind the hood".


问:
nuxt-i18n Strategy:no_prefix
I'm trying to use nuxt-i18n to get internationalization for my application, the following are the nuxt-i18n configs and it works fine, but when I want to use strategy: 'no_prefix' it gives errors ... not sure what to do, please suggest.

```<code>i18n: {
    //strategy: 'no_prefix',
    defaultLocale: 'en',
    locales: [
      {
        code: 'en',
        name: 'English',
        iso: 'en-US',
        file: 'english.js'
      },
      {
        code: 'hi',
        name: 'Hindi',
        file: 'hindi.js'
      }
    ],
    lazy: true,
    langDir: 'static/locales/'
  },
</code>```

https://nuxt-community.github.io/nuxt-i18n/routing.html#strategy

WARN  [nuxt-i18n] Passing non-current locale to switchLocalePath is
  unsupported when using no_prefix strategy

  19:39:39

WARN  [nuxt-i18n] Passing non-current locale to localePath is
  unsupported when using no_prefix strategy

  19:39:39

答:
If you are using the no_prefix strategy you won't get the benefit for using the path functions that is provided by the module. For example those 2 switchLocalePath & localePath is not supported when using no_prefix. As the docs say:

```<code>This implies that you have to rely on browser & cookie detection, and implement locale switches by calling the i18n API.
</code>```

So you should use the APIs that are provided by the module in order to change the locale. One of example in my project is when user want's to change a locale I added a handler and change the locale by calling this:

this.$i18n.setLocale('en')

or

root.$i18n.setLocale(langCode) (if using the composition-api)

Title: nuxt-i18n Strategy:no_prefix

Body:
I'm trying to use nuxt-i18n to get internationalization for my application, the following are the nuxt-i18n configs and it works fine, but when I want to use strategy: 'no_prefix' it gives errors ... not sure what to do, please suggest.

i18n: {
    //strategy: 'no_prefix',
    defaultLocale: 'en',
    locales: [
      {
        code: 'en',
        name: 'English',
        iso: 'en-US',
        file: 'english.js'
      },
      {
        code: 'hi',
        name: 'Hindi',
        file: 'hindi.js'
      }
    ],
    lazy: true,
    langDir: 'static/locales/'
  },

https://nuxt-community.github.io/nuxt-i18n/routing.html#strategy

WARN  [nuxt-i18n] Passing non-current locale to switchLocalePath is
  unsupported when using no_prefix strategy

  19:39:39

WARN  [nuxt-i18n] Passing non-current locale to localePath is
  unsupported when using no_prefix strategy

  19:39:39

Body:
If you are using the no_prefix strategy you won't get the benefit for using the path functions that is provided by the module. For example those 2 switchLocalePath & localePath is not supported when using no_prefix. As the docs say:

This implies that you have to rely on browser & cookie detection, and implement locale switches by calling the i18n API.

So you should use the APIs that are provided by the module in order to change the locale. One of example in my project is when user want's to change a locale I added a handler and change the locale by calling this:

this.$i18n.setLocale('en')

or

root.$i18n.setLocale(langCode) (if using the composition-api)


问:
How to find authentication SSH logs for Linux
I am trying to write a query via splunk to find SSH logs used for authentication in Linux. Any ideas as to the query needed to writer to achieve this? I am new to splunk so any information would help.

Here is what I have started but to no avail:

sshd "Invalid user" NOT port NOT "preauth]" | iplocation InvalidSSHIP

答:
I strongly suggest you use the Splunk TA for Nix, https://splunkbase.splunk.com/app/833/

In it, you will find common inputs and field extractions for SSH event logs, as well as other common *nix formats.

If you follow this TA, you should be able to find the events you are looking for with the following search

```<code>index=os eventtype=ssh*
</code>```

Body:
I strongly suggest you use the Splunk TA for Nix, https://splunkbase.splunk.com/app/833/

In it, you will find common inputs and field extractions for SSH event logs, as well as other common *nix formats.

If you follow this TA, you should be able to find the events you are looking for with the following search

index=os eventtype=ssh*


问:
SwiftUI Preview timeout for large project
I've been trying to preview SwiftUI files in my large iOS project and cannot get past this error TimeoutError: Timed out waiting for a thunk to build after 30.0 seconds.

What's interesting/confusing is that a newly created SwiftUI file with the default "Hello World" Text does successfully load the preview in the same project, however more complex SwiftUI files show the time out error even when I change the preview struct to display a Text("Hello World") view.

Has anyone else experienced this or could point in what direction I can dig to fix this timeout issue?

答: In case it helps someone else... I ended being able to load the previews by temporarily setting the project to iOS 13 development target (normally it's iOS 12). Thankfully we'll be dropping iOS 12 soon so this won't be an issue after that.</p>


问:
PHP Cookie management
here is what my client requirements are:

1> There is a common web page that lets each of the customer login. On successful login, a cookie is created and the customer is redirected to a "Waiting area" page. I need to create a cookie that would last for 10 secs and keep refreshing the time until the customer has closed the window.

2> The admin page will list all the customers who have not yet closed the "Waiting area" page and are waiting on the admin to move forward.

Since I am new to session and cookie management, I am not sure exactly what needs to be done here i.e. use session_start or setcookie ? Since the admin needs a list of all customers waiting, I guess all these entries need to go in a database table? And whenever a customer closes the page, the entry should be deleted from the database.

Is my understanding correct? If anyone has better suggestions, please let me know.

答:
Your requirements are strange, I cannot figure out why any user would "wait" on a "Waiting area" page.  I would rethink the 10 sec. cookie part.

For data persistance, I would recommend you use sessions  as they are pretty easy to integrate to that type of context.

Title: PHP Cookie management