问:
How to force re render when an array changes its value in ReactJS
How to force re-render when an array changes its value in ReactJS.

I have an array like

const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);
```
<p>and when I call a delete function to remove one element of this array the view doesn't render.</p>
<pre class="lang-js prettyprint-override"><code>let OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
};
</code>```

答:
I've a workaraund when I want the page to render againg when using hooks that works for me.

I Just declare a state and then change its value to force re-render, something like this

```<code>const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);
const [refresh, setRefresh] = useState<boolean>(false);

const OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
    setRefresh(!refresh) //**Here i force a re render when changing th state**
}
</code>```

I hope it works for you :)

Body:
How to force re-render when an array changes its value in ReactJS.

I have an array like

const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);

and when I call a delete function to remove one element of this array the view doesn't render.

let OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
};

Body:
I've a workaraund when I want the page to render againg when using hooks that works for me.

I Just declare a state and then change its value to force re-render, something like this

const [providers, setProviders] = useState<Array<any>>(props.filters?.providers!);
const [refresh, setRefresh] = useState<boolean>(false);

const OnDelete = (prop: any, func: any, p: IFilter) => {
    const index = prop.findIndex((x: IFilter) => x.code == p.code);
    if (index !== -1) {
        prop.splice(index, 1);
    }
    func(prop);
    setRefresh(!refresh) //**Here i force a re render when changing th state**
}

I hope it works for you :)


来源: stackexchange

问:
How to refactor code using if condition in javascript?
i have code like below,

```<code>React.useMemo(() => {
    if (isInProgress && data && data.Run) {
        if (data.Run.partial === true) { //how can i rewrite this
            setIsRunPartial(true);
        }
        else {
            setIsRunPartial(false);
        }
    }

}, [data, isInProgress]);
</code>```

here the data.Run.partial can be undefined true or false. how can rewrite above code to look clean. i have to call setIsRunPartial to true if data.Run.partial is true and false if data.Run.partial is false.

how can rewrite above code. could someone help me with this. thanks.

答:
You can simply use setIsRunPartial(!!data.Run.partial)

If it is undefined, the !! boolean cast will make it become False --> setIsRunpartial(false) in case of undefined

Other than that, if true or other truthy value --> setIsRunPartial(!!truthy) -->setIsRunPartial(true)

if false or other falsy value --> setIsRunPartial(!!falsy) -->setIsRunPartial(false)

ContentLicense: CC BY-SA 4.0

Body:
i have code like below,

React.useMemo(() => {
    if (isInProgress && data && data.Run) {
        if (data.Run.partial === true) { //how can i rewrite this
            setIsRunPartial(true);
        }
        else {
            setIsRunPartial(false);
        }
    }

}, [data, isInProgress]);

here the data.Run.partial can be undefined true or false. how can rewrite above code to look clean. i have to call setIsRunPartial to true if data.Run.partial is true and false if data.Run.partial is false.

how can rewrite above code. could someone help me with this. thanks.


问:
Docker - Call PHP script on web container from a CRON container
I have a web app running in a docker container (apache, php).
I've been looking for solutions to install a cron job in order to regularly perform some actions on my web app (execute php files etc).

I found multiple answers (How to run a cron job inside a docker container?), all based on creating a separated container which will be responsible to run the cron jobs.

Now, how do I make this cron container communicate with my web container ?

I found multiple solutions :

Install and use CURL on my cron container

Install cron on web container and run it in the background (against good practices)

I'm also wondering if I could use a shared network in my compose file between my web and my cron container, but I'm unsure on how to make it work.

Do you guys have other ideas or code samples to help me achieve this ?

答:
Managed to make it work using a shared network between my web container and my cron container (thanks @David Maze)

Cron Dockerfile :

```<code>FROM ubuntu:18.04

RUN apt-get update
RUN apt-get install -y systemd
RUN apt-get install -y nano
RUN apt-get install -y cron
RUN apt-get install -y curl

RUN systemctl enable cron
RUN (crontab -l -u root; echo "* * * * * curl web:80 -d 'action=cron.run'") | crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log
</code>```

Docker compose

```<code>version: '3.7'

services:

    # Web container
    web:
        # [...]
        ports:
            - "0001:80"
            - "0002:443"
        networks:
            - cron_network

    # Cron container
    cron:
        # [...]
        depends_on:
            - web
        networks:
          - cron_network

networks:
  cron_network:
</code>```

Body:
Managed to make it work using a shared network between my web container and my cron container (thanks @David Maze)

Cron Dockerfile :

FROM ubuntu:18.04

RUN apt-get update
RUN apt-get install -y systemd
RUN apt-get install -y nano
RUN apt-get install -y cron
RUN apt-get install -y curl

RUN systemctl enable cron
RUN (crontab -l -u root; echo "* * * * * curl web:80 -d 'action=cron.run'") | crontab

# Create the log file to be able to run tail
RUN touch /var/log/cron.log

# Run the command on container startup
CMD cron && tail -f /var/log/cron.log

Docker compose

version: '3.7'

services:

    # Web container
    web:
        # [...]
        ports:
            - "0001:80"
            - "0002:443"
        networks:
            - cron_network

    # Cron container
    cron:
        # [...]
        depends_on:
            - web
        networks:
          - cron_network

networks:
  cron_network:


问:
Assign value to specific cell in PySpark dataFrame
I want to change a value in a specific cell of my Spark DataFrame using PySpark.

Trivial example - I create a mock Spark DataFrame:

```<code>df = spark.createDataFrame(
    [
     (1, 1.87, 'new_york'),
     (4, 2.76, 'la'),
     (6, 3.3, 'boston'),
     (8, 4.1, 'detroit'),
     (2, 5.70, 'miami'),
     (3, 6.320, 'atlanta'),
     (1, 6.1, 'houston')
    ],
    ('variable_1', "variable_2", "variable_3")
)
</code>```

Runnning display(df) I get this table:

```<code>variable_1   variable_2   variable_3
    1           1.87    new_york
    4           2.76    la
    6           3.3     boston
    8           4.1     detroit
    2           5.7     miami
    3           6.32    atlanta
    1           6.1     houston
</code>```

Let´s say for example, I would like to assign a new value for the cell in the 4th row and 3rd column, i.e. changing detroit for new_orleans. I know assignments as df.iloc[4, 3] = 'new_orleans' or df.loc[4, 'detroit'] = 'new_orleans' are not valid in Spark.

A valid answer to my question using when would be:

```<code>from pyspark.sql.functions import when
targetDf = df.withColumn("variable_3", \
              when(((df["variable_1"] == 8) & (df["variable_2"] == 4.1)) , 'new_orleans').otherwise(df["variable_3"]))
</code>```

My question is: could this be done in a more practical way in PySpark without the necessity of entering all the values and column names of the row where I want to change just 1 single cell (maybe achieving the same without using the when function)?

Thanks in advance for your help and @useruser9806664 for his feedback.

答:
I had the same problem but I used sql expresions:</p>
```<code>expr = """CASE WHEN variable1==8 AND variable==4.1 THEN 'new_orleans' ELSE variable3 END AS variable4"""

df = df.selectExpr(*,expr)
</code>```

Body:
I want to change a value in a specific cell of my Spark DataFrame using PySpark.

Trivial example - I create a mock Spark DataFrame:

df = spark.createDataFrame(
    [
     (1, 1.87, 'new_york'),
     (4, 2.76, 'la'),
     (6, 3.3, 'boston'),
     (8, 4.1, 'detroit'),
     (2, 5.70, 'miami'),
     (3, 6.320, 'atlanta'),
     (1, 6.1, 'houston')
    ],
    ('variable_1', "variable_2", "variable_3")
)

Runnning display(df) I get this table:

variable_1   variable_2   variable_3
    1           1.87    new_york
    4           2.76    la
    6           3.3     boston
    8           4.1     detroit
    2           5.7     miami
    3           6.32    atlanta
    1           6.1     houston

Let´s say for example, I would like to assign a new value for the cell in the 4th row and 3rd column, i.e. changing detroit for new_orleans. I know assignments as df.iloc[4, 3] = 'new_orleans' or df.loc[4, 'detroit'] = 'new_orleans' are not valid in Spark.

A valid answer to my question using when would be:

from pyspark.sql.functions import when
targetDf = df.withColumn("variable_3", \
              when(((df["variable_1"] == 8) & (df["variable_2"] == 4.1)) , 'new_orleans').otherwise(df["variable_3"]))

My question is: could this be done in a more practical way in PySpark without the necessity of entering all the values and column names of the row where I want to change just 1 single cell (maybe achieving the same without using the when function)?

Thanks in advance for your help and @useruser9806664 for his feedback.

Body:
I had the same problem but I used sql expresions:

expr = """CASE WHEN variable1==8 AND variable==4.1 THEN 'new_orleans' ELSE variable3 END AS variable4"""

df = df.selectExpr(*,expr)


问:
I'm keep getting an error that says the column of the range is too small
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

```<code>var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```
```<code>const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();
</code>```

But it works here

```<code>    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }

</code>```

答:
As answered by Kostas, the column and row indices for .getRange() should start at 1.

The reason this snippet works with a 0 index:

```<code>cellMHS.offset(ctMHS, 0).getValue()
</code>```

is that the .offset() method is different from the .getRange() method: .offset() doesn't expect an absolute cell or row index: its arguments are offsets relative to the range represented by cellMHS, i.e. how far away from that range.  So a value of 0 just means use the same column as the original range.  You can even pass a negative offset to reference a column to the left of cellMHS.

Body:
I was writing some code and when i tried to run it I got an error

The starting column of the range is too small.

I'm using Google Apps Script

The error I'm getting is on this line

var cellCup = ss.getRange(ctCup, 0).activate().getValue();

const ss = SpreadsheetApp.openByUrl(THIS).getSheetByName('WP_Data');
var ctCup =114;
var cellCup = ss.getRange(ctCup, 0).activate().getValue();

But it works here

    var ctMHS = 3;
    var cellMHS = ss.getRange('A3');
    while ( cellMHS.offset(ctMHS, 0).getValue() != "" ) {
      ctMHS++;
    }

Body:
As answered by Kostas, the column and row indices for .getRange() should start at 1.

The reason this snippet works with a 0 index:

cellMHS.offset(ctMHS, 0).getValue()

is that the .offset() method is different from the .getRange() method: .offset() doesn't expect an absolute cell or row index: its arguments are offsets relative to the range represented by cellMHS, i.e. how far away from that range.  So a value of 0 just means use the same column as the original range.  You can even pass a negative offset to reference a column to the left of cellMHS.


问:
capturing the residual from felm in original dataframe and passing to Python
I am running R via Python using %load_ext rpy2.ipython.

```<code>#Prepare R in Python
%load_ext rpy2.ipython
%R install.packages("pacman")
%R pacman::p_load(pacman, tidyverse, lfe)
</code>```

In R, I am running a model using felm on a dataframe. I want to capture the residuals in the original dataframe and then pass that dataframe back into Python. I can do this for regular lm as:

```<code>%%R -o test
dat <- mtcars
test <- mutate(res=residuals(lm(mpg~disp, data = dat)), dat)
</code>```

Then in Python I have a nice dataframe with res included:

```<code>test.describe()
</code>```

Unfortunately, this approach doesn't seem to work when I use felm instead of lm:

```<code>%%R -o test2
dat <- mtcars
test2 <- mutate(res=residuals(felm(mpg~disp, data = dat)), dat)
</code>```

I get the following: "ValueError: Data must be 1-dimensional" Any ideas why this works for lm and not for felm? I did notice that when I run:

```<code>%%R
dat <- mtcars
test2 <- mutate(res=residuals(felm(mpg~disp, data = dat)), dat)
head(test2, 10)
</code>```

the residual is calculated correctly and appears to be added to the dataframe but is named "mpg" instead of "res." Not sure what is going on here. Any help is appreciated.

Body:
I am running R via Python using %load_ext rpy2.ipython.

#Prepare R in Python
%load_ext rpy2.ipython
%R install.packages("pacman")
%R pacman::p_load(pacman, tidyverse, lfe)

In R, I am running a model using felm on a dataframe. I want to capture the residuals in the original dataframe and then pass that dataframe back into Python. I can do this for regular lm as:

%%R -o test
dat <- mtcars
test <- mutate(res=residuals(lm(mpg~disp, data = dat)), dat)

Then in Python I have a nice dataframe with res included:

test.describe()

Unfortunately, this approach doesn't seem to work when I use felm instead of lm:

%%R -o test2
dat <- mtcars
test2 <- mutate(res=residuals(felm(mpg~disp, data = dat)), dat)

I get the following: "ValueError: Data must be 1-dimensional" Any ideas why this works for lm and not for felm? I did notice that when I run:

%%R
dat <- mtcars
test2 <- mutate(res=residuals(felm(mpg~disp, data = dat)), dat)
head(test2, 10)

the residual is calculated correctly and appears to be added to the dataframe but is named "mpg" instead of "res." Not sure what is going on here. Any help is appreciated.

Body:
The issue is that with lm the residuals return a named vector, whereas with felm, it is returning a matrix with single column

str(residuals(felm(mpg~disp, data = dat)) )
 num [1:32, 1] -2.01 -2.01 -2.35 2.43 3.94 ...
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr "mpg"

Considering removing the dimensions by converting to vector with as.vector or wrap with c

c(residuals(felm(mpg~disp, data = dat)))

With mutate, it would be

library(dplyr)
test <-  dat %>%
    mutate(res = c(residuals(felm(mpg~disp, data = .))))

-output

> str(test)
'data.frame':   32 obs. of  12 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
 $ res : num  -2.01 -2.01 -2.35 2.43 3.94 ...

With the OP's approach, the column remains as a matrix and this may have problems in the describe method from python

> test <-  dat %>%
+     mutate(res = residuals(felm(mpg~disp, data = .)))
>
> str(test)
'data.frame':   32 obs. of  12 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
 $ res : num [1:32, 1] -2.01 -2.01 -2.35 2.43 3.94 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : NULL
  .. ..$ : chr "mpg"


问:
Will Apple reject my iPhone application because of increasing memory usage?
I have an application with multiple views. It works pretty fine without any leaks or crashes. But when you run using performance tool for leaks, I see when I switch through multiple views and comeback to home screen, my overall size of the application gets increased. Like if its 1.53MB after visiting 4-5 different views and getting back to screen increases the consumption to 1.58MB or less but definitely greater than 1.53MB.
I tried resolving this issue but not able to figure out where I am going wrong since there are no memory leaks.

Does anyone know what could be the problem?

Will apple reject my application on this basis?

答:
If an application has an increasing memory footprint on a known stable state for example named A after going into and coming back from state B which should have no persistent affect on state A and there is no memory leaks this problem called (as much as I know) the lingering memory.

Checklist to be sure if you have lingering memory problem:

App has no memory leaks, or no memory leaks on non-system code when profiled by Instruments.

State A and State B are individually stable states, like in state-machine.
State B has no permanent affect on State A, or it's memory. State A could be a gateway, a menu to another states like State B or State C. But Child states has no or limited info about state A and makes no change about State A.

On loop state changes starts and ends with root state for example A->B->A, A->C->A, A->B->C->A; you encounter increasing memory usage on State A. Memory usage on other child states are not important.

To spot and solve this problem profile your app with instruments. But instead of monitoring leaks, you should monitor allocations and total memory. Every time your app gets to State A, including start, take a memory snapshot. (There is a button for that :D) After snapshot go to State B, State C and use your application as it suppose to. After coming back to root state, in this example State A, take another snapshot. Instruments will show you memory allocations and difference delta in total memory between snapshots. It will also give information about for which object the memory had allocated and when if possible. If it was your code you probably will see the type of class and allocation point. Instruments can not help you about when the object should have been released but when you got the lingering object or memory, figuring out the deallocation point should be much easier.

BUT! Do not forget:
OS and Framework codes could have leaks and lingering memory problems like every OS. If you are sure that it is not your code leaking or lingering in the memory the everything is fine. That was the case in my app and it got approved(App: Tusudoku). System function often use additional memory if there is available, but they immediately release it when received memory warning. Although devices has limited memory, it is a waste if still not used, and using memory does not make memory chip to use measurably increased electrical current. Using memory to the limits for performance and immediately releasing it when someone definitely needs it, is best possible practice. These cache memories does not tend to be grove over time linearly but you should force memory warning every time app gets to root state, in this example State A. So this way you will be sure any cache memory allocated by system or frameworks will be deallocated, then you take the snapshot.

Most of the apps on the App Store® has memory leaks and other memory problems. The question is how this affect user. Non-linear lingering memory with rapidly dropping acceleration on increase velocity generally won't be a reason for rejection. Calculated the memory usage as 15MB for a perfect working app but if it worked, no problem, say that it will reach 20MB limit max ever and you are good to go. So you later fix your memory problems. Bu if your application has a linear or worse increasing memory usage and can not release that memories when needed, that will be a critical problem.

For more information about memory usage please consider reading official documentation and watching WWDC videos(That's where I learned all about memory fixes using Instruments).

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Can I pass strings with reserved characters?
When I try this:

```<code>db = 'ACS-Sociodemographics(USA,CensusBlockGroups,2018)'
ctx.cursor().execute(f"USE DATABASE {db}")
</code>```

I get this error:

```<code>ProgrammingError: 001003 (42000): SQL compilation error:
syntax error line 1 at position 16 unexpected '-'.
</code>```

Is there a recommended way to pass a string with reserved characters?

答:
Yes, the db name needs to be encased in double quotes. To make life easier, wrap the whole thing in single quotes like so:</p>
```<code>ctx.cursor().execute(f'USE DATABASE "{db}"')
</code>```

Body:
When I try this:

db = 'ACS-Sociodemographics(USA,CensusBlockGroups,2018)'
ctx.cursor().execute(f"USE DATABASE {db}")

I get this error:

ProgrammingError: 001003 (42000): SQL compilation error:
syntax error line 1 at position 16 unexpected '-'.

Is there a recommended way to pass a string with reserved characters?

Body:
Yes, the db name needs to be encased in double quotes. To make life easier, wrap the whole thing in single quotes like so:

ctx.cursor().execute(f'USE DATABASE "{db}"')


问:
How to check the sub string is exists or not in main string
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

```<code>$a = 'Hello world';
$b = 'Hello';
</code>```

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).

答:
strpos().

It returns FALSE if the substring is not found.

Body:
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

$a = 'Hello world';
$b = 'Hello';

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).


问:
geom_line() with x as factor and a grouping variable for color
I have the following reproducible data :

```<code>d <- data.frame(ATB = rep(c("ATB1", "ATB2"), each = 4),
            status = rep(rep(c("S", "R"), each = 2), 2),
            season = rep(c("Winter", "summer"), 4),
            n = c(239,284,113,120,229,269,127,140)
            )
</code>```

I am trying to draw points for the count n for each line by season, the color being the variable ATB, and to link each point according to the ATB and to the status from one season value to another (ATB1 S winter linked to ATB1 S summer).  Here is the plot I am trying to get:

Until now I managed to draw the points but not the lines.

```<code>  ggplot(d, aes(x=season, y = n)) +
    geom_point(aes(color = ATB)) +
    geom_line(aes(color = ATB, linetype = status))
</code>```

I tried group = 1 in each aes, but it didn't work.

Is there a way to obtain the plot ?

答:
You need to group by the interaction of ATB and status, otherwise you are not correctly telling ggplot which points to connect:

  ggplot(d, aes(x=season, y = n)) +
    geom_point(aes(color = ATB)) +
    geom_line(aes(color = ATB, linetype = status,
                  group = interaction(ATB, status))) +
    scale_linetype_manual(values = c(2, 1))
```

Body:
I have the following reproducible data :

d <- data.frame(ATB = rep(c("ATB1", "ATB2"), each = 4),
            status = rep(rep(c("S", "R"), each = 2), 2),
            season = rep(c("Winter", "summer"), 4),
            n = c(239,284,113,120,229,269,127,140)
            )

I am trying to draw points for the count n for each line by season, the color being the variable ATB, and to link each point according to the ATB and to the status from one season value to another (ATB1 S winter linked to ATB1 S summer).  Here is the plot I am trying to get:

Until now I managed to draw the points but not the lines.

  ggplot(d, aes(x=season, y = n)) +
    geom_point(aes(color = ATB)) +
    geom_line(aes(color = ATB, linetype = status))

I tried group = 1 in each aes, but it didn't work.

Is there a way to obtain the plot ?


问:
Loss is nan, stopping training when training Mask-RCNN multi-class segmentation
```<code>number of train data: 346
number of test data: 69
Epoch: [0] [0/346] eta: 0:35:20 lr: 0.000019 loss: -312.6024 (-312.6024) loss_classifier: 1.5789 (1.5789) loss_box_reg: 0.1299 (0.1299) loss_mask: -314.3485 (-314.3485) loss_objectness: 0.0266 (0.0266) loss_rpn_box_reg: 0.0106 (0.0106) time: 6.1275 data: 0.1599 max mem: 0
Loss is nan, stopping training
{‘loss_classifier’: tensor (nan, grad_fn = ), ‘loss_box_reg’: tensor (nan, grad_fn = ), ‘loss_mask’: tensor (nan, grad_fn = ), ’ tensor (nan, grad_fn = ), ‘loss_rpn_box_reg’: tensor (nan, grad_fn = )}
An exception has occurred, use% tb to see the full traceback.

SystemExit : 1
</code>```

And this is the dataset code:

```<code>
class maskrcnn_Dataset(torch.utils.data.Dataset):
   def __init__(self, root, transforms=None):
    self.root = root
    self.transforms = transforms
    # load all image files, sorting them to
    # ensure that they are aligned
    self.imgs = list(sorted(os.listdir(os.path.join(root, "images"))))
    self.masks = list(sorted(os.listdir(os.path.join(root, "masks"))))
    #self.class_masks = list(sorted(os.listdir(os.path.join(root, "SegmentationClass"))))

def __getitem__(self, idx):
    # load images ad masks
    img_path = os.path.join(self.root, "images", self.imgs[idx])
    x=self.imgs[idx].split('.')
    mask_path = os.path.join(self.root, "masks", self.masks[idx])
    #class_mask_path = os.path.join(self.root, "SegmentationClass", self.class_masks[idx])

    #read and convert image to RGB
    img = cv2.imread(img_path)
    mask_for_all=[]
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # note that we haven't converted the mask to RGB,
    # because each color corresponds to a different instance
    # with 0 being background
    # mask = Image.open(mask_path)
    mask_folder=os.path.join(self.root,"masks")
    source_mask = os.path.join(mask_folder, x[0])
    #print(os.listdir(source_mask))
    boxes = []
    xx=trier(os.listdir(source_mask))
    #print(xx)
    for file_name in xx:
        mask = Image.open(os.path.join(source_mask,file_name))
        mask = np.array(mask)
        mask_for_all.append(mask)
        obj_ids = np.unique(mask)
        obj_ids = obj_ids[1:]
        masks = mask == obj_ids[:, None, None]
        num_objs = len(obj_ids)
        for i in range(num_objs):
            pos = np.where(masks[i])
            xmin = np.min(pos[1])
            xmax = np.max(pos[1])
            ymin = np.min(pos[0])
            ymax = np.max(pos[0])
            boxes.append([xmin, ymin, xmax, ymax])

    num_objs=len(boxes)
    boxes = torch.as_tensor(boxes, dtype=torch.float32)
    # there is only one class
    if(self.root.find("train")!=-1):
        #print("bisgltjf")

        labels =class_ids_train[class_ids_train_names.index(self.imgs[idx])]
        #print(labels)
    else:
        labels =class_ids_val[class_ids_val_names.index(self.imgs[idx])]
        #print('l3assba')

    #labels = np.array([])
    #for i in range(masks.shape[0]):
     #   labels = np.append(labels, (masks[i] * class_mask).max())

    labels = torch.as_tensor(labels, dtype=torch.int64)
    #print(boxes,":",labels)
    masks = torch.as_tensor(mask_for_all, dtype=torch.uint8)
    #print(labels)
    #print(masks)
    #print(masks.shape)

    image_id = torch.tensor([idx])
    area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
    # suppose all instances are not crowd
    iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
    #print(img.shape)
    #print(self.imgs[idx])

    target = {}
    target["boxes"] = boxes
    #print(boxes)
    target["labels"] = labels
    #print(labels.shape)
    target["masks"] = masks
    #print(masks.shape)
    target["image_id"] = image_id
    #print(image_id.shape)
    target["area"] = area
    #print(area)
    target["iscrowd"] = iscrowd
    #print(iscrowd.shape)

    if self.transforms is not None:
        img, target = self.transforms(img, target)

    return img, target

def __len__(self):
    return len(self.imgs)
</code>```

答:
There can be two issues:

Check the coordinate of boxes, make sure [xmin, ymin, xmax, ymax] is positive

Make sure the mask's length is the same as boxes.

Body:
number of train data: 346
number of test data: 69
Epoch: [0] [0/346] eta: 0:35:20 lr: 0.000019 loss: -312.6024 (-312.6024) loss_classifier: 1.5789 (1.5789) loss_box_reg: 0.1299 (0.1299) loss_mask: -314.3485 (-314.3485) loss_objectness: 0.0266 (0.0266) loss_rpn_box_reg: 0.0106 (0.0106) time: 6.1275 data: 0.1599 max mem: 0
Loss is nan, stopping training
{‘loss_classifier’: tensor (nan, grad_fn = ), ‘loss_box_reg’: tensor (nan, grad_fn = ), ‘loss_mask’: tensor (nan, grad_fn = ), ’ tensor (nan, grad_fn = ), ‘loss_rpn_box_reg’: tensor (nan, grad_fn = )}
An exception has occurred, use% tb to see the full traceback.

SystemExit : 1

And this is the dataset code:

class maskrcnn_Dataset(torch.utils.data.Dataset):
   def __init__(self, root, transforms=None):
    self.root = root
    self.transforms = transforms
    # load all image files, sorting them to
    # ensure that they are aligned
    self.imgs = list(sorted(os.listdir(os.path.join(root, "images"))))
    self.masks = list(sorted(os.listdir(os.path.join(root, "masks"))))
    #self.class_masks = list(sorted(os.listdir(os.path.join(root, "SegmentationClass"))))

def __getitem__(self, idx):
    # load images ad masks
    img_path = os.path.join(self.root, "images", self.imgs[idx])
    x=self.imgs[idx].split('.')
    mask_path = os.path.join(self.root, "masks", self.masks[idx])
    #class_mask_path = os.path.join(self.root, "SegmentationClass", self.class_masks[idx])

    #read and convert image to RGB
    img = cv2.imread(img_path)
    mask_for_all=[]
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    # note that we haven't converted the mask to RGB,
    # because each color corresponds to a different instance
    # with 0 being background
    # mask = Image.open(mask_path)
    mask_folder=os.path.join(self.root,"masks")
    source_mask = os.path.join(mask_folder, x[0])
    #print(os.listdir(source_mask))
    boxes = []
    xx=trier(os.listdir(source_mask))
    #print(xx)
    for file_name in xx:
        mask = Image.open(os.path.join(source_mask,file_name))
        mask = np.array(mask)
        mask_for_all.append(mask)
        obj_ids = np.unique(mask)
        obj_ids = obj_ids[1:]
        masks = mask == obj_ids[:, None, None]
        num_objs = len(obj_ids)
        for i in range(num_objs):
            pos = np.where(masks[i])
            xmin = np.min(pos[1])
            xmax = np.max(pos[1])
            ymin = np.min(pos[0])
            ymax = np.max(pos[0])
            boxes.append([xmin, ymin, xmax, ymax])

    num_objs=len(boxes)
    boxes = torch.as_tensor(boxes, dtype=torch.float32)
    # there is only one class
    if(self.root.find("train")!=-1):
        #print("bisgltjf")

        labels =class_ids_train[class_ids_train_names.index(self.imgs[idx])]
        #print(labels)
    else:
        labels =class_ids_val[class_ids_val_names.index(self.imgs[idx])]
        #print('l3assba')

    #labels = np.array([])
    #for i in range(masks.shape[0]):
     #   labels = np.append(labels, (masks[i] * class_mask).max())

    labels = torch.as_tensor(labels, dtype=torch.int64)
    #print(boxes,":",labels)
    masks = torch.as_tensor(mask_for_all, dtype=torch.uint8)
    #print(labels)
    #print(masks)
    #print(masks.shape)

    image_id = torch.tensor([idx])
    area = (boxes[:, 3] - boxes[:, 1]) * (boxes[:, 2] - boxes[:, 0])
    # suppose all instances are not crowd
    iscrowd = torch.zeros((num_objs,), dtype=torch.int64)
    #print(img.shape)
    #print(self.imgs[idx])

    target = {}
    target["boxes"] = boxes
    #print(boxes)
    target["labels"] = labels
    #print(labels.shape)
    target["masks"] = masks
    #print(masks.shape)
    target["image_id"] = image_id
    #print(image_id.shape)
    target["area"] = area
    #print(area)
    target["iscrowd"] = iscrowd
    #print(iscrowd.shape)

    if self.transforms is not None:
        img, target = self.transforms(img, target)

    return img, target

def __len__(self):
    return len(self.imgs)


问:
Compare headers of dataframes and add the columns to the delta table
There are two  dataframes

df1 ---> OrgID, location, Address, State -- which is delta table

df2 ---> OrgID, location, Address, State, Active, Seq_Number -- which is createOrReplaceTempViewtable

In df2 there are two additional columns Active, Seq_Number.

How to get the datatypes of the new columns

How to add the new columns to the existing Delta table and update the values

tried the below:

converted the dataframes to pandaDF and used this, which got new columns in the Index object.

```<code>df_new_columns = df1.columns.difference(df2.columns)
</code>```
```<code>new = [ ]

if len(df_new_columns.tolist()) != 0:

for column in df_new_columns.tolist():
    column_name = column
    new.append(column)
</code>```

答:
Try this:</p>
```<code>delta_table = pd.concat([delta_table, createOrReplaceTempViewtable[['Active', 'Seq_Number']]])
</code>```

Body:
There are two  dataframes

df1 ---> OrgID, location, Address, State -- which is delta table

df2 ---> OrgID, location, Address, State, Active, Seq_Number -- which is createOrReplaceTempViewtable

In df2 there are two additional columns Active, Seq_Number.

How to get the datatypes of the new columns

How to add the new columns to the existing Delta table and update the values

tried the below:

converted the dataframes to pandaDF and used this, which got new columns in the Index object.

df_new_columns = df1.columns.difference(df2.columns)

new = [ ]

if len(df_new_columns.tolist()) != 0:

for column in df_new_columns.tolist():
    column_name = column
    new.append(column)

Body:
Try this:

delta_table = pd.concat([delta_table, createOrReplaceTempViewtable[['Active', 'Seq_Number']]])


问:
Group and create three new columns by condition [Low, Hit, High]
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High.

I now would create this three columns Hit, Low, High and calculate for each row which condition applies and put a 1 into this col, the other two would become 0. After that I would group the values and sum them up. But I suspect there must be a better and faster way, such as calculate it directly while grouping.

Data

```<code>import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

+----+--------+---------+
|    | Type   |   Value |
|----+--------+---------|
|  0 | RF     |    -1.5 | <- Low
|  1 | RF     |    -0.1 | <- Hit
|  2 | RF     |     1.7 | <- High
|  3 | MLP    |     0.2 | <- Hit
|  4 | MLP    |    -0.7 | <- Low
|  5 | MLP    |    -0.6 | <- Low
+----+--------+---------+
</code>```

Expected Output

```<code>pd.DataFrame({"Type":["RF", "MLP"], "Low":[1,2], "Hit":[1,1], "High":[1,0]})

+----+--------+-------+-------+--------+
|    | Type   |   Low |   Hit |   High |
|----+--------+-------+-------+--------|
|  0 | RF     |     1 |     1 |      1 |
|  1 | MLP    |     2 |     1 |      0 |
+----+--------+-------+-------+--------+
</code>```

答:
you can try this:</p>
```<code># Your code
import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

# Set your range
RANGE_MIN = -0.25
RANGE_MAX = 0.25

# --- define functions to be applied to df ---
# evaluate if value is a low
def eval_low(value):
    if value < RANGE_MIN:
        return 1
    else:
        return 0

# evaluate if value is a high
def eval_high(value):
    if value > RANGE_MAX:
        return 1
    else:
        return 0

# evaluate if value is a hit
def eval_hit(value):
    if value >= RANGE_MIN and value <= RANGE_MAX:
        return 1
    else:
        return 0

# Evaluate the functions in new columns
df['Low'] = df.Value.apply(eval_low)
df['Hit'] = df.Value.apply(eval_hit)
df['High'] = df.Value.apply(eval_high)

# get the summary
df.groupby('Type').sum()
</code>```

Body:
I have a large dataset (~5 Mio rows) with results from a Machine Learning training. Now I want to check to see if the results hit the "target range" or not. Lets say this range contains all values between -0.25 and +0.25. If it's inside this range, it's a Hit, if it's below Low and on the other side High.

I now would create this three columns Hit, Low, High and calculate for each row which condition applies and put a 1 into this col, the other two would become 0. After that I would group the values and sum them up. But I suspect there must be a better and faster way, such as calculate it directly while grouping.

Data

import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

+----+--------+---------+
|    | Type   |   Value |
|----+--------+---------|
|  0 | RF     |    -1.5 | <- Low
|  1 | RF     |    -0.1 | <- Hit
|  2 | RF     |     1.7 | <- High
|  3 | MLP    |     0.2 | <- Hit
|  4 | MLP    |    -0.7 | <- Low
|  5 | MLP    |    -0.6 | <- Low
+----+--------+---------+

Expected Output

pd.DataFrame({"Type":["RF", "MLP"], "Low":[1,2], "Hit":[1,1], "High":[1,0]})

+----+--------+-------+-------+--------+
|    | Type   |   Low |   Hit |   High |
|----+--------+-------+-------+--------|
|  0 | RF     |     1 |     1 |      1 |
|  1 | MLP    |     2 |     1 |      0 |
+----+--------+-------+-------+--------+

Body:
you can try this:

# Your code
import pandas as pd

df = pd.DataFrame({"Type":["RF", "RF", "RF", "MLP", "MLP", "MLP"], "Value":[-1.5,-0.1,1.7,0.2,-0.7,-0.6]})

# Set your range
RANGE_MIN = -0.25
RANGE_MAX = 0.25

# --- define functions to be applied to df ---
# evaluate if value is a low
def eval_low(value):
    if value < RANGE_MIN:
        return 1
    else:
        return 0

# evaluate if value is a high
def eval_high(value):
    if value > RANGE_MAX:
        return 1
    else:
        return 0

# evaluate if value is a hit
def eval_hit(value):
    if value >= RANGE_MIN and value <= RANGE_MAX:
        return 1
    else:
        return 0

# Evaluate the functions in new columns
df['Low'] = df.Value.apply(eval_low)
df['Hit'] = df.Value.apply(eval_hit)
df['High'] = df.Value.apply(eval_high)

# get the summary
df.groupby('Type').sum()


问:
C++ and STL refresher course
I know C and C++ quite well. I know in much detail about pointers and well versed with pointer arithmetic and worked on Win32 API and a bit of MFC as well in my university days. In my previous job, I had no chance to look on these matters and worked in some other domain. Now what I want is a crash or refresher course in:

C++

STL

I do not want to go through 500+ pages of books because I know C#, Java, Ruby, Python and even x86 Assembly as well. What I want is to cover advanced and dark corners of C++ and intermediate STL.

Can anyone point out good links about it?
I know about Google! ;-)
But an intelligent human recommendation is something else yet Google has not implemented.

答:
I'm not quite sure what you mean exactly by advanced C++ and intermediate STL.

The  C++ FAQ Lite  helped me a lot when I first started with C++.

OwnerDisplayName: Mohsin Hijazee

Title: C++ and STL refresher course

LastEditorDisplayName: Ferruccio

OwnerDisplayName: sybreon


问:
How to implement RandomAccessFile's seek() and getFilePointer() using FileInputStream and BufferReader?
I would like to Open a file containing UTF-8 encoded text, Can able to set position, Read 25 lines, Can able to get position.

Unfortunately RandomAccessFile does not support UTF-8 encoding. So I have written this code. I recursive call getParsedLines() method with the returned offset value to read next 25 lines but it prints first 1-25 rows, then print 349-373, 695-719 and so on.

```<code>public long getParsedLines(File file, long offset) {

    int counter = 0;
    FileInputStream fis = null;
    InputStreamReader streamReader = null;
    BufferedReader br = null;
    try {
        fis = new FileInputStream(file);
        fis.getChannel().position(offset);
        streamReader = new InputStreamReader(fis, "UTF8");
        br = new BufferedReader(streamReader);
        String str;
        while (counter <= 24) {
            if ((str = br.readLine()) != null) {
                System.out.println(str);
            } else {
                offset = -1;
                break;
            }
            counter++;
        }
        if (fis != null) {
            offset = fis.getChannel().position();

        }
    } catch (IOException ex) {
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
        }

    }

    return offset;
}
</code>```

how can I get last offset correct so I can print 1-25, 26-50, 51-75. 76-100 and so on.

Yes.. For some backward compatibility I have some constraint that I have to read text file "line by line" using readLine() and read only 25-25 lines at a time not the whole text.

答: If you must do it this way, you can use the BufferedReader.skip method to skip characters (having kept a count of the number of chars already read).  But if possible, I'd suggest to just keep the same BufferedReader around (without closing it), so that it's automatically in the right place in any case.

Body:
I would like to Open a file containing UTF-8 encoded text, Can able to set position, Read 25 lines, Can able to get position.

Unfortunately RandomAccessFile does not support UTF-8 encoding. So I have written this code. I recursive call getParsedLines() method with the returned offset value to read next 25 lines but it prints first 1-25 rows, then print 349-373, 695-719 and so on.

public long getParsedLines(File file, long offset) {

    int counter = 0;
    FileInputStream fis = null;
    InputStreamReader streamReader = null;
    BufferedReader br = null;
    try {
        fis = new FileInputStream(file);
        fis.getChannel().position(offset);
        streamReader = new InputStreamReader(fis, "UTF8");
        br = new BufferedReader(streamReader);
        String str;
        while (counter <= 24) {
            if ((str = br.readLine()) != null) {
                System.out.println(str);
            } else {
                offset = -1;
                break;
            }
            counter++;
        }
        if (fis != null) {
            offset = fis.getChannel().position();

        }
    } catch (IOException ex) {
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
        } catch (IOException ex) {
        }

    }

    return offset;
}

how can I get last offset correct so I can print 1-25, 26-50, 51-75. 76-100 and so on.

Yes.. For some backward compatibility I have some constraint that I have to read text file "line by line" using readLine() and read only 25-25 lines at a time not the whole text.


问:
What is "range" actually? Is it a function?
One of the preferred way to loop through arrays and slices is to use range like this

arr = []int{1, 2}

for index, item := range arr {
  continue
}
```

I know how range works, I've been using it multiple times. But I'm still not sure what it is behind the scene. Is it a function and a modification of range(arr)? The fact that it returns 2 variables make me think that way, but I need a confirmation.

What's the implementation behind it?

答:
Range is one of the keywords according to the spec.

```<code>The following keywords are reserved and may not be used as identifiers.

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var
</code>```

For statements with range clause

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.

```<code>RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .
</code>```

Body:
One of the preferred way to loop through arrays and slices is to use range like this

arr = []int{1, 2}

for index, item := range arr {
  continue
}

I know how range works, I've been using it multiple times. But I'm still not sure what it is behind the scene. Is it a function and a modification of range(arr)? The fact that it returns 2 variables make me think that way, but I need a confirmation.

What's the implementation behind it?

Body:
Range is one of the keywords according to the spec.

The following keywords are reserved and may not be used as identifiers.

break        default      func         interface    select
case         defer        go           map          struct
chan         else         goto         package      switch
const        fallthrough  if           range        type
continue     for          import       return       var

For statements with range clause

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables if present and then executes the block.

RangeClause = [ ExpressionList "=" | IdentifierList ":=" ] "range" Expression .


问:
Mark Gradle source folder as test source in IntelliJ
I have an integration test source folder set up in gradle like so:

```<code>subprojects {
    apply plugin: 'java'
    apply plugin: 'idea'

    sourceCompatibility = 1.8

    configurations {
        integrationTestCompile.extendsFrom testCompile
        integrationTestCompileOnly.extendsFrom integrationTestCompile
        integrationTestCompileOnly.extendsFrom testCompileOnly
        integrationTestRuntime.extendsFrom testRuntime
    }

    sourceSets {
        integrationTest {
            java {
                compileClasspath += main.output + test.output
                runtimeClasspath += main.output + test.output
                srcDir file('src/integrationTest/java')
            }
            resources.srcDir file('src/integrationTest/resources')
        }
    }

    task integrationTest(type:Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
        outputs.upToDateWhen { false }
    }
}
</code>```

For executing the tests, this works perfectly well, but it causes problems with IntelliJ's inspections, which may change behavior for test code. IntelliJ does not recognize the source folder as test source.

I tried adding them as such (inside subprojects):

```<code>idea {
    module {
        testSourceDirs += file('src/integrationTest/java')
    }
}
</code>```

but that did not help at all. I also tried manually marking them as test source (context menu -> mark directory as -> test sources root), but IntelliJ quickly overrides that back to normal source root.

How do I configure this correctly in Gradle?

I'm using IntelliJ 2016.1.3 and Gradle 2.14.1 on Ubuntu 16.04

答:
I know this is old but facing the same problem I found buried somewhere in this jetbrains ticket something hinting that your test sourceSet should be declared in gradle like so :

```<code>sourceSets {
    integrationTest {
        test{ //<- note this, this is what flags it right for intelliJ to process it correctly
            java {
                compileClasspath += main.output + test.output
                runtimeClasspath += main.output + test.output
                srcDir file('src/integrationTest/java')
                // note that you'll need to specify the outputDir for it to work
                // I don't fully get the reasons for this (but I rarely do when it comes to gradle anyway)
                outputDir = file("build/classes/java/integrationTest")
            }
            resources {
                srcDir file('src/integrationTest/resources')
            }
        }
    }
}
</code>```

Doing so made intelliJ instantly recognize my integration-test folder like the test-source it is ...

[Small rant] I could not find trace of the appropriate corresponding gradle doc and as often I find info on how it works from retro-engineering or scarce hints in this case trial/error+ IntelliJ youtrack ticket (which says a lot on how poorly gradle is documented in my view ...)

Note that I am on

Intellij : IntelliJ IDEA 2021.3.2 (Ultimate Edition) Build #IU-213.6777.52

Gradle : 6.7.1

Body:
I have an integration test source folder set up in gradle like so:

subprojects {
    apply plugin: 'java'
    apply plugin: 'idea'

    sourceCompatibility = 1.8

    configurations {
        integrationTestCompile.extendsFrom testCompile
        integrationTestCompileOnly.extendsFrom integrationTestCompile
        integrationTestCompileOnly.extendsFrom testCompileOnly
        integrationTestRuntime.extendsFrom testRuntime
    }

    sourceSets {
        integrationTest {
            java {
                compileClasspath += main.output + test.output
                runtimeClasspath += main.output + test.output
                srcDir file('src/integrationTest/java')
            }
            resources.srcDir file('src/integrationTest/resources')
        }
    }

    task integrationTest(type:Test) {
        testClassesDir = sourceSets.integrationTest.output.classesDir
        classpath = sourceSets.integrationTest.runtimeClasspath
        outputs.upToDateWhen { false }
    }
}

For executing the tests, this works perfectly well, but it causes problems with IntelliJ's inspections, which may change behavior for test code. IntelliJ does not recognize the source folder as test source.

I tried adding them as such (inside subprojects):

idea {
    module {
        testSourceDirs += file('src/integrationTest/java')
    }
}

but that did not help at all. I also tried manually marking them as test source (context menu -> mark directory as -> test sources root), but IntelliJ quickly overrides that back to normal source root.

How do I configure this correctly in Gradle?

I'm using IntelliJ 2016.1.3 and Gradle 2.14.1 on Ubuntu 16.04

Body:
I know this is old but facing the same problem I found buried somewhere in this jetbrains ticket something hinting that your test sourceSet should be declared in gradle like so :

sourceSets {
    integrationTest {
        test{ //<- note this, this is what flags it right for intelliJ to process it correctly
            java {
                compileClasspath += main.output + test.output
                runtimeClasspath += main.output + test.output
                srcDir file('src/integrationTest/java')
                // note that you'll need to specify the outputDir for it to work
                // I don't fully get the reasons for this (but I rarely do when it comes to gradle anyway)
                outputDir = file("build/classes/java/integrationTest")
            }
            resources {
                srcDir file('src/integrationTest/resources')
            }
        }
    }
}

Doing so made intelliJ instantly recognize my integration-test folder like the test-source it is ...

[Small rant] I could not find trace of the appropriate corresponding gradle doc and as often I find info on how it works from retro-engineering or scarce hints in this case trial/error+ IntelliJ youtrack ticket (which says a lot on how poorly gradle is documented in my view ...)

Note that I am on

Intellij : IntelliJ IDEA 2021.3.2 (Ultimate Edition) Build #IU-213.6777.52

Gradle : 6.7.1


问:
How to run WSL programs within AutoIt?
I'm trying to run a linux console application using AutoIt.
So far I was successful in generating a batch file with the following command:

```<code>wsl /home/ggeorgiev/DD/myprogram --json_file /mnt/c/Users/ggeorgiev/my_input.json
</code>```

This batch runs successfully from cmd, powershell and also when I just double click on it in the explorer. So, I'm thinking that part is okay.

In AutoIt, I'm trying to run the same batch file ("JBDD_start.bat") using the following function:

```<code>Func RunJBDD()

    Local $iPID = Run("cmd.exe " &  "JBDD_start.bat", @WorkingDir, @SW_HIDE, BitOR($STDERR_CHILD, $STDOUT_CHILD,$RUN_CREATE_NEW_CONSOLE ))
    Local $sOutput = ""
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then ; Exit the loop if the process closes or StdoutRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stdout Read:", $sOutput)
    WEnd

    $sOutput = ''
    While 1
        $sOutput &= StderrRead($iPID)
        If @error Then ; Exit the loop if the process closes or StderrRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stderr Read:", $sOutput)
    WEnd
EndFunc
</code>```

It doesn't show anything in the StdErr nor in StdOut message boxes.
Any suggestions on what may have gone wrong or how to find what happens "behind the scenes" are highly appreciated.

答:
Try this, maybe it helps to get your output.</p>
```<code>ConsoleWrite( _getDOSOutput('ping 4.2.2.2') & @CRLF)

Func _getDOSOutput($command)
    Local $text = '', $Pid = Run('"' & @ComSpec & '" /c ' & $command, '', @SW_HIDE, 2 + 4)
    While 1
        $text &= StdoutRead($Pid, False, False)
        If @error Then ExitLoop
        Sleep(10)
    WEnd
    Return $text
EndFunc   ;==>_getDOSOutput
</code>```

Title: How to run WSL programs within AutoIt?

Body:
I'm trying to run a linux console application using AutoIt.
So far I was successful in generating a batch file with the following command:

wsl /home/ggeorgiev/DD/myprogram --json_file /mnt/c/Users/ggeorgiev/my_input.json

This batch runs successfully from cmd, powershell and also when I just double click on it in the explorer. So, I'm thinking that part is okay.

In AutoIt, I'm trying to run the same batch file ("JBDD_start.bat") using the following function:

Func RunJBDD()

    Local $iPID = Run("cmd.exe " &  "JBDD_start.bat", @WorkingDir, @SW_HIDE, BitOR($STDERR_CHILD, $STDOUT_CHILD,$RUN_CREATE_NEW_CONSOLE ))
    Local $sOutput = ""
    While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then ; Exit the loop if the process closes or StdoutRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stdout Read:", $sOutput)
    WEnd

    $sOutput = ''
    While 1
        $sOutput &= StderrRead($iPID)
        If @error Then ; Exit the loop if the process closes or StderrRead returns an error.
            ExitLoop
        EndIf
        MsgBox($MB_SYSTEMMODAL, "Stderr Read:", $sOutput)
    WEnd
EndFunc

It doesn't show anything in the StdErr nor in StdOut message boxes.
Any suggestions on what may have gone wrong or how to find what happens "behind the scenes" are highly appreciated.

Body:
Try this, maybe it helps to get your output.

ConsoleWrite( _getDOSOutput('ping 4.2.2.2') & @CRLF)

Func _getDOSOutput($command)
    Local $text = '', $Pid = Run('"' & @ComSpec & '" /c ' & $command, '', @SW_HIDE, 2 + 4)
    While 1
        $text &= StdoutRead($Pid, False, False)
        If @error Then ExitLoop
        Sleep(10)
    WEnd
    Return $text
EndFunc   ;==>_getDOSOutput


问:
How to select an option in MUI select list with jest?
I have a Material UI select component id like to automate tests with jest. Is it possible to select an option within a list selector Material UI component and have the option populate its value confirmably in jest? I am unable to find any reliable method or information on how to do this.</p>

答:
In MUI library all input components have a property called inputProps.
This property is forwarded to the html <input /> at the end of the tree. So you can pass a property that identifies the input so you can use it to find and interact with it.


问:
How do I get the RAM manufacturer on MacOS using Python 3?
I'm working on a benchmarking application, and I thought it would be useful if users could see the manufacturer of their RAM. I came across this post: Get ram manufacturer, which was very helpful for finding the manufacturer on Windows. However, it didn't answer the question of how I would get the manufacturer of RAM on MacOS.

I came across many libraries for finding system information, such as psutil and system-info. However, none of the libraries I found could find the manufacturer of RAM on MacOS.

I also tried running system_profiler SPHardwareDataType from Python, but that only returns information for the amount of memory installed, not the manufacturer of the memory.

However, I do see that in the "System Information" application on MacOS, you can view the manufacturer of your RAM, as shown in this screenshot: https://i.imgur.com/VeieDsT.png. But that still doesn't solve the problem of how I would get the manufacturer from that application into Python.

Any help would be appreciated. Thanks in advance!

答:
system_profiler SPMemoryDataType should have the info you need.

Here's the output on my machine, that matches the screenshot you provided, but that you can easily parse.

```<code>Memory:

    Memory Slots:

      ECC: Disabled
      Upgradeable Memory: No

        BANK 0/ChannelA-DIMM0:

          Size: 16 GB
          Type: DDR4
          Speed: 2400 MHz
          Status: OK
          Manufacturer: Micron
          Part Number: 16ATS2G64HZ-2G6B1
          Serial Number: -

        BANK 2/ChannelB-DIMM0:

          Size: 16 GB
          Type: DDR4
          Speed: 2400 MHz
          Status: OK
          Manufacturer: Micron
          Part Number: 16ATS2G64HZ-2G6B1
          Serial Number: -
</code>```

Body:
system_profiler SPMemoryDataType should have the info you need.

Here's the output on my machine, that matches the screenshot you provided, but that you can easily parse.

Memory:

    Memory Slots:

      ECC: Disabled
      Upgradeable Memory: No

        BANK 0/ChannelA-DIMM0:

          Size: 16 GB
          Type: DDR4
          Speed: 2400 MHz
          Status: OK
          Manufacturer: Micron
          Part Number: 16ATS2G64HZ-2G6B1
          Serial Number: -

        BANK 2/ChannelB-DIMM0:

          Size: 16 GB
          Type: DDR4
          Speed: 2400 MHz
          Status: OK
          Manufacturer: Micron
          Part Number: 16ATS2G64HZ-2G6B1
          Serial Number: -


问:
is there a way to link equal type definitions together?
example code:

```<code><xsd:element name="a">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>
<xsd:element name="b">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>
</code>```

Now the type definition of element a and b are the same. is there a way to "link" those types together so that i do not have to repeat the typing?

答:
Ok, I see. The easiest way to go is to create a named type:

```<code><xsd:simpleType name="PatternType">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})" />
    </xsd:restriction>
</xsd:simpleType>

<xsd:element name="a" type="tns:PatternType" />
<xsd:element name="b" type="tns:PatternType" />
</code>```

where tns is a prefix for your schema target namespace

Body:
example code:

<xsd:element name="a">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>
<xsd:element name="b">
    <xsd:simpleType>
        <xsd:restriction base="xsd:string">
            <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})"/>
        </xsd:restriction>
    </xsd:simpleType>
</xsd:element>

Now the type definition of element a and b are the same. is there a way to "link" those types together so that i do not have to repeat the typing?

Body:
Ok, I see. The easiest way to go is to create a named type:

<xsd:simpleType name="PatternType">
    <xsd:restriction base="xsd:string">
        <xsd:pattern value="|(([1-9]|[12][0-9]|3[01])/([0-9]|1[12])/[0-9]{1,4})" />
    </xsd:restriction>
</xsd:simpleType>

<xsd:element name="a" type="tns:PatternType" />
<xsd:element name="b" type="tns:PatternType" />

where tns is a prefix for your schema target namespace


问:
How to search for a string with one double quote with git grep in Windows cmd
The problem is that strings with two qoutes are searched well. But! I want to look for a string "Agent (one double quote!) inside my repo on cmd in Windows. So I having this:

git grep "\"Agent\"" > 1.txt (it works! all strings with "Agent" was found)

git grep "\"Agent" > 1.txt (error! fatal: ambiguous argument '>': unknown revision...)

Any ideas how to properly escape?

答:
Interesting so here are my findings in CMD and Git Bash if you will use just one quote whether it is a single quote or double quote the command will break and bash will intercept it as 2 different commands. This is not only in the case of git grep but an echo will also have the same behavior.

Here you can see that I'm using syntax similar to yours in echo and it's not writing into the file just printing the next whole line

Now when I have added the closing quotes echo is working perfectly and writing into the file.

Now if you want to print a single quote you would have to use double quotes as starting and ending quotes and vice versa. click here for reference.

Now according to this documentation, wrapping a single quote in double-quotes works and this works in the case of grep as well.

But its reverse (wrapping double quotes in single quotes) doesn't work in windows CMD this might be because bash is intercepting double quotes ("). But you can use git bash and below will work properly.


问:
infinitetly loop array with setTimeout javascript
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

```<code>if (x == links.length) { loopUrls() }
</code>```

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

```<code>        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();
</code>```

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

答:
a way to do that :</p>
```<code>// const links = [ ... ]

const myImg = document.queryselector('#ifURLS')

function LoadImg()
  {
  let
    indx = 0
  , let refIntv =
      setInterval( ()=>
        {
        myImg.src = links[indx++]

        if (indx >= links.length)
          clearInterval( refIntv )
        }
        , 5000 )  // 5s delay
  }
</code>```

Body:
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

if (x == links.length) { loopUrls() }

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

Body:
a way to do that :

// const links = [ ... ]

const myImg = document.queryselector('#ifURLS')

function LoadImg()
  {
  let
    indx = 0
  , let refIntv =
      setInterval( ()=>
        {
        myImg.src = links[indx++]

        if (indx >= links.length)
          clearInterval( refIntv )
        }
        , 5000 )  // 5s delay
  }


问:
How to determine which cubes the line passes through
I was looking for a way to build cubes of the same size, then draw a line through this space and output the result in the form of coordinates of cubes that this line intersects and paint these cubes with a different color. The line can be either straight or curved.

I used matplotlib to plot cubes and lines. From these sources:

https://www.geeksforgeeks.org/how-to-draw-3d-cube-using-matplotlib-in-python/

Representing voxels with matplotlib

Example code:

```<code>from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

axes = [5, 5, 5]

# Create Data
data = np.ones(axes, dtype=np.bool)

# Controll Tranperency
alpha = 0.3

# Control colour
colors = np.empty(axes + [4], dtype=np.float32)

colors[0] = [1, 0, 0, alpha]  # red
colors[1] = [0, 1, 0, alpha]  # green
colors[2] = [0, 0, 1, alpha]  # blue
colors[3] = [1, 1, 0, alpha]  # yellow
colors[4] = [1, 1, 1, alpha]  # grey

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x1 = [1, 4]
y1 = [0, 5]
z1 = [0, 5]

ax.plot3D(x1, y1, z1, 'black', linewidth = 5)

# Voxels is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')
</code>```

result

In short: I need to plot a grid of cubes and draw a line through it. After determine which cubes this line intersects.

Is it possible to do this in Matplotlib or do I need to use another library to solve my question?

答:
God, why do I put myself though this.

Anyways, here is an iterative solution because I do not feel like doing linear algebra. I tried and I failed.

```<code># Here be dragons
def linelamb(x,y,z):
    return lambda s: [int(i) for i in [x[0]+s*(x[1]-x[0]), y[0]+s*(y[1]-y[0]), z[0]+s*(z[1]-z[0])]]

line = linelamb(x1,y1,z1)

hitboxes = np.zeros(axes)

x,y,z = 0,0,0

for r in [i for i in np.arange(0,1,0.001)]:
    xnew,ynew,znew = line(r)
    if not (x == xnew and y == ynew and z == znew):
        hitboxes[xnew,ynew,znew] = 1
    x,y,z = xnew,ynew,znew

ax.voxels(hitboxes, facecolors=[0,0,0,0.5], edgecolors='black');
</code>```

I spent some extra time to make this more adaptable but my brain stopped working. You might want to adaptively change the step size of the range but good luck.

Body:
I was looking for a way to build cubes of the same size, then draw a line through this space and output the result in the form of coordinates of cubes that this line intersects and paint these cubes with a different color. The line can be either straight or curved.

I used matplotlib to plot cubes and lines. From these sources:

https://www.geeksforgeeks.org/how-to-draw-3d-cube-using-matplotlib-in-python/

Representing voxels with matplotlib

Example code:

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

axes = [5, 5, 5]

# Create Data
data = np.ones(axes, dtype=np.bool)

# Controll Tranperency
alpha = 0.3

# Control colour
colors = np.empty(axes + [4], dtype=np.float32)

colors[0] = [1, 0, 0, alpha]  # red
colors[1] = [0, 1, 0, alpha]  # green
colors[2] = [0, 0, 1, alpha]  # blue
colors[3] = [1, 1, 0, alpha]  # yellow
colors[4] = [1, 1, 1, alpha]  # grey

# Plot figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x1 = [1, 4]
y1 = [0, 5]
z1 = [0, 5]

ax.plot3D(x1, y1, z1, 'black', linewidth = 5)

# Voxels is used to customizations of
# the sizes, positions and colors.
ax.voxels(data, facecolors=colors, edgecolors='grey')

result

In short: I need to plot a grid of cubes and draw a line through it. After determine which cubes this line intersects.

Is it possible to do this in Matplotlib or do I need to use another library to solve my question?

Body:
God, why do I put myself though this.

Anyways, here is an iterative solution because I do not feel like doing linear algebra. I tried and I failed.

# Here be dragons
def linelamb(x,y,z):
    return lambda s: [int(i) for i in [x[0]+s*(x[1]-x[0]), y[0]+s*(y[1]-y[0]), z[0]+s*(z[1]-z[0])]]

line = linelamb(x1,y1,z1)

hitboxes = np.zeros(axes)

x,y,z = 0,0,0

for r in [i for i in np.arange(0,1,0.001)]:
    xnew,ynew,znew = line(r)
    if not (x == xnew and y == ynew and z == znew):
        hitboxes[xnew,ynew,znew] = 1
    x,y,z = xnew,ynew,znew

ax.voxels(hitboxes, facecolors=[0,0,0,0.5], edgecolors='black');

I spent some extra time to make this more adaptable but my brain stopped working. You might want to adaptively change the step size of the range but good luck.


问:
How do I modify a realm object without getting these error messages?
I have a small Xcode project in Swift 5. It is a simple NotePad type app which has categories of notes so for example you could have a category of Home with an associated list of notes relevant to the home. I am having trouble modifying one of the notes of the associated category using Realm. I have tried placing the modification code inside a realm.write closure but I get the error message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'The Realm is already in a write transaction'

When I remove the realm.write I get a different message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

What's going on and how can I modify a note and update the realm database?

```<code>import RealmSwift

class NotePadListViewController: UITableViewController {

    var noteArray: Results<Note>?
    let realm = try! Realm()

    var selectedCategory: Category? {
        didSet {
            loadItems()
        }
    }

//    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.autocapitalizationType = .none

//        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

    }

    // MARK: TableView Datasource Methods

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return noteArray?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)

        cell.textLabel?.text = noteArray?[indexPath.row].title ?? "No Notes Added."

        return cell
    }

    // MARK: TableView Delegate Methods

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = noteArray?[indexPath.row]
        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if let note = noteArray?[indexPath.row] {

            if editingStyle == .delete {
                do {
                    try realm.write {
                        realm.delete(note)
                        tableView.deleteRows(at: [indexPath], with: .fade)
                    }
                } catch {
                    print("Error deleting note: \(error)")
                }
            }
        }
    }

    // MARK: - Add new note

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = nil

        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    func loadItems() {

        noteArray = selectedCategory?.notes.sorted(byKeyPath: "title", ascending: true)

        tableView.reloadData()
    }
}

// MARK: - Create Note View Protocol

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {

        if let currentCategory = selectedCategory {

            if note.row == -1 {

                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }

            }
        }

        tableView.reloadData()
    }
}

// MARK: - SearchBar delegate methods

extension NotePadListViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        noteArray = noteArray?.filter("title CONTAINS[cd] %@ ", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)

        tableView.reloadData()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchText == "" {
            loadItems()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
    }
}
</code>```
```<code>import UIKit
import RealmSwift

protocol CreateNoteViewProtocol: AnyObject {
    func send(note: Note)
}

class CreateNoteView: UIView, UITextViewDelegate, UITextFieldDelegate {

    var savedNote: Note? {
        didSet {
            if savedNote == nil {
                noteTitle.text = "Note title"
                noteTitle.textColor = UIColor.lightGray
                noteContent.text = "Type something interesting..."
                noteContent.textColor = UIColor.lightGray
            } else {
                noteTitle.text = savedNote!.title
                noteTitle.textColor = UIColor.black
                noteContent.text = savedNote!.content
                noteContent.textColor = UIColor.black
            }
        }
    }

    @IBOutlet weak var noteTitle: UITextField!
    @IBOutlet weak var noteContent: UITextView!

    weak var delegate: CreateNoteViewProtocol!

    let realm = try! Realm()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        noteTitle.delegate = self
        noteContent.delegate = self
    }

    func commonInit() {

        let viewFromXib = Bundle.main.loadNibNamed("CreateNoteView", owner: self, options: nil)![0] as! UIView
        viewFromXib.frame = self.bounds
        addSubview(viewFromXib)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @IBAction func cancelButtonTapped(_ UIButton: Any) {
        self.removeFromSuperview()
    }

    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            existingNote.title = noteTitle.text ?? "No Title"
            existingNote.content = noteContent.text
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.textColor == UIColor.lightGray {
            textField.text = nil
            textField.textColor = UIColor.black
        }
    }
}
</code>```
```<code>import Foundation
import RealmSwift

class Note: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var content: String = ""
    @objc dynamic var row: Int = 0
    @objc dynamic var dateCreated: Date = Date()
    var parentCategory = LinkingObjects(fromType: Category.self, property: "notes")
}
</code>```
```<code>import Foundation
import RealmSwift

class Category: Object {
    @objc dynamic var name: String = ""
    let notes = List<Note>()
}```

```

答:
It works now when I have the following code in CreateNoteView;</p>
```<code>    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            try! realm.write {
                existingNote.title = noteTitle.text ?? "No Title"
                existingNote.content = noteContent.text
            }
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }
</code>```

Body:
I have a small Xcode project in Swift 5. It is a simple NotePad type app which has categories of notes so for example you could have a category of Home with an associated list of notes relevant to the home. I am having trouble modifying one of the notes of the associated category using Realm. I have tried placing the modification code inside a realm.write closure but I get the error message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'The Realm is already in a write transaction'

When I remove the realm.write I get a different message;

*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

What's going on and how can I modify a note and update the realm database?

import RealmSwift

class NotePadListViewController: UITableViewController {

    var noteArray: Results<Note>?
    let realm = try! Realm()

    var selectedCategory: Category? {
        didSet {
            loadItems()
        }
    }

//    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    @IBOutlet weak var searchBar: UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()

        searchBar.autocapitalizationType = .none

//        print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask))

    }

    // MARK: TableView Datasource Methods

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return noteArray?.count ?? 1
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)

        cell.textLabel?.text = noteArray?[indexPath.row].title ?? "No Notes Added."

        return cell
    }

    // MARK: TableView Delegate Methods

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = noteArray?[indexPath.row]
        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

        if let note = noteArray?[indexPath.row] {

            if editingStyle == .delete {
                do {
                    try realm.write {
                        realm.delete(note)
                        tableView.deleteRows(at: [indexPath], with: .fade)
                    }
                } catch {
                    print("Error deleting note: \(error)")
                }
            }
        }
    }

    // MARK: - Add new note

    @IBAction func addButtonPressed(_ sender: UIBarButtonItem) {

        let createNoteView = CreateNoteView(frame: CGRect(x: (self.view.frame.width - 240.0)/2.0, y: (self.view.frame.height - 300.0)/2.0, width: 240.0, height: 300.0))

        createNoteView.savedNote = nil

        view.addSubview(createNoteView)

        createNoteView.delegate = self

    }

    func loadItems() {

        noteArray = selectedCategory?.notes.sorted(byKeyPath: "title", ascending: true)

        tableView.reloadData()
    }
}

// MARK: - Create Note View Protocol

extension NotePadListViewController: CreateNoteViewProtocol {

    func send(note: Note) {

        if let currentCategory = selectedCategory {

            if note.row == -1 {

                note.row = noteArray?.count ?? 0
                do {
                    try! realm.write {
                        currentCategory.notes.append(note)
                    }
                }
            } else {
                do {
                    try! realm.write {
                        let row = note.row
                        currentCategory.notes[row] = note
                    }
                }

            }
        }

        tableView.reloadData()
    }
}

// MARK: - SearchBar delegate methods

extension NotePadListViewController: UISearchBarDelegate {

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

        noteArray = noteArray?.filter("title CONTAINS[cd] %@ ", searchBar.text!).sorted(byKeyPath: "dateCreated", ascending: true)

        tableView.reloadData()
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchText == "" {
            loadItems()
            DispatchQueue.main.async {
                searchBar.resignFirstResponder()
            }
        }
    }
}

import UIKit
import RealmSwift

protocol CreateNoteViewProtocol: AnyObject {
    func send(note: Note)
}

class CreateNoteView: UIView, UITextViewDelegate, UITextFieldDelegate {

    var savedNote: Note? {
        didSet {
            if savedNote == nil {
                noteTitle.text = "Note title"
                noteTitle.textColor = UIColor.lightGray
                noteContent.text = "Type something interesting..."
                noteContent.textColor = UIColor.lightGray
            } else {
                noteTitle.text = savedNote!.title
                noteTitle.textColor = UIColor.black
                noteContent.text = savedNote!.content
                noteContent.textColor = UIColor.black
            }
        }
    }

    @IBOutlet weak var noteTitle: UITextField!
    @IBOutlet weak var noteContent: UITextView!

    weak var delegate: CreateNoteViewProtocol!

    let realm = try! Realm()

    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
        noteTitle.delegate = self
        noteContent.delegate = self
    }

    func commonInit() {

        let viewFromXib = Bundle.main.loadNibNamed("CreateNoteView", owner: self, options: nil)![0] as! UIView
        viewFromXib.frame = self.bounds
        addSubview(viewFromXib)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @IBAction func cancelButtonTapped(_ UIButton: Any) {
        self.removeFromSuperview()
    }

    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            existingNote.title = noteTitle.text ?? "No Title"
            existingNote.content = noteContent.text
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }

    func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.textColor == UIColor.lightGray {
            textView.text = nil
            textView.textColor = UIColor.black
        }
    }

    func textFieldDidBeginEditing(_ textField: UITextField) {
        if textField.textColor == UIColor.lightGray {
            textField.text = nil
            textField.textColor = UIColor.black
        }
    }
}

import Foundation
import RealmSwift

class Note: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var content: String = ""
    @objc dynamic var row: Int = 0
    @objc dynamic var dateCreated: Date = Date()
    var parentCategory = LinkingObjects(fromType: Category.self, property: "notes")
}

import Foundation
import RealmSwift

class Category: Object {
    @objc dynamic var name: String = ""
    let notes = List<Note>()
}```

Body:
It works now when I have the following code in CreateNoteView;

    @IBAction func saveButtonTapped(_ UIButton: Any) {

        if let existingNote = savedNote {

            try! realm.write {
                existingNote.title = noteTitle.text ?? "No Title"
                existingNote.content = noteContent.text
            }
            delegate.send(note: existingNote)

        } else {

            let note = Note()
            note.title = noteTitle.text ?? "No Title"
            note.content = noteContent.text
            note.row = -1
            note.dateCreated = Date()
            delegate.send(note: note)

        }

        self.removeFromSuperview()
    }


问:
How to check the sub string is exists or not in main string
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

```<code>$a = 'Hello world';
$b = 'Hello';
</code>```

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).

答:
You are looking for strpos function

remember to use === instead of ==

Body:
Is there any way to check the sub string is exists in main string or not. If exits, no need any another action. If not exists, I want to add some another string to main string.

For an example:

$a = 'Hello world';
$b = 'Hello';

I want to check the $b is exists in $a or not. If exists, i am sending that variable to database. If not exists, I want to use str_replace('Hello', $b.'World', $b).


问:
Hide a Form tab depending on the value of a field
pretty simple question here in scope.

Question:
Wondering If I would be able to hide the tabs of a form based off the values of a table's fields.

I have been reading the 2019 Access Bible and so far it is still unclear to me how I would write the VBA module to constantly be running. Im asking the question a little early in my attempts, but hoping I can ask this well enough to get a head start.

I dont quite understand the execution model of VBA for access yet. I have prior expierence coding but this will be my 1st time in access. Just looking for a little help on how to write the function scope. You see below that I think it should be "Main" something, as I want it to run whenever in form view. Like I know how to write Private sub functions to respond to a button click. But not for a function that just runs in the background of the form.

I guess the real question is when to execute? Right? Any suggestions?

I was thinking something along the line of this below.

```<code>Main function()
If Me.FieldProcess_Water = "1" Then
Me.TabProcess_Water.Visible = True
Else
Me.TabProcess_Water.Visible  = False
End If
End Sub
</code>```

答:
This requires some setup to reduce redundant code but should do what you want.

First you'll need your checkbox names and page names to be similar. In my example I have the page names as Tab_Name and the checkboxes as just Name. eg. Tab_Process Water and Process Water.

Then Create a sub called Form_Current() in the form's code-behind.

```<code>Private Sub Form_Current()
    Dim chk As Control

    For Each chk In Me.Controls
        If chk.ControlType = acCheckBox Then
            If chk = False Then
               'Change TabCtl0 to whatever your's is called
                Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = False
            Else
                Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = True
            End If
        End If
    Next

End Sub
</code>```

This will iterate through the current record's checkboxes and toggle it's respective tab's visibility.

To have the CheckBox update the tabs as they are clicked:

```<code>Private Sub Form_Load()
    Dim chk As Control
    Dim prop As Variant
    For Each chk In Me.Controls
        If chk.ControlType = acCheckBox Then
           chk.OnClick = "=Check_Click()"
        End If
    Next
End Sub
</code>```

This will assign a command to each checkbox.

```<code>    Dim caller As String
    caller = Me.ActiveControl.Name
    If Me.ActiveControl.Value = False Then
        Me.TabCtl0.Pages("Tab_" & caller).Visible = False
    Else
        Me.TabCtl0.Pages("Tab_" & caller).Visible = True
    End If
</code>```

This will hide the relevant tabs.

Body:
pretty simple question here in scope.

Question:
Wondering If I would be able to hide the tabs of a form based off the values of a table's fields.

I have been reading the 2019 Access Bible and so far it is still unclear to me how I would write the VBA module to constantly be running. Im asking the question a little early in my attempts, but hoping I can ask this well enough to get a head start.

I dont quite understand the execution model of VBA for access yet. I have prior expierence coding but this will be my 1st time in access. Just looking for a little help on how to write the function scope. You see below that I think it should be "Main" something, as I want it to run whenever in form view. Like I know how to write Private sub functions to respond to a button click. But not for a function that just runs in the background of the form.

I guess the real question is when to execute? Right? Any suggestions?

I was thinking something along the line of this below.

Main function()
If Me.FieldProcess_Water = "1" Then
Me.TabProcess_Water.Visible = True
Else
Me.TabProcess_Water.Visible  = False
End If
End Sub

Body:
This requires some setup to reduce redundant code but should do what you want.

First you'll need your checkbox names and page names to be similar. In my example I have the page names as Tab_Name and the checkboxes as just Name. eg. Tab_Process Water and Process Water.

Then Create a sub called Form_Current() in the form's code-behind.

Private Sub Form_Current()
    Dim chk As Control

    For Each chk In Me.Controls
        If chk.ControlType = acCheckBox Then
            If chk = False Then
               'Change TabCtl0 to whatever your's is called
                Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = False
            Else
                Me.TabCtl0.Pages("Tab_" & chk.Name).Visible = True
            End If
        End If
    Next

End Sub

This will iterate through the current record's checkboxes and toggle it's respective tab's visibility.

To have the CheckBox update the tabs as they are clicked:

Private Sub Form_Load()
    Dim chk As Control
    Dim prop As Variant
    For Each chk In Me.Controls
        If chk.ControlType = acCheckBox Then
           chk.OnClick = "=Check_Click()"
        End If
    Next
End Sub

This will assign a command to each checkbox.

    Dim caller As String
    caller = Me.ActiveControl.Name
    If Me.ActiveControl.Value = False Then
        Me.TabCtl0.Pages("Tab_" & caller).Visible = False
    Else
        Me.TabCtl0.Pages("Tab_" & caller).Visible = True
    End If

This will hide the relevant tabs.


问:
Vercel ignore build step according to folder of committed files
i'm using vercel's ignore build step field to disable preview deploys (IE - only deploy if the branch is main)

I'm doing this with the following bash script:

```<code>if [[ "$VERCEL_GIT_COMMIT_REF" == "main" ]] ; then
  # Proceed with the build
    echo "✅ - Build can proceed"
  exit 1;
else
  # Don't build
  echo " - Build canceled"
  exit 0;
fi
</code>```

Now, another requirement I have is to only deploy if the changed files belong to a specific folder. Can I somehow combine these two requirements in the same script?

How do I access the paths of the committed files in this bash script?

Thanks!

答:
Vercel has added some docs that address this exact situation:

```<code>git diff HEAD^ HEAD --quiet ./packages/frontend/
</code>```

If changes were commited to ./packages/frontend/, the command will yield a non-empty response, allowing the build to proceed.

I also use a similar setup, but call a node script (check it out here) as my Ignored Build Step option.

Body:
i'm using vercel's ignore build step field to disable preview deploys (IE - only deploy if the branch is main)

I'm doing this with the following bash script:

if [[ "$VERCEL_GIT_COMMIT_REF" == "main" ]] ; then
  # Proceed with the build
    echo "✅ - Build can proceed"
  exit 1;
else
  # Don't build
  echo " - Build canceled"
  exit 0;
fi

Now, another requirement I have is to only deploy if the changed files belong to a specific folder. Can I somehow combine these two requirements in the same script?

How do I access the paths of the committed files in this bash script?

Thanks!

Body:
Vercel has added some docs that address this exact situation:

git diff HEAD^ HEAD --quiet ./packages/frontend/

If changes were commited to ./packages/frontend/, the command will yield a non-empty response, allowing the build to proceed.

I also use a similar setup, but call a node script (check it out here) as my Ignored Build Step option.


问:
How to refactor code using if condition in javascript?
i have code like below,

```<code>React.useMemo(() => {
    if (isInProgress && data && data.Run) {
        if (data.Run.partial === true) { //how can i rewrite this
            setIsRunPartial(true);
        }
        else {
            setIsRunPartial(false);
        }
    }

}, [data, isInProgress]);
</code>```

here the data.Run.partial can be undefined true or false. how can rewrite above code to look clean. i have to call setIsRunPartial to true if data.Run.partial is true and false if data.Run.partial is false.

how can rewrite above code. could someone help me with this. thanks.

答:
You could just take the value, if you have already a boolean type.</p>
```<code>setIsRunPartial(data.Run.partial);
</code>```

Body:
i have code like below,

React.useMemo(() => {
    if (isInProgress && data && data.Run) {
        if (data.Run.partial === true) { //how can i rewrite this
            setIsRunPartial(true);
        }
        else {
            setIsRunPartial(false);
        }
    }

}, [data, isInProgress]);

here the data.Run.partial can be undefined true or false. how can rewrite above code to look clean. i have to call setIsRunPartial to true if data.Run.partial is true and false if data.Run.partial is false.

how can rewrite above code. could someone help me with this. thanks.

Body:
You could just take the value, if you have already a boolean type.

setIsRunPartial(data.Run.partial);