问:
How to click on the list of items in protractor
HTML code

```<code><li class="active-result result-selected group-option" data-option-array-index="72">Information Technology and Services</li>
</code>```

While doing automation testing in protractor am not able to click on the particular list item. Using xpath, I can click the list item but without using xpath i have to do.

Please help me.

答:
Use this method will click the element in list

```<code>  clickElementInList: function (list, item) {
        list.reduce((result, element) => {
            if (result) return result;
            return element.getText().then((text) => {
                if (text.toLowerCase().includes(item.toLowerCase())) return element;
            });
        }).then((element_found) => {
            if (!element_found) throw new Error(item + " not found");
            this.click(element_found);
        });
    },
</code>```

Body:
HTML code

Information Technology and Services

While doing automation testing in protractor am not able to click on the particular list item. Using xpath, I can click the list item but without using xpath i have to do.

Please help me.

Body:
Use this method will click the element in list

  clickElementInList: function (list, item) {
        list.reduce((result, element) => {
            if (result) return result;
            return element.getText().then((text) => {
                if (text.toLowerCase().includes(item.toLowerCase())) return element;
            });
        }).then((element_found) => {
            if (!element_found) throw new Error(item + " not found");
            this.click(element_found);
        });
    },


来源: stackexchange

问:
Why does the While loop inside the QT loop is not blocking the QT GUI
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

```<code>int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();
</code>```

}

答:
You're not using QApplication event pump at all, you  short-circuited on Moodle\glfw\Wavefront library event loop.

Qt's OpenGl support via QOpenGLWidget directly works with paintGL method which ought to perform all rendering and which is called from inside of event loop. If you're not using that, you'll have somehow combine two threads, which is problematic that both OpenGL pipeline and Qt main loop on some platforms are limited to be usable ONLY in main thread.

ContentLicense: CC BY-SA 4.0

Body:
I am using GLFW along with QT for an opengl application.

i have a while loop inside the main function.

Why the while loop is not blocking the QT GUI ?

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    cont.SetName("RootItem");
    TreeModel* model = new TreeModel("RootElement", &cont);
    WavefrontRenderer w(model);
    w.show();
    glfwInit();
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_SAMPLES, 4);
    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Renderer", nullptr, nullptr);   //
    glfwMakeContextCurrent(window);
    GLenum GlewInitResult;
    glewExperimental = GL_TRUE;
    GlewInitResult = glewInit();

    w.InitData();

    while (!glfwWindowShouldClose(window))
    {
        glClearColor(0.0, 0.3, 0.3, 0.0);
        glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
        w.render();
        glfwPollEvents();
        glfwSwapBuffers(window);
    }
    // glfw: terminate, clearing all previously allocated GLFW resources.
    // ------------------------------------------------------------------
    glfwTerminate();
    //return 0;

    return a.exec();

}


问:
T SQL days or hours or minutes left until specific schedule start day and time
I have an XML that has multiple schedules. I need help to show from the current day (Example: Monday, 14:00:03) how many days or hours or minutes left until a specific schedule [Sched 1 AT] or [Sched 2 AT] time start and day [Sched 1 Weekdays] or [Sched 1 Weekdays] in a separate column [TimeLeft].
Schedules I have, run:

daily

once a week on Sunday or Saturday

once every 2 weeks on Sunday or Saturday

My XML is and the query:

create table MyTable (Roles XML)
insert into MyTable values
('<registered guid="{B40F5E54-21D0-4EDB-B636-B2F9EE30CCDE}">
  <schedule tz="Local" start="2007-11-01 00:00:00">
      <trigger type="MonthlyByWeek" exact="False" at="18:05:00" weeks="2" weekdays="6" description="Every 2nd Saturday" />
      <trigger type="MonthlyByWeek" exact="False" at="00:05:00" weeks="2" weekdays="0" description="Every 2nd Sunday" />
    <modifier type="Network" />
  </schedule>
</registered>

<registered guid="{A4465325-926A-48FA-B11E-D6E486D76D93}">
  <schedule tz="Local" start="2009-11-11 00:00:00">
 <trigger type="Weekly" exact="True" at="00:05:00" frequency="1" weekdays="0" description="Weekly on Sunday" />
 <trigger type="Weekly" exact="True" at="04:05:00" frequency="1" weekdays="0" description="Weekly on Sunday" />
 <modifier type="Network" />
  </schedule>
</registered>

<registered guid="{3DE26049-74E7-4FE3-9E47-CF022A6F7923}">
  <schedule tz="Local" start="2011-11-11 00:00:00">
      <trigger type="Weekly" exact="True" at="00:07:30" frequency="1" weekdays="1, 2, 3, 4, 5, 6" description="Daily" />
      <modifier type="Network" />
  </schedule>
</registered>')

SELECT T.Schedule.query('.') AS Schedule,
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@type)[1]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@type)[1]', 'nvarchar(100)')
  END [Sched 1 When],
    CASE
  WHEN T.Schedule.value('(schedule/trigger/@at)[1]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@at)[1]', 'nvarchar(100)')
  END [Sched 1 AT],
       -- Week Start Sunday
       -- Sunday = 0
       -- Monday = 1
       -- Tuesday = 2
       -- Wednesday = 3
       -- Thursday = 4
       -- Friday = 5
       -- Saturday = 6
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@frequency)[1]', 'nvarchar(100)') LIKE '%1%'
  THEN 'Once'
  WHEN T.Schedule.value('(schedule/trigger/@frequency)[1]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE 'Unknown'
    END [Sched 1 Frequency],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@description)[1]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@description)[1]', 'nvarchar(100)')
    END [Sched 1 Description],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[1]', 'nvarchar(100)') = '1, 2, 3, 4, 5, 6'
  THEN 'Mon, Tue, Wend, Thu, Fri, Sat'
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[1]', 'nvarchar(100)') LIKE '%0%'
  THEN 'Sun'
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[1]', 'nvarchar(100)') LIKE '%6%'
  THEN 'Sat'
  ELSE 'Unknown'
    END [Sched 1 Weekdays],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@type)[2]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@type)[2]', 'nvarchar(100)')
  END [Sched 2 When],
    CASE
  WHEN T.Schedule.value('(schedule/trigger/@at)[2]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@at)[2]', 'nvarchar(100)')
  END [Sched 2 AT],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@frequency)[2]', 'nvarchar(100)') LIKE '%1%'
  THEN 'Once'
  WHEN T.Schedule.value('(schedule/trigger/@frequency)[2]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE 'Unknown'
    END [Sched 2 Frequency],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@description)[2]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE T.Schedule.value('(schedule/trigger/@description)[2]', 'nvarchar(100)')
    END [Sched 2 Description],
       CASE
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[2]', 'nvarchar(100)') = '1, 2, 3, 4, 5, 6'
  THEN 'Mon, Tue, Wend, Thu, Fri, Sat'
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[2]', 'nvarchar(100)') LIKE '%0%'
  THEN 'Sun'
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[2]', 'nvarchar(100)') LIKE '%6%'
  THEN 'Sat'
  WHEN T.Schedule.value('(schedule/trigger/@weekdays)[2]', 'nvarchar(100)') IS NULL
  THEN 'None'
  ELSE 'Unknown'
    END [Sched 2 Weekdays]
FROM
( SELECT CAST(Roles AS XML) as [State] from Mytable
) x
CROSS APPLY x.State.nodes('/registered') AS T(Schedule)```

答:
```<code>declare @checkdatetime datetime = '20200216 10:00:00';

select *, datediff(minute, @checkdatetime, o.execdatetime) as minutes_till_next_execution
from
(
    select *,
    row_number() over(partition by Scheduleguid, TrigAt /*?*/ order by execdatetime) as execrownum
    from
    (
        select
            sch.*,
            --possible execution datetime
            dateadd(day, d.n,
                dateadd(month, isnull(m.n, 0),
                --datetimefromparts(.....)
                cast(cast(year(@checkdatetime) as varchar(20)) + right('00'+cast(month(@checkdatetime) as varchar(20)), 2) + '01 ' + TrigAt  as datetime)
            )) as execdatetime
        from
        --shred xml
        (
            select
                T.Schedule.value('(@guid)[1]', 'uniqueidentifier') AS Scheduleguid,
                dense_rank() over(order by T.Schedule) as ScheduleOrdinal, --position
                S.Trig.value('(@type)[1]', 'nvarchar(100)') as TrigType,
                S.Trig.value('(@at)[1]', 'nvarchar(100)') as TrigAt,
                S.Trig.value('(@weeks)[1]', 'tinyint') as MonthWeekFrequency,
                S.Trig.value('(@frequency)[1]', 'tinyint') as TrigFrequency,
                S.Trig.value('(@description)[1]', 'nvarchar(100)') as TrigDescription,
                S.Trig.value('(@weekdays)[1]', 'varchar(20)') as TrigWeekdays,
                cast(ltrim(rtrim(ss.value)) as tinyint) as triggerweekday
            FROM Mytable as x
            cross apply x.Roles.nodes('./registered[position() <= 100]') AS T(Schedule) --position() to filter schedules in xml (first 2, 3, 100 schedules etc)
            cross apply T.Schedule.nodes('./schedule/trigger') AS S(Trig)
            cross apply string_split(S.Trig.value('(@weekdays)[1]', 'varchar(20)'), ',') as ss --split weekdays of trigger
        ) as sch
        --lazy brute force
        --days
        cross apply
        (
            --31 values for days in a month
            select top (31) row_number() over(order by (select null)) as n
            from
            (values(0), (0), (0), (0), (0), (0)) as num1(n)
            cross join
            (values(0), (0), (0), (0), (0), (0)) as num2(n)
        ) as d
        --months
        outer apply
        (
            --2 values for current and next month
            select n
            from (values(0), (1)) as num(n)
            where sch.MonthWeekFrequency is not null
        ) as m
    ) as ex
    where 1=1
    -- execution dates which are eq or greater than @check
    and @checkdatetime  <= ex.execdatetime
    -- execution dates of the same trigweekday
    and ex.triggerweekday = datepart(weekday, dateadd(day, @@datefirst, ex.execdatetime))-1
    --execution dates on the same week number
    and
    (
      ex.MonthWeekFrequency is null
      or
      ex.MonthWeekFrequency = datediff(week, dateadd(month, datediff(month, '20200101', ex.execdatetime), '20200101'), ex.execdatetime) +1
    )
) as o
where o.execrownum = 1 --...the very next execution
order by ScheduleOrdinal, TrigAt;
</code>```


问:
Javascript Syntax Differences
What is the difference between these two?

```<code>collapse: function(fold)
{
...
...
}
</code>```

and

```<code>function collapse(fold)
{
...
...
}
</code>```

答:
The first one is creating a property called "collapse" on whatever the current object is (or if there is no current object, then it will error out) and assigning a function to it.  The function will only be accessible through its associated object, by calling something along the lines of obj.collapse();.

The second one is creating a function called "collapse" in the global namespace (i.e. as a property on window).  The function can be called from anywhere by doing collapse();.

ContentLicense: CC BY-SA 3.0

Title: Javascript Syntax Differences

Body:
What is the difference between these two?

collapse: function(fold)
{
...
...
}

and

function collapse(fold)
{
...
...
}


问:
List of functions: Apply additional argument only to those functions who can take it
I have a list of functions, most of which take the same additional argument (na.rm = TRUE).

I want to add a function which doesn't take this argument (length). Is it possible to apply the additional argument only to the functions which can take it? I thought of using ..., but I am not really sure how to apply it, and if this is possible at all.

I am using lapply, but happy with any options, also beyond base R.

x <- c(1:10,NA)

# working example only with functions that take the extra argument

show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}
show_stats(x)
#> $mean
#> [1] 5.5
#>
#> $sd
#> [1] 3.02765

# sadly not working, because length() only takes one argument
show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

show_stats(x)
#> Error in f(x, na.rm = TRUE): 2 arguments passed to 'length' which requires 1
```

Created on 2020-02-16 by the reprex package (v0.3.0)

答:
I am not sure if this is the safest way to do this but you can use tryCatch wherein if there is an error you return f(x) without any additional arguments.

```<code>show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) tryCatch(f(x, na.rm = TRUE), error = function(e) f(x)))
}
show_stats(x)

#$mean
#[1] 5.5

#$sd
#[1] 3.02765

#$n
#[1] 11
</code>```

Body:
I have a list of functions, most of which take the same additional argument (na.rm = TRUE).

I want to add a function which doesn't take this argument (length). Is it possible to apply the additional argument only to the functions which can take it? I thought of using ..., but I am not really sure how to apply it, and if this is possible at all.

I am using lapply, but happy with any options, also beyond base R.

x <- c(1:10,NA)

# working example only with functions that take the extra argument

show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}
show_stats(x)
#> $mean
#> [1] 5.5
#>
#> $sd
#> [1] 3.02765

# sadly not working, because length() only takes one argument
show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) f(x, na.rm = TRUE))
}

show_stats(x)
#> Error in f(x, na.rm = TRUE): 2 arguments passed to 'length' which requires 1

Created on 2020-02-16 by the reprex package (v0.3.0)

Body:
I am not sure if this is the safest way to do this but you can use tryCatch wherein if there is an error you return f(x) without any additional arguments.

show_stats <- function(x) {
  funs <- list(mean = mean, sd = sd, n = length)
  lapply(funs, function(f) tryCatch(f(x, na.rm = TRUE), error = function(e) f(x)))
}
show_stats(x)

#$mean
#[1] 5.5

#$sd
#[1] 3.02765

#$n
#[1] 11


问:
Load shared assets between multiple entries in Webpack
I'm developing an app based on Node.js, Express and Webpack.

The application has multiple pages (with different client-side logic) so I'm using a custom structure folder, without a unique /src folder.

This is the structure:

```<code>|── clients
    └── client_1
        └── client_1_logic.js
        └── client_1_style.css
    └── client_2
        └── client_2_logic.js
        └── client_2_style.css

|── server
    └── index.js (node.js server entry point)
    └── other_serverside_stuff.js

|── public (public static folder)
    └── static_files (audio, img...)
    └── js (webpack bundled scripts)
        └── client_1.bundle.js
        └── client_2.bundle.js

|── shared (here's the question)

</code>```

I'm happy with the current structure, cause I can separate the logic in a neat way, importing modules only when needed, bundling everything and putting it in the public folder, so I can retrieve the files runtime from the client-side.
The public folder is set to be a static folder with express: app.use(express.static(path.join(__dirname, '../public')));

What I want to do is to put some files in the shared folder (for example a common config file, ora a basic .css template), and import them in the client side logic.
For example, imagine a config.js in the shared folder, I would like to import it in client_1_logic.js this way:

```<code>// libs
import {html, render} from 'lit-html';
// style
import 'bootstrap/dist/css/bootstrap.min.css';
// config
import config from './shared/config.js';

// do something with imported modules ...
</code>```

Now I get the error Module not found: Error: Can't resolve './shared/config.js'.

It works if I put the shared folder both in client_1 and client_2 subfolders, but I dont' really want to duplicate all the files.

Here's my webpack.config.js:

```<code>const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    player: './clients/client_1/client_1_logic.js',
    controller: './clients/client_2/client_2_logic.js'
  },
  devtool: 'inline-source-map',
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public/js/'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      }
    ]
  }
};
</code>```

Many thanks in advance,
Francesco

答:
Okay I found a clean solution:

Adding a resolve rule to the webpack.config.js this way:

```<code>resolve: {
  alias: {
    config: path.join(__dirname, 'shared/'),
  }
}
</code>```

I can import the file from clients this way:

import config from 'shared/config.js' (without ./)

Here we go!

Body:
I'm developing an app based on Node.js, Express and Webpack.

The application has multiple pages (with different client-side logic) so I'm using a custom structure folder, without a unique /src folder.

This is the structure:

|── clients
    └── client_1
        └── client_1_logic.js
        └── client_1_style.css
    └── client_2
        └── client_2_logic.js
        └── client_2_style.css

|── server
    └── index.js (node.js server entry point)
    └── other_serverside_stuff.js

|── public (public static folder)
    └── static_files (audio, img...)
    └── js (webpack bundled scripts)
        └── client_1.bundle.js
        └── client_2.bundle.js

|── shared (here's the question)

I'm happy with the current structure, cause I can separate the logic in a neat way, importing modules only when needed, bundling everything and putting it in the public folder, so I can retrieve the files runtime from the client-side.
The public folder is set to be a static folder with express: app.use(express.static(path.join(__dirname, '../public')));

What I want to do is to put some files in the shared folder (for example a common config file, ora a basic .css template), and import them in the client side logic.
For example, imagine a config.js in the shared folder, I would like to import it in client_1_logic.js this way:

// libs
import {html, render} from 'lit-html';
// style
import 'bootstrap/dist/css/bootstrap.min.css';
// config
import config from './shared/config.js';

// do something with imported modules ...

Now I get the error Module not found: Error: Can't resolve './shared/config.js'.

It works if I put the shared folder both in client_1 and client_2 subfolders, but I dont' really want to duplicate all the files.

Here's my webpack.config.js:

const path = require('path');

module.exports = {
  mode: 'development',
  entry: {
    player: './clients/client_1/client_1_logic.js',
    controller: './clients/client_2/client_2_logic.js'
  },
  devtool: 'inline-source-map',
  output: {
    filename: '[name].bundle.js',
    path: path.join(__dirname, 'public/js/'),
    publicPath: '/',
  },
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      }
    ]
  }
};

Many thanks in advance,
Francesco

Body:
Okay I found a clean solution:

Adding a resolve rule to the webpack.config.js this way:

resolve: {
  alias: {
    config: path.join(__dirname, 'shared/'),
  }
}

I can import the file from clients this way:

import config from 'shared/config.js' (without ./)

Here we go!


答:
I think Greg's answers cover "standard operating procedure", but I find many uses for the findInterval function as well. It naturally returns a number that identifies the interval in the second argument.</p>

```<code> data$int <- findInterval(data$wt, c(179, 200, 300, Inf))
 data
</code>```

Title: coding variable values into classes using R

Body:
I have a set of data in which I need to code values of certain variables (numeric) into 3 classes.

My data set is similar to this but has 60 more variables:

anim <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
wt <- c(181,179,180.5,201,201.5,245,246.4,189.3,301,354,369,205,199,394,231.3)
data <- data.frame(anim,wt)

> data
   anim    wt
1     1 181.0
2     2 179.0
3     3 180.5
4     4 201.0
5     5 201.5
6     6 245.0
7     7 246.4
8     8 189.3
9     9 301.0
10   10 354.0
11   11 369.0
12   12 205.0
13   13 199.0
14   14 394.0
15   15 231.3

I need to code values of the variable "wt" up into 3 classes: (wt >= 179 & wt < 200) = 1; (wt >= 200 & wt < 300) = 2; (wt > 300) = 3

which should give me this

> data2
   anim    wt SWT
1     1 181.0   1
2     2 179.0   1
3     3 180.5   1
4     4 201.0   2
5     5 201.5   2
6     6 245.0   2
7     7 246.4   2
8     8 189.3   1
9     9 301.0   3
10   10 354.0   3
11   11 369.0   3
12   12 205.0   2
13   13 199.0   1
14   14 394.0   3
15   15 231.3   2

Body:
I think Greg's answers cover "standard operating procedure", but I find many uses for the findInterval function as well. It naturally returns a number that identifies the interval in the second argument.

 data$int <- findInterval(data$wt, c(179, 200, 300, Inf))
 data


问:
Remove unicode '\xa0' from pandas column
I was given a latin-1 .txt dataset, which I am trying to clean up to use for proper analysis using python 3 and pandas. The dataset, being scraped from html contains a number of \xa0 occurences, which I can't seem to deal with using decode, strip, -u replace, or any other method which I found on stack overflow. All of my attempts seem to be ignored by python, still printing out the same results. As I am new to data scraping, chances are that I missed out on something obvious, but right now I don't see a way forward

I have tried to decode to ascii, strip to str and then replace, or replace using a -u clause, not leading to anything

```<code>filepath = 'meow3.txt'
outF = open("myOutFile.txt", "a")
with open(filepath) as fp:
    line = fp.readline()
    for line in fp:
        if line.strip().startswith(','):
            line = line.replace(',','',1)
        line = line.replace(u'\xa0', u' ')
        print(line)

df = pd.read_csv('myOutFile.txt', sep=",", encoding="latin-1", header=None, names=["Company name", "Total", "Invested since-to"])

print (df)
</code>```

```<code>3sun Group, £10m ,Feb 2014
,Abacus, £4.15m ,Aug 2013
,Accsys Group ,£12m, Mar 2017,
Acro ,\xa0£7.8m, Nov 2015 – Sep 2017,
ACS Clothing, £25.3m ,Jan 2014
</code>```

this is how the dataset looks like, and why in my code I am removing the first comma provided it is at the start of the column. But none of the suggested answers I tried seemed to help with removing the \xa0 part of the dataset, still giving the same result (seen above). If anyone has any clue for how I could make this work, I would be very grateful,
Cheers,
Jericho

Edit: While I know this would be best dealt with by pre-processing before turning it into txt file, I have no access or control of that process, and I have to work with the data I was given.

答:
I suddenly stuck by this problem today and finally find a quickest and neatest solution.
Say your pandas dataframe has a column with values like 'South\xa0Carolina'.

Use the following code to remove all '\xa0'. Actually I have tried .replace("\xa0"," ") and .replace(r'\xa0',r' '), but none of them worked.

data['col'].str.split().str.join(' ')
```

Body:
I was given a latin-1 .txt dataset, which I am trying to clean up to use for proper analysis using python 3 and pandas. The dataset, being scraped from html contains a number of \xa0 occurences, which I can't seem to deal with using decode, strip, -u replace, or any other method which I found on stack overflow. All of my attempts seem to be ignored by python, still printing out the same results. As I am new to data scraping, chances are that I missed out on something obvious, but right now I don't see a way forward

I have tried to decode to ascii, strip to str and then replace, or replace using a -u clause, not leading to anything

filepath = 'meow3.txt'
outF = open("myOutFile.txt", "a")
with open(filepath) as fp:
    line = fp.readline()
    for line in fp:
        if line.strip().startswith(','):
            line = line.replace(',','',1)
        line = line.replace(u'\xa0', u' ')
        print(line)

df = pd.read_csv('myOutFile.txt', sep=",", encoding="latin-1", header=None, names=["Company name", "Total", "Invested since-to"])

print (df)

3sun Group, £10m ,Feb 2014
,Abacus, £4.15m ,Aug 2013
,Accsys Group ,£12m, Mar 2017,
Acro ,\xa0£7.8m, Nov 2015 – Sep 2017,
ACS Clothing, £25.3m ,Jan 2014

this is how the dataset looks like, and why in my code I am removing the first comma provided it is at the start of the column. But none of the suggested answers I tried seemed to help with removing the \xa0 part of the dataset, still giving the same result (seen above). If anyone has any clue for how I could make this work, I would be very grateful,
Cheers,
Jericho

Edit: While I know this would be best dealt with by pre-processing before turning it into txt file, I have no access or control of that process, and I have to work with the data I was given.


问:
Send notifications to android app using Firebase Functions
I am developing a chat app and so, I need to send notifications that new messages have been received.
For that, I am using Firebase Functions.
I'm using the sendToDevice function, that needs a token to send a notification. The problem is, I can't seem to retrieve token of the user that sent the message.
This is my .js code:

```<code>const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref("/chats/{id}/messages/{messageId}/content")
.onWrite((change,context) => {
    var content = change.after.val();

    var payload = {
        data:{
            title: "Stranger has sent you a message",
            text: content
        }
    };

    // Here I need to the ID of the person who sent the message
    // And then compare this Id with the two Ids of the to users that are in the conversation
    // If the two Ids are different, then save the other Id as the token
    // So that I can send a notification to the other user.
    const senderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");

    admin.messaging().sendToDevice(senderId, payload)
    .then(function(response){
        console.log("Successfully sent message: ", response);
        return null;
    })
    .catch(function(error){
        console.log("Error sending message: ", error);
    })
});
</code>```

As you can see, I am checking for any changes in the messages/content child.
That as the content of my notification.

Then, I am trying to retrieve the message sender ID so I can know who sent the message and retrieve the other user Id to notify him.

This might be a little confusing so here is my Firebase Realtime Database:

What am I doing wrong so this piece of code works as it should? This is the activity I have in android to receive the message:

```<code>class MyFirebaseInstanceId : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        if(p0.data.size > 0){
            val payload :Map<String, String> = p0.data

            sendNotification(payload)

        }
    }

    private fun sendNotification(payload: Map<String, String>) {
        val builder = NotificationCompat.Builder(this)
        builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_disabled)
        builder.setContentTitle(payload.get("username"))
        builder.setContentText(payload.get("email"))

        val intent = Intent(this, MainActivity::class.java)
        val stackBuilder = TaskStackBuilder.create(this)

        stackBuilder.addNextIntent(intent)

        val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

        builder.setContentIntent(resultPendingIntent)

        val notificationManager =  (getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager

        notificationManager.notify(0, builder.build())
    }
}
</code>```

答:
Following our comments above, here is how to use the once() and val() methods in your Cloud Function:

```<code>//.....
const refSenderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");

return refSenderId.once('value')
 .then(dataSnapshot => {
     const senderId = dataSnapshot.val();
     return admin.messaging().sendToDevice(senderId, payload)
 })
.then(function(response){
    console.log("Successfully sent message: ", response);
    return null;
})
.catch(function(error){
    console.log("Error sending message: ", error);
    return null;   // <- Note the return here.
})
//.....
</code>```

Body:
I am developing a chat app and so, I need to send notifications that new messages have been received.
For that, I am using Firebase Functions.
I'm using the sendToDevice function, that needs a token to send a notification. The problem is, I can't seem to retrieve token of the user that sent the message.
This is my .js code:

const functions = require('firebase-functions');

const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.sendNotification = functions.database.ref("/chats/{id}/messages/{messageId}/content")
.onWrite((change,context) => {
    var content = change.after.val();

    var payload = {
        data:{
            title: "Stranger has sent you a message",
            text: content
        }
    };

    // Here I need to the ID of the person who sent the message
    // And then compare this Id with the two Ids of the to users that are in the conversation
    // If the two Ids are different, then save the other Id as the token
    // So that I can send a notification to the other user.
    const senderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");

    admin.messaging().sendToDevice(senderId, payload)
    .then(function(response){
        console.log("Successfully sent message: ", response);
        return null;
    })
    .catch(function(error){
        console.log("Error sending message: ", error);
    })
});

As you can see, I am checking for any changes in the messages/content child.
That as the content of my notification.

Then, I am trying to retrieve the message sender ID so I can know who sent the message and retrieve the other user Id to notify him.

This might be a little confusing so here is my Firebase Realtime Database:

What am I doing wrong so this piece of code works as it should? This is the activity I have in android to receive the message:

class MyFirebaseInstanceId : FirebaseMessagingService() {
    override fun onMessageReceived(p0: RemoteMessage) {
        if(p0.data.size > 0){
            val payload :Map<String, String> = p0.data

            sendNotification(payload)

        }
    }

    private fun sendNotification(payload: Map<String, String>) {
        val builder = NotificationCompat.Builder(this)
        builder.setSmallIcon(R.drawable.common_google_signin_btn_icon_disabled)
        builder.setContentTitle(payload.get("username"))
        builder.setContentText(payload.get("email"))

        val intent = Intent(this, MainActivity::class.java)
        val stackBuilder = TaskStackBuilder.create(this)

        stackBuilder.addNextIntent(intent)

        val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)

        builder.setContentIntent(resultPendingIntent)

        val notificationManager =  (getSystemService(Context.NOTIFICATION_SERVICE)) as NotificationManager

        notificationManager.notify(0, builder.build())
    }
}

Body:
Following our comments above, here is how to use the once() and val() methods in your Cloud Function:

//.....
const refSenderId = database.ref("/chats/{id}/messages/{id}/sender/{senderId}");

return refSenderId.once('value')
 .then(dataSnapshot => {
     const senderId = dataSnapshot.val();
     return admin.messaging().sendToDevice(senderId, payload)
 })
.then(function(response){
    console.log("Successfully sent message: ", response);
    return null;
})
.catch(function(error){
    console.log("Error sending message: ", error);
    return null;   // <- Note the return here.
})
//.....


问:
JSON serialization/deserialization in ASP.Net Core
Since there is no JavaScriptSerializer, what native implementation can be used to handle this?

I noticed JsonResult and I can format data to JSON with this, but how do I deserialize?

Or maybe I am missing some dependencies in project.json?

答:
.net core

using System.Text.Json;

###To serialize

```<code>var jsonStr = JsonSerializer.Serialize(MyObject)
</code>```

###Deserialize

```<code>var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);
</code>```

For more information about excluding properties and nulls check out
This Microsoft site

Body:
.net core

using System.Text.Json;

###To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

###Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out
This Microsoft site


问:
ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there
I have a situation very much like the one at Error "ImportError: DLL load failed: %1 is not a valid Win32 application", but the answer there isn't working for me.

My Python code says:

```<code>import cv2
</code>```

But that line throws the error shown in the title of this question.

I have OpenCV installed in C:\lib\opencv on this 64-bit machine. I'm using 64-bit Python.

My PYTHONPATH variable: PYTHONPATH=C:\lib\opencv\build\python\2.7. This folder contains cv2.pyd and that's all.

My PATH variable: Path=%OPENCV_DIR%\bin;... This folder contains 39 DLL files such as opencv_core246d.dll.

OPENCV_DIR has this value: OPENCV_DIR=C:\lib\opencv\build\x64\vc11.

The solution at Error "ImportError: DLL load failed: %1 is not a valid Win32 application" says to add "the new opencv binaries path (C:\opencv\build\bin\Release) to the Windows PATH environment variable". But as shown above, I already have the OpenCV binaries folder (C:\lib\opencv\build\x64\vc11\bin) in my PATH. And my OpenCV installation doesn't have any Release folders (except for an empty one under build/java).

What's going wrong? Can I tell Python to verbosely trace the loading process? Exactly what DLL files is it looking for?

I noticed that, according to http://www.dependencywalker.com/, the cv2.pyd in C:\lib\opencv\build\python\2.7 is 32-bit, whereas the machine and the Python I'm running are 64-bit. Could that be the problem? And if so, where can I find a 64-bit version of cv2.pyd?

答:
This has worked for me. I have tried different methods, but this was my best solution.

Open a command prompt and type the following;

pip install opencv-python
```

(Make sure your Internet connection is on.)

After that, try importing it again.

Body:
I have a situation very much like the one at Error "ImportError: DLL load failed: %1 is not a valid Win32 application", but the answer there isn't working for me.

My Python code says:

import cv2

But that line throws the error shown in the title of this question.

I have OpenCV installed in C:\lib\opencv on this 64-bit machine. I'm using 64-bit Python.

My PYTHONPATH variable: PYTHONPATH=C:\lib\opencv\build\python\2.7. This folder contains cv2.pyd and that's all.

My PATH variable: Path=%OPENCV_DIR%\bin;... This folder contains 39 DLL files such as opencv_core246d.dll.

OPENCV_DIR has this value: OPENCV_DIR=C:\lib\opencv\build\x64\vc11.

The solution at Error "ImportError: DLL load failed: %1 is not a valid Win32 application" says to add "the new opencv binaries path (C:\opencv\build\bin\Release) to the Windows PATH environment variable". But as shown above, I already have the OpenCV binaries folder (C:\lib\opencv\build\x64\vc11\bin) in my PATH. And my OpenCV installation doesn't have any Release folders (except for an empty one under build/java).

What's going wrong? Can I tell Python to verbosely trace the loading process? Exactly what DLL files is it looking for?

I noticed that, according to http://www.dependencywalker.com/, the cv2.pyd in C:\lib\opencv\build\python\2.7 is 32-bit, whereas the machine and the Python I'm running are 64-bit. Could that be the problem? And if so, where can I find a 64-bit version of cv2.pyd?

Body:
This has worked for me. I have tried different methods, but this was my best solution.

Open a command prompt and type the following;

pip install opencv-python

(Make sure your Internet connection is on.)

After that, try importing it again.


问:
Multiple paragraphs in single form field - Jquery append on keydown
I have a very basic CMS that I've put together with PHP and MySQL. Everything works great, except I can't find a way to make textarea fields capable of containing multiple paragraphs (e.g. blog posts, detailed service descriptions). The data is stored in MySQL with
s between the paragraphs, but when I call it back for display, all breaks are removed. There is nothing in the PHP that would pull out html (no trimming of html entities, string replacing, etc.) Ideally, I'd be able to wrap the cursor in

 like this textarea I'm typing in now does.

Today I've been trying JQuery.

```<code><script type="text/javascript">
$(document).ready(function(){
$('#thetest').keydown(function(event) {
if (event.keyCode == '13') {
    $('#thetest').append('<p>Test</p>');
});
});
</script>

<form action="test_upload.php" enctype="multipart/form-data" method="POST">
<p>Content: </p>
<textarea wrap="virtual" id="thetest" name="thetest" value=""
autocomplete="off" rows="20"cols="100">
</textarea>
<input type="submit" name="submit" value="Upload" />
</form>
</code>```

If anyone could point me in the right direction, I'd greatly appreciate it. I'd think there'd be a jquery plugin for forms that would handle it, but I haven't found one. Thanks very much in advance.

答:
Are your users typing in the paragraph tags, or do you want it WYSIWYG style? If it's the former, you shouldn't have a problem (and if you do, you can just htmlentities() it before it goes in and decode when you fetch it). If it's the latter, I would process the $_POST['thetest'] string as it comes back to you before putting it in your database. You can preg_replace() your newline characters with
 and
 before storing it, with more newline characters to make it readable of course.

Or you can cheat with ``` just to preserve white space, but that wouldn't be semantically responsible :p

Body:
I have a very basic CMS that I've put together with PHP and MySQL. Everything works great, except I can't find a way to make textarea fields capable of containing multiple paragraphs (e.g. blog posts, detailed service descriptions). The data is stored in MySQL with
s between the paragraphs, but when I call it back for display, all breaks are removed. There is nothing in the PHP that would pull out html (no trimming of html entities, string replacing, etc.) Ideally, I'd be able to wrap the cursor in

 like this textarea I'm typing in now does.

Today I've been trying JQuery.

<form action="test_upload.php" enctype="multipart/form-data" method="POST">

Content:

<textarea wrap="virtual" id="thetest" name="thetest" value=""
autocomplete="off" rows="20"cols="100">
</textarea>
<input type="submit" name="submit" value="Upload" />
</form>

If anyone could point me in the right direction, I'd greatly appreciate it. I'd think there'd be a jquery plugin for forms that would handle it, but I haven't found one. Thanks very much in advance.

Body:
Are your users typing in the paragraph tags, or do you want it WYSIWYG style? If it's the former, you shouldn't have a problem (and if you do, you can just htmlentities() it before it goes in and decode when you fetch it). If it's the latter, I would process the $_POST['thetest'] string as it comes back to you before putting it in your database. You can preg_replace() your newline characters with <p> and </p> before storing it, with more newline characters to make it readable of course.

Or you can cheat with <pre> just to preserve white space, but that wouldn't be semantically responsible :p


问:
How to right install react-hot-loader in webpack?
I tried install react-hot-loader, but this dont work and i get error

```<code>main.9d9605180f32844bc508.css
Cannot use [chunkhash] or [contenthash] for chunk in '[name].[contenthash].js' (use [hash] instead)
</code>```

webpack config

```<code>module.exports = {
        context: path.resolve(__dirname, 'src'),
        mode: 'production',
        entry: {
            main: ['webpack-dev-server/client?http://localhost:9090', '@babel/polyfill', './index.jsx']
        },
        resolve: {
            extensions: ['.js', '.jsx', '.sass', '.scss', '.css', '.png', '.jpg', '.json'],
            alias: {
                '@': path.resolve(__dirname, 'src')
            }
        },
        devServer: {
            port: 9090,
            hot: isDev
        }
</code>```

and loader for jsx

```<code>{
                test: /\.jsx$/,
                exclude: /node_modules/,
                use: [
                    'react-hot-loader/webpack',
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-react']
                        }
                    },
                    'eslint-loader'
                ]
            },
</code>```

for npm command

```<code>"scripts": {
    "start": "webpack-dev-server --mode=development",
    "build": "webpack --mode=production",
    "dev": "webpack-dev-server --hot -w --mode=development"
  }
</code>```

how to install correctly react-hot-loader?

答:
install this     "react-hot-loader/babel",
and add to .babelrc into plugins array.

```<code>npm i react-hot-loader
</code>```

in the react component that you have state:

```<code>import { hot } from "react-hot-loader/root";
class YourClass extends React.Component{
  constructor(props){
  super(props)
  this.state={}
 }
render(){
return(JSX CODE)}
}

export default hot(YourClass)
</code>```

in your webpack:

```<code>entry: {
    main: [ "react-hot-loader/patch", "./src/main.js"]
  }
</code>```

Body:
I tried install react-hot-loader, but this dont work and i get error

main.9d9605180f32844bc508.css
Cannot use [chunkhash] or [contenthash] for chunk in '[name].[contenthash].js' (use [hash] instead)

webpack config

module.exports = {
        context: path.resolve(__dirname, 'src'),
        mode: 'production',
        entry: {
            main: ['webpack-dev-server/client?http://localhost:9090', '@babel/polyfill', './index.jsx']
        },
        resolve: {
            extensions: ['.js', '.jsx', '.sass', '.scss', '.css', '.png', '.jpg', '.json'],
            alias: {
                '@': path.resolve(__dirname, 'src')
            }
        },
        devServer: {
            port: 9090,
            hot: isDev
        }

and loader for jsx

{
                test: /\.jsx$/,
                exclude: /node_modules/,
                use: [
                    'react-hot-loader/webpack',
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['@babel/preset-react']
                        }
                    },
                    'eslint-loader'
                ]
            },

for npm command

"scripts": {
    "start": "webpack-dev-server --mode=development",
    "build": "webpack --mode=production",
    "dev": "webpack-dev-server --hot -w --mode=development"
  }

how to install correctly react-hot-loader?

Body:
install this     "react-hot-loader/babel",
and add to .babelrc into plugins array.

npm i react-hot-loader

in the react component that you have state:

import { hot } from "react-hot-loader/root";
class YourClass extends React.Component{
  constructor(props){
  super(props)
  this.state={}
 }
render(){
return(JSX CODE)}
}

export default hot(YourClass)

in your webpack:

entry: {
    main: [ "react-hot-loader/patch", "./src/main.js"]
  }


问:
How can I create strokeDasharray circular progress react native?
I tried to build the circular progress bar with dashed arrays by referring to (https://github.com/stssoftware/react-native-svg-circular-progress)
using below code

```<code>>   <Circle cx={half} cy={half} r={half} fill={blankColor}
> stroke="#0074d9"
>                 strokeWidth="10"
>                 strokeDasharray="8, 3"/>
</code>```

full code :

```<code>import React from 'react'
import {View, StyleSheet} from 'react-native'
import Svg, {Path, Circle} from 'react-native-svg'

const styles = StyleSheet.create({
    textView: {
        position: 'absolute',
        top: 0, left: 0, bottom: 0, right: 0,
        justifyContent: 'center',
        alignItems: 'center'
    }
})

function generateArc(percentage, radius){
    if (percentage === 100) percentage = 99.999
    const a = percentage*2*Math.PI/100 // angle (in radian) depends on percentage
    const r = radius // radius of the circle
    var rx = r,
        ry = r,
        xAxisRotation = 0,
        largeArcFlag = 1,
        sweepFlag = 1,
        x = r + r*Math.sin(a),
        y = r - r*Math.cos(a)
    if (percentage <= 50){
        largeArcFlag = 0;
    }else{
        largeArcFlag = 1
    }

    return `A${rx} ${ry} ${xAxisRotation} ${largeArcFlag} ${sweepFlag} ${x} ${y}`
}

const CircularProgress = ({
    percentage = 40,
    blankColor = "#eaeaea",
    donutColor = "#43cdcf",
    fillColor = "white",
    progressWidth = 35,
    size = 100,
    children
}) => {
    let half = size / 2;
    return <View style={{width: size, height: size}}>
        <Svg width={size} height={size}>
            <Circle cx={half} cy={half} r={half} fill={blankColor} stroke="#0074d9"
                strokeWidth="10"
                strokeDasharray="8, 3"/>
            <Path
                d={`M${half} ${half} L${half} 0 ${generateArc(percentage, half)} Z`}
                fill={donutColor}
            />
            {<Circle cx={half} cy={half} r={progressWidth} fill={fillColor}
                    />}
        </Svg>
        <View style={styles.textView}>
            {children}
        </View>
    </View>
}
export default CircularProgress
</code>```

but I am not getting proper circle, can someone help me develop the circle or point to any progress bar component  where I can get dashed array of stroke

I need something like below

but i am getting like below

答:
You have strokeWidth of 10. The stroke grow around the like, means 5 before the line, and 5 after the line.

In your code you set the radius of the circle as half of the SVG width and height. means the 5 of stroke width that grow after the stoke line will just overflow the SVG.

To fix it, set the radius as width/2 - strikeWidth/2 in your case 100/2 - 10/2 or half - 5.

In final words, this should resolve your problem:

```<code><Circle
  cx={half}
  cy={half}
  r={half-5}
  fill={blankColor}
  stroke="#0074d9"
  strokeWidth="10"
  strokeDasharray="8, 3"
/>
</code>```

Body:
I tried to build the circular progress bar with dashed arrays by referring to (https://github.com/stssoftware/react-native-svg-circular-progress)
using below code

>   <Circle cx={half} cy={half} r={half} fill={blankColor}
> stroke="#0074d9"
>                 strokeWidth="10"
>                 strokeDasharray="8, 3"/>

full code :

import React from 'react'
import {View, StyleSheet} from 'react-native'
import Svg, {Path, Circle} from 'react-native-svg'

const styles = StyleSheet.create({
    textView: {
        position: 'absolute',
        top: 0, left: 0, bottom: 0, right: 0,
        justifyContent: 'center',
        alignItems: 'center'
    }
})

function generateArc(percentage, radius){
    if (percentage === 100) percentage = 99.999
    const a = percentage*2*Math.PI/100 // angle (in radian) depends on percentage
    const r = radius // radius of the circle
    var rx = r,
        ry = r,
        xAxisRotation = 0,
        largeArcFlag = 1,
        sweepFlag = 1,
        x = r + r*Math.sin(a),
        y = r - r*Math.cos(a)
    if (percentage <= 50){
        largeArcFlag = 0;
    }else{
        largeArcFlag = 1
    }

    return `A${rx} ${ry} ${xAxisRotation} ${largeArcFlag} ${sweepFlag} ${x} ${y}`
}

const CircularProgress = ({
    percentage = 40,
    blankColor = "#eaeaea",
    donutColor = "#43cdcf",
    fillColor = "white",
    progressWidth = 35,
    size = 100,
    children
}) => {
    let half = size / 2;
    return <View style={{width: size, height: size}}>
        <Svg width={size} height={size}>
            <Circle cx={half} cy={half} r={half} fill={blankColor} stroke="#0074d9"
                strokeWidth="10"
                strokeDasharray="8, 3"/>
            <Path
                d={`M${half} ${half} L${half} 0 ${generateArc(percentage, half)} Z`}
                fill={donutColor}
            />
            {<Circle cx={half} cy={half} r={progressWidth} fill={fillColor}
                    />}
        </Svg>
        <View style={styles.textView}>
            {children}
        </View>
    </View>
}
export default CircularProgress

but I am not getting proper circle, can someone help me develop the circle or point to any progress bar component  where I can get dashed array of stroke

I need something like below

but i am getting like below

Body:
You have strokeWidth of 10. The stroke grow around the like, means 5 before the line, and 5 after the line.

In your code you set the radius of the circle as half of the SVG width and height. means the 5 of stroke width that grow after the stoke line will just overflow the SVG.

To fix it, set the radius as width/2 - strikeWidth/2 in your case 100/2 - 10/2 or half - 5.

In final words, this should resolve your problem:

<Circle
  cx={half}
  cy={half}
  r={half-5}
  fill={blankColor}
  stroke="#0074d9"
  strokeWidth="10"
  strokeDasharray="8, 3"
/>


问:
Should I use the 'request' module for a new project?
The 'request' module has been a long-time standard for Node.js.  They have recently deprecated the library.

I am starting a new project, and looking for the best solution to do my networking.  I started off using the native 'https' module, but ran into problem after problem.  Using the request module seemed to be easy and work just fine.  There are also many other libraries to replace the request module.

Generally speaking, you should avoid using deprecated libraries when possible.  But does that rule of thumb apply here?

Is it bad to start a new project with the 'request' module?  If so, what is the new standard?

答:
Request isn’t really deprecated. It’s no longer considering new features or breaking changes, but it is still being maintained.  It’s safe to use for the foreseeable future, but how good an idea it is to use it is up to the developer. Not really a right or wrong answer here.

They’ve stopped new work on it because they believe the patterns it uses are out of date and to switch over to modern patterns would effectively make request an entirely new module, so rather than invalidate thousands of blogs and SO answers by making a massive update, they’ve decided to stop in order to make space for a new standard to emerge that effectively uses new features. As of yet, a new standard does not exist.

If you like request, and the outdated patterns it uses are good for your purposes, then go for it. But new patterns and features exist for a reason, and they might be worth exploring.


问:
Need Help in Building a Query Expression in Laravel
I recently started using Laravel and got stuck on a query. I'm working on a Tasks App where the user completes different tasks posted by admin.

I want to get only those tasks that are not completed by the login user. when a user completes a task I have a 3rd table completed_tasks where both user_id and task_id stored.

This is how my tables look like:

user table (default table created by Laravel auth)
attributes: id,name,email,password

task table
attributes: id,name,description

Completed_task table
attributes: id, user_id,task_id

I tried using belongsToMany relation between user and tasks using completed_task table as a pivot

Relationship function in users model

public function tasks(){
    return $this->belongsToMany('App\Task', 'completed_task', 'user_id','task_id');
}
```

By using this function I'm getting all tasks that are completed by the login user but I want to get tasks that are not completed by the login user.

答:
All model function looks like this :

User.php

```<code>// A user has many tasks
public function tasks(){
  return $this->hasMany(Task::class);
}
</code>```

Task.php

```<code>// A Task belongs to User
public function users(){
  return $this->belongsTo(User::class);
}

// A task has a completed status
public function completed(){
  return $this->hasOne(Completed::class);
}
</code>```

Completed.php

```<code>// A Completed status belongs to a Task
public function tasks(){
  return $this->belongsTo(Task::class);
}
</code>```

Body:
I recently started using Laravel and got stuck on a query. I'm working on a Tasks App where the user completes different tasks posted by admin.

I want to get only those tasks that are not completed by the login user. when a user completes a task I have a 3rd table completed_tasks where both user_id and task_id stored.

This is how my tables look like:

user table (default table created by Laravel auth)
attributes: id,name,email,password

task table
attributes: id,name,description

Completed_task table
attributes: id, user_id,task_id

I tried using belongsToMany relation between user and tasks using completed_task table as a pivot

Relationship function in users model

public function tasks(){
    return $this->belongsToMany('App\Task', 'completed_task', 'user_id','task_id');
}

By using this function I'm getting all tasks that are completed by the login user but I want to get tasks that are not completed by the login user.

Body:
All model function looks like this :

User.php

// A user has many tasks
public function tasks(){
  return $this->hasMany(Task::class);
}

Task.php

// A Task belongs to User
public function users(){
  return $this->belongsTo(User::class);
}

// A task has a completed status
public function completed(){
  return $this->hasOne(Completed::class);
}

Completed.php

// A Completed status belongs to a Task
public function tasks(){
  return $this->belongsTo(Task::class);
}


问:
Can I receive a callback whenever an NSPasteboard is written to?
I've read Apple's Pasteboard Programming Guide, but it doesn't answer a particular question I have.

I'm trying to write a Cocoa application (for OS X, not iOS) that will keep track of everything that is written to the general pasteboard (so, whenever any application copies and pastes, but not, say, drags-and-drops, which also makes use of NSPasteboard). I could (almost) accomplish this by basically polling the general pasteboard on a background thread constantly, and checking changeCount. Of course, doing this would make me feel very dirty on the inside.

My question is, is there a way to ask the Pasteboard server to notify me through some sort of callback any time a change is made to the general pasteboard? I couldn't find anything in the NSPasteboard class reference, but I'm hoping it lurks somewhere else.

Another way I could imagine accomplishing this is if there was a way to swap out the general pasteboard implementation with a subclass of NSPasteboard that I could define myself to issue a callback. Maybe something like this is possible?

I would greatly prefer if this were possible with public, App Store-legal APIs, but if using a private API is necessary, I'll take that too.

Thanks!

答:
For those who need simplified version of code snippet that gets the job done in Swift 5.7,

it just works (base on @Devarshi code):

```<code>func watch(using closure: @escaping (_ copiedString: String) -> Void) {
    let pasteboard = NSPasteboard.general
    var changeCount = NSPasteboard.general.changeCount

    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
        guard let copiedString = pasteboard.string(forType: .string),
              pasteboard.changeCount != changeCount else { return }

        defer {
            changeCount = pasteboard.changeCount
        }

        closure(copiedString)
    }
}
</code>```

how to use is as below:

```<code>watch {
    print("detected : \($0)")
}
</code>```

then if you attempt copy any text in your pasteboard, it will watch and print out to the console like below..

```<code>detected : your copied message in pasteboard
detected : your copied message in pasteboard
</code>```

in case, full code sample for how to use it for example in SwiftUI:

```<code>import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {

                    watch {
                        print("detect : \($0)")
                    }

                }
        }
    }

    func watch(using closure: @escaping (_ copiedString: String) -> Void) {
        let pasteboard = NSPasteboard.general
        var changeCount = NSPasteboard.general.changeCount

        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            guard let copiedString = pasteboard.string(forType: .string),
                  pasteboard.changeCount != changeCount else { return }

            defer {
                changeCount = pasteboard.changeCount
            }

            closure(copiedString)
        }
    }
}

</code>```

Swift async await version:

```<code>import SwiftUI

@main
struct TestApp: App {
    var isWatch = true

    var body: some Scene {
        WindowGroup {
            ContentView()
                .task {
                    await watch {
                        print("detect : \($0)")
                    }
                }
        }
    }

    func watch(using closure: @escaping (_ copiedString: String) -> Void) async {
        let pasteboard = NSPasteboard.general
        var changeCount = NSPasteboard.general.changeCount

        while isWatch {
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            guard let copyString = pasteboard.string(forType: .string),
                  pasteboard.changeCount != changeCount else { continue }

            changeCount = pasteboard.changeCount
            closure(copyString)
        }
    }
}

</code>```

Note that these are just the samples.

You can do whatever you want to do on top of that.

ContentLicense: CC BY-SA 2.5

Body:
For those who need simplified version of code snippet that gets the job done in Swift 5.7,

it just works (base on @Devarshi code):

func watch(using closure: @escaping (_ copiedString: String) -> Void) {
    let pasteboard = NSPasteboard.general
    var changeCount = NSPasteboard.general.changeCount

    Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
        guard let copiedString = pasteboard.string(forType: .string),
              pasteboard.changeCount != changeCount else { return }

        defer {
            changeCount = pasteboard.changeCount
        }

        closure(copiedString)
    }
}

how to use is as below:

watch {
    print("detected : \($0)")
}

then if you attempt copy any text in your pasteboard, it will watch and print out to the console like below..

detected : your copied message in pasteboard
detected : your copied message in pasteboard

in case, full code sample for how to use it for example in SwiftUI:

import SwiftUI

@main
struct TestApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
                .onAppear {

                    watch {
                        print("detect : \($0)")
                    }

                }
        }
    }

    func watch(using closure: @escaping (_ copiedString: String) -> Void) {
        let pasteboard = NSPasteboard.general
        var changeCount = NSPasteboard.general.changeCount

        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            guard let copiedString = pasteboard.string(forType: .string),
                  pasteboard.changeCount != changeCount else { return }

            defer {
                changeCount = pasteboard.changeCount
            }

            closure(copiedString)
        }
    }
}

Swift async await version:

import SwiftUI

@main
struct TestApp: App {
    var isWatch = true

    var body: some Scene {
        WindowGroup {
            ContentView()
                .task {
                    await watch {
                        print("detect : \($0)")
                    }
                }
        }
    }

    func watch(using closure: @escaping (_ copiedString: String) -> Void) async {
        let pasteboard = NSPasteboard.general
        var changeCount = NSPasteboard.general.changeCount

        while isWatch {
            try? await Task.sleep(nanoseconds: 1_000_000_000)
            guard let copyString = pasteboard.string(forType: .string),
                  pasteboard.changeCount != changeCount else { continue }

            changeCount = pasteboard.changeCount
            closure(copyString)
        }
    }
}

Note that these are just the samples.

You can do whatever you want to do on top of that.