问:
How to get Cryptocurrency Candlestick Market Data from Binance in R?
I had been trying to get cryptocurrency market data for some time, and the truth is that it took me a long time to find a way to import them in a clear way in R.

After researching, I think I found a fairly easy way to do it for those of us who use this language and would like to share it. thus, the next person with the same problem won't have to deal with as much.
I also think it would be good if others share their way of doing it, if there is an easier or faster way it would help to us who use R.

For this task we have to use Binance API, see the documentation and how to obtain other market data here.

答:
To GET the candlestick data we can use the function fromJSON from the package RJSONIO.

suppose that we want to see the pair BTC/USDT in intervals of 1 hour, the maximum amount of observations that we can adquire in one request is 1000, so we do:

Candlestick.data <- fromJSON("https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=1000")

seeing the data with View(Candlestick.data) we can se that is a list of lists, where each sublist contain all the candlestick data corresponding to 1-hour interval (close price, highest price, volume, number of trades, etc.).

To change the lists into a dataframe we could do:

```<code>i <- 1:length(Candlestick.data)
df <- sapply(i, function(i){as.numeric(unlist(Candlestick.data[i]))})
</code>```

By doing this, each column of df corresponds to the period (1-hour ago, 2-hours ago, and so on) and each row to the different candlestick data. So let's say we want to see all the close prices of the last 1000 hours, as we can see in the documentation , this is the 5th element of each list, so we can do this by df[5,].

If we want the rows to be the periods and the columns to be the candlestick data, we can transpose the matrix with t() like this
df_t <- t(df) and now to get the close prices df_t[,5].

Finally, to make the request easier, we can use the function paste0() and now, in summary, we could do for example:

```<code>library(RJSONIO)

crypto_A <- "ETH"       # the spot market crypto_A vs crypto_B must exist in Binance
crypto_B <- "BTC"
interval <- "15m"       # see all the possible intervals in the documentation
observations <- "1000"  # remember that the maximum is 1000

Candlestick.data <- fromJSON(paste0("https://api.binance.com/api/v3/klines?symbol=",crypto_A,crypto_B,"&interval=",interval,"&limit=",observations))

i <- 1:length(Candlestick.data)
df <- sapply(i, function(i){as.numeric(unlist(Candlestick.data[i]))})

df_t <- t(df)
</code>```

Hope this can help  and remember to read the documentation for more details.

Body:
To GET the candlestick data we can use the function fromJSON from the package RJSONIO.

suppose that we want to see the pair BTC/USDT in intervals of 1 hour, the maximum amount of observations that we can adquire in one request is 1000, so we do:

Candlestick.data <- fromJSON("https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&limit=1000")

seeing the data with View(Candlestick.data) we can se that is a list of lists, where each sublist contain all the candlestick data corresponding to 1-hour interval (close price, highest price, volume, number of trades, etc.).

To change the lists into a dataframe we could do:

i <- 1:length(Candlestick.data)
df <- sapply(i, function(i){as.numeric(unlist(Candlestick.data[i]))})

By doing this, each column of df corresponds to the period (1-hour ago, 2-hours ago, and so on) and each row to the different candlestick data. So let's say we want to see all the close prices of the last 1000 hours, as we can see in the documentation , this is the 5th element of each list, so we can do this by df[5,].

If we want the rows to be the periods and the columns to be the candlestick data, we can transpose the matrix with t() like this
df_t <- t(df) and now to get the close prices df_t[,5].

Finally, to make the request easier, we can use the function paste0() and now, in summary, we could do for example:

library(RJSONIO)

crypto_A <- "ETH"       # the spot market crypto_A vs crypto_B must exist in Binance
crypto_B <- "BTC"
interval <- "15m"       # see all the possible intervals in the documentation
observations <- "1000"  # remember that the maximum is 1000

Candlestick.data <- fromJSON(paste0("https://api.binance.com/api/v3/klines?symbol=",crypto_A,crypto_B,"&interval=",interval,"&limit=",observations))

i <- 1:length(Candlestick.data)
df <- sapply(i, function(i){as.numeric(unlist(Candlestick.data[i]))})

df_t <- t(df)

Hope this can help  and remember to read the documentation for more details.


来源: stackexchange

问:
Constraint for curriculum to be met with Optapy - School timetabling optimization
I am using Optapy library in python and I want to add constraint that the curriculum needs to be met, since I get for now many unassigned lessons even though most of the timeslots and rooms are empty and the teacher resources are mostly unused.
I tried to add the following constraint:

```<code>def curriculum_needs_to_be_met(constraint_factory):
return constraint_factory \
    .forEach(LessonClass) \
    .filter(lambda lesson: lesson.timeslot is None) \
    .penalize("Curriculum needs to be met", HardSoftScore.ONE_HARD)
</code>```

But still I get many unassigned lessons. Any idea how can I define the curriculum constraint?

答:
All variables should be assigned without a constraint. The only reason why they would be unassigned is either:

You are checking the input problem (where all the lessons are unassigned) instead of the solution returned from solver.solve (where all the lessons should be assigned, unless the solver terminated before it found a feasible solution (in which case, the solver should be given more time)).

You passed nullable=True to @planning_variable (i.e. the domain looks like this):

```<code> @planning_entity
 class Lesson:
     def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
         self.id = id
         self.subject = subject
         self.teacher = teacher
         self.student_group = student_group
         self.timeslot = timeslot
         self.room = room

     @planning_id
     def get_id(self):
         return self.id

     @planning_variable(Timeslot, ["timeslotRange"], nullable=True)
     def get_timeslot(self):
         return self.timeslot

     def set_timeslot(self, new_timeslot):
         self.timeslot = new_timeslot

     # ...
</code>```

which you do if you want to allow the variable to take a None value. However, this is probably not the case, since you don't want the variable to take a None value.

Thus, I would double check you are using the solution instead of the problem. If you are using the solution and still see unassigned values, then I would update its TerminationConfiguration to give it more time. See the OptaPlanner docs for example termination configurations: https://www.optaplanner.org/docs/optaplanner/latest/optimization-algorithms/optimization-algorithms.html#termination ; You can create a new termination configuration in OptaPy like this:

```<code>import optapy.config
termination = optapy.config.solver.termination.TerminationConfig()
termination.setBestScoreFeasible(True) # keep solving until the solution feasible
solver_config = optapy.config.solver.SolverConfig() \
    .withTerminationConfig(termination) \
# rest of SolverConfig setup
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using Optapy library in python and I want to add constraint that the curriculum needs to be met, since I get for now many unassigned lessons even though most of the timeslots and rooms are empty and the teacher resources are mostly unused.
I tried to add the following constraint:

def curriculum_needs_to_be_met(constraint_factory):
return constraint_factory \
    .forEach(LessonClass) \
    .filter(lambda lesson: lesson.timeslot is None) \
    .penalize("Curriculum needs to be met", HardSoftScore.ONE_HARD)

But still I get many unassigned lessons. Any idea how can I define the curriculum constraint?

Body:
All variables should be assigned without a constraint. The only reason why they would be unassigned is either:

You are checking the input problem (where all the lessons are unassigned) instead of the solution returned from solver.solve (where all the lessons should be assigned, unless the solver terminated before it found a feasible solution (in which case, the solver should be given more time)).

You passed nullable=True to @planning_variable (i.e. the domain looks like this):

 @planning_entity
 class Lesson:
     def __init__(self, id, subject, teacher, student_group, timeslot=None, room=None):
         self.id = id
         self.subject = subject
         self.teacher = teacher
         self.student_group = student_group
         self.timeslot = timeslot
         self.room = room

     @planning_id
     def get_id(self):
         return self.id

     @planning_variable(Timeslot, ["timeslotRange"], nullable=True)
     def get_timeslot(self):
         return self.timeslot

     def set_timeslot(self, new_timeslot):
         self.timeslot = new_timeslot

     # ...

which you do if you want to allow the variable to take a None value. However, this is probably not the case, since you don't want the variable to take a None value.

Thus, I would double check you are using the solution instead of the problem. If you are using the solution and still see unassigned values, then I would update its TerminationConfiguration to give it more time. See the OptaPlanner docs for example termination configurations: https://www.optaplanner.org/docs/optaplanner/latest/optimization-algorithms/optimization-algorithms.html#termination ; You can create a new termination configuration in OptaPy like this:

import optapy.config
termination = optapy.config.solver.termination.TerminationConfig()
termination.setBestScoreFeasible(True) # keep solving until the solution feasible
solver_config = optapy.config.solver.SolverConfig() \
    .withTerminationConfig(termination) \
# rest of SolverConfig setup


问:
Pandas groupby with "Wide" data
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

```<code>import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444
</code>```

I have a similar dataframe that places each data point in one of two groups (1 or 2):

```<code>grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2
</code>```

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

```<code>avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))
</code>```
```<code>                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

答:
I wanted to understand @piterbarg's answer, so I reformatted it.  I'm sharing that here, in case it's helpful for anyone else.</p>
```<code>stacked_cost = (
    cost
    .rename_axis('date')
    .stack()
    .to_frame(name='cost')
)

stacked_grp = (
    grp
    .rename_axis('date')
    .stack()
    .to_frame(name='group')
)

avg = (
    stacked_cost
    .join(stacked_grp)
    .reset_index()
    .groupby(['date','group'])
    .mean()
    .unstack()
)

print(avg)
</code>```
```<code>             cost
group           1      2
date
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5
</code>```

Title: Pandas groupby with "Wide" data

Body:
My dataframes are in a "wide" format, such that columns contain data for different entities, and rows are dates, e.g. product costs through time:

import pandas as pd

cost = pd.DataFrame([[10,20,30,40],[11,22,33,44],[111,222,333,444]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01     10    20     30       40
2022-01-02     11    22     33       44
2022-01-03    111   222    333      444

I have a similar dataframe that places each data point in one of two groups (1 or 2):

grp = pd.DataFrame([[1,2,1,2],[1,1,2,2],[2,1,1,2]], columns=['Knife','Fork','Spoon','Spatula'], index=pd.date_range('2022-01-01','2022-01-03'))

            Knife  Fork  Spoon  Spatula
2022-01-01      1     2      1        2
2022-01-02      1     1      2        2
2022-01-03      2     1      1        2

I want to do an aggregate groupby-style mean on each of the groups for each date. As such, this is my desired output, showing the averages for groups 1 and 2:

avg =  pd.DataFrame([[(10+30)/2,(20+40)/2],[(11+22)/2,(33+44)/2],[(111+444)/2,(222+333)/2]], columns=[1,2], index=pd.date_range('2022-01-01','2022-01-03'))

                1      2
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5

I've tried to melt each dataframe, reindex, merge, groupby, aggregate and pivot but it's a real mess (esp the reindexing).

It seems to me there must be a better way to aggregate this kind of "wide" data? My actual data is way bigger (and with more groups), hence a desire for efficiency.

How can I most efficiently gain my desired output?

Body:
I wanted to understand @piterbarg's answer, so I reformatted it.  I'm sharing that here, in case it's helpful for anyone else.

stacked_cost = (
    cost
    .rename_axis('date')
    .stack()
    .to_frame(name='cost')
)

stacked_grp = (
    grp
    .rename_axis('date')
    .stack()
    .to_frame(name='group')
)

avg = (
    stacked_cost
    .join(stacked_grp)
    .reset_index()
    .groupby(['date','group'])
    .mean()
    .unstack()
)

print(avg)

             cost
group           1      2
date
2022-01-01   20.0   30.0
2022-01-02   16.5   38.5
2022-01-03  277.5  277.5


问:
"No numeric types to aggregate" while using Pandas expanding()
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

```<code>tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue
</code>```

This works:

```<code>tmp.groupby('col1').agg(lambda x: ','.join(x))
</code>```

And this works:

```<code>tmp.groupby('col1').expanding().agg('count')
</code>```

But this returns an error:

```<code>tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))
</code>```

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

答:
A third option I have found:

```<code>tmp['col3'] = tmp.groupby('col1')['col2'].transform(lambda x: [';'.join(x[:i+1]) for i in range(len(x))])
</code>```

Putting this out there in case it is useful to anyone; however, both the options by @enke and @Corralien are superior.

Tested on a large dataset, the times were:

```<code>accumulate: 0:13
apply: 0:25
for loop:  2:28
</code>```

Since the accumulate option was faster and more intuitive, I am marking that as the accepted answer, although the other is very nice for being a one liner with no imports.

Body:
In Pandas 1.1.4, I am receiving a DataError: No numeric types to aggregate when using an ExpandingGroupby.

Example dataset:

tmp = pd.DataFrame({'col1':['a','b','b','c','d','d'], 'col2': ['red','red','green','green','red','blue']})

print(tmp)

col1    col2
a       red
b       red
b       green
c       green
d       red
d       blue

This works:

tmp.groupby('col1').agg(lambda x: ','.join(x))

And this works:

tmp.groupby('col1').expanding().agg('count')

But this returns an error:

tmp.groupby('col1').expanding().agg(lambda x: ','.join(x))

DataError: No numeric types to aggregate

There is no conceptual reason this shouldn't work, and there are several references online to people using custom functions within an ExpandingGroupby.

There is obviously no reason that this should need to be a numeric, especially given that the count works with the non-numeric column.  What is happening here?  If this can't be done natively for whatever reason, how can I do it manually?

Body:
A third option I have found:

tmp['col3'] = tmp.groupby('col1')['col2'].transform(lambda x: [';'.join(x[:i+1]) for i in range(len(x))])

Putting this out there in case it is useful to anyone; however, both the options by @enke and @Corralien are superior.

Tested on a large dataset, the times were:

accumulate: 0:13
apply: 0:25
for loop:  2:28

Since the accumulate option was faster and more intuitive, I am marking that as the accepted answer, although the other is very nice for being a one liner with no imports.


问:
Running Puppeteer with headless: false & Firebase Functions
I'm trying to use Puppeteer + Firebase Functions while using the headless: false option

```<code>await puppeteer.launch({
        headless: false
    });
</code>```

It works well locally. I use the headless: false so it won't trigger a bot check, which work well.

When I deploy it to Firebase Functions it doesn't seem to be able to launch a browser:

Error: Failed to launch the browser process!

[15:32:0209/162803.759118:ERROR:file_path_watcher_linux.cc(78)] Failed to read /proc/sys/fs/inotify/max_user_watches

[15:15:0209/162804.834741:ERROR:ozone_platform_x11.cc(234)] Missing X server or $DISPLAY

[15:15:0209/162804.834794:ERROR:env.cc(225)] The platform failed to initialize. Exiting.

Is there some sort of a solution to run it as a Firebase Function?

答:
I’ll start with the cases that combined Cloud functions and Puppeteer. Here is an old question that discusses the same log error. I think this is the first place to look for a solution, as it provides links to a couple of Github Issues reporting similar error logs. In this other Github issue, a user recommended code to start Puppeteer in Cloud functions. This example can help you as well.

I’ll leave these two guides that can walk you through. This old medium article and this more updated version from logrocket.

Other question has several workarounds; unfortunately, none of them include Cloud Functions, just in case this is caused purely by Puppeteer. And here is how to run Headful Mode.

However, if you want to avoid being detected by the bot, there is also a discussion about this that could give you some hints.

There is no exact solution for this, as it seems there are several causes and workarounds. I would advise you to open a new question once you have tried some alternatives already provided by the community, and see if there's a more specific solution.

Body:
I'm trying to use Puppeteer + Firebase Functions while using the headless: false option

await puppeteer.launch({
        headless: false
    });

It works well locally. I use the headless: false so it won't trigger a bot check, which work well.

When I deploy it to Firebase Functions it doesn't seem to be able to launch a browser:

Error: Failed to launch the browser process!

[15:32:0209/162803.759118:ERROR:file_path_watcher_linux.cc(78)] Failed to read /proc/sys/fs/inotify/max_user_watches

[15:15:0209/162804.834741:ERROR:ozone_platform_x11.cc(234)] Missing X server or $DISPLAY

[15:15:0209/162804.834794:ERROR:env.cc(225)] The platform failed to initialize. Exiting.

Is there some sort of a solution to run it as a Firebase Function?


问:
CSS button hover effects not working with id's
I do not have any inline styling. I am sorry for any inconvenience as I am a self-learner and this is my first question.

Many thanks for your support.

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit a:hover {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>

    <input type="submit" id="submit" value="Get Started"></code>```

答:
I think this should be it..

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit:hover {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form" action="https://www.freecodecamp.org/email-submit">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>
  <input type="submit" id="submit" value="Get Started">
</form></code>```

Body:
I do not have any inline styling. I am sorry for any inconvenience as I am a self-learner and this is my first question.

Many thanks for your support.

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit a:hover {
  background-color: red;
}

<form id="form">

  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" />

    <input type="submit" id="submit" value="Get Started">

Body:
I think this should be it..

#submit {
  background-color: yellow;
  font-weight: bold;
  font-size: 15px;
  border-width: medium;
}

#submit:hover {
  background-color: red;
}

<form id="form" action="https://www.freecodecamp.org/email-submit">
  <label for="email" id="email-label"></label><br>
  <input id="email" type="email" required name="Form-elements" placeholder="Enter your Email Address" /><br><br>
  <input type="submit" id="submit" value="Get Started">
</form>


答:
How about split the string with white space first, then split each of the splited items with comma like following algorithm?</p>

```<code>threeItems = split main string with white space
for each itemString in threeItems
  threeItem = split itemString with comma
  do something with threeItem
end for
</code>```

ContentLicense: CC BY-SA 3.0

Title: Content from a string into a array

Body:
I have a string that needs to be put sorted(not in the high to low way), the string is set to separate each number with a comma and after every third number a space:

26,2496,1492252306 1049,99,68353132 860,99,59587920 4717,99,43863427 807,99,67243688 1382,99,37865117 1088,99,14810482 95,99,67711274 5,99,200000000 3310,99,25639438 75,99,157217334 1923,99,29678736 48,99,118806349 133,99,35055345 563,99,21098356 3410,99,17805574 47,99,62821143 2504,99,14821240 5,99,200000000 3076,99,19425499 474,99,31321799 3983,99,16825678 17826,99,13768252 1129,99,17249030 5393,99,14082021 338,120,137201472 2850,1944 -1,-1 -1,-1 -1,-1 -1,-1 4509,3988 3863,3987 2632,4148 5790,4105 -1,-1 -1,-1

i need to create some sort of association for each of the 3 numbers. kinda like a something along the lines of 2d array and a dictionary. any suggestion?

Body:
How about split the string with white space first, then split each of the splited items with comma like following algorithm?

threeItems = split main string with white space
for each itemString in threeItems
  threeItem = split itemString with comma
  do something with threeItem
end for


问:
javascript sum values from two different functions
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

```<code>      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }
</code>```

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

```<code>function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

</code>```

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

```<code>      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }
</code>```

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

```<code>function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }
</code>```

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

答:
You could try to use the "Number" method to convert the variables to numbers:

function combinedTotal(){
        var addTogether = Number(showHourlyRate()) + Number(showMileageRate());
        alert(addTogether);
        return addTogether;
      }```

The Nan message seems to pop up when the number is not a legal number, reference this.

Body:
I'm trying to create a calculator, I've managed to get the values from a google Sheets doc when I console.log from within the function. I'm now trying to combine those figures to get a total price. I'm getting a NAN error.

I'm new to Javascript so I could be missing something simple but I have tried and tried and I can't figure it out.

I simply want to add the hourly rate and the mileage together to get 25.00 and then convert it to a UK currency.

      function showHourlyRate(qty) {
        var oneFunc = qty
        console.log(oneFunc) //result is 5.00
        return oneFunc
      };

      function showMileageRate(qty) {
        var twoFunc = qty
        console.log(twoFunc) //result is 20.00
        return twoFunc
      };

      function combinedTotal(){
        var addTogether = showHourlyRate() + showMileageRate();
        alert(addTogether); // gives NAN
        return addTogether;
      }

UPDATE:

Excuse me if my terminology is not correct.

I've updated my question as the answers still didn't work for me which make me think I've done something early on so...

This is a google apps script.

I have a functions.gs, within this file I get the spreadsheet and sheet needed. I then get the range of columns and filter the results to match my word. Once it finds a match, get the next column which has a price. I then return that.

Here's that part: (I've only added the hourly rate one as the mileage one is the same but with the names changed)

function getHourlyRate() {
  const sheet = SpreadsheetApp.openById("17iaOdOS9N09tFb38w4P9GC8furzy33sXVnQK8dIhPnI").getSheetByName("Working Hours");
  const data = sheet.getRange(2, 1, sheet.getLastRow()-1, 8).getValues();
  const filteredData = data.filter(r => r[0] === "Sundries");

  return filteredData.length === 0 ? "No Match" : filteredData.reduce((subtotal, r) => subtotal + r[1], 0).toFixed(2);

}

My next file is the index.html. I first load the function on initial load, I then get the hourly rate using the function afterSidebar Loads which then uses the showHourlyRate function.

Thats how I get my 20.00 or 5.00 figure

here's the html file:

      var arrayOfArrays;

      function afterSidebarLoads() {
        google.script.run.withSuccessHandler(showHourlyRate).getHourlyRate();
        google.script.run.withSuccessHandler(showMileageRate).getMileageRate();

      document.addEventListener("DOMContentLoaded", afterSidebarLoads);

      }

      function showHourlyRate(qty) {
        var oneFunc = hourlyRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(oneFunc) //result is 0.55
        return oneFunc
      };

      function showMileageRate(mileageRate) {
        var twoFunc = mileageRate
        // var ghjJhg = oneFunc.toFixed(2)
        // console.log(twoFunc) //result is 22.64
        return twoFunc
      };

      function combinedTotal(){
      }

I hope this makes more sense and thank you all for answering.

UPDATE 2:

So it turns out that the following code works in the functions.gs file but not in the index.html file

function combinedTotal(){
        var addTogether = Number(getHourlyRate()) + Number(getMileageRate());
        console.log(addTogether);
        return addTogether;
      }

I changed the functions names to match the ones in the functions.gs file.

What am I not understanding?

Body:
You could try to use the "Number" method to convert the variables to numbers:

function combinedTotal(){
        var addTogether = Number(showHourlyRate()) + Number(showMileageRate());
        alert(addTogether);
        return addTogether;
      }

The Nan message seems to pop up when the number is not a legal number, reference this.


问:
how can I change chips color in Primeng?
I want to change color chips in primeng,that whenever I select one I get a diffrent color!, can anyone help me how to do that!

my code :

```<code> <p-multiSelect [options]="cars" [(ngModel)]="selectedCars1"  [selectionLimit]=3 [panelStyle]="{minWidth:'12em'}"
                         [maxSelectedLabels]=2></p-multiSelect>
          <p>Selected Cars: </p>
          <p-chips [(ngModel)]="selectedCars1" ></p-chips>
</code>```

答:
Maybe I'm a bit late but I achieve it in the following way and add a Border-Radius</p>
```<code><p-chip [ngStyle]="{'background': '#EF5350','border-radius': '15px' }"></p-chip>
</code>```

Body:
I want to change color chips in primeng,that whenever I select one I get a diffrent color!, can anyone help me how to do that!

my code :

Selected Cars:

Body:
Maybe I'm a bit late but I achieve it in the following way and add a Border-Radius

<p-chip [ngStyle]="{'background': '#EF5350','border-radius': '15px' }"></p-chip>


问:
SINR and Signal power Pr[dBm] calculations in Veins simulations
I need help in the following,
Question-1: In veins simulations, how the SINR of a signal is calculated and where its implemented in the code?
Question-2: In veins simulations, how the Pr[dBm] of a signal is calculated and where its implemented in the code? Is it the receiver's antenna where the signal is first received?
Question-3: Where in the code i can find the decision making process of accepting or rejecting the signal when the signal is received with a certain power that is below of above some threshold? How can we set the threshold/sensitivity level?

thanks in advance,

Best regards,
/MM

答:
If you think for a moment about how a physical system behaves, you might end up understanding the folders structure of Veins. A signal arrives at an antenna, if it's too weak (less than sensitivity), it's withdrawn a priori, otherwise it's going to a decoder and there you might have some errors in proportion to the SINR you got.

Statistics are generated in Mac1609_4.cc

I'm a bit unsure on this, you'll be able to find yourself after reading this.

Decision making? Decider80211p.cc (how cool is that?!)

To look after source files, in Omnet++ you could use Ctrl+left click to find in which files something is defined/declared. I'm still studying myself so please verify this information. Let me know in the comments the answer to number 2.


问:
Error building : fatal error: pcre.h: No such file or directory
I'm just finished installing Ubuntu 13.10.

I want try Phalcon, and when I build the source (phalcon.so), I have this error :

```<code>     from /home/fabrice/Downloads/cphalcon/build/32bits/phalcon.c:204:
/usr/include/php5/ext/pcre/php_pcre.h:29:18: fatal error: pcre.h: No such file or directory
 #include "pcre.h"
                  ^
compilation terminated.
make: *** [phalcon.lo] Erreur 1
</code>```

My installation of lamp is :

sudo apt-get install -y apache2 php5 mysql-server libapache2-mod-php5
  php5-mysql  php5-curl php5-imagick  php5-mcrypt php5-memcache
  php5-sqlite php5-xdebug php-apc php5-intl  php-mongo php5-dev gcc

Can anybody help me ?

答:
For MacOS monterey amd64 (darwin), it is necessary to create a symlink.

First, locate where the pcre.h was installed by Brew:

$ brew list pcre | grep 'pcre\.h$'

/opt/homebrew/Cellar/pcre/8.45/include/pcre.h
```
<p>Then, gets the directory that GCC is looking for header (.h) files:</p>
<pre class="lang-sh prettyprint-override"><code>$ cpp -v

...
#include <...> search starts here:
 /Library/Developer/CommandLineTools/usr/lib/clang/13.0.0/include
 /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include
 /Library/Developer/CommandLineTools/usr/include   # <---- we are going to use this one
 /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)
</code>```

Finally, create a symlink to the pcre.h file, so that GCC will find it in  its search path:

ln -s /opt/homebrew/Cellar/pcre/8.45/include/pcre.h \
      /Library/Developer/CommandLineTools/usr/include/pcre.h
```
<p>To test if it worked, we can use the following C code:</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <pcre.h>
int main() {
   printf("lala popo");
   return 0;
}
</code>```

And run:

gcc test.c -o test
```

Body:
I'm just finished installing Ubuntu 13.10.

I want try Phalcon, and when I build the source (phalcon.so), I have this error :

     from /home/fabrice/Downloads/cphalcon/build/32bits/phalcon.c:204:
/usr/include/php5/ext/pcre/php_pcre.h:29:18: fatal error: pcre.h: No such file or directory
 #include "pcre.h"
                  ^
compilation terminated.
make: *** [phalcon.lo] Erreur 1

My installation of lamp is :

sudo apt-get install -y apache2 php5 mysql-server libapache2-mod-php5
  php5-mysql  php5-curl php5-imagick  php5-mcrypt php5-memcache
  php5-sqlite php5-xdebug php-apc php5-intl  php-mongo php5-dev gcc

Can anybody help me ?

Body:
For MacOS monterey amd64 (darwin), it is necessary to create a symlink.

First, locate where the pcre.h was installed by Brew:

$ brew list pcre | grep 'pcre\.h$'

/opt/homebrew/Cellar/pcre/8.45/include/pcre.h

Then, gets the directory that GCC is looking for header (.h) files:

$ cpp -v

...
#include <...> search starts here:
 /Library/Developer/CommandLineTools/usr/lib/clang/13.0.0/include
 /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include
 /Library/Developer/CommandLineTools/usr/include   # <---- we are going to use this one
 /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks (framework directory)

Finally, create a symlink to the pcre.h file, so that GCC will find it in  its search path:

ln -s /opt/homebrew/Cellar/pcre/8.45/include/pcre.h \
      /Library/Developer/CommandLineTools/usr/include/pcre.h

To test if it worked, we can use the following C code:

#include <stdio.h>
#include <pcre.h>
int main() {
   printf("lala popo");
   return 0;
}

And run:

gcc test.c -o test


问:
How can I use progressive enhancement techniques to progressively load a slow page?
I've got a portal page in ASP.NET MVC with a few different sections (partial views), some of which will be unavoidably slow the first time a user accesses them, because they have to pull in up-to-date data from an external internet source.

Some of this data can be loaded almost immediately, but the old "Web 1.0" design just goes to a "loading" page until all of the data is available.  I'm trying to improve the user experience by immediately displaying the local data, and then using a couple of ajax updates to display the remote data a few seconds later.

Of course I want to do this using progressive enhancement in case the Javascript breaks, gets blocked, or isn't supported for whatever reason. My first thought was to use a meta refresh and disable it with javascript, but apparently that's impossible. I'm also violently opposed to the idea of a window.location redirect, because (a) it's highly perceptible, unlike a server redirect, and (b) it's well within the realm of possibility for the JS redirect to work but the ajax to still break (think IE6, ill-behaved mobile devices, etc.)

Is there some way I can build up a page that loads in stages, but still works with plain HTML?

答: I suppose this depends on the nature of the data that you're pulling in, but "progressive enhancement" in this case might be serving the page without the external content to clients who don't have javascript available, then pulling in and inserting content using javascript where you can. Personally I'd be concerned (slightly) with the "no javascript available" case, but not concerned with the "javascript breaks" case, because error handling in your javascript can take care of the "ajax didn't work properly" scenario.


问:
When are functions assigned to a variable actually computed?
I'm doing some troubleshooting on a Lua function I wrote yesterday as part of a game development effort using the Love2D API.  The function is designed to handle mob entities stepping around an obstruction in a tile-based roguelike type system with PG terrain.  Code is below, though I'm not primarily looking for syntax help here, it's just for context.  The troubleshooting raised an interesting question in my mind that I couldn't find the answer to in Lua's documentation.

For the curious, this particular function checks "left" and "right" of an obstruction for any given direction in a set of 8 directions, sees whether the square in that direction contains walkable terrain, and then walks onto it if so.  If both directions are clear, it flips a coin.  If both are blocked, it gives up (for now, for testing purposes).

I'm defining this inside of a (confirmed working) Entity class, hence all the "self" sugar.  Move, canMove, and Wander are all also confirmed working methods of Entity.

```<code>ObstructionHandler = function(self, x_direction, y_direction)
    local direction = {
        x = x_direction,
        y = y_direction
    }
    local direction_list = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}}

    local check1 = nil
    local check2 = nil
    local move1 = nil
    local move2 = nil

    for i = 1, #direction_list do
        if direction.x == direction_list[i][1] and direction.y == direction_list[i][2] then
            if i == 1 then
                check1 = self:canMove(direction_list[#direction_list][1], direction_list[#direction_list][2])
                move1 = self:Move(direction_list[#direction_list][1], direction_list[#direction_list][2])
            else
                check1 = self:canMove(direction_list[i - 1][1], direction_list[i - 1][2])
                move1 = self:Move(direction_list[i - 1][1], direction_list[i - 1][2])
            end

            if i == #direction_list then
                check2 = self:canMove(direction_list[1][1], direction_list[1][2])
                move2 = self:Move(direction_list[1][1], direction_list[1][2])
            else
                check2 = self:canMove(direction_list[i + 1][1], direction_list[i + 1][2])
                move2 = self:Move(direction_list[i + 1][1], direction_list[i + 1][2])
            end
                if check1 and check2 then
                    if math.random(0,1) <= 0.5 then
                        move1
                    else -- this is where the error pops
                        move2
                    end
                elseif check1 then
                    move1
                elseif check2 then
                    move2
                else
                    self.boredom = self.boredom + 1
                    self:Wander()
                end
            end
    end
end
</code>```

The error I receive is that an equal sign is expected near "else".  I've seen these sorts of things pop up before when I call a function improperly, or when there's a failure to close a parenthesis somewhere, whatever.  After checking for that sort of thing, I tried moving the "self:" sugar from the declaration to the place where I actually call the functions, i.e.:

```<code>...
            if i == #direction_list then
                check2 = canMove(direction_list[1][1], direction_list[1][2])
                move2 = Move(direction_list[1][1], direction_list[1][2])
            else
                check2 = canMove(direction_list[i + 1][1], direction_list[i + 1][2])
                move2 = Move(direction_list[i + 1][1], direction_list[i + 1][2])
            end
                if self:check1 and self:check2 then -- this is where the error pops in this version
                    if math.random(0,1) <= 0.5 then
                        self:move1
                    else
                        self:move2
                    end
                elseif self:check1 then
                    self:move1
                elseif self:check2 then
                    self:move2
                else
                    self.boredom = self.boredom + 1
                    self:Wander()
                end
...
</code>```

What I found really interesting in doing this is that it changed the error.  When running it like this, Love returns the error "function arguments expected near 'and'".  I double-checked canMove and Move, and they are getting all the arguments they need, here.  However, this got me thinking: when is Lua (and/or Love) actually computing the results of a function when that function is assigned to a variable?

If I say something like a = f(x), is it running f(x) there and then, and assigning the output to a at that time?  Or does it wait until I later call on a to run f(x)?  Or is it both, like is it redoing that work if I start with a declaration and then later call on it?

If any intrepid souls want to help fix my code, that's awesome, but I'll figure that out myself in time; what I'm primarily interested in is this hair-splitting thing about assignation and computation, because now that it's on my mind, it's driving me nuts not knowing.

答:
move is not a valid Lua statement. You cannot just write an identifier on its own. You need to combine it with other things.

Adding self: doesn't change that. It merely replaces the local move1 by a table element. Still this is an invalid expression.

The only thing that changes is that Lua now expects arguments as the colon syntax is only used in combination with functions.

If move1 is a function value you can call

```<code>move1()
</code>```

or if it was a method of the table self you could call

```<code>self:move1()
</code>```

But just writing move1 is syntactically incorrect.
Same for move2.

If I say something like a = f(x), is it running f(x) there and then,
and assigning the output to a at that time? Or does it wait until I
later call on a to run f(x)? Or is it both, like is it redoing that
work if I start with a declaration and then later call on it?

Function calls happen at runtime. So does the function definition which is also just an assignment. Your program is executed line by line from top to bottom.

Body:
I'm doing some troubleshooting on a Lua function I wrote yesterday as part of a game development effort using the Love2D API.  The function is designed to handle mob entities stepping around an obstruction in a tile-based roguelike type system with PG terrain.  Code is below, though I'm not primarily looking for syntax help here, it's just for context.  The troubleshooting raised an interesting question in my mind that I couldn't find the answer to in Lua's documentation.

For the curious, this particular function checks "left" and "right" of an obstruction for any given direction in a set of 8 directions, sees whether the square in that direction contains walkable terrain, and then walks onto it if so.  If both directions are clear, it flips a coin.  If both are blocked, it gives up (for now, for testing purposes).

I'm defining this inside of a (confirmed working) Entity class, hence all the "self" sugar.  Move, canMove, and Wander are all also confirmed working methods of Entity.

ObstructionHandler = function(self, x_direction, y_direction)
    local direction = {
        x = x_direction,
        y = y_direction
    }
    local direction_list = {{0, -1}, {1, -1}, {1, 0}, {1, 1}, {0, 1}, {-1, 1}, {-1, 0}, {-1, -1}}

    local check1 = nil
    local check2 = nil
    local move1 = nil
    local move2 = nil

    for i = 1, #direction_list do
        if direction.x == direction_list[i][1] and direction.y == direction_list[i][2] then
            if i == 1 then
                check1 = self:canMove(direction_list[#direction_list][1], direction_list[#direction_list][2])
                move1 = self:Move(direction_list[#direction_list][1], direction_list[#direction_list][2])
            else
                check1 = self:canMove(direction_list[i - 1][1], direction_list[i - 1][2])
                move1 = self:Move(direction_list[i - 1][1], direction_list[i - 1][2])
            end

            if i == #direction_list then
                check2 = self:canMove(direction_list[1][1], direction_list[1][2])
                move2 = self:Move(direction_list[1][1], direction_list[1][2])
            else
                check2 = self:canMove(direction_list[i + 1][1], direction_list[i + 1][2])
                move2 = self:Move(direction_list[i + 1][1], direction_list[i + 1][2])
            end
                if check1 and check2 then
                    if math.random(0,1) <= 0.5 then
                        move1
                    else -- this is where the error pops
                        move2
                    end
                elseif check1 then
                    move1
                elseif check2 then
                    move2
                else
                    self.boredom = self.boredom + 1
                    self:Wander()
                end
            end
    end
end

The error I receive is that an equal sign is expected near "else".  I've seen these sorts of things pop up before when I call a function improperly, or when there's a failure to close a parenthesis somewhere, whatever.  After checking for that sort of thing, I tried moving the "self:" sugar from the declaration to the place where I actually call the functions, i.e.:

...
            if i == #direction_list then
                check2 = canMove(direction_list[1][1], direction_list[1][2])
                move2 = Move(direction_list[1][1], direction_list[1][2])
            else
                check2 = canMove(direction_list[i + 1][1], direction_list[i + 1][2])
                move2 = Move(direction_list[i + 1][1], direction_list[i + 1][2])
            end
                if self:check1 and self:check2 then -- this is where the error pops in this version
                    if math.random(0,1) <= 0.5 then
                        self:move1
                    else
                        self:move2
                    end
                elseif self:check1 then
                    self:move1
                elseif self:check2 then
                    self:move2
                else
                    self.boredom = self.boredom + 1
                    self:Wander()
                end
...

What I found really interesting in doing this is that it changed the error.  When running it like this, Love returns the error "function arguments expected near 'and'".  I double-checked canMove and Move, and they are getting all the arguments they need, here.  However, this got me thinking: when is Lua (and/or Love) actually computing the results of a function when that function is assigned to a variable?

If I say something like a = f(x), is it running f(x) there and then, and assigning the output to a at that time?  Or does it wait until I later call on a to run f(x)?  Or is it both, like is it redoing that work if I start with a declaration and then later call on it?

If any intrepid souls want to help fix my code, that's awesome, but I'll figure that out myself in time; what I'm primarily interested in is this hair-splitting thing about assignation and computation, because now that it's on my mind, it's driving me nuts not knowing.

Body:
move is not a valid Lua statement. You cannot just write an identifier on its own. You need to combine it with other things.

Adding self: doesn't change that. It merely replaces the local move1 by a table element. Still this is an invalid expression.

The only thing that changes is that Lua now expects arguments as the colon syntax is only used in combination with functions.

If move1 is a function value you can call

move1()

or if it was a method of the table self you could call

self:move1()

But just writing move1 is syntactically incorrect.
Same for move2.

If I say something like a = f(x), is it running f(x) there and then,
and assigning the output to a at that time? Or does it wait until I
later call on a to run f(x)? Or is it both, like is it redoing that
work if I start with a declaration and then later call on it?

Function calls happen at runtime. So does the function definition which is also just an assignment. Your program is executed line by line from top to bottom.


问:
Can I set "usedWithCloudKit" to false in core data contents
I'm trying to disable/ remove cloud kit in my project so that I can have ordered relationships in core data. From what I can tell, the only reference to cloudKit anywhere in my project is inside CoreDataDB.xcdatamodeld/My_Project.xcdatamodel/contents and these are the first two lines of the file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="19574" systemVersion="20G314" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithCloudKit="YES" userDefinedModelVersionIdentifier="">
...
```

line 2 has this snippet: usedWithCloudKit="YES"

Can I safely switch it to NO or is there another way I should go about removing cloud kit.

Extra notes:

Cloud Kit is not enabled in Signing and Capabilities

I'm not using NSPersistentCloudKitContainer

The original error I'm trying to solve is CloudKit Integration MyEntity.myCustomRelationship must not be ordered [8]

答: Check to see under "Configurations" if "Default" or any custom configurations you have in your Data Model file has "Used with CloudKit" checked. Should appear in the right panel when you select a configuration.

Body:
I'm trying to disable/ remove cloud kit in my project so that I can have ordered relationships in core data. From what I can tell, the only reference to cloudKit anywhere in my project is inside CoreDataDB.xcdatamodeld/My_Project.xcdatamodel/contents and these are the first two lines of the file:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="19574" systemVersion="20G314" minimumToolsVersion="Automatic" sourceLanguage="Swift" usedWithCloudKit="YES" userDefinedModelVersionIdentifier="">
...

line 2 has this snippet: usedWithCloudKit="YES"

Can I safely switch it to NO or is there another way I should go about removing cloud kit.

Extra notes:

Cloud Kit is not enabled in Signing and Capabilities

I'm not using NSPersistentCloudKitContainer

The original error I'm trying to solve is CloudKit Integration MyEntity.myCustomRelationship must not be ordered [8]


问:
How do I load a package from a package in a Lerna monorepo?
I have:

```<code>packages
 -models
   -package.json
   -....
 -server
   -src
     -index.ts
   -package.json
</code>```

In my packages/server/package.json, I have:

```<code>  "scripts": {
    "dev": "ts-node src/index.ts"
  },
  "dependencies": {
    "@myapp/models": "../models",
</code>```

In my packages/server/src/index.ts, I have:

```<code>import { sequelize } from '@myapp/models'
</code>```

In my packages/models/src/index.ts, I have:

```<code>export type UserAttributes = userAttr

export { sequelize } from './sequelize';

</code>```

but it gives me an error:

```<code>  Try `npm install @types/myapp__models` if it exists or add a new declaration (.d.ts) file containing `declare module '@myapp/models';`

 import { sequelize } from '@myapp/models'
</code>```

How do I get this to work properly?

答:
lerna bootstrap first then yarn add <package_name> works
Or
lerna bootstrap first, then add the package and the target version then run yarn.</p>

Body:
I have:

packages
 -models
   -package.json
   -....
 -server
   -src
     -index.ts
   -package.json

In my packages/server/package.json, I have:

  "scripts": {
    "dev": "ts-node src/index.ts"
  },
  "dependencies": {
    "@myapp/models": "../models",

In my packages/server/src/index.ts, I have:

import { sequelize } from '@myapp/models'

In my packages/models/src/index.ts, I have:

export type UserAttributes = userAttr

export { sequelize } from './sequelize';

but it gives me an error:

  Try `npm install @types/myapp__models` if it exists or add a new declaration (.d.ts) file containing `declare module '@myapp/models';`

 import { sequelize } from '@myapp/models'

How do I get this to work properly?


问:
Increment columns in laravel
Is there a way to increment more than one column in laravel?

Let's say:

```<code>DB::table('my_table')
->where('rowID', 1)
->increment('column1', 2)
->increment('column2', 10)
->increment('column3', 13)
->increment('column4', 5);
</code>```

But this results to:

Call to a member function increment() on integer

I just want to find an efficient way to do this using the given functions from laravel. Thanks. Any suggestions will do.

答:
just use this code

```<code>\App\Models\User::find(1)->increment('column1');  //id = 1
</code>```

or multi recorded

```<code>\App\Models\User::where('column1','>','100')->increment('column1');
</code>```

Title: Increment columns in laravel

Body:
Is there a way to increment more than one column in laravel?

Let's say:

DB::table('my_table')
->where('rowID', 1)
->increment('column1', 2)
->increment('column2', 10)
->increment('column3', 13)
->increment('column4', 5);

But this results to:

Call to a member function increment() on integer

I just want to find an efficient way to do this using the given functions from laravel. Thanks. Any suggestions will do.

Body:
just use this code

\App\Models\User::find(1)->increment('column1');  //id = 1

or multi recorded

\App\Models\User::where('column1','>','100')->increment('column1');


问:
Apache Beam Pipeline - Serialization problem
My Beam pipeline seems to work properly, but produces a lot of warnings:

```<code>[direct-runner-worker] WARN org.apache.beam.sdk.util.MutationDetectors - Coder of type class org.apache.beam.sdk.coders.SerializableCoder has a #structuralValue method which does not return true when the encoding of the elements is equal. Element com.emarsys.dataflow.templates.MetricBundle@73d85187

</code>```

The class looks like this:

```<code>@AllArgsConstructor
@Data
public class MetricBundle implements Serializable {
    private Long customerId;
    private String query;
    private Map<PrimaryKey, Metric> metrics;
}
</code>```

The problem is with the Map. PrimaryKey and Metric classes are composed of simple types, and implement the Serializable interface.

The transform producing the PCollection<MetricBundle> is using .setCoder(SerializableCoder.of(MetricBundle.class));

Do I have to implement a custom coder in order to serialize Map properly?
During testing, I found no conflicts in the result, all elements are handled properly.

答: This is warning that due to the use of SerializableCoder it's not able to check certain properties of your pipeline. (SerializableCoder is also very inefficient.) I would recommend using a more specific coder here, but you don't have to necessarily write one of your own. E.g. it looks like you could decorate your class with @DefaultSchema(JavaFieldSchema.class). See https://beam.apache.org/documentation/programming-guide/#schemas

Body:
My Beam pipeline seems to work properly, but produces a lot of warnings:

[direct-runner-worker] WARN org.apache.beam.sdk.util.MutationDetectors - Coder of type class org.apache.beam.sdk.coders.SerializableCoder has a #structuralValue method which does not return true when the encoding of the elements is equal. Element com.emarsys.dataflow.templates.MetricBundle@73d85187

The class looks like this:

@AllArgsConstructor
@Data
public class MetricBundle implements Serializable {
    private Long customerId;
    private String query;
    private Map<PrimaryKey, Metric> metrics;
}

The problem is with the Map. PrimaryKey and Metric classes are composed of simple types, and implement the Serializable interface.

The transform producing the PCollection<MetricBundle> is using .setCoder(SerializableCoder.of(MetricBundle.class));

Do I have to implement a custom coder in order to serialize Map properly?
During testing, I found no conflicts in the result, all elements are handled properly.


问:
Intellij Idea problem with text file impossible to read
I have a problem using Intellij Idea.

I am absolutely unable to load text file as InputStream - it doesnt matter where do I put the file (main/java, main/resources...) it just can't find the file - in Eclipse everything works just fine.

I tried setings->compiler->resource patterns and added ?*.txt but that doesn't seem to work either.

Any help is appreciated.

答:
If you open the Project Structure dialog, and click on Modules and select your module - are the correct folders marked as Source Folders on the sources tab?

Link for how to get to Project Structure dialog

Also, if you print out the absolute path of that file you are trying to read, is that anywhere near where you expect it to be?


问:
Find duplicated value with different time index
I'm new to pandas and would like to check if there are more efficient way to do what I would like to achieve.

I have a customer master data change log for 12 months looks like below (the full file have 150K rows and 15 columns)

date1
changed_by
customer
field_name

23/02/2021 18:59
101852
40001375
Industry

23/02/2021 18:59
101852
40001375
Industry code 1

23/02/2021 18:59
101852
40001375
Region

30/12/2021 02:31
119186
30045194
Postal Code

30/12/2021 02:31
119186
30045194
Industry code 1

30/12/2021 02:31
119186
30045194
Region

30/01/2021 03:31
109209
40001375
Postal Code

30/01/2021 03:31
109209
40001375
Industry code 1

30/01/2021 03:31
109209
40001375
Bank

I would like to check if there are any customers' data being change more than once within the period, i.e. same customer ID but different date, then extract those line for further analysis.

Below are the code I currently have and seems work ok.

```<code>pvz = df3.groupby(['date1','customer'])['field_name'].count().reset_index()
pvz
</code>```

Gives me

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

30/12/2021 02:31
30045194
3

Then I:

```<code>pvz[pvz.duplicated(subset='customer',keep=False)]
</code>```

Return the below that seems ok:

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

As a beginner I would like to check

if there are any suggestions on my code and if there are more efficient way to do what I would like to achieve

I thought of set the date column to datetime index. But I do not know how to handle it afterward, and whether it would make my task any easier ?

Thank you.

答:
If you have one optimization you can do is to replace the groupyby_count by value_counts:

```<code>>>> df.value_counts(['date1', 'customer']).rename('count').reset_index() \
      .loc[lambda x: x.duplicated('customer', keep=False)]

              date1  customer  count
0  23/02/2021 18:59  40001375      3
1  30/01/2021 03:31  40001375      3
</code>```

Body:
I'm new to pandas and would like to check if there are more efficient way to do what I would like to achieve.

I have a customer master data change log for 12 months looks like below (the full file have 150K rows and 15 columns)

date1
changed_by
customer
field_name

23/02/2021 18:59
101852
40001375
Industry

23/02/2021 18:59
101852
40001375
Industry code 1

23/02/2021 18:59
101852
40001375
Region

30/12/2021 02:31
119186
30045194
Postal Code

30/12/2021 02:31
119186
30045194
Industry code 1

30/12/2021 02:31
119186
30045194
Region

30/01/2021 03:31
109209
40001375
Postal Code

30/01/2021 03:31
109209
40001375
Industry code 1

30/01/2021 03:31
109209
40001375
Bank

I would like to check if there are any customers' data being change more than once within the period, i.e. same customer ID but different date, then extract those line for further analysis.

Below are the code I currently have and seems work ok.

pvz = df3.groupby(['date1','customer'])['field_name'].count().reset_index()
pvz

Gives me

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

30/12/2021 02:31
30045194
3

Then I:

pvz[pvz.duplicated(subset='customer',keep=False)]

Return the below that seems ok:

date1
customer
field_name

23/02/2021 18:59
40001375
3

30/01/2021 03:31
40001375
3

As a beginner I would like to check

if there are any suggestions on my code and if there are more efficient way to do what I would like to achieve

I thought of set the date column to datetime index. But I do not know how to handle it afterward, and whether it would make my task any easier ?

Thank you.

Body:
If you have one optimization you can do is to replace the groupyby_count by value_counts:

>>> df.value_counts(['date1', 'customer']).rename('count').reset_index() \
      .loc[lambda x: x.duplicated('customer', keep=False)]

              date1  customer  count
0  23/02/2021 18:59  40001375      3
1  30/01/2021 03:31  40001375      3


问:
how can i convert NSString to String
Im trying to convert a NSString from a text field to a standard String so that I can check if it contains a certain character.

I have tried

```<code>var nSStringText = textField.text! as NSString
var stringText = nSStringText as String

</code>```

```<code>output

'NSString' is not convertible to 'String'
</code>```

答:
```<code>let plainString = "borat"                    // from String
let nsString = NSString(string: plainString) // to NSString
let backToString = String(nsString)          // back to String
</code>```

String has a number of initializers, one of which takes an NSString. Conversely, NSString also has a number of initializers, one of which takes a String. Use these initializers to transition between the types.

Title: how can i convert NSString to String

Body:
Im trying to convert a NSString from a text field to a standard String so that I can check if it contains a certain character.

I have tried

var nSStringText = textField.text! as NSString
var stringText = nSStringText as String

output

'NSString' is not convertible to 'String'

Body:
let plainString = "borat"                    // from String
let nsString = NSString(string: plainString) // to NSString
let backToString = String(nsString)          // back to String

String has a number of initializers, one of which takes an NSString. Conversely, NSString also has a number of initializers, one of which takes a String. Use these initializers to transition between the types.


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

答: Since you are using C# I would recommend using the regular expression tester here http://regexhero.net/tester/  It is great, you will be able to see the results of you expression highlighted as you build your expression.</p>

Title: Need help creating a Regex


问:
Why does my click counter only count the first click?
I have a website that does wiki speed runs. I have a mode that is called wiki golf. the goal of the game is to get to the jesus wikipedia page in under 5 clicks from a random page. Right now this code is working, but only runs once. (the click counter only goes to one and then stops.) The code is counting how many times you click inside of an iframe.</p>
```<code>    <head>
    <script src="https://code.jquery.com/jquery-3.1.1.js">

    </script>
    <meta charset="utf-8">
    <link rel="stylesheet" href="/game/game.css">
    <script src="/game/game.js">

    </script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
     crossorigin="anonymous" referrerpolicy="no-referrer" />

</head>
<div id="message"></div>
<div id="invisible_layer">

</div>
<iframe src="https://en.wikipedia.org/wiki/Special:Random"  id="mainFrame" style="position:relative; top:0; left:0; bottom:0; right:0; width:100%; height:80%; border:none; margin:0; padding:0; overflow:hidden; z-index:999999;"></iframe>
</div>
<title> Wiki Golf | WikiRun </title>

<style>
    #invisible_layer {
        position: absolute;
        background-color: trasparent;
        width: 500px;
        height: 300px;
    }
</style>

</html>
<div class="stopwatch">
    <p>
        <h1>
            <b> Good Luck!! </b>
   </h1>
  </p>
  </div>
  <p>Clicks: <a id="bellow">0</a></p>
</a>

  <script>
  let count = 0;

var myConfObj = {
  iframeMouseOver : true
}
window.addEventListener('blur',function(){
  if(myConfObj.iframeMouseOver){
    count += 1;
     document.getElementById("bellow").innerHTML = count;

  }
});

document.getElementById('mainFrame').addEventListener('mouseover',function(){
   myConfObj.iframeMouseOver = true;
});
document.getElementById('mainFrame').addEventListener('mouseout',function(){
    myConfObj.iframeMouseOver = false;
});
</script>

</script>
</code>```

答:
It's because you're triggering the click count increase on a "blur" event, which, I suppose, only fires once when you first click into the iframe and then never again because the iframe is still focused. Why don't you use a simple "click" event instead?

document.querySelector('iframe').addEventListener('click',function(){
  if(myConfObj.iframeMouseOver){
    count += 1;
     document.getElementById("bellow").innerHTML = count;

  }
});
```

Body:
I have a website that does wiki speed runs. I have a mode that is called wiki golf. the goal of the game is to get to the jesus wikipedia page in under 5 clicks from a random page. Right now this code is working, but only runs once. (the click counter only goes to one and then stops.) The code is counting how many times you click inside of an iframe.

    <meta charset="utf-8">
    <link rel="stylesheet" href="/game/game.css">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/site.webmanifest">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg=="
     crossorigin="anonymous" referrerpolicy="no-referrer" />

<title> Wiki Golf | WikiRun </title>

             Good Luck!!

Clicks: 0

</script>


答:
ipAddress is not an element of the list, you should iterate over the complete list.

import json

with open("test.json") as jsonFile:
    jsonObject = json.load(jsonFile)
    jsonFile.close()

ips = []

for items in jsonObject:
    ips.append(str(items['ipAddress']))

print(ips)
```

I'd suggest to check better the basics of Python and investigate more about this error, there are several posts about this.

Title: Extract data from GCP source ips JSON file

Body:
I'm trying to setup in GCP a firewall rule in my VPC setting, using as a source all the Google IPs used by the monitoring, GCP allow to download the following txt file

[{"ipAddress":"104.155.77.122","region":"EUROPE","location":"Belgium"},{"ipAddress":"104.155.110.139","region":"EUROPE","location":"Belgium"},{"ipAddress":"146.148.119.250","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.195.128.75","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.240.124.58","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.205.234.10","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.205.72.231","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.187.114.193","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.205.205.242","region":"EUROPE","location":"Belgium"},{"ipAddress":"35.187.242.246","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.186.144.97","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.198.221.49","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.198.194.122","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.198.248.66","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.185.178.105","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.198.224.104","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.240.151.105","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"35.186.159.51","region":"ASIA_PACIFIC","location":"Singapore"},{"ipAddress":"146.148.59.114","region":"USA","location":"Iowa"},{"ipAddress":"23.251.144.62","region":"USA","location":"Iowa"},{"ipAddress":"146.148.41.163","region":"USA","location":"Iowa"},{"ipAddress":"35.239.194.85","region":"USA","location":"Iowa"},{"ipAddress":"104.197.30.241","region":"USA","location":"Iowa"},{"ipAddress":"35.192.92.84","region":"USA","location":"Iowa"},{"ipAddress":"35.238.3.7","region":"USA","location":"Iowa"},{"ipAddress":"35.224.249.156","region":"USA","location":"Iowa"},{"ipAddress":"35.238.118.210","region":"USA","location":"Iowa"},{"ipAddress":"35.197.117.125","region":"USA","location":"Oregon"},{"ipAddress":"35.203.157.42","region":"USA","location":"Oregon"},{"ipAddress":"35.199.157.7","region":"USA","location":"Oregon"},{"ipAddress":"35.233.206.171","region":"USA","location":"Oregon"},{"ipAddress":"35.197.32.224","region":"USA","location":"Oregon"},{"ipAddress":"35.233.167.246","region":"USA","location":"Oregon"},{"ipAddress":"35.203.129.73","region":"USA","location":"Oregon"},{"ipAddress":"35.185.252.44","region":"USA","location":"Oregon"},{"ipAddress":"35.233.165.146","region":"USA","location":"Oregon"},{"ipAddress":"35.186.164.184","region":"USA","location":"Virginia"},{"ipAddress":"35.188.230.101","region":"USA","location":"Virginia"},{"ipAddress":"35.199.27.30","region":"USA","location":"Virginia"},{"ipAddress":"35.186.176.31","region":"USA","location":"Virginia"},{"ipAddress":"35.236.207.68","region":"USA","location":"Virginia"},{"ipAddress":"35.236.221.2","region":"USA","location":"Virginia"},{"ipAddress":"35.221.55.249","region":"USA","location":"Virginia"},{"ipAddress":"35.199.12.162","region":"USA","location":"Virginia"},{"ipAddress":"35.186.167.85","region":"USA","location":"Virginia"},{"ipAddress":"35.199.66.47","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.198.18.224","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.199.67.79","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.198.36.209","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.199.90.14","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.199.123.150","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.198.39.162","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.199.77.186","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"},{"ipAddress":"35.199.126.168","region":"SOUTH_AMERICA","location":"Sao Paulo, Brazil"}]

What I need is to extract all ip address to a list, for later create the firewall rule using gcloud or python, the following code is what I tried but I'm getting errors

import json

with open("test.json") as jsonFile:
    jsonObject = json.load(jsonFile)
    jsonFile.close()

ips = jsonObject['ipAddress']

print(ips)

    C:\Scripts\Python\GCP\listipaddresses> python3 .\listips.py
Traceback (most recent call last):
  File "C:\Scripts\Python\GCP\listipaddresses\listips.py", line 8, in <module>
    product = jsonObject['ipAddress']
TypeError: list indices must be integers or slices, not str

Can anyone could help me how to achieve this?

Thanks
Best regards

Body:
ipAddress is not an element of the list, you should iterate over the complete list.

import json

with open("test.json") as jsonFile:
    jsonObject = json.load(jsonFile)
    jsonFile.close()

ips = []

for items in jsonObject:
    ips.append(str(items['ipAddress']))

print(ips)

I'd suggest to check better the basics of Python and investigate more about this error, there are several posts about this.


问:
Can Le be part of the data passed to PCSC SCardTransmit for a Case 4 command regardless of protocol?
ISO/IEC 7816-3:2006 (12.1.2) defines the bytestring for a command to a Smart Card that sends data and is expected to produce some beyond a status word:

A command APDU of case 4 consists of a header, a LC field, a data field and a LE field.

ISO/IEC 7816-4:2020 (5.2) is similar. I restrict to the short case (4S) where

LC is a byte in 01H…FFH directly coding integer NC (the number of bytes in the data field, thus discounting the 4-byte header)

LE is a byte in 01H…FFH directly coding integer NE (the number of bytes expected from the card in response when no error occurs, discounting status words), or 00H meaning maximum (or equivalently NE=256).

In such case 4S, can LE be part of the data passed to PCSC SCardTransmit regardless of the protocol?

In other words, when passing such command to PCSC SCardTransmit, can we set cbSendLength to NC+6 regardless of the protocol?

I ask because I have a reproducible issue where including LE in a command (e.g. 00 A4 09 00  02  20 03  42 with cbSendLength = 8 in a context where the card will actually return a status word 6A 82 and no data) causes SCardTransmit to fail. The value of the LE byte is immaterial. That's with T=0 cards from different manufacturers and applications, several readers of different models but all with the same manufacturer-recommended Windows driver (GemPcCCID 4.1.4.0 of 2016-08-08 signed 2018-07-26, there). The problem vanishes with Microsoft's default CCID WUDF driver, or if I set cbSendLength to one less (thus removing LE). I have so far found no other reader/driver configuration triggering that issue, so I'm tented to say that's a driver issue (or at least an issue of the combination of that driver and the PCSC service it's supposed to work with).

I'd like some specification that tells if it's legit to include the LE byte to SCardTransmit, and I'd prefer something not Windows-specific.

I understand that if somewhat the application knows that the protocol T=0 is used, it's easy to omit the LE byte from the initial SCardTransmit, and I see how LE can be handled subsequently when the card sends a 61xx status word. However some contactless Smart Card readers pretend to be T=0 when they really use the ISO/IEC 14443-4 protocol, and then the LE byte is useful in some cases, thus I don't want to use that option.

Addition: the spec of ScardTransmit has:

For T=0, in the special case where no data is sent to the card and no data expected in return, this length (of the data passed to ScardTransmit) must reflect that the bP3 member is not being sent; the length should be sizeof(CmdBytes) - sizeof(BYTE)(that is 4, the length of the C-APDU).

Therefore, under in T=0, in cases 1, 2S, 3S, what's passed to ScardTransmit is the C-APDU, and in case 1 that differs from the C-TPDU. I'm asking if there is a reference settling about the imperative, in case 4S under T=0 specifically, to strip LE from a C-APDU (making it the C-TPDU) before passing it to ScardTransmit, similar to the above prescription to not make such conversion from C-APDU to C-TPDU in case 1 under T=0 (which ScardTransmit, the driver, or the reader will perform).

答:
As stated in the other answer, it's not safe to pass a Case 4 command APDU to SCardTransmit complete with Le when under the T=0 protocol. The question also asks where that's documented.

Such restriction is currently stated neither in Microsoft's spec of SCardTansmit, nor in the pscsclite spec. However, SCardTransmit has historically been developed as an implementation (with different parameter passing but similar functionality) of IFD_Transmit_to_ICC specified by PC/SC in Part 3, paragraph 4.3.2.1 (caution: possibly slow loading) and that states:

Provisions for SCARD_PROTOCOL_T0 communication
The CommandData needs to be formatted as an APDU as described in the ISO/IEC 7816-4. The following cases are supported:

Case 1: Command with no incoming or outgoing data byte: CLA INS P1 P2

Case 2: Command with outgoing data bytes:  CLA INS P1 P2 Le

Case 3: Command with incoming data bytes: CLA INS P1 P2 Lc [Data bytes]

Specific remarks:

Only the short format of Lc and Le is supported, i.e. one byte long.

An incoming order with no data byte « CLA INS P1 P2 » should be sent to the card as TPDU through a case 1 APDU.

A case 4 APDU cannot be used. It is the responsibility of the application or the service provider to generate a « get response » if they need it.

Hence when under the T=0 protocol, it's imprudent to pass SCardTransmit anything else than a Case 1, Case 2S, or Case 3S Command APDU.

If we pass a Case 4S Command APDU ( CLA INS P1 P2 Lc [Lc Data bytes] Le, with Lc in [0x01…0xff] ) that works fine with many drivers and readers. In my experience, both under Windows with Microsoft's Usbccid WUDF driver and many other vendor's drivers, and with pcsclite and it's companion libccid, the full C-APDU is passed to the reader, which filters out Le in the C-TPDU to the card, and everything is well. However there are exceptions, including the GemCCID 4.1.4 Windows driver, which performs no transfer and returns an error.


问:
Fake DbContext of Entity Framework 4.1 to Test my repositories
I'm have a Base Repository and all Entities repositories inherits from that.

In my testes i create a Fake DbContext and Fake DbSet to test my repositories, but when implementing some methods in my FakeDbContext I'm not able to implement the IDbContext.Entry method:

```<code>public class FakeDbContext : IDbContext
{
    private IDbSet<Usuario> _usuario;
    private IDbSet<Atividade> _atividade;
    private IDbSet<Autor> _autor;
    private IDbSet<CategoriaModulo> _categoriaModulo;
    private IDbSet<CategoriaMateria> _categoriaMateria;
    private IDbSet<Site> _site;
    private IDbSet<Modulo> _modulo;
    private IDbSet<Perfil> _perfil;
    private IDbSet<CategoriaGaleriaImagem> _categoriaGaleriaImagem;

    public IDbSet<Usuario> Usuario { get { return _usuario ?? (_usuario = new FakeDbSet<Usuario>()); } set { } }
    public IDbSet<Atividade> Atividade { get { return _atividade ?? (_atividade = new FakeDbSet<Atividade>()); } set { } }
    public IDbSet<Autor> Autor { get { return _autor ?? (_autor = new FakeDbSet<Autor>()); } set { } }
    public IDbSet<CategoriaModulo> CategoriaModulo { get { return _categoriaModulo ?? (_categoriaModulo = new FakeDbSet<CategoriaModulo>()); } set { } }
    public IDbSet<CategoriaMateria> CategoriaMateria { get { return _categoriaMateria ?? (_categoriaMateria = new FakeDbSet<CategoriaMateria>()); } set { } }
    public IDbSet<Site> Site { get { return _site ?? (_site = new FakeDbSet<Site>()); } set { } }
    public IDbSet<Modulo> Modulo { get { return _modulo ?? (_modulo = new FakeDbSet<Modulo>()); } set { } }
    public IDbSet<Perfil> Perfil { get { return _perfil ?? (_perfil = new FakeDbSet<Perfil>()); } set { } }
    public IDbSet<CategoriaGaleriaImagem> CategoriaGaleriaImagem { get { return _categoriaGaleriaImagem ?? (_categoriaGaleriaImagem = new FakeDbSet<CategoriaGaleriaImagem>()); } set { } }

    public void SaveChanges()
    {
        //do nothing
    }

    public IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        foreach (PropertyInfo property in typeof(FakeDbContext).GetProperties())
        {
            if (property.PropertyType == typeof(IDbSet<TEntity>))
                return property.GetValue(this, null) as IDbSet<TEntity>;
        }
        throw new Exception("Type collection not found");
    }

    public System.Data.Entity.Infrastructure.DbEntityEntry Entry<TEntity>(TEntity entity) where TEntity : class
    {
    }
}
</code>```

The last method I'm not able to implementing, can you guys help me?

I'm using this Entry method to update a Entity in my base repository:

```<code>public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
        #region Fields

        protected TEntity EntityType;
        protected IDbSet<TEntity> DbSet;

        #endregion

        #region Properties

        public IDbContext DbContext
        {
            get
            {
                return DbContextFactory.Instance.GetOrCreateContext();
            }
        }

        #endregion

        #region Constructors

        protected BaseRepository()
        {
            this.EntityType = DependencyResolverFactory.Instance.Get<TEntity>();
            this.DbSet = DbContext.Set<TEntity>();
        }

        #endregion

        #region Methods

        public virtual void Add(TEntity entity)
        {
            this.DbSet.Add(entity);
        }

        public virtual void Remove(TEntity entity)
        {
            this.DbSet.Remove(entity);
        }

        public virtual void RemoveById(object id)
        {
            TEntity entity = this.GetById(id);
            this.DbSet.Remove(entity);
        }

        public virtual void Edit(TEntity entity)
        {
            this.DbContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual TEntity GetById(object id)
        {
            return (TEntity)this.DbSet.Find(id);
        }

        public virtual IList<TEntity> GetAll()
        {
            return ((IEnumerable<TEntity>)this.DbSet).ToList();
        }

        #endregion
    }
</code>```

答:
Read this and all linked questions before you continue. Unit testing anything returning EF related classes or working with linq-to-entities is dangerous.

Give up with unit testing your repositories and instead unit test your application logic by faking repositories themselves. If you want to test your repositories create integration tests talking to the real database.

Body:
I'm have a Base Repository and all Entities repositories inherits from that.

In my testes i create a Fake DbContext and Fake DbSet to test my repositories, but when implementing some methods in my FakeDbContext I'm not able to implement the IDbContext.Entry method:

public class FakeDbContext : IDbContext
{
    private IDbSet<Usuario> _usuario;
    private IDbSet<Atividade> _atividade;
    private IDbSet<Autor> _autor;
    private IDbSet<CategoriaModulo> _categoriaModulo;
    private IDbSet<CategoriaMateria> _categoriaMateria;
    private IDbSet<Site> _site;
    private IDbSet<Modulo> _modulo;
    private IDbSet<Perfil> _perfil;
    private IDbSet<CategoriaGaleriaImagem> _categoriaGaleriaImagem;

    public IDbSet<Usuario> Usuario { get { return _usuario ?? (_usuario = new FakeDbSet<Usuario>()); } set { } }
    public IDbSet<Atividade> Atividade { get { return _atividade ?? (_atividade = new FakeDbSet<Atividade>()); } set { } }
    public IDbSet<Autor> Autor { get { return _autor ?? (_autor = new FakeDbSet<Autor>()); } set { } }
    public IDbSet<CategoriaModulo> CategoriaModulo { get { return _categoriaModulo ?? (_categoriaModulo = new FakeDbSet<CategoriaModulo>()); } set { } }
    public IDbSet<CategoriaMateria> CategoriaMateria { get { return _categoriaMateria ?? (_categoriaMateria = new FakeDbSet<CategoriaMateria>()); } set { } }
    public IDbSet<Site> Site { get { return _site ?? (_site = new FakeDbSet<Site>()); } set { } }
    public IDbSet<Modulo> Modulo { get { return _modulo ?? (_modulo = new FakeDbSet<Modulo>()); } set { } }
    public IDbSet<Perfil> Perfil { get { return _perfil ?? (_perfil = new FakeDbSet<Perfil>()); } set { } }
    public IDbSet<CategoriaGaleriaImagem> CategoriaGaleriaImagem { get { return _categoriaGaleriaImagem ?? (_categoriaGaleriaImagem = new FakeDbSet<CategoriaGaleriaImagem>()); } set { } }

    public void SaveChanges()
    {
        //do nothing
    }

    public IDbSet<TEntity> Set<TEntity>() where TEntity : class
    {
        foreach (PropertyInfo property in typeof(FakeDbContext).GetProperties())
        {
            if (property.PropertyType == typeof(IDbSet<TEntity>))
                return property.GetValue(this, null) as IDbSet<TEntity>;
        }
        throw new Exception("Type collection not found");
    }

    public System.Data.Entity.Infrastructure.DbEntityEntry Entry<TEntity>(TEntity entity) where TEntity : class
    {
    }
}

The last method I'm not able to implementing, can you guys help me?

I'm using this Entry method to update a Entity in my base repository:

public abstract class BaseRepository<TEntity> : IBaseRepository<TEntity> where TEntity : class
    {
        #region Fields

        protected TEntity EntityType;
        protected IDbSet<TEntity> DbSet;

        #endregion

        #region Properties

        public IDbContext DbContext
        {
            get
            {
                return DbContextFactory.Instance.GetOrCreateContext();
            }
        }

        #endregion

        #region Constructors

        protected BaseRepository()
        {
            this.EntityType = DependencyResolverFactory.Instance.Get<TEntity>();
            this.DbSet = DbContext.Set<TEntity>();
        }

        #endregion

        #region Methods

        public virtual void Add(TEntity entity)
        {
            this.DbSet.Add(entity);
        }

        public virtual void Remove(TEntity entity)
        {
            this.DbSet.Remove(entity);
        }

        public virtual void RemoveById(object id)
        {
            TEntity entity = this.GetById(id);
            this.DbSet.Remove(entity);
        }

        public virtual void Edit(TEntity entity)
        {
            this.DbContext.Entry(entity).State = EntityState.Modified;
        }

        public virtual TEntity GetById(object id)
        {
            return (TEntity)this.DbSet.Find(id);
        }

        public virtual IList<TEntity> GetAll()
        {
            return ((IEnumerable<TEntity>)this.DbSet).ToList();
        }

        #endregion
    }


问:
How do I import Apache Airflow into Intellij?
So I'm trying to get my Intellij to see Apache Airflow that I downloaded. The steps I've taken so far:
I've downloaded the most recent Apache Airflow setup and saved the apache airflow 2.2.3 onto my desktop. I'm trying to get it to work with my Intellij, I've tried adding the Apache Airflow folder into the Library and Modules, both have come back with errors stating it's not being utilized. I've tried looking up documentation on it within Airflow but I'm not able to find any documentation on how to implement in your own IDE to write Python scripts for DAGs and other items?

How would I go about doing this as I'm at a complete loss of how to get Intellij to register that Apache Airflow is a Library to utilize for Python code so I can write DAG files correctly within the IDE itself.

Any help would be much appreciated as I've been stuck on this aspect for the past couple of days searching for any kind of documentation to make this work.

答:
Airflow is both application and library. In your case you are not trying to run the application but only looking to write DAGs so you need it just as a library.
You should just open a virtual environment (preferably) and run:

```<code>pip install apache-airflow
</code>```

Then you can write DAGs using the library and Intellij will let you know if you are using wrong imports or deprecated objects.

When your DAG file is ready deploy it to the DAG folder on the machine where Airflow is running.

Body:
Airflow is both application and library. In your case you are not trying to run the application but only looking to write DAGs so you need it just as a library.
You should just open a virtual environment (preferably) and run:

pip install apache-airflow

Then you can write DAGs using the library and Intellij will let you know if you are using wrong imports or deprecated objects.

When your DAG file is ready deploy it to the DAG folder on the machine where Airflow is running.


问:
Win32 File Name Comparison
Does anyone know what culture settings Win32 uses when dealing with case-insensitive files names?

Is this something that varies based on the user's culture, or are the casing rules that Win32 uses culture invariant?

答: According to Windows Driver Samples FastFAT and CDFS, it uses RtlUpcaseUnicodeString to convert a string to uppercase.  According to a brief look in Ghidra, that uses an internal function named NLS_UPCASE, whose behavior is based on your current system codepage.

OwnerDisplayName: Scott Wisniewski

ContentLicense: CC BY-SA 2.5

Title: Win32 File Name Comparison

LastEditorDisplayName: moocha