问:
How to make Hinge Joint more rigid
I'm trying to create a chain in unity3d. A player should be capable of grabing one side of it and pull it to different location. So i created some grids and connect them together. It all works fine, the problem is only when user pulls a bit faster, then I got some spaces bettwen seperate grids. Is there anyway to set max distance on that?

Btw. I'm doing these in 2d so i have 2d Rigidbody and 2d Hinge joint.

Thanks!

答: In Editor, Hinge Joint -> Use Spring = true; Spring/Damper/Target Position = 0.</p>

Title: How to make Hinge Joint more rigid


来源: stackexchange

问:
Cordova "failed to fetch plugin" error
I've run into this "Failed to fetch plugin error" quite frequently lately. It seems especially easy to prop up if I download my own branch:

t2wu@THW-air:~/Documents/Work/John/DEMO_APP/BCAppII(dev) $ cordova
  plugin add https://github.com/t2wu/cordova-plugin-geofence.git#t2wu

Error: Failed to fetch plugin
  https://github.com/t2wu/cordova-plugin-geofence.git#t2wu via registry.
  Probably this is either a connection problem, or plugin spec is
  incorrect. Check your connection and plugin name/version/URL. Failed
  to get absolute path to installed module

If I download a plugin like cordova plugin add cordova-plugin-geofence, but when I have to use a specific repo, especially a branch on that repo, it fails frequently.

I am using Cordova 7.1.0. (Cordova 8 have other issues I'm not willing to touch right now.)

答: I saw this issue when I was running npm install before doing my platform add commands. For some reason this screwed everything up, but if I just dropped npm install it was still done as part of the platform add commands.

ContentLicense: CC BY-SA 3.0

Title: Cordova "failed to fetch plugin" error

ContentLicense: CC BY-SA 4.0


问:
Why does chakra-ui colorMode become "dark" when I refresh the page in nextjs example app?
I am running 'with-chakra-ui' from the nextjs example.

https://stackblitz.com/github/vercel/next.js/tree/canary/examples/with-chakra-ui

Colormode switch does work well. But when I refresh the page, it always returns to the darkmode like this video.

Video Link

I want to remember the color mode.

How can I do this?

答:
Oh, I found why it returned to the darkmode.

In the _app.tsx, ColorModeProvider option was {useSystemColorMode: true}.

Change it to false, then the page can remember the color mode.


问:
How to delete packages from packageNames in Accessibility service in android ?
I have Accessibiltiy service which opens my activity when specific apps start.

```<code>    public class Accessibility extends AccessibilityService{
  private AccessibilityServiceInfo info;
        @Override
        protected void onServiceConnected() {

            super.onServiceConnected();
            info = new AccessibilityServiceInfo();
            info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_VIEW_CLICKED;

            info.packageNames = null;
            DatabaseHandler db = new DatabaseHandler(this);
            List<AppData> blackList = db.getAllApps();

            info.packageNames = new String[blackList.size()];
            int k = 0;
            for (AppData app : blackList) {
                if(app.isBlocked() == 1) {
                    info.packageNames[k] = app.getPackageName();
                    k++;
                }
            }
            for(int i = 0; i < info.packageNames.length; i++) {
                Log.d(myTag, "BLOCKED APP = " +   info.packageNames[i]);
            }
            info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
            info.notificationTimeout = 100;
            this.setServiceInfo(info);

            //register Broadcastreceiver
            registerReceiver(receiver, new IntentFilter("UPDATE_BLACKLIST"));
        }

        //Receives notification when blacklist was updated
        private final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                onServiceConnected();
            }
        };
    }
</code>```

When accessibility service gets broadcast receiver, it calls method onServiceConnected() which has to update list with packageNames and it updates successfully but, if I update list again with new package names, my accessibiltiy service still continue to work when I open application which is not now in the list.
I displayed in logs the full list - there is no old package names, but accessibiltiy service still works when I open that applications.
How can I totally update package names in my service ?

答: Use info = getServiceInfo() instead of info = new AccessibilityServiceInfo();

Body:
I have Accessibiltiy service which opens my activity when specific apps start.

    public class Accessibility extends AccessibilityService{
  private AccessibilityServiceInfo info;
        @Override
        protected void onServiceConnected() {

            super.onServiceConnected();
            info = new AccessibilityServiceInfo();
            info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED | AccessibilityEvent.TYPE_VIEW_CLICKED;

            info.packageNames = null;
            DatabaseHandler db = new DatabaseHandler(this);
            List<AppData> blackList = db.getAllApps();

            info.packageNames = new String[blackList.size()];
            int k = 0;
            for (AppData app : blackList) {
                if(app.isBlocked() == 1) {
                    info.packageNames[k] = app.getPackageName();
                    k++;
                }
            }
            for(int i = 0; i < info.packageNames.length; i++) {
                Log.d(myTag, "BLOCKED APP = " +   info.packageNames[i]);
            }
            info.feedbackType = AccessibilityServiceInfo.FEEDBACK_SPOKEN;
            info.notificationTimeout = 100;
            this.setServiceInfo(info);

            //register Broadcastreceiver
            registerReceiver(receiver, new IntentFilter("UPDATE_BLACKLIST"));
        }

        //Receives notification when blacklist was updated
        private final BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                onServiceConnected();
            }
        };
    }

When accessibility service gets broadcast receiver, it calls method onServiceConnected() which has to update list with packageNames and it updates successfully but, if I update list again with new package names, my accessibiltiy service still continue to work when I open application which is not now in the list.
I displayed in logs the full list - there is no old package names, but accessibiltiy service still works when I open that applications.
How can I totally update package names in my service ?


问:
How can I calculate a hover state change based on the original state values?
This may not be possible using just CSS alone buuuut let's give her a whirl.

For example: I have an image with certain margins. let's say something like this:

```<code>img {
margin-left: 1em;
}
</code>```

What I want to do, (I'll write it in pseudo code) is something like this:

```<code>img:hover {
margin-left: [take original non-hover state margin, then -1 from that to make 0]
}
</code>```

Hopefully I'm making sense here if it's even possible - I've really tried to simplify that example down.

答:
```<code>img {
margin-left: 1em;
}
img:hover {
margin-right: 1em;// for minus 1
}
</code>```

you can use margin-right to subract

P.S remember what you learnt in childhood about net force

Body:
This may not be possible using just CSS alone buuuut let's give her a whirl.

For example: I have an image with certain margins. let's say something like this:

img {
margin-left: 1em;
}

What I want to do, (I'll write it in pseudo code) is something like this:

img:hover {
margin-left: [take original non-hover state margin, then -1 from that to make 0]
}

Hopefully I'm making sense here if it's even possible - I've really tried to simplify that example down.

Body:
img {
margin-left: 1em;
}
img:hover {
margin-right: 1em;// for minus 1
}

you can use margin-right to subract

P.S remember what you learnt in childhood about net force


问:
PHP Warning: require(...): Failed to open stream: No such file or directory in
I´m working on a onlineshop.

I need to require the "nav_bar.php" file into the "item_page.php" file.

Here´s my directory:

directory

And here´s my code:

```<code>require "../nav_bar/nav_bar.php";
</code>```

note: I also tried a lot of other "path" variations but it never worked.

Some examples of my tries:

```<code>require "source\main\nav_bar\nav_bar.php";

require "C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\nav_bar\nav_bar.php";
</code>```

A few days ago, I got this Error. I already searched a ton of other questions and a lot of other websites with this error, but I can not find a answer for my problem...

I know, that this error is somehow common but I don´t know how I can solve this one.

Can anyone help me?

Here´s the error message:

```<code>error: Command failed: "C:\xampp\php\php.exe" "c:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php" PHP Warning:  require(../nav_bar/nav_bar.php): Failed to open stream: No such file or directory in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php on line 8 PHP Fatal error:  Uncaught Error: Failed opening required '../nav_bar/nav_bar.php' (include_path='C:\xampp\php\PEAR') in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php:8 Stack trace:
#0 {main}   thrown in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php on line 8
</code>```

Error message

note: I use a VS-Code extension named: "five server"

But I don´t think, this extension has something to do with the error.

Heres the extension:

https://marketplace.visualstudio.com/items?itemName=yandeu.five-server

Thank you in advance :)

答:
The include_path does not include the current directory...

Heres a example to solve this, with an absolute path:

```<code>require dirname(__DIR__)."/nav_bar/nav_bar.php";
</code>```

Thanks @Kevin Y for the comment that solved that question

Body:
I´m working on a onlineshop.

I need to require the "nav_bar.php" file into the "item_page.php" file.

Here´s my directory:

directory

And here´s my code:

require "../nav_bar/nav_bar.php";

note: I also tried a lot of other "path" variations but it never worked.

Some examples of my tries:

require "source\main\nav_bar\nav_bar.php";

require "C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\nav_bar\nav_bar.php";

A few days ago, I got this Error. I already searched a ton of other questions and a lot of other websites with this error, but I can not find a answer for my problem...

I know, that this error is somehow common but I don´t know how I can solve this one.

Can anyone help me?

Here´s the error message:

error: Command failed: "C:\xampp\php\php.exe" "c:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php" PHP Warning:  require(../nav_bar/nav_bar.php): Failed to open stream: No such file or directory in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php on line 8 PHP Fatal error:  Uncaught Error: Failed opening required '../nav_bar/nav_bar.php' (include_path='C:\xampp\php\PEAR') in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php:8 Stack trace:
#0 {main}   thrown in C:\Users\holli\OneDrive\Dokumente\onlineshop\source\main\item_page\item_page.php on line 8

Error message

note: I use a VS-Code extension named: "five server"

But I don´t think, this extension has something to do with the error.

Heres the extension:

https://marketplace.visualstudio.com/items?itemName=yandeu.five-server

Thank you in advance :)

Body:
The include_path does not include the current directory...

Heres a example to solve this, with an absolute path:

require dirname(__DIR__)."/nav_bar/nav_bar.php";

Thanks @Kevin Y for the comment that solved that question


问:
Flutter: How to make a button like this?
I tried to use TextButton.Icon to make the effect as following.
But I found that the words can only be at the left or right of the icon. How can I put the words under the icon like this?

答:
You can use Column Widget and populate its children with Icon and TextField.
Then Wrap the whole widget with GestureDetector for on pressed functionality.
You can also wrap it with InkWell and Material to get splash effect like in other buttons.</p>


答:
You need not wrap with column.</p>
```<code>TextButton(
        onPressed:(){},
        child: Column(
          children: [
            Icon(Icons.play_arrow,color:Colors.green),
            Text(
              'Hello',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
</code>```

Title: Flutter: How to make a button like this?

Body:
I tried to use TextButton.Icon to make the effect as following.
But I found that the words can only be at the left or right of the icon. How can I put the words under the icon like this?

Body:
You need not wrap with column.

TextButton(
        onPressed:(){},
        child: Column(
          children: [
            Icon(Icons.play_arrow,color:Colors.green),
            Text(
              'Hello',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),


问:
C: How can I create a 2d array that hold 2d arrays?
for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game

such that

```<code>int zone[2][2];
// fill zone array
int map[3][3];
map[0][0] = zone;
</code>```

答:
You can create a multi-dimensional 9x2x2 array where each 2x2 zone is accessed by their zone index (0-8).

int zone[9][2][2];

// I can now access any of the nine 2x2 zones using indices 0-8
zone[0][0][0]
zone[1][0][0]
zone[2][0][0]
...
zone[8][0][0]
```

Body:
for example I have generated a "zone" of 1s and 0s in a 2x2 2d array . But i need to store 9 of these zones to access whenever from another 3x3 2d array "map". The zone arrays are randomly generated and need to stay the same once added to the 2d map array, so that I could "leave" a zone and come back and itd be the same. Kinda like an ASCII game

such that

int zone[2][2];
// fill zone array
int map[3][3];
map[0][0] = zone;


问:
When and how can we start forgetting about non-retina display iPhones and iPod Touches?
Now more than one year passed since a retina display device appeared. Does anyone know some numbers how many users still suffer under the low-resolution devices? How long do they use their iPhones or iPods until they realize that a retina display is so much better?

I'm sick of having to create every graphic two times, trashing the binary with all these low-resolution files. I wonder if anyone has stopped supporting low resolution hardware without a big loss.

And: If I wanted to stop supporting low resolution devices, what kind of settings in the info.plist must I make? And what would happen if a low-res device still installs my retina-only app?

答:
Why do people still use IE 6? or why do some people still have Windows XP? Simply b/c they can't afford new ones. Money is to blame. There is no simple answer as to when should you stop supporting certain technology. In the technology world you should usually wait for a big company (like Facebook) to stop supporting certain devices. Only those big sharks can force people to switch.

If you want your users to be happy and want your software to be great you should always support all available devices/versions if possible. Little work for you is a big benefit for your users.

In the end you don't have to do anything you don't want to. But your software will resemble it.


问:
How to connect to and access information on a NoSQL database using C++
I want my code to be able to connect to a wide-column store database like Cassandra or DynamoDB and read/write information to it.

I have been working on a project primarily written in C++ and was able to use a MySQL database simply by including mysql.h header file and using some functions defined in this file to connect to the database and perform queries. I'm not sure if this is even the right way, but it gets the job done.

However, my project requires data to be stored in such a way that an entity can have multiple values under a single attribute (eg. hobbies: {fishing, camping, coding} )and so, I've come to a realization that RDBMS is not efficient in this scenario and decided to shift to a wide-column store database. But, I am not able to find any sort of guildlines on how I can connect to Cassandra or DynamoDB and perform queries using C++.

答: You can use Datastax C/C++ driver for connecting your application with Cassandra database.</p>


问:
Allow access when certain query string exists otherwise deny
I want to allow access to my site when there is s=stick_path or s=stick_relative in the query string otherwise deny the access. e.g allow access when www.domain.com/?s=stick_path but deny access when www.domain.com/?s=ck_relative or www.domain.com/?s=action_path.

I have tried for simple example like www.domain.com/?s=stick_path but it does not seem to work.

```<code>RewriteCond %{QUERY_STRING} !^s=stick_path$
RewriteRule ^.* - [F,L]
</code>```

I think one can trick the .htaccess rule if s parameter is present twice like www.domain.com/?s=stick_path&s=action_path

答:
Answer pulled from an OP's update

RewriteEngine ON was missing in the .htaccess.

So, the correct code was:

```<code>RewriteEngine on
RewriteCond %{QUERY_STRING} !^s=stick_path$
RewriteRule ^.* - [F,L]
</code>```

Body:
I want to allow access to my site when there is s=stick_path or s=stick_relative in the query string otherwise deny the access. e.g allow access when www.domain.com/?s=stick_path but deny access when www.domain.com/?s=ck_relative or www.domain.com/?s=action_path.

I have tried for simple example like www.domain.com/?s=stick_path but it does not seem to work.

RewriteCond %{QUERY_STRING} !^s=stick_path$
RewriteRule ^.* - [F,L]

I think one can trick the .htaccess rule if s parameter is present twice like www.domain.com/?s=stick_path&s=action_path

Body:
Answer pulled from an OP's update

RewriteEngine ON was missing in the .htaccess.

So, the correct code was:

RewriteEngine on
RewriteCond %{QUERY_STRING} !^s=stick_path$
RewriteRule ^.* - [F,L]


问:
searching for words from a text file in discord.py
So I've been developing a discord bot for my server to delete slurs, and its going well, but i want to know how I would use this line of code:

```<code>@client.event
async def on_message(message):
    if "slur" in message.content:
        print("slur deleted")
        await message.channel.send("No cussing!")
        await client.process_commands(message)
        await message.delete()
</code>```

read from a list of words in a .txt file instead of that one word?

答:
so make one file , lets assume file name words.txt and then we will open file and put all words in each line.And remember all words should be in lower cases in the file
and then use this code:

@client.event
async def on_message(message):
    with open("words.txt","r") as f:
        words = f.readlines()
    if words in message.content.lower():
        print("slur deleted")
        await message.channel.send("No cussing!")
        await message.delete()
    await client.process_commands(message)
```

Body:
So I've been developing a discord bot for my server to delete slurs, and its going well, but i want to know how I would use this line of code:

@client.event
async def on_message(message):
    if "slur" in message.content:
        print("slur deleted")
        await message.channel.send("No cussing!")
        await client.process_commands(message)
        await message.delete()

read from a list of words in a .txt file instead of that one word?


问:
Confidence Interval and Standard error of Skewness and Kurtosis
Please tell me how to calculate skewness and kurtosis along with their respective standard error and confidence interval associated with it(i.e. SE of Skewness and S.E of Kurtosis) I found two packages

1) package:'measure' can only calculate skewness and kurtosis

2) package:'rela'  can calcuate both skewness and kurtosis but uses bootstrap by default and no command to turn it off during the calculation.

答:
```<code>def skew_kurt(dataframe: pd.DataFrame) -> pd.DataFrame:

out = []
for col in dataframe:

    x = dataframe[col]
    sd = x.std()

    if sd == 0:
        out.append({name: np.nan for name in ['skew stat', 'skew se', 'kurt stat', 'kurt se']})
        continue

    w, m1 = len(x), x.mean()
    dif = x - m1
    m2, m3, m4 = tuple([(dif ** i).sum() for i in range(2, 5)])

    skew = w * m3 / (w - 1) / (w - 2) / sd ** 3
    skew_se = np.sqrt(6 * w * (w - 1) / ((w - 2) * (w + 1) * (w + 3)))

    kurt = (w * (w + 1) * m4 - 3 * m2 ** 2 * (w - 1)) / ((w - 1) * (w - 2) * (w - 3) * sd ** 4)
    kurt_se = np.sqrt(4 * (w ** 2 - 1) * skew_se ** 2 / ((w - 3) * (w + 5)))

    out.append({'skew stat': skew, 'skew se': skew_se, 'kurt stat': kurt, 'kurt se': kurt_se})

dataframe = pd.DataFrame(out, index = list(dataframe))
dataframe['skew<2'] = np.absolute(dataframe['skew stat']) < 2 * dataframe['skew se']
dataframe['kurt<2'] = np.absolute(dataframe['kurt stat']) < 2 * dataframe['kurt se']

return dataframe[['skew stat', 'skew se', 'skew<2', 'kurt stat', 'kurt se', 'kurt<2']]
</code>```


问:
pivot_longer by match in other column
I have a dataset similar to the following that I've wrangling from two different datasets using tidyverse:

What I want is to pivot_longer resident_census_total and visitor_census_total into a new column called 'census_totals'. However, I also need them to match the appropriate status, e.g. when status == 'Resident', I need the 'census_totals' column to have the value from resident_census_total, and vice versa with Visitor. This is where I'm running into trouble, because just using

```<code>pivot_longer(
  cols = c("resident_census_total, "visitor_census_total"),
  names_to = "census_totals"
)
</code>```

leads to the data from the two columns simply alternating, rather than matching appropriately.

Dummy dataframe below:

```<code>dummy <- data.frame(
  location = rep(c("j210", "s34", "q3"), 6),
  day = rep(c("Day 1", "Day 2", "Day 3"), each = 3),
  period = rep(c("2019_fire", "2020_YOY", "2021_YOY"), 6),
  total_agents = c(3585, 1234, 0, 456, 124, 688, 24, 1235, 77, 4578, 357, 124,
                   2345, 14, 1223, 345, 123, 22),
  Status = rep(c("Resident", "Visitor"), 9),
  resident_census_total = rep(c(127, 345, 1123), 6),
  visitor_census_total = rep(c(0, 266, 456), 6)
)
)
</code>```

答:
It'd great if you could provide an example of your desired output so that our answers would be more accurate.

Based on your question, I'm guessing you want a column of consensus_totals to replace resident_census_total and visitor_census_total. You don't really need to use pivot_longer in this case, just use case_when() to match your Status and output the appropriate columns.

Here's a tidyverse approach:

You can use ifelse(Status == "Resident", resident_census_total, visitor_census_total) to replace case_when() if you're sure you only have TWO Status.

```<code>library(tidyverse)

dummy %>% mutate(census_totals = case_when(Status == "Resident" ~ resident_census_total,
                                           Status == "Visitor" ~ visitor_census_total)) %>%
  select(-resident_census_total, -visitor_census_total)
</code>```

Output

```<code>   location   day    period total_agents   Status census_totals
1      j210 Day 1 2019_fire         3585 Resident           127
2       s34 Day 1  2020_YOY         1234  Visitor           266
3        q3 Day 1  2021_YOY            0 Resident          1123
4      j210 Day 2 2019_fire          456  Visitor             0
5       s34 Day 2  2020_YOY          124 Resident           345
6        q3 Day 2  2021_YOY          688  Visitor           456
7      j210 Day 3 2019_fire           24 Resident           127
8       s34 Day 3  2020_YOY         1235  Visitor           266
9        q3 Day 3  2021_YOY           77 Resident          1123
10     j210 Day 1 2019_fire         4578  Visitor             0
11      s34 Day 1  2020_YOY          357 Resident           345
12       q3 Day 1  2021_YOY          124  Visitor           456
13     j210 Day 2 2019_fire         2345 Resident           127
14      s34 Day 2  2020_YOY           14  Visitor           266
15       q3 Day 2  2021_YOY         1223 Resident          1123
16     j210 Day 3 2019_fire          345  Visitor             0
17      s34 Day 3  2020_YOY          123 Resident           345
18       q3 Day 3  2021_YOY           22  Visitor           456
</code>```

Your dataset for reference

```<code>  location   day    period total_agents   Status resident_census_total visitor_census_total
1      j210 Day 1 2019_fire         3585 Resident                   127                    0
2       s34 Day 1  2020_YOY         1234  Visitor                   345                  266
3        q3 Day 1  2021_YOY            0 Resident                  1123                  456
4      j210 Day 2 2019_fire          456  Visitor                   127                    0
5       s34 Day 2  2020_YOY          124 Resident                   345                  266
6        q3 Day 2  2021_YOY          688  Visitor                  1123                  456
7      j210 Day 3 2019_fire           24 Resident                   127                    0
8       s34 Day 3  2020_YOY         1235  Visitor                   345                  266
9        q3 Day 3  2021_YOY           77 Resident                  1123                  456
10     j210 Day 1 2019_fire         4578  Visitor                   127                    0
11      s34 Day 1  2020_YOY          357 Resident                   345                  266
12       q3 Day 1  2021_YOY          124  Visitor                  1123                  456
13     j210 Day 2 2019_fire         2345 Resident                   127                    0
14      s34 Day 2  2020_YOY           14  Visitor                   345                  266
15       q3 Day 2  2021_YOY         1223 Resident                  1123                  456
16     j210 Day 3 2019_fire          345  Visitor                   127                    0
17      s34 Day 3  2020_YOY          123 Resident                   345                  266
18       q3 Day 3  2021_YOY           22  Visitor                  1123                  456
</code>```

Title: pivot_longer by match in other column

Body:
I have a dataset similar to the following that I've wrangling from two different datasets using tidyverse:

What I want is to pivot_longer resident_census_total and visitor_census_total into a new column called 'census_totals'. However, I also need them to match the appropriate status, e.g. when status == 'Resident', I need the 'census_totals' column to have the value from resident_census_total, and vice versa with Visitor. This is where I'm running into trouble, because just using

pivot_longer(
  cols = c("resident_census_total, "visitor_census_total"),
  names_to = "census_totals"
)

leads to the data from the two columns simply alternating, rather than matching appropriately.

Dummy dataframe below:

dummy <- data.frame(
  location = rep(c("j210", "s34", "q3"), 6),
  day = rep(c("Day 1", "Day 2", "Day 3"), each = 3),
  period = rep(c("2019_fire", "2020_YOY", "2021_YOY"), 6),
  total_agents = c(3585, 1234, 0, 456, 124, 688, 24, 1235, 77, 4578, 357, 124,
                   2345, 14, 1223, 345, 123, 22),
  Status = rep(c("Resident", "Visitor"), 9),
  resident_census_total = rep(c(127, 345, 1123), 6),
  visitor_census_total = rep(c(0, 266, 456), 6)
)
)

Body:
It'd great if you could provide an example of your desired output so that our answers would be more accurate.

Based on your question, I'm guessing you want a column of consensus_totals to replace resident_census_total and visitor_census_total. You don't really need to use pivot_longer in this case, just use case_when() to match your Status and output the appropriate columns.

Here's a tidyverse approach:

You can use ifelse(Status == "Resident", resident_census_total, visitor_census_total) to replace case_when() if you're sure you only have TWO Status.

library(tidyverse)

dummy %>% mutate(census_totals = case_when(Status == "Resident" ~ resident_census_total,
                                           Status == "Visitor" ~ visitor_census_total)) %>%
  select(-resident_census_total, -visitor_census_total)

Output

   location   day    period total_agents   Status census_totals
1      j210 Day 1 2019_fire         3585 Resident           127
2       s34 Day 1  2020_YOY         1234  Visitor           266
3        q3 Day 1  2021_YOY            0 Resident          1123
4      j210 Day 2 2019_fire          456  Visitor             0
5       s34 Day 2  2020_YOY          124 Resident           345
6        q3 Day 2  2021_YOY          688  Visitor           456
7      j210 Day 3 2019_fire           24 Resident           127
8       s34 Day 3  2020_YOY         1235  Visitor           266
9        q3 Day 3  2021_YOY           77 Resident          1123
10     j210 Day 1 2019_fire         4578  Visitor             0
11      s34 Day 1  2020_YOY          357 Resident           345
12       q3 Day 1  2021_YOY          124  Visitor           456
13     j210 Day 2 2019_fire         2345 Resident           127
14      s34 Day 2  2020_YOY           14  Visitor           266
15       q3 Day 2  2021_YOY         1223 Resident          1123
16     j210 Day 3 2019_fire          345  Visitor             0
17      s34 Day 3  2020_YOY          123 Resident           345
18       q3 Day 3  2021_YOY           22  Visitor           456

Your dataset for reference

  location   day    period total_agents   Status resident_census_total visitor_census_total
1      j210 Day 1 2019_fire         3585 Resident                   127                    0
2       s34 Day 1  2020_YOY         1234  Visitor                   345                  266
3        q3 Day 1  2021_YOY            0 Resident                  1123                  456
4      j210 Day 2 2019_fire          456  Visitor                   127                    0
5       s34 Day 2  2020_YOY          124 Resident                   345                  266
6        q3 Day 2  2021_YOY          688  Visitor                  1123                  456
7      j210 Day 3 2019_fire           24 Resident                   127                    0
8       s34 Day 3  2020_YOY         1235  Visitor                   345                  266
9        q3 Day 3  2021_YOY           77 Resident                  1123                  456
10     j210 Day 1 2019_fire         4578  Visitor                   127                    0
11      s34 Day 1  2020_YOY          357 Resident                   345                  266
12       q3 Day 1  2021_YOY          124  Visitor                  1123                  456
13     j210 Day 2 2019_fire         2345 Resident                   127                    0
14      s34 Day 2  2020_YOY           14  Visitor                   345                  266
15       q3 Day 2  2021_YOY         1223 Resident                  1123                  456
16     j210 Day 3 2019_fire          345  Visitor                   127                    0
17      s34 Day 3  2020_YOY          123 Resident                   345                  266
18       q3 Day 3  2021_YOY           22  Visitor                  1123                  456


问:
command "django-admin.py startproject mysite" not recognized
EDIT: I added the path to django-admin.py to my system path (C:\Users\me\Downloads\Django-1.5.1\django\bin) but even after this when I try to run django-admin.py startproject mysite, it asks me to pick a file to open with and even when I pick python.py, it opens in chrome for some reason. I also tried python django-admin.py startproject mysite but it says

python: can't open file django-admin.py: [Errno 2] No such file or directory

Any idea what is wrong?

I added python27 to the system path and when I open up cmd and switch to a directory (C:\Users\me\djcode) and then type in django-admin.py startproject mysite it says

django-admin.py is not recognized as an internal or external command, operable program or batch file

When I try typing the command python django-admin.py startproject mysite, it says

python: can't open file django-admin.py: [Errno 2] No such file or directory

Any idea why?

In the djangobook (http://www.djangobook.com/en/2.0/chapter02.html) it says

django-admin.py should be on your system path if you installed Django via its setup.py utility

what does this mean? how do I add django-admin.py to my system path? I am not sure where django-admin.py even is.

答: I have tried all of the mentioned things however I was still unable to create a project using django-admin startapp appname. So I used python -m django startproject appname instead and was able to create the proejct


问:
How do I Add Custom XML to An Element Using Python-Docx?
I've been trying to get text wrapping for my table which isn't implemented in python-docx.

So far so good, I've isolated that MS Word adds <w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="text" w:tblpY="1"/> as a child to the table properties element so I just need to inject that into my table in python-docx.

I got real close. Because I was able to find the element class in the library to add a child to. However my problem lays in the w: namespace because it won't let me construct an Element tag with the ':' character in it. I tried two methods, both failed.

tblPrElement = Element('w:tblpPr ', {'w:leftFromText': '180', 'w:rightFromText': '180', 'w:vertAnchor': 'text', 'w:tblpY': '1' })

tblPrElement = parse_xml('<w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="text" w:tblpY="1"/>')

If I try it omitting the w: ...

```<code>document = Document()
table = document.add_table(rows=1, cols=3)
tblPrElement = parse_xml('<tblpPr leftFromText="180" rightFromText="180" vertAnchor="text" tblpY="1"/>')
table._tblPr.append(tblPrElement)
</code>```

...then the document builds but ms word can't open it because the xml then looks like this:

答:
python-docx has a qn method for using with element creation.

def qn(tag):
    """
    Stands for "qualified name", a utility function to turn a namespace
    prefixed tag name into a Clark-notation qualified tag name for lxml. For
    example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
    """
```
<p>It allows you to type XML with namespace prefixes.</p>
<pre class="lang-py prettyprint-override"><code>from docx.oxml.ns import qn

def set_text_wrap_around_table(table):
    tbl_properties_element = Element(qn('w:tblpPr'),
                           {
                              qn('w:leftFromText'): '180',
                              qn('w:rightFromText'): '180',
                              qn('w:vertAnchor'): 'text',
                              qn('w:tblpY'): '1'
                           })
    table._tblPr.append(tbl_properties_element)
</code>```

If the element you'd like to create already has a class defined in python-docx you can create it using docx.oxml.OxmlElement for example, you can create a paragraph run element class like so:

from docx.oxml import OxmlElement

run_element = OxmlElement('w:r')
```

This has the added benefits of having its possible children defined as attributes and more.

Body:
I've been trying to get text wrapping for my table which isn't implemented in python-docx.

So far so good, I've isolated that MS Word adds <w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="text" w:tblpY="1"/> as a child to the table properties element so I just need to inject that into my table in python-docx.

I got real close. Because I was able to find the element class in the library to add a child to. However my problem lays in the w: namespace because it won't let me construct an Element tag with the ':' character in it. I tried two methods, both failed.

tblPrElement = Element('w:tblpPr ', {'w:leftFromText': '180', 'w:rightFromText': '180', 'w:vertAnchor': 'text', 'w:tblpY': '1' })

tblPrElement = parse_xml('<w:tblpPr w:leftFromText="180" w:rightFromText="180" w:vertAnchor="text" w:tblpY="1"/>')

If I try it omitting the w: ...

document = Document()
table = document.add_table(rows=1, cols=3)
tblPrElement = parse_xml('<tblpPr leftFromText="180" rightFromText="180" vertAnchor="text" tblpY="1"/>')
table._tblPr.append(tblPrElement)

...then the document builds but ms word can't open it because the xml then looks like this:

Body:
python-docx has a qn method for using with element creation.

def qn(tag):
    """
    Stands for "qualified name", a utility function to turn a namespace
    prefixed tag name into a Clark-notation qualified tag name for lxml. For
    example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
    """

It allows you to type XML with namespace prefixes.

from docx.oxml.ns import qn

def set_text_wrap_around_table(table):
    tbl_properties_element = Element(qn('w:tblpPr'),
                           {
                              qn('w:leftFromText'): '180',
                              qn('w:rightFromText'): '180',
                              qn('w:vertAnchor'): 'text',
                              qn('w:tblpY'): '1'
                           })
    table._tblPr.append(tbl_properties_element)

If the element you'd like to create already has a class defined in python-docx you can create it using docx.oxml.OxmlElement for example, you can create a paragraph run element class like so:

from docx.oxml import OxmlElement

run_element = OxmlElement('w:r')

This has the added benefits of having its possible children defined as attributes and more.


问:
Custom display in CRUDified object
I have a an entity referencing another entity by MappedLongForeignKey.

I am using the CRUDify trait and have a problem.

```<code>Entity 1:
id
title (String)
validTo (Date)

Entity 2:
id
...
fk_entity_1 (mapped via MappedLongForeignKey)
</code>```

In the listings generated by CRUDify for entity 2 I would like to include a column formatted as

```<code>fk_entity_1.title ( fk_entity_1.validTo )
</code>```

I tried to create a function returning such a string and adding that fn to fieldsForDisplay, but it seems fieldsForDisplay requires mapped fields.

Is this possible to accomplish?

* Edit *
What I am trying to accomplish is (using the built in functionality of CRUDify for listings) produce listings as:

```<code>{Entity 2 fields}   "Entity 1"
 ...                Title_X (2001-01-01)
 ...                Title_Y (2011-02-02)
</code>```

If worse comes to worst, I can roll my own listings, but I really like the CRUDify functionality.

答: I'm not quite sure what you're trying to accomplish, but maybe you could override the asHtml method of the fields instead?</p>

Title: Custom display in CRUDified object

Body:
I have a an entity referencing another entity by MappedLongForeignKey.

I am using the CRUDify trait and have a problem.

Entity 1:
id
title (String)
validTo (Date)

Entity 2:
id
...
fk_entity_1 (mapped via MappedLongForeignKey)

In the listings generated by CRUDify for entity 2 I would like to include a column formatted as

fk_entity_1.title ( fk_entity_1.validTo )

I tried to create a function returning such a string and adding that fn to fieldsForDisplay, but it seems fieldsForDisplay requires mapped fields.

Is this possible to accomplish?

* Edit *
What I am trying to accomplish is (using the built in functionality of CRUDify for listings) produce listings as:

{Entity 2 fields}   "Entity 1"
 ...                Title_X (2001-01-01)
 ...                Title_Y (2011-02-02)

If worse comes to worst, I can roll my own listings, but I really like the CRUDify functionality.


问:
Why does fgetc() in C always reads extra, non-existent characters whenever I try to read non-printable characters from txt files?
I am trying to read non-printable characters from a text file, print out the characters' ASCII code, and finally write these non-printable characters into an output file.

However, I have noticed that for every non-printable character I read, there is always an extra non-printable character existing in front of what I really want to read.

For example, the character I want to read is "§".
And when I print out its ASCII code in my program, instead of printing just "167", it prints out "194 167".

I looked it up in the debugger and saw "Â§" in the char array. But I don't have Â anywhere in my input file.
screenshot of debugger

And after I write the non-printable character into my output file, I have noticed that it is also just "§", not "Â§".

There is an extra character being attached to every single non-printable character I read. Why is this happening? How do I get rid of it?

Thanks!

Code as follows:

```<code>        case 1:
            mode = 1;
            FILE *fp;
            fp = fopen ("input2.txt", "r");
            int charCount = 0;

            while(!feof(fp)) {
                original_message[charCount] = fgetc(fp);
                charCount++;
            }
            original_message[charCount - 1] = '\0';
            fclose(fp);

            k = strlen(original_message);//split the original message into k input symbols
            printf("k: \n%lld\n", k);

            printf("ASCII code:\n");
            for (int i = 0; i < k; i++)
            {
                ASCII = original_message[i];
                printf("%d ", ASCII);
            }
</code>```

答:
C's getchar (and getc and fgetc) functions are designed to read individual bytes.  They won't directly handle "wide" or "multibyte" characters such as occur in the UTF-8 encoding of Unicode.

But there are other functions which are specifically designed to deal with those extended characters.  In particular, if you wish, you can replace your call to fgetc(fp) with fgetwc(fp), and then you should be able to start reading characters like § as themselves.

You will have to #include <wchar.h> to get the prototype for fgetwc.  And you may have to add the call

```<code>setlocale(LC_CTYPE, "");
</code>```

at the top of your program to synchronize your program's character set "locale" with that of your operating system.

Not your original code, but I wrote this little program:

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

int main()
{
    wchar_t c;
    setlocale(LC_CTYPE, "");
    while((c = fgetwc(stdin)) != EOF)
        printf("%lc %d\n", c, c);
}
</code>```

When I type "A", it prints A 65.
When I type "§", it prints § 167.
When I type "Ƶ", it prints Ƶ 437.
When I type "†", it prints † 8224.

Now, with all that said, reading wide characters using functions like fgetwc isn't the only or necessarily even the best way of dealing with extended characters.  In your case, it carries a number of additional consequences:

Your original_message array is going to have to be an array of wchar_t, not an array of char.

Your original_message array isn't going to be an ordinary C string — it's a "wide character string".  So you can't call strlen on it; you're going to have to call wcslen.

Similarly, you can't print it using %s, or its characters using %c.  You'll have to remember to use %ls or %lc.

So although you can convert your entire program to use "wide" strings and "w" functions everywhere, it's a ton of work.  In many cases, and despite anomalies like the one you asked about, it's much easier to use UTF-8 everywhere, since it tends to Just Work.  In particular, as long as you don't have to pick a string apart and work with its individual characters, or compute the on-screen display length of a string (in "characters") using strlen, you can just use plain C strings everywhere, and let the magic of UTF-8 sequences take care of any non-ASCII characters your users happen to enter.

Body:
I am trying to read non-printable characters from a text file, print out the characters' ASCII code, and finally write these non-printable characters into an output file.

However, I have noticed that for every non-printable character I read, there is always an extra non-printable character existing in front of what I really want to read.

For example, the character I want to read is "§".
And when I print out its ASCII code in my program, instead of printing just "167", it prints out "194 167".

I looked it up in the debugger and saw "Â§" in the char array. But I don't have Â anywhere in my input file.
screenshot of debugger

And after I write the non-printable character into my output file, I have noticed that it is also just "§", not "Â§".

There is an extra character being attached to every single non-printable character I read. Why is this happening? How do I get rid of it?

Thanks!

Code as follows:

        case 1:
            mode = 1;
            FILE *fp;
            fp = fopen ("input2.txt", "r");
            int charCount = 0;

            while(!feof(fp)) {
                original_message[charCount] = fgetc(fp);
                charCount++;
            }
            original_message[charCount - 1] = '\0';
            fclose(fp);

            k = strlen(original_message);//split the original message into k input symbols
            printf("k: \n%lld\n", k);

            printf("ASCII code:\n");
            for (int i = 0; i < k; i++)
            {
                ASCII = original_message[i];
                printf("%d ", ASCII);
            }

Body:
C's getchar (and getc and fgetc) functions are designed to read individual bytes.  They won't directly handle "wide" or "multibyte" characters such as occur in the UTF-8 encoding of Unicode.

But there are other functions which are specifically designed to deal with those extended characters.  In particular, if you wish, you can replace your call to fgetc(fp) with fgetwc(fp), and then you should be able to start reading characters like § as themselves.

You will have to #include <wchar.h> to get the prototype for fgetwc.  And you may have to add the call

setlocale(LC_CTYPE, "");

at the top of your program to synchronize your program's character set "locale" with that of your operating system.

Not your original code, but I wrote this little program:

#include <stdio.h>
#include <wchar.h>
#include <locale.h>

int main()
{
    wchar_t c;
    setlocale(LC_CTYPE, "");
    while((c = fgetwc(stdin)) != EOF)
        printf("%lc %d\n", c, c);
}

When I type "A", it prints A 65.
When I type "§", it prints § 167.
When I type "Ƶ", it prints Ƶ 437.
When I type "†", it prints † 8224.

Now, with all that said, reading wide characters using functions like fgetwc isn't the only or necessarily even the best way of dealing with extended characters.  In your case, it carries a number of additional consequences:

Your original_message array is going to have to be an array of wchar_t, not an array of char.

Your original_message array isn't going to be an ordinary C string — it's a "wide character string".  So you can't call strlen on it; you're going to have to call wcslen.

Similarly, you can't print it using %s, or its characters using %c.  You'll have to remember to use %ls or %lc.

So although you can convert your entire program to use "wide" strings and "w" functions everywhere, it's a ton of work.  In many cases, and despite anomalies like the one you asked about, it's much easier to use UTF-8 everywhere, since it tends to Just Work.  In particular, as long as you don't have to pick a string apart and work with its individual characters, or compute the on-screen display length of a string (in "characters") using strlen, you can just use plain C strings everywhere, and let the magic of UTF-8 sequences take care of any non-ASCII characters your users happen to enter.


问:
Iterating over string returns empty in c (os development)
I was making an os, or atleast trying to, but I stumbled upon a problem. While trying to iterate over a string to convert to char to print to screen, the returned char seemed to be empty!(I am actually new to os development); Here is the code snippet:

int offset = 0;

void clear_screen() {
    unsigned char * video = 0xB8000;
    for(int i = 0; i < 2000; i+=2){
        video[i] = ' ';
    }
}

void printc(char c) {
    unsigned char * video = 0xB8000;
    video[offset] = c;
    video[offset+1] = 0x03;
    offset += 2;
}

void print(unsigned char *string) {
    char * sus = '\0';
    uint32 i = 0;
    printc('|');
    sus[0] = 'a';
    printc(sus[0]);  //this prints "a" correctly
    string[i] = 'c';
    while (string[i] != '\0') {
        printc(string[i]);   //this while loop is only called once
        i++;                 //it prints " " only once and exits
    }
    printc('|');
}

int bootup(void)
{
    clear_screen();

    // printc('h');
    // printc('e');
    // printc('l');                     /* These work */
    // printc('l');
    // printc('o');

    print("hello"); //this doesn't

    return 1;

}
```
<p>Output that it prints:</p>
```|a |
```
<p>Thanks in advance!!</p>
<p><strong>edit</strong></p>
<p>New print function</p>
<pre class="lang-c prettyprint-override"><code>void print(unsigned char *string) {
    uint32 i = 0;
    printc('|');
    while (string[i] != '\0') {
        printc('i');  //not printed
        printc(string[i]);
        i++;
    }
    printc('|');
}
</code>```

still does not work

edit 2
updated the code as per @lundin's advice

int offset = 0;

void clear_screen() {
    unsigned char * video = (unsigned char *)0xB8000;
    for(int i = 0; i < 2000; i+=2){
        video[i] = ' ';
    }
}

void printc(char c) {
    unsigned char * video = (unsigned char *)0xB8000;
    video[offset] = c;
    video[offset+1] = 0x03;
    offset += 2;
}

void print(const char *string) {
    int i = 0;
    printc('|');
    while (string[i] != '\0') {
        printc('i');
        printc(string[i]);
        i++;
    }
    printc('|');
}

int bootup(void)
{
    clear_screen();
    // printc('h');
    // printc('e');
    // printc('l');
    // printc('l');
    // printc('o');
    print("hello");
    return 1;

}
```
<p>stack:</p>
```init_lm:
    mov ax, 0x10
    mov fs, ax          ;other segments are ignored
    mov gs, ax

    mov rbp, 0x90000    ;set up stack
    mov rsp, rbp

    ;Load kernel from disk
    xor ebx, ebx        ;upper 2 bytes above bh in ebx is for cylinder = 0x0
    mov bl, 0x2         ;read from 2nd sectors
    mov bh, 0x0         ;head
    mov ch, 1           ;read 1 sector
    mov rdi, KERNEL_ADDRESS
    call ata_chs_read

    jmp KERNEL_ADDRESS

    jmp $
```

答:
Before proceeding I would recommend reading the OSDev wiki's page on text-based UIs.

While this may go beyond the scope of the question somewhat, I would strongly recommend that, rather than working with the character/attribute values as unsigned char manually, you might want to declare a struct type for those pairs:

```<code>struct TextCell {
    volatile unsigned char ch;
    volatile uint8_t attribute;
};
</code>```

(You could actually be even more refined about it, by using a bitfield for the individual foreground, background, and decoration components of the attributes, but that's probably getting ahead of things.)

From there you can define the text buffer as a constant pointer:

```<code>const struct TextCell* text_buffer = (TextCell *)0xB8000;
</code>```

You could further define

```<code>const uint16_t MAXH = 80, MAXV = 25;
uint16_t currv = 0, currh = 0;
struct TextCell* text_cursor = text_buffer;

void advance_cursor() {
    text_cursor++;
    if (currh < MAXH) {
        currh++;
    }
    else {
        currh = 0;
        if (currv < MAXV) {
            currv++;
        }
        else {
            /* handle scrolling */
        }
    }
}

void gotoxy(uint16_t x, uint16_t y) {
    uint16_t new_pos = x * y;
    if (new_pos > (MAXV * MAXH)) {
        text_cursor = text_buffer + (MAXV * MAXH);
        currh = MAXH;
        currv = MAXV;
    }
    else {
        text_cursor += new_pos;
        currh = x;
        currv = y;
}
</code>```

Which would lead to the following modifications of your code:

```<code>void kprintc(char c, uint8_t attrib) {
    text_cursor->ch = c;
    text_cursor->attribute = attrib;
    advance_cursor();
}

void kprint(const char *string, uint8_t attribs) {
    int i;
    for (i = 0; string[i] != '\0'; i++) {
        kprintc(string[i], attribs);
    }
}

void clear_screen() {
    for(int i = 0; i < (MAXH * MAXV); i++) {
        kprintc(' ', 0);
    }
}

int bootup(void) {
    clear_screen();
    // kprintc('h', 0x03);
    // kprintc('e', 0x03);
    // kprintc('l', 0x03);
    // kprintc('l', 0x03);
    // kprintc('o', 0x03);
    kprint("hello", 0x03);
    return 1;
}
</code>```

So, why am I suggesting all of this extra stuff? Because it is a lot easier to debug this way, mainly - it divides the concerns up better, and structures the data (or in this case, the video text buffer) more effectively. Also, you'll eventually need to do something like this at some point in the project, so if it helps now, you might as well do it now.

If I am out of line in this, please let me know.

Body:
I was making an os, or atleast trying to, but I stumbled upon a problem. While trying to iterate over a string to convert to char to print to screen, the returned char seemed to be empty!(I am actually new to os development); Here is the code snippet:

int offset = 0;

void clear_screen() {
    unsigned char * video = 0xB8000;
    for(int i = 0; i < 2000; i+=2){
        video[i] = ' ';
    }
}

void printc(char c) {
    unsigned char * video = 0xB8000;
    video[offset] = c;
    video[offset+1] = 0x03;
    offset += 2;
}

void print(unsigned char *string) {
    char * sus = '\0';
    uint32 i = 0;
    printc('|');
    sus[0] = 'a';
    printc(sus[0]);  //this prints "a" correctly
    string[i] = 'c';
    while (string[i] != '\0') {
        printc(string[i]);   //this while loop is only called once
        i++;                 //it prints " " only once and exits
    }
    printc('|');
}

int bootup(void)
{
    clear_screen();

    // printc('h');
    // printc('e');
    // printc('l');                     /* These work */
    // printc('l');
    // printc('o');

    print("hello"); //this doesn't

    return 1;

}

Output that it prints:

|a |

Thanks in advance!!

edit

New print function

void print(unsigned char *string) {
    uint32 i = 0;
    printc('|');
    while (string[i] != '\0') {
        printc('i');  //not printed
        printc(string[i]);
        i++;
    }
    printc('|');
}

still does not work

edit 2
updated the code as per @lundin's advice

int offset = 0;

void clear_screen() {
    unsigned char * video = (unsigned char *)0xB8000;
    for(int i = 0; i < 2000; i+=2){
        video[i] = ' ';
    }
}

void printc(char c) {
    unsigned char * video = (unsigned char *)0xB8000;
    video[offset] = c;
    video[offset+1] = 0x03;
    offset += 2;
}

void print(const char *string) {
    int i = 0;
    printc('|');
    while (string[i] != '\0') {
        printc('i');
        printc(string[i]);
        i++;
    }
    printc('|');
}

int bootup(void)
{
    clear_screen();
    // printc('h');
    // printc('e');
    // printc('l');
    // printc('l');
    // printc('o');
    print("hello");
    return 1;

}

stack:

init_lm:
    mov ax, 0x10
    mov fs, ax          ;other segments are ignored
    mov gs, ax

    mov rbp, 0x90000    ;set up stack
    mov rsp, rbp

    ;Load kernel from disk
    xor ebx, ebx        ;upper 2 bytes above bh in ebx is for cylinder = 0x0
    mov bl, 0x2         ;read from 2nd sectors
    mov bh, 0x0         ;head
    mov ch, 1           ;read 1 sector
    mov rdi, KERNEL_ADDRESS
    call ata_chs_read

    jmp KERNEL_ADDRESS

    jmp $

Body:
Before proceeding I would recommend reading the OSDev wiki's page on text-based UIs.

While this may go beyond the scope of the question somewhat, I would strongly recommend that, rather than working with the character/attribute values as unsigned char manually, you might want to declare a struct type for those pairs:

struct TextCell {
    volatile unsigned char ch;
    volatile uint8_t attribute;
};

(You could actually be even more refined about it, by using a bitfield for the individual foreground, background, and decoration components of the attributes, but that's probably getting ahead of things.)

From there you can define the text buffer as a constant pointer:

const struct TextCell* text_buffer = (TextCell *)0xB8000;

You could further define

const uint16_t MAXH = 80, MAXV = 25;
uint16_t currv = 0, currh = 0;
struct TextCell* text_cursor = text_buffer;

void advance_cursor() {
    text_cursor++;
    if (currh < MAXH) {
        currh++;
    }
    else {
        currh = 0;
        if (currv < MAXV) {
            currv++;
        }
        else {
            /* handle scrolling */
        }
    }
}

void gotoxy(uint16_t x, uint16_t y) {
    uint16_t new_pos = x * y;
    if (new_pos > (MAXV * MAXH)) {
        text_cursor = text_buffer + (MAXV * MAXH);
        currh = MAXH;
        currv = MAXV;
    }
    else {
        text_cursor += new_pos;
        currh = x;
        currv = y;
}

Which would lead to the following modifications of your code:

void kprintc(char c, uint8_t attrib) {
    text_cursor->ch = c;
    text_cursor->attribute = attrib;
    advance_cursor();
}

void kprint(const char *string, uint8_t attribs) {
    int i;
    for (i = 0; string[i] != '\0'; i++) {
        kprintc(string[i], attribs);
    }
}

void clear_screen() {
    for(int i = 0; i < (MAXH * MAXV); i++) {
        kprintc(' ', 0);
    }
}

int bootup(void) {
    clear_screen();
    // kprintc('h', 0x03);
    // kprintc('e', 0x03);
    // kprintc('l', 0x03);
    // kprintc('l', 0x03);
    // kprintc('o', 0x03);
    kprint("hello", 0x03);
    return 1;
}

So, why am I suggesting all of this extra stuff? Because it is a lot easier to debug this way, mainly - it divides the concerns up better, and structures the data (or in this case, the video text buffer) more effectively. Also, you'll eventually need to do something like this at some point in the project, so if it helps now, you might as well do it now.

If I am out of line in this, please let me know.


问:
React Navigation: Force screen to animate from left to right
With React Navigation v6.x and using the .navigate() function, new views always animate from right to left.

Typically this is fine, but I have a couple views that I always want to load from the left.

I have tried to read the docs, code examples, and stackoverflow threads related to transitions and I cannot glean any useful information.

Can anyone can give me some pointers on this?

Cheers

答:
First make this below.

```<code> const leftToRightAnimation = {
  cardStyleInterpolator: ({ current, layouts }) => {
    return {
      cardStyle: {
        transform: [
          {
            translateX: current.progress.interpolate({
              inputRange: [0, 1],
              outputRange: [-layouts.screen.width, 0],
            }),
          },
        ],
      },
    };
  },
};
</code>```

Basically all it's doing is it's moving the screen from the x direction of full screen width away in left direction to fitting the screen. And implicitly progress is going from 0 to 1.

The transform works just like any other react-native component read more here (https://reactnative.dev/docs/transforms).

And it uses interpolate from the react-native animated (https://reactnative.dev/docs/animated)

Then put it in the screen you want the transition to apply to.

```<code><NavigationContainer>
      <Root.Navigator headerMode="none" initialRouteName="Home">
        <Root.Screen name="Home" component={Home} />
        <Root.Screen name="NotModal" component={NotModal} options={leftToRightAnimation} />
      </Root.Navigator>
 </NavigationContainer>
</code>```

Body:
First make this below.

 const leftToRightAnimation = {
  cardStyleInterpolator: ({ current, layouts }) => {
    return {
      cardStyle: {
        transform: [
          {
            translateX: current.progress.interpolate({
              inputRange: [0, 1],
              outputRange: [-layouts.screen.width, 0],
            }),
          },
        ],
      },
    };
  },
};

Basically all it's doing is it's moving the screen from the x direction of full screen width away in left direction to fitting the screen. And implicitly progress is going from 0 to 1.

The transform works just like any other react-native component read more here (https://reactnative.dev/docs/transforms).

And it uses interpolate from the react-native animated (https://reactnative.dev/docs/animated)

Then put it in the screen you want the transition to apply to.

<NavigationContainer>
      <Root.Navigator headerMode="none" initialRouteName="Home">
        <Root.Screen name="Home" component={Home} />
        <Root.Screen name="NotModal" component={NotModal} options={leftToRightAnimation} />
      </Root.Navigator>
 </NavigationContainer>


问:
Passing arrays as parameters in bash
How can I pass an array as parameter to a bash function?</p>

答:
How to pass regular and associative arrays as parameters by reference in bash

Modern bash (apparently version 4.3 or later), allows you to pass arrays by reference. I'll show that below. If you'd like to manually serialize and deserialize the arrays instead, see my answer here for bash regular "indexed" arrays, and here for bash associative arrays. For printing arrays by value or reference, see my answer here.

Passing arrays by reference, as shown below, is much easier and more-concise, however, so that's what I now recommend.

The code below is also available online in my eRCaGuy_hello_world repo here: array_pass_as_bash_parameter_by_reference.sh. See also this example here: array_pass_as_bash_parameter_2_associative.sh.

Here is a demo for regular bash arrays:

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref[0]}"
    echo "${data_ref[1]}"
}

# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"
```
<p>Sample output:</p>
<blockquote>
```Fred Flintstone
Barney Rubble
```
</blockquote>
<p>...and here is a demo for <strong>associative bash arrays</strong> (ie: bash hash tables, "dictionaries", or "unordered maps"):</p>
<pre class="lang-bash prettyprint-override"><code>function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref["a"]}"
    echo "${data_ref["b"]}"
}

# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"
</code>```

Sample output:

```<code>Fred Flintstone
Barney Rubble
</code>```

References:

I modified the above code samples from @Todd Lehman's answer here: How to pass an associative array as argument to a function in Bash?

See also my manual serializing/deserializing answer here

And see my follow-up Question here: Why do the man bash pages state the declare and local -n attribute "cannot be applied to array variables", and yet it can?

Title: Passing arrays as parameters in bash

Body:
How to pass regular and associative arrays as parameters by reference in bash

Modern bash (apparently version 4.3 or later), allows you to pass arrays by reference. I'll show that below. If you'd like to manually serialize and deserialize the arrays instead, see my answer here for bash regular "indexed" arrays, and here for bash associative arrays. For printing arrays by value or reference, see my answer here.

Passing arrays by reference, as shown below, is much easier and more-concise, however, so that's what I now recommend.

The code below is also available online in my eRCaGuy_hello_world repo here: array_pass_as_bash_parameter_by_reference.sh. See also this example here: array_pass_as_bash_parameter_2_associative.sh.

Here is a demo for regular bash arrays:

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref[0]}"
    echo "${data_ref[1]}"
}

# declare a regular bash "indexed" array
declare -a data
data+=("Fred Flintstone")
data+=("Barney Rubble")
foo "data"

Sample output:

Fred Flintstone
Barney Rubble

...and here is a demo for associative bash arrays (ie: bash hash tables, "dictionaries", or "unordered maps"):

function foo {
    # declare a local **reference variable** (hence `-n`) named `data_ref`
    # which is a reference to the value stored in the first parameter
    # passed in
    local -n data_ref="$1"
    echo "${data_ref["a"]}"
    echo "${data_ref["b"]}"
}

# declare a bash associative array
declare -A data
data["a"]="Fred Flintstone"
data["b"]="Barney Rubble"
foo "data"

Sample output:

Fred Flintstone
Barney Rubble

References:

I modified the above code samples from @Todd Lehman's answer here: How to pass an associative array as argument to a function in Bash?

See also my manual serializing/deserializing answer here

And see my follow-up Question here: Why do the man bash pages state the declare and local -n attribute "cannot be applied to array variables", and yet it can?


问:
I can't publish a App Engine application to GCloud using the Google Cloud Platform tools in Visual Studio 2019
I just moved my application to use ASP.Net on .Net Core 3.1. I previously was using NodeJS and Express. I installed the Google Cloud Platform tools for Visual Studio, generated the app.yaml and Dockerfile using the right click menu on my project, modified the app.yaml to what I would assume is a valid configuration, and attempted to publish it. I selected App Engine Flex, selected my project, and I got a "The selected GCP project needs services to be enabled before you can deploy. Enable the services" message. Clicking on Enable the services (which looks like a link) does not do anything. This is preventing be from publishing my app, which is kind of annoying.

Any help would be greatly appreciated :)

app.yaml

```<code>service: api
runtime: custom
env: flex
env_variables:
    ASPNETCORE_ENVIROMENT: "production"
instance_class: F2
automatic_scaling:
    min_idle_instances: 0
    max_idle_instances: 2
    min_pending_latency: 15ms
    max_pending_latency: 100ms
</code>```

Dockerfile

```<code>FROM gcr.io/google-appengine/aspnetcore:3.1
COPY . /app
WORKDIR /app
ENTRYPOINT ["dotnet", "Project Phoenix Game Services.dll"]
</code>```

答:
This happened to me also, when trying to publish a .NET 6 Web API. In order to solve it this is what I did:

Went to my dashboard https://console.cloud.google.com/

Searched for "App Engine Admin API", using the search bar on the top

Enabled it.

Body:
I just moved my application to use ASP.Net on .Net Core 3.1. I previously was using NodeJS and Express. I installed the Google Cloud Platform tools for Visual Studio, generated the app.yaml and Dockerfile using the right click menu on my project, modified the app.yaml to what I would assume is a valid configuration, and attempted to publish it. I selected App Engine Flex, selected my project, and I got a "The selected GCP project needs services to be enabled before you can deploy. Enable the services" message. Clicking on Enable the services (which looks like a link) does not do anything. This is preventing be from publishing my app, which is kind of annoying.

Any help would be greatly appreciated :)

app.yaml

service: api
runtime: custom
env: flex
env_variables:
    ASPNETCORE_ENVIROMENT: "production"
instance_class: F2
automatic_scaling:
    min_idle_instances: 0
    max_idle_instances: 2
    min_pending_latency: 15ms
    max_pending_latency: 100ms

Dockerfile

FROM gcr.io/google-appengine/aspnetcore:3.1
COPY . /app
WORKDIR /app
ENTRYPOINT ["dotnet", "Project Phoenix Game Services.dll"]


问:
Can I set Azure ML output to real JSON using Azure API Management?
I have started using Azure ML to deploy ML service, but it sent results as raw text. I see Azure API Management can use to set outbound body. Can I use it to convert raw text to JSON? and how?

This is an example result from Azure ML WebService.

```<code>"{\"transcript\": \"\\u0e27\\u0e31\\u0e19\"}"
</code>```

Another question, Can I decode UTF-8 in set-body policy?

答: Now, I fixed this by making score.py return python dict instead of json.dumps().</p>

Body:
I have started using Azure ML to deploy ML service, but it sent results as raw text. I see Azure API Management can use to set outbound body. Can I use it to convert raw text to JSON? and how?

This is an example result from Azure ML WebService.

"{\"transcript\": \"\\u0e27\\u0e31\\u0e19\"}"

Another question, Can I decode UTF-8 in set-body policy?


问:
python - findall and multiline combine results
I have two findall statements that work well separately. But I'd like to combine them into one statement.  How do I allow of continuous find not stopped by any /n?

Beautiful soup is not an option for bigger picture.

Code

```<code>#!/usr/bin/python
import re
import os

f = open(os.path.join("data.txt"), "r")
text = f.read()

print (text)

fValue = re.findall(r"line-height: 1.45;\"\>(.*)</h3><p class=3D", text, re.MULTILINE) #Value1
print ("fAdd: " , fValue)
fPrice = re.findall(r"(\$.*)</p>", text, re.MULTILINE) #price
print ("fPrice: " , fPrice)

fCombine = re.findall(r"(\$.*)</p>.*\n.*line-height: 1.45;\"\>(.*)</h3><p class=3D", text, re.MULTILINE) #price
print ("fCombine: " , fCombine)
</code>```

Data

```<code>-family: 'Montserrat', sans-serif; text-decoration: none; color: #323232; f=
ont-weight: 500; font-size: 16px; line-height: 1.38;">$144,900</p><h3 class=
=3D"highlight-title" style=3D"margin: 0; margin-bottom: 6px; font-family: '=
Montserrat', sans-serif; text-decoration: none; color: #323232; font-weight=
: 500; font-size: 13px; line-height: 1.45;">Value1</h3><p class=3D"hi=
ghlight-description" style=3D"margin: 0; font-family: 'Montserrat', sans-se=
rif; text-decoration: none; color: #323232; font-weight: 500; font-size: 13=
</code>```

Results:

```<code>fValue:  ['Value1']
fPrice:  ['$144,900']
fCombine:  []
</code>```

Desired:

```<code>fValue:  ['Value1']
fPrice:  ['$144,900']
fCombine:  ['Value1','$144,900']
</code>```

答:
Since your regex patterns are working as you want. An easy option would be to use the boolean OR operator to combine them.

The pattern would become:
r'line-height: 1.45;\"\>(.*)
<p class=3D|(\$.*)
'

using findall on this will return two match objects with two groups in them, but not all the groups will have values in them:

```<code>pattern = r"line-height: 1.45;\"\>(.*)</h3><p class=3D|(\$.*)</p>"
matches = re.findall(pattern, TEXT, re.MULTILINE)
print(matches)
# [('', '$144,900'), ('Value1', '')] the 1st tuple is the first match,
 which has only the price, the second tuple is the second match which doesnt have a value but has a price.
</code>```

You can use finditer too, if you use capture groups the answer becomes a lot clearer but the result will be similar.

```<code>pattern = r"line-height: 1.45;\"\>(?P<value>.*)</h3><p class=3D|(?P<price>\$.*)</p>"
matches = re.finditer(pattern, TEXT, re.MULTILINE)
for match in matches:
    print(match.groupdict())

# {'value': None, 'price': '$144,900'}
# {'value': 'Value1', 'price': None}

</code>```

regex test: https://regex101.com/r/yEISii/1

Body:
I have two findall statements that work well separately. But I'd like to combine them into one statement.  How do I allow of continuous find not stopped by any /n?

Beautiful soup is not an option for bigger picture.

Code

#!/usr/bin/python
import re
import os

f = open(os.path.join("data.txt"), "r")
text = f.read()

print (text)

fValue = re.findall(r"line-height: 1.45;\"\>(.*)
(.*)
<p class=3D", text, re.MULTILINE) #price
print ("fCombine: " , fCombine)

Data

-family: 'Montserrat', sans-serif; text-decoration: none; color: #323232; f=
ont-weight: 500; font-size: 16px; line-height: 1.38;">$144,900

Value1
<p class=3D"hi=
ghlight-description" style=3D"margin: 0; font-family: 'Montserrat', sans-se=
rif; text-decoration: none; color: #323232; font-weight: 500; font-size: 13=

Results:

fValue:  ['Value1']
fPrice:  ['$144,900']
fCombine:  []

Desired:

fValue:  ['Value1']
fPrice:  ['$144,900']
fCombine:  ['Value1','$144,900']

Body:
Since your regex patterns are working as you want. An easy option would be to use the boolean OR operator to combine them.

The pattern would become:
r'line-height: 1.45;\"\>(.*)</h3><p class=3D|(\$.*)</p>'

using findall on this will return two match objects with two groups in them, but not all the groups will have values in them:

pattern = r"line-height: 1.45;\"\>(.*)</h3><p class=3D|(\$.*)</p>"
matches = re.findall(pattern, TEXT, re.MULTILINE)
print(matches)
# [('', '$144,900'), ('Value1', '')] the 1st tuple is the first match,
 which has only the price, the second tuple is the second match which doesnt have a value but has a price.

You can use finditer too, if you use capture groups the answer becomes a lot clearer but the result will be similar.

pattern = r"line-height: 1.45;\"\>(?P<value>.*)</h3><p class=3D|(?P<price>\$.*)</p>"
matches = re.finditer(pattern, TEXT, re.MULTILINE)
for match in matches:
    print(match.groupdict())

# {'value': None, 'price': '$144,900'}
# {'value': 'Value1', 'price': None}

regex test: https://regex101.com/r/yEISii/1


问:
Unable to CURL POST in Python
The API instructions that I'm following state I should do the following:

```<code># Log in with a valid username and password to receive an authorization code.
curl -X POST "https://api.sensorpush.com/api/v1/oauth/authorize" -H "accept: application/json" -H "Content-Type: application/json" -d @- <<BODY
{ "email": "me@email.com", "password": "abc123" }
BODY
</code>```

I'm not very familiar with curl requests.  After doing some research, I rewrote this in Python as:

```<code>import requests
from requests.structures import CaseInsensitiveDict

url = "https://api.sensorpush.com/api/v1/oauth/authorize"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "applications/json"
data = "@- <<BODY { 'email': 'me@email.com', 'password': 'abc123' } BODY"

resp = requests.post(url, headers=headers, data=data)

print(resp.status_code)
</code>```

I expected to receive an authorization code, but all it returns is "412" (with the correct email and password inserted).  This error code tells me access was denied, so I'm wondering what was incorrect about my Python code?

答:
Can you try this and see if it works?</p>
```<code>import requests
import json
url = "https://api.sensorpush.com/api/v1/oauth/authorize"
headers = {'Content-Type':'application/json', 'accept':'application/json'}
data = { "email": "me@email.com", "password": "abc123" }
data = json.dumps(data)
r = requests.post(url, data=data, headers=headers)
print(r.json())
</code>```

Title: Unable to CURL POST in Python

Body:
The API instructions that I'm following state I should do the following:

# Log in with a valid username and password to receive an authorization code.
curl -X POST "https://api.sensorpush.com/api/v1/oauth/authorize" -H "accept: application/json" -H "Content-Type: application/json" -d @- <<BODY
{ "email": "me@email.com", "password": "abc123" }
BODY

I'm not very familiar with curl requests.  After doing some research, I rewrote this in Python as:

import requests
from requests.structures import CaseInsensitiveDict

url = "https://api.sensorpush.com/api/v1/oauth/authorize"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "applications/json"
data = "@- <<BODY { 'email': 'me@email.com', 'password': 'abc123' } BODY"

resp = requests.post(url, headers=headers, data=data)

print(resp.status_code)

I expected to receive an authorization code, but all it returns is "412" (with the correct email and password inserted).  This error code tells me access was denied, so I'm wondering what was incorrect about my Python code?

Body:
Can you try this and see if it works?

import requests
import json
url = "https://api.sensorpush.com/api/v1/oauth/authorize"
headers = {'Content-Type':'application/json', 'accept':'application/json'}
data = { "email": "me@email.com", "password": "abc123" }
data = json.dumps(data)
r = requests.post(url, data=data, headers=headers)
print(r.json())


问:
Filtering elements of array on the basis of dates
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })```

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?

答:
Simple JavaScript logic.

Calculate time difference in millisecond between start date and end date.

Convert the time into days by dividing with (1000 * 60 * 60 * 24).

Logic for (1000 * 60 * 60 * 24) => 1000 ms = 1 second, 60 seconds = 1 minute, 60 minute = 1 hour, 24 hours = 1 day.

const data = [
    { "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-19T00:00:04.4962889" },
    { "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-26T00:00:04.4962889" },
    { "startDate": "2021-08-18T00:00:04.498059", "endDate": "2021-08-19T00:00:04.4962889" }
];
const newArray = [];
data.forEach(element => {
    const diffTime = new Date(element.endDate) - new Date(element.startDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    if (diffDays > 7) {
        newArray.push(element);
    }
});
console.log(newArray);```

Body:
I have a array as follows:

data = [
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    },
    {
      "startDate": "2021-08-18T00:00:04.498059"
      "endDate": "2021-08-19T00:00:04.4962889"
    }
    ]

    newArray = [];
    this.data.foreach(element => {
       if((element.startDate - element.endDate) > 7) {
           this.newArray.push(element);
       }
    })

I want to traverse the above array and check if difference between startDate and endDate is greater than 7 days for any element, than push that element to a new array.

Because of the date format I don't know my approach is correct or not. How can I do this correctly?


问:
How to attend best practice for not using UI code in the Controller with GetX flutter when I need to show a Dialog if my task complete.?
For a simple Email login with OTP code I have a structure as follows.

View

await _signUpCntrl.signUp(email, password);

Controller

_showOtpDialog(email);

_showOtpDialog func

```<code> return Get.dialog(
        AlertDialog(
</code>```

So the thing is _showOtpDialog function is inside a controller file. ie. /Controllers/controller_file.dart

I want do something like a blocListener, call the _showOtpDialog from a screen(view) file on signup success. (also relocate the _showOtpDialog to a view file)

Using GetX I have to use one of the builders either obs or getbuilder. Which is I think not a good approach to show a dialog box.

On internet it says Workers are the alternative to BlocListener. However Workers function resides on Controller file and with that the dialog is still being called on the controller file.

As OTP dialog will have its own state and a controller I wanted to put it inside a /view/viewfile.dart
How do I obtain this?
I tried using StateMixin but when I call Get.dialog() it throw an error.

visitChildElements() called during build

答:
Unlike BLoC there's no BlocListener or BlocConsumer in GetX.

Instead GetX has RxWorkers. You can store your response object in a Rx variable:

```<code>class SomeController extends GetxController{

    final response= Rxn<SomeResponse>();

    Future<void> someMethod()async{

         response.value = await someApiCall();

    }
 }
</code>```

And then right before the return of your widget's build method:

```<code>class SomeWidget extends StatelessWidget{

   final controller = Get.put(SomeController());

 @override
 Widget build(BuildContext context){

   ever(controller.response, (SomeResponse res){
        if(res.success){
          return Get.dialog(SuccessDialog()); //Or snackbar, or navigate to another page
        }
        ....
      });

     return UI();

  }
</code>```

Body:
For a simple Email login with OTP code I have a structure as follows.

View

await _signUpCntrl.signUp(email, password);

Controller

_showOtpDialog(email);

_showOtpDialog func

 return Get.dialog(
        AlertDialog(

So the thing is _showOtpDialog function is inside a controller file. ie. /Controllers/controller_file.dart

I want do something like a blocListener, call the _showOtpDialog from a screen(view) file on signup success. (also relocate the _showOtpDialog to a view file)

Using GetX I have to use one of the builders either obs or getbuilder. Which is I think not a good approach to show a dialog box.

On internet it says Workers are the alternative to BlocListener. However Workers function resides on Controller file and with that the dialog is still being called on the controller file.

As OTP dialog will have its own state and a controller I wanted to put it inside a /view/viewfile.dart
How do I obtain this?
I tried using StateMixin but when I call Get.dialog() it throw an error.

visitChildElements() called during build

Body:
Unlike BLoC there's no BlocListener or BlocConsumer in GetX.

Instead GetX has RxWorkers. You can store your response object in a Rx variable:

class SomeController extends GetxController{

    final response= Rxn<SomeResponse>();

    Future<void> someMethod()async{

         response.value = await someApiCall();

    }
 }

And then right before the return of your widget's build method:

class SomeWidget extends StatelessWidget{

   final controller = Get.put(SomeController());

 @override
 Widget build(BuildContext context){

   ever(controller.response, (SomeResponse res){
        if(res.success){
          return Get.dialog(SuccessDialog()); //Or snackbar, or navigate to another page
        }
        ....
      });

     return UI();

  }


问:
How can I create a dummy variable based on text analysis and time sequence of events?

Coworkers
Date

A
2011-01-01

D
2011-01-02

B;;D
2011-01-03

E;;F
2011-01-04

D
2012-11-05

D;;G
2012-11-06

A
2012-11-09

Hello, I am trying to create a dummy variable based on text analysis (e.g., grepl).
The unit of analysis is a project, and the two main variables are coworkers (text) and date.

I am curious if there is any way that I can create a dummy variable that indicates all projects done by a worker who collaborated with "B" (in this example, D) as 1.
One more KEY condition I would like to add is...  I would like to give the value of 1 only to projects that occurred AFTER B and D worked together.
I mean, in this case, I want to mark the project in the second row, which is done by D, as 0 because it occurred before B and D met.

Can I create this type of variable using R commands?
As I have millions of observations, I would not be able to do it manually.
Alphabets in the table are texts.

Thank you!

PS. In the "Coworkers" column, coworkers are separated by ;;

答:
Here is one possible solution with tidyverse (at least I think this is what you are looking for). First, I create a new column (i.e., flag) that indicates whether B has co-worked with D, and if so, then I assign a 1. Next, I use cummax which will everything 1 after the first row of B;;D. This creates two groups for the before and after. Next, I use case_when to change the first occurrence to 0, as you specified. Then, for any row with D, I change to 1 and all others are changed to 0.

```<code>library(tidyverse)

df %>%
  mutate(flag = ifelse(str_detect(Coworkers, "B;;D") | str_detect(Coworkers, "D;;B"), 1, 0),
         flag = cummax(flag == 1),
         flag = case_when(flag != 0 & !duplicated(flag) ~ 0,
                          grepl("D", Coworkers) & flag == 1 ~ 1,
                          TRUE ~ 0))
</code>```

Output

```<code>  Coworkers       Date flag
1         A 2011-01-01    0
2         D 2011-01-02    0
3      B;;D 2011-01-03    0
4      E;;F 2011-01-04    0
5         D 2012-11-05    1
6      D;;G 2012-11-06    1
7         A 2012-11-09    0
8         B 2012-12-09    0
9      C;;B 2012-12-09    0
</code>```

Data

```<code>df <- structure(list(Coworkers = c("A", "D", "B;;D", "E;;F", "D", "D;;G",
"A", "B", "C;;B"), Date = c("2011-01-01", "2011-01-02", "2011-01-03",
"2011-01-04", "2012-11-05", "2012-11-06", "2012-11-09", "2012-12-09",
"2012-12-09")), class = "data.frame", row.names = c(NA, -9L))
</code>```

Body:
Here is one possible solution with tidyverse (at least I think this is what you are looking for). First, I create a new column (i.e., flag) that indicates whether B has co-worked with D, and if so, then I assign a 1. Next, I use cummax which will everything 1 after the first row of B;;D. This creates two groups for the before and after. Next, I use case_when to change the first occurrence to 0, as you specified. Then, for any row with D, I change to 1 and all others are changed to 0.

library(tidyverse)

df %>%
  mutate(flag = ifelse(str_detect(Coworkers, "B;;D") | str_detect(Coworkers, "D;;B"), 1, 0),
         flag = cummax(flag == 1),
         flag = case_when(flag != 0 & !duplicated(flag) ~ 0,
                          grepl("D", Coworkers) & flag == 1 ~ 1,
                          TRUE ~ 0))

Output

  Coworkers       Date flag
1         A 2011-01-01    0
2         D 2011-01-02    0
3      B;;D 2011-01-03    0
4      E;;F 2011-01-04    0
5         D 2012-11-05    1
6      D;;G 2012-11-06    1
7         A 2012-11-09    0
8         B 2012-12-09    0
9      C;;B 2012-12-09    0

Data

df <- structure(list(Coworkers = c("A", "D", "B;;D", "E;;F", "D", "D;;G",
"A", "B", "C;;B"), Date = c("2011-01-01", "2011-01-02", "2011-01-03",
"2011-01-04", "2012-11-05", "2012-11-06", "2012-11-09", "2012-12-09",
"2012-12-09")), class = "data.frame", row.names = c(NA, -9L))