答:
Remember each variable lives somewhere in memory. When you replace \bkey with Dimension, which variable holds the new string? And which variable do you check, to see if it ends in Dimension?

Take care to pay attention to these sort of memory concerns, asking yourself whether you're updating the variable itself, or a copy of the variable. These types of bugs will pop up all the time.

Title: Nested if loop not firing in python

Body:
I have a python question and I can't figure out why this is not firing. Below is the code:

import re
sfname='C:\python_Script\Testmain.txt'
i=0
Var1='AS'
Var2=''
Var3=''

with open("C:\python_Script\Testmain.txt") as file_in:
    lines = []
    for line in file_in:
        lines.append(line)
        if line.startswith('create view [dbo].'):
            print (lines[i])
        if not line.startswith('create view [dbo].'):
            lines[i]=lines[i].replace("_"," ")
            lines[i]= re.sub(r"\bid","key",lines[i])
            Var2=lines[i]
            Var2=re.sub(r"\bkey","Dimension",Var2)
            if not line.endswith("Dimension"):
                Var2='Fact Table'
            Var3=lines[i] +"    "+Var1+"    "+Var2

            print(Var3)
        i+=1

the text file I'm reading from is relatively simple it has these attributes in it:

create view [dbo].Ignore_table
communication_channel_id
user_id
bounce_count
assignment_override_id
create view [dbo].test1
id
test1

basically I want to ignore anything with 'create view[dbo].' and create a print statement which replaces the word 'ID' with 'Key' adds an AS and then does 1 of 2 things:
if) Var2 ends with 'Key' replace with the word 'Dimension'.
if) var2 does not end with 'Key' then rename the whole thing 'Fact table'

but for some reason this second if the loop will fire even if it does not end with 'dimension' and it will always be 'Fact Table' Why?


来源: stackexchange

问:
Are there implications with destructuring getState() (in a Redux Think) as opposed to calling it many times?
Are there any implications when destructuring getState() in a Redux thunk?

I find that it's much more readable to do something like const {bar, foo} = getState().app as opposed to getState().app.bar and getState().app.foo everywhere.

Is there an argument (or proof rather) that it's actually cheaper doing a variable assignment or calling the getState() function multiple times?

答:
No perf implications.

getState's implementation is just return currentState.

Personally, I'd only call it once in a given function just because there's no benefit to calling it more than once.

ContentLicense: CC BY-SA 4.0


问:
Python loses connection to MySQL database after about a day
I am developing a web-based application using Python, Flask, MySQL, and uWSGI. However, I am not using SQL Alchemy or any other ORM. I am working with a preexisting database from an old PHP application that wouldn't play well with an ORM anyway, so I'm just using mysql-connector and writing queries by hand.

The application works correctly when I first start it up, but when I come back the next morning I find that it has become broken. I'll get errors like mysql.connector.errors.InterfaceError: 2013: Lost connection to MySQL server during query or the similar mysql.connector.errors.OperationalError: 2055: Lost connection to MySQL server at '10.0.0.25:3306', system error: 32 Broken pipe.

I've been researching it and I think I know what the problem is. I just haven't been able to find a good solution. As best as I can figure, the problem is the fact that I am keeping a global reference to the database connection, and since the Flask application is always running on the server, eventually that connection expires and becomes invalid.

I imagine it would be simple enough to just create a new connection for every query, but that seems like a far from ideal solution. I suppose I could also build some sort of connection caching mechanism that would close the old connection after an hour or so and then reopen it. That's the best option I've been able to come up with, but I still feel like there ought to be a better one.

I've looked around, and most people that have been receiving these errors have huge or corrupted tables, or something to that effect. That is not the case here. The old PHP application still runs fine, the tables all have less than about 50,000 rows, and less than 30 columns, and the Python application runs fine until it has sat for about a day.

So, here's to hoping someone has a good solution for keeping a continually open connection to a MySQL database. Or maybe I'm barking up the wrong tree entirely, if so hopefully someone knows.

答:
I have it working now. Using pooled connections seemed to fix the issue for me.

mysql.connector.connect(
    host='10.0.0.25',
    user='xxxxxxx',
    passwd='xxxxxxx',
    database='xxxxxxx',
    pool_name='batman',
    pool_size = 3
)

def connection():
    """Get a connection and a cursor from the pool"""
    db = mysql.connector.connect(pool_name = 'batman')
    return (db, db.cursor())
```
<p>I call <code>connection()</code> before each query function and then close the cursor and connection before returning. Seems to work. Still open to a better solution though.</p>
<h2>Edit</h2>
<p>I have since found a better solution. (I was still occasionally running into issues with the pooled connections). There is actually a dedicated library for Flask to handle mysql connections, which is almost a drop-in replacement.</p>
<p>From bash: <code>pip install Flask-MySQL</code></p>
<p>Add <code>MYSQL_DATABASE_HOST</code>, <code>MYSQL_DATABASE_USER</code>, <code>MYSQL_DATABASE_PASSWORD</code>, <code>MYSQL_DATABASE_DB</code> to your Flask config. Then in the main Python file containing your Flask App object:</p>
<pre class="lang-py prettyprint-override"><code>from flaskext.mysql import MySQL
mysql = MySQL()
mysql.init_app(app)
</code>```

And to get a connection: mysql.get_db().cursor()

All other syntax is the same, and I have not had any issues since. Been using this solution for a long time now.

Body:
I have it working now. Using pooled connections seemed to fix the issue for me.

mysql.connector.connect(
    host='10.0.0.25',
    user='xxxxxxx',
    passwd='xxxxxxx',
    database='xxxxxxx',
    pool_name='batman',
    pool_size = 3
)

def connection():
    """Get a connection and a cursor from the pool"""
    db = mysql.connector.connect(pool_name = 'batman')
    return (db, db.cursor())

I call connection() before each query function and then close the cursor and connection before returning. Seems to work. Still open to a better solution though.

Edit

I have since found a better solution. (I was still occasionally running into issues with the pooled connections). There is actually a dedicated library for Flask to handle mysql connections, which is almost a drop-in replacement.

From bash: pip install Flask-MySQL

Add MYSQL_DATABASE_HOST, MYSQL_DATABASE_USER, MYSQL_DATABASE_PASSWORD, MYSQL_DATABASE_DB to your Flask config. Then in the main Python file containing your Flask App object:

from flaskext.mysql import MySQL
mysql = MySQL()
mysql.init_app(app)

And to get a connection: mysql.get_db().cursor()

All other syntax is the same, and I have not had any issues since. Been using this solution for a long time now.


问:
AVAudioPlayer Error using iOS Simulator
following problem:

```<code><0xb03e7000> Error '!obj' trying to fetch default input device's sample rate
<0xb03e7000> Error getting audio input device sample rate: '!obj'
<0xb03e7000> AQMEIOManager::FindIOUnit: error '!dev'
</code>```

I found this problem already here on stackoverflow but none of the
provided solutions worked for me.

Code:

```<code>#import "CJTActionViewController.h"

@interface CJTActionViewController()

@property NSURL *url;
@property NSData *songFile;
@property AVAudioPlayer *audioPlayer;

@end

@implementation CJTActionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/cannon_01.wav", [[NSBundle mainBundle] resourcePath]]];
    self.songFile = [[NSData alloc] initWithContentsOfURL:self.url];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:self.songFile error:nil];
    self.audioPlayer.delegate = self;
    self.audioPlayer.numberOfLoops = 0;
}

- (IBAction)firePressed(id):sender
{
    [self.audioPlayer play];
}

@end
</code>```

Delegate is set. Dont know if its important but on another mac this
code runs without problems.

I use ios 6.1 and simulator 6.1

答:
My solution was:
- Set the System preference, Audio input to something else than Internal Mic
- In Simulator, set the input to Internal Mic
If both of them are the same, it "locks" the Mic somehow.

To all: thanks for answers. I really thought it was my programming bad, but really, it's due to bad design by Apple.
This topic was raised 6 years ago and Apple has still not get rid of this bug!

ContentLicense: CC BY-SA 3.0

Title: AVAudioPlayer Error using iOS Simulator

Body:
following problem:

<0xb03e7000> Error '!obj' trying to fetch default input device's sample rate
<0xb03e7000> Error getting audio input device sample rate: '!obj'
<0xb03e7000> AQMEIOManager::FindIOUnit: error '!dev'

I found this problem already here on stackoverflow but none of the
provided solutions worked for me.

Code:

#import "CJTActionViewController.h"

@interface CJTActionViewController()

@property NSURL *url;
@property NSData *songFile;
@property AVAudioPlayer *audioPlayer;

@end

@implementation CJTActionViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.url = [NSURL fileURLWithPath: [NSString stringWithFormat:@"%@/cannon_01.wav", [[NSBundle mainBundle] resourcePath]]];
    self.songFile = [[NSData alloc] initWithContentsOfURL:self.url];
    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:self.songFile error:nil];
    self.audioPlayer.delegate = self;
    self.audioPlayer.numberOfLoops = 0;
}

- (IBAction)firePressed(id):sender
{
    [self.audioPlayer play];
}

@end

Delegate is set. Dont know if its important but on another mac this
code runs without problems.

I use ios 6.1 and simulator 6.1


问:
8086 can't access to external memory
we're working on a proteus simulation that actually has 8x(2KB) external memory (6116) but as we tried so far can't access to external memory. The Question said that external memory address should start at 0x14000 and we designed the proper decoder logic; and tried three ways to access such an address as below:

Goal: to move a value from internal registers to external memory startng at 0x14000

1- using ORG & MOV instruction together

2- using ORG $ PUSH-POP instruction together

3- without using ORG instruction + moving 1400 to DS (DataSegmentRegister)

but non of them worked
any help would be appreciated

https://drive.google.com/open?id=1Eznyj0pQfS2ccj5eIesYnnle01v2ftId

答:
one possible solution was to write the first memory access (only), twice.

this may related to a bug in Proteus and it's really strange

as you can see, the 00h memory access instructions repeated twice but for others like 01h instructions are normally worked without repeating

and the working snippet was sth like the following ...

```<code>MOV AX,DATA_HERE
MOV DS, AX

MOV AX,1400H
MOV DS , AX

MOV CL,07H
MOV BX,00h
MOV [BX],CL

MOV CL,09H
MOV BX,00h
MOV [BX],CL

MOV CL,08h
MOV BX,01h
MOV [BX],CL
</code>```

Title: 8086 can't access to external memory

Body:
one possible solution was to write the first memory access (only), twice.

this may related to a bug in Proteus and it's really strange

as you can see, the 00h memory access instructions repeated twice but for others like 01h instructions are normally worked without repeating

and the working snippet was sth like the following ...

MOV AX,DATA_HERE
MOV DS, AX

MOV AX,1400H
MOV DS , AX

MOV CL,07H
MOV BX,00h
MOV [BX],CL

MOV CL,09H
MOV BX,00h
MOV [BX],CL

MOV CL,08h
MOV BX,01h
MOV [BX],CL


问:
MultiLine Regular Expression and outputting to a file in windows
I have an log file that I need to extract specific patterns from.  I need to find and then process them into a new file. grep on Linux would usually do the trick but the regular expression spans multiple lines, which I understand grep does not do.

here is an example from my log/debug file:

```<code>Da:
1.328   0.5045

Db:
0.6415  0.1192

Lambda:
0.4429  -0.35
-0.0461 -0.02421

seps:
0.714272
</code>```

I'm looking for /Lambda:\n([-\d\.]+)\s+([\-\d\.]+)\s+\n([\-\d\.]+)\s+([\-\d\.]+)/  I then want to output the lines to a new file removing the lambda and rearrange the numbers onto the same line so output \1\s\2\s\3\s\4\n

So I have actually two questions:

Is there an easy utility to accomplish this, on any system?

Is there a way to do this specifically on windows?

I'm hoping there is a simple solution to this that has escaped me.  I would rather stay in windows but if I have to go to Linux I will to get this done.

答:
thanks for all the answers.  I like the answers you gave me for the perl and awk.  I'm one of those weird programmers that doesn't know perl, so I took the ruby route.  here is my solution

```<code>x=ARGV[0]
f=File.new(ARGV[1])
g=File.new(ARGV[2],"w")
f.read.gsub(/#{x}:\s*(([\d\.\-]*\t*)+\n)+/ ){|entry|
    puts entry
    g.puts entry.gsub(/#{x}:\n/,'').gsub(/\s+/,"\t").strip
}
</code>```

this I can use as a utility with my editor Notepad++ through NppExec, which does not support redirect and piping, as far as I know.  This also allows for me to collect any of the output that I need to diagnose by program.  Thanks again y'all.

OwnerDisplayName: Halpo

ContentLicense: CC BY-SA 2.5

Body:
I have an log file that I need to extract specific patterns from.  I need to find and then process them into a new file. grep on Linux would usually do the trick but the regular expression spans multiple lines, which I understand grep does not do.

here is an example from my log/debug file:

Da:
1.328   0.5045

Db:
0.6415  0.1192

Lambda:
0.4429  -0.35
-0.0461 -0.02421

seps:
0.714272

I'm looking for /Lambda:\n([-\d\.]+)\s+([\-\d\.]+)\s+\n([\-\d\.]+)\s+([\-\d\.]+)/  I then want to output the lines to a new file removing the lambda and rearrange the numbers onto the same line so output \1\s\2\s\3\s\4\n

So I have actually two questions:

Is there an easy utility to accomplish this, on any system?

Is there a way to do this specifically on windows?

I'm hoping there is a simple solution to this that has escaped me.  I would rather stay in windows but if I have to go to Linux I will to get this done.

LastEditorDisplayName: Chad Birch

Body:
thanks for all the answers.  I like the answers you gave me for the perl and awk.  I'm one of those weird programmers that doesn't know perl, so I took the ruby route.  here is my solution

x=ARGV[0]
f=File.new(ARGV[1])
g=File.new(ARGV[2],"w")
f.read.gsub(/#{x}:\s*(([\d\.\-]*\t*)+\n)+/ ){|entry|
    puts entry
    g.puts entry.gsub(/#{x}:\n/,'').gsub(/\s+/,"\t").strip
}

this I can use as a utility with my editor Notepad++ through NppExec, which does not support redirect and piping, as far as I know.  This also allows for me to collect any of the output that I need to diagnose by program.  Thanks again y'all.


问:
Automatic documentation tool for eclipse Java
is there an automatic documentation tool for eclipse? (Like the Ghost Doc Tool)
I'm working in Java and i want a reccomended tool.

thanks

答:
It's built-in.

Just type /** [enter] above a method and it will autocomplete the javadoc.
Then just use the javadoc tool to generate the html documentation.

Obviously, all useful docs have to be written by hand.


问:
Running attended installer inside docker windows/servercore
I've been attempting to move an application to the cloud for a while now and have most of the services set up in pods running in a k8s cluster. The last piece has been giving me trouble, I need to set up an image with an older piece of software that cannot be installed silently. I then attempted in my dockerfile to install its .net dependencies (2005.x86, 2010.x86, 2012.x86, 2015.x86, 2015.x64) and manually transfer a local install of the program but that also did not work.

Is there any way to run through a guided install in a remote windows image or be able to determine all of the file changes made by an installer in order to do them manually?

答:
You can track the changes done by the installer following these steps:

start a new container based on your base image

```<code>docker run --name test -d <base_image>
</code>```

open a shell in the new container (I am not familiar with Windows so you might have to adapt the command below)

```<code>docker exec -ti test cmd
</code>```

Run whatever commands you need to run inside the container. When you are done exit from the container

Examine the changes to the container's filesystem:

```<code>docker container diff test
</code>```

You can also use docker container export to export the container's filesystem as a tar archive, and then docker image import to create an image from that archive.

Body:
You can track the changes done by the installer following these steps:

start a new container based on your base image

docker run --name test -d <base_image>

open a shell in the new container (I am not familiar with Windows so you might have to adapt the command below)

docker exec -ti test cmd

Run whatever commands you need to run inside the container. When you are done exit from the container

Examine the changes to the container's filesystem:

docker container diff test

You can also use docker container export to export the container's filesystem as a tar archive, and then docker image import to create an image from that archive.


问:
Join tables in Hive using LIKE
I am joining tbl_A to tbl_B, on column CustomerID in tbl_A to column Output in tbl_B which contains customer ID. However, tbl_B has all other information in related rows that I do not want to lose when joining. I tried to join using like, but I lost rows that did not contain customer ID in the output column.

Here is my join query in Hive:

```<code>select a.*, b.Output from tbl_A a
left join tbl_B b
On b.Output like concat('%', a.CustomerID, '%')
</code>```

However, I lose other rows from output.

答:
You could also achieve the objective by a simple hive query like this :)

select a.*, b.Output
from tbl_A a, tbl_B b
where b.Output like concat('%', a.CustomerID, '%')
```

Title: Join tables in Hive using LIKE

Body:
I am joining tbl_A to tbl_B, on column CustomerID in tbl_A to column Output in tbl_B which contains customer ID. However, tbl_B has all other information in related rows that I do not want to lose when joining. I tried to join using like, but I lost rows that did not contain customer ID in the output column.

Here is my join query in Hive:

select a.*, b.Output from tbl_A a
left join tbl_B b
On b.Output like concat('%', a.CustomerID, '%')

However, I lose other rows from output.


问:
log messages appearing twice with Python Logging
I'm using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

```<code># BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)
</code>```

Later on, I call this method to configure logging:

```<code>if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()
</code>```

And then within say, the buy_ham module, I'd call:

```<code>self.logger.info('Successfully able to write to %s' % path)
</code>```

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening. I'm assuming I've missed something obvious.

答:
I was getting a strange situation where console logs were doubled but my file logs were not.  After a ton of digging I figured it out.

Please be aware that third party packages can register loggers.  This is something to watch out for (and in some cases can't be prevented).  In many cases third party code checks to see if there are any existing root logger handlers; and if there isn't--they register a new console handler.

My solution to this was to register my console logger at the root level:

```<code>rootLogger = logging.getLogger()  # note no text passed in--that's how we grab the root logger
if not rootLogger.handlers:
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(logging.Formatter('%(process)s|%(levelname)s] %(message)s'))
        rootLogger.addHandler(ch)
</code>```

Body:
I'm using Python logging, and for some reason, all of my messages are appearing twice.

I have a module to configure logging:

# BUG: It's outputting logging messages twice - not sure why - it's not the propagate setting.
def configure_logging(self, logging_file):
    self.logger = logging.getLogger("my_logger")
    self.logger.setLevel(logging.DEBUG)
    self.logger.propagate = 0
    # Format for our loglines
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    # Setup console logging
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)
    ch.setFormatter(formatter)
    self.logger.addHandler(ch)
    # Setup file logging as well
    fh = logging.FileHandler(LOG_FILENAME)
    fh.setLevel(logging.DEBUG)
    fh.setFormatter(formatter)
    self.logger.addHandler(fh)

Later on, I call this method to configure logging:

if __name__ == '__main__':
    tom = Boy()
    tom.configure_logging(LOG_FILENAME)
    tom.buy_ham()

And then within say, the buy_ham module, I'd call:

self.logger.info('Successfully able to write to %s' % path)

And for some reason, all the messages are appearing twice. I commented out one of the stream handlers, still the same thing. Bit of a weird one, not sure why this is happening. I'm assuming I've missed something obvious.

Body:
I was getting a strange situation where console logs were doubled but my file logs were not.  After a ton of digging I figured it out.

Please be aware that third party packages can register loggers.  This is something to watch out for (and in some cases can't be prevented).  In many cases third party code checks to see if there are any existing root logger handlers; and if there isn't--they register a new console handler.

My solution to this was to register my console logger at the root level:

rootLogger = logging.getLogger()  # note no text passed in--that's how we grab the root logger
if not rootLogger.handlers:
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(logging.Formatter('%(process)s|%(levelname)s] %(message)s'))
        rootLogger.addHandler(ch)


问:
Connection to DB2 through JDBC in Shell Script
I want to connect DB2 Database through JDBC in Shell Script on Linux Server

I have the jdbc details
jdbc:db2://10.XXX.XXX.XX:/

I know we can connect using "Db2 Connect" command but DBA  is not recommending that. They are asking to use jdbc only.

Appreciate your help of you can point to any sample script.

thanks,
Rajesh

答: There's also jsqsh  https://github.com/scgray/jsqsh/wiki which can connect to any JDBC endpoint. It's endorsed by IBM  https://www.ibm.com/support/knowledgecenter/SSPT3X_3.0.0/com.ibm.swg.im.infosphere.biginsights.analyze.doc/doc/bsql_jsqsh.html


问:
Is there a way for me to programmatically get if the side menu is floating or fixed?
I am developing a plugin on Buildfire platform. I see that an app can have either floating or fixed side menu. I would like to change the position of my plugin content depending on the side menu style.
I already checked appearance and there is nothing that can help me. Am I missing something?
Any help is appreciated.</p>

答:
I dont believe this is provided currently (as of Feb 2020). The closet method would be buildfire.appearance.getAppTheme which only returns fonts and colors

```<code>{
  "appName": "AlicanDemo2019",
  "colors": {
    "backgroundColor": "#18191a",
    "titleBar": "#09a3ee",
    "titleBarTextAndIcons": "#ffffff",
    "headerText": "#09a3ee",
    "bodyText": "#ffffff",
    "icons": "#09a3ee",
    "primaryTheme": "#09a3ee",
    "successTheme": "#14cb5d",
    "infoTheme": "#69d5ff",
    "warningTheme": "#faba41",
    "dangerTheme": "#ed4b4b",
    "defaultTheme": "#0677ae",
    "footerMenuBackgroundColor": "#18191a",
    "footerMenuIconColor": "#09a3ee"
  },
  "fontId": "Architects+Daughter",
  "fontName": "Architects Daughter"
}
</code>```

Body:
I dont believe this is provided currently (as of Feb 2020). The closet method would be buildfire.appearance.getAppTheme which only returns fonts and colors

{
  "appName": "AlicanDemo2019",
  "colors": {
    "backgroundColor": "#18191a",
    "titleBar": "#09a3ee",
    "titleBarTextAndIcons": "#ffffff",
    "headerText": "#09a3ee",
    "bodyText": "#ffffff",
    "icons": "#09a3ee",
    "primaryTheme": "#09a3ee",
    "successTheme": "#14cb5d",
    "infoTheme": "#69d5ff",
    "warningTheme": "#faba41",
    "dangerTheme": "#ed4b4b",
    "defaultTheme": "#0677ae",
    "footerMenuBackgroundColor": "#18191a",
    "footerMenuIconColor": "#09a3ee"
  },
  "fontId": "Architects+Daughter",
  "fontName": "Architects Daughter"
}


Title: How to replace the value of a dataframe column with the value of another column using groupby.first()?

Body:
I have a df like this:

               Value1     Value2
2008-01-01       -1          4
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         13
2009-04-07        0         14

I want to check the first value1 of every Year-Month. If it's < 0, I want value2 to replace with value1. How can I do that?

In this example, the result should be:

               Value1     Value2
2008-01-01       -1         -1
2008-01-01       -1          5
2008-01-03       -1          6
2008-02-25        0          7
2008-02-26       -1          8
2008-02-27        0          9
2008-03-02        5         10
2008-03-16       -1         11
2008-03-17       -1         12
2009-04-04       -1         -1
2009-04-07        0         14

Because only 2008-01, 2009-04 first value1 are negative, 2008-2, 2008-03 first value1 are positive, just leave it.

I used:

g = df.groupby([df.index.year,df.index.month])

if g['value1'].first() < 0:
   g['value1'].first() = g['value2'].first()

it doesn't seem to work. Thanks.

Body:
Here is another approach. I hope it is useful for you:

import pandas as pd
import numpy as np
df = pd.DataFrame({'date':['2008-01-01','2008-01-03','2008-02-25','2008-02-26','2008-02-27','2008-03-02','2008-03-16','2008-03-17','2009-04-04','2009-04-07'],
                   'value1':[-1,-1,0,-1,0,5,-1,-1,-1,0],
                   'value2':[5,6,7,8,9,10,11,12,13,14]})
df['date'] = pd.to_datetime(df['date'])
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
df['day'] = df['date'].dt.day
df_a = (df.groupby(['year','month'])['day'].first()).reset_index()
df_a['aux'] = True
df_output = df.merge(df_a,how='left',on=['year','month','day'])
df_output['value1'] = np.where((df_output['aux'] == True) & (df['value1'] < 0),
         df['value2'],
         df['value1'])
df_output = df_output.drop(columns=['year','month','day','aux'])
print(df_output)

Output:

        date  value1  value2
0 2008-01-01       5       5
1 2008-01-03      -1       6
2 2008-02-25       0       7
3 2008-02-26      -1       8
4 2008-02-27       0       9
5 2008-03-02       5      10
6 2008-03-16      -1      11
7 2008-03-17      -1      12
8 2009-04-04      13      13
9 2009-04-07       0      14


问:
Getting seconds until the start of the next hour?
I'm writing a small API call which returns the current amount of seconds left until the end of the hour, the end of the day, and the end of the week.

Getting the end of day/week was easy, in just using strtotime('tomorrow') or strtotime('next sunday') and subtracting with time(). However, I'm not seeing any available function that would allow me to get the timestamp of the start of the next hour.

strtime('next hour') just returns back the current timestamp +1 hour - rather than the time remaining until the next hour starts.

Is there any simple way of accomplishing this?

答:
If you really want to use strtotime you can do this</p>

```<code> $start=date("H:i:s");
 $end=date("H:00:00",strtotime("$start +1 hour"));
 $secondsleft = (strtotime($end) - strtotime($start));
</code>```

Body:
If you really want to use strtotime you can do this

 $start=date("H:i:s");
 $end=date("H:00:00",strtotime("$start +1 hour"));
 $secondsleft = (strtotime($end) - strtotime($start));


问:
Proper way to create a singleton service in ASP.NET Core - does it have to use the static keyword, or not?
This is really confusing for me. Nothing is stopping us from creating a class with instance fields and
instance methods, versus creating a class with static fields and static methods. Both can be registered as a singleton.

Is there a preferred approach to this problem, and why?

EDIT: I'm not asking about creating a class using the singleton pattern. I'm asking about singleton dependency injecting a class versus injecting the same class but with static defined members/fields/methods/properties.

答:
I'm asking about [...] injecting the same class but with static defined members/fields/methods/properties

That is possible but useless. If a controller requires such a singleton object, then you still have no instance method to call on this object. Your controller have to call static methods on the class.

[...] creating a class with instance fields and instance methods

That is a better way to do because it will allow you to mock the object for unit testing.

If you want concrete example, I've coded a class with instance methods to store data about users, which is registered as a singleton object, and used in controller.

Hope it makes things clearer for you.


问:
Scala add element to Nil list in scala
I'm solving a problem on leetcode-
https://leetcode.com/problems/minimum-absolute-difference/

I can't seem to understand why in the code below the result list is not correctly appended after resetting it to nil.
I looked online of course but could not fathom the concept behind this behavior. Can someone explain why after result is assigned Nil, no value can get added to that list? How do I reset the list?
I tried with ListBuffer and clear() but I got the same issue, at the end of the run the result is Nil

Expected behavior:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]

Actual behavior:
Input: arr = [4,2,1,3]
Output: List()

```<code>  def minimumAbsDifference(arr: Array[Int]): List[List[Int]] = {
    val sortedInput = arr.sorted
    var min = Integer.MAX_VALUE
    var result = Seq[List[Int]]()
    for(i <- 0 until sortedInput.length - 1){
      val diff = sortedInput(i+1) - sortedInput(i)
      if(min > diff){
         result = Nil
         min = diff
      }
      if(min == diff){
        result :+ List(sortedInput(i),sortedInput(i+1))
      }
    }
    result.toList
  }
</code>```

答:
You're assigning Nil to result and then never assigning anything else.

Because List is immutable result :+ List(...) returns a new list which is then thrown away.  You need to assign the new list to result.

A couple of other notes:

It is extremely inefficient (decidedly not "leet") to append to a list.  It's much more efficient to prepend (building the result in reverse) and then reverse at the end.

It is also extremely inefficient to access List items by index.

Use of var should generally be avoided in Scala, though this particular usage (contained locally to an otherwise pure function) is not beyond the pale.

Title: Scala add element to Nil list in scala

Body:
I'm solving a problem on leetcode-
https://leetcode.com/problems/minimum-absolute-difference/

I can't seem to understand why in the code below the result list is not correctly appended after resetting it to nil.
I looked online of course but could not fathom the concept behind this behavior. Can someone explain why after result is assigned Nil, no value can get added to that list? How do I reset the list?
I tried with ListBuffer and clear() but I got the same issue, at the end of the run the result is Nil

Expected behavior:
Input: arr = [4,2,1,3]
Output: [[1,2],[2,3],[3,4]]

Actual behavior:
Input: arr = [4,2,1,3]
Output: List()

  def minimumAbsDifference(arr: Array[Int]): List[List[Int]] = {
    val sortedInput = arr.sorted
    var min = Integer.MAX_VALUE
    var result = Seq[List[Int]]()
    for(i <- 0 until sortedInput.length - 1){
      val diff = sortedInput(i+1) - sortedInput(i)
      if(min > diff){
         result = Nil
         min = diff
      }
      if(min == diff){
        result :+ List(sortedInput(i),sortedInput(i+1))
      }
    }
    result.toList
  }


问:
Django referencing foreignkeys on updates
I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit.

I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value.

Which I did:

item = {}
for entry in params:
    if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']:
        item[entry] = params[entry]

        if entry == 'code':
            item[entry] = Demo_user_sessions.objects.get(session=session_key)

obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item)
```

<p>This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey.</p>

<p>Here my model for the entry that I am trying to make.</p>

<pre class="lang-py prettyprint-override"><code>class Demo_user_sessions(models.Model):
    session_key = models.CharField(primary_key=True, max_length=8)
    timestamp = models.DateTimeField(auto_now_add=True)
    code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
    # ... some other

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return self
</code>```

Here my current error message when doing:

Traceback (most recent call last):
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/Mantaray/main/views.py", line 111, in api_user_session
    obj, created = Demo_user_sessions.objects.update_or_create(session=params['session_key'], defaults=item)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/query.py", line 584, in update_or_create
    setattr(obj, k, v() if callable(v) else v)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__
    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/base.py", line 518, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type Demo_user_sessions)
```

I kinda get the problem of the error message. I just don't know what to change or what to do differently.

答:
Update your model from

```<code>code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
</code>```

to

```<code>code = models.ForeignKey(HS_Code, on_delete=models.CASCADE, null=True)
</code>```

Body:
I asked this question before, it got closed because I didn't provide sufficient information to the situation. This is the edit.

I'm running Django and running into this problem. I'm trying to create or update an entry in my MySQL table. One of the keys is, however, a foreignKey. (I know how to create table entries with foreignKeys, but my approach doesn't work) As per Django reference for doing the recommended way is to set the new table entry as default value.

Which I did:

item = {}
for entry in params:
    if entry not in ['_state', 'timestamp', 'rule_case', 'session_key']:
        item[entry] = params[entry]

        if entry == 'code':
            item[entry] = Demo_user_sessions.objects.get(session=session_key)

obj, created = Demo_user_sessions.objects.update_or_create(session=session_key, defaults=item)

This I extended by looking for the special key and replacing the content with the link to the referenced table. The one by the foreignKey.

Here my model for the entry that I am trying to make.

class Demo_user_sessions(models.Model):
    session_key = models.CharField(primary_key=True, max_length=8)
    timestamp = models.DateTimeField(auto_now_add=True)
    code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)
    # ... some other

    class Meta:
        ordering = ['timestamp']

    def __str__(self):
        return self

Here my current error message when doing:

Traceback (most recent call last):
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 505, in dispatch
    response = self.handle_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 465, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception
    raise exc
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/views.py", line 502, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/Mantaray/main/views.py", line 111, in api_user_session
    obj, created = Demo_user_sessions.objects.update_or_create(session=params['session_key'], defaults=item)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/query.py", line 584, in update_or_create
    setattr(obj, k, v() if callable(v) else v)
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 215, in __set__
    'Cannot assign "%r": "%s.%s" must be a "%s" instance.' % (
  File "/Users/5knnbdwm/Python/mantaray_env/lib/python3.8/site-packages/django/db/models/base.py", line 518, in __repr__
    return '<%s: %s>' % (self.__class__.__name__, self)
TypeError: __str__ returned non-string (type Demo_user_sessions)

I kinda get the problem of the error message. I just don't know what to change or what to do differently.

Body:
Update your model from

code = models.ForeignKey('HS_Code', on_delete=models.CASCADE, null=True)

to

code = models.ForeignKey(HS_Code, on_delete=models.CASCADE, null=True)


问:
iPhone : Using Streetview (as in Trip Advisor)
I know the mapkit does not support street view but it is possible to render it in a web control (as shown in another stackoverflow post: Google Map Street view in Iphone app).

However, in the Trip Adviser app, they have mashed it up with a A.R control.
Again, I can probably do the AR bit but how do I get the angle from street view.  E.g, what the user is facing?

答:
TripAdvisor have answered your question: http://tech.tripadvisor.com/2011/02/augmented-reality-on-ipad-project.html.

Pin Positioning is described in the blog post.


问:
Resolution for 2d pixel art games
I'm having problems to set the right resolution on unity to not have pixel distortion on my pixel art assets. When I create an tile grid, on the preview tab the assets look terrible.

I have an tilemap with 64x32 resolution for each tile.

I'm using 64 pixels per unit.

The camera size is set to 5 in a 640x360 resolution (using the following formula: vertical resolution / PPU / 2).

What I'm doing wrong and what I'm missing?

答: I don't know how the tiles are defined, but assuming those are rects with textures on topm you could check your texture filter setting and play with it a little, setting it up for example to "anisotropic"</p>

Title: Resolution for 2d pixel art games


问:
Setting Linq2Db to read and update with CHAR type and NOT NULL constraint in Oracle
Reading value of fixed CHAR string from table, using Linq2db Oracle provider:

```<code>CREATE TABLE mytable
    (pk                         NUMBER(15,0) NOT NULL,
     fixed_data                 CHAR(20) DEFAULT ' ' NOT NULL)
</code>```

Although in database, length of FIXED_DATA filed is 20,

```<code>SELECT LENGTH(fixed_data) FROM mytable WHERE pk = 1

-- result is 20
</code>```

When same field is read using Linq2Db, value gets truncated to empty string:

```<code>var row = (from row in database.mytable where row.pk == 1 select row).ToList()[0];
Console.WriteLine(row.fixed_data.Length);

// result is zero
</code>```

This causes problem when record is updated using Linq2Db, Oracle converts empty string to NULL, and UPDATE fails:

```<code>database.Update(row);

// Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01407: cannot update ("MYSCHEMA"."MYTABLE"."FIXED_DATA") to NULL

</code>```

Is there any setting in Linq2Db for read->update cycle to work with CHAR type and NOT NULL constraint?

答:
Found a solution, thanks to source code openly available. By default, Linq2Db calls expression IDataReader.GetString(int).TrimEnd(' ') on every CHAR and NCHAR column. However this can be easily customized, by implementing custom provider, which overrides field value retrieval expression, with one that does not trim:</p>

```<code>class MyOracleProvider : OracleDataProvider
{
    public MyOracleProvider(string name)
        : base(name)
    {
        // original is SetCharField("Char",  (r,i) => r.GetString(i).TrimEnd(' '));
        SetCharField("Char", (r, i) => r.GetString(i));
        // original is SetCharField("NChar", (r,i) => r.GetString(i).TrimEnd(' '));
        SetCharField("NChar", (r, i) => r.GetString(i));
    }
}
</code>```

Body:
Reading value of fixed CHAR string from table, using Linq2db Oracle provider:

CREATE TABLE mytable
    (pk                         NUMBER(15,0) NOT NULL,
     fixed_data                 CHAR(20) DEFAULT ' ' NOT NULL)

Although in database, length of FIXED_DATA filed is 20,

SELECT LENGTH(fixed_data) FROM mytable WHERE pk = 1

-- result is 20

When same field is read using Linq2Db, value gets truncated to empty string:

var row = (from row in database.mytable where row.pk == 1 select row).ToList()[0];
Console.WriteLine(row.fixed_data.Length);

// result is zero

This causes problem when record is updated using Linq2Db, Oracle converts empty string to NULL, and UPDATE fails:

database.Update(row);

// Oracle.ManagedDataAccess.Client.OracleException: 'ORA-01407: cannot update ("MYSCHEMA"."MYTABLE"."FIXED_DATA") to NULL

Is there any setting in Linq2Db for read->update cycle to work with CHAR type and NOT NULL constraint?

Body:
Found a solution, thanks to source code openly available. By default, Linq2Db calls expression IDataReader.GetString(int).TrimEnd(' ') on every CHAR and NCHAR column. However this can be easily customized, by implementing custom provider, which overrides field value retrieval expression, with one that does not trim:

class MyOracleProvider : OracleDataProvider
{
    public MyOracleProvider(string name)
        : base(name)
    {
        // original is SetCharField("Char",  (r,i) => r.GetString(i).TrimEnd(' '));
        SetCharField("Char", (r, i) => r.GetString(i));
        // original is SetCharField("NChar", (r,i) => r.GetString(i).TrimEnd(' '));
        SetCharField("NChar", (r, i) => r.GetString(i));
    }
}


问:
How can I suppress blank pages in SQL Reports?
I have a SQL Report that insists on printing an extra blank page at the end, even though all the report items should fit on one page.  I tried shortening the elements on the page that is spilling over, but no matter how much I compress them, or how much blank space is left on the first page, SRS still thinks it needs to take up another page as well.  This is annoying because it's such a common problem - all it takes is one mistake to make a report spill over.  So I'm not asking how can I fix this on this one report, but how can I fix this on this and future reports:  Is there a flag or setting I can set to tell SRS "No matter what, never print more than 1 page"?  Or "Suppress blank pages = true"?</p>

答: Also, look at headers & footers.  I was focused on the central part of the report getting all of the columns smaller, but it was a footer that caused the issue.</p>

OwnerDisplayName: Dennis Ferron

LastEditorDisplayName: Dustin Brooks


问:
JS Recursively find element in parent-child array
i have a array with a nested parent-child structure. I need to recursively go through this array and find wanted element.
I wrote this function:

```<code>recursivelyFindElementByCondition(nodes, isSatisfyingCondition) {

    function recursiveCheck(items) {
        for (const item of items) {
            if (isSatisfyingCondition(item)) {
                return item;
            }

            if (item.rows) {
                recursiveCheck(item.rows)
            }
        }
    }

    return recursiveCheck(nodes);
}
</code>```

But i don't understand why it returns undefined. It should work correct as far as i understand.
I know that there is a way to create a variable out of scope of recursive function and assign element to it and then return it in the end, just wanted to do it without unnecessary variable and have no idea why is approach above doesn't work.

答:
The result of the recursive call must be returned, for it to propagate up to the point of invocation and be returned as the result.

function findNode(nodes, predicate) {
    for (const node of nodes) {
        if (predicate(node)) return node

        if (node.rows) {
            let match = findNode(node.rows, predicate)
            if (match) return match
        }
    }
}

const tree = [{
    value: 'a',
    rows: [{
        value: 'b'
    }]
}, {
    value: 'c',
    rows: [{
        value: 'd',
        rows: [{
            value: 'e'
        }]
    }]
}]

const result = findNode(tree, ({value}) => value === 'e')

console.log(result)```

Body:
i have a array with a nested parent-child structure. I need to recursively go through this array and find wanted element.
I wrote this function:

recursivelyFindElementByCondition(nodes, isSatisfyingCondition) {

    function recursiveCheck(items) {
        for (const item of items) {
            if (isSatisfyingCondition(item)) {
                return item;
            }

            if (item.rows) {
                recursiveCheck(item.rows)
            }
        }
    }

    return recursiveCheck(nodes);
}

But i don't understand why it returns undefined. It should work correct as far as i understand.
I know that there is a way to create a variable out of scope of recursive function and assign element to it and then return it in the end, just wanted to do it without unnecessary variable and have no idea why is approach above doesn't work.


问:
what is the difference between `KeyId: secretKey` and `KeyId: '#(secretKey)'`?
i have a question regarding to this ticket
Using karate-config parameters in a feature file

what is the difference between
KeyId: secretKey,
and
KeyId: '#(secretKey)' ?
is it possible to use apiKey with out assigning to def inside of the message? like
* print "Key in this project is #apiKey"
Thank you

答:
You asked 3 questions:

a) Please read: https://github.com/intuit/karate#karate-expressions

b) Please read: https://github.com/intuit/karate#embedded-expressions

c) Please read: https://github.com/intuit/karate#print

for example:

```<code>* def val = 'bar'
# correct
* def temp = { foo: '#(val)' }
# wrong
* def temp = { foo: val }
# correct but not recommended
* def temp = ({ foo: val })
# variables are easy to use, forget about the # part
* print 'value of val:', val
</code>```

Body:
You asked 3 questions:

a) Please read: https://github.com/intuit/karate#karate-expressions

b) Please read: https://github.com/intuit/karate#embedded-expressions

c) Please read: https://github.com/intuit/karate#print

for example:

* def val = 'bar'
# correct
* def temp = { foo: '#(val)' }
# wrong
* def temp = { foo: val }
# correct but not recommended
* def temp = ({ foo: val })
# variables are easy to use, forget about the # part
* print 'value of val:', val


问:
Jsonschema RefResolver to resolve multiple refs in python
How may we validate multiple refs in a schema using jsonschema.RefResolver?

I have a validation script that works good if I have one ref in a file. I now have two or three refs in a schema, that are in a different directory.

```<code>base_dir = '/schema/models/'
with open (os.path.join(base_dir, 'Defined.json')) as file_object:
    schema = json.load(file_object)
    resolver = jsonschema.RefResolver('file://' + base_dir + '/' + 'Fields/Ranges.json', schema)
    jsonschema.Draft4Validator(schema, resolver=resolver).validate(data)
</code>```

My json schema:

```<code>{
  "properties": {
    "description": {
        "type": "object",
        "after": {"type": ["string", "null"]},
        "before": {"type": "string"}
      },
      "width": {"type": "number"} ,
      "range_specifier": {"type": "string"},
      "start": {"type": "number", "enum" : [0, 1] } ,
      "ranges": {
        "$ref": "Fields/Ranges.json"
      },
      "values": {
        "$ref": "Fields/Values.json"
      }
  }
}
</code>```

So my question is should I have two resolvers one for ranges and one for values and call the resolvers separately in Draft4Validator ? Or is there a better way to do this?

答:
You can use the python library "pyjn"
(pip install pyjn)
and do this in three lines.</p>

```<code>from pyjn import pyjn
pyjn=pyjn()
json_pathtest='C:/Users/Entity.json'
print(pyjn.refsolver(json_pathtest))

</code>```

Body:
How may we validate multiple refs in a schema using jsonschema.RefResolver?

I have a validation script that works good if I have one ref in a file. I now have two or three refs in a schema, that are in a different directory.

base_dir = '/schema/models/'
with open (os.path.join(base_dir, 'Defined.json')) as file_object:
    schema = json.load(file_object)
    resolver = jsonschema.RefResolver('file://' + base_dir + '/' + 'Fields/Ranges.json', schema)
    jsonschema.Draft4Validator(schema, resolver=resolver).validate(data)

My json schema:

{
  "properties": {
    "description": {
        "type": "object",
        "after": {"type": ["string", "null"]},
        "before": {"type": "string"}
      },
      "width": {"type": "number"} ,
      "range_specifier": {"type": "string"},
      "start": {"type": "number", "enum" : [0, 1] } ,
      "ranges": {
        "$ref": "Fields/Ranges.json"
      },
      "values": {
        "$ref": "Fields/Values.json"
      }
  }
}

So my question is should I have two resolvers one for ranges and one for values and call the resolvers separately in Draft4Validator ? Or is there a better way to do this?

Body:
You can use the python library "pyjn"
(pip install pyjn)
and do this in three lines.

from pyjn import pyjn
pyjn=pyjn()
json_pathtest='C:/Users/Entity.json'
print(pyjn.refsolver(json_pathtest))


问:
I want to prevent the user from entering negative values when prompted for an entry. How do I go about this in this code?
How do I prevent the following C++ code from taking in negative values? Any zero, positive integer, or positive decimal I enter as a user produces correct results, but when I enter a negative value I want the program to tell the user that what they've entered is not a positive integer or decimal, and to re-attempt their entry.

main driver file:

```<code>#include <iostream>
#include <iomanip>
#include <cmath>
#include "convert.h"
using namespace std;

int main()
{
   string str;
   cout <<
       "Please enter a string representing a positive integer or decimal: ";
   cin >> str;
   convertToNumeric ctn(str);
   long int integerValue = ctn.getIntValue();
   double doubleValue = ctn.getDecValue();
   double integral;

   /* If the string represents an integer value, adding decimal portion to
    * the decimal value.
    */
   if (std::modf(doubleValue, &integral) == 0)
   {
       cout << "Integer Conversion: " << integerValue << endl;
       cout << "Decimal Conversion: " << std::fixed << std::setprecision(1)
           << integral <<endl;
   }
   /*
    * Else, display the values normally.
    */
   else
   {
       cout << "Integer Conversion: " << integerValue << endl;
       cout << "Decimal Conversion: " << doubleValue << endl;
   }
   /*
    * Demonstrating that the converted values are useable with
    * long int-specific and double-specific operations.
    */
   cout << endl;
   cout << "Demonstration of long int: " << integerValue << " + 100 = " <<
       (integerValue + 100) << endl;
   cout << "Demonstration of decimal: " << doubleValue << " + 100.12 = " <<
       (doubleValue + 100.12) << endl;
   return 0;
}
</code>```

convert.cpp file:

```<code>#include <iostream>
#include "convert.h"

using namespace std;

convertToNumeric::convertToNumeric()
{
   str = "123";
}

/*
* This accessor function is the overloaded constructor that takes a string
* and calls the convert method to convert into respective integer and
* decimal value. There is not return value. The input is s, which is the
* string to be converted.
*/
convertToNumeric::convertToNumeric(string s)
{
   str = s;
   if(convert(str))
   {
       cout << "Conversion Successful!" << endl;
   }
   else
   {
       cout << "Conversion failed." <<endl;
   }
}

/*
* This mutator function serves the purpose of converting a string into its
* respective integer and decimal values. The input is s, which is the
* string to be converted. The function returns a boolean value indicating
* whether conversion is successful or not.
*/
bool convertToNumeric::convert(string s)
{
   bool success = false;
   bool dotFound = false;

   /*
    * Here, we are looping through each character in the string and storing
    * the integer portion in cstk1 and the decimal portion in cstk2.
    * Ex: If s = 123.45, cstk1 = 321 and cstk2 = 54
    * (since the stack follows LIFO)
    */
   for(unsigned int i = 0; i < s.size(); i++)
   {
       if(s[i] == '.') dotFound = true;
       else if(dotFound)
       {
           cstk2.push(s[i]);
       }
       else
       {
       cstk1.push(s[i]);
       }
   }

   /*
    * Here, we are popping out each value from stack cstk1 and generating
    * the integer value.
    * Ex: s = 123.45 and cstk1 = 321, num = 0
    * Iteration 1: num = 0 + (3 * 1) = 3
    * Iteration 2: num = 3 + (2 * 10) = 23
    * Iteration 3: num = 23 + (1 * 100) = 123
    * Now intValue = 123
    */
   long int num = 0; int multiplyValue = 1;
   char val = '0';
   while(cstk1.pop(val))
   {
       int valInInt = val - '0';
       num += (valInInt * multiplyValue);
       multiplyValue *= 10;
   }
   intValue = num;

   /*
    * Here, we are popping out each value from stack cstk2 and generating
    * the decimal value.
    * Ex: s = 123.45 and cstk2 = 54, num = 0, doubleValue = 123
    * (equated to integer value)
    * Iteration 1: num = 0 + (5 * 1) = 5
    * Iteration 2: num = 5 + (4 * 10) = 45
    * Iteration 3: num = 45 / 100 = 0.45
    * Now doubleValue = 123 + 0.45 = 123.45
    */
   doubleValue = double(num);
   num = 0; multiplyValue = 1;
   while(cstk2.pop(val))
   {
       int valInInt = val - '0';
       num += (valInInt * multiplyValue);
       multiplyValue *= 10;
   }
   doubleValue += (double(num) / multiplyValue);
   success = true;
   return success;
}

/*
* The accessor function below is returning the integer value of the string
* that has been converted.
*/
long int convertToNumeric::getIntValue()
{
   return intValue;
}

/*
* The accessor function below is returning the double value of the string
* that has been converted.
*/
double convertToNumeric::getDecValue()
{
   return doubleValue;
}
</code>```

Reproducible examples:

Correct:
Positive number

Incorrect:
Negative number
Letter

答:
Here's a quick way to do it:

#include <cstdint>
#include <iostream>
#include <string>

bool has_decimal(const std::string& str)
{
    return !(std::string::npos == str.find_first_of('.'));
}

bool conversion_was_complete(std::size_t length, std::size_t converted)
{
    return length == converted;
}

int main()
{
    std::string input;
    bool valid = false;
    union Number {
        double d;
        std::uint64_t i;
    } number;

    bool isInt = false;

    do {
        std::cout << "Enter a positive number: ";
        std::getline(std::cin, input);

        // Catch negative numbers here
        if (input[0] == '-') {
            std::cerr << "Invalid number entered.\n";
            continue;
        }

        std::size_t location;
        if (has_decimal(input)) {
            try {
                number.d = std::stod(input, &location);
            } catch (std::invalid_argument& e) {
                // do nothing, it's handled elsewhere
            }
        } else {
            isInt = true;
            try {
                number.i = std::stoi(input, &location);
            } catch (std::invalid_argument& e) {
                // do nothing, it's handled elsewhere
            }
        }

        if (conversion_was_complete(input.length(), location)) {
            valid = true;
        } else {
            std::cerr << "Invalid number entered.\n";
            isInt = false; // Entering words will set this to true, so it needs
                // to be reset
        }
    } while (!valid);

    std::cout << "You entered " << (isInt ? number.i : number.d) << ".\n";
}
```

The whole input thing will probably end up in a function for your use-case. My functions could just be lambdas in that function if you don't want the helpers floating around.

The try/catch blocks are needed because std::stoi and std::stod will throw if they cannot do any conversion; it handles the the scenario where the first character is not numeric or a '-'. I chose a union because it seemed like the the best way to store your value to me. The one issue is the flag indicating the actual type for printing purposes. You'll probably just want to wrap it all up in a class to clean it up. Another option is to just use a double. That depends on your requirements.

Body:
How do I prevent the following C++ code from taking in negative values? Any zero, positive integer, or positive decimal I enter as a user produces correct results, but when I enter a negative value I want the program to tell the user that what they've entered is not a positive integer or decimal, and to re-attempt their entry.

main driver file:

#include <iostream>
#include <iomanip>
#include <cmath>
#include "convert.h"
using namespace std;

int main()
{
   string str;
   cout <<
       "Please enter a string representing a positive integer or decimal: ";
   cin >> str;
   convertToNumeric ctn(str);
   long int integerValue = ctn.getIntValue();
   double doubleValue = ctn.getDecValue();
   double integral;

   /* If the string represents an integer value, adding decimal portion to
    * the decimal value.
    */
   if (std::modf(doubleValue, &integral) == 0)
   {
       cout << "Integer Conversion: " << integerValue << endl;
       cout << "Decimal Conversion: " << std::fixed << std::setprecision(1)
           << integral <<endl;
   }
   /*
    * Else, display the values normally.
    */
   else
   {
       cout << "Integer Conversion: " << integerValue << endl;
       cout << "Decimal Conversion: " << doubleValue << endl;
   }
   /*
    * Demonstrating that the converted values are useable with
    * long int-specific and double-specific operations.
    */
   cout << endl;
   cout << "Demonstration of long int: " << integerValue << " + 100 = " <<
       (integerValue + 100) << endl;
   cout << "Demonstration of decimal: " << doubleValue << " + 100.12 = " <<
       (doubleValue + 100.12) << endl;
   return 0;
}

convert.cpp file:

#include <iostream>
#include "convert.h"

using namespace std;

convertToNumeric::convertToNumeric()
{
   str = "123";
}

/*
* This accessor function is the overloaded constructor that takes a string
* and calls the convert method to convert into respective integer and
* decimal value. There is not return value. The input is s, which is the
* string to be converted.
*/
convertToNumeric::convertToNumeric(string s)
{
   str = s;
   if(convert(str))
   {
       cout << "Conversion Successful!" << endl;
   }
   else
   {
       cout << "Conversion failed." <<endl;
   }
}

/*
* This mutator function serves the purpose of converting a string into its
* respective integer and decimal values. The input is s, which is the
* string to be converted. The function returns a boolean value indicating
* whether conversion is successful or not.
*/
bool convertToNumeric::convert(string s)
{
   bool success = false;
   bool dotFound = false;

   /*
    * Here, we are looping through each character in the string and storing
    * the integer portion in cstk1 and the decimal portion in cstk2.
    * Ex: If s = 123.45, cstk1 = 321 and cstk2 = 54
    * (since the stack follows LIFO)
    */
   for(unsigned int i = 0; i < s.size(); i++)
   {
       if(s[i] == '.') dotFound = true;
       else if(dotFound)
       {
           cstk2.push(s[i]);
       }
       else
       {
       cstk1.push(s[i]);
       }
   }

   /*
    * Here, we are popping out each value from stack cstk1 and generating
    * the integer value.
    * Ex: s = 123.45 and cstk1 = 321, num = 0
    * Iteration 1: num = 0 + (3 * 1) = 3
    * Iteration 2: num = 3 + (2 * 10) = 23
    * Iteration 3: num = 23 + (1 * 100) = 123
    * Now intValue = 123
    */
   long int num = 0; int multiplyValue = 1;
   char val = '0';
   while(cstk1.pop(val))
   {
       int valInInt = val - '0';
       num += (valInInt * multiplyValue);
       multiplyValue *= 10;
   }
   intValue = num;

   /*
    * Here, we are popping out each value from stack cstk2 and generating
    * the decimal value.
    * Ex: s = 123.45 and cstk2 = 54, num = 0, doubleValue = 123
    * (equated to integer value)
    * Iteration 1: num = 0 + (5 * 1) = 5
    * Iteration 2: num = 5 + (4 * 10) = 45
    * Iteration 3: num = 45 / 100 = 0.45
    * Now doubleValue = 123 + 0.45 = 123.45
    */
   doubleValue = double(num);
   num = 0; multiplyValue = 1;
   while(cstk2.pop(val))
   {
       int valInInt = val - '0';
       num += (valInInt * multiplyValue);
       multiplyValue *= 10;
   }
   doubleValue += (double(num) / multiplyValue);
   success = true;
   return success;
}

/*
* The accessor function below is returning the integer value of the string
* that has been converted.
*/
long int convertToNumeric::getIntValue()
{
   return intValue;
}

/*
* The accessor function below is returning the double value of the string
* that has been converted.
*/
double convertToNumeric::getDecValue()
{
   return doubleValue;
}

Reproducible examples:

Correct:
Positive number

Incorrect:
Negative number
Letter

Body:
Here's a quick way to do it:

#include <cstdint>
#include <iostream>
#include <string>

bool has_decimal(const std::string& str)
{
    return !(std::string::npos == str.find_first_of('.'));
}

bool conversion_was_complete(std::size_t length, std::size_t converted)
{
    return length == converted;
}

int main()
{
    std::string input;
    bool valid = false;
    union Number {
        double d;
        std::uint64_t i;
    } number;

    bool isInt = false;

    do {
        std::cout << "Enter a positive number: ";
        std::getline(std::cin, input);

        // Catch negative numbers here
        if (input[0] == '-') {
            std::cerr << "Invalid number entered.\n";
            continue;
        }

        std::size_t location;
        if (has_decimal(input)) {
            try {
                number.d = std::stod(input, &location);
            } catch (std::invalid_argument& e) {
                // do nothing, it's handled elsewhere
            }
        } else {
            isInt = true;
            try {
                number.i = std::stoi(input, &location);
            } catch (std::invalid_argument& e) {
                // do nothing, it's handled elsewhere
            }
        }

        if (conversion_was_complete(input.length(), location)) {
            valid = true;
        } else {
            std::cerr << "Invalid number entered.\n";
            isInt = false; // Entering words will set this to true, so it needs
                // to be reset
        }
    } while (!valid);

    std::cout << "You entered " << (isInt ? number.i : number.d) << ".\n";
}

The whole input thing will probably end up in a function for your use-case. My functions could just be lambdas in that function if you don't want the helpers floating around.

The try/catch blocks are needed because std::stoi and std::stod will throw if they cannot do any conversion; it handles the the scenario where the first character is not numeric or a '-'. I chose a union because it seemed like the the best way to store your value to me. The one issue is the flag indicating the actual type for printing purposes. You'll probably just want to wrap it all up in a class to clean it up. Another option is to just use a double. That depends on your requirements.


问:
Filter dictionary on the basis of key value present in list
I have a dictionary D1 like this

and a list L1 like this

I want to have a dictionary like this (Filtering those key-value pairs whose key is present in the list )

So, I tried D1.Where(x => L1.Contains(x.Key)) but i got a dictionary of 2 rows with empry string in key and value.

Please advise.

答:
There are multiple ways to achieve what you need

In case all keys of D1 are present in L1 without mutating D1

```<code>Dictionary<string, string> D2 = new Dictionary<string, string>();
L1.ForEach(x => D2[x] = D1[x]);
</code>```

OR

```<code>var D2 = L1.ToDictionary(el => el, key => D1[key]);
</code>```

Safe option:

```<code>var D2 = D1.Keys.Intersect(L1).ToDictionary(key => key, key => D1[key]);
</code>```

and even more, depends on your creativity

Note that this is slow for big list and dictionary

```<code>D1.Where(x => L1.Contains(x.Key))
</code>```

Body:
There are multiple ways to achieve what you need

In case all keys of D1 are present in L1 without mutating D1

Dictionary<string, string> D2 = new Dictionary<string, string>();
L1.ForEach(x => D2[x] = D1[x]);

OR

var D2 = L1.ToDictionary(el => el, key => D1[key]);

Safe option:

var D2 = D1.Keys.Intersect(L1).ToDictionary(key => key, key => D1[key]);

and even more, depends on your creativity

Note that this is slow for big list and dictionary

D1.Where(x => L1.Contains(x.Key))


问:
AttributeError: 'NoneType' object has no attribute 'data' - when I'm removing duplicate elements from a sorted linked list
```<code>def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode is not None:
                previousNode = currentNode
                currentNode = currentNode.next
                if currentNode.data == previousNode.data: # Line of Error
                    previousNode.next = currentNode.next
</code>```

How to get the last node of the linked list get compared with its previous node.
Only the last element is not removed, even though it is duplicate.

答:
You are getting error because you are reaching end of linked list. And after doing next you are not checking for None value. One way to handle this it to check if currentNode has next value or not in while condition.

```<code>def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode and currentNode.next:
                previousNode = currentNode
                currentNode = currentNode.next
                if currentNode.data == previousNode.data: # Line of Error
                    previousNode.next = currentNode.next
</code>```

Try this implementation it should work. Above implementation have logical error. Where it will skip elements when 3 or more same numbers come.

```<code>def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode:
                nextNode = currentNode.next
                while nextNode and nextNode.data == currentNode.data:
                    currentNode.next = nextNode.next
                    nextNode = nextNode.next
                currentNode = nextNode
</code>```

Body:
def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode is not None:
                previousNode = currentNode
                currentNode = currentNode.next
                if currentNode.data == previousNode.data: # Line of Error
                    previousNode.next = currentNode.next

How to get the last node of the linked list get compared with its previous node.
Only the last element is not removed, even though it is duplicate.

Body:
You are getting error because you are reaching end of linked list. And after doing next you are not checking for None value. One way to handle this it to check if currentNode has next value or not in while condition.

def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode and currentNode.next:
                previousNode = currentNode
                currentNode = currentNode.next
                if currentNode.data == previousNode.data: # Line of Error
                    previousNode.next = currentNode.next

Try this implementation it should work. Above implementation have logical error. Where it will skip elements when 3 or more same numbers come.

def listDistinct(self):
        if self.isListEmpty():
            return self.failureValue
        else:
            currentNode = self.head
            while currentNode:
                nextNode = currentNode.next
                while nextNode and nextNode.data == currentNode.data:
                    currentNode.next = nextNode.next
                    nextNode = nextNode.next
                currentNode = nextNode


问:
Logstash-logback-encoder: Using StructuredArguments without formatting in the message?
I wonder what the best practices are with using StructuredArguments inside logging calls when using logstash-logback-encoder to log in JSON format.

I want to log some structured arguments in separate fields, but I don't want to format these arguments into the literal string message.

If I write my log lines like this, everything works fine as I want to, but both my IntelliJ IDEA and Sonarqube static code analysis considers this problematic issues:

```<code>log.info("Query executed successfully!", StructuredArguments.value("hits", result.getHits()));
(or more concise)
log.info("Query executed successfully!", v("hits", result.getHits()));
</code>```

IntelliJ warns this on this line:

more arguments provided (1) than placeholders specified (0)

How can I avoid this? Of course I can silence the warnings and add exceptions for them, but I wonder if that is a best practice.

答:
If you don't want to include the data inside the log message, and want to avoid the static analysis warnings, use Markers instead of StructuredArguments:

import net.logstash.logback.marker.Markers;

log.info(Markers.append("hits", result.getHits()), "Query executed successfully!");
```

See here for more details.

Body:
I wonder what the best practices are with using StructuredArguments inside logging calls when using logstash-logback-encoder to log in JSON format.

I want to log some structured arguments in separate fields, but I don't want to format these arguments into the literal string message.

If I write my log lines like this, everything works fine as I want to, but both my IntelliJ IDEA and Sonarqube static code analysis considers this problematic issues:

log.info("Query executed successfully!", StructuredArguments.value("hits", result.getHits()));
(or more concise)
log.info("Query executed successfully!", v("hits", result.getHits()));

IntelliJ warns this on this line:

more arguments provided (1) than placeholders specified (0)

How can I avoid this? Of course I can silence the warnings and add exceptions for them, but I wonder if that is a best practice.

Body:
If you don't want to include the data inside the log message, and want to avoid the static analysis warnings, use Markers instead of StructuredArguments:

import net.logstash.logback.marker.Markers;

log.info(Markers.append("hits", result.getHits()), "Query executed successfully!");

See here for more details.


问:
vs 2015 constexpr variable non constant but fine on vs 2019?
I have a simple constexpr class (using c++17)

```<code>struct foo {
   float x, y;

   // ill formed constexpr in vs 2015
   foo() {}

   constexpr foo(float x, float y) : x(x), y(y) {
   }

};

constexpr auto bar() {
    return foo(4.0, 5.0);
}

int main() {
    auto f = bar();
}
</code>```

This is illformed bc of the non constexpr default constructor on 2015. But vs 2019 doesnt report a problem.

According to this reference page "all selected ctors" must be constexpr. I assume the word "selected" means "used" and even though default ctor is unused, 2015 wont eval into a constexpr until I make the default ctor constexpr.

Other specs are worded differently but I could not make clear of them either. Also most constexpr examples use the keyword everywhere. An example of selective constexpr use would be nice.

Latest GNU ans Clang behave like vs 2019 but Im not convinced that this was an oversight or bug in vs 2015.

So what is it? Should all ctors be constexpr or is visual studio 2019 correct here?

答:
There has never been a requirement that all constructors of a literal type must be constexpr. The requirement has only been that all functions which get invoked in a constant expression context must be able to be constant expressions (and thus must be declared constexpr).

Note that older versions of Visual Studio did not do a good job of implementing constexpr correctly.

Body:
I have a simple constexpr class (using c++17)

struct foo {
   float x, y;

   // ill formed constexpr in vs 2015
   foo() {}

   constexpr foo(float x, float y) : x(x), y(y) {
   }

};

constexpr auto bar() {
    return foo(4.0, 5.0);
}

int main() {
    auto f = bar();
}

This is illformed bc of the non constexpr default constructor on 2015. But vs 2019 doesnt report a problem.

According to this reference page "all selected ctors" must be constexpr. I assume the word "selected" means "used" and even though default ctor is unused, 2015 wont eval into a constexpr until I make the default ctor constexpr.

Other specs are worded differently but I could not make clear of them either. Also most constexpr examples use the keyword everywhere. An example of selective constexpr use would be nice.

Latest GNU ans Clang behave like vs 2019 but Im not convinced that this was an oversight or bug in vs 2015.

So what is it? Should all ctors be constexpr or is visual studio 2019 correct here?


问:
Pygame : Repeating an action every x amount of time
I am a beginner in Python learning to build a simple game in Pygame where the player(monkey) tries to catch as many bananas as possible falling from the top of the screen.

My problem is how to get the bananas to spawn and fall individually every x time/seconds. Either they all spawn at once or if I use time.sleep, pauses the bananas midair. Even used threading after getting completely lost.

The relevant components of my code are as follows:

catch_game

```<code>import sys

import pygame
from pygame.sprite import Group

from settings import Settings
# from background import Background
from monkey import Monkey
from banana import Banana

import functions

def run_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
    pygame.display.set_caption('Monkey Catch')

    monkey = Monkey(screen, settings)
    # background = Background((0, 0), screen)
    bananas = Group()

    functions.create_banana(screen, settings, bananas)

    while True:
        monkey.movement()
        functions.check_events(monkey)
        functions.update_screen(screen, settings, monkey, bananas)
        functions.update_banana(monkey, bananas)

run_game()
</code>```

banana

```<code>import pygame
from pygame.sprite import Sprite
from random import randint

class Banana(Sprite):
    def __init__(self, screen, settings):
        super(Banana, self).__init__()
        self.screen = screen
        self.settings = settings

        self.image = pygame.image.load('E:\PycharmProjects\catch\images/banana.png')
        self.rect = self.image.get_rect()
        self.screen_rect = self.screen.get_rect()

        self.y = self.screen_rect.top
        self.y = float(self.rect.y)

        self.x = randint(0, 1150)

        self.speed = settings.banana_fallspeed

    def update(self):
        '''Banana falls down'''
        self.y += self.settings.banana_fallspeed

        self.rect.y = self.y
        self.rect.x = self.x

    def blit(self):
        self.screen.blit(self.image, self.rect)
</code>```

functions

```<code>import pygame
import sys
from banana import Banana
import threading
import time

def update_screen(screen, settings, monkey, bananas):
    screen.fill([255, 255, 255])
    # background.blit()
    monkey.blit()

    for banana in bananas:
        banana.update()
        bananas.draw(screen)

    pygame.display.flip()

def keydown_events(event, monkey):
    if event.key == pygame.K_RIGHT:
        monkey.moving_right = True
    if event.key == pygame.K_LEFT:
        monkey.moving_left = True

def keyup_events(event, monkey):
    if event.key == pygame.K_RIGHT:
        monkey.moving_right = False
    if event.key == pygame.K_LEFT:
        monkey.moving_left = False

def check_events(monkey):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            keydown_events(event, monkey)
        if event.type == pygame.KEYUP:
            keyup_events(event, monkey)

def create_banana(screen, settings, bananas):
        banana = Banana(screen, settings)
        bananas.add(banana)

def update_banana(monkey, bananas):
    '''kill bananas, collisions with monkey'''
    for banana in bananas.copy():
        if banana.rect.bottom >= 720:
            bananas.remove(banana)
    collision = pygame.sprite.spritecollide(monkey, bananas, True)
    if collision:
        bananas.remove(banana)

        # time.sleep(2)
        # fall_interval = banana.threading.Timer(3, create_banana(screen, settings, bananas))
        # fall_interval.start()

</code>```

答:
You can use coroutines to run functions at the same time using asyncio. For example:

```<code>import asyncio
import time

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
</code>```

If you create a new task for each banana, you should be able to get a few on screen at different times.

Source: https://docs.python.org/3/library/asyncio-task.html

Body:
I am a beginner in Python learning to build a simple game in Pygame where the player(monkey) tries to catch as many bananas as possible falling from the top of the screen.

My problem is how to get the bananas to spawn and fall individually every x time/seconds. Either they all spawn at once or if I use time.sleep, pauses the bananas midair. Even used threading after getting completely lost.

The relevant components of my code are as follows:

catch_game

import sys

import pygame
from pygame.sprite import Group

from settings import Settings
# from background import Background
from monkey import Monkey
from banana import Banana

import functions

def run_game():
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
    pygame.display.set_caption('Monkey Catch')

    monkey = Monkey(screen, settings)
    # background = Background((0, 0), screen)
    bananas = Group()

    functions.create_banana(screen, settings, bananas)

    while True:
        monkey.movement()
        functions.check_events(monkey)
        functions.update_screen(screen, settings, monkey, bananas)
        functions.update_banana(monkey, bananas)

run_game()

banana

import pygame
from pygame.sprite import Sprite
from random import randint

class Banana(Sprite):
    def __init__(self, screen, settings):
        super(Banana, self).__init__()
        self.screen = screen
        self.settings = settings

        self.image = pygame.image.load('E:\PycharmProjects\catch\images/banana.png')
        self.rect = self.image.get_rect()
        self.screen_rect = self.screen.get_rect()

        self.y = self.screen_rect.top
        self.y = float(self.rect.y)

        self.x = randint(0, 1150)

        self.speed = settings.banana_fallspeed

    def update(self):
        '''Banana falls down'''
        self.y += self.settings.banana_fallspeed

        self.rect.y = self.y
        self.rect.x = self.x

    def blit(self):
        self.screen.blit(self.image, self.rect)

functions

import pygame
import sys
from banana import Banana
import threading
import time

def update_screen(screen, settings, monkey, bananas):
    screen.fill([255, 255, 255])
    # background.blit()
    monkey.blit()

    for banana in bananas:
        banana.update()
        bananas.draw(screen)

    pygame.display.flip()

def keydown_events(event, monkey):
    if event.key == pygame.K_RIGHT:
        monkey.moving_right = True
    if event.key == pygame.K_LEFT:
        monkey.moving_left = True

def keyup_events(event, monkey):
    if event.key == pygame.K_RIGHT:
        monkey.moving_right = False
    if event.key == pygame.K_LEFT:
        monkey.moving_left = False

def check_events(monkey):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            keydown_events(event, monkey)
        if event.type == pygame.KEYUP:
            keyup_events(event, monkey)

def create_banana(screen, settings, bananas):
        banana = Banana(screen, settings)
        bananas.add(banana)

def update_banana(monkey, bananas):
    '''kill bananas, collisions with monkey'''
    for banana in bananas.copy():
        if banana.rect.bottom >= 720:
            bananas.remove(banana)
    collision = pygame.sprite.spritecollide(monkey, bananas, True)
    if collision:
        bananas.remove(banana)

        # time.sleep(2)
        # fall_interval = banana.threading.Timer(3, create_banana(screen, settings, bananas))
        # fall_interval.start()

Body:
You can use coroutines to run functions at the same time using asyncio. For example:

import asyncio
import time

async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

If you create a new task for each banana, you should be able to get a few on screen at different times.

Source: https://docs.python.org/3/library/asyncio-task.html


问:
How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?
I download eclipse for c++ (cdt-master-8.0.2.zip).

When I write:

```<code>#include <iostream>
</code>```

It marks:

```<code>Unresolved inclusion: <iostream>
</code>```

How can I fix it?

答: I'd had this issue with Eclipse 2019-12 where the includes were previously being resolved, but then weren't.  This was with a Meson build C/C++ project.  I'm not sure exactly what happened, but closing the project and reopening it resolved the issue for me.</p>

Body:
I download eclipse for c++ (cdt-master-8.0.2.zip).

When I write:

#include <iostream>

It marks:

Unresolved inclusion: <iostream>

How can I fix it?


问:
How to manage Azure App Service Certificate
I have purchased an app service wildcard certificate and would like to import this cert into Azure Key vault for other purposes.  Once I export/import the cert into Azure key vault and use for other custom domains (for example: APIM) will the auto renew ability continue to work as expected (automatically) or will I be forced to manage the cert differently now stored in key vault? </p>

答: The renewal process of the certificate is managed on key vault, so doesn't matter where you use it, it will be the same renewal process. </p>


问:
Replace uploaded image using Cloudinary and Flutter
I upload my images like this:

```<code>CloudinaryResponse response = await this.url.uploadImage(filePath,
        filename: "background",
        folder: "alquileres/$userId/$portfolioId/$investmentId");
</code>```

The image names are "background_longID". I'd like to overwrite all the images.

I've found an old issue in Github but doesn't provide too much info (https://github.com/cloudinary/cloudinary_ios/issues/87)

答:
You can find details about the upload and various flags for upload on the documentation page at https://cloudinary.com/documentation/image_upload_api_reference#upload_method.

If the primary concern is that you don't want Cloudinary to add the _longId parameter to the file name, you can set the flag unique_filename=false during the upload.

Another flag that you should consider is overwrite. By default, this flag is set to false. So when you re-upload, the old image is not replaced. You could set the flag overwrite=true as well to ensure that the new image is uploaded correctly.

Body:
I upload my images like this:

CloudinaryResponse response = await this.url.uploadImage(filePath,
        filename: "background",
        folder: "alquileres/$userId/$portfolioId/$investmentId");

The image names are "background_longID". I'd like to overwrite all the images.

I've found an old issue in Github but doesn't provide too much info (https://github.com/cloudinary/cloudinary_ios/issues/87)


答:
I recommend to use a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:

banana_delay = 500 # 0.5 seconds
banana_event = pygame.USEREVENT + 1
pygame.time.set_timer(banana_event, banana_delay)
```

<p>Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between <code>pygame.USEREVENT</code> (24) and <code>pygame.NUMEVENTS</code> (32). In this case <code>pygame.USEREVENT+1</code> is the event id for the timer event, which spawns the bullets.</p>

<p>Create a new banana when the event occurs in the event loop:</p>

<pre class="lang-py prettyprint-override"><code>def check_events(screen, settings, bananas, monkey):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # [...]

        if event.type == banana_event:
            create_banana(screen, settings, bananas)
</code>```

The timer event can be stopped by passing 0 to the time parameter.

If you want spawn the bananas by a random time spawn, then you have to change the timespan (in milliseconds) randomly. Use random.randint(a, b) to generate random times:

if event.type == banana_event:
    create_banana(screen, settings, bananas)
    banana_delay = random.randint(500, 3000) # random from 0.5 to 3 seconds
    pygame.time.set_timer(banana_event, banana_delay)
```

Title: Pygame : Repeating an action every x amount of time

Body:
I recommend to use a timer event. Use pygame.time.set_timer() to repeatedly create an USEREVENT. e.g.:

banana_delay = 500 # 0.5 seconds
banana_event = pygame.USEREVENT + 1
pygame.time.set_timer(banana_event, banana_delay)

Note, in pygame customer events can be defined. Each event needs a unique id. The ids for the user events have to be between pygame.USEREVENT (24) and pygame.NUMEVENTS (32). In this case pygame.USEREVENT+1 is the event id for the timer event, which spawns the bullets.

Create a new banana when the event occurs in the event loop:

def check_events(screen, settings, bananas, monkey):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # [...]

        if event.type == banana_event:
            create_banana(screen, settings, bananas)

The timer event can be stopped by passing 0 to the time parameter.

If you want spawn the bananas by a random time spawn, then you have to change the timespan (in milliseconds) randomly. Use random.randint(a, b) to generate random times:

if event.type == banana_event:
    create_banana(screen, settings, bananas)
    banana_delay = random.randint(500, 3000) # random from 0.5 to 3 seconds
    pygame.time.set_timer(banana_event, banana_delay)


问:
How to test Android Workers with In-Memory Room database injected by Koin
My current Android Application employs Koin for DI

```<code>def koin_version = '2.0.1'
api "org.koin:koin-androidx-scope:$koin_version"
api "org.koin:koin-androidx-viewmodel:$koin_version"
api "org.koin:koin-androidx-ext:$koin_version"

androidTestImplementation "org.koin:koin-test:$koin_version"
</code>```

I wish to test my Workers that have my Room database injected into them

For testing I wish to inject an In Memory version of my Room database.

the worker version I have is

```<code>def work_version = '2.3.0'
implementation "androidx.work:work-runtime:$work_version"
implementation "androidx.work:work-runtime-ktx:$work_version"
androidTestImplementation "androidx.work:work-testing:$work_version"
</code>```

This is the test I am running

```<code>@RunWith(AndroidJUnit4::class)
class MyWorkerTest : KoinTest {
    private lateinit var context: Context

    @Before
    fun startKoinForTest() {
        context = InstrumentationRegistry.getInstrumentation().targetContext

        if (GlobalContext.getOrNull() == null) {
            startKoin {
                androidLogger()
                androidContext(context)
                modules(roomTestModule)
            }
        }
    }

    @After
    fun stopKoinAfterTest() = stopKoin()

    @Test
    fun testMyWorker() {
        val worker = TestListenableWorkerBuilder<MyWorker>(context).build()
        runBlocking {
            val result = worker.doWork()
            assertThat(result, `is`(Result.success()))
        }
    }
}
</code>```

My Koin testDatabase Module resembles this :-

```<code>val roomTestModule = module {
    single {
        Room.inMemoryDatabaseBuilder(androidApplication(), MyDatabase::class.java)
            .allowMainThreadQueries()
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    Timber.e("In Memory")
                }
            })
            .build()
    }
}
</code>```

However the Database version injected into my Worker is always the Disk based one.

My Worker resembles this :-

```<code>class MyWorker(val context: Context, val params: WorkerParameters) :
    CoroutineWorker(context, params),
    KoinComponent {

    internal val service: MyService by inject()
    internal val database: MyDatabase by inject()

    override suspend fun doWork(): Result = coroutineScope {
        withContext(Dispatchers.IO) {

        }
    }
}
</code>```

How can I inject my In Memory database into my workers for testing?

答:
You can use a custom WorkerFactory (https://developer.android.com/reference/androidx/work/WorkerFactory) to create instances of your Workers. That way you can have Koin inject the dependencies before doWork() is invoked.

To use a custom WorkerFactory you need to use the following API:
https://developer.android.com/reference/androidx/work/Configuration.Builder#setWorkerFactory(androidx.work.WorkerFactory)

Body:
My current Android Application employs Koin for DI

def koin_version = '2.0.1'
api "org.koin:koin-androidx-scope:$koin_version"
api "org.koin:koin-androidx-viewmodel:$koin_version"
api "org.koin:koin-androidx-ext:$koin_version"

androidTestImplementation "org.koin:koin-test:$koin_version"

I wish to test my Workers that have my Room database injected into them

For testing I wish to inject an In Memory version of my Room database.

the worker version I have is

def work_version = '2.3.0'
implementation "androidx.work:work-runtime:$work_version"
implementation "androidx.work:work-runtime-ktx:$work_version"
androidTestImplementation "androidx.work:work-testing:$work_version"

This is the test I am running

@RunWith(AndroidJUnit4::class)
class MyWorkerTest : KoinTest {
    private lateinit var context: Context

    @Before
    fun startKoinForTest() {
        context = InstrumentationRegistry.getInstrumentation().targetContext

        if (GlobalContext.getOrNull() == null) {
            startKoin {
                androidLogger()
                androidContext(context)
                modules(roomTestModule)
            }
        }
    }

    @After
    fun stopKoinAfterTest() = stopKoin()

    @Test
    fun testMyWorker() {
        val worker = TestListenableWorkerBuilder<MyWorker>(context).build()
        runBlocking {
            val result = worker.doWork()
            assertThat(result, `is`(Result.success()))
        }
    }
}

My Koin testDatabase Module resembles this :-

val roomTestModule = module {
    single {
        Room.inMemoryDatabaseBuilder(androidApplication(), MyDatabase::class.java)
            .allowMainThreadQueries()
            .addCallback(object : RoomDatabase.Callback() {
                override fun onCreate(db: SupportSQLiteDatabase) {
                    super.onCreate(db)
                    Timber.e("In Memory")
                }
            })
            .build()
    }
}

However the Database version injected into my Worker is always the Disk based one.

My Worker resembles this :-

class MyWorker(val context: Context, val params: WorkerParameters) :
    CoroutineWorker(context, params),
    KoinComponent {

    internal val service: MyService by inject()
    internal val database: MyDatabase by inject()

    override suspend fun doWork(): Result = coroutineScope {
        withContext(Dispatchers.IO) {

        }
    }
}

How can I inject my In Memory database into my workers for testing?