问:
Change variable value of the already running program
I think it is impossible, but I should try.

I have a program, that is doing a physical simulation and recording frames to files. It is recording until the breakup value is not achieved, like:

```<code>int counter=0; //global variable

void SomeFunction()
{
...
if(counter == 400) //written exactly by this way, i.e. 400 is not a variable, just a number
PostQuitMessage(0);
else
MakeScreenshot();

counter++;
...
}
</code>```

The problem is that I forgot to change if(counter == 400) to if(counter == 1000) and now program will be finished with 400 frames, although I need exactly 1000.

I can’t just recompile the program because calculations are very heavy and the program is already running for 2 days, I can’t wait.

It is very important for me, is there any way to change the if statement, or exactly the variable value during the program running?

The only hope I have, is, as far as I remember there was programs that could like change money/health/another stuff in games, and there user exactly could search a variable by value, and change it

Currently it is on about 200-300 frame, I have so little time to fix it.

答:
I downloaded Cheat engine and found address of the counter variable by its value. Through all addresses, the address I need was colored in green.

I changed the value stored at that address to 401, and now all is ok.

Body:
I think it is impossible, but I should try.

I have a program, that is doing a physical simulation and recording frames to files. It is recording until the breakup value is not achieved, like:

int counter=0; //global variable

void SomeFunction()
{
...
if(counter == 400) //written exactly by this way, i.e. 400 is not a variable, just a number
PostQuitMessage(0);
else
MakeScreenshot();

counter++;
...
}

The problem is that I forgot to change if(counter == 400) to if(counter == 1000) and now program will be finished with 400 frames, although I need exactly 1000.

I can’t just recompile the program because calculations are very heavy and the program is already running for 2 days, I can’t wait.

It is very important for me, is there any way to change the if statement, or exactly the variable value during the program running?

The only hope I have, is, as far as I remember there was programs that could like change money/health/another stuff in games, and there user exactly could search a variable by value, and change it

Currently it is on about 200-300 frame, I have so little time to fix it.


来源: stackexchange

问:
Use float or decimal for accounting application dollar amount?
We are rewriting our legacy accounting system in VB.NET and SQL Server. We brought in a new team of .NET/ SQL Programmers to do the rewrite. Most of the system is already completed with the dollar amounts using floats. The legacy system language, I programmed in, did not have a float, so I probably would have used a decimal.

What is your recommendation?

Should the float or decimal data type be used for dollar amounts?

What are some of the pros and cons for either?

One con mentioned in our daily scrum was you have to be careful when you calculate an amount that returns a result that is over two decimal positions. It sounds like you will have to round the amount to two decimal positions.

Another con is all displays and printed amounts have to have a format statement that shows two decimal positions. I noticed a few times where this was not done and the amounts did not look correct.  (i.e. 10.2 or 10.2546)

A pro is the float-only approach takes up eight bytes on disk where the decimal would take up nine bytes (decimal 12,2).

答:
For a banking system I helped develop, I was responsible for the "interest accrual" part of the system.  Each day, my code calculated how much interest had been accrued (earnt) on the balance that day.

For that calculation, extreme accuracy and fidelity was required (we used Oracle's FLOAT) so we could record the "billionth's of a penny" being accrued.

When it came to "capitalising" the interest (ie. paying the interest back into your account) the amount was rounded to the penny.  The data type for the account balances was two decimal places.  (In fact it was more complicated as it was a multi-currency system that could work in many decimal places - but we always rounded to the "penny" of that currency).  Yes - there where "fractions" of loss and gain, but when the computers figures were actualised (money paid out or paid in) it was always REAL money values.

This satisfied the accountants, auditors and testers.

So, check with your customers.  They will tell you their banking/accounting rules and practices.

OwnerDisplayName: Gerhard Weiss

ContentLicense: CC BY-SA 4.0

LastEditorDisplayName: Gerhard Weiss

OwnerDisplayName: Guy

ContentLicense: CC BY-SA 2.5


问:
UITableView issue when using separate delegate/dataSource
General Description:

To start with what works, I have a UITableView which has been placed onto an Xcode-generated view using Interface Builder.  The view's File Owner is set to an Xcode-generated subclass of UIViewController.  To this subclass I have added working implementations of numberOfSectionsInTableView: tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: and the Table View's dataSource and delegate are connected to this class via the File Owner in Interface Builder.

The above configuration works with no problems.  The issue occurs when I want to move this Table View's dataSource and delegate-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class.  To accomplish this, I try the following:

Create a new subclass of UITableViewController in Xcode

Move the known-good implementations of numberOfSectionsInTableView:, tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: to the new subclass

Drag a UITableViewController to the top level of the  existing XIB in InterfaceBuilder, delete the UIView/UITableView that are automatically created for this UITableViewController, then set the UITableViewController's class to match the new subclass

Remove the previously-working UITableView's existing dataSource and delegate connections and connect them to the new UITableViewController

When complete, I do not have a working UITableView.  I end up with one of three outcomes which can seemingly happen at random:

When the UITableView loads, I get a runtime error indicating I am sending tableView:cellForRowAtIndexPath: to an object which does not recognize it

When the UITableView loads, the project breaks into the debugger without error

There is no error, but the UITableView does not appear

With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view).  I added some NSLog calls and found that although numberOfSectionsInTableView: and numberOfRowsInSection: are both getting called, cellForRowAtIndexPath: is not.  I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have.  If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project.  Thanks for your time!

Complete steps to reproduce:

Create a new iPhone OS, View-Based Application in Xcode and call it TableTest

Open TableTestViewController.xib in Interface Builder and drag a UITableView onto the provided view surface.

Connect the UITableView's dataSource and delegate-outlets to File's Owner, which should already represent the TableTestViewController-class.  Save your changes

Back in Xcode, add the following code to TableTestViewController.m:

```<code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"Returning num sections");
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"Returning num rows");
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Trying to return cell");
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.text = @"Hello";
    NSLog(@"Returning cell");
    return cell;
}
</code>```

Build and Go, and you should see the word Hello appear in the UITableView

Now to attempt to move this UITableView's logic out to a separate class, first create a new file in Xcode, choosing UITableViewController subclass and calling the class TableTestTableViewController

Remove the above code snippet from TableTestViewController.m and place it into TableTestTableViewController.m, replacing the default implementation of these three methods with ours.

Back in Interface Builder within the same TableTestViewController.xib-file, drag a UITableViewController into the main IB window and delete the new UITableView object that automatically came with it

Set the class for this new UITableViewController to TableTestTableViewController

Remove the dataSource and delegate bindings from the existing, previously-working UITableView and reconnect the same two bindings to the new TableTestTableViewController we created.

Save changes, Build and Go, and if you're getting the results I'm getting, note the UITableView no longer functions properly

Solution:
With some more troubleshooting and some assistance from the iPhone Developer Forums, I've documented a solution!  The main UIViewController subclass of the project needs an outlet pointing to the UITableViewController instance.  To accomplish this, simply add the following to the primary view's header (TableTestViewController.h):

```<code>#import "TableTestTableViewController.h"
</code>```

and

```<code>IBOutlet TableTestTableViewController *myTableViewController;
</code>```

Then, in Interface Builder, connect the new outlet from File's Owner to TableTestTableViewController in the main IB window.  No changes are necessary in the UI part of the XIB.  Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely.  Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.

答:
I just spent many hours pulling my hair out trying to figure out why a UITableView wouldn't show up when when I had it embedded in a separate nib instead of in the main nib.  I finally found your discussion above and realized that it was because my UITableViewController wasn't being retained!  Apparently the delegate and datasource properties of UITableView are not marked "retain" and so my nib was loading but the controller was getting tossed...  And due to the wonders of objective-c I got no error messages at all from this... I still don't understand why it didn't crash.  I know that I've seen "message sent to released xxx" before... why wasn't it giving me one of those?!?

I think most developers would assume that structure that they build in an interface builder would be held in some larger context (the Nib) and not subject to release.  I guess I know why they do this.. so that the iPhone can drop and reload parts of the nib on low memory.  But man, that was hard to figure out.

Can someone tell me where I should have read about that behavior in the docs?

Also - about hooking up the view.  First, if you drag one in from the UI builder you'll see that they hook up the view property (which is an IBOutlet) to the table view.  It's not necessary to expose the tableView, that seems to get set internally.  In fact it doesn't even seem to be necessary to set the view unless you want viewDidLoad notification. I've just broken the view connection between my uitableview and uitableviewcontroller (only delegate and datasource set) and it's apparently working fine.

ContentLicense: CC BY-SA 3.0

Body:
General Description:

To start with what works, I have a UITableView which has been placed onto an Xcode-generated view using Interface Builder.  The view's File Owner is set to an Xcode-generated subclass of UIViewController.  To this subclass I have added working implementations of numberOfSectionsInTableView: tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: and the Table View's dataSource and delegate are connected to this class via the File Owner in Interface Builder.

The above configuration works with no problems.  The issue occurs when I want to move this Table View's dataSource and delegate-implementations out to a separate class, most likely because there are other controls on the View besides the Table View and I'd like to move the Table View-related code out to its own class.  To accomplish this, I try the following:

Create a new subclass of UITableViewController in Xcode

Move the known-good implementations of numberOfSectionsInTableView:, tableView:numberOfRowsInSection: and tableView:cellForRowAtIndexPath: to the new subclass

Drag a UITableViewController to the top level of the  existing XIB in InterfaceBuilder, delete the UIView/UITableView that are automatically created for this UITableViewController, then set the UITableViewController's class to match the new subclass

Remove the previously-working UITableView's existing dataSource and delegate connections and connect them to the new UITableViewController

When complete, I do not have a working UITableView.  I end up with one of three outcomes which can seemingly happen at random:

When the UITableView loads, I get a runtime error indicating I am sending tableView:cellForRowAtIndexPath: to an object which does not recognize it

When the UITableView loads, the project breaks into the debugger without error

There is no error, but the UITableView does not appear

With some debugging and having created a basic project just to reproduce this issue, I am usually seeing the 3rd option above (no error but no visible table view).  I added some NSLog calls and found that although numberOfSectionsInTableView: and numberOfRowsInSection: are both getting called, cellForRowAtIndexPath: is not.  I am convinced I'm missing something really simple and was hoping the answer may be obvious to someone with more experience than I have.  If this doesn't turn out to be an easy answer I would be happy to update with some code or a sample project.  Thanks for your time!

Complete steps to reproduce:

Create a new iPhone OS, View-Based Application in Xcode and call it TableTest

Open TableTestViewController.xib in Interface Builder and drag a UITableView onto the provided view surface.

Connect the UITableView's dataSource and delegate-outlets to File's Owner, which should already represent the TableTestViewController-class.  Save your changes

Back in Xcode, add the following code to TableTestViewController.m:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSLog(@"Returning num sections");
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSLog(@"Returning num rows");
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Trying to return cell");
    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.text = @"Hello";
    NSLog(@"Returning cell");
    return cell;
}

Build and Go, and you should see the word Hello appear in the UITableView

Now to attempt to move this UITableView's logic out to a separate class, first create a new file in Xcode, choosing UITableViewController subclass and calling the class TableTestTableViewController

Remove the above code snippet from TableTestViewController.m and place it into TableTestTableViewController.m, replacing the default implementation of these three methods with ours.

Back in Interface Builder within the same TableTestViewController.xib-file, drag a UITableViewController into the main IB window and delete the new UITableView object that automatically came with it

Set the class for this new UITableViewController to TableTestTableViewController

Remove the dataSource and delegate bindings from the existing, previously-working UITableView and reconnect the same two bindings to the new TableTestTableViewController we created.

Save changes, Build and Go, and if you're getting the results I'm getting, note the UITableView no longer functions properly

Solution:
With some more troubleshooting and some assistance from the iPhone Developer Forums, I've documented a solution!  The main UIViewController subclass of the project needs an outlet pointing to the UITableViewController instance.  To accomplish this, simply add the following to the primary view's header (TableTestViewController.h):

#import "TableTestTableViewController.h"

and

IBOutlet TableTestTableViewController *myTableViewController;

Then, in Interface Builder, connect the new outlet from File's Owner to TableTestTableViewController in the main IB window.  No changes are necessary in the UI part of the XIB.  Simply having this outlet in place, even though no user code directly uses it, resolves the problem completely.  Thanks to those who've helped and credit goes to BaldEagle on the iPhone Developer Forums for finding the solution.

LastEditorDisplayName: Ryan Townshend

OwnerDisplayName: Pat Niemeyer

LastEditorDisplayName: Pat Niemeyer


问:
Import the data from the XML files into a MySQL database
I would like to build a Rails application to import the data from a XML file into a MySQL database. Any help?</p>

答:
Why do you need Rails for this task? Will the XML file be uploaded by users? If not, then a script in ruby may be all you need.

In all cases you need to:

parse incoming XML and set the properties of some object or variables

save these properties or variables in the database.

For the first task you may use ReXML, LibXML, Nokogiri or any other XML parser library.

For the second (if you don't use ActiveRecord in Rails), you may see the documentation for the mysql2 gem.

Feel free to ask further questions if you have any problems with these libraries.


问:
Elastic BeanStalk Application versions update automatically during specific time
Elastic Beanstalk application version is updated automatically daily during specific time. Don't how it is getting triggered and source is upload. Can someone suggest how can we find why application version is updated and source is uploaded.</p>

```<code>**Version label**                                                             **Source**
87f62452d3h673377a1d331502d8f8                             class-time-service-hzavks12/program-time-service-87f62452d3h673377a1d331502d8f8-jenkins-hzavk12-branch-deploy-program-time-service-100.zip
-jenkins-hzavk12-branch-deploy-program-time-service-100

</code>```

答:
To investigate who/what triggers the deployments of your app daily during a specific time can have a look at:

event history in CloudTrial for API calls related to EB.

rules in CloudWatch Events, especially scheduled expressions which cloud execute a lambda-based or CodePiepline deployments of your application.

Jenkins setup. From the file name it seems the deployment zip  originates from Jenkins. Maybe Jenkins is performing the deployment on a recurring schedule.

Body:
Elastic Beanstalk application version is updated automatically daily during specific time. Don't how it is getting triggered and source is upload. Can someone suggest how can we find why application version is updated and source is uploaded.

**Version label**                                                             **Source**
87f62452d3h673377a1d331502d8f8                             class-time-service-hzavks12/program-time-service-87f62452d3h673377a1d331502d8f8-jenkins-hzavk12-branch-deploy-program-time-service-100.zip
-jenkins-hzavk12-branch-deploy-program-time-service-100


问:
Read random line from file also imports a \n?
So my code is :

    fs.readFile(fileName, function(err, data){
        data += "";
        var lines = data.split('\n');
        randomLineN = Math.floor(Math.random() * lines.length)
        randomString = lines[randomLineN];
        uploader=""
        fs.readFile("./uploaders.txt", function(err, data){
            data += '';
            var lines = data.split('\n');
            uploader = lines[randomLineN];
            msg.reply("Enjoy this random clip submitted by : {0} [{1}]".format(uploader,randomString))
        })
    })
```

But when I execute that, it shows:
http://prntscr.com/srlpma
And I do not want there to be a new line! I want all this in one line... How though?
(I tried "uploader.replace(/\n/g, '')", dosen't work though.)

答:
I think the problem is with randomString.

Try

randomString.replace(/\n/g, '')
```

<p>or for better </p>

<pre class="lang-js prettyprint-override"><code>randomString.replace(/\r?\n|\r/g, '')
</code>```

Body:
So my code is :

    fs.readFile(fileName, function(err, data){
        data += "";
        var lines = data.split('\n');
        randomLineN = Math.floor(Math.random() * lines.length)
        randomString = lines[randomLineN];
        uploader=""
        fs.readFile("./uploaders.txt", function(err, data){
            data += '';
            var lines = data.split('\n');
            uploader = lines[randomLineN];
            msg.reply("Enjoy this random clip submitted by : {0} [{1}]".format(uploader,randomString))
        })
    })

But when I execute that, it shows:
http://prntscr.com/srlpma
And I do not want there to be a new line! I want all this in one line... How though?
(I tried "uploader.replace(/\n/g, '')", dosen't work though.)

Body:
I think the problem is with randomString.

Try

randomString.replace(/\n/g, '')

or for better

randomString.replace(/\r?\n|\r/g, '')


问:
How to find rows of a dataframe containing a date value?
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

```<code>   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})
</code>```

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

```                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7
```

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

答:
```<code>import pandas as pd
from datetime import datetime

dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
dt3 = pd.Series([1,2,3,4,5,6,7])
df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})

m = pd.concat([pd.to_datetime(df['A'], errors='coerce'),
               pd.to_datetime(df['B'], errors='coerce')], axis=1).isna().all(axis=1)

print(df[~m])
</code>```

Prints:

```<code>                            A                           B  C
1  2020-06-01 12:17:51.320286  2020-06-01 12:17:51.320826  2
6                  2020-05-05                  2020-05-25  7
</code>```

Body:
There is a huge dataframe containing multiple data types in different columns. I want to find rows that contain date values in different columns.
Here a test dataframe:

   dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
   dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
   dt3 = pd.Series([1,2,3,4,5,6,7])
   df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})

Now, I want to create a new dataframe that contains only dates in both columns A and B, here rows 2nd and last.

Expected output:

                            A                           B  C
1  2020-06-01 16:58:17.274311  2020-06-01 17:13:20.391394  2
6                  2020-05-05                  2020-05-25  7

What is the best way to do that? Thanks.

P.S.> Dates can be in any standard format.

Body:
import pandas as pd
from datetime import datetime

dt = pd.Series(['abc', datetime.now(), 12, '', None, np.nan, '2020-05-05'])
dt1 = pd.Series([3, datetime.now(), 'sam', '', np.nan, 'abc-123', '2020-05-25'])
dt3 = pd.Series([1,2,3,4,5,6,7])
df = pd.DataFrame({"A":dt.values, "B":dt1.values, "C":dt3.values})

m = pd.concat([pd.to_datetime(df['A'], errors='coerce'),
               pd.to_datetime(df['B'], errors='coerce')], axis=1).isna().all(axis=1)

print(df[~m])

Prints:

                            A                           B  C
1  2020-06-01 12:17:51.320286  2020-06-01 12:17:51.320826  2
6                  2020-05-05                  2020-05-25  7


问:
Extending Python syntax for own needs: how hard? will it break Anaconda?
The first part is what I want to do and the questions. Before discussing why I want to to that and proposing counterarguments, please read the motivation in the second part.

In short: I am not a developer. The main use of Python is fast prototyping of mathematical methods; additional motivation is learning how Python is implemented. This topic is not of crucial importance for me. If it seems lame and off-topic, feel free to remove, and I apologize for the inconvenience.

This feature does not introduce new functionality but serves as a shortcut for lambda.
The idea is borrowed from wolfram-language.

If the symbol of closing parenthesis is preceded with &, then the code inside the parentheses is interpreted as the definition of a function, where `1</code>, <code>`2, ... play the role of its arguments.
Example: (`1 + `2 &)(a, b) means (lambda x, y: x + y)(a, b)

Provided that I learn everything needed about Python, how hard / time consuming is to implement that extension? At the moment, I see two options:

1.a. Preprocessing text of the script before compiling (I use iPython in Anaconda).

Immediate problem: assigning unique names to arguments. Possible workaround: reserve names such as __my_lambda_123.

1.b. Modifying CPython similarly as described in https://hackernoon.com/modifying-the-python-language-in-7-minutes-b94b0a99ce14

Imagine that I implemented that feature correctly. Do you immediately see that it breaks something essential in Python, or iPython, or Anaconda? Assume that I do not use any developers' packages such as unittest, but a lot of "scientific" packages including numpy, as well as "interface" packages such as sqlalchemy.

Motivation. I gradually study Python as a programming language and appreciate its deepness, consistency and unique philosophy. I understand that my idea is not in line with the latter. However, I use Python for implementing mathematical methods which are barely reusable. A typical life cycle is following: (1) implement some mathematical method and experiments for a research project; (1.a) maybe save some function/class in my package if it feels reusable; (2) conduct computational experiments; (3) publish a paper; (4) never use the code again. It is much easier to implement an algorithm from scratch than to structure and reuse the code since the coincidence between large parts of different methods is very rare.

My typical project is one large Python script with long code fragments. Even structuring the code into functions is not time-efficient, since the life cycle of my program does not include "deploy", "maintain", "modify". I keep the amount of structure to a minimum needed for fast implementing and debugging.

I would use wolfram-mathematica but in my recent projects, it became useless due to the limitations of its standard libraries, the poor performance of the code in Wolfram language, and overall closeness of the platform. I switch to Python for its rich selection of libraries, and also with the intent of acquiring some software developer's skills. However, at the moment, programming in the Wolfram language style is much more efficient for me. The code of algorithms feels much more readable when it is more compact (you do not need to scroll), and includes less language-specific words such as lambda.

答:
Just as a heads up, the issue you raise in 1a is called macro hygiene.

It's also a bit sketchy to be doing the "lambda replacing" in text, before it's converted to an abstract syntax tree (AST). This is certainly going to be prone to errors since now you have to explicitly deal with various parsing issues and the actual replacement in one go.

If you do go this route (I don't recommend it), I recommend you also look at Racket's macro system, which can do what you want.

There are also other potential problems you might run into - you need to think about how you want strings such as ("`1" + `1)(a) to parse, or, for example, strings such as (`2 + `3)(a, b) - is this an error or is it ok (if so, which argument goes where?). These are the kinds of test cases you need to think about if you're sure you want to design an addition to Python's syntax.

There's also a practical consideration - you'll essentially need to support your own fork of Python, so you won't be able to get updates to the language without redeveloping this feature for each release (kind of? I think).

TLDR: I highly recommend you don't do this, just use lambdas.


问:
What is the difference between pyenv, virtualenv, anaconda?
I am a ruby programmer trying to learn python. I am pretty familiar with pyenv since it is like a copy and paste from rbenv. Pyenv helps allow to have more than one version of python in a system and also to isolate the python without touching sensitive parts of system.

I suppose every python installation comes with pip package. What I still don't understand is, there are many good python libs out there that suggest to use this virtualenv and anaconda. I can even find a virtualenv plugin for pyenv.

Now I am getting confused with the purpose of these two pyenv and virtualenv.
worse inside pyenv there is a virtualenv plugin.

My questions are:

what is the difference between pyenv and virtualenv?

Is there any difference in using  pip command inside both pyenv and virtualenv?

what does this pyenv virutalenv do?

Your explanation with example will be highly appreciated.

答:
Simple analogy:

pyenv ~ rbenv

pip ~ bundler

virtual env ~ gemset in rvm. This can be managed by bundler directly without gemset.

Since I use python3 I prefer the python3 built-in virtual environment named venv. venv is simple and easy to use. I would recommend you to read its official docs. The doc is short and concise.

In ruby, we don't really need a virtual environment because the bundler takes care of it. Both virtual env and bundler are great, however, they have different solutions to solve the same problem.


问:
I need to calculate the number of holidays, falling on working days only, between two dates
I have a table, called Holidays, which lists all the dates classed as a holiday:

```<code>Date
01/01/2020
10/04/2020
13/04/2020
</code>```

I have a table called employees, which shows an employee's working days, in a 7 digit syntax, where 0 is a working day and 1 is not a working day. It goes from Monday to Sunday. So '0000011' would mean that person works on Monday to Friday, and does not work on Saturday/Sunday.

```<code>Code     WorkingDays
A1       0000011
B1       1000111
</code>```

I have a table of date ranges as such:

```<code>From         To          Employee
01/01/2020   31/05/2020  A1
01/01/2020   31/05/2020  B1
</code>```

What I would like to return is:

```<code>From         To          Employee    Holidays
01/01/2020   31/05/2020  A1          3
01/01/2020   31/05/2020  B1          0
</code>```

Employee A1 - there are 3 Holidays which fall between those two dates and are also working days
Employee B1 - there are no Holidays which fall between those two dates and are also working days

I need something similar to the NETWORKDAYS.INTL function, but instead of calculating working days I need it to calculate holidays somehow. Is this possible?

答:
I'd think maybe SUMPRODUCT is a good alternative to what you are looking for:

Formula in G2:

```<code>=SUMPRODUCT((A$2:A$4>=D2)*(A$2:A$4<=E2)*(MID(C2,WEEKDAY(A$2:A$4,2),1)="0"))
</code>```

Drag down.

Body:
I have a table, called Holidays, which lists all the dates classed as a holiday:

Date
01/01/2020
10/04/2020
13/04/2020

I have a table called employees, which shows an employee's working days, in a 7 digit syntax, where 0 is a working day and 1 is not a working day. It goes from Monday to Sunday. So '0000011' would mean that person works on Monday to Friday, and does not work on Saturday/Sunday.

Code     WorkingDays
A1       0000011
B1       1000111

I have a table of date ranges as such:

From         To          Employee
01/01/2020   31/05/2020  A1
01/01/2020   31/05/2020  B1

What I would like to return is:

From         To          Employee    Holidays
01/01/2020   31/05/2020  A1          3
01/01/2020   31/05/2020  B1          0

Employee A1 - there are 3 Holidays which fall between those two dates and are also working days
Employee B1 - there are no Holidays which fall between those two dates and are also working days

I need something similar to the NETWORKDAYS.INTL function, but instead of calculating working days I need it to calculate holidays somehow. Is this possible?

Body:
I'd think maybe SUMPRODUCT is a good alternative to what you are looking for:

Formula in G2:

=SUMPRODUCT((A$2:A$4>=D2)*(A$2:A$4<=E2)*(MID(C2,WEEKDAY(A$2:A$4,2),1)="0"))

Drag down.


问:
Making an aim trajectory using a line renderer
The reference of a trajectory line

Hey, i'm new to unity and trying to create a trajectory line with the help of a line renderer but it doesn't seem to be working. I have attached my movement script below. It would be very helpful if someone helps me out.

```<code>public void Update()
{

    if (Input.GetMouseButtonDown(0)) //press
    {
        startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
        startPoint.z = 15;
        direction = endPoint - startPoint;
        transform.right = direction;

        for (int i = 0; i < numberOfDots; i++)
        {
            trajectoryDots[i].transform.position = calculatePosition(i * 0.01f);
        }
    }

    if (Input.GetMouseButtonUp(0)) //release
    {
        endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
        endPoint.z = 15;

        force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
        rb.AddForce(force * power, ForceMode2D.Impulse);
    }

}
</code>```

答:
Line render don't have transforms for all it's position.

So u can't set the transform's position.  Instead use lineRenderer.SetPosition function to set the position of the point in the line along with the index.

Body:
The reference of a trajectory line

Hey, i'm new to unity and trying to create a trajectory line with the help of a line renderer but it doesn't seem to be working. I have attached my movement script below. It would be very helpful if someone helps me out.

public void Update()
{

    if (Input.GetMouseButtonDown(0)) //press
    {
        startPoint = cam.ScreenToWorldPoint(Input.mousePosition);
        startPoint.z = 15;
        direction = endPoint - startPoint;
        transform.right = direction;

        for (int i = 0; i < numberOfDots; i++)
        {
            trajectoryDots[i].transform.position = calculatePosition(i * 0.01f);
        }
    }

    if (Input.GetMouseButtonUp(0)) //release
    {
        endPoint = cam.ScreenToWorldPoint(Input.mousePosition);
        endPoint.z = 15;

        force = new Vector2(Mathf.Clamp(startPoint.x - endPoint.x, minPower.x, maxPower.x), Mathf.Clamp(startPoint.y - endPoint.y, minPower.y, maxPower.y));
        rb.AddForce(force * power, ForceMode2D.Impulse);
    }

}


问:
Flutter - Disk Full Error - A Document Being Saved by xcdevice
I'm running into an issue where my iMac, with over 100G free, gets Disk Full Error after running Flutter for an hour or so.

When I reboot I get dozens folders in my Trash "Recovered Files" that are around 2G each.

The issue is actually described fairly well here (with screenshots): https://github.com/flutter/flutter/issues/56270

However, the moderator closed every comment as "off topic" (seems like several people are having this problem). So I figured it may be a good idea to bring this here to see if anyone else has found a solution for this?

I'm running VSCode and when I run Flutter Doctor I'm 100% compliant. Using the latest Flutter/Dart/MacOS/Xcode/Android Studio versions. I am primarily building my Flutter app to macOS platform (desktop).

I tried the suggestions in the above issue post and none of these worked for me (re-installing cocoa pods, re-installing Xcode, re-installing Android Studio).

答:
Can confirm, running flutter with an attached ios device eats disk space.

This is happening to myself and another developer on my team. I lost 200 GB of disk space yesterday. It's a frustrating productivity killer.

I am using the latest flutter

flutter doctor reports everything as fine

xcrun --find simctl is fine

Using Android studio 3.6.3

Latest patched Catalina 10.15.4

This morning I opened the Android Studio IDE with an android device and an ios device connected. I opened a get info window on my hard drive and left it open. Then I did nothing but watch the info window.  No builds or anything. Over the course of a couple minutes, I watched 7 GB disappear.

I shut down the IDE and the loss stopped.  I reopened the IDE with only the android device attached. I waited and watched for a few minutes. No loss of disk space.

Then I reopened the IDE with just an ipad attached and the losses started again. Then I unplugged the ipad and left the IDE open and the losses stopped.


问:
Find min/max of two dates (typed)
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

```<code>TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.
</code>```

my code

```<code>  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);
</code>```

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

答:
You can compare dates like so in typescript:

const begin: Date = new Date();
const end: Date = new Date();

const min: Date = begin < end ? begin : end;
const max: Date = begin > end ? begin : end;
```

The problem you were having is that Math.min returns a number.

Title: Find min/max of two dates (typed)

Body:
I want a strongly typed code. When I apply solutions from a similar question - Min/Max of dates in an array? - I get error

TS2345: Argument of type 'Date' is not assignable to parameter of type 'number'.

my code

  const min: Date = Math.min(begin as Date, (end || defaultDate) as Date);
  const max: Date = Math.max(begin as Date, (end || defaultDate) as Date);

begin as Date part is underlined.

What's the correct way of finding min/max dates in Typescript?

Body:
You can compare dates like so in typescript:

const begin: Date = new Date();
const end: Date = new Date();

const min: Date = begin < end ? begin : end;
const max: Date = begin > end ? begin : end;

The problem you were having is that Math.min returns a number.


问:
create an alert using css, jquery/javascript arrays or switch
I'm doing some experimenting. So this may look bad to javascript experts here. But I'm trying to learn.

I have a header div that will show a larger image when the user mouses over each thumbnail image. I used jQuery to create this effect. The header div contains a button. Once the button is clicked, an alert will pop up to tell the user the artist's name of image. The button is wired to an ID of a paragraph. Problem is, my code is not working. I don't want to use "onclick" inline javascript (which is what I am using to call the showArtistname() function). I want unobtrusive javascript like jQuery is. I'm not sure how to do this. I don't know if I should use an array or if I'm even approaching this correctly. Well, it's not correct, because it's not working...

Here is my jQuery code:

```<code>$(function(){
$("a:has(img.small)").mouseover(function(){
var bigImage= $(this).attr("href");
$("#heading").attr({src: bigImage});
return false;
});

});
</code>```

Here is my javascript code:

```<code>function showArtistname(){

var a = document.getElementById   ("bluesails", "purplemountains", "bigsky", "nightlights", "fireysunset", "brilliantsunrise").innerHTML;

switch(a) {
case "bluesails":
    alert("Arthur MacKenzie")
    break
case "purplemountains":
    alert("Maggie Laing")
    break

case "bigsky":
    alert("Arthur MacKenzie")
    break

case "nightlights":
    alert("Aria Soriano")
    break

case "fireysunset":
    alert("Felix Buckley")
    break

case "brilliantsunrise":
    alert("Felix Buckley")

}
}
</code>```

Here is my HTML:

```<code><div class="container_12" id="_container">

<div class="grid_12" id="12_header" >

    <div class="hc_left_pic"> <img src="images/01_md.jpg" id="heading" alt="Big Image." />
 <div id="showImage" onclick="showArtistname()"></div>
  </a></div>
</div>

<div class="clear"></div>

<div class="grid_4" id="artist_container1">
<a href="images/01_md.jpg"><img src="images/01_sm.jpg" width="100" height="100" class="small" alt="Small image Blue Sails" /></a>
    <p class="text" id="bluesails">Blue Sails</p>
</div>

<div class="grid_4" id="artist_container2">
<a href="images/02_md.jpg"><img src="images/02_sm.jpg" width="100" height="100" class="small" alt="Small Image Purple Mountains"/></a>
    <p class="text" id="purplemountains">Purple Mountains</p>
</div>

<div class="grid_4" id="artist_container3">
<a href="images/03_md.jpg"><img src="images/03_sm.jpg" width="100" height="100" class="small" alt="Small Image Big Sky"/></a>
    <p class="text" id="bigsky">Big Sky</p>
</div>

<div class="clear"></div>

<div class="grid_4" id="artist_container4">
<a href="images/04_md.jpg"><img src="images/04_sm.jpg" width="100" height="100" class="small" alt="Small Image Night Lights" /></a>
    <p class="text" id="nightlights">Night Lights</p>
</div>

 <div class="grid_4" id="artist_container5">
<a href="images/05_md.jpg"><img src="images/05_sm.jpg" width="100" height="100" class="small"  alt="Small Product Image Firey Sunset"/></a>
    <p class="text" id="fireysunset">Firey Sunset</p>
</div>

<div class="grid_4" id="artist_container6">
<a href="images/06_md.jpg"><img src="images/06_sm.jpg" width="100" height="100" class="small"  alt="Small Product Image Brilliant Sunrise"/></a>
    <p class="text" id="brilliantsunrise">Brilliant Sunrise</p>
</div>
</code>```

Here is my CSS:

```<code>.container_12 .grid_4 {
  width: 274px;
  height: 370px;
  background-color:#ccc;
  border: 3px solid #999;
  padding-left:10px;
  padding-right:10px;
  padding-bottom:10px;
 }

#showImage{
margin: -170px 20px 80px 700px;
width: 176px;
height: 48px;
background:url(../images/showimage.jpg);
position:relative;
z-index:100;
}

 .grid_4 img {
position:relative;
left:100px;
top:20px;
padding:0 0 60px 0;
border:none;

}
.grid_4 p {
position:relative;
text-align:center;
}

p.text {
font-family:Arial, Helvetica, sans-serif;
font-size:.75em;
color:#000;
line-height:1.25em;
font-weight:bold;
}

#12_header {
display: inline;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
height:225px;
font-family:Arial, Helvetica, sans-serif;
font-size:;
color:#000;
font-weight:bold;
line-height:1.2em;

}

.hc_left_pic {
float:left;
margin-top:15px;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
width:935px;
height:250px;
}
</code>```

I hope I've given enough information to get a solution to this.

Thanks

答:
Seems you have a bit to learn in the way of jQuery, but we all did at one point, I see what your trying to do above, and your taking the same approach i would have a few years ago. Well done for giving us some code, it shows your not just looking for someone to do free work. Good job.

See below a jsfiddle of what you want.

NOTE:

Ive removed the links as they are made completely redundant (or at least they were with your return false;).

Also I've commented out all the css.

http://jsfiddle.net/YAaFg/

Have fun,

Cheers

Charlie

Body:
I'm doing some experimenting. So this may look bad to javascript experts here. But I'm trying to learn.

I have a header div that will show a larger image when the user mouses over each thumbnail image. I used jQuery to create this effect. The header div contains a button. Once the button is clicked, an alert will pop up to tell the user the artist's name of image. The button is wired to an ID of a paragraph. Problem is, my code is not working. I don't want to use "onclick" inline javascript (which is what I am using to call the showArtistname() function). I want unobtrusive javascript like jQuery is. I'm not sure how to do this. I don't know if I should use an array or if I'm even approaching this correctly. Well, it's not correct, because it's not working...

Here is my jQuery code:

$(function(){
$("a:has(img.small)").mouseover(function(){
var bigImage= $(this).attr("href");
$("#heading").attr({src: bigImage});
return false;
});

});

Here is my javascript code:

function showArtistname(){

var a = document.getElementById   ("bluesails", "purplemountains", "bigsky", "nightlights", "fireysunset", "brilliantsunrise").innerHTML;

switch(a) {
case "bluesails":
    alert("Arthur MacKenzie")
    break
case "purplemountains":
    alert("Maggie Laing")
    break

case "bigsky":
    alert("Arthur MacKenzie")
    break

case "nightlights":
    alert("Aria Soriano")
    break

case "fireysunset":
    alert("Felix Buckley")
    break

case "brilliantsunrise":
    alert("Felix Buckley")

}
}

Here is my HTML:

Blue Sails

Purple Mountains

Big Sky

Night Lights

Firey Sunset

Brilliant Sunrise

Here is my CSS:

.container_12 .grid_4 {
  width: 274px;
  height: 370px;
  background-color:#ccc;
  border: 3px solid #999;
  padding-left:10px;
  padding-right:10px;
  padding-bottom:10px;
 }

#showImage{
margin: -170px 20px 80px 700px;
width: 176px;
height: 48px;
background:url(../images/showimage.jpg);
position:relative;
z-index:100;
}

 .grid_4 img {
position:relative;
left:100px;
top:20px;
padding:0 0 60px 0;
border:none;

}
.grid_4 p {
position:relative;
text-align:center;
}

p.text {
font-family:Arial, Helvetica, sans-serif;
font-size:.75em;
color:#000;
line-height:1.25em;
font-weight:bold;
}

#12_header {
display: inline;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
height:225px;
font-family:Arial, Helvetica, sans-serif;
font-size:;
color:#000;
font-weight:bold;
line-height:1.2em;

}

.hc_left_pic {
float:left;
margin-top:15px;
background-color:#e5e5e5;
border: 3px solid #bfbfbf;
width:935px;
height:250px;
}

I hope I've given enough information to get a solution to this.

Thanks


问:
Multiple Views Vs Multiple Fragments
I'm going to create a complex/normal design that has an empty screen layout & shimmer layout.

my question is to have all in one layout with multiple <include> files is better than doing two fragments and keep replacing them.

more details:

1- make the data screen shown & empty screen hidden as follows:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar"
        layout="@layout/common_toolbar" />

    <include layout="@layout/empty_layout"/>

    // my data layout

</LinearLayout>
</code>```

2- create a FrameLayout and keep change the container for different screens with multiple fragments:

```<code><LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

I need to know the best practice as depending on slow rendering of multiple views.

another question, is that included in for shown/hidden views or it depends on shown ones only as I got confused
and need to apply best practices.

答:
if you attend to reuse some views Fragment is the best, otherwise, if you looking best to render I advise you to use constraint layout and section your views with a group so you can hide and show group
take a look to this one How to group multiple views in a ConstraintLayout</p>

Title: Multiple Views Vs Multiple Fragments

Body:
I'm going to create a complex/normal design that has an empty screen layout & shimmer layout.

my question is to have all in one layout with multiple <include> files is better than doing two fragments and keep replacing them.

more details:

1- make the data screen shown & empty screen hidden as follows:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/toolbar"
        layout="@layout/common_toolbar" />

    <include layout="@layout/empty_layout"/>

    // my data layout

</LinearLayout>

2- create a FrameLayout and keep change the container for different screens with multiple fragments:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

I need to know the best practice as depending on slow rendering of multiple views.

another question, is that included in for shown/hidden views or it depends on shown ones only as I got confused
and need to apply best practices.


问:
Python Web Scraping: Output to csv
I'm doing some progress with web scraping however I still need some help to perform some operations:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):
</code>```

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

答:
This is what I have done on my own:

```<code>import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

filename = url.rsplit('/', 1)[1] + '.csv'

tables = soup.select('.col-md-4 table')
rows = []

for tr in tables:
    t = tr.get_text(strip=True, separator='|').split('|')
    rows.append(t)
    df = pd.DataFrame(rows)
    print(df)
    df.to_csv(filename)
</code>```

Thanks,

Title: Python Web Scraping: Output to csv

Body:
I'm doing some progress with web scraping however I still need some help to perform some operations:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

# soup = BeautifulSoup(requests.get(converturl).content, 'html.parser')

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

out = []

for tr in soup.select('.col-md-4 tbody tr'):

On the class col-md-4 I know there are 3 tables I want to generate a csv which as an output has three values: first name, last name, and for the last value I want the header name of the table.

first name, last name, header table

Any help would be appreciated.

Body:
This is what I have done on my own:

import requests
import pandas as pd
from bs4 import BeautifulSoup

url = 'http://fcf.cat/equip/1920/1i/sant-ildefons-ue-b'

soup = BeautifulSoup(requests.get(url).content, 'html.parser')

filename = url.rsplit('/', 1)[1] + '.csv'

tables = soup.select('.col-md-4 table')
rows = []

for tr in tables:
    t = tr.get_text(strip=True, separator='|').split('|')
    rows.append(t)
    df = pd.DataFrame(rows)
    print(df)
    df.to_csv(filename)

Thanks,


问:
Using the spread operator on an array with objects
I got a Javascript object which looks like this:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}
</code>```

I also got an array to which I push items like this:

```<code>myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items
</code>```

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

```<code>{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}
</code>```

I tried doing it with the spread operator:

```<code>return {...object, ...myArr}
</code>```

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?

答:
```<code>const obj = {key1: 1};
const myArr = [{key2: 2}];
myArr.forEach(val => Object.assign(obj, val));

console.log(obj); // {key1: 1, key2: 2}
</code>```

Body:
I got a Javascript object which looks like this:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   }
}

I also got an array to which I push items like this:

myArr.push({[item.itemId] : anotherDefinedObject}); //inside a loop on items

I then want to join all the items I pushed to the array to the first object. Meaning that if for example the items ids were "key3" and "key4" I would get this object:

{
   key1: {
           itemId: "someId",
           myValue: "value"
   },
   key2: {
           itemId: "someId2",
           myValue: "value2"
   },
   key3: { //the object that was added },
   key4: { //the object that was added }
}

I tried doing it with the spread operator:

return {...object, ...myArr}

But then instead of getting what I needed, I get "0", "1" and such as the keys in the new object (since 0,1 etc are the keys of the arrays).

How do I concatenate the object and the array the way I want?


问:
Java Averaging Program
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:

 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).

I am totally new to Java and programming, this has me completely lost! Here's what I've tried.

import java.util.Scanner;

```<code>public class Average {

    public static void main(String[] args) {

    double numb1, numb2, numb3;
    System.out.println("Enter two numbers you'd like to be averaged.");
    Scanner keyboard = new Scanner(System.in);
    numb1 = keyboard.nextInt();
    numb2 = keyboard.nextInt();

    }

        public double average (int num1, int num2) {

            return (num1 + num2) / 2.0;
    }

        public double average (int num1, int num2, int num3)
        {
         return (num1 + num2 + num3) / 3.0;
        }
</code>```

}

The program doesn't go past getting the values from the user. Please help!

答:
```<code>public class Marks {
    int roll_no;
    int subject1;
    int subject2;
    int subject3;

    public int getRoll_no() {
        return roll_no;
    }

    public void setRoll_no(int roll_no) {
        this.roll_no = roll_no;
    }

    public int getSubject1() {
        return subject1;
    }

    public void setSubject1(int subject1) {
        this.subject1 = subject1;
    }

    public int getSubject2() {
        return subject2;
    }

    public void setSubject2(int subject2) {
        this.subject2 = subject2;
    }

    public int getSubject3() {
        return subject3;
    }

    public void setSubject3(int subject3) {
        this.subject3 = subject3;
    }
    public void getDetails(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the marks of subject1");
        this.subject1 = sc.nextInt();
        System.out.println("Enter the marks of subject2");
        this.subject2 = sc.nextInt();
        System.out.println("Enter the marks of subject3");
        this.subject3 = sc.nextInt();
        System.out.println("Enter the roll number");
        this.roll_no = sc.nextInt();
    }
    public int getAverage(){
        int avg = (getSubject1() + getSubject2() + getSubject3()) / 3;
        return avg;
    }
    public void printAverage(){
        System.out.println("The average is : " + getAverage());
    }
    public void printRollNum(){
        System.out.println("The roll number of the student is: " + getRoll_no());
    }
    public static void main(String[] args){
        Marks[] e1 = new Marks[8];
        for(int i=0; i<2; i++) {
            System.out.println("Enter the data of student with id:");
            e1[i] = new Marks();
            e1[i].getDetails();
            e1[i].printAverage();
        }
        System.out.println("Roll number details");
        for(int i=0; i<2; i++){
            e1[i].printRollNum();
        }
    }
}
</code>```

Title: Java Averaging Program

Body:
Write a class called Average that can be used to calculate average of several integers. It should contain the following methods:

 A method that accepts two integer parameters and returns their average.
 A method that accepts three integer parameters and returns their average.
 A method that accepts two integer parameters that represent a range. Issue an error message and return zero if the second parameter is less than the first one. Otherwise, the method should return the average of the integers in that range (inclusive).

I am totally new to Java and programming, this has me completely lost! Here's what I've tried.

import java.util.Scanner;

public class Average {

    public static void main(String[] args) {

    double numb1, numb2, numb3;
    System.out.println("Enter two numbers you'd like to be averaged.");
    Scanner keyboard = new Scanner(System.in);
    numb1 = keyboard.nextInt();
    numb2 = keyboard.nextInt();

    }

        public double average (int num1, int num2) {

            return (num1 + num2) / 2.0;
    }

        public double average (int num1, int num2, int num3)
        {
         return (num1 + num2 + num3) / 3.0;
        }

}

The program doesn't go past getting the values from the user. Please help!


问:
,what is the use and benefit of Serialize() function in php
I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.</p>

答:
That is easly explained by reading the official PHP page that states:

Generates a storable representation of a value
  This is useful for storing or passing PHP values around without losing their type and structure.

Basically you can serialize an object write the string in a file and on another request you can simply read the file and unserialize it to have the final object loaded.


问:
Linear Regression with one variable
While implementing Gradient Descent Algorithm in linear regression, the prediction that my algorithm is making and the resulting regression line are coming as a wrong output. Could anyone please have a look at my implementation and help me out? Also, please guide me that how can I know what value of "learning rate" and "number of iterations" to choose in specific regression problem?

```<code>theta0 = 0                               #first parameter
theta1 = 0                               #second parameter
alpha = 0.001                             #learning rate (denoted by alpha)
num_of_iterations = 100                #total number of iterations performed by Gradient Descent
m = float(len(X))                         #total number of training examples

for i in range(num_of_iterations):
    y_predicted = theta0 + theta1 * X
    derivative_theta0 = (1/m) * sum(y_predicted - Y)
    derivative_theta1 = (1/m) * sum(X * (y_predicted - Y))
    temp0 = theta0 - alpha * derivative_theta0
    temp1 = theta1 - alpha * derivative_theta1
    theta0 = temp0
    theta1 = temp1
print(theta0, theta1)

y_predicted = theta0 + theta1 * X
plt.scatter(X,Y)
plt.plot(X, y_predicted, color = 'red')
plt.show()
</code>```

Resulting regression line about which I need some help

答: Your learning rate is to high, I got it working by reducing the learning rate to alpha = 0.0001.</p>

Title: Linear Regression with one variable

Body:
While implementing Gradient Descent Algorithm in linear regression, the prediction that my algorithm is making and the resulting regression line are coming as a wrong output. Could anyone please have a look at my implementation and help me out? Also, please guide me that how can I know what value of "learning rate" and "number of iterations" to choose in specific regression problem?

theta0 = 0                               #first parameter
theta1 = 0                               #second parameter
alpha = 0.001                             #learning rate (denoted by alpha)
num_of_iterations = 100                #total number of iterations performed by Gradient Descent
m = float(len(X))                         #total number of training examples

for i in range(num_of_iterations):
    y_predicted = theta0 + theta1 * X
    derivative_theta0 = (1/m) * sum(y_predicted - Y)
    derivative_theta1 = (1/m) * sum(X * (y_predicted - Y))
    temp0 = theta0 - alpha * derivative_theta0
    temp1 = theta1 - alpha * derivative_theta1
    theta0 = temp0
    theta1 = temp1
print(theta0, theta1)

y_predicted = theta0 + theta1 * X
plt.scatter(X,Y)
plt.plot(X, y_predicted, color = 'red')
plt.show()

Resulting regression line about which I need some help


问:
Firebase: There is no user record corresponding to this identifier. The user may have been deleted
I am using Ionic2/Angular2 with AngularFire2 and Firebase to authenticate my users at login.

After I register a user via email & password successfully, I can login with that email & password successfully.

```<code>public fireAuth: firebase.auth.Auth;
...
    loginFirebaseUser(email: string, password: string): firebase.Promise<boolean> {
        return this.fireAuth.signInWithEmailAndPassword(email, password).then(() => {
            console.log('signInWithEmailAndPassword', email, password);
        }).catch((error)=> {
            console.error('Error signInWithEmailAndPassword', email, password, error.name, error.message);
            throw new Error(error.message);
        });
    }
</code>```

When I change the users email, it updates successfully (I can see the update in the admin console and there's no errors).

```<code>this.fireAuth.onAuthStateChanged((firebaseUser: firebase.User) => {
    firebaseUser.updateEmail(newEmail).then((data) => {...
</code>```

I then verify the new email successfully. However, when I try login in again with the new email and password, I get:

```<code>There is no user record corresponding to this identifier. The user may
 have been deleted.
</code>```

In summary, if I don't update the email address, everything works. If I do update the email address, I get the above error if I try log in.

答: This is happening because the email with you are login/sign-in with does not exist, either you have to register that email it with auth.createUserWithEmailAndPassword then login/sign-up or correct your email and password.

Body:
I am using Ionic2/Angular2 with AngularFire2 and Firebase to authenticate my users at login.

After I register a user via email & password successfully, I can login with that email & password successfully.

public fireAuth: firebase.auth.Auth;
...
    loginFirebaseUser(email: string, password: string): firebase.Promise<boolean> {
        return this.fireAuth.signInWithEmailAndPassword(email, password).then(() => {
            console.log('signInWithEmailAndPassword', email, password);
        }).catch((error)=> {
            console.error('Error signInWithEmailAndPassword', email, password, error.name, error.message);
            throw new Error(error.message);
        });
    }

When I change the users email, it updates successfully (I can see the update in the admin console and there's no errors).

this.fireAuth.onAuthStateChanged((firebaseUser: firebase.User) => {
    firebaseUser.updateEmail(newEmail).then((data) => {...

I then verify the new email successfully. However, when I try login in again with the new email and password, I get:

There is no user record corresponding to this identifier. The user may
 have been deleted.

In summary, if I don't update the email address, everything works. If I do update the email address, I get the above error if I try log in.


问:
Selecting two highest values from a list, whilst keeping a record of their index positions?
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

```<code>a = [1,2,7,9,3,4]
</code>```

Desired output:

```<code>maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2
</code>```

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

答:
Use sorted and list.index:

```<code>MaxVal, secondMax = sorted(a)[-2:]
index_max = a.index(MaxVal)
index_secondMax = a.index(secondMax)
</code>```

Body:
I am trying to get the highest and the second highest values from list a. I also need to keep track of what the index value was for each of these values.

For example:

a = [1,2,7,9,3,4]

Desired output:

maxVal = 9
secondMax = 7

index_max = 3
index_secondMax = 2

Does any one have any suggestions for how to approach this, can't seem to figure out a way of doing it.

Body:
Use sorted and list.index:

MaxVal, secondMax = sorted(a)[-2:]
index_max = a.index(MaxVal)
index_secondMax = a.index(secondMax)


问:
How can I get PHP to display the headers it received from a browser?
Are they all stored in $_SERVER? Even custom ones?

答:
What's happening is that http headers' names are rewritten:

Prefixed with HTTP_

Replaced '-' by '_'

Upper Cased

That's at least what I've observed for my custom headers and apache 2.4. This is not canonical nor a comprehensive list of what you should check, but it may lead you to the right direction as for me none of the above helped.


问:
Preg_match a string, must containing Letters and numbers
The sentence maybe:
BenQ G2420HDBL 23.6" Wide LCD Monitor

Need to grab the "G2420HDBL" part. The letters and numbers may be in a different order but still remains a string with both letters and numbers present.

答:
Now I understand what you actually need. This regex finds strings containing any numbers, letters and dashes. Only the string cannot start or end with a dash.</p>

```<code>$name = 'BenQ -1G2-420H-DBL- 23.6" Wide LCD Monitor';
$a = preg_match('/\b(([0-9A-Z]+[A-Z0-9]+)[-]*)+\b/i', $name, $m);

var_dump($m[0]);
</code>```

Body:
Now I understand what you actually need. This regex finds strings containing any numbers, letters and dashes. Only the string cannot start or end with a dash.

$name = 'BenQ -1G2-420H-DBL- 23.6" Wide LCD Monitor';
$a = preg_match('/\b(([0-9A-Z]+[A-Z0-9]+)[-]*)+\b/i', $name, $m);

var_dump($m[0]);


问:
Cover "Manhattan skyline" using the minimum number of rectangles
I write to solve a Codility problem provided below,

You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

```<code>class Solution { public int solution(int[] H); }
</code>```

that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

```<code>  H[0] = 8    H[1] = 8    H[2] = 5
  H[3] = 7    H[4] = 9    H[5] = 8
  H[6] = 7    H[7] = 4    H[8] = 8
</code>```

the function should return 7. The figure shows one possible arrangement of seven blocks.

Assume that:

N is an integer within the range [1..100,000];
each element of array H is an integer within the range [1..1,000,000,000].
Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I write a solution for the provided problem. The algorithm and code is provided below,

Algorithm

i.   set block count = 1 and start iterating from the 2nd element of the array

ii.  if the current depth is same as previous, keep going

iii. If the current depth is higher, push that in the stack and increase the count

iv.  If the current depth is lower, keep poping till the current depth >= peek. Afterward, if the stack size = 0 or higher, increase the block count by 1

The code,

```<code>public static int solution(int[] H) {

    Stack<Integer> stack = new Stack<>();

    stack.push(H[0]);
    int count = 1;

    int N = H.length;

    for (int i = 1; i < N; i++) {

        if (H[i] == stack.peek()) {
            continue;
        } else if (H[i] > stack.peek()) {
            stack.push(H[i]);
            count++;
        } else {

            while (!stack.isEmpty() && H[i] < stack.peek()) {
                stack.pop();
            }

            stack.push(H[i]);
            count++;
        }
    }

    return count;
}
</code>```

The solution doesn't provide the correct answer and I can't find the bug even after spending some time in debugging. Can anyone see that?

The test set is provided below and the answer is 7 (I get 8).

```<code>    int[] H = new int[9];

    H[0] = 8;
    H[1] = 8;
    H[2] = 5;
    H[3] = 7;
    H[4] = 9;
    H[5] = 8;
    H[6] = 7;
    H[7] = 4;
    H[8] = 8;
</code>```

Thank you.

答:
Another one in Java. Simpler, because I used assumption that height > 0.</p>

```<code>    public int solution(int[] hs) {
        int squares = 0;
        Stack<Integer> s = new Stack<>();
        s.push(0);

        for (int h: hs) {
            while (s.peek() > h) {
                s.pop();
            }
            if (s.peek() != h) {
                s.push(h);
                ++squares;
            }
        }

        return squares;
    }
</code>```

Body:
I write to solve a Codility problem provided below,

You are going to build a stone wall. The wall should be straight and N meters long, and its thickness should be constant; however, it should have different heights in different places. The height of the wall is specified by an array H of N positive integers. H[I] is the height of the wall from I to I+1 meters to the right of its left end. In particular, H[0] is the height of the wall's left end and H[N−1] is the height of the wall's right end.

The wall should be built of cuboid stone blocks (that is, all sides of such blocks are rectangular). Your task is to compute the minimum number of blocks needed to build the wall.

Write a function:

class Solution { public int solution(int[] H); }

that, given an array H of N positive integers specifying the height of the wall, returns the minimum number of blocks needed to build it.

For example, given array H containing N = 9 integers:

  H[0] = 8    H[1] = 8    H[2] = 5
  H[3] = 7    H[4] = 9    H[5] = 8
  H[6] = 7    H[7] = 4    H[8] = 8

the function should return 7. The figure shows one possible arrangement of seven blocks.

Assume that:

N is an integer within the range [1..100,000];
each element of array H is an integer within the range [1..1,000,000,000].
Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(N) (not counting the storage required for input arguments).

I write a solution for the provided problem. The algorithm and code is provided below,

Algorithm

i.   set block count = 1 and start iterating from the 2nd element of the array

ii.  if the current depth is same as previous, keep going

iii. If the current depth is higher, push that in the stack and increase the count

iv.  If the current depth is lower, keep poping till the current depth >= peek. Afterward, if the stack size = 0 or higher, increase the block count by 1

The code,

public static int solution(int[] H) {

    Stack<Integer> stack = new Stack<>();

    stack.push(H[0]);
    int count = 1;

    int N = H.length;

    for (int i = 1; i < N; i++) {

        if (H[i] == stack.peek()) {
            continue;
        } else if (H[i] > stack.peek()) {
            stack.push(H[i]);
            count++;
        } else {

            while (!stack.isEmpty() && H[i] < stack.peek()) {
                stack.pop();
            }

            stack.push(H[i]);
            count++;
        }
    }

    return count;
}

The solution doesn't provide the correct answer and I can't find the bug even after spending some time in debugging. Can anyone see that?

The test set is provided below and the answer is 7 (I get 8).

    int[] H = new int[9];

    H[0] = 8;
    H[1] = 8;
    H[2] = 5;
    H[3] = 7;
    H[4] = 9;
    H[5] = 8;
    H[6] = 7;
    H[7] = 4;
    H[8] = 8;

Thank you.

Body:
Another one in Java. Simpler, because I used assumption that height > 0.

    public int solution(int[] hs) {
        int squares = 0;
        Stack<Integer> s = new Stack<>();
        s.push(0);

        for (int h: hs) {
            while (s.peek() > h) {
                s.pop();
            }
            if (s.peek() != h) {
                s.push(h);
                ++squares;
            }
        }

        return squares;
    }


问:
OnEditorActionListener not working even with maxLines=1 and imeOptions set on GO or DONE
i tried for hours to intercept the "enter" button on the keyboard but it just doesn't work. I know there are a lot of questions similar to mine but none of those answers solved my problem.

Here is my Edit Text xml:

```<code><EditText
        android:id="@+id/et_toolbar_search"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:background="@null"
        android:gravity="center_vertical"
        android:hint="Search..."
        android:imeOptions="actionDone"
        android:inputType="text"
        android:textSize="@dimen/font_size_15"
        android:maxLines="1"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="@+id/view_toolbar_search_background"
        app:layout_constraintEnd_toStartOf="@+id/img_toolbar_cancel_search"
        app:layout_constraintStart_toEndOf="@id/img_toolbar_search"
        app:layout_constraintTop_toTopOf="@+id/view_toolbar_search_background" />
</code>```

then, after i bind the view using Butterknife i set the listener in the OnCreate method of the activity
 like this:

```<code>etSearch.setOnEditorActionListener((v, actionId, event) -> {

   /*if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                || (actionId == EditorInfo.IME_ACTION_DONE)) {*/

        Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();

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

I have another app where i've done this some months ago and there it works flawlessly(xml is literally copied from there) so my phone keyboard/Android version shouldn't be a problem.
I know singleLine is deprecated, but someone suggested to add it - doesn't work with or without it.
I've already tried switiching imeOption to every other action, still won't work.
I commented the IF because i thought maybe it was wrong, but the listener is literally never triggered.

Any help is greatly appreaciated.

答: So after hours & hours i finally solved it. The problem was that inside the activity i had a fragment that also overrode the EditorListener so i guess it also overrode the one in the activity. Anyway, deleteing the listener in the fragment solved my problem</p>

Body:
i tried for hours to intercept the "enter" button on the keyboard but it just doesn't work. I know there are a lot of questions similar to mine but none of those answers solved my problem.

Here is my Edit Text xml:

<EditText
        android:id="@+id/et_toolbar_search"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="10dp"
        android:layout_marginEnd="10dp"
        android:background="@null"
        android:gravity="center_vertical"
        android:hint="Search..."
        android:imeOptions="actionDone"
        android:inputType="text"
        android:textSize="@dimen/font_size_15"
        android:maxLines="1"
        android:singleLine="true"
        app:layout_constraintBottom_toBottomOf="@+id/view_toolbar_search_background"
        app:layout_constraintEnd_toStartOf="@+id/img_toolbar_cancel_search"
        app:layout_constraintStart_toEndOf="@id/img_toolbar_search"
        app:layout_constraintTop_toTopOf="@+id/view_toolbar_search_background" />

then, after i bind the view using Butterknife i set the listener in the OnCreate method of the activity
 like this:

etSearch.setOnEditorActionListener((v, actionId, event) -> {

   /*if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                || (actionId == EditorInfo.IME_ACTION_DONE)) {*/

        Toast.makeText(this, "Clicked", Toast.LENGTH_SHORT).show();

        return false;
    });

I have another app where i've done this some months ago and there it works flawlessly(xml is literally copied from there) so my phone keyboard/Android version shouldn't be a problem.
I know singleLine is deprecated, but someone suggested to add it - doesn't work with or without it.
I've already tried switiching imeOption to every other action, still won't work.
I commented the IF because i thought maybe it was wrong, but the listener is literally never triggered.

Any help is greatly appreaciated.


问:
How to read the first row of a Dataframe as data row and not header
I'm trying to read the data out of pdf using Tabula-Py but facing a small issue:

The library reads the data like this:

```<code>  F 01/02/1994 01/12/1994 ac $123
0 M 01/03/1994 01/10/1992 ad $133
1 M 01/04/1994 01/09/1992 ae $133
2 M 01/05/1994 01/08/1992 aa $133
</code>```

When I give them column names: The issue is that the first row is automatically being treated as Header and not the data while being Read by Tabula-PDF, so the output becomes:

```<code>  Gender  D.O.B       D.O.P      Plan  Price
0 M      01/03/1994  01/10/1992  ad    $133
1 M      01/04/1994  01/09/1992  ae    $133
2 M      01/05/1994  01/08/1992  aa    $133
</code>```

which is incorrect. It drops the first row

The correct Output required is Below:

```<code> Gender D.O.B       D.O.P      Plan Price
0 F     01/02/1994  01/12/1994 cc   $123
1 M     01/03/1994  01/10/1992 aa   $133
2 M     01/04/1994  01/09/1992 aa   $133
3 M     01/05/1994  01/08/1992 aa   $133
</code>```

The code that i'm using is :

```<code>def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    for i in range (0,len(df)):
        print(len(df[i]))
        dfnew.append(df[i])

    e = pd.DataFrame(dfnew[i],index=None)
    print(e)
    f = pd.DataFrame(e,columns=head)
    g = pd.DataFrame(data = e.values,columns=f.columns)
    print(g)
</code>```

Is there a way so that i don't lose the first row well?

答:
You can transpose the dataframe and reset_index so that the header becomes a normal column. Then you can transpose back:

```<code>def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    df = df.T.reset_index().T.reset_index(drop=True)

    df.columns = head

    return df
</code>```

Body:
I'm trying to read the data out of pdf using Tabula-Py but facing a small issue:

The library reads the data like this:

  F 01/02/1994 01/12/1994 ac $123
0 M 01/03/1994 01/10/1992 ad $133
1 M 01/04/1994 01/09/1992 ae $133
2 M 01/05/1994 01/08/1992 aa $133

When I give them column names: The issue is that the first row is automatically being treated as Header and not the data while being Read by Tabula-PDF, so the output becomes:

  Gender  D.O.B       D.O.P      Plan  Price
0 M      01/03/1994  01/10/1992  ad    $133
1 M      01/04/1994  01/09/1992  ae    $133
2 M      01/05/1994  01/08/1992  aa    $133

which is incorrect. It drops the first row

The correct Output required is Below:

 Gender D.O.B       D.O.P      Plan Price
0 F     01/02/1994  01/12/1994 cc   $123
1 M     01/03/1994  01/10/1992 aa   $133
2 M     01/04/1994  01/09/1992 aa   $133
3 M     01/05/1994  01/08/1992 aa   $133

The code that i'm using is :

def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    for i in range (0,len(df)):
        print(len(df[i]))
        dfnew.append(df[i])

    e = pd.DataFrame(dfnew[i],index=None)
    print(e)
    f = pd.DataFrame(e,columns=head)
    g = pd.DataFrame(data = e.values,columns=f.columns)
    print(g)

Is there a way so that i don't lose the first row well?

Body:
You can transpose the dataframe and reset_index so that the header becomes a normal column. Then you can transpose back:

def table_type_2(path):
    df = read_pdf(path,guess = True, multiple_tables=True)
    head = ['Gender', 'Date of Birth', 'Date of', 'Coverage', 'Gross Benefit']

    df = df.T.reset_index().T.reset_index(drop=True)

    df.columns = head

    return df


问:
Is there any way to kill a Thread?
Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p>

答:
As mentioned in @Kozyarchuk's answer, installing trace works. Since this answer contained no code, here is a working ready-to-use example:

```<code>import sys, threading, time

class TraceThread(threading.Thread):
    def __init__(self, *args, **keywords):
        threading.Thread.__init__(self, *args, **keywords)
        self.killed = False
    def start(self):
        self._run = self.run
        self.run = self.settrace_and_run
        threading.Thread.start(self)
    def settrace_and_run(self):
        sys.settrace(self.globaltrace)
        self._run()
    def globaltrace(self, frame, event, arg):
        return self.localtrace if event == 'call' else None
    def localtrace(self, frame, event, arg):
        if self.killed and event == 'line':
            raise SystemExit()
        return self.localtrace

def f():
    while True:
        print('1')
        time.sleep(2)
        print('2')
        time.sleep(2)
        print('3')
        time.sleep(2)

t = TraceThread(target=f)
t.start()
time.sleep(2.5)
t.killed = True
</code>```

It stops after having printed 1 and 2. 3 is not printed.

OwnerDisplayName: Sudden Def

Title: Is there any way to kill a Thread?

Body:
As mentioned in @Kozyarchuk's answer, installing trace works. Since this answer contained no code, here is a working ready-to-use example:

import sys, threading, time

class TraceThread(threading.Thread):
    def __init__(self, *args, **keywords):
        threading.Thread.__init__(self, *args, **keywords)
        self.killed = False
    def start(self):
        self._run = self.run
        self.run = self.settrace_and_run
        threading.Thread.start(self)
    def settrace_and_run(self):
        sys.settrace(self.globaltrace)
        self._run()
    def globaltrace(self, frame, event, arg):
        return self.localtrace if event == 'call' else None
    def localtrace(self, frame, event, arg):
        if self.killed and event == 'line':
            raise SystemExit()
        return self.localtrace

def f():
    while True:
        print('1')
        time.sleep(2)
        print('2')
        time.sleep(2)
        print('3')
        time.sleep(2)

t = TraceThread(target=f)
t.start()
time.sleep(2.5)
t.killed = True

It stops after having printed 1 and 2. 3 is not printed.


问:
Discord.py channel.edit doesn't do anything, and bot doesn't go past that line
So basically, I have a channel which name is the member count of my server. Now, whenever someone joins or leaves it will update the name to "Member count: guild.member_count". On_member_join is working fine, but on_member_remove calls when someone joins but it never finishes, even though the code for join and remove is basically the same

```<code>@client.event
async def on_member_remove(member):
    print('on_member_remove called')
    count_channel = client.get_channel(ID)
    await count_channel.edit(name = 'Member count: {}'.format(count_channel.guild.member_count))
    print('on_member_remove finished')
</code>```

In this one, on_member_remove finished never prints, and it all works perfectly when on_member_join
Code for on_member_join:

```<code>@client.event
async def on_member_join(member):
    print('on_member_joim called')
    count_channel = client.get_channel(ID)
    await count_channel.edit(name = 'Member count: {}'.format(count_channel.guild.member_count))
    print('on_member_join finished')
</code>```

答:
Channels have recently been rate-limited. This has been announced in the official Discord development servers. You're not doing anything wrong.

Here's the announcement:

Body:
So basically, I have a channel which name is the member count of my server. Now, whenever someone joins or leaves it will update the name to "Member count: guild.member_count". On_member_join is working fine, but on_member_remove calls when someone joins but it never finishes, even though the code for join and remove is basically the same

@client.event
async def on_member_remove(member):
    print('on_member_remove called')
    count_channel = client.get_channel(ID)
    await count_channel.edit(name = 'Member count: {}'.format(count_channel.guild.member_count))
    print('on_member_remove finished')

In this one, on_member_remove finished never prints, and it all works perfectly when on_member_join
Code for on_member_join:

@client.event
async def on_member_join(member):
    print('on_member_joim called')
    count_channel = client.get_channel(ID)
    await count_channel.edit(name = 'Member count: {}'.format(count_channel.guild.member_count))
    print('on_member_join finished')


答:
If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:</p>

```<code>if(file_exists($thefile)) {
    $data = unserialize(readfile($thefile));
} else {
    $data = array(); // or anything
}

// do something with data

$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)
</code>```

Title: ,what is the use and benefit of Serialize() function in php

Body: I know its Generates a storable representation of a value and  used to access the objects across the php files but what if i dont use this function while storing the objects.

Body:
If you want to communicate a PHP variable (array, class, string, etc) to another script/a database/write it in a file, you serialize it. Suppose you have a little script that you want to run multiple times, and you need a place to keep some data between script runs. Here is a sketch of what you do:

if(file_exists($thefile)) {
    $data = unserialize(readfile($thefile));
} else {
    $data = array(); // or anything
}

// do something with data

$f = fopen($thefile);
fwrite($f, serialize($data));
fclose($f)


问:
How to achieve this when I hover an flex item?
I have searched all over stack overflow but I am unable to find any clue and I am struck here. I used flex container and child items in my code to some extent but I couldn't move beyond that. Thing is when we hover a child item, a new child item need to be created as shown in the expected result. Should we need to use pseudo element or any other flex properties to achieve this. Thanks much in advance.

My code:

https://jsfiddle.net/k2qr398u/1/

My result

https://imgur.com/kRHNHuu

Expected result:

https://imgur.com/2B6CkYF

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  /* position: relative; */
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--**HTML**-->

<body>

  <div class="container">
    <div class="col col-1">
      <img src="images/css.svg" alt="CSS logo" class="img-css">
      <br>
      <p>I am</p>
    </div>

    <div class="col col-2">

      <p class="my-name">Sri</p>

    </div>

    <div class="col col-3">
      <img src="images/javascript.svg" alt="JS logo" class="img-js">
      <p>Developer
      </p>
    </div>

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

P.S: Sorry if this question sounds very silly or dumb, I am a beginner trying to learn web dev skillsets.

答:
I have created something similar to your expected result. Please run the code snippet for the result.

UPDATE: To include the hover off transition.

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  position: relative;
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

/*
.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}
*/

.col-1,
.col-2-1,
.col-2-2,
.col-3 {
  position: absolute;
  left: 0;
  top: 0;
  transition: 1s;
}

.wrapper {
  position: relative;
}

.wrapper:hover .col-1 {
  transition: 1s;
  left: -200px;
}

.wrapper:hover .col-2-1 {
  transition: 1s;
  top: -170px;
}

.wrapper:hover .col-2-2 {
  transition: 1s;
  top: 170px;
}

.wrapper:hover .col-3 {
  transition: 1s;
  left: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--**HTML**-->

<body>

  <div class="container">
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-1">
        <img src="images/css.svg" alt="CSS logo" class="img-css">
        <br>
        <p>I am</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-2-1">
        <p class="my-name">Sri</p>
      </div>
      <div class="col col-2-2">
        <p class="my-name">Pratham</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-3">
        <img src="images/javascript.svg" alt="JS logo" class="img-js">
        <p>Developer
        </p>
      </div>
    </div>

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

Body:
I have searched all over stack overflow but I am unable to find any clue and I am struck here. I used flex container and child items in my code to some extent but I couldn't move beyond that. Thing is when we hover a child item, a new child item need to be created as shown in the expected result. Should we need to use pseudo element or any other flex properties to achieve this. Thanks much in advance.

My code:

https://jsfiddle.net/k2qr398u/1/

My result

https://imgur.com/kRHNHuu

Expected result:

https://imgur.com/2B6CkYF

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  /* position: relative; */
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}

I am

Sri

Developer

P.S: Sorry if this question sounds very silly or dumb, I am a beginner trying to learn web dev skillsets.

Body:
I have created something similar to your expected result. Please run the code snippet for the result.

UPDATE: To include the hover off transition.

/**CSS**/

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: sans-serif;
  background-color: #400017;
}

.img-css {
  width: 50px;
  height: 50px;
}

.main-heading {
  display: block;
  text-align: center;
  color: #fc065d;
  margin-bottom: 70px;
}

.img-js {
  width: 50px;
  height: 50px;
}

.container {
  display: flex;
  justify-content: space-around;
  align-items: center;
  flex-wrap: wrap;
  border: 3px solid #360310;
  max-width: 610px;
  height: 310px;
  text-align: center;
  margin: 0 auto;
  flex-direction: row;
  /* transform: translate(-50%,-50%); */
}

.col {
  width: 130px;
  height: 100px;
  margin: 0 auto;
  border: 3px solid #5e0a1f;
  padding-top: 44px;
  padding-left: 26px;
  padding-right: 26px;
  color: #fff;
  background-color: #010001;
  border-radius: 30px;
  z-index: 20;
  position: relative;
}

.col p {
  font-size: 16px;
  font-weight: bold;
}

/*
.col-2 p {
  position: relative;
  top: 55px;
  text-align: center;
  font-weight: bold;
}
*/

.col-1,
.col-2-1,
.col-2-2,
.col-3 {
  position: absolute;
  left: 0;
  top: 0;
  transition: 1s;
}

.wrapper {
  position: relative;
}

.wrapper:hover .col-1 {
  transition: 1s;
  left: -200px;
}

.wrapper:hover .col-2-1 {
  transition: 1s;
  top: -170px;
}

.wrapper:hover .col-2-2 {
  transition: 1s;
  top: 170px;
}

.wrapper:hover .col-3 {
  transition: 1s;
  left: 200px;
}

<!--**HTML**-->

<body>

  <div class="container">
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-1">
        <img src="images/css.svg" alt="CSS logo" class="img-css">
        <br>
        <p>I am</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-2-1">
        <p class="my-name">Sri</p>
      </div>
      <div class="col col-2-2">
        <p class="my-name">Pratham</p>
      </div>
    </div>
    <div class="wrapper">
      <div class="col"> Underneath</div>
      <div class="col col-3">
        <img src="images/javascript.svg" alt="JS logo" class="img-js">
        <p>Developer
        </p>
      </div>
    </div>

  </div>
</body>


答:
```<code>import numpy as np
a = [1,2,7,9,3,4]
max_value = np.sort(a)[-1]
max_value2 = np.sort(a)[-2]
int(np.squeeze(np.where(a == max_value))),int(np.squeeze(np.where(a == max_value2)))
</code>```

Title: Selecting two highest values from a list, whilst keeping a record of their index positions?