答:
So i made it work but not with rolling windows as it doesn't support string type. the feature is reported and requested on Pandas Repo as well.

My solution snippet to the problem:

```<code>    if len(df.index) > 0:
        res = df.loc[(df.merchant == data['transaction']['merchant']) & (df.amount == data['transaction']['amount'])]
        res['timediff'] = (data['transaction']['time'] - res['time']).dt.total_seconds().abs() <= 120
        if res.timediff.any():
            continue
    df = df.append(df1)
print(df)
</code>```

Sample data:

```<code>{"transaction": {"merchant": "merchantA", "amount": 20, "time": "2019-02-13T10:00:00.000Z"}}
{"transaction": {"merchant": "merchantB", "amount": 90, "time": "2019-02-13T11:00:01.000Z"}}
{"transaction": {"merchant": "merchantC", "amount": 10, "time": "2019-02-13T11:00:10.000Z"}}
{"transaction": {"merchant": "merchantD", "amount": 10, "time": "2019-02-13T11:00:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:01:30.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:03:00.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:02:00.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:02:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:02:30.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:05:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:00:30.000Z"}}
</code>```

Output:

```<code>                      merchant  amount                time
2019-02-13 10:00:00  merchantA      20 2019-02-13 10:00:00
2019-02-13 11:00:01  merchantB      90 2019-02-13 11:00:01
2019-02-13 11:00:10  merchantC      10 2019-02-13 11:00:10
2019-02-13 11:00:20  merchantD      10 2019-02-13 11:00:20
2019-02-13 11:01:30  merchantE      10 2019-02-13 11:01:30
2019-02-13 11:03:00  merchantF      10 2019-02-13 11:03:00
2019-02-13 11:05:20  merchantF      10 2019-02-13 11:05:20
</code>```

Title: How to find duplicate based upon multiple columns in a rolling window in pandas?

Body:
Sample Data

{"transaction": {"merchant": "merchantA", "amount": 20, "time": "2019-02-13T10:00:00.000Z"}}
{"transaction": {"merchant": "merchantB", "amount": 90, "time": "2019-02-13T11:00:01.000Z"}}
{"transaction": {"merchant": "merchantC", "amount": 90, "time": "2019-02-13T11:00:10.000Z"}}
{"transaction": {"merchant": "merchantD", "amount": 90, "time": "2019-02-13T11:00:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 90, "time": "2019-02-13T11:01:30.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 90, "time": "2019-02-13T11:02:30.000Z"}}
.
.

I have some code like this

    df = pd.DataFrame()
for line in sys.stdin:
    data = json.loads(line)
    # df1 = pd.DataFrame(data["transaction"], index=[len(df.index)])
    df1 = pd.DataFrame(data["transaction"], index=[data['transaction']['time']])
    df1['time'] = pd.to_datetime(df1['time'])
    df = df.append(df1)
    # df['count'] = df.rolling('2min', on='time', min_periods=1)['amount'].count()

print(df)
print(len(df[df.merchant.eq(data['transaction']['merchant']) & df.amount.eq(data['transaction']['amount'])].index))

Current output

2019-02-13T10:00:00.000Z  merchantA      20 2019-02-13 10:00:00
2019-02-13T11:00:01.000Z  merchantB      90 2019-02-13 11:00:01
2019-02-13T11:00:10.000Z  merchantC      90 2019-02-13 11:00:10
2019-02-13T11:00:20.000Z  merchantD      90 2019-02-13 11:00:20
2019-02-13T11:01:30.000Z  merchantE      90 2019-02-13 11:01:30
2019-02-13T11:02:30.000Z  merchantE      90 2019-02-13 11:02:30

2

Expected output

2019-02-13T10:00:00.000Z  merchantA      20 2019-02-13 10:00:00
2019-02-13T11:00:01.000Z  merchantB      90 2019-02-13 11:00:01
2019-02-13T11:00:10.000Z  merchantC      90 2019-02-13 11:00:10
2019-02-13T11:00:20.000Z  merchantD      90 2019-02-13 11:00:20
2019-02-13T11:01:30.000Z  merchantE      90 2019-02-13 11:01:30

As the data is streaming. I want to check if a duplicate record(whose merchant and amount value are same) arrives withing two minutes so I discard it as and do no processing on it. print it as a duplicate.

Do I have to do something with index zipping or groupby? but then how to equate of multiple columns.
Or some rolling condition on two columns but can't find anything how to do it.

What am I missing here?

Thanks

EDIT

#dup = df[df.duplicated(subset=['merchant', 'amount'], keep=False)]
     res = df.loc[(df.merchant == data['transaction']['merchant']) & (df.amount == data['transaction']['amount'])]
        # res['timediff'] = pd.to_timedelta((data['transaction']['time'] - res['time']), unit='T')
        res['timediff'] = (data['transaction']['time'] - res['time'])
        if len(res.index) >1:
           print(res)

so im trying something like this and if the result is less than 120 seconds i can process it.
But the resulting df in currently in the form of

                      merchant  amount                time       concat          timediff
2019-02-13 11:03:00  merchantF      10 2019-02-13 11:03:00  merchantF10 -1 days +23:59:20
2019-02-13 11:02:20  merchantF      10 2019-02-13 11:02:20  merchantF10          00:00:00

2019-02-13 11:01:30  merchantE      10 2019-02-13 11:01:30  merchantE10 00:01:00
2019-02-13 11:02:00  merchantE      10 2019-02-13 11:02:00  merchantE10 00:00:30
2019-02-13 11:02:30  merchantE      10 2019-02-13 11:02:30  merchantE10 00:00:00

-1 days +23:59:20 this format I think can be delt with taking Absolute value?

how can I convert the time in a format that I can compare it with 120 seconds? pd.to_deltatime() didn't work for me or maybe I'm using it wrong.

Body:
So i made it work but not with rolling windows as it doesn't support string type. the feature is reported and requested on Pandas Repo as well.

My solution snippet to the problem:

    if len(df.index) > 0:
        res = df.loc[(df.merchant == data['transaction']['merchant']) & (df.amount == data['transaction']['amount'])]
        res['timediff'] = (data['transaction']['time'] - res['time']).dt.total_seconds().abs() <= 120
        if res.timediff.any():
            continue
    df = df.append(df1)
print(df)

Sample data:

{"transaction": {"merchant": "merchantA", "amount": 20, "time": "2019-02-13T10:00:00.000Z"}}
{"transaction": {"merchant": "merchantB", "amount": 90, "time": "2019-02-13T11:00:01.000Z"}}
{"transaction": {"merchant": "merchantC", "amount": 10, "time": "2019-02-13T11:00:10.000Z"}}
{"transaction": {"merchant": "merchantD", "amount": 10, "time": "2019-02-13T11:00:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:01:30.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:03:00.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:02:00.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:02:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:02:30.000Z"}}
{"transaction": {"merchant": "merchantF", "amount": 10, "time": "2019-02-13T11:05:20.000Z"}}
{"transaction": {"merchant": "merchantE", "amount": 10, "time": "2019-02-13T11:00:30.000Z"}}

Output:

                      merchant  amount                time
2019-02-13 10:00:00  merchantA      20 2019-02-13 10:00:00
2019-02-13 11:00:01  merchantB      90 2019-02-13 11:00:01
2019-02-13 11:00:10  merchantC      10 2019-02-13 11:00:10
2019-02-13 11:00:20  merchantD      10 2019-02-13 11:00:20
2019-02-13 11:01:30  merchantE      10 2019-02-13 11:01:30
2019-02-13 11:03:00  merchantF      10 2019-02-13 11:03:00
2019-02-13 11:05:20  merchantF      10 2019-02-13 11:05:20


来源: stackexchange

问:
Remove comma only from number separators (regular expression grouping)
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

```<code>Hello, world! -> Hello, world!
</code>```

but

```<code>Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337
</code>```

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

答:
Using regex and vanilla python this might help:

```<code>import re

def convert_commas(old):

    new = []
    pattern = re.compile(r"\d+,\d+")
    for word in old.split():
        if re.findall(pattern, word):
            word = word.replace(',','')
        new.append(word)

    new = (" ").join(new)
    return new

print(convert_commas(old))
</code>```

Can then use this function as a callback with map on the column to convert the commas for example

ContentLicense: CC BY-SA 4.0

Body:
I have a column of alpha-numeric string in pandas dataframe.
The goal is to only remove comma from number separators. For example:

Hello, world! -> Hello, world!

but

Warhammer 40,000 -> Warhammer 40000
Codename 1,337 -> Codename 1337

I can deduce that only when both sides are numerics '[0-9]+,[0-9]+' do I want to remove the comma. However, I can't seem to figure out a way to keep the same digits. Could someone help? If related, the size of the dataframe is a few hundred thousand rows and an average string is about 100 words.

p.s. this is my first post. I tried searching for related issue but found none. English is not my mother-tougue, chances are, I might have missed the keyword for this issue. Please do link me to the right place should this happens. Many thanks and much appreciated :)

Update: added the keyword 'grouping' as reminder for myself.

Body:
Using regex and vanilla python this might help:

import re

def convert_commas(old):

    new = []
    pattern = re.compile(r"\d+,\d+")
    for word in old.split():
        if re.findall(pattern, word):
            word = word.replace(',','')
        new.append(word)

    new = (" ").join(new)
    return new

print(convert_commas(old))

Can then use this function as a callback with map on the column to convert the commas for example


问:
Google App Engine - socket.io throws errors before successfully connect
Ok so... For a while web sockets have been implemented in the GAE flex environment.
I've got an app deployed there and everything works "sorta" fine except that sometimes

When Connecting or

After a random disconnect and it tries to reconnect

I get a couple of these errors:

```<code>POST https://XXX.appspot.com/socket.io/?EIO=3&transport=polling&t=N00Ml-1&sid=XuKv8-6R2TZrIERGAAAO 400

WebSocket connection to 'wss://XXX.appspot.com/socket.io/?EIO=3&transport=websocket&sid=XuKv8-6R2TZrIERGAAAO' failed: WebSocket is closed before the connection is established

GET https://XXX.appspot.com/socket.io/?EIO=3&transport=polling&t=N00Ml-2&sid=XuKv8-6R2TZrIERGAAAO 400
</code>```

I've googled a lot and tried a lot of the stuff suggested to people that had similar issues (most of them BEFORE GAE introduced websocket support).

After a couple of these errors it just connects and everything is fine... I've tried forcing transport as websocket on the client side but it doesn't seem to change anything.

Is there any fix? Should i just change cloud provider?

Not posting any code since it's the basic socket.io nodejs implementation, in fact I've tested with an empty basic implementation and it's the same thing, my best guess is they havn't implemented the load balancer correctly? Anybody has these issues? Should i go aws instead?

答:
I managed to fix this... I've posted on the socket.io github issues

https://github.com/socketio/socket.io/issues/3543

And here's a link to a better explanation
https://github.com/socketio/socket.io/issues/3612#issuecomment-656667871

Body:
Ok so... For a while web sockets have been implemented in the GAE flex environment.
I've got an app deployed there and everything works "sorta" fine except that sometimes

When Connecting or

After a random disconnect and it tries to reconnect

I get a couple of these errors:

POST https://XXX.appspot.com/socket.io/?EIO=3&transport=polling&t=N00Ml-1&sid=XuKv8-6R2TZrIERGAAAO 400

WebSocket connection to 'wss://XXX.appspot.com/socket.io/?EIO=3&transport=websocket&sid=XuKv8-6R2TZrIERGAAAO' failed: WebSocket is closed before the connection is established

GET https://XXX.appspot.com/socket.io/?EIO=3&transport=polling&t=N00Ml-2&sid=XuKv8-6R2TZrIERGAAAO 400

I've googled a lot and tried a lot of the stuff suggested to people that had similar issues (most of them BEFORE GAE introduced websocket support).

After a couple of these errors it just connects and everything is fine... I've tried forcing transport as websocket on the client side but it doesn't seem to change anything.

Is there any fix? Should i just change cloud provider?

Not posting any code since it's the basic socket.io nodejs implementation, in fact I've tested with an empty basic implementation and it's the same thing, my best guess is they havn't implemented the load balancer correctly? Anybody has these issues? Should i go aws instead?


问:
guide to mingw make files mingw32-make
I'm a C++ programmer and have experience with GCC on Linux. I want to develop an application in Windows , so i need a full guide to mingw make files, variables and mingw32-make. Is there anybody who can introduce a resource for this?</p>

答:
The main difference I came across is that mingw32-make will use windows PATH. So if you try to run it from git bash it won't behave quite like you expect it to (namely, it will invoke bat scripts when you don't expect it to, and shims also don't quite work).

Setting SHELL := /bin/bash or anything similar won't have any effect (which you can debug by running make -d), but you can still make it use bash instead of sh by setting SHELL := bash.exe. That's doesn't solve the windows PATH problem though.

What I did notice however is that if I additionally set .SHELLFLAGS := -euo pipefail -c then it suddenly behaves properly in git bash, as if it starts using Unix-like paths (would be great if someone could confirm / explain why exactly).

So I ended up with the following in my Makefile:

ifeq ($(OS),Windows_NT)
    SHELL := bash.exe
else
    SHELL := /usr/bin/env bash
endif
.SHELLFLAGS := -eo pipefail -c
```

With that setup it appears to behave normally in git bash, just like on Linux.

ContentLicense: CC BY-SA 3.0

Title: guide to mingw make files mingw32-make

Body:
The main difference I came across is that mingw32-make will use windows PATH. So if you try to run it from git bash it won't behave quite like you expect it to (namely, it will invoke bat scripts when you don't expect it to, and shims also don't quite work).

Setting SHELL := /bin/bash or anything similar won't have any effect (which you can debug by running make -d), but you can still make it use bash instead of sh by setting SHELL := bash.exe. That's doesn't solve the windows PATH problem though.

What I did notice however is that if I additionally set .SHELLFLAGS := -euo pipefail -c then it suddenly behaves properly in git bash, as if it starts using Unix-like paths (would be great if someone could confirm / explain why exactly).

So I ended up with the following in my Makefile:

ifeq ($(OS),Windows_NT)
    SHELL := bash.exe
else
    SHELL := /usr/bin/env bash
endif
.SHELLFLAGS := -eo pipefail -c

With that setup it appears to behave normally in git bash, just like on Linux.


问:
How to get SUM of f3 but Grouped by f2
I want to get all comments count grouped by category. eg

```<code>f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43
</code>```

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

答:
Okay I thought it all over.. and basically if i do understand correct you want the sum for each distinct set.

So not 34 + 34 + 34 + 23 + 23 + 23 + 43 + 43 + 43 ... BUT 34 + 23 + 43

In order to that you need to trick MySQL with the following query :

```<code>SELECT
SUM(tot.invalid_votes) AS total
FROM (SELECT DISTINCT QV, invalid_votes FROM `results`) tot
</code>```

This will return the SUM of the Distinct values based on QV field.

Table :

```<code>QV  invalid_votes
0544    5
0544    5
0544    5
0545    6
0545    6
</code>```

based on the database information you provided i get the following result 11

Title: How to get SUM of f3 but Grouped by f2

Body:
I want to get all comments count grouped by category. eg

f1      f2      f3
php     hello   34
php     hello   34
php     hello   34
php     world   23
php     world   23
php     world   23
asp     world1   43
asp     world1  43
asp     world1   43

How to get sum of f3 but grouped by f2?

So not 34 + 34 + 34 +23 ... but 34 + 23 + 43

EDIT: f2 is unique

Body:
Okay I thought it all over.. and basically if i do understand correct you want the sum for each distinct set.

So not 34 + 34 + 34 + 23 + 23 + 23 + 43 + 43 + 43 ... BUT 34 + 23 + 43

In order to that you need to trick MySQL with the following query :

SELECT
SUM(tot.invalid_votes) AS total
FROM (SELECT DISTINCT QV, invalid_votes FROM `results`) tot

This will return the SUM of the Distinct values based on QV field.

Table :

QV  invalid_votes
0544    5
0544    5
0544    5
0545    6
0545    6

based on the database information you provided i get the following result 11


问:
document.execCommand('copy') not working, even though the DOM element is created
I am trying to copy text as an onClick event, but it doesn't seem to pick up the value. Here's what I have:

  const copyText = () => {
    const input = document.createElement("input");
    input.innerHTML = 'test text';
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    console.log("input", input);
  };

  copyText();```

What am I doing wrong?

答:
To answer your question "What am I doing wrong?", you should probably use input.value instead of input.innerHTML. However, getting "copy to clipboard" to work on all platforms is a nightmare. After quite a bit of research and experimentation, I ended up with:

```<code>// Adapted from https://gist.githubusercontent.com/Chalarangelo/4ff1e8c0ec03d9294628efbae49216db/raw/cbd2d8877d4c5f2678ae1e6bb7cb903205e5eacc/copyToClipboard.js.
export function copyToClipboard(text: string): boolean {
    // Create and append textarea to body:
    const textarea = document.createElement('textarea');
    textarea.setAttribute('readonly', 'true'); // Method needed because of missing TypeScript definition.
    textarea.contentEditable = 'true';
    textarea.style.position = 'absolute';
    textarea.style.top = '-1000px';
    textarea.value = text;
    document.body.appendChild(textarea);

    // Save the current selection of the user:
    const selectedRange = document.getSelection()!.rangeCount > 0 ? document.getSelection()!.getRangeAt(0) : false;

    // Select the content of the textarea:
    textarea.select(); // Ordinary browsers
    textarea.setSelectionRange(0, textarea.value.length); // iOS

    // Try to copy the range to the clipboard:
    let success: boolean;
    try {
        success = document.execCommand('copy');
    } catch (error) {
        console.error('Could not copy to the clipboard.', error);
        alert('Could not copy to the clipboard.');
        success = false;
    }

    // Remove the added textarea again:
    document.body.removeChild(textarea);

    // Restore the selection of the user:
    if (selectedRange) {
        document.getSelection()!.removeAllRanges();
        document.getSelection()!.addRange(selectedRange);
    }

    return success;
}
</code>```

Please note that this is written in TypeScript. For JavaScript, just remove all : string, : boolean and !.

Body:
I am trying to copy text as an onClick event, but it doesn't seem to pick up the value. Here's what I have:

  const copyText = () => {
    const input = document.createElement("input");
    input.innerHTML = 'test text';
    document.body.appendChild(input);
    input.select();
    document.execCommand("copy");
    document.body.removeChild(input);
    console.log("input", input);
  };

  copyText();

What am I doing wrong?

Body:
To answer your question "What am I doing wrong?", you should probably use input.value instead of input.innerHTML. However, getting "copy to clipboard" to work on all platforms is a nightmare. After quite a bit of research and experimentation, I ended up with:

// Adapted from https://gist.githubusercontent.com/Chalarangelo/4ff1e8c0ec03d9294628efbae49216db/raw/cbd2d8877d4c5f2678ae1e6bb7cb903205e5eacc/copyToClipboard.js.
export function copyToClipboard(text: string): boolean {
    // Create and append textarea to body:
    const textarea = document.createElement('textarea');
    textarea.setAttribute('readonly', 'true'); // Method needed because of missing TypeScript definition.
    textarea.contentEditable = 'true';
    textarea.style.position = 'absolute';
    textarea.style.top = '-1000px';
    textarea.value = text;
    document.body.appendChild(textarea);

    // Save the current selection of the user:
    const selectedRange = document.getSelection()!.rangeCount > 0 ? document.getSelection()!.getRangeAt(0) : false;

    // Select the content of the textarea:
    textarea.select(); // Ordinary browsers
    textarea.setSelectionRange(0, textarea.value.length); // iOS

    // Try to copy the range to the clipboard:
    let success: boolean;
    try {
        success = document.execCommand('copy');
    } catch (error) {
        console.error('Could not copy to the clipboard.', error);
        alert('Could not copy to the clipboard.');
        success = false;
    }

    // Remove the added textarea again:
    document.body.removeChild(textarea);

    // Restore the selection of the user:
    if (selectedRange) {
        document.getSelection()!.removeAllRanges();
        document.getSelection()!.addRange(selectedRange);
    }

    return success;
}

Please note that this is written in TypeScript. For JavaScript, just remove all : string, : boolean and !.


问:
How to fix "AttributeError: module 'tensorflow' has no attribute 'get_default_graph'"?
I am trying to run some code to create an LSTM model but i get an error:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

My code is as follows:

```<code>from keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
</code>```

I have found someone else with a similar problem and they updated tensorflow and it works; but mine is up to date and still does not work. I am new to using keras and machine learning so I apologise if this is something silly!

答:
Assuming people referring to this thread will be using more and more tensorflow 2:

Tensorflow 2 integrates further keras api, since keras is designed/developed very wisely. The answer is very easy if you are using tensorflow 2, as described also here:

```<code>from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, LSTM

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss=tensorflow.keras.losses.binary_crossentropy, optimizer=tensorflow.keras.optimizers.Adam(), metrics=['accuracy'])
</code>```

and that's how you change one would use something like MNIST from keras official page with just replacing tensorflow.keras instead of  keras and runnig it also on gpu;

```<code>from __future__ import print_function
import tensorflow
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 1024
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tensorflow.keras.losses.categorical_crossentropy,
          optimizer=tensorflow.keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
</code>```

Body:
I am trying to run some code to create an LSTM model but i get an error:

AttributeError: module 'tensorflow' has no attribute 'get_default_graph'

My code is as follows:

from keras.models import Sequential

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

I have found someone else with a similar problem and they updated tensorflow and it works; but mine is up to date and still does not work. I am new to using keras and machine learning so I apologise if this is something silly!

Body:
Assuming people referring to this thread will be using more and more tensorflow 2:

Tensorflow 2 integrates further keras api, since keras is designed/developed very wisely. The answer is very easy if you are using tensorflow 2, as described also here:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, LSTM

model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
model.add(LSTM(17))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss=tensorflow.keras.losses.binary_crossentropy, optimizer=tensorflow.keras.optimizers.Adam(), metrics=['accuracy'])

and that's how you change one would use something like MNIST from keras official page with just replacing tensorflow.keras instead of  keras and runnig it also on gpu;

from __future__ import print_function
import tensorflow
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras import backend as K

batch_size = 1024
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = tensorflow.keras.utils.to_categorical(y_train, num_classes)
y_test = tensorflow.keras.utils.to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
             activation='relu',
             input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=tensorflow.keras.losses.categorical_crossentropy,
          optimizer=tensorflow.keras.optimizers.Adadelta(),
          metrics=['accuracy'])

model.fit(x_train, y_train,
      batch_size=batch_size,
      epochs=epochs,
      verbose=1,
      validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])


问:
DPI Graphics Screen Resolution Pixels WinForm PrintPageEventArgs
How do Dpi Points relate to Pixels for any display my application is running on?

```<code>int points;
Screen primary;

public Form1() {
  InitializeComponent();
  points = -1;
  primary = null;
}

void OnPaint(object sender, PaintEventArgs e) {
  if (points < 0) {
    points = (int)(e.Graphics.DpiX / 72.0F); // There are 72 points per inch
  }
  if (primary == null) {
    primary = Screen.PrimaryScreen;
    Console.WriteLine(primary.WorkingArea.Height);
    Console.WriteLine(primary.WorkingArea.Width);
    Console.WriteLine(primary.BitsPerPixel);
  }
}
</code>```

Do I now have all of the information I need?

Can I use any of the information above to find out just how long 1200 pixels is?

答:
I realize it has been a few months, but while reading a book on WPF, I came across the answer:

If using standard Windows DPI setting (96 dpi), each device-independent unit corresponds to one real, physical pixel.

```<code>[Physical Unit Size] = [Device-Independent Unit Size] x [System DPI]
                     = 1/96 inch x 96 dpi
                     = 1 pixel
</code>```

Hence, 96 pixels to make an inch through the Windows system DPI settings.

However, this does, in reality, depend on your display size.

For a 19-inch LDC monitor set to a resolution of 1600 x 1200, use the Pythagoras theorem helps to calculate pixel density for the monitor:

```<code>[Screen DPI] = Math.Sqrt(Math.Pow(1600, 2) + Math.Pow(1200, 2)) / 19
</code>```

Using this data, I wrote up a little static tool that I now keep in my Tools class of all my projects:

```<code>/// <summary>
/// Calculates the Screen Dots Per Inch of a Display Monitor
/// </summary>
/// <param name="monitorSize">Size, in inches</param>
/// <param name="resolutionWidth">width resolution, in pixels</param>
/// <param name="resolutionHeight">height resolution, in pixels</param>
/// <returns>double presision value indicating the Screen Dots Per Inch</returns>
public static double ScreenDPI(int monitorSize, int resolutionWidth, int resolutionHeight) {
  //int resolutionWidth = 1600;
  //int resolutionHeight = 1200;
  //int monitorSize = 19;
  if (0 < monitorSize) {
    double screenDpi = Math.Sqrt(Math.Pow(resolutionWidth, 2) + Math.Pow(resolutionHeight, 2)) / monitorSize;
    return screenDpi;
  }
  return 0;
}
</code>```

I hope others get some use out of this nifty little tool.

ContentLicense: CC BY-SA 2.5

Body:
How do Dpi Points relate to Pixels for any display my application is running on?

int points;
Screen primary;

public Form1() {
  InitializeComponent();
  points = -1;
  primary = null;
}

void OnPaint(object sender, PaintEventArgs e) {
  if (points < 0) {
    points = (int)(e.Graphics.DpiX / 72.0F); // There are 72 points per inch
  }
  if (primary == null) {
    primary = Screen.PrimaryScreen;
    Console.WriteLine(primary.WorkingArea.Height);
    Console.WriteLine(primary.WorkingArea.Width);
    Console.WriteLine(primary.BitsPerPixel);
  }
}

Do I now have all of the information I need?

Can I use any of the information above to find out just how long 1200 pixels is?

Body:
I realize it has been a few months, but while reading a book on WPF, I came across the answer:

If using standard Windows DPI setting (96 dpi), each device-independent unit corresponds to one real, physical pixel.

[Physical Unit Size] = [Device-Independent Unit Size] x [System DPI]
                     = 1/96 inch x 96 dpi
                     = 1 pixel

Hence, 96 pixels to make an inch through the Windows system DPI settings.

However, this does, in reality, depend on your display size.

For a 19-inch LDC monitor set to a resolution of 1600 x 1200, use the Pythagoras theorem helps to calculate pixel density for the monitor:

[Screen DPI] = Math.Sqrt(Math.Pow(1600, 2) + Math.Pow(1200, 2)) / 19

Using this data, I wrote up a little static tool that I now keep in my Tools class of all my projects:

/// <summary>
/// Calculates the Screen Dots Per Inch of a Display Monitor
/// </summary>
/// <param name="monitorSize">Size, in inches</param>
/// <param name="resolutionWidth">width resolution, in pixels</param>
/// <param name="resolutionHeight">height resolution, in pixels</param>
/// <returns>double presision value indicating the Screen Dots Per Inch</returns>
public static double ScreenDPI(int monitorSize, int resolutionWidth, int resolutionHeight) {
  //int resolutionWidth = 1600;
  //int resolutionHeight = 1200;
  //int monitorSize = 19;
  if (0 < monitorSize) {
    double screenDpi = Math.Sqrt(Math.Pow(resolutionWidth, 2) + Math.Pow(resolutionHeight, 2)) / monitorSize;
    return screenDpi;
  }
  return 0;
}

I hope others get some use out of this nifty little tool.


问:
Dynamically ignore json properties based on condition
I have a POJO object with a List<Integer> stores for example. Is it possible to ignore it with @JsonIgrnore based on the condition to be empty or null when returning this object to the frontend?

答:
There is annotation called @JsonInclude accepting various configs.

In your case it would be:

```<code>@JsonInclude(JsonInclude.Include.NON_EMPTY)
List<Integer> stores
</code>```

Javadoc says:

```<code>NON_EMPTY
Value that indicates that only properties with null value,
or what is considered empty, are not to be included.
</code>```

Body:
There is annotation called @JsonInclude accepting various configs.

In your case it would be:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
List<Integer> stores

Javadoc says:

NON_EMPTY
Value that indicates that only properties with null value,
or what is considered empty, are not to be included.


问:
Replacing the values in a column with the frequency of occurence in same column in excel/sql/pandas
I am having a table which contains over 600000 records and a column named implementer_userid, value in which may get repeated for more than one record. Now i want to store how many times a particular distinct value is occuring in that column. COUNTIF(Excel), GroupBy(sql) and similar functions wont work as i dont want a count of a specific value and instead replace all distinct values with their frequencies. Help me by doing so in any one of the three frameworks: Excel, Pandas(Python) & SQL.

答:
If I understand your problem correctly, you can just construct a frequency table using value_counts() function, and then go through your column, replacing keys (row values) with the respective frequencies, as retrieved from the dictionary you've constructed earlier. For example:

```<code>frequencies = your_pandas_dataframe['Your column'].value_counts()
your_pandas_dataframe['Result column'] = your_pandas_dataframe['Your column'].apply(lambda x: frequencies[x])
</code>```

If you don't want this extra column, you can probably do something like this instead:

```<code># ...
your_pandas_dataframe['Your column'] = your_pandas_dataframe['Your column'].apply(lambda x: frequencies[x])
</code>```

Does this answer your question?

Body:
If I understand your problem correctly, you can just construct a frequency table using value_counts() function, and then go through your column, replacing keys (row values) with the respective frequencies, as retrieved from the dictionary you've constructed earlier. For example:

frequencies = your_pandas_dataframe['Your column'].value_counts()
your_pandas_dataframe['Result column'] = your_pandas_dataframe['Your column'].apply(lambda x: frequencies[x])

If you don't want this extra column, you can probably do something like this instead:

# ...
your_pandas_dataframe['Your column'] = your_pandas_dataframe['Your column'].apply(lambda x: frequencies[x])

Does this answer your question?


问:
Android, how to toast my simplexml class?
Sorry, I'm quite new in Android...
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class MyActivity extends Activity {
    Artworks myArtworks;

    ...
    myArtworks = serial.read(Artworks.class, artworksXmlFile);
    ...
}
--------------------------------------------------------------

file Artworks.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

@Element
public class Artworks {
    @ElementList(entry = "artwork", inline = true)
    private List<Artwork> list;
    ...
}
--------------------------------------------------------------

file Artwork.java:
public class Artwork {
    // how to use here Toast.makeText(..., text, Toast.LENGTH_SHORT).show() ???
}
--------------------------------------------------------------
</code>```

How do I use the Toast class (or any UI class) in my class Artwork, which I do never instantiate directly, but it's indirectly created by a call to serial.read(Artworks.class)?
How do I do it, exactly?

Thanks in advance!

答:
```<code>import android.widget.Toast;

public class Artwork {
   Toast.makeText(Artwork.this, "text", Toast.LENGTH_LONG).show();
}
</code>```

Body:
Sorry, I'm quite new in Android...
I have an activity which creates an object instance of my class:

file MyActivity.java:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class MyActivity extends Activity {
    Artworks myArtworks;

    ...
    myArtworks = serial.read(Artworks.class, artworksXmlFile);
    ...
}
--------------------------------------------------------------

file Artworks.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

@Element
public class Artworks {
    @ElementList(entry = "artwork", inline = true)
    private List<Artwork> list;
    ...
}
--------------------------------------------------------------

file Artwork.java:
public class Artwork {
    // how to use here Toast.makeText(..., text, Toast.LENGTH_SHORT).show() ???
}
--------------------------------------------------------------

How do I use the Toast class (or any UI class) in my class Artwork, which I do never instantiate directly, but it's indirectly created by a call to serial.read(Artworks.class)?
How do I do it, exactly?

Thanks in advance!


问:
Magento: How to get SQL query of Product load?
What is the full SQL query for product load?

I mean, how to get the full SQL query for this code:-

```<code>$productId = 52;
$product = Mage::getModel('catalog/product')->load($productId);
</code>```

I know, we can get the SQL query for collection object through printLogQuery. Example:-

```<code>$collection = Mage::getModel('catalog/product')->getCollection();
$collection->printLogQuery(true);
</code>```

I couldn't find such for product load(). Any idea?

答:
Getting the sql select from

```<code>$collection->getSelect()->__toString()
</code>```

is not reliable. Activate the db log, with n98-magerun.phar

```<code>n98-magerun.phar dev:log:db
</code>```

then you can tail the log file

```<code>tail -f var/debug/pdo_mysql.log
</code>```

to see realtime executing queries.

When you are done, deactivate the db log, using the same command

```<code>n98-magerun.phar dev:log:db
</code>```

Body:
What is the full SQL query for product load?

I mean, how to get the full SQL query for this code:-

$productId = 52;
$product = Mage::getModel('catalog/product')->load($productId);

I know, we can get the SQL query for collection object through printLogQuery. Example:-

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->printLogQuery(true);

I couldn't find such for product load(). Any idea?

Body:
Getting the sql select from

$collection->getSelect()->__toString()

is not reliable. Activate the db log, with n98-magerun.phar

n98-magerun.phar dev:log:db

then you can tail the log file

tail -f var/debug/pdo_mysql.log

to see realtime executing queries.

When you are done, deactivate the db log, using the same command

n98-magerun.phar dev:log:db


问:
put() prints duplicate lines in c
i was trying to run following code:

```<code>  #include<stdio.h>

void main()
{
        int c;
        while((c=getchar()) !=EOF)
                        putchar(c);
                        }
</code>```

i typed "hi" (or any other word) only once and when i press enter its print same thing again with a new line, no matter how large the line is

output

i dont know whats happening , the input stream is not buffered

答:
Your terminal operates in line mode. So when you type the characters

```<code>hi
</code>```

the program does not read them yet. They are just echoed to your terminal. When you press Enter, then all characters (hi plus a newline) are sent to the stdin of your program. These are read in character by character and then output. Thus, the text appears twice in your terminal.

If you want to change this, you have to put your terminal into character mode and switch local echo off. Libraries like ncurses can help you with that.

Title: put() prints duplicate lines in c

Body:
i was trying to run following code:

  #include<stdio.h>

void main()
{
        int c;
        while((c=getchar()) !=EOF)
                        putchar(c);
                        }

i typed "hi" (or any other word) only once and when i press enter its print same thing again with a new line, no matter how large the line is

output

i dont know whats happening , the input stream is not buffered

Body:
Your terminal operates in line mode. So when you type the characters

hi

the program does not read them yet. They are just echoed to your terminal. When you press Enter, then all characters (hi plus a newline) are sent to the stdin of your program. These are read in character by character and then output. Thus, the text appears twice in your terminal.

If you want to change this, you have to put your terminal into character mode and switch local echo off. Libraries like ncurses can help you with that.


问:
VBA Hiding Columns and Rows using Cell Reference
I would like to hide certain columns and rows based on inputs into certain cells, to make the code easily editable.

Furthermore, if the reference cell/range is empty, then I would like to continue the code without hiding any rows or columns.

Columns to Hide: based on cells C8:D8

Rows to Hide: based on cells C9:D9

This is where the logical fest should take place

```<code>

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value
</code>```

Current Code

```<code>Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim Filename As String
Dim Cell As String
Dim Counter As Long

If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

MsgBox "Enter Tab Name"
Exit Sub

End If

With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)

End If

If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

MyFile = Dir(MyFolder & "\", vbReadOnly)

StartTime = Timer

Do While MyFile <> ""
DoEvents
On Error GoTo 0

Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
 Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
' Set a reference to the settings sheet

Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source

' Gather the report sheet's name

reportSheetName = settingsSheet.Range("C7").Value ' good

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Set reportSheet = Sheets(reportSheetName)

Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

Set targetRowsRange = reportSheet.Range(reportRowsAddr)

targetColumnsRange.EntireColumn.Hidden = True
targetRowsRange.EntireRow.Hidden = True

With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1 '.FitToPagesTall = 1
End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

reportSheet.Select
reportSheet.PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

ThisWorkbook.Path & "\" & Cell, _

Quality:=xlQualityStandard, IncludeDocProperties:=True, _

IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

Workbooks(MyFile).Close SaveChanges:=False

MyFile = Dir

Loop

'turns settings back on

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub
</code>```

答:
A couple of thoughts about your code:

Dim MySheet As String

As mySheet is referring to the sheet name, be clear about it.

Rename the variable as Dim mySheetName as String

Set ReportSheet = Sheets(MySheet)

When setting the reference to the report sheet use full quilifying to the object.

Add Set reportSheet = ThisWorkbook.Worksheets(mySheetName)

I tried using the following logic, but it did not work, since I'm not able to insert " as part of the naming to properly create my variable.

To insert a double quote character, you can use: char(34)

e.g. TEST1 = "(" & Chr(34) & ThisWorkbook.Sheets("Sheet1").Range("C8").Value & ThisWorkbook.Sheets("Sheet1").Range("D8").Value & Chr(34) & ")"

Now about the request:

You could do this in a shorter way, but I chose this longer path, to illustrate the idea.

Gather the settings' information

Set a reference to both columns and rows

Find the intersection between them

Look for non empty cells in that range and hide their columns and rows

Code:

```<code>Public Sub DynamicallyHideCells()

    Dim settingsSheet As Worksheet
    Dim reportSheet As Worksheet

    Dim targetColumnsRange As Range
    Dim targetRowsRange As Range
    Dim targetRange As Range
    Dim targetCell As Range

    Dim reportSheetName As String
    Dim reportColumnsAddr As String
    Dim reportRowsAddr As String

    ' Set a reference to the settings sheet
    Set settingsSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Gather the report sheet's name
    reportSheetName = settingsSheet.Range("C7").Value

    ' Check the : between the two cells reference
    reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

    ' Check the : between the two cells reference
    reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

    ' Set a reference to the report's sheet
    Set reportSheet = ThisWorkbook.Worksheets(reportSheetName)

    ' Set a reference to the report's columns
    Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

    ' Set a reference to the report's rows
    Set targetRowsRange = reportSheet.Range(reportRowsAddr)

    ' Find the range of cells to be evaluated
    Set targetRange = Intersect(targetColumnsRange, targetRowsRange)

    ' Loop through each cell and hide if not empty
    For Each targetCell In targetRange.Cells

        If targetCell.Value <> vbNullString Then
            targetCell.EntireColumn.Hidden = True
            targetCell.EntireRow.Hidden = True
        End If

    Next targetCell

End Sub
</code>```

EDIT:

If you only need to hide the columns. Use the following code:

EDIT 2:

Added line to check if input cells are empty (' Check if either cell are empty and exit sub).

```<code>Public Sub HideColumns()

    Dim settingsSheet As Worksheet
    Dim reportSheet As Worksheet

    Dim targetColumnsRange As Range

    Dim reportSheetName As String
    Dim reportColumnsAddr As String

    ' Set a reference to the settings sheet
    Set settingsSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Gather the report sheet's name
    reportSheetName = settingsSheet.Range("C7").Value

    ' Check the : between the two cells reference
    reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

    ' Check if either cell are empty and exit sub
    If settingsSheet.Range("C8").Value = vbNullString Or settingsSheet.Range("D8").Value = vbNullString Then

        ' Set a reference to the report's sheet
        Set reportSheet = ThisWorkbook.Worksheets(reportSheetName)

        ' Set a reference to the report's columns
        Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

        ' Hide the columns in range
        targetColumnsRange.EntireColumn.Hidden = True

    Else

        ' Do something here

    End If

End Sub
</code>```

Hope this is what you're looking for.

Let me know if it works.

Body:
I would like to hide certain columns and rows based on inputs into certain cells, to make the code easily editable.

Furthermore, if the reference cell/range is empty, then I would like to continue the code without hiding any rows or columns.

Columns to Hide: based on cells C8:D8

Rows to Hide: based on cells C9:D9

This is where the logical fest should take place

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Current Code

Option Explicit

Private Sub CommandButton1_Click()

Dim MyFolder As String, MyFile As String
Dim StartTime As Double
Dim MinutesElapsed As String
Dim Filename As String
Dim Cell As String
Dim Counter As Long

If ThisWorkbook.Sheets("Sheet1").Range("C7").Value = vbNullString Then

MsgBox "Enter Tab Name"
Exit Sub

End If

With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Title = "Select a Folder"
If .Show = True Then
MyFolder = .SelectedItems(1)

End If

If .SelectedItems.Count = 0 Then Exit Sub
Err.Clear
End With

Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual

MyFile = Dir(MyFolder & "\", vbReadOnly)

StartTime = Timer

Do While MyFile <> ""
DoEvents
On Error GoTo 0

Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=False

Dim settingsSheet As Worksheet 'Source
Dim reportSheet As Worksheet 'To convert to PDF
 Dim targetColumnsRange As Range 'feeds from source
Dim targetRowsRange As Range
Dim reportSheetName As String 'source sheet with the target's sheet name
Dim reportColumnsAddr As String
Dim reportRowsAddr As String
' Set a reference to the settings sheet

Set settingsSheet = ThisWorkbook.Worksheets("Sheet1") ' source

' Gather the report sheet's name

reportSheetName = settingsSheet.Range("C7").Value ' good

reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

Set reportSheet = Sheets(reportSheetName)

Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

Set targetRowsRange = reportSheet.Range(reportRowsAddr)

targetColumnsRange.EntireColumn.Hidden = True
targetRowsRange.EntireRow.Hidden = True

With reportSheet.PageSetup
.Zoom = False
.FitToPagesWide = 1 '.FitToPagesTall = 1
End With

Filename = ActiveWorkbook.Name

Cell = Replace(Filename, ".xlsx", ".PDF")

reportSheet.Select
reportSheet.PageSetup.Orientation = xlLandscape

ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _

ThisWorkbook.Path & "\" & Cell, _

Quality:=xlQualityStandard, IncludeDocProperties:=True, _

IgnorePrintAreas:=True, OpenAfterPublish:=False

Counter = Counter + 1

0

Workbooks(MyFile).Close SaveChanges:=False

MyFile = Dir

Loop

'turns settings back on

Application.ScreenUpdating = True
Application.DisplayStatusBar = True
Application.EnableEvents = True
Application.Calculation = xlCalculationManual

MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")

MsgBox "Successfully Converted " & Counter & " Files in " & MinutesElapsed & " minutes", vbInformation

End Sub

Body:
A couple of thoughts about your code:

Dim MySheet As String

As mySheet is referring to the sheet name, be clear about it.

Rename the variable as Dim mySheetName as String

Set ReportSheet = Sheets(MySheet)

When setting the reference to the report sheet use full quilifying to the object.

Add Set reportSheet = ThisWorkbook.Worksheets(mySheetName)

I tried using the following logic, but it did not work, since I'm not able to insert " as part of the naming to properly create my variable.

To insert a double quote character, you can use: char(34)

e.g. TEST1 = "(" & Chr(34) & ThisWorkbook.Sheets("Sheet1").Range("C8").Value & ThisWorkbook.Sheets("Sheet1").Range("D8").Value & Chr(34) & ")"

Now about the request:

You could do this in a shorter way, but I chose this longer path, to illustrate the idea.

Gather the settings' information

Set a reference to both columns and rows

Find the intersection between them

Look for non empty cells in that range and hide their columns and rows

Code:

Public Sub DynamicallyHideCells()

    Dim settingsSheet As Worksheet
    Dim reportSheet As Worksheet

    Dim targetColumnsRange As Range
    Dim targetRowsRange As Range
    Dim targetRange As Range
    Dim targetCell As Range

    Dim reportSheetName As String
    Dim reportColumnsAddr As String
    Dim reportRowsAddr As String

    ' Set a reference to the settings sheet
    Set settingsSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Gather the report sheet's name
    reportSheetName = settingsSheet.Range("C7").Value

    ' Check the : between the two cells reference
    reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

    ' Check the : between the two cells reference
    reportRowsAddr = settingsSheet.Range("C9").Value & ":" & settingsSheet.Range("D9").Value

    ' Set a reference to the report's sheet
    Set reportSheet = ThisWorkbook.Worksheets(reportSheetName)

    ' Set a reference to the report's columns
    Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

    ' Set a reference to the report's rows
    Set targetRowsRange = reportSheet.Range(reportRowsAddr)

    ' Find the range of cells to be evaluated
    Set targetRange = Intersect(targetColumnsRange, targetRowsRange)

    ' Loop through each cell and hide if not empty
    For Each targetCell In targetRange.Cells

        If targetCell.Value <> vbNullString Then
            targetCell.EntireColumn.Hidden = True
            targetCell.EntireRow.Hidden = True
        End If

    Next targetCell

End Sub

EDIT:

If you only need to hide the columns. Use the following code:

EDIT 2:

Added line to check if input cells are empty (' Check if either cell are empty and exit sub).

Public Sub HideColumns()

    Dim settingsSheet As Worksheet
    Dim reportSheet As Worksheet

    Dim targetColumnsRange As Range

    Dim reportSheetName As String
    Dim reportColumnsAddr As String

    ' Set a reference to the settings sheet
    Set settingsSheet = ThisWorkbook.Worksheets("Sheet1")

    ' Gather the report sheet's name
    reportSheetName = settingsSheet.Range("C7").Value

    ' Check the : between the two cells reference
    reportColumnsAddr = settingsSheet.Range("C8").Value & ":" & settingsSheet.Range("D8").Value

    ' Check if either cell are empty and exit sub
    If settingsSheet.Range("C8").Value = vbNullString Or settingsSheet.Range("D8").Value = vbNullString Then

        ' Set a reference to the report's sheet
        Set reportSheet = ThisWorkbook.Worksheets(reportSheetName)

        ' Set a reference to the report's columns
        Set targetColumnsRange = reportSheet.Range(reportColumnsAddr)

        ' Hide the columns in range
        targetColumnsRange.EntireColumn.Hidden = True

    Else

        ' Do something here

    End If

End Sub

Hope this is what you're looking for.

Let me know if it works.


问:
Authorization code flow with Azure B2C, Angular and client backend
I want to create an authorization code flow similar to the screenshot below. I have an Angular app, deployed alongside a .NET Core client backend and using Azure B2C as an authorization server. Unfortunately I'm not quite sure how the flow goes.
I have a login button in my Angular app, does this directly call the Azure B2C with a redirect to the client backend? Or does the login button link to the client backend and this redirects to Azure B2C?

答:
If I understand the question correctly, you are wondering what endpoint is the Angular App calling on button click.  This depends on your implementation of the Http call in your Angular app.  You would have the login button call a service to Login.  That service will  inject the HttpClient in the constructor.  Then, in the login method on the service, you will use the httpClient to create your API call which will include the URL of the endpoint you want to call.  If you call your client backend, you can call the Azure B2C endpoint and handle the authorization there and pass either a 200 or 401 status code back to the Angular app.  If you want to call your Azure B2C directly from Angular, you would handle the response accordingly based on what Azure B2C will return (I have not used Azure B2C previously so I do not know the response that the API will return).  I hope this helps.  Below I have a link to the Angular docs regarding the HttpClient.

Angular Docs on Http


问:
Ruby on Rails multiply tiered users with authentication and authorisation
Could I get some advice with an authentication/authorisation design please?

It's for a car garage application that allows a customer to monitor the status of their car.

Here are my requirements:
1. I need a heirarchy of 4 users:

```<code>  A. Superuser (me)
  B. Garage owner.
  C. Mechanic.
  D. Customer.
</code>```

The superuser can create/edit/delete users A,B,C and D.
The Garage owner can create/edit/delete users C and D.

There can be multiple Garage owners that own the same group of mechanics, and customers.

Authentication for garage owners and mechanics is an account number (that the application issues) and password.

Authentication for customers is based on their email address and password.

A single login form for all types of user.

A customer has visibility of the status of their car only. A mechanic or garage owner has access to all cars associated with the garage. And the super user has access to all cars in the db.

My plugins of choice for this would be authlogic and cancan, but I can't seem to find an elegant design that will represent the ownership of some users by other users, for example, that for a particular garage owner, get all the mechanics or customers.

I would appreciate any thoughts about the best way to model this.

Thanks

答: I think you want a User model with a garage_id and a role property. I would expect that you could use an after_save on the User to set the login property to the email or account_number appropriately. You could do the rest in the CanCan Ability class. Obviously the super user will have a NULL garage_id.

Body:
Could I get some advice with an authentication/authorisation design please?

It's for a car garage application that allows a customer to monitor the status of their car.

Here are my requirements:
1. I need a heirarchy of 4 users:

  A. Superuser (me)
  B. Garage owner.
  C. Mechanic.
  D. Customer.

The superuser can create/edit/delete users A,B,C and D.
The Garage owner can create/edit/delete users C and D.

There can be multiple Garage owners that own the same group of mechanics, and customers.

Authentication for garage owners and mechanics is an account number (that the application issues) and password.

Authentication for customers is based on their email address and password.

A single login form for all types of user.

A customer has visibility of the status of their car only. A mechanic or garage owner has access to all cars associated with the garage. And the super user has access to all cars in the db.

My plugins of choice for this would be authlogic and cancan, but I can't seem to find an elegant design that will represent the ownership of some users by other users, for example, that for a particular garage owner, get all the mechanics or customers.

I would appreciate any thoughts about the best way to model this.

Thanks


问:
How to execute multiple commands in the while loop condition?
I want to create a directory with increasing numbers every time I run the script. My current solution is:

```<code>COUNTER=1
while mkdir $COUNTER; (( $? != 0 ))
do
     COUNTER=$((COUNTER + 1))
done
</code>```

Is separating the commands in the while condition with a ;(semicolon) the best practice?

答:
The very purpose of while and the shell's other control statements is to run a command and examine its exit code. You can use ! to negate the exit code.

```<code>while ! mkdir "$COUNTER"
do
     COUNTER=$((COUNTER + 1))
done
</code>```

Notice also the quoting; see further Why is testing "$?" to see if a command succeeded or not, an anti-pattern?

As such, if you want two commands to run and only care about the exit code from the second, a semicolon is the correct separator. Often, you want both commands to succeed; then, && is the correct separator to use.

Body:
I want to create a directory with increasing numbers every time I run the script. My current solution is:

COUNTER=1
while mkdir $COUNTER; (( $? != 0 ))
do
     COUNTER=$((COUNTER + 1))
done

Is separating the commands in the while condition with a ;(semicolon) the best practice?

Body:
The very purpose of while and the shell's other control statements is to run a command and examine its exit code. You can use ! to negate the exit code.

while ! mkdir "$COUNTER"
do
     COUNTER=$((COUNTER + 1))
done

Notice also the quoting; see further Why is testing "$?" to see if a command succeeded or not, an anti-pattern?

As such, if you want two commands to run and only care about the exit code from the second, a semicolon is the correct separator. Often, you want both commands to succeed; then, && is the correct separator to use.


问:
tf how to restore two variables from the same variable
I have saved a model and now I am trying to restore it in two branches, like this:

I wrote this code, and it raises ValueError: The same saveable will be restored with two names.
How do I restore two variables from the same variable?

```<code>restore_variables = {}
for varr in tf.global_variables()
    if varr.op.name in checkpoint_variables:
        restore_variables[varr.op.name.split("_red")[0]] = varr
        restore_variables[varr.op.name.split("_blue")[0]] = varr
init_saver = tf.train.Saver(restore_variables, max_to_keep=0)
</code>```

答:
I may not be understanding the problem correctly, but can't you just make two saver objects? Something like this:

import tensorflow as tf

# Make checkpoint
with tf.Graph().as_default(), tf.Session() as sess:
    a = tf.Variable([1., 2.], name='a')
    sess.run(a.initializer)
    b = tf.Variable([3., 4., 5.], name='b')
    sess.run(b.initializer)
    saver = tf.train.Saver([a, b])
    saver.save(sess, 'tmp/vars.ckpt')

# Restore checkpoint
with tf.Graph().as_default(), tf.Session() as sess:
    # Red
    a_red = tf.Variable([0., 0.], name='a_red')
    b_red = tf.Variable([0., 0., 0.], name='b_red')
    saver_red = tf.train.Saver({'a': a_red, 'b': b_red})
    saver_red.restore(sess, 'tmp1/vars.ckpt')
    print(a_red.eval())
    # [1. 2.]
    print(b_red.eval())
    # [3. 4. 5.]

    # Blue
    a_blue = tf.Variable([0., 0.], name='a_blue')
    b_blue = tf.Variable([0., 0., 0.], name='b_blue')
    saver_blue = tf.train.Saver({'a': a_blue, 'b': b_blue})
    saver_blue.restore(sess, 'tmp/vars.ckpt')
    print(a_blue.eval())
    # [1. 2.]
    print(b_blue.eval())
    # [3. 4. 5.]
```

Body:
I have saved a model and now I am trying to restore it in two branches, like this:

I wrote this code, and it raises ValueError: The same saveable will be restored with two names.
How do I restore two variables from the same variable?

restore_variables = {}
for varr in tf.global_variables()
    if varr.op.name in checkpoint_variables:
        restore_variables[varr.op.name.split("_red")[0]] = varr
        restore_variables[varr.op.name.split("_blue")[0]] = varr
init_saver = tf.train.Saver(restore_variables, max_to_keep=0)


问:
Disable selecting text in a TextBox
I have a textbox with the following (important) properties:

```<code>this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.license.ShortcutsEnabled = false;
</code>```

It looks like this:

How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?

答:
Very Easy Solution

Find a Label and into the textbox go to mousedown event and
set focus to the label

This is in VB and can be easily converted into C#

```<code>Private Sub RichTextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles RichTextBox1.MouseDown
        Label1.Focus()
    End Sub
</code>```

Title: Disable selecting text in a TextBox

Body:
I have a textbox with the following (important) properties:

this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.license.ShortcutsEnabled = false;

It looks like this:

How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?

Body:
Very Easy Solution

Find a Label and into the textbox go to mousedown event and
set focus to the label

This is in VB and can be easily converted into C#

Private Sub RichTextBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles RichTextBox1.MouseDown
        Label1.Focus()
    End Sub


问:
Animation, remove blink when a view.visibility(gone) and another view take the space
I'm dealing with animations, and I'm new with it. I've got this structure in XML file:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="@color/colorAccent"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/textViewT"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some Text"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:gravity="center"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Something"
            android:textSize="12sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center"/>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="vertical" />
</code>```

Animation:

```<code><set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<translate
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="-100%"/>
</code>```

And my MainActivity looks:

```<code>public class MainActivity extends AppCompatActivity {

MyRecyclerViewAdapter adapter;
boolean animationOnOff;
LinearLayout ll;
Animation animScroll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    ....

    animationOnOff = true;
    ll = findViewById(R.id.linearLayout1);
    animScroll = AnimationUtils.loadAnimation(this, R.anim.total_gasto_hide);
    animScroll.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ll.animate().alpha(0).setDuration(0).withEndAction(new Runnable() {
                @Override
                public void run() {
                    ll.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    RecyclerView recyclerView = findViewById(R.id.list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy > 0) {
                if(animationOnOff) {
                    ll.startAnimation(animScroll);
                    animationOnOff = false;
                }
            } else {

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

This code should take the linearLayout1 up and disapear after 300ms with a visibility(view.GONE), so far so good. The problem is that the recyclerview is not getting stick with this animation, and when the linearLayout1 is gone the recycler instantly get the position of the view gone (Doing some kind of blink effect). Gif below:

So my question is, how can I do it to eliminate this blink effect and achieve a smooth interpolation effect when the linearLayout1 is gone?

答:
I will suggest you use CoordinatorLayout with CollapsingToolbarLayout and change the app:layout_scrollFlags as per your needs

This will help you to remove the boiler part code which you have added
  in your Activity

```<code> <androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/cl_newdashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            app:elevation="2dp">

            <!--Toolbar here if you don't want to collapse it-->

        <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways">

            <!--COLLAPSING UI to be added here-->

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_prescriptions"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <!--REST OF THE VIEW-->

</androidx.coordinatorlayout.widget.CoordinatorLayout>
</code>```

The UI part which will land inside the CollapsingToolbarLayout will hide when the RecyclerView is scrolled,

Body:
I'm dealing with animations, and I'm new with it. I've got this structure in XML file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:focusable="true"
        android:orientation="vertical"
        android:padding="10dp"
        android:background="@color/colorAccent"
        android:layout_gravity="center">

        <TextView
            android:id="@+id/textViewT"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Some Text"
            android:textSize="18sp"
            android:textStyle="bold"
            android:textColor="@color/colorPrimaryDark"
            android:gravity="center"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Something"
            android:textSize="12sp"
            android:textColor="@color/colorPrimary"
            android:gravity="center"/>

    </LinearLayout>

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingStart="10dp"
        android:paddingEnd="10dp"
        android:scrollbars="vertical" />

Animation:

<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">

<translate
    android:duration="300"
    android:fromYDelta="0"
    android:toYDelta="-100%"/>

And my MainActivity looks:

public class MainActivity extends AppCompatActivity {

MyRecyclerViewAdapter adapter;
boolean animationOnOff;
LinearLayout ll;
Animation animScroll;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ArrayList<String> animalNames = new ArrayList<>();
    animalNames.add("Horse");
    ....

    animationOnOff = true;
    ll = findViewById(R.id.linearLayout1);
    animScroll = AnimationUtils.loadAnimation(this, R.anim.total_gasto_hide);
    animScroll.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationEnd(Animation animation) {
            ll.animate().alpha(0).setDuration(0).withEndAction(new Runnable() {
                @Override
                public void run() {
                    ll.setVisibility(View.GONE);
                }
            });
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }
    });
    RecyclerView recyclerView = findViewById(R.id.list);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    adapter = new MyRecyclerViewAdapter(this, animalNames);
    recyclerView.setAdapter(adapter);
    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(dy > 0) {
                if(animationOnOff) {
                    ll.startAnimation(animScroll);
                    animationOnOff = false;
                }
            } else {

            }
        }
    });
}
}

This code should take the linearLayout1 up and disapear after 300ms with a visibility(view.GONE), so far so good. The problem is that the recyclerview is not getting stick with this animation, and when the linearLayout1 is gone the recycler instantly get the position of the view gone (Doing some kind of blink effect). Gif below:

So my question is, how can I do it to eliminate this blink effect and achieve a smooth interpolation effect when the linearLayout1 is gone?

Body:
I will suggest you use CoordinatorLayout with CollapsingToolbarLayout and change the app:layout_scrollFlags as per your needs

This will help you to remove the boiler part code which you have added
  in your Activity

 <androidx.coordinatorlayout.widget.CoordinatorLayout
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/cl_newdashboard"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/transparent"
            app:elevation="2dp">

            <!--Toolbar here if you don't want to collapse it-->

        <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsing_toolbar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:layout_scrollFlags="scroll|enterAlways">

            <!--COLLAPSING UI to be added here-->

        </com.google.android.material.appbar.CollapsingToolbarLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_prescriptions"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

    <!--REST OF THE VIEW-->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

The UI part which will land inside the CollapsingToolbarLayout will hide when the RecyclerView is scrolled,


问:
How to implement chat using jQuery, PHP, and MySQL?
I have made a chat script using php, mysql and jquery. It uses json to get data from the server. It makes fixed interval requests to the server with the lastly fetched message id to get new messages from the server. But when multiple users will be chatting then thousands and crores of requests will be made to the server within an hour and the hosting people will block it for sure.

Th gmail chat uses socket I think. Because it does not sends fixed interval requests for sure. Could any one of you please give me some sample code or some direction to solve this issue.

Please I need help desperately.

Many thanks in advance. My respect and regards for all.

答:
Right or wrong, a hosting company might get cranky for a couple reasons:

1) Odds are good they are using apache prefork.  Each chat request is probably gonna be a new connection and thus hog up a single apache process.  Each apache process eats anywhere from 1mb of memory to 100mb of memory.

2) If they maintain the database server and you, the client, suck at database programming, you can hammer their database.  "Suck" means anything from "no proper indexing" to "makes a bazillion tiny queries instead of nice fat ones".

As has been suggested above, make sure your code uses persistent connections.  Also:

1) Implement a back-off algorithm on the client.  Poll the server once a second during activity, then back off to five seconds, then ten, twenty, etc...  That way you dont hammer the server when there is no activity.

2) Multiple tabs will kill you.  User opens 10 tabs and they all have your chat widget polling the server once a second?  Bad news.  Even if your host doesn't get pissed, your performance will degrade.

If this thing gets huge, design your system in a way that you can run the chat-server bits independently from the rest of your web application.  In otherwords, the clients would be making a request to "chat.yourwebapp.com", which in turn is running on something like lighttpd.

LastEditorDisplayName: ryeguy

OwnerDisplayName: Cory R. King


问:
modify width of processing div
I have this div that appears on loading pages:

```<code><div id="divProcessing" style="position: absolute; left: 0px; top: 0px; width: 100%; height: 100%; background-color: transparent;  z-Index: 2000;overflow:hidden; display:none;border:none;"/>
</code>```

My problem is that on a page that has scroll bars the div is not expanded on all the page, only on screen size and i can access the content behind the div if i scroll.

I don't know how to expand or how to calculate the width/height of content page

答:
If the div is a direct child of body, you can try adding:

```<code>html, body {
    height: 100%;
    overflow: hidden;     /* in case your content is floated */
}
</code>```

Do you have a page online where we can see it?

Title: modify width of processing div

Body:
I have this div that appears on loading pages:

My problem is that on a page that has scroll bars the div is not expanded on all the page, only on screen size and i can access the content behind the div if i scroll.

I don't know how to expand or how to calculate the width/height of content page

Body:
If the div is a direct child of body, you can try adding:

html, body {
    height: 100%;
    overflow: hidden;     /* in case your content is floated */
}

Do you have a page online where we can see it?


问:
Implement RSS feed in React native
So, I've been learning react native lately and I am trying to create an RSS reader.I have managed to Download the RSS data but I am stuck in implementing them into JSX ( Screen). I've been trying using setState method but it didn't work.
I can get the RSS data logged into Console but I can't display them in user through JSX

PS: Comments are just tests that I made

```<code>class HomeScreen extends React.Component {
  state = {
    feed: {},
    items: {}
  };

  RSS() {
    return fetch("http://di.ionio.gr/feed/")
      .then(response => response.text())
      .then(responseData => rssParser.parse(responseData))
      .then(rss => {
        this.setState(() => ({
          //...prevState,
          feed: rss
          //titles: rss.items,
        }));
      });
  }

  render() {
    {this.RSS();}
    return (
      <View style={styles.top}>
        <HeaderScreen {...this.props} />
        <Text>{this.state.feed.title}</Text>
      </View>
    );
  }
}
</code>```

I've been using react-native-rss-parser.

I also tried without setState but that also didn't work.

Thanks in advance

答:
With your current setup, you're creating an endless loop.  This is because you have a side effect (i.e. network request) in your render function.

When your request returns and you call setState your component is rendered again, which in turn calls the network again with this.RSS(), etc. etc. etc.

To fix this, move the this.RSS() to either your constructor function or better yet to the componentDidMount function.

i.e.

```<code>componentDidMount() {
  this.RSS();
}

render() {
  return (
    <View style={styles.top}>
      <Text>{this.state.feed.title}</Text>
    </View>
  );
}
</code>```

Title: Implement RSS feed in React native

Body:
So, I've been learning react native lately and I am trying to create an RSS reader.I have managed to Download the RSS data but I am stuck in implementing them into JSX ( Screen). I've been trying using setState method but it didn't work.
I can get the RSS data logged into Console but I can't display them in user through JSX

PS: Comments are just tests that I made

class HomeScreen extends React.Component {
  state = {
    feed: {},
    items: {}
  };

  RSS() {
    return fetch("http://di.ionio.gr/feed/")
      .then(response => response.text())
      .then(responseData => rssParser.parse(responseData))
      .then(rss => {
        this.setState(() => ({
          //...prevState,
          feed: rss
          //titles: rss.items,
        }));
      });
  }

  render() {
    {this.RSS();}
    return (
      <View style={styles.top}>
        <HeaderScreen {...this.props} />
        <Text>{this.state.feed.title}</Text>
      </View>
    );
  }
}

I've been using react-native-rss-parser.

I also tried without setState but that also didn't work.

Thanks in advance

Body:
With your current setup, you're creating an endless loop.  This is because you have a side effect (i.e. network request) in your render function.

When your request returns and you call setState your component is rendered again, which in turn calls the network again with this.RSS(), etc. etc. etc.

To fix this, move the this.RSS() to either your constructor function or better yet to the componentDidMount function.

i.e.

componentDidMount() {
  this.RSS();
}

render() {
  return (
    <View style={styles.top}>
      <Text>{this.state.feed.title}</Text>
    </View>
  );
}


问:
JavaScript - Get url from window without submitting it
So I have a page that I want to retrieve the URL from but I want to get the current text that is written there regardless of if the url was submitted or not (imagine if the user entered a page and decided to change the val=sfbdjkfg directly through the url but didn't submit it )

So window.location.href is not what I want because I have to submit to get the URL

Is there any way to do this?
What about using a javaScript framework that uses dynamic routes?

答:
There's no such way via javascript to interact with browser UI components such as URL bar or "add as bookmark" button unless your browser provides that.
Browser itself act as a wrapper/client that provides specific APIs and surely not to open gates to access the outside of it, for security reasons.</p>


问:
How can i use DataTable as a data source for my test case using mstest or nunit?
I have a data table which contains the data and i want to use data table as a parameter for my test case as a data driven testing.

Any Testing Framework (MsTest/Nunit) suggestion is appreciated with c# as a scripting language.

Scenario:-

I need to get the test data from TFS which i am able to retrieve and store it in a data table. Once i have saved in data table i need to use the same data table in my test case as a parameter so that my test case runs for all the parameter.

```<code>    [DataTestMethod]
    [WorkItem(13)]
    public void GetTestValuesFromTestParameter()
    {
        //Code to get the data from TFS
       var method = MethodBase.GetCurrentMethod();
       var attr = (WorkItemAttribute)method.GetCustomAttributes(typeof(WorkItemAttribute), true)[0];
       GetTableItemsFromTestCase(workItemId);
    }

    private DataTable GetTableItemsFromTestCase(int workItemId)
    {
        //Return the data table items from TFS
    }
</code>```

Suppose the test case in TFS has 2 parameter [Name,FirstName] and i will prepare the test data with the value

```<code>//////Data table Start /////
   [Name] [FirstName]
 1. ["QWERTY","LAST"]
 2. ["TEST","TEST"]
//////Data table END /////
</code>```

and now i have a data table with 2 rows. The test case should run with 2 input values from data table (i,.e-> 'QWERTY' and 'TEST').

Work item attribute is a mapping to get the ID of the Test case in TFS which will get the data from TFS.

I am struck here and need help on how to pass the Data table to the test case.

答:
A custom ITestDataSource would be needed for this special case

The data source will get the data from TFS and pass that data to the test case.

```<code>public class WorkItemAttribute : Attribute, ITestDataSource {
    private readonly int workItemId;

    public WorkItemAttribute(int workItemId) {
        this.workItemId = workItemId;
    }

    public IEnumerable<object[]> GetData(MethodInfo methodInfo) {
        var dataTable = GetTableItemsFromTestCase(workItemId);
        yield return new object[] { dataTable };
    }

    private DataTable GetTableItemsFromTestCase(int workItemId) {
        //Return the data table items from TFS
    }

    public string GetDisplayName(MethodInfo methodInfo, object[] data) {
        if (data != null)
            return string.Format(CultureInfo.CurrentCulture, "{0} WorkItem {1} - ({2})", methodInfo.Name, workItemId, string.Join(",", data));

        return null;
    }
}
</code>```

This is like your very own version of DynamicData or DataRow attribute

The test can then use the data source like

```<code>[DataTestMethod]
[WorkItem(13)]
public void GetTestValuesFromTestParameter(DataTable data) {
    //...
}
</code>```

Body:
I have a data table which contains the data and i want to use data table as a parameter for my test case as a data driven testing.

Any Testing Framework (MsTest/Nunit) suggestion is appreciated with c# as a scripting language.

Scenario:-

I need to get the test data from TFS which i am able to retrieve and store it in a data table. Once i have saved in data table i need to use the same data table in my test case as a parameter so that my test case runs for all the parameter.

    [DataTestMethod]
    [WorkItem(13)]
    public void GetTestValuesFromTestParameter()
    {
        //Code to get the data from TFS
       var method = MethodBase.GetCurrentMethod();
       var attr = (WorkItemAttribute)method.GetCustomAttributes(typeof(WorkItemAttribute), true)[0];
       GetTableItemsFromTestCase(workItemId);
    }

    private DataTable GetTableItemsFromTestCase(int workItemId)
    {
        //Return the data table items from TFS
    }

Suppose the test case in TFS has 2 parameter [Name,FirstName] and i will prepare the test data with the value

//////Data table Start /////
   [Name] [FirstName]
 1. ["QWERTY","LAST"]
 2. ["TEST","TEST"]
//////Data table END /////

and now i have a data table with 2 rows. The test case should run with 2 input values from data table (i,.e-> 'QWERTY' and 'TEST').

Work item attribute is a mapping to get the ID of the Test case in TFS which will get the data from TFS.

I am struck here and need help on how to pass the Data table to the test case.

Body:
A custom ITestDataSource would be needed for this special case

The data source will get the data from TFS and pass that data to the test case.

public class WorkItemAttribute : Attribute, ITestDataSource {
    private readonly int workItemId;

    public WorkItemAttribute(int workItemId) {
        this.workItemId = workItemId;
    }

    public IEnumerable<object[]> GetData(MethodInfo methodInfo) {
        var dataTable = GetTableItemsFromTestCase(workItemId);
        yield return new object[] { dataTable };
    }

    private DataTable GetTableItemsFromTestCase(int workItemId) {
        //Return the data table items from TFS
    }

    public string GetDisplayName(MethodInfo methodInfo, object[] data) {
        if (data != null)
            return string.Format(CultureInfo.CurrentCulture, "{0} WorkItem {1} - ({2})", methodInfo.Name, workItemId, string.Join(",", data));

        return null;
    }
}

This is like your very own version of DynamicData or DataRow attribute

The test can then use the data source like

[DataTestMethod]
[WorkItem(13)]
public void GetTestValuesFromTestParameter(DataTable data) {
    //...
}


问:
Try to find a better way to layout 4 images
I have 4 images and try to layout them as my expections. I know there is a very easy way to layout with table layout like the following snippet.

```

But I don't want to do it with table layout for HTML Semantic reason. So How do I do it with CSS ?

答:
There are several ways to do it, one possible approach is using an unordered list of images with Flexbox position

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-wrap: wrap;
  width: 175px;
}

li {
  text-align: center;
  flex-basis: 100%; }

li:not(:first-child) { flex-basis: 33.3%; }

img { width: 50px; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
</ul></code>```

Body:
I have 4 images and try to layout them as my expections. I know there is a very easy way to layout with table layout like the following snippet.

But I don't want to do it with table layout for HTML Semantic reason. So How do I do it with CSS ?

Body:
There are several ways to do it, one possible approach is using an unordered list of images with Flexbox position

ul {
  margin: 0;
  padding: 0;
  list-style: none;
  display: flex;
  flex-wrap: wrap;
  width: 175px;
}

li {
  text-align: center;
  flex-basis: 100%; }

li:not(:first-child) { flex-basis: 33.3%; }

img { width: 50px; }

<ul>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
  <li><img src="https://en.pimg.jp/015/085/802/1/15085802.jpg" /></li>
</ul>


问:
a array of week days[mon,wed,thu,fri,sun] display in string like mon,wed-fri,sun
A array of week days [Mon,Wed,Thu,Fri,Sun] and display it in string like Mon,Wed-Fri,sun using TS or JS.

Where the continues day will be like Wed-Fri.

ex-1  [Mon,Tue,Wed,Thu,Fri,sat,sun] display like Mon-Sun
ex-2  [Mon,Tue,Thu,Fri,Sat,sun] display like Mon-Tue,Thu-sun
ex-2  [Mon,Tue,Thu,Sat,Sun] display like Mon-Tue,Thu,sat-sun
```

答:
const fullList = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun']
function optimizeList(list) {
  var from = -1, to = -1, res = [];
  fullList.forEach(function(n, idx) {
    var found = list.indexOf(n) >= 0;
    if (found && to >= 0 && idx === to + 1)
      to = idx;
    if (from === -1 && found)
      from = to = idx;
    if (to >= 0 && (idx === fullList.length - 1 || to !== idx)) {
      res.push(fullList[from] + (to !== from ? '-' + fullList[to] : ''));
      from = to = -1;
    }
  })
  return res
}

console.log(optimizeList(['Mon','Tue','Fri','Sun']))
console.log(optimizeList(['Tue','Fri']))
console.log(optimizeList(['Mon','Tue','Wed','Thu','Fri','Sat','Sun']))
console.log(optimizeList(['Sat','Sun']))
console.log(optimizeList(['Tue','Wed']))```