Title: How to run a random country effects and time fixed effects in R by using plm?

Body:
My subset of my dataset looks as follows (the full dataset has all the countries of the world):

structure(list(Country = c("Afghanistan", "Afghanistan", "Afghanistan",
"Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan",
"Afghanistan", "Afghanistan"), CountryCode = c("AFG", "AFG",
"AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG"), Time = c("1996",
"1997", "1998", "1999", "2000", "2001", "2002", "2003", "2004",
"2005"), Time.Code = c("YR1996", "YR1997", "YR1998", "YR1999",
"YR2000", "YR2001", "YR2002", "YR2003", "YR2004", "YR2005"),
    gdp_pc_g = c(NA, NA, NA, NA, NA, NA, NA, 3.86838029515866,
    -2.87520316702623, 7.20796721836321), gdp_pc = c(NA, NA,
    NA, NA, NA, NA, 1189.78466765718, 1235.81006329565, 1200.27801321735,
    1286.79365893927), population_g = c(4.0194777158615, 2.63650176396731,
    1.9473438616857, 2.17042851112236, 2.97505722281038, 3.90280496415438,
    4.4967187466326, 4.66834379545461, 4.32155951673842, 3.68269988149014
    ), savings = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), inflation = c(NA,
    NA, NA, NA, NA, NA, NA, 11.655238211175, 11.2714320712639,
    10.9127735539374), unemployment = c(10.9619998931885, 10.7829999923706,
    10.8020000457764, 10.8090000152588, 10.8059997558594, 10.8090000152588,
    11.2569999694824, 11.1409997940063, 10.9879999160767, 11.2170000076294
    ), crime = c(NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_), health = c(NA,
    NA, NA, NA, NA, NA, 0.08418062, 0.65096337, 0.5429256, 0.5291841
    ), health_new = c(NA, NA, NA, NA, NA, NA, 1.21245611, 5.45767879,
    3.60296822, 3.37097836), co2 = c(1180, 1100, 1040, 810, 760,
    730, 1029.99997138977, 1220.00002861023, 1029.99997138977,
    1549.99995231628), debt_wb = c(NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_), debt_imf = c(NA, NA, NA, NA, NA, NA, 345.97748,
    270.60236, 244.96669, 206.35601), qualityofgovernment = c(-1.94518780708313,
    NA, -1.9237864613533, NA, -1.96282829840978, NA, -1.63204962015152,
    -1.4781574010849, -1.49412107467651, -1.52730602025986),
    migration = c(27.194, 6.129, 35.74, 85.758, -1007.135, -192.286,
    1327.074, 388.632, -248.616, 252.185), gdp_pc_log = c(NA,
    NA, NA, NA, NA, NA, 7.08152761818328, 7.11948195573634, 7.09030848662408,
    7.15990886757784), gdp_pc_1996 = c(NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_), gdp_pc_1996_log = c(NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_), unemployment_log = c(2.39443473688013, 2.3779708191924,
    2.37973130640847, 2.38037912184574, 2.38010151282881, 2.38037912184574,
    2.42099015466168, 2.41063197858748, 2.3968037605953, 2.41743048534325
    ), crime_log = c(NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
    ), health_new_log = c(NA, NA, NA, NA, NA, NA, 0.192648145236196,
    1.69702356932679, 1.28175801129963, 1.21520301677122), co2_log = c(7.07326971745971,
    7.00306545878646, 6.94697599213542, 6.69703424766648, 6.63331843328038,
    6.59304453414244, 6.93731405344676, 7.10660616117831, 6.93731405344676,
    7.3460101791496), migration_t5 = c(NA, NA, NA, NA, NA, 27.194,
    6.129, 35.74, 85.758, -1007.135), debt_imf_1996 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), debt_imf_1996_log = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), debt_imf_2001 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), debt_imf_2006 = c(22.984644,
    22.984644, 22.984644, 22.984644, 22.984644, 22.984644, 22.984644,
    22.984644, 22.984644, 22.984644), debt_imf_2011 = c(7.5010844,
    7.5010844, 7.5010844, 7.5010844, 7.5010844, 7.5010844, 7.5010844,
    7.5010844, 7.5010844, 7.5010844), debt_imf_2016 = c(8.4372661,
    8.4372661, 8.4372661, 8.4372661, 8.4372661, 8.4372661, 8.4372661,
    8.4372661, 8.4372661, 8.4372661), politics_1996 = c(-1.94518780708313,
    -1.94518780708313, -1.94518780708313, -1.94518780708313,
    -1.94518780708313, -1.94518780708313, -1.94518780708313,
    -1.94518780708313, -1.94518780708313, -1.94518780708313),
    politics_2006 = c(-1.63495093584061, -1.63495093584061, -1.63495093584061,
    -1.63495093584061, -1.63495093584061, -1.63495093584061,
    -1.63495093584061, -1.63495093584061, -1.63495093584061,
    -1.63495093584061), politics_2016 = c(-1.55767250061035,
    -1.55767250061035, -1.55767250061035, -1.55767250061035,
    -1.55767250061035, -1.55767250061035, -1.55767250061035,
    -1.55767250061035, -1.55767250061035, -1.55767250061035),
    politics_t5 = c(NA, NA, NA, NA, NA, 0.55481219291687, NA,
    0.576213538646698, NA, 0.53717170159022), politics_2001 = c(NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA), politics_2011 = c(-1.72906082868576,
    -1.72906082868576, -1.72906082868576, -1.72906082868576,
    -1.72906082868576, -1.72906082868576, -1.72906082868576,
    -1.72906082868576, -1.72906082868576, -1.72906082868576),
    politics_t10 = c(NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
    ), debt_imf_2001_log = c(NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
    ), debt_imf_2006_log = c(3.13482634077627, 3.13482634077627,
    3.13482634077627, 3.13482634077627, 3.13482634077627, 3.13482634077627,
    3.13482634077627, 3.13482634077627, 3.13482634077627, 3.13482634077627
    ), debt_imf_2011_log = c(2.01504759675729, 2.01504759675729,
    2.01504759675729, 2.01504759675729, 2.01504759675729, 2.01504759675729,
    2.01504759675729, 2.01504759675729, 2.01504759675729, 2.01504759675729
    ), debt_imf_2016_log = c(2.13265833433292, 2.13265833433292,
    2.13265833433292, 2.13265833433292, 2.13265833433292, 2.13265833433292,
    2.13265833433292, 2.13265833433292, 2.13265833433292, 2.13265833433292
    ), debt_imf_log = c(NA, NA, NA, NA, NA, NA, 5.84637368623429,
    5.6006504370586, 5.50112224211777, 5.32960288104705), gdp_pc_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), population_g_t5 = c(NA, NA,
    NA, NA, NA, 4.0194777158615, 2.63650176396731, 1.9473438616857,
    2.17042851112236, 2.97505722281038), savings_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), inflation_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), unemployment_t5 = c(NA, NA,
    NA, NA, NA, 10.9619998931885, 10.7829999923706, 10.8020000457764,
    10.8090000152588, 10.8059997558594), crime_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), health_new_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), co2_t5 = c(NA, NA, NA, NA,
    NA, 1180, 1100, 1040, 810, 760), debt_imf_t5 = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), qualityofgovernment_t5 = c(NA,
    NA, NA, NA, NA, -1.94518780708313, NA, -1.9237864613533,
    NA, -1.96282829840978), gdp_pc_t5_log = c(NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_), inflation_t5_log = c(NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_), unemployment_t5_log = c(NA, NA, NA,
    NA, NA, 2.39443473688013, 2.3779708191924, 2.37973130640847,
    2.38037912184574, 2.38010151282881), crime_t5_log = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), health_new_t5_log = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), co2_t5_log = c(NA, NA, NA,
    NA, NA, 7.07326971745971, 7.00306545878646, 6.94697599213542,
    6.69703424766648, 6.63331843328038), debt_imf_t5_log = c(NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_), politics = c(0.55481219291687,
    NA, 0.576213538646698, NA, 0.53717170159022, NA, 0.867950379848478,
    1.0218425989151, 1.00587892532349, 0.972693979740143), politics_t5_log = c(NA,
    NA, NA, NA, NA, -0.589125613643679, NA, -0.551276960171269,
    NA, -0.621437493326265), migration_rate = c(1.59, 0.345,
    1.934, 4.461, -50.229, -9.717, 65.242, 17.307, -10.498, 10.383
    ), migration_rate_t5 = c(NA, NA, NA, NA, NA, 1.59, 0.345,
    1.934, 4.461, -50.229), inflation_new = c(NA, NA, NA, NA,
    NA, NA, NA, 1.11655238211175, 1.11271432071264, 1.10912773553937
    ), inflation_new_t5 = c(NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_
    ), inflation_new_t5_log = c(NA_real_, NA_real_, NA_real_,
    NA_real_, NA_real_, NA_real_, NA_real_, NA_real_, NA_real_,
    NA_real_)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))

Now I want to run a regression which takes into account the random country effects and fixed time effects. Therefore, I use the plm package and I tried the following regression:

test <- plm(pd6$gdp_pc_g ~ pd6$gdp_pc_t5_log + pd6$population_g_t5 + pd6$savings_t5 + pd6$inflation_new_t5 + factor(pd6$Time),
                                          data = pd6,
                                          index = c("Country","Time"),
                                          model = "random",
                                          effect = "individual")
summary(test)

In this way we use the random country effects and the fixed time effects by using factor(Time) but we get the following output:

Error in solve.default(crossprod(ZBeta)) :
  Lapack routine dgesv: system is exactly singular: U[24,24] = 0

In my opinion, this is a weird outcome as when I use the previous inflation rate variable it gives the following outcome:

regression_check_random_factortime <- plm(pd6$gdp_pc_g ~ pd6$gdp_pc_t5_log + pd6$population_g_t5 + pd6$savings_t5 + pd6$inflation_t5_log + factor(pd6$Time),
                                          data = pd6,
                                          index = c("Country","Time"),
                                          model = "random",
                                          effect = "individual")
summary(regression_check_random_factortime)

Oneway (individual) effect Random Effect Model
   (Swamy-Arora's transformation)

Call:
plm(formula = pd6$gdp_pc_g ~ pd6$gdp_pc_t5_log + pd6$population_g_t5 +
    pd6$savings_t5 + pd6$inflation_t5_log + factor(pd6$Time),
    data = pd6, effect = "individual", model = "random",
    index = c("Country", "Time"))

Unbalanced Panel: n = 169, T = 3-21, N = 2727

Effects:
                 var std.dev share
idiosyncratic 15.604   3.950 0.928
individual     1.212   1.101 0.072
theta:
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
0.09946 0.33231 0.37425 0.34853 0.38355 0.38355

Residuals:
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
-53.627  -1.567   0.065   0.007   1.614  82.712

Coefficients:
                       Estimate Std. Error  z-value  Pr(>|z|)
(Intercept)           9.7790463  1.1571926   8.4507 < 2.2e-16 ***
pd6$gdp_pc_t5_log    -0.8142922  0.1125480  -7.2351 4.653e-13 ***
pd6$population_g_t5  -0.7436232  0.0883748  -8.4144 < 2.2e-16 ***
pd6$savings_t5        0.0030500  0.0058523   0.5212  0.602253
pd6$inflation_t5_log -0.0173477  0.0855059  -0.2029  0.839227
factor(pd6$Time)2002  0.5805051  0.5394360   1.0761  0.281868
factor(pd6$Time)2003  1.5797661  0.5500974   2.8718  0.004081 **
factor(pd6$Time)2004  2.3271585  0.5485730   4.2422 2.213e-05 ***
factor(pd6$Time)2005  2.3897793  0.5398510   4.4267 9.567e-06 ***
factor(pd6$Time)2006  3.0947233  0.5423607   5.7060 1.156e-08 ***
factor(pd6$Time)2007  3.1148694  0.5304367   5.8723 4.299e-09 ***
factor(pd6$Time)2008  1.1228860  0.5350573   2.0986  0.035850 *
factor(pd6$Time)2009 -3.5876306  0.5278708  -6.7964 1.073e-11 ***
factor(pd6$Time)2010  1.6113963  0.5152687   3.1273  0.001764 **
factor(pd6$Time)2011  1.1078570  0.5146832   2.1525  0.031358 *
factor(pd6$Time)2012  1.1763884  0.5085243   2.3133  0.020704 *
factor(pd6$Time)2013  0.8604293  0.5078134   1.6944  0.090193 .
factor(pd6$Time)2014  0.6028326  0.5363680   1.1239  0.261049
factor(pd6$Time)2015 -0.0027967  0.5089855  -0.0055  0.995616
factor(pd6$Time)2016  0.5767955  0.5060689   1.1398  0.254388
factor(pd6$Time)2017  1.1948758  0.5109051   2.3387  0.019349 *
factor(pd6$Time)2018  0.9389180  0.5209395   1.8024  0.071490 .
factor(pd6$Time)2019  0.3594668  0.5264469   0.6828  0.494723
factor(pd6$Time)2020 -7.5368238  0.5278253 -14.2790 < 2.2e-16 ***
factor(pd6$Time)2021  3.5392484  0.5264602   6.7227 1.784e-11 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Total Sum of Squares:    60994
Residual Sum of Squares: 44490
R-Squared:      0.2706
Adj. R-Squared: 0.26412
Chisq: 1009.59 on 24 DF, p-value: < 2.22e-16

Just to clarify, I have 3 inflation variables"

inflation_t5 which is the inflation rate lagged for 5 years

inflation_new_t5 which is 1 plus the inflation rate divided by 100

inflation_t5_log is the log of the inflation_t5 (cannot be used as it cannot take the log of negative values and that is the reason why I have added the inflation_new_t5

In addition, it gives the same error when I do this regression:

test2 <- plm(pd6$gdp_pc_g ~ pd6$gdp_pc_t5_log + pd6$population_g_t5 + pd6$savings_t5 + factor(pd6$Time),
             data = pd6,
             index = c("Country", "Time"),
             model = "random",
             effect = "individual")
summary(test2)

Error in solve.default(crossprod(ZBeta)) :
  Lapack routine dgesv: system is exactly singular: U[23,23] = 0

I do not understand how I can fix the problem such that these regression will get the right outcomes such as in the 'regression_check_random_factortime' regression.

Can someone help me such that I get the right regression with the country random effects and time fixed effects?


来源: stackexchange

问:
Angular Observer and external notification
Disclaimer: I am new to Angular, Observers and so forth.

I have an external onChange function from some API where I can listen to change notifications:

```<code>
const myConnection = new Connection(HTTP_ENDPOINT, WSS_ENDPOINT);
(async () => {
    const subscriptionId = await myConnection.onChange(myUpdate);
    console.log('Starting web socket ', subscriptionId);
})()

function myUpdate(info:someInfo) {
  // calling `myObserver.next(info);` does not seem to actually update the HTML here.
}
</code>```

I want myUpdate to trigger an update to my HTML whenever onChange is called. For that, I figured that the Observer pattern is adequate.

```<code>import { Observable, Observer } from 'rxjs';

const myObserver = {
  next: (x:someInfo) => { console.log(x); }
};

function mySubscriber(observer: Observer<someInfo>) {
  // TODO How to hook this up with onChange?
}

export class myComponent {
  myObservable = new Observable(mySubscriber);
  constructor() {
    this.myObservable.subscribe(myObserver);
  }
}
</code>```

What I got to work so far is to call observer.next via setInterval(.., 1000) inside mySubscriber and using global variables that I had populated from myUpdate. But it'd be nice for me to understand how I can directly my observer with the external onChange API.

ContentLicense: CC BY-SA 4.0

Body:
Disclaimer: I am new to Angular, Observers and so forth.

I have an external onChange function from some API where I can listen to change notifications:

const myConnection = new Connection(HTTP_ENDPOINT, WSS_ENDPOINT);
(async () => {
    const subscriptionId = await myConnection.onChange(myUpdate);
    console.log('Starting web socket ', subscriptionId);
})()

function myUpdate(info:someInfo) {
  // calling `myObserver.next(info);` does not seem to actually update the HTML here.
}

I want myUpdate to trigger an update to my HTML whenever onChange is called. For that, I figured that the Observer pattern is adequate.

import { Observable, Observer } from 'rxjs';

const myObserver = {
  next: (x:someInfo) => { console.log(x); }
};

function mySubscriber(observer: Observer<someInfo>) {
  // TODO How to hook this up with onChange?
}

export class myComponent {
  myObservable = new Observable(mySubscriber);
  constructor() {
    this.myObservable.subscribe(myObserver);
  }
}

What I got to work so far is to call observer.next via setInterval(.., 1000) inside mySubscriber and using global variables that I had populated from myUpdate. But it'd be nice for me to understand how I can directly my observer with the external onChange API.


问:
Debian change dist-package path
I'm currently using Debian GNU/Linux bookworm, but I'm struggling with python3 package updates.
In fact, it uses :
/usr/lib/python3/dist-packages to check for packages installed for system software and this is not what i want. This directory contains python3.9 packages, and it later raises compatibility uses

I want to use this directory instead:
/usr/local/lib/python3.10/dist-packages/
That exists in my computer with the software in the version that i want but it doesn't works. I've tried the

PYTHON_INCLUDE_DIR=/usr/include/python3.10
PYTHON_LIBRARY=/home/me/.local/lib/
export PYTHON_INCLUDE_DIR
export PYTHON_LIBRARY
```
<p>commands, but it did not work.
My py sys.path contains :</p>
<pre class="lang-py prettyprint-override"><code>['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/me/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']
</code>```

I would really appreciate some help on this one :,(

I even tried to reinstall python and reboot (which caused GNOME to crash), but it stils uses python3.9 dist package path, i don't know how to get rid of it, or even how to update it !

Title: Debian change dist-package path

Body:
I'm currently using Debian GNU/Linux bookworm, but I'm struggling with python3 package updates.
In fact, it uses :
/usr/lib/python3/dist-packages to check for packages installed for system software and this is not what i want. This directory contains python3.9 packages, and it later raises compatibility uses

I want to use this directory instead:
/usr/local/lib/python3.10/dist-packages/
That exists in my computer with the software in the version that i want but it doesn't works. I've tried the

PYTHON_INCLUDE_DIR=/usr/include/python3.10
PYTHON_LIBRARY=/home/me/.local/lib/
export PYTHON_INCLUDE_DIR
export PYTHON_LIBRARY

commands, but it did not work.
My py sys.path contains :

['', '/usr/lib/python310.zip', '/usr/lib/python3.10', '/usr/lib/python3.10/lib-dynload', '/home/me/.local/lib/python3.10/site-packages', '/usr/local/lib/python3.10/dist-packages', '/usr/lib/python3/dist-packages']

I would really appreciate some help on this one :,(

I even tried to reinstall python and reboot (which caused GNOME to crash), but it stils uses python3.9 dist package path, i don't know how to get rid of it, or even how to update it !


问:
.aab not working with Autentication Bloc Flutter
I created a mobile application that works correctly when I run it and I generate the .apk, but I have tried to upload it to the PlayStore and it has returned to me because it does not initialize well, it does not even enter the login, I have no idea what to check since when I run it it works correctly, for authentication I am using Authentication Bloc, this is my main.dart, the only thing I have noticed is that with the .aab it does not enter the condition and it goes to the else, so it does not enter the Login.</p>
```<code>   void main() {
    runApp(
     MultiBlocProvider(
      providers: [
       BlocProvider<AuthenticationBloc>(
        create: (context) => AuthenticationBloc()..add(AppStartedEvent()),
       ),
     ],
    child: const MyApp(),
   ),
 );
}

 class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);

@override
Widget build(BuildContext context) {
 return MaterialApp(
  debugShowCheckedModeBanner: false,
  title: "Administrador de pedidos",
  home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
    builder: (context, state) {
      if (state is UserAuthenticatedState) {
        return HomePage();
      } else if (state is UserUnAuthenticatedState) {
        return  LoginForm();
      } else {
        CheckInternet().checkConnection(context);
      }
      CheckInternet().checkConnection(context);
      return Scaffold(
        backgroundColor: Theme.of(context).primaryColor,
        body: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Image.asset(
                "logo-login3.png",
                height: 200,
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(bottom: 64.0),
              child: Align(
                alignment: Alignment.bottomCenter,
                child: CircularProgressIndicator(),
              ),
            ),
          ],
        ),
      );
    },
  ),
  theme: ThemeData(
    primaryColor: const Color(0xFF00416A),
    fontFamily: 'Titillium Web',
    brightness: Brightness.light, colorScheme:
    ColorScheme.fromSwatch().copyWith(secondary: const Color(0xFF94D500)),
  ),
 );
}
}
</code>```

Body:
I created a mobile application that works correctly when I run it and I generate the .apk, but I have tried to upload it to the PlayStore and it has returned to me because it does not initialize well, it does not even enter the login, I have no idea what to check since when I run it it works correctly, for authentication I am using Authentication Bloc, this is my main.dart, the only thing I have noticed is that with the .aab it does not enter the condition and it goes to the else, so it does not enter the Login.

   void main() {
    runApp(
     MultiBlocProvider(
      providers: [
       BlocProvider<AuthenticationBloc>(
        create: (context) => AuthenticationBloc()..add(AppStartedEvent()),
       ),
     ],
    child: const MyApp(),
   ),
 );
}

 class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);

@override
Widget build(BuildContext context) {
 return MaterialApp(
  debugShowCheckedModeBanner: false,
  title: "Administrador de pedidos",
  home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
    builder: (context, state) {
      if (state is UserAuthenticatedState) {
        return HomePage();
      } else if (state is UserUnAuthenticatedState) {
        return  LoginForm();
      } else {
        CheckInternet().checkConnection(context);
      }
      CheckInternet().checkConnection(context);
      return Scaffold(
        backgroundColor: Theme.of(context).primaryColor,
        body: Stack(
          children: <Widget>[
            Align(
              alignment: Alignment.center,
              child: Image.asset(
                "logo-login3.png",
                height: 200,
              ),
            ),
            const Padding(
              padding: EdgeInsets.only(bottom: 64.0),
              child: Align(
                alignment: Alignment.bottomCenter,
                child: CircularProgressIndicator(),
              ),
            ),
          ],
        ),
      );
    },
  ),
  theme: ThemeData(
    primaryColor: const Color(0xFF00416A),
    fontFamily: 'Titillium Web',
    brightness: Brightness.light, colorScheme:
    ColorScheme.fromSwatch().copyWith(secondary: const Color(0xFF94D500)),
  ),
 );
}
}


问:
Perform vTPM attestation programatically on Azure
I am trying to invoke Attest APIs (https://learn.microsoft.com/en-us/rest/api/attestation/attestation/attest-tpm?tabs=HTTP) on a Azure VM with vTPM enabled.

I followed this article and have created the following:

Azure Attestation Service in my subscription

A new policy for TPM attestation

Client with Attestation Reader role

A Ubuntu 20.04.5 instance with vTPM enabled (secure-boot disabled)

With all the pre-requisites setup, I am wondering if its possible for me to call Attestation APIs and perform attestation on-demand using the Attestation client libraries ?

OR, if the attestation is performed only by Azure automatically (the article does not indicate this), is it possible to read and verify the attestation results auto-triggered by Azure ? My objective is to see if I can create a client driven way to attest / verify attestation.


问:
an error occurred while processing this directive Zen Cart
I moved my Zen cart website from one server to another with a different domain and everything works fine except some links. When I'm trying to access some product categories, It gives me error "[an error occurred while processing this directive]". I have checked multiple solution from the internet but nothing works. Please help me in this regard.
Thanks
Website: https://test.desperado2.com/
Error Page Example: https://test.desperado2.com/magic-and-fire/books-and-booklets/big-magic-for-little-hands-by-joshua-jay

I have checked multiple solution from the internet but nothing works.


问:
Python numerical precision
How does Python handle big numbers? I was working with exponentials and exponential notation returned me inf but when I used pow function I got it rigth.

Particularly, I had: 1e1000 -> inf and pow(10, 1000) equals to a big number.

Title: Python numerical precision


问:
How to remove formula (query, if etc) without losing current sheet value in google sheet?
how to remove Formula without losing value in google sheet.
i know how to copy value without formula (CTRL + SWIFT + C). but i want remove all formula (ifs, query, xlook etc in current sheet)  without losing value in current sheet. how to remove formula without losing value in google sheet?


问:
Drupal webform displays two asterisks for one required content field
I added a required opt-in checkbox to an existing webform in Drupal 8 and it is displaying two asterisks for the checkbox instead of just one.

Added the checkbox as I would any other required content. I expected it to have one asterisk associated with it to show that it was required content but it is displaying two asterisks. No, I did not add any asterisk myself.


问:
Android: RunTimeException with Robolectric Shadow Package Parser
I'm running a unit tests using RobolectricTestRunner but am seeing a NPE caused by a Shadow Package Parser Exception

I have configured the test class as such:

```<code>@RunWith(RobolectricTestRunner.class)
@Config(application = RobolectricTestApp.class)
public class YourRoomsActivityTest {
    @Test
    public void test_dummy() {
        // Required until real tests are added back
    }
...
}
</code>```

The exception:
java.lang.RuntimeException at ShadowPackageParser.java:69
Caused by: android.content.pm.PackageParser$PackageParserException at PackageParser.java:1353
Caused by: java.lang.NullPointerException at CppAssetManager2.java:689

Body:
I'm running a unit tests using RobolectricTestRunner but am seeing a NPE caused by a Shadow Package Parser Exception

I have configured the test class as such:

@RunWith(RobolectricTestRunner.class)
@Config(application = RobolectricTestApp.class)
public class YourRoomsActivityTest {
    @Test
    public void test_dummy() {
        // Required until real tests are added back
    }
...
}

The exception:
java.lang.RuntimeException at ShadowPackageParser.java:69
Caused by: android.content.pm.PackageParser$PackageParserException at PackageParser.java:1353
Caused by: java.lang.NullPointerException at CppAssetManager2.java:689


问:
Issue with displaying timer which uses django modle attributes
I'm trying to use django to build a phase timer app for myself. I want a timer to run for each phase, then reset to zero and run for the next phase for n-cycles.

I've tried asking 'Friend computer' for help but am still struggling.

Here's the model.

```<code>from django.db import models

# Create your models here.

class Cycle(models.Model):
    name = models.CharField(max_length=100)
    instructions = models.TextField()
    phase_1_time = models.PositiveIntegerField()
    phase_1_hold_time = models.PositiveIntegerField()
    phase_2_time = models.PositiveIntegerField()
    phase_2_hold_time = models.PositiveIntegerField()
    recovery_time = models.PositiveIntegerField()
    max_cycles = models.PositiveIntegerField()

    def __str__(self):
        return self.name
</code>```

And here's the view

```<code>''' View for the cycle app.'''
from django.shortcuts import render
from .models import Cycle

def exercise_list(request):
    exercises = Cycle.objects.all()
    return render(request, 'cycles/exercise_list.html', {'exercises': exercises})

def exercise_detail(request, exercise_id):
    exercise = Cycle.objects.get(id=exercise_id)
    phase_1_duration = exercise.phase_1_time
    phase_1_pause_duration = exercise.phase_1_pause_time
    phase_2_duration = exercise.phase_2_time
    phase_2_pause_duration = exercise.phase_2_pause_time
    recovery = exercise.recovery_time
    max_cycles = exercise.max_cycles
    return render(request, 'cycles/exercise_detail.html', {
        'exercise': exercise,
        'phase_1_duration': phase_1_duration,
        'phase_1_pause_duration': phase_1_pause_duration,
        'phase_2_duration': phase_2_duration,
        'phase_2_pause_duration': phase_2_pause_duration,
        'recovery': recovery,
        'max_cycles': max_cycles,
</code>```

and the html

```<code><html>
  <head>
    <title>{{exercise.name}}</title>
  </head>
  <body>
    <h1>{{ exercise.name }}</h1>
    <p>Instructions: {{ exercise.instructions }}</p>
    <p>Phase 1 Time: {{ exercise.Phase_1_time }}</p>
    <p>Phase 1 pause Time: {{ exercise.phase_1_pause_time }}</p>
    <p>Phase2 Time: {{ exercise.Phase_2_time }}</p>
    <p>Phase 2 pause Time: {{ exercise.phase_2_pause_time }}</p>
    <p>Long pause Time: {{ exercise.long_pause}}</p>
    <p>Recovery Time: {{ exercise.recovery_time }}</p>
    <p>Max Cycles: {{ exercise.max_cycles }}</p>
    <div id = timer></div>
    <div id="button">  <button onclick="firstRound()">Start Round</button></div>

    <script>
      // state constants
      const STATE_Phase_1 = 0;
      const STATE_Phase_1_pause = 1;
      const STATE_Phase_2 = 2;
      const STATE_Phase_2_pause = 3;
      const STATE_LONG_pause = 4;
      const STATE_RECOVERY = 5;
      const STATE_END_CYCLE = 6;
      let interval = null;
      let time_in_state = 0;
      function run_cycle(Phase_1, P1_pause, Phase_2, P2_pause, max_cycles) {
        let breath_cycle = 0;
        let state = STATE_Phase_1;

        function frame() {
          let time_in_state = 0;
          time_in_state += 10;

          // Calculate the total number of seconds that have passed
          let total_seconds = time_in_state / 1000;

          // Calculate the number of minutes and seconds
          let minutes = Math.floor(total_seconds / 60);
          let seconds = Math.floor(total_seconds % 60);

          // Format the time as a string
          let time_string = `${minutes}:${String(seconds).padStart(2, "0")}`;

          // Update the timer div with the current time
          document.getElementById("timer").innerHTML = time_string;
          switch (state) {
                case STATE_Phase_1:
                    frac = time_in_state / Phase_1;//frac is the time in the state divided by the value passed from the django model
                    if (frac >= 1) {// if the fraction is greater than 1, then the state is complete move to the next state
                        state = STATE_Phase_1_pause;
                        time_in_state = 0; // reset the time in state
                        break;
                    }
                    break;
                case STATE_Phase_1_pause:
                    frac = time_in_state / in_pause;
                    if (frac >= 1) {
                        state = STATE_Phase_2;
                        time_in_state = 0;
                        break;
                    }
                    break;
                case STATE_Phase_2:
                  frac = time_in_state / Phase_2;
                    if (frac >= 1) {
                        state = STATE_Phase_2_pause;
                        break;
                    }
                    break;
                case STATE_Phase_2_pause:
                  frac = time_in_state / ex_pause;
                  if (frac >= 1) {
                    breath_cycle += 1;
                    if (breath_cycle < max_breath_cycles) {
                      state = STATE_Phase_1;
                      time_in_state = 0;
                    }
                    else {
                      state = STATE_END_CYCLE;
                      // I want to end the cycle here and just stop the timer from running
                      interval = clearInterval(interval);
                      break;

                    }
                  }

                    break;
            }
        }
        interval = setInterval(frame, 1000);

        }

      function firstRound() {
        const Phase_1 = {{exercise.Phase_1_time}};
        const p1_pause = {{exercise.in_pause_time}};
        const Phase_2 = {{exercise.Phase_2_time}};
        const p2_pause = {{exercise.out_pause_time}};
        const max_cycles = {{exercise.max_cycles}};
        breath_cycle(Phase_1, p1_pause, Phase_2, p2_pause, max_cycles);
      }

        </script>
  </body>
</html>
</code>```

When I runserver I can see all the objects, but when I click the 'Start Round' button the timer just appears and shows '0:00' without increasing or moving on to the next page. I don't know if this is because I'm passing things from python to JavaScript improperly or if its just that the javascript is cobbled togethr cludge.

If anyone had any advice I'd appreacate it.

Body:
I'm trying to use django to build a phase timer app for myself. I want a timer to run for each phase, then reset to zero and run for the next phase for n-cycles.

I've tried asking 'Friend computer' for help but am still struggling.

Here's the model.

from django.db import models

# Create your models here.

class Cycle(models.Model):
    name = models.CharField(max_length=100)
    instructions = models.TextField()
    phase_1_time = models.PositiveIntegerField()
    phase_1_hold_time = models.PositiveIntegerField()
    phase_2_time = models.PositiveIntegerField()
    phase_2_hold_time = models.PositiveIntegerField()
    recovery_time = models.PositiveIntegerField()
    max_cycles = models.PositiveIntegerField()

    def __str__(self):
        return self.name

And here's the view

''' View for the cycle app.'''
from django.shortcuts import render
from .models import Cycle

def exercise_list(request):
    exercises = Cycle.objects.all()
    return render(request, 'cycles/exercise_list.html', {'exercises': exercises})

def exercise_detail(request, exercise_id):
    exercise = Cycle.objects.get(id=exercise_id)
    phase_1_duration = exercise.phase_1_time
    phase_1_pause_duration = exercise.phase_1_pause_time
    phase_2_duration = exercise.phase_2_time
    phase_2_pause_duration = exercise.phase_2_pause_time
    recovery = exercise.recovery_time
    max_cycles = exercise.max_cycles
    return render(request, 'cycles/exercise_detail.html', {
        'exercise': exercise,
        'phase_1_duration': phase_1_duration,
        'phase_1_pause_duration': phase_1_pause_duration,
        'phase_2_duration': phase_2_duration,
        'phase_2_pause_duration': phase_2_pause_duration,
        'recovery': recovery,
        'max_cycles': max_cycles,

and the html

    <title>{{exercise.name}}</title>

{{ exercise.name }}

Instructions: {{ exercise.instructions }}

Phase 1 Time: {{ exercise.Phase_1_time }}

Phase 1 pause Time: {{ exercise.phase_1_pause_time }}

Phase2 Time: {{ exercise.Phase_2_time }}

Phase 2 pause Time: {{ exercise.phase_2_pause_time }}

Long pause Time: {{ exercise.long_pause}}

Recovery Time: {{ exercise.recovery_time }}

Max Cycles: {{ exercise.max_cycles }}

  <button onclick="firstRound()">Start Round</button>

When I runserver I can see all the objects, but when I click the 'Start Round' button the timer just appears and shows '0:00' without increasing or moving on to the next page. I don't know if this is because I'm passing things from python to JavaScript improperly or if its just that the javascript is cobbled togethr cludge.

If anyone had any advice I'd appreacate it.


问:
How to Save the Appointment in following format "04.01.2023 08:00 - 13:00" in a Variable in ASP.Net Web Api
On the Web-Client, the appointment is given in the following format "04.01.2023 08:00 - 13:00". After retrieving it, how can I save it in DateTime variable? Or what would be the proper way to retrieve this appointment to expose it from my Api

var appointment = new DateTime(2023, 01, 04, 08, 00) ??


问:
how to create a invoice sheet in Oracle Apex
I'm using oracle Apex 22.2 to build an app to manage records for a company and I need to print an invoice as in the image below. and I need to use Unicode characters on the invoice. how can I create a page with an invoice as below? what region and items should I use? the way I need the invoice

I'm new to oracle apex and I tried using the static content region for the task but got stuck.
any help would be appreciated


问:
How can you turn a string that contains an equation into a readable and solvable equation in Lua
I am currently attempting to write a calculator (as a learning project) but am having troubles turning an equation in a string to a solveable equation that can be read. This is my code so far:

```<code>io.write('Please insert equation: ', '\n' )

--Variables
local equation = io.read()
local restart = 1
local incorrect = 0
local numberthingy = tostring(tonumber(equation))

while restart == 1 do
    io.write('Is this correct? (Y/N): ', equation, '\n')
    local choice = io.read()
    if choice == 'Y' then
        print(numberthingy)
        restart = 0
    elseif choice == 'N' then
        incorrect = 1
        while incorrect == 1 do --restarts entire while loop if incorrect
            io.write('Please insert equation: ', '\n')
            equation = io.read()
            restart = 1
            break
        end
    else
        print("Please Choose Applicable Options")
        restart = 1
    end
end
</code>```

I'm expecting an answer such as 3 when entering 1 + 2 or any other equation but I am continuously recieving nil

Body:
I am currently attempting to write a calculator (as a learning project) but am having troubles turning an equation in a string to a solveable equation that can be read. This is my code so far:

io.write('Please insert equation: ', '\n' )

--Variables
local equation = io.read()
local restart = 1
local incorrect = 0
local numberthingy = tostring(tonumber(equation))

while restart == 1 do
    io.write('Is this correct? (Y/N): ', equation, '\n')
    local choice = io.read()
    if choice == 'Y' then
        print(numberthingy)
        restart = 0
    elseif choice == 'N' then
        incorrect = 1
        while incorrect == 1 do --restarts entire while loop if incorrect
            io.write('Please insert equation: ', '\n')
            equation = io.read()
            restart = 1
            break
        end
    else
        print("Please Choose Applicable Options")
        restart = 1
    end
end

I'm expecting an answer such as 3 when entering 1 + 2 or any other equation but I am continuously recieving nil


问:
Updating labels on Blue/Green deployment to EKS using Helm
I am trying to create a blue/green deployment Helm chart, but struggling with how to switch the primary/secondary and have the labels move with the deployments.

Effectively, I setup the Helm chart using 2 "slots" defined in the values.yaml file:

blue:
  enabled: false

green:
  enabled: false

productionSlot: blue

image:
  name: "nginx"
  blue_tag: "latest"
  green_tag: "latest"
...
```
<p>Then in my deploy.yaml and service.yaml I switch on/off the template like this:</p>
<pre class="lang-yaml prettyprint-override"><code>{{- if .Values.blue.enabled }}
  {{- $_ := set . "currSlot" "blue" }}
  {{- template "blue-green-deploy.deployment" . }}
{{- end }}
{{- if .Values.green.enabled }}
{{- if .Values.blue.enabled }}
---
{{- end }}
  {{- $_ := set . "currSlot" "green" }}
  {{- template "blue-green-deploy.deployment" . }}
{{- end }}
</code>```

And then the Deployment looks something like:

{{- define "blue-green-deploy.deployment" -}}
{{- $currSlot := (pluck .currSlot .Values | first) }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-{{ .currSlot }}
  labels:
    release: {{ .Release.Name }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    app: {{ template "blue-green-deploy.name" . }}
    version: {{ $currSlot.appVersion | quote }}
    slot: {{ .currSlot }}
    route: {{ template "blue-green-deploy.route" . }}
...
```
<p>Effectively I call the same template, but with the <code>currSlot</code> set to the proper slot I am processing.  On the first deploy I set both blue and green to "enabled".  After that, whichever is not the primary I set it to "enabled" w/ the new version, do the deploy (which updated just the deployment and the service, not the Istio resources)</p>
<p>Then, once integration testing completes on the new pods, if successful I "flip" the productionSlot value and the alt becomes the primary and the primary becomes the alt by swapping the Istio <code>DestinationRule</code>s subset filters.</p>
<pre class="lang-yaml prettyprint-override"><code>...
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-dr
spec:
  host: {{ include "blue-green-deploy.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local
  subsets:
  - name: primary
    labels:
      slot: {{ .Values.productionSlot }}
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-dr-alt
spec:
  host: {{ include "blue-green-deploy.fullname" . }}-{{ if eq .Values.productionSlot "blue" }}green{{ else }}blue{{ end }}.{{ .Release.Namespace }}.svc.cluster.local
  subsets:
  - name: alt
    labels:
      slot: {{ if eq .Values.productionSlot "blue" }}green{{ else }}blue{{ end }}
</code>```

To "swap" the blue/green routes, I simply call helm passing in the productionSlot value like this:

helm upgrade test-app . --namespace test --install --set productionSlot=green --reuse-values --wait

Where I am struggling is I need to update the route label of the Deployments themselves as well, but when I do the route switch I am not setting either blue or green "enabled" as I don't want to override their deployed pods at all...I just need to update the label on the Deployment, and by extension the Pods.

Is there a way to do that with Helm?  If I set the blue.enabled and/or green.enabled to true then it's going to force the deployment change and reinstall the pods, right?

Body:
I am trying to create a blue/green deployment Helm chart, but struggling with how to switch the primary/secondary and have the labels move with the deployments.

Effectively, I setup the Helm chart using 2 "slots" defined in the values.yaml file:

blue:
  enabled: false

green:
  enabled: false

productionSlot: blue

image:
  name: "nginx"
  blue_tag: "latest"
  green_tag: "latest"
...

Then in my deploy.yaml and service.yaml I switch on/off the template like this:

{{- if .Values.blue.enabled }}
  {{- $_ := set . "currSlot" "blue" }}
  {{- template "blue-green-deploy.deployment" . }}
{{- end }}
{{- if .Values.green.enabled }}
{{- if .Values.blue.enabled }}
---
{{- end }}
  {{- $_ := set . "currSlot" "green" }}
  {{- template "blue-green-deploy.deployment" . }}
{{- end }}

And then the Deployment looks something like:

{{- define "blue-green-deploy.deployment" -}}
{{- $currSlot := (pluck .currSlot .Values | first) }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-{{ .currSlot }}
  labels:
    release: {{ .Release.Name }}
    chart: "{{ .Chart.Name }}-{{ .Chart.Version }}"
    app: {{ template "blue-green-deploy.name" . }}
    version: {{ $currSlot.appVersion | quote }}
    slot: {{ .currSlot }}
    route: {{ template "blue-green-deploy.route" . }}
...

Effectively I call the same template, but with the currSlot set to the proper slot I am processing.  On the first deploy I set both blue and green to "enabled".  After that, whichever is not the primary I set it to "enabled" w/ the new version, do the deploy (which updated just the deployment and the service, not the Istio resources)

Then, once integration testing completes on the new pods, if successful I "flip" the productionSlot value and the alt becomes the primary and the primary becomes the alt by swapping the Istio DestinationRules subset filters.

...
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-dr
spec:
  host: {{ include "blue-green-deploy.fullname" . }}.{{ .Release.Namespace }}.svc.cluster.local
  subsets:
  - name: primary
    labels:
      slot: {{ .Values.productionSlot }}
---
apiVersion: networking.istio.io/v1alpha3
kind: DestinationRule
metadata:
  name: {{ include "blue-green-deploy.fullname" . }}-dr-alt
spec:
  host: {{ include "blue-green-deploy.fullname" . }}-{{ if eq .Values.productionSlot "blue" }}green{{ else }}blue{{ end }}.{{ .Release.Namespace }}.svc.cluster.local
  subsets:
  - name: alt
    labels:
      slot: {{ if eq .Values.productionSlot "blue" }}green{{ else }}blue{{ end }}

To "swap" the blue/green routes, I simply call helm passing in the productionSlot value like this:

helm upgrade test-app . --namespace test --install --set productionSlot=green --reuse-values --wait

Where I am struggling is I need to update the route label of the Deployments themselves as well, but when I do the route switch I am not setting either blue or green "enabled" as I don't want to override their deployed pods at all...I just need to update the label on the Deployment, and by extension the Pods.

Is there a way to do that with Helm?  If I set the blue.enabled and/or green.enabled to true then it's going to force the deployment change and reinstall the pods, right?


问:
I get NPM ERR when I try to install strapi
I tried to install strapi with npx create-strapi-app backend, but an error keep appearing , I couldn't solve the problem or found any solution anywhere, I don't know what I'm doing wrong exaclty
Here is the code error I'm getting :


问:
How to do multiple things in a single line with Pandas
I have a dataset with the following columns:
['country code', 'transaction date', 'amount', 'distance', 'employee']

Im cleaning the data and but there are many things that I need to do that make the code messy. I'm working on google colab and currently im using one cell per step, and I was wondering if there is a way to do it all in just one.

This is what i currently have:

cell 1: i dont need all the columns, just three so i do:
step1

```<code>df = df[['transaction Date','amount','distance']
</code>```

cell 2: the date is in the excel format (i.e  44327 = 2021-05-11) so I do the following to change the format
step 2

```<code>pd.to_datetime(data['Transaction Date'], unit='D', origin='1899-12-30')
</code>```

cell 3 i want to filter with two conditions
step 3

```<code>df2=df[(df['distance'].notnull()) & (df['transaction Date'] > '2021-01-01') ]
</code>```

cell4: i group by week
step 4

```<code>final_df = df2.groupby([pd.Grouper(key='transaction date', freq='W')])['values'].sum()
</code>```

I'd love to be able to have just one cell that looks something like this>

```<code>df = step1.step2.step3.step4
</code>```

Body:
I have a dataset with the following columns:
['country code', 'transaction date', 'amount', 'distance', 'employee']

Im cleaning the data and but there are many things that I need to do that make the code messy. I'm working on google colab and currently im using one cell per step, and I was wondering if there is a way to do it all in just one.

This is what i currently have:

cell 1: i dont need all the columns, just three so i do:
step1

df = df[['transaction Date','amount','distance']

cell 2: the date is in the excel format (i.e  44327 = 2021-05-11) so I do the following to change the format
step 2

pd.to_datetime(data['Transaction Date'], unit='D', origin='1899-12-30')

cell 3 i want to filter with two conditions
step 3

df2=df[(df['distance'].notnull()) & (df['transaction Date'] > '2021-01-01') ]

cell4: i group by week
step 4

final_df = df2.groupby([pd.Grouper(key='transaction date', freq='W')])['values'].sum()

I'd love to be able to have just one cell that looks something like this>

df = step1.step2.step3.step4


问:
Unity: saving Inspector to script
Im wondering if its posible to save seralized data from inspector back into script.

if I'm creating a data base class from inspector, could i write it to the file.

```<code>[System.Serializable]
public class Item
{
//attributes
}
</code>```
```<code>public class ItemDataBase : MonoBehaviour
{

    public Item[] items =
        {
        new Item("Sword",Item.itemType.Weapon,"a sharp blade"),
        new Item("Hammer",Item.itemType.Weapon,"looks heavy"),
        new Item("Spear",Item.itemType.Weapon,"sharp stick"),
        new Item("Health Potion",Item.itemType.Weapon,"color of blood")
    };

}
</code>```

lets say if i would build up this database form inspector, could i wright/update this file

Title: Unity: saving Inspector to script

Body:
Im wondering if its posible to save seralized data from inspector back into script.

if I'm creating a data base class from inspector, could i write it to the file.

[System.Serializable]
public class Item
{
//attributes
}

public class ItemDataBase : MonoBehaviour
{

    public Item[] items =
        {
        new Item("Sword",Item.itemType.Weapon,"a sharp blade"),
        new Item("Hammer",Item.itemType.Weapon,"looks heavy"),
        new Item("Spear",Item.itemType.Weapon,"sharp stick"),
        new Item("Health Potion",Item.itemType.Weapon,"color of blood")
    };

}

lets say if i would build up this database form inspector, could i wright/update this file


问:
FullCalendar to detect render event
Is there any option that I can add eventlistener or function during rendering?

What I want to do is manipulating week number value as I wanted instead of showing the actual week number of the year. It works fine by manipulating DOM as below image, but I have an issue with initial view and when I forcefully use render function

this is what I expected, and it works except for initial day view.

this happens for initial view (when refresh the page), or use render function

The problem for initial view or after render function, it cannot overwrite content but just adding the custom text I want.

This is my code snippet.

```<code>    detectChanges(event) {
        this.domModification();
    }

    domModification() {
        const { type } = this.schedule.getApi().view;

        if (type === 'timeGridDay') {
            const weekNumberTag = document.querySelector('a.fc-timegrid-axis-cushion')
            weekNumberTag.innerHTML = 'test';
        }
    }

</code>```

Title: FullCalendar to detect render event

Body:
Is there any option that I can add eventlistener or function during rendering?

What I want to do is manipulating week number value as I wanted instead of showing the actual week number of the year. It works fine by manipulating DOM as below image, but I have an issue with initial view and when I forcefully use render function

this is what I expected, and it works except for initial day view.

this happens for initial view (when refresh the page), or use render function

The problem for initial view or after render function, it cannot overwrite content but just adding the custom text I want.

This is my code snippet.

    detectChanges(event) {
        this.domModification();
    }

    domModification() {
        const { type } = this.schedule.getApi().view;

        if (type === 'timeGridDay') {
            const weekNumberTag = document.querySelector('a.fc-timegrid-axis-cushion')
            weekNumberTag.innerHTML = 'test';
        }
    }


问:
PyQt fill transparent object with color
So I'm doing an assignment with the go chess, and I first created all the pieces on the board, which are transparent. If it's a black player's turn, when the player clicks it, the piece will turn from transparent to the black piece. The pieces can change color depending on if a black or white piece is added. How am I supposed to do it?

```<code>def drawPieces(self, painter):
    '''draw the prices on the board'''
    colour = Qt.GlobalColor.transparent  # empty square could be modeled with transparent pieces
    for row in range(len(self.boardArray)):
        for col in range(len(self.boardArray)):
            painter.save()
            painter.translate(row*self.squareWidth(),col*self.squareHeight())
            # TODO draw some the pieces as ellipses
            # TODO choose your colour and set the painter brush to the correct colour
            brush = QBrush(Qt.BrushStyle.SolidPattern)
            brush.setColor(colour)
            painter.setBrush(brush)
            radiusW = self.squareWidth() *1/10
            radiusH = self.squareHeight() *1/10
            center = QPointF(radiusW, radiusH)
            painter.drawEllipse(center, radiusW, radiusH)
            painter.restore()
</code>```
```<code>def placestone(self,painter):
    # function to place the stone on the board
    if self.turn == Piece.Black:
        self.boardArray[self.Ypos][self.Xpos].Piece = Piece.Black

    else:
        self.boardArray[self.Ypos][self.Xpos].Piece = Piece.White
</code>```

I'm expecting when the user clicks the place where the transparent piece is, the piece will change color according to which player's turn it is

Title: PyQt fill transparent object with color

Body:
So I'm doing an assignment with the go chess, and I first created all the pieces on the board, which are transparent. If it's a black player's turn, when the player clicks it, the piece will turn from transparent to the black piece. The pieces can change color depending on if a black or white piece is added. How am I supposed to do it?

def drawPieces(self, painter):
    '''draw the prices on the board'''
    colour = Qt.GlobalColor.transparent  # empty square could be modeled with transparent pieces
    for row in range(len(self.boardArray)):
        for col in range(len(self.boardArray)):
            painter.save()
            painter.translate(row*self.squareWidth(),col*self.squareHeight())
            # TODO draw some the pieces as ellipses
            # TODO choose your colour and set the painter brush to the correct colour
            brush = QBrush(Qt.BrushStyle.SolidPattern)
            brush.setColor(colour)
            painter.setBrush(brush)
            radiusW = self.squareWidth() *1/10
            radiusH = self.squareHeight() *1/10
            center = QPointF(radiusW, radiusH)
            painter.drawEllipse(center, radiusW, radiusH)
            painter.restore()

def placestone(self,painter):
    # function to place the stone on the board
    if self.turn == Piece.Black:
        self.boardArray[self.Ypos][self.Xpos].Piece = Piece.Black

    else:
        self.boardArray[self.Ypos][self.Xpos].Piece = Piece.White

I'm expecting when the user clicks the place where the transparent piece is, the piece will change color according to which player's turn it is


问:
How to use Microsoft login info to access an Azure application using MSAL auth for react?
I am working on a single page application (SPA) app that grants access to specific paths in the application, based on roles setup in Azure AD for the user logging in. As per this https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles

This is my 'authConfig.js' file -you can see the cacheLocation

```<code>const clientId = window.REACT_APP_CLIENTID
export const msalConfig = {
    auth: {
        clientId: clientId,
        authority: window.REACT_APP_AUTHORITY,
        redirectUri: 'http://localhost:3000/todolist/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin
        postLogoutRedirectUri: "/", // Indicates the page to navigate after logout.
        navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
    },
    cache: {
        cacheLocation: "localStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    },
    system: {
        loggerOptions: {
            loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            }
        }
    }
};

/**
 * Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
export const protectedResources = {
    apiTodoList: {
        todoListEndpoint: window.REACT_APP_APIENDPOINT+"/api/v2/support/list",
        scopes: [window.REACT_APP_APIENDPOINT+"/access_as_user"],
    },
}

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
export const loginRequest = {
    scopes: [...protectedResources.apiTodoList.scopes]
};

export const appRoles = {
    TaskUser: "TaskUser",
    TaskAdmin: "TaskAdmin",
    TrialAdmin: "Trial.Admin",
    GlobalAdmin: "Global.Admin"
}
</code>```

Here is the App.jsx file. Here the PageLayout component renders the Page, based on the RouteGuard's authentication comp

```<code>import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { MsalProvider } from "@azure/msal-react";

import { RouteGuard } from './components/RouteGuard';
import { PageLayout } from "./components/PageLayout";
import { TodoList } from "./pages/TodoList";

import { appRoles } from "./authConfig";

import "./styles/App.css";

const Pages = () => {
  return (
    <Switch>
      <RouteGuard
        exact
        path=''
        roles={[appRoles.TaskUser, appRoles.TaskAdmin, appRoles.TrialAdmin, appRoles.GlobalAdmin]}
        Component={TodoList}
      />
    </Switch>
  )
}

/**
 * msal-react is built on the React context API and all parts of your app that require authentication must be
 * wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication
 * then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the
 * PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
 */
const App = ({ instance }) => {

  return (
    <Router>
      <MsalProvider instance={instance}>
        <PageLayout>
          <Pages instance={instance} />
        </PageLayout>
      </MsalProvider>
    </Router>
  );
}

export default App;
</code>```

So as far as my understanding goes, the path 'todolist' is accessed with the listed role, and component is rendered

```<code>import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";

import { Nav, Navbar, Button, Dropdown, DropdownButton} from "react-bootstrap";

import React, { useState, useEffect } from "react";

import { loginRequest } from "../authConfig";

import { InteractionStatus, InteractionType } from "@azure/msal-browser";

import "../styles/App.css";

import logo from "../public/images/logo.jpg";

export const NavigationBar = (props) => {

    const { instance } = useMsal();
    const { inProgress } = useMsal();
    const [isAuthorized, setIsAuthorized] = useState(false);
    //The below function is needed incase you want to login using Popup and not redirect
    const handleLogin = () => {
        instance.loginPopup(loginRequest)
            .catch((error) => console.log(error))
    }

    /**
     * Most applications will need to conditionally render certain components based on whether a user is signed in or not.
     * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
     * only render their children if a user is authenticated or unauthenticated, respectively.
     */
    return (
        <>
            <Navbar className="color-custom" variant="dark">
                <a className="navbar-brand" href="/"><img src={logo} className="navbarLogo" alt="TODDOLIST1"/></a>
                <AuthenticatedTemplate>
 <Nav.Link as={Button} id="signupbutton" variant="dark" className="signupNav" href="/todolist"><strong>List</strong></Nav.Link>
                    <Button variant="warning" className="ml-auto" drop="left" title="Sign Out" onClick={() => instance.logoutRedirect({ postLogoutRedirectUri: "/" })}><strong>Sign Out</strong></Button>
                </AuthenticatedTemplate>
                <UnauthenticatedTemplate>
                    <Button variant="dark" className="ml-auto" drop="left" title="Sign In" onClick={() => instance.loginRedirect(loginRequest)}>Sign In</Button>
                </UnauthenticatedTemplate>
            </Navbar>
        </>
    );
};
</code>```

Here is the RouteGuard.jsx component that renders based on roles/authorization.

```<code>import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import { useMsal } from "@azure/msal-react";

export const RouteGuard = ({ Component, ...props }) => {

    const { instance } = useMsal();
    const [isAuthorized, setIsAuthorized] = useState(false);

    const onLoad = async () => {
        const currentAccount = instance.getActiveAccount();

        if (currentAccount && currentAccount.idTokenClaims['roles']) {
            let intersection = props.roles
                .filter(role => currentAccount.idTokenClaims['roles'].includes(role));

            if (intersection.length > 0) {
                setIsAuthorized(true);
            }
        }
    }

    useEffect(() => {
        onLoad();
    }, [instance]);

    return (
        <>

            {
                isAuthorized
                    ?
                    <Route {...props} render={routeProps => <Component {...routeProps} />} />
                    :
                    <div className="data-area-div">
                        <h3>You are unauthorized to view this content.</h3>
                    </div>
            }
        </>
    );
};
</code>```

I am able to login to the application once. And then since auth info is stored in localStorage, it does maintain the login and I am not required to do so again.
However, I would want to login or access the /todolist page directly if I access the application through login.microsoft.com and select the application. When I do this now, it asks me to login again.

Since I am already logged in to Microsoft login (lets say accessing Outlook with the same email), how would I be able to directly login in to the Todolist application, without having to sign in again (entering the password)

Any suggestions ?

Body:
I am working on a single page application (SPA) app that grants access to specific paths in the application, based on roles setup in Azure AD for the user logging in. As per this https://github.com/Azure-Samples/ms-identity-javascript-react-tutorial/tree/main/5-AccessControl/1-call-api-roles

This is my 'authConfig.js' file -you can see the cacheLocation

const clientId = window.REACT_APP_CLIENTID
export const msalConfig = {
    auth: {
        clientId: clientId,
        authority: window.REACT_APP_AUTHORITY,
        redirectUri: 'http://localhost:3000/todolist/', // You must register this URI on Azure Portal/App Registration. Defaults to window.location.origin
        postLogoutRedirectUri: "/", // Indicates the page to navigate after logout.
        navigateToLoginRequestUrl: false, // If "true", will navigate back to the original request location before processing the auth code response.
    },
    cache: {
        cacheLocation: "localStorage", // Configures cache location. "sessionStorage" is more secure, but "localStorage" gives you SSO between tabs.
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    },
    system: {
        loggerOptions: {
            loggerCallback: (level, message, containsPii) => {
                if (containsPii) {
                    return;
                }
                switch (level) {
                    case LogLevel.Error:
                        console.error(message);
                        return;
                    case LogLevel.Info:
                        console.info(message);
                        return;
                    case LogLevel.Verbose:
                        console.debug(message);
                        return;
                    case LogLevel.Warning:
                        console.warn(message);
                        return;
                }
            }
        }
    }
};

/**
 * Add here the endpoints and scopes when obtaining an access token for protected web APIs. For more information, see:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
 */
export const protectedResources = {
    apiTodoList: {
        todoListEndpoint: window.REACT_APP_APIENDPOINT+"/api/v2/support/list",
        scopes: [window.REACT_APP_APIENDPOINT+"/access_as_user"],
    },
}

/**
 * Scopes you add here will be prompted for user consent during sign-in.
 * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
 * For more information about OIDC scopes, visit:
 * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
 */
export const loginRequest = {
    scopes: [...protectedResources.apiTodoList.scopes]
};

export const appRoles = {
    TaskUser: "TaskUser",
    TaskAdmin: "TaskAdmin",
    TrialAdmin: "Trial.Admin",
    GlobalAdmin: "Global.Admin"
}

Here is the App.jsx file. Here the PageLayout component renders the Page, based on the RouteGuard's authentication comp

import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import { MsalProvider } from "@azure/msal-react";

import { RouteGuard } from './components/RouteGuard';
import { PageLayout } from "./components/PageLayout";
import { TodoList } from "./pages/TodoList";

import { appRoles } from "./authConfig";

import "./styles/App.css";

const Pages = () => {
  return (
    <Switch>
      <RouteGuard
        exact
        path=''
        roles={[appRoles.TaskUser, appRoles.TaskAdmin, appRoles.TrialAdmin, appRoles.GlobalAdmin]}
        Component={TodoList}
      />
    </Switch>
  )
}

/**
 * msal-react is built on the React context API and all parts of your app that require authentication must be
 * wrapped in the MsalProvider component. You will first need to initialize an instance of PublicClientApplication
 * then pass this to MsalProvider as a prop. All components underneath MsalProvider will have access to the
 * PublicClientApplication instance via context as well as all hooks and components provided by msal-react. For more, visit:
 * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-react/docs/getting-started.md
 */
const App = ({ instance }) => {

  return (
    <Router>
      <MsalProvider instance={instance}>
        <PageLayout>
          <Pages instance={instance} />
        </PageLayout>
      </MsalProvider>
    </Router>
  );
}

export default App;

So as far as my understanding goes, the path 'todolist' is accessed with the listed role, and component is rendered

import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from "@azure/msal-react";

import { Nav, Navbar, Button, Dropdown, DropdownButton} from "react-bootstrap";

import React, { useState, useEffect } from "react";

import { loginRequest } from "../authConfig";

import { InteractionStatus, InteractionType } from "@azure/msal-browser";

import "../styles/App.css";

import logo from "../public/images/logo.jpg";

export const NavigationBar = (props) => {

    const { instance } = useMsal();
    const { inProgress } = useMsal();
    const [isAuthorized, setIsAuthorized] = useState(false);
    //The below function is needed incase you want to login using Popup and not redirect
    const handleLogin = () => {
        instance.loginPopup(loginRequest)
            .catch((error) => console.log(error))
    }

    /**
     * Most applications will need to conditionally render certain components based on whether a user is signed in or not.
     * msal-react provides 2 easy ways to do this. AuthenticatedTemplate and UnauthenticatedTemplate components will
     * only render their children if a user is authenticated or unauthenticated, respectively.
     */
    return (
        <>
            <Navbar className="color-custom" variant="dark">

                <AuthenticatedTemplate>
 List
                    <Button variant="warning" className="ml-auto" drop="left" title="Sign Out" onClick={() => instance.logoutRedirect({ postLogoutRedirectUri: "/" })}>Sign Out</Button>
                </AuthenticatedTemplate>
                <UnauthenticatedTemplate>
                    <Button variant="dark" className="ml-auto" drop="left" title="Sign In" onClick={() => instance.loginRedirect(loginRequest)}>Sign In</Button>
                </UnauthenticatedTemplate>
            </Navbar>
        </>
    );
};

Here is the RouteGuard.jsx component that renders based on roles/authorization.

import React, { useState, useEffect } from "react";
import { Route } from "react-router-dom";
import { useMsal } from "@azure/msal-react";

export const RouteGuard = ({ Component, ...props }) => {

    const { instance } = useMsal();
    const [isAuthorized, setIsAuthorized] = useState(false);

    const onLoad = async () => {
        const currentAccount = instance.getActiveAccount();

        if (currentAccount && currentAccount.idTokenClaims['roles']) {
            let intersection = props.roles
                .filter(role => currentAccount.idTokenClaims['roles'].includes(role));

            if (intersection.length > 0) {
                setIsAuthorized(true);
            }
        }
    }

    useEffect(() => {
        onLoad();
    }, [instance]);

    return (
        <>

            {
                isAuthorized
                    ?
                    <Route {...props} render={routeProps => <Component {...routeProps} />} />
                    :

You are unauthorized to view this content.

            }
        </>
    );
};

I am able to login to the application once. And then since auth info is stored in localStorage, it does maintain the login and I am not required to do so again.
However, I would want to login or access the /todolist page directly if I access the application through login.microsoft.com and select the application. When I do this now, it asks me to login again.

Since I am already logged in to Microsoft login (lets say accessing Outlook with the same email), how would I be able to directly login in to the Todolist application, without having to sign in again (entering the password)

Any suggestions ?


问:
Can't create Microsoft 365 Development Program (phone number already in use.)
I'm facing some problems when creating a new Microsoft 365 Development Program account when i try requesting the SMS verification code. I get:

We can't continue with the signup process for the following reason:

Your phone number is already associated with an existing developer account.
For help with your Microsoft account, go to Microsoft account and verify your information.

MS-CorrelationID: f21a28b2-4534-4bb9-8167-1323c8b2d00e

Code: 40901

The problem is that i had an dev account set up before on my previous job, but  I no longer work there so I dont have access to that email.

Please help:)

tried logging in with email accounts by the login is registration on my previous email


问:
EBS volumes Storage Analysis
I have created a ec2 instance and attached 4 ebs volumes, gp2=3gb, gp3=3, io1=4gb, io2=4 and mounted it.

I have installed postgres source code on it and the database location path is /usr/local/postgresql/pgsql/data.

I have create a test table name testdb with 2 million  sample entries, but it does not shows the space consumed on ebs volumes that I have attached.

Whatever tables i am creating all the storage is been utilize by the root volume which comes by default when we create an instance and it shows 34% used.

I want to know how can move or  change the location, so that the database which I have created with 2 million entries, it should reflect in any of the ebs-volumes which I have attached to an instances.

Also, how can I check what data is being consume by the ebs-vol?

The 4 volumes which i have attached only shows 2% used, How to check what 2% has been used for and i want table which i am creating in PSQL database to be store in any volumes by default automatically without storing in root volume. so that I can make an analysis which EBS vol is good out of 4 with low cost use.

I'm unable to find what i am doing wrong.

Title: EBS volumes Storage Analysis


问:
Postgres - connection timeout (JDBC - DBeaver) but connects to pgadmin (completely local)
freshly installed postgres and will installing got an error
'An error occured executing the microsoft VC++ runtime installer'

solved by creating a shortcut "[PATH]\postgresql-9.6.24-1-windows-x64.exe --install_runtimes 0"

```<code>listen_addresses = '*'      # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)
port = 5432             # (change requires restart)
max_connections = 100           # (change requires restart)
</code>```
```<code># IPv4 local connections:
host    all             all             all            md5
# IPv6 local connections:
host    all             all             all                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
host    replication     postgres        127.0.0.1/32            md5
host    replication     postgres        ::1/128                 md5
</code>```

checked everything

Body:
freshly installed postgres and will installing got an error
'An error occured executing the microsoft VC++ runtime installer'

solved by creating a shortcut "[PATH]\postgresql-9.6.24-1-windows-x64.exe --install_runtimes 0"

listen_addresses = '*'      # what IP address(es) to listen on;
                    # comma-separated list of addresses;
                    # defaults to 'localhost'; use '*' for all
                    # (change requires restart)
port = 5432             # (change requires restart)
max_connections = 100           # (change requires restart)

# IPv4 local connections:
host    all             all             all            md5
# IPv6 local connections:
host    all             all             all                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
host    replication     postgres        127.0.0.1/32            md5
host    replication     postgres        ::1/128                 md5

checked everything


问:
Using Bleak library in python to try and discover my Android phone
I am currently writing a python program that automates the lights in my home. I want the program to be able to scan for bluetooth devices, and if it discovers my android phone (Which means I am home), I want the program to turn on the lights in my room. If my android phone is not discovered, I want the program to turn off all the lights in my room.

However I am having a little trouble discovering my phone. The program works well and discovers many bluetooth devices like my ear buds etc... but never my phone. Even if my phone is "discoverable" mode.

I am obviously missing something here. Are phones just not discoverable this way? I have tried with both android and iphone but the results are the same. No devices with those MAC addresses are found. What am I missing here?

My code:

```<code>import asyncio
from bleak import BleakScanner

class BluetoothScanner:
    def __init__(self, target_addresses):
        self.target_addresses = target_addresses

    async def run(self):
        # Scan for devices for 20 seconds. The default is 5 seconds.
        devices = await BleakScanner.discover(timeout=20)
        for d in devices:
            if d.address in self.target_addresses:
                print(f"Target device  >>\033[1m{d.name}\033[0m<< with MAC address {d.address} found!")
            else:
                print(d)

if __name__ == "__main__":
    PHONE_MAC_ADDRESS = "XX:XX:XX:XX:XX:XX"  # My phone
    BUDS_MAC_ADDRESS = "XX:XX:XX:XX:XX:XX"   # My ear buds

    scanner = BluetoothScanner([PHONE_MAC_ADDRESS, BUDS_MAC_ADDRESS])
    loop = asyncio.get_event_loop()
    loop.run_until_complete(scanner.run())
</code>```

The program discovers my ear buds perfectly, but not my android phone! Any help on the matter is appreciated!

Body:
I am currently writing a python program that automates the lights in my home. I want the program to be able to scan for bluetooth devices, and if it discovers my android phone (Which means I am home), I want the program to turn on the lights in my room. If my android phone is not discovered, I want the program to turn off all the lights in my room.

However I am having a little trouble discovering my phone. The program works well and discovers many bluetooth devices like my ear buds etc... but never my phone. Even if my phone is "discoverable" mode.

I am obviously missing something here. Are phones just not discoverable this way? I have tried with both android and iphone but the results are the same. No devices with those MAC addresses are found. What am I missing here?

My code:

import asyncio
from bleak import BleakScanner

class BluetoothScanner:
    def __init__(self, target_addresses):
        self.target_addresses = target_addresses

    async def run(self):
        # Scan for devices for 20 seconds. The default is 5 seconds.
        devices = await BleakScanner.discover(timeout=20)
        for d in devices:
            if d.address in self.target_addresses:
                print(f"Target device  >>\033[1m{d.name}\033[0m<< with MAC address {d.address} found!")
            else:
                print(d)

if __name__ == "__main__":
    PHONE_MAC_ADDRESS = "XX:XX:XX:XX:XX:XX"  # My phone
    BUDS_MAC_ADDRESS = "XX:XX:XX:XX:XX:XX"   # My ear buds

    scanner = BluetoothScanner([PHONE_MAC_ADDRESS, BUDS_MAC_ADDRESS])
    loop = asyncio.get_event_loop()
    loop.run_until_complete(scanner.run())

The program discovers my ear buds perfectly, but not my android phone! Any help on the matter is appreciated!


问:
How to do label encoding and one hot encoding in linux
Label one hot encoding
(https://i.stack.imgur.com/nPxR7.jpg)
Label encoding
(https://i.stack.imgur.com/JLaeh.jpg)
Data set
(https://i.stack.imgur.com/CLKZY.jpg)

What’s the code that can i do that on it


问:
No columns to parse from file
I am trying to read my data, but everytime I do (data = pd.read_csv(...), it says:

EmptyDataError: No columns to parse from file

I am just trying to read my csv file, and it does have columns, so I am seriously lost to why it says this. Can anyone help me please.

I use a MacBook so I haven't tried with the path solution

I tried to google solutions for this problem and I've done everything but it's still not working.

Title: No columns to parse from file


问:
change some django settings variables on runtime
I read some old answers but there is no way I understand so I want to learn if a new solution found.
I use django-rest-framework backend with react. Some apps like mailgun or django-storages variables configured from settings.py like secretkeys or app-ids. So on production, I want that users can enter the keys from admin panel or a form. I try
django-constance and django-extra-settings but I can not re-define variables with them.
I try to django.conf.settings but there is a warning about alter variables on runtime

So is there anyway to re-define a variable in settings.py


问:
Why doesn't fixed effects regression using lm function drop time-invariant variables?
Unit-fixed effects regression is supposed to drop time-invariant variables because time-invariant variables are absorbed by unit-fixed effects. This happens when we use plm function, but not with lm function. Why?

I generate the data as follows. This is essentially a small panel data of 3 individuals * 3 time-periods with independent variable X, dependent variable Y, time-invariant covariates Z, as well as unit-fixed effect id and time-fixed effect t.

```<code>X = rnorm(9,0,1)
Y = 2*X
df <- data.frame(
  X,
  Y,
  Z = c(1, 1, 1, 0, 0, 0, 0, 0, 0),
  id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
  t = c(1, 2, 3, 1, 2, 3, 1, 2, 3)
)
</code>```

I first use plm function to conduct a unit-fixed effect regression as follows.

```<code>plmfit <- plm(Y~X+Z, index = c("id", "t"), effect = "twoways", model = "within", data = df)
summary(plmfit)
</code>```

The output is like this:

```<code>Twoways effects Within Model

Call:
plm(formula = Y ~ X + Z, data = df, effect = "twoways",
    model = "within", index = c("id", "t"))

Balanced Panel: n = 3, T = 3, N = 9

Residuals:
          1           2           3           4           5           6
 1.7753e-15 -1.9565e-16  6.5662e-17  1.2292e-17  1.0598e-16  4.8263e-17
          7           8           9
-3.4982e-18 -2.1355e-17 -2.9027e-18

Coefficients:
    Estimate Std. Error   t-value  Pr(>|t|)
X 2.0000e+00 4.6806e-16 4.273e+15 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Total Sum of Squares:    19.528
Residual Sum of Squares: 3.2086e-30
R-Squared:      1
Adj. R-Squared: 1
F-statistic: 1.82585e+31 on 1 and 3 DF, p-value: < 2.22e-16
</code>```

This is okay. The time-invariant Z is not reported.

Next, I use lm function to do the same thing.

```<code>lmfit <- lm(Y~X+Z+factor(id)+factor(t),data=df)
summary(lmfit)
</code>```

The output is like this:

```<code>Call:
lm(formula = Y ~ X + Z + factor(id) + factor(t), data = df)

Residuals:
         1          2          3          4          5          6          7
 4.624e-16 -3.466e-16 -1.158e-16 -2.556e-16  1.228e-16  1.328e-16 -2.068e-16
         8          9
 2.238e-16 -1.701e-17

Coefficients: (1 not defined because of singularities)
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  2.961e-16  3.257e-16  9.090e-01    0.430
X            2.000e+00  1.918e-16  1.043e+16   <2e-16 ***
Z           -3.627e-16  3.475e-16 -1.044e+00    0.373
factor(id)2 -9.204e-17  3.796e-16 -2.430e-01    0.824
factor(id)3         NA         NA         NA       NA
factor(t)2  -4.906e-16  3.531e-16 -1.390e+00    0.259
factor(t)3  -3.636e-16  4.260e-16 -8.530e-01    0.456
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 4.237e-16 on 3 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 3.862e+31 on 5 and 3 DF,  p-value: < 2.2e-16
</code>```

As you can see, the time-invariant variable Z is not dropped. This is surprising. What is going on here? I would greatly appreciate it if anyone could give me an answer.

Body:
Unit-fixed effects regression is supposed to drop time-invariant variables because time-invariant variables are absorbed by unit-fixed effects. This happens when we use plm function, but not with lm function. Why?

I generate the data as follows. This is essentially a small panel data of 3 individuals * 3 time-periods with independent variable X, dependent variable Y, time-invariant covariates Z, as well as unit-fixed effect id and time-fixed effect t.

X = rnorm(9,0,1)
Y = 2*X
df <- data.frame(
  X,
  Y,
  Z = c(1, 1, 1, 0, 0, 0, 0, 0, 0),
  id = c(1, 1, 1, 2, 2, 2, 3, 3, 3),
  t = c(1, 2, 3, 1, 2, 3, 1, 2, 3)
)

I first use plm function to conduct a unit-fixed effect regression as follows.

plmfit <- plm(Y~X+Z, index = c("id", "t"), effect = "twoways", model = "within", data = df)
summary(plmfit)

The output is like this:

Twoways effects Within Model

Call:
plm(formula = Y ~ X + Z, data = df, effect = "twoways",
    model = "within", index = c("id", "t"))

Balanced Panel: n = 3, T = 3, N = 9

Residuals:
          1           2           3           4           5           6
 1.7753e-15 -1.9565e-16  6.5662e-17  1.2292e-17  1.0598e-16  4.8263e-17
          7           8           9
-3.4982e-18 -2.1355e-17 -2.9027e-18

Coefficients:
    Estimate Std. Error   t-value  Pr(>|t|)
X 2.0000e+00 4.6806e-16 4.273e+15 < 2.2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Total Sum of Squares:    19.528
Residual Sum of Squares: 3.2086e-30
R-Squared:      1
Adj. R-Squared: 1
F-statistic: 1.82585e+31 on 1 and 3 DF, p-value: < 2.22e-16

This is okay. The time-invariant Z is not reported.

Next, I use lm function to do the same thing.

lmfit <- lm(Y~X+Z+factor(id)+factor(t),data=df)
summary(lmfit)

The output is like this:

Call:
lm(formula = Y ~ X + Z + factor(id) + factor(t), data = df)

Residuals:
         1          2          3          4          5          6          7
 4.624e-16 -3.466e-16 -1.158e-16 -2.556e-16  1.228e-16  1.328e-16 -2.068e-16
         8          9
 2.238e-16 -1.701e-17

Coefficients: (1 not defined because of singularities)
              Estimate Std. Error    t value Pr(>|t|)
(Intercept)  2.961e-16  3.257e-16  9.090e-01    0.430
X            2.000e+00  1.918e-16  1.043e+16   <2e-16 ***
Z           -3.627e-16  3.475e-16 -1.044e+00    0.373
factor(id)2 -9.204e-17  3.796e-16 -2.430e-01    0.824
factor(id)3         NA         NA         NA       NA
factor(t)2  -4.906e-16  3.531e-16 -1.390e+00    0.259
factor(t)3  -3.636e-16  4.260e-16 -8.530e-01    0.456
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 4.237e-16 on 3 degrees of freedom
Multiple R-squared:      1, Adjusted R-squared:      1
F-statistic: 3.862e+31 on 5 and 3 DF,  p-value: < 2.2e-16

As you can see, the time-invariant variable Z is not dropped. This is surprising. What is going on here? I would greatly appreciate it if anyone could give me an answer.


问:
How does GCC's 100% CPU usage avoid slowing Windows computers to a crawl?
Unsure if this question fits better here or at Superuser, but it's about GCC internals so here seemed better.

Most heavy computing tasks on Windows that show up in task manager as "100%" CPU usage make the whole user interface sluggish - keyboard inputs lag, the mouse stutters, switching windows is delayed, etc. My understanding of why this happens is that Windows responds to the high demand for CPU time by servicing UI tasks less frequently. Examples include complex image manipulation commands, websites with too many javascript-powered ads, complex matrix operations in matlab or numpy, etc. Many of these aren't even multithreaded and only max out a single core, but they still slow the computer.

But I've noticed that when compiling large projects with GCC, it pegs all CPU cores at 100% usage for minutes at a time, but the user interface remains completely smooth. I've noticed the same thing with both MinGW toolchains and arm-none-eabi toolchains. How is GCC able to avoid stepping on the toes of UI tasks while maintaining such efficient CPU usage? I'm aware the task manager CPU usage number is a bit of a lie to children, but there's clearly something GCC is doing differently despite trying to use all available resources.


问:
The mappings Entity and another Entity are inconsistent with each other
I have a problem with my relations between my entities.

```<code>namespace AppBundle\Entity;

class StatusUpdate
{
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Manager", inversedBy="statusUpdates", fetch="EAGER")
     */
    private ?Manager $manager;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Order", inversedBy="statusUpdates", fetch="EAGER")
     */
    private ?Order $order;
}
</code>```

My second entity:

```<code>namespace AppBundle\Entity;

class Manager extends User
{

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\StatusUpdate", mappedBy="manager", cascade={"all"})
 */
protected Collection $statusUpdates;
...
}
</code>```

My third entity:

```<code>namespace AppBundle\Entity;

class Order extends AbstractEntity
{
/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\StatusUpdate", mappedBy="order", cascade={"all"})
 */
protected Collection $statusUpdates;
...
}
</code>```

It gives me a mapping error:

[FAIL] The entity-class AppBundle\Entity\StatusUpdate mapping is invalid:

The mappings AppBundle\Entity\StatusUpdate#manager and AppBundle\Entity\Manager#statusUpdates are inconsistent with each other.

if you comment on the manager property in the StatusUpdate class, the error disappears

Body:
I have a problem with my relations between my entities.

namespace AppBundle\Entity;

class StatusUpdate
{
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Manager", inversedBy="statusUpdates", fetch="EAGER")
     */
    private ?Manager $manager;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Order", inversedBy="statusUpdates", fetch="EAGER")
     */
    private ?Order $order;
}

My second entity:

namespace AppBundle\Entity;

class Manager extends User
{

/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\StatusUpdate", mappedBy="manager", cascade={"all"})
 */
protected Collection $statusUpdates;
...
}

My third entity:

namespace AppBundle\Entity;

class Order extends AbstractEntity
{
/**
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\StatusUpdate", mappedBy="order", cascade={"all"})
 */
protected Collection $statusUpdates;
...
}

It gives me a mapping error:

[FAIL] The entity-class AppBundle\Entity\StatusUpdate mapping is invalid:

The mappings AppBundle\Entity\StatusUpdate#manager and AppBundle\Entity\Manager#statusUpdates are inconsistent with each other.

if you comment on the manager property in the StatusUpdate class, the error disappears


问:
Faking IHttpContextAccessor for HangFire
I have multi-tenant Web API application built using ASP.NET Core 6. We are using HangFire for Report Scheduling.
It uses Onion based Architecture where Interface lies in the application and implementation
outside the layer

Project has application Layer and Integration Layer , so IDbContext will be present in app layer and implementation class DbContext lies in Integration Layer, so I can not create dbContext instance directly from app layer as it is not accessible.

As it is web API , we use jwt token and this token is passed as part of "Http Request Header" for every other request for user to authorize.

As background jobs run , this HttpContext will be null which ends up giving error for all services as most of the DI services use this to get the values like connection String for DbContext, logged in user, URL to third party services as all are stored as part of that HttpHeader.

```<code> public jmasdbContext(DbContextOptions<jmasdbContext> options, ITenantProviderService tnt, IJwtAuthenticationManager jwt, IWebHostEnvironment env)
        : base(options)
    {
        //Check if is developement is added for migration purpose.- THIS IF CONDITION CAN BE REMOVED WHILE DEPLOYING TO PRODUCTION
        if (!env.EnvironmentName.Equals("Development"))
        {
            //This if part will be executed only during Login creation as Claims will not be set at this time,
            //we need to fetch ConnectionString from Tenant...
            if (tnt != null && tnt.HasTenantSet())
            {
                ConnectionString = tnt.Tenant.ConnectionString;
            }
            else if (jwt != null && !string.IsNullOrEmpty(jwt.GetAccessToken()))
            {
                ConnectionString = jwt.GetTenantConnectionString();
            }
        }
    }
</code>```

Here is how the connectionString is Set. First part gets executed during setting the tenant (login) and else part for every subsequent request

The code jwt.GetAccessToken() is dependent on httpContext and jwt.GetTenantConnectionString() is dependent on the jwt.GetAccessToken as it is stored as part of token claims.

```<code>/// <summary>
    /// Gets the token passed in Header
    /// </summary>
    /// <returns>Access Token</returns>
    public string GetAccessToken()
    {

        if (_httpContextAccessor != null && _httpContextAccessor.HttpContext != null)
        {
            return _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
        }

        if (!string.IsNullOrEmpty(AccessToken))
        {
            return AccessToken;
        }

        return string.Empty;
    }
</code>```

To get the connectionString for the Tenant

```<code>/// <summary>
    /// Get Tenant's connection string
    /// </summary>
    /// <returns></returns>
    public string GetTenantConnectionString()
    {
        var customerDomain_Name = GetCustomerDomain();
        var keyName = customerDomain_Name + ":DataContext";
        var connectionString = _configuration.GetValue<string>(keyName);
        return connectionString;
    }
</code>```

I tried faking using "https://stackoverflow.com/questions/47404479/add-httpcontext-into-hangfire" and other Unit test ways but nothing seem to work and defining HttpContext in .NET  Core has been changed and I can not create HttpContext manually and need to be injected via IHttpContextAccessor.

Do you see any ways this can be achieved?

Body:
I have multi-tenant Web API application built using ASP.NET Core 6. We are using HangFire for Report Scheduling.
It uses Onion based Architecture where Interface lies in the application and implementation
outside the layer

Project has application Layer and Integration Layer , so IDbContext will be present in app layer and implementation class DbContext lies in Integration Layer, so I can not create dbContext instance directly from app layer as it is not accessible.

As it is web API , we use jwt token and this token is passed as part of "Http Request Header" for every other request for user to authorize.

As background jobs run , this HttpContext will be null which ends up giving error for all services as most of the DI services use this to get the values like connection String for DbContext, logged in user, URL to third party services as all are stored as part of that HttpHeader.

 public jmasdbContext(DbContextOptions<jmasdbContext> options, ITenantProviderService tnt, IJwtAuthenticationManager jwt, IWebHostEnvironment env)
        : base(options)
    {
        //Check if is developement is added for migration purpose.- THIS IF CONDITION CAN BE REMOVED WHILE DEPLOYING TO PRODUCTION
        if (!env.EnvironmentName.Equals("Development"))
        {
            //This if part will be executed only during Login creation as Claims will not be set at this time,
            //we need to fetch ConnectionString from Tenant...
            if (tnt != null && tnt.HasTenantSet())
            {
                ConnectionString = tnt.Tenant.ConnectionString;
            }
            else if (jwt != null && !string.IsNullOrEmpty(jwt.GetAccessToken()))
            {
                ConnectionString = jwt.GetTenantConnectionString();
            }
        }
    }

Here is how the connectionString is Set. First part gets executed during setting the tenant (login) and else part for every subsequent request

The code jwt.GetAccessToken() is dependent on httpContext and jwt.GetTenantConnectionString() is dependent on the jwt.GetAccessToken as it is stored as part of token claims.

///
    /// Gets the token passed in Header
    ///
    /// <returns>Access Token</returns>
    public string GetAccessToken()
    {

        if (_httpContextAccessor != null && _httpContextAccessor.HttpContext != null)
        {
            return _httpContextAccessor.HttpContext.Request.Headers["Authorization"];
        }

        if (!string.IsNullOrEmpty(AccessToken))
        {
            return AccessToken;
        }

        return string.Empty;
    }

To get the connectionString for the Tenant

///
    /// Get Tenant's connection string
    ///
    /// <returns></returns>
    public string GetTenantConnectionString()
    {
        var customerDomain_Name = GetCustomerDomain();
        var keyName = customerDomain_Name + ":DataContext";
        var connectionString = _configuration.GetValue<string>(keyName);
        return connectionString;
    }

I tried faking using "https://stackoverflow.com/questions/47404479/add-httpcontext-into-hangfire" and other Unit test ways but nothing seem to work and defining HttpContext in .NET  Core has been changed and I can not create HttpContext manually and need to be injected via IHttpContextAccessor.

Do you see any ways this can be achieved?