问:
How to update Dart Class Variable and refresh flutter state?
I have a main dart file and a settings dart file. The settings dart file is responsible for the appearance of the main dart file. Settings dart has a AppTheme class. Upon users typing on this settings page I want the main page to update.

My attempt at this was calling the class and redefining the variables based on user input. Doesnt work whether or not I use setState(). I also tried jus staying on the main page and tried changing the theme onPressed for the settings button. That didnt work either. Iconbutton update doesnt update the state either.

```<code>import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:resume/settings.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      theme: ThemeData.light(),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {

    double buttonMargin = MediaQuery.of(context).size.width / 10;
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    return MaterialApp(
      home: Scaffold(
        backgroundColor: AppTheme().backgroundMain,
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            child: Column(
              children: <Widget>[
                Container(
                  height: (MediaQuery.of(context).size.height / 2.25),
                  child: Column(children: <Widget>[
                    Container(
                      margin: EdgeInsets.all(10),
                      child: Text(AppTheme().name,
                          style: TextStyle(
                              fontFamily: 'Pacifico',
                              fontSize: screenWidth / 8.57142857143,
                              color: AppTheme().nameTextColor,
                              fontWeight: FontWeight.bold)),
                    ),
                  ]),
                ),
                Container(
                  height: screenHeight / 2.3,
                  alignment: Alignment.bottomCenter,
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: <Widget>[
                      Container(
                          margin: EdgeInsets.fromLTRB(
                              buttonMargin * 1.5,
                              buttonMargin * 3,
                              buttonMargin * 1.5,
                              buttonMargin * 3),
                          height: MediaQuery.of(context).size.height / 2,
                          width: MediaQuery.of(context).size.width / 2,
                          child: RaisedButton(
                            color: AppTheme().backgroundSecondary,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.settings,
                                  color: Colors.white,
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    'Settings',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                )
                              ],
                            ),
                            onPressed: () {
                              setState(() {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) {
                                    return MySettings();
                                  }),
                                );
                              },
                              );
                              },
                          ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

settings.dart

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

void settings() {
  runApp(MySettings());
}

class AppTheme {
  var backgroundMain = Colors.red;
  var backgroundSecondary = Colors.teal;
  var backgroundAvatar = Colors.white;
  var nameTextColor = Colors.white;
  var professionTextColor = Colors.red[100];
  var contactTextColor = Colors.teal;
  var testPrint = print("hi");

  String name = 'John Doe';

  String nameFont = 'Pacifico';
  String professionFont = 'roboto';
}

class MySettings extends StatefulWidget {
  @override
  MySettingsState createState() => MySettingsState();
}

class MySettingsState extends State<MySettings> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: AppTheme().backgroundMain,
          title: Text('Settings'),
          leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              setState(() {
                AppTheme().backgroundMain = Colors.yellow;
                print(AppTheme().name);
                Navigator.pop(context);
              });
            },
          ),
        ),
        backgroundColor: Colors.teal,
        body: SafeArea(
            child: ListView(
          children: <Widget>[
            Container(
              child: TextField(
                onChanged: (text) {
                  setState(() {
                    AppTheme().name = text;
                  });
                },
              ),
            ),
            Container(
              child: TextField(),
            ),
          ],
        )),
      ),
    );
  }
}

</code>```

答:
1 Make sure to properly import

Flutter/Dart Static variables lost / keep getting reinitialized

2 You cannot alter the variables in the class. You must create an object and alter the object.

i.e I was doing

```<code>Class MyClass {
var myVariable = someValue
}

MyClass.myVariale = aDifferentValue
</code>```

This did not update MyClass
What I needed to do worked once I created an object

```<code>var myClassObject = new Myclass();
myClassObject.myVariable = aDifferentValue
</code>```

Now I just alter and call on myClassObject.

Body:
I have a main dart file and a settings dart file. The settings dart file is responsible for the appearance of the main dart file. Settings dart has a AppTheme class. Upon users typing on this settings page I want the main page to update.

My attempt at this was calling the class and redefining the variables based on user input. Doesnt work whether or not I use setState(). I also tried jus staying on the main page and tried changing the theme onPressed for the settings button. That didnt work either. Iconbutton update doesnt update the state either.

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:resume/settings.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Title',
      theme: ThemeData.light(),
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  Widget build(BuildContext context) {

    double buttonMargin = MediaQuery.of(context).size.width / 10;
    double screenWidth = MediaQuery.of(context).size.width;
    double screenHeight = MediaQuery.of(context).size.height;

    return MaterialApp(
      home: Scaffold(
        backgroundColor: AppTheme().backgroundMain,
        body: SafeArea(
          child: Padding(
            padding: const EdgeInsets.fromLTRB(0, 20, 0, 0),
            child: Column(
              children: <Widget>[
                Container(
                  height: (MediaQuery.of(context).size.height / 2.25),
                  child: Column(children: <Widget>[
                    Container(
                      margin: EdgeInsets.all(10),
                      child: Text(AppTheme().name,
                          style: TextStyle(
                              fontFamily: 'Pacifico',
                              fontSize: screenWidth / 8.57142857143,
                              color: AppTheme().nameTextColor,
                              fontWeight: FontWeight.bold)),
                    ),
                  ]),
                ),
                Container(
                  height: screenHeight / 2.3,
                  alignment: Alignment.bottomCenter,
                  child: ListView(
                    scrollDirection: Axis.horizontal,
                    children: <Widget>[
                      Container(
                          margin: EdgeInsets.fromLTRB(
                              buttonMargin * 1.5,
                              buttonMargin * 3,
                              buttonMargin * 1.5,
                              buttonMargin * 3),
                          height: MediaQuery.of(context).size.height / 2,
                          width: MediaQuery.of(context).size.width / 2,
                          child: RaisedButton(
                            color: AppTheme().backgroundSecondary,
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Icon(
                                  Icons.settings,
                                  color: Colors.white,
                                ),
                                Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: Text(
                                    'Settings',
                                    style: TextStyle(color: Colors.white),
                                  ),
                                )
                              ],
                            ),
                            onPressed: () {
                              setState(() {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(builder: (context) {
                                    return MySettings();
                                  }),
                                );
                              },
                              );
                              },
                          ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

settings.dart

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

void settings() {
  runApp(MySettings());
}

class AppTheme {
  var backgroundMain = Colors.red;
  var backgroundSecondary = Colors.teal;
  var backgroundAvatar = Colors.white;
  var nameTextColor = Colors.white;
  var professionTextColor = Colors.red[100];
  var contactTextColor = Colors.teal;
  var testPrint = print("hi");

  String name = 'John Doe';

  String nameFont = 'Pacifico';
  String professionFont = 'roboto';
}

class MySettings extends StatefulWidget {
  @override
  MySettingsState createState() => MySettingsState();
}

class MySettingsState extends State<MySettings> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          backgroundColor: AppTheme().backgroundMain,
          title: Text('Settings'),
          leading: IconButton(
            icon: Icon(Icons.arrow_back),
            onPressed: () {
              setState(() {
                AppTheme().backgroundMain = Colors.yellow;
                print(AppTheme().name);
                Navigator.pop(context);
              });
            },
          ),
        ),
        backgroundColor: Colors.teal,
        body: SafeArea(
            child: ListView(
          children: <Widget>[
            Container(
              child: TextField(
                onChanged: (text) {
                  setState(() {
                    AppTheme().name = text;
                  });
                },
              ),
            ),
            Container(
              child: TextField(),
            ),
          ],
        )),
      ),
    );
  }
}

Body:
1 Make sure to properly import

Flutter/Dart Static variables lost / keep getting reinitialized

2 You cannot alter the variables in the class. You must create an object and alter the object.

i.e I was doing

Class MyClass {
var myVariable = someValue
}

MyClass.myVariale = aDifferentValue

This did not update MyClass
What I needed to do worked once I created an object

var myClassObject = new Myclass();
myClassObject.myVariable = aDifferentValue

Now I just alter and call on myClassObject.


来源: stackexchange

问:
Converting csv read hex string values to uint8_t in c++
So I am currently able to read some hex values from a csv file using ifstream. I am able to read the values and assign them to a string variable. But I want to convert them to uint8_t values. So essentially I want something like this uint8_t A = 0x41;

I have tried atoi ,  stoi , and strtol but i don't seem to get any valid output.(I might be using them wrong)

int read_csv(){
using namespace std;
ifstream fin;
fin.open("simpletrajhex.txt");
while (fin.good ()){
      char[] line;
      getline (fin, line, ',');
      uint8_t hex1 = (uint8_t)stoi(line,NULL,16);
      cout << line << " " << hex1 << endl;
    }
  return 1;
}
```

<p>When I read my csv file i get something similar</p>

```0xFF
0x5F
0x02
0x00
0xFF
```

But these are strings and I need each value to be converted to uint8_t
and when I try convert nothing shows up.

答:
You cannot store hex value as it is in an uint8_t variable, so uint8_t A = 0x41 is not possible. Instead, you will have to get a decimal equivalent of the hex number into uint8_t.

Try using std::stoul

Get the decimal equivalent of hex and get the hex back from the decimal when you need it.

ContentLicense: CC BY-SA 4.0

Body:
So I am currently able to read some hex values from a csv file using ifstream. I am able to read the values and assign them to a string variable. But I want to convert them to uint8_t values. So essentially I want something like this uint8_t A = 0x41;

I have tried atoi ,  stoi , and strtol but i don't seem to get any valid output.(I might be using them wrong)

int read_csv(){
using namespace std;
ifstream fin;
fin.open("simpletrajhex.txt");
while (fin.good ()){
      char[] line;
      getline (fin, line, ',');
      uint8_t hex1 = (uint8_t)stoi(line,NULL,16);
      cout << line << " " << hex1 << endl;
    }
  return 1;
}

When I read my csv file i get something similar

0xFF
0x5F
0x02
0x00
0xFF

But these are strings and I need each value to be converted to uint8_t
and when I try convert nothing shows up.


问:
ionic alert mandatory input
I am using ionic 3 for my new app and I need to make inputs taken from my ionic-alert controller to be mandatory. Went through ionic-component documentation and api documentation, but could not find how to do this. Below is my code. I want to make name and mobile inputs to be mandatory and disable Continue button until both are filled.

```<code>let prompt = this.alertCtrl.create({
        title: 'Tell us about yourself',
        message: "Please provide us your name, and mobile number",
        inputs: [
        {
          name: 'name',
          placeholder: 'Name'
        },
        {
          name: 'mobile',
          placeholder: 'Mobile number'
        },],
        buttons: [
        {
          text: 'Cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Continue',
          handler: data => {
            console.log('Continue clicked');
          }
        }]
        });
        prompt.present();
</code>```

答:
For anybody still looking for a workaround, here is what I did, not only in Ionic 3 but in Ionic 4 as well.

You can make your inputs mandatory, validate data upon confirmation or even update the alert message by using some DOM manipulation through the document object.

Basically you want to open your alert and query all your inputs or buttons that you are interested in. Then you can add some listeners to you inputs to enable or disable any other element.

Example (Ionic 4)

```<code>    const alert = await this.alertCntrl.create({
      header: 'Alert!',
      subHeader: 'Delete item',
      message: 'Please fill the following code to confirm deletion: XYZ',
      inputs: [{type: 'text', placeholder: 'Confirmation code', id: 'code'}],
      buttons: [
        {text: 'Confirm', handler: _data => this.deleteItem(), cssClass: 'confirm'},
        {text: 'Cancel', role: 'cancel'},
      ],
    });
    await alert.present();

    const code$ = new Subject();

    const confirmBtn = document.querySelector('.confirm') as HTMLButtonElement;
    confirmBtn.disabled = true;

    const codeInput = document.getElementById('code') as HTMLInputElement;

    codeInput.addEventListener('keyup', () => codigo$.next(codeInput.value));

    code$.asObservable().subscribe(code => confirmBtn.disabled = code !== 'XYZ');
</code>```

To show that the button is disable I have added some css to ionic global.scss

```<code>// This will match the class that we set up to the btn in the alert config.
// and color the btn text to grey only when it is disabled
button.confirm:disabled {
  color: grey;
}
</code>```

Title: ionic alert mandatory input

Body:
I am using ionic 3 for my new app and I need to make inputs taken from my ionic-alert controller to be mandatory. Went through ionic-component documentation and api documentation, but could not find how to do this. Below is my code. I want to make name and mobile inputs to be mandatory and disable Continue button until both are filled.

let prompt = this.alertCtrl.create({
        title: 'Tell us about yourself',
        message: "Please provide us your name, and mobile number",
        inputs: [
        {
          name: 'name',
          placeholder: 'Name'
        },
        {
          name: 'mobile',
          placeholder: 'Mobile number'
        },],
        buttons: [
        {
          text: 'Cancel',
          handler: data => {
            console.log('Cancel clicked');
          }
        },
        {
          text: 'Continue',
          handler: data => {
            console.log('Continue clicked');
          }
        }]
        });
        prompt.present();

Body:
For anybody still looking for a workaround, here is what I did, not only in Ionic 3 but in Ionic 4 as well.

You can make your inputs mandatory, validate data upon confirmation or even update the alert message by using some DOM manipulation through the document object.

Basically you want to open your alert and query all your inputs or buttons that you are interested in. Then you can add some listeners to you inputs to enable or disable any other element.

Example (Ionic 4)

    const alert = await this.alertCntrl.create({
      header: 'Alert!',
      subHeader: 'Delete item',
      message: 'Please fill the following code to confirm deletion: XYZ',
      inputs: [{type: 'text', placeholder: 'Confirmation code', id: 'code'}],
      buttons: [
        {text: 'Confirm', handler: _data => this.deleteItem(), cssClass: 'confirm'},
        {text: 'Cancel', role: 'cancel'},
      ],
    });
    await alert.present();

    const code$ = new Subject();

    const confirmBtn = document.querySelector('.confirm') as HTMLButtonElement;
    confirmBtn.disabled = true;

    const codeInput = document.getElementById('code') as HTMLInputElement;

    codeInput.addEventListener('keyup', () => codigo$.next(codeInput.value));

    code$.asObservable().subscribe(code => confirmBtn.disabled = code !== 'XYZ');

To show that the button is disable I have added some css to ionic global.scss

// This will match the class that we set up to the btn in the alert config.
// and color the btn text to grey only when it is disabled
button.confirm:disabled {
  color: grey;
}


问:
Why timer invoke its block so quickly sometimes
I create a timer and invoke its block every 5 second. Then I make application to enter background and enter foreground after a while. But it could invoke the block quickly sometimes.

```<code>let _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { (timer) in
        print("--------")
   }
</code>```

When I enter foreground the interval of first printing and second printing may less than a second sometimes. Is time interval invalid in this case?

答:
To understand the behavior, you need to understand how NSTimer and RunLoop works. In simple terms, a RunLoop would check if the Timer should fire, if yes it would notify the Timer to fire the selector, else it won't. Now, since you are on the background, your RunLoop is not checking for events so it won't be able to notify the Timer. But once it goes to foreground, it would see that it would need to notify the Timer even if it passed the fireDate.

TimeLine Diagram:

Let A(5th second) and B(10th second) be timer fire events. Scheduled on a timer Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true)

C is entered background (0 seconds)

D be coming back to foreground (9th second, between A and B).

-----> A ------> B

C--------->D

Explanation:

On C, the RunLoop would be paused. Therefore Event A is not able to be processed until the RunLoop has resumed processing, which is on Event D. Upon Event D, it will see that Event A should fire so it would notify the Timer. After a second, the RunLoop would see that Event B has happened so it would notify the Timer again. This scenario explains why your events are printing in a second's interval. It is just the delayed event handling that makes it seem that it fired earlier, when in reality it was processed late.

Apple Doc:

A timer is not a real-time mechanism. If a timer’s firing time occurs
  during a long run loop callout or while the run loop is in a mode that
  isn't monitoring the timer, the timer doesn't fire until the next time
  the run loop checks the timer. Therefore, the actual time at which a
  timer fires can be significantly later.

resources: What is an NSTimer's behavior when the app is backgrounded?, NSRunLoop and Timer Docs

Suggestions:

Stop your timer once app goes background, but store the fireDate. Once coming back to foreground, check if fireDate is past Date(). Then create a new Timer to handle events while on foreground.

Body:
I create a timer and invoke its block every 5 second. Then I make application to enter background and enter foreground after a while. But it could invoke the block quickly sometimes.

let _ = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { (timer) in
        print("--------")
   }

When I enter foreground the interval of first printing and second printing may less than a second sometimes. Is time interval invalid in this case?


答:
If you can afford to load the whole input file in memory, here's a quick-and-dirty function that does just that:

```<code>(defn read-vec-of-strings [filename]
  (let [contents (slurp filename)                      ;; see (1) below
        lines    (clojure.string/split contents #"\n") ;; see (2) below
        vectors  (mapv #(mapv str %) lines)]           ;; see (3) below
    vectors))
</code>```

Step (1) loads the whole file as a single string in memory;

Step (2) splits the file by newlines;

Step (3) is where the magic happens: for each line in the file (mapv ... lines), call another (anonymous) function #(mapv str %) that iterates through each character of the line and turns them into a string (so the character \# becomes the string "#"), and accumulate the result in a vector.

I saved your input file as input.txt and called the function like this:

```<code>>  (clojure.pprint/pprint (read-vec-of-strings "input.txt"))

[["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
 ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
 ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
 ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
 ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
 ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
 ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
 ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]
nil
</code>```

Title: Is is possible to read from an input file and convert each line of the text file into a vector of strings?

Body:
I have a text file as shown below:

---#--###----
-#---#----##-
####-#-#-#-##
---#---#-#---
-#-####---##-
-#------#----
-############
------------@

Can I read from the input file and get an output in this format

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]
]

I tried reading the input file line by line and adding to a vector:

    (defn loadFile2 []
        (with-open [rdr (clojure.java.io/reader "map.txt")]
        (reduce conj [] (line-seq rdr)))
    )

    (defn convert_input_to_string []
        "Converts"
        ;(def temp )
        (loop [i 0 temp (loadFile2)]
            (if (< i (count temp))

            (recur (inc i) (assoc temp i (str (join (seq (get temp
             i))))) )
            temp
            ))
    )

(convert_input_to_string).

This approach gives me a vector of strings:

[---#--###----
 -#---#----##-
 ####-#-#-#-##
 ---#---#-#---
 -#-####---##-
 -#------#----
 -############
 ------------@
]

I want the vector in this format:

[ ["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
  ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
  ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
  ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
  ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
  ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
  ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
  ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]

Body:
If you can afford to load the whole input file in memory, here's a quick-and-dirty function that does just that:

(defn read-vec-of-strings [filename]
  (let [contents (slurp filename)                      ;; see (1) below
        lines    (clojure.string/split contents #"\n") ;; see (2) below
        vectors  (mapv #(mapv str %) lines)]           ;; see (3) below
    vectors))

Step (1) loads the whole file as a single string in memory;

Step (2) splits the file by newlines;

Step (3) is where the magic happens: for each line in the file (mapv ... lines), call another (anonymous) function #(mapv str %) that iterates through each character of the line and turns them into a string (so the character \# becomes the string "#"), and accumulate the result in a vector.

I saved your input file as input.txt and called the function like this:

>  (clojure.pprint/pprint (read-vec-of-strings "input.txt"))

[["-" "-" "-" "#" "-" "-" "#" "#" "#" "-" "-" "-" "-"]
 ["-" "#" "-" "-" "-" "#" "-" "-" "-" "-" "#" "#" "-"]
 ["#" "#" "#" "#" "-" "#" "-" "#" "-" "#" "-" "#" "#"]
 ["-" "-" "-" "#" "-" "-" "-" "#" "-" "#" "-" "-" "-"]
 ["-" "#" "-" "#" "#" "#" "#" "-" "-" "-" "#" "#" "-"]
 ["-" "#" "-" "-" "-" "-" "-" "-" "#" "-" "-" "-" "-"]
 ["-" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#" "#"]
 ["-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "-" "@"]]
nil


问:
Rotary Encoder State Machine - Can only read ONE of two pin states per interrupt
Background:

I am writing a driver for a Gray-code rotary encoder using a state machine after reading this arduino example. My device is coded with c# using the .net micro framework. Since it's not quite a real-time embedded os, I can only capture the state of ONE of the encoder's two pins during an interrupt. Upon interrupt, the event is queued to run in a high priority thread. The state of the pin which generated the interrupt is passed as an argument into the "ISR" aka the NativeEventHandler delegate. Reading the second pin's state while the handler runs is not accurate because it's several milliseconds after the actual event was queued.(I've tried it)

In my case, the base state is with both Pins A and B pulled high (value=1)

So, I have only 4 measurable states, but the actual states are based on the previous state.

Pin A High 1

Pin B High 1

Pin A Low 0

Pin B Low 0

I'm having trouble making a state transition table where the table won't get confused. I am trying to come up with some speedy logic to or maybe some bitwise operations to complete this.

Here's the states table(not the transition table) I've come up with:

```<code>Pin State   Assigned Value  State Name
PinB-High   4               CW Rot
PinA-High   3               CW3
PinB-Low    2               CW2
PinA-Low    1               CW1
Start       0               Start
PinB-Low    5               CCW1
PinA-Low    6               CCW2
PinB-High   7               CCW3
PinA-High   8               CCW Rot
</code>```

How do I get the right transitions only 4 states?

答: Even if you think about bit pairs for each of the encoder states, contact bouncing is so noisy that decoding these excitations using a state machine, the results can be inaccurate. A mix of states plus some kind of capacitor debouncing and some delay matching the contact bouncing time spec introduced in the interrupt function, can help. Bouncing can change a lot from one encoder brand and model to another. Software latencies in operating systems can make things even worse. It takes time and some testing.</p>

ContentLicense: CC BY-SA 3.0

Body:
Background:

I am writing a driver for a Gray-code rotary encoder using a state machine after reading this arduino example. My device is coded with c# using the .net micro framework. Since it's not quite a real-time embedded os, I can only capture the state of ONE of the encoder's two pins during an interrupt. Upon interrupt, the event is queued to run in a high priority thread. The state of the pin which generated the interrupt is passed as an argument into the "ISR" aka the NativeEventHandler delegate. Reading the second pin's state while the handler runs is not accurate because it's several milliseconds after the actual event was queued.(I've tried it)

In my case, the base state is with both Pins A and B pulled high (value=1)

So, I have only 4 measurable states, but the actual states are based on the previous state.

Pin A High 1

Pin B High 1

Pin A Low 0

Pin B Low 0

I'm having trouble making a state transition table where the table won't get confused. I am trying to come up with some speedy logic to or maybe some bitwise operations to complete this.

Here's the states table(not the transition table) I've come up with:

Pin State   Assigned Value  State Name
PinB-High   4               CW Rot
PinA-High   3               CW3
PinB-Low    2               CW2
PinA-Low    1               CW1
Start       0               Start
PinB-Low    5               CCW1
PinA-Low    6               CCW2
PinB-High   7               CCW3
PinA-High   8               CCW Rot

How do I get the right transitions only 4 states?


问:
Regex using brackets for a single character
I was solving this regex problem

Given a test string, s , write a RegEx that matches s under the following conditions:

s must start with Mr., Mrs., Ms., Dr. or Er.

The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).

I used this pattern

```<code>Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)\..[A-Za-z]+$'
</code>```

but it failed this test case "Ms._underscore", then I tried using this pattern

```<code>Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)[\..][A-Za-z]+$'
</code>```

and it passed all test cases, I cannot figure out the difference.

答:
I think you may have the two patterns reversed.  The second one does not match and the first one matches:

^(Mr|Mrs|Ms|Dr|Er)\..[A-Za-z]+$

Demo 1

^(Mr|Mrs|Ms|Dr|Er)[\..][A-Za-z]+$

Demo 2

The second one uses character class [\..] which removes special meaning of any regex tokens (e.g., . within [] matches literal period and not its special meaning (any character).  The first pattern matches a literal period followed by any single character other than newline.  For details on this, check out the "Explanation" on the right side in the demo links above.

UPDATE: your pattern also would match Ms.underscore (no space between title and name). So consider the following pattern, which I think works better for what you're looking for:

^(Mr|Mrs|Ms|Dr|Er)\.[ _][A-Za-z]+$

Demo 3

Body:
I was solving this regex problem

Given a test string, s , write a RegEx that matches s under the following conditions:

s must start with Mr., Mrs., Ms., Dr. or Er.

The rest of the string must contain only one or more English alphabetic letters (upper and lowercase).

I used this pattern

Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)\..[A-Za-z]+$'

but it failed this test case "Ms._underscore", then I tried using this pattern

Regex_Pattern = r'^(Mr|Mrs|Ms|Dr|Er)[\..][A-Za-z]+$'

and it passed all test cases, I cannot figure out the difference.


问:
Try/Catch is breaking Firebase Cloud Functions
I'm using Firebase Functions and have a try / catch within a get().then( ... ) function.

ESLint is calling the catch an error with:

Parsing error: Unexpected token { eslint

If I get rid of the try/catch completely, the error rolls up to another issue which is:

```<code>Each then() should return a value or throw eslint(promise/always-return)
</code>```

That error resolves when adding

```<code>return null
</code>```

I tried adding return null to the code when the try/catch was there to see if the issue may have just been that it was missing it, but it doesn't fix it.

An example of what this actually looks like in the code is this, I have tried what seems like everything:

答:
I think you just need to change

```<code>try {...}
catch {...}
</code>```

to

```<code>try {...}
catch(e) {...}
</code>```

Body:
I'm using Firebase Functions and have a try / catch within a get().then( ... ) function.

ESLint is calling the catch an error with:

Parsing error: Unexpected token { eslint

If I get rid of the try/catch completely, the error rolls up to another issue which is:

Each then() should return a value or throw eslint(promise/always-return)

That error resolves when adding

return null

I tried adding return null to the code when the try/catch was there to see if the issue may have just been that it was missing it, but it doesn't fix it.

An example of what this actually looks like in the code is this, I have tried what seems like everything:

Body:
I think you just need to change

try {...}
catch {...}

to

try {...}
catch(e) {...}


问:
fixing a failed ruby gem install
I am installing the ruby gem mysql-dbd on a new system which is running ruby 2.5.  The problem is that it gets a syntax error because at 2.4 ruby combined Integer and Fixed num types.

The failed install leaves the unpacked gem package on disk so I was able to examine the entrails and the fix appears to be trivial (as in insert a '#' in a statement to remove the now redundant reference to FixNum).

My question is having fixed the source how do I go about building and installing the gem?   Not being familiar with rake.

BTW the gem has long been "unsupported".

答:
You could try something like this:

```<code># install_dbd_mysql.rb

Fixnum = Integer

require 'rubygems/commands/install_command'

install = Gem::Commands::InstallCommand.new
install.handle_options ['dbd-mysql']
install.execute
</code>```

Run:

```<code>$ ruby install_dbd_mysql.rb
</code>```

Title: fixing a failed ruby gem install

Body:
You could try something like this:

# install_dbd_mysql.rb

Fixnum = Integer

require 'rubygems/commands/install_command'

install = Gem::Commands::InstallCommand.new
install.handle_options ['dbd-mysql']
install.execute

Run:

$ ruby install_dbd_mysql.rb


问:
Load Excel 2007 file with columns more than 255 columns into SQL Server table using SQL Server 2012 Import Export Wizard
I have an Excel .xlsx file that has data columns extending to 316 columns.
Each column has data specific to that column. I want to load these data into a SQL Server table.

I tried to use the SQL Import Export wizard for loading this Excel file into the SQL Server table. However the Excel is not loaded fully.The data is only loaded up to 255 columns. The columns after 255th are not getting loaded into the table.

Is there any way to load the excel with more than 300 columns into a SQL Server table

答:
Today we have many tool for make that, but if you haven't licence for SSIS or you can't buy some software ..you can try this.

Split your excel, but I prefere convert xls to csv ( is better ) ,
put a ID (equals) each csv file and load with Import Export Wizard
in diferente tables.After just with a JOIN is enough.

You can use some language , for example python with (Python SQL
driver - pyodbc /Python SQL driver - pymssql ) and make a script for
load csv , in Internet there are many examples.


问:
Saving large Pandas df of text data to disk crashes Colab due to using up all RAM. Is there a workaround?
I have a very large Pandas dataframe that I would like to save to disk to use later. The dataframe only contains string data.

However, no matter what format I use, the saving process crashes my Google Colab enviroment due to using up all available RAM, except CSV, which doesn't complete even after 5 hours.

but that also crashes the enviroment.

Is there a workaround to saving a large text pandas dataframe to disk?

I have tried to_json, to_feather, to_parquet, to_pickle, and they all crash the enviroment.

I also tried to_sql by using

```<code>from sqlalchemy import create_engine
engine = sqlalchemy.create_engine("sqlite:///database.db")
df.to_sql("table", engine)
</code>```

I would like to save my dataframe to disk within a reasonable time without crashing the enviroment.

答:
Use the chunksize argument with an appropriate number, e.g.

```<code>df.to_csv('filename.csv', chunksize=100000)
</code>```

This tells Python to convert the data into .csv 100000 lines at a time, rather than essentially store an entire second copy of your dataframe in RAM before dumping it to the disk.

Similar for .to_sql: Pandas would write in batches, rather than everything at once.

Body:
I have a very large Pandas dataframe that I would like to save to disk to use later. The dataframe only contains string data.

However, no matter what format I use, the saving process crashes my Google Colab enviroment due to using up all available RAM, except CSV, which doesn't complete even after 5 hours.

but that also crashes the enviroment.

Is there a workaround to saving a large text pandas dataframe to disk?

I have tried to_json, to_feather, to_parquet, to_pickle, and they all crash the enviroment.

I also tried to_sql by using

from sqlalchemy import create_engine
engine = sqlalchemy.create_engine("sqlite:///database.db")
df.to_sql("table", engine)

I would like to save my dataframe to disk within a reasonable time without crashing the enviroment.

Body:
Use the chunksize argument with an appropriate number, e.g.

df.to_csv('filename.csv', chunksize=100000)

This tells Python to convert the data into .csv 100000 lines at a time, rather than essentially store an entire second copy of your dataframe in RAM before dumping it to the disk.

Similar for .to_sql: Pandas would write in batches, rather than everything at once.


问:
How to Convince management to upgrade to .Net 4.0
We developed an application using .net 2.0.
We license our software which means whenever we release a new version, we have to push out the change to all our existing clients.

No one in my group has the slightest motivation to upgrade to a newer version of .net. They simple see it as more work for our support team to deploy and argue that clients will be resistant to any change.

Can anyone point me in the direction of some argument i could present to Non programmers that might sway them.

If noting else, some argument that it is safe, and will not cause our clients any harm who already have the .net 2.0 framework on their machines?

I figure it's hopeless. I'm gonna be stuck using the .net 2.0 framework until for another 4 or 5 years i bet... perhaps longer :( help!

I really want to be able to use WCF, LINQ, WPF (possible), and the option to use the Entity Framework 4.0.!

thanks

jonathan

答:
In my experience a business that doesn't keep its technology stack up-to-date loses their best developers, leaving the business with poor systems and service. Which certainly affects bottom-line.

Non-technical managers often find that difficult to grasp or understand, and are more pressured with short-term concerns.

Therefore, you'll have to emphasise the financial benefits of upgrading.

Look at how Entity-Framework, to take one example, will save time (money) writing data access code. Work out the difference between manually coding your data access layer and auto-generating code with EF. Present the cost-saving to management responsible for budgets.

If that fails and you're surrounded by people who lack any motivation to use new technology, and you really like new technology, you may need to find a more suitable job.


问:
Manage the parallel degree of sql execution
I have a process that sends a lot of commands to be executed with parallel.

exmaple of command:

```<code>Insert /*+ parallel(16) */ ...
</code>```

The problem is that if the requested parallel is higher than the available servers, the command gets downgraded in the parallel degree,
and because I send several commands togather they "steal" parallel servers from each others.

I have one specific query, that’s more important and needs to run with the requested parallel, while the other queries are less important.

Is there a way to enforce the optimizer to decrease the other statements parallel degree and increase the parallel of the important query?

Is there a way to change the parallel degree of statement after it started running?

I'm using oracle 11g.

答:
Look into statement queuing and parameters like PARALLEL_MAX_SERVERS to ensure that important processes are getting enough parallel servers.  (In my experience, setting up resource manager is too complicated, and is rarely done well.)

Statement queuing

There is no way to move parallel servers from one statement to another while they are running.  However, with statement queuing we can ask Oracle to not run an important statement until it has the necessary parallel resources.  It might be better for a large parallel process to wait a minute and get all requested parallel servers than to run immediately with only partial resources.

Use the hint /*+ parallel(16) statement_queuing*/ in the most important statements.

Make sure that the parameter PARALLEL_SERVERS_TARGET is set appropriately - statement queuing will only use parallel servers up to that number.  You may want to set that parameter to be the same as PARALLEL_MAX_SERVERS.

PARALLEL_MAX_SERVERS

Make sure that the parameter PARALLEL_MAX_SEERVERS is set appropriately.  This is a difficult value to set and I frequently see low values.  Keep in mind that Oracle parallel servers are relatively lightweight processes.  In most cases, half of the allocated servers  will only be used to store intermediate results, and won't be running.

For example, if your system has 32 cores you should set PARALLEL_MAX_SERVERS to at least 64, if not 128 or 256.  Many of DBAs incorrectly decrease the value for PARALLEL_MAX_SERVERS before testing.  Based on my experience and testing, Oracle servers can efficiently handle more parallel servers than most people realize.

Body:
I have a process that sends a lot of commands to be executed with parallel.

exmaple of command:

Insert /*+ parallel(16) */ ...

The problem is that if the requested parallel is higher than the available servers, the command gets downgraded in the parallel degree,
and because I send several commands togather they "steal" parallel servers from each others.

I have one specific query, that’s more important and needs to run with the requested parallel, while the other queries are less important.

Is there a way to enforce the optimizer to decrease the other statements parallel degree and increase the parallel of the important query?

Is there a way to change the parallel degree of statement after it started running?

I'm using oracle 11g.


问:
Revers Engineering CRC 32 in firmware
i have a p-flash (size is about 700kb) in this flash there is a CRC32. I know where it is, and i know the CRC calculation method (polynomial, initial value, final Xor Value, input and output reflected) the problem is that just a part of these 700kb are used to calculate the crc. And i don't know which part. Is there a way to find out the input data for the calculation?
I have 5 of these 700kb files. The files are all the same except 4 bytes that are different, and the 4 bytes of the crc.</p>

答:
If you can get the files onto a PC, that would help. You can xor any two of the files to get a file that is all zeroes except for the 4 different bytes and the 4 bytes of the CRC. The xor of two files will also eliminate any initial value or final xor value, as if initial value = 0 and final xor value = 0. Then check the nearly all zero file to see if the CRC matches what you would expect. If it matches, then you would know that the CRC includes the 4 non-zero bytes and all the zero bytes that follow, but you wouldn't know how far before the 4 non-zero bytes that the CRC includes in its calculation, but this would at least be a start. If it does match, that would reduce the amount of searching for what is included in the CRC calculation.

Assuming the part used for CRC is contiguous, you could do a brute force search using a fast CRC32. On a X86 with SSE2 (xmm) registers, an assembly based CRC32 could calculate a CRC32 for 700,000 bytes in about 0.0002 seconds on an Intel 3770K 3.5ghz a 3rd gen processor (they're faster now), or a bit more than 70 seconds to try lengths from 8 to 700,000 bytes.

I converted the code from this github example to Visual Studio asm, for both reflected and non-reflected CRC, using CRC32 and CRC32C polynomials, and I could upload the code if interested.

https://github.com/intel/isa-l/blob/master/crc/crc16_t10dif_01.asm

Title: Revers Engineering CRC 32 in firmware


问:
How to set fonts in a webpage that are not on Google fonts or Font Squirrel?
How do I use fonts such as Agency FB, Berlin Sans, Century Gothic etc. in my webpage which, when searched on Google fonts redirect to other sites like

https://store.typenetwork.com/foundry/fontbureau/fonts/agency-fb?src=GoogleFonts
https://www.fonts.com/font/monotype/century-gothic/regular

and if uploaded to Font Squirrel, display the following message

'Font Bureau has requested that their font Agency FB Regular be blacklisted by the Generator. You will not be able to convert this font.'

I have tried the following codes (which worked with fonts which are not of this type)

```<code>@font-face
{
    font-family: 'airstrike';
    src: url('fonts/airstrike-webfont.woff2') format('woff2'),
         url('fonts/airstrike-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}
</code>```

Please experts, help me out with this basic (but detrimental to the design of my webpage) problem as this is one of the last ones remaining in my webpage.

答:
Problem solved. I downloaded similar fonts of copyrighted originals from https://www.whatfontis.com/ took the .ttf file and uploaded it to https://www.fontsquirrel.com/ where it got converted into two files of .woff and .woff2 extensions and a sample stylesheet was provided. I just copied the code in my .css file and modified it accordingly. Here is the code i used</p>

```<code>@font-face
{
    font-family: 'agency';
    src: url('fonts/agency-webfont.woff2') format('woff2'),
        url('fonts/agency-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}
</code>```

Body:
How do I use fonts such as Agency FB, Berlin Sans, Century Gothic etc. in my webpage which, when searched on Google fonts redirect to other sites like

https://store.typenetwork.com/foundry/fontbureau/fonts/agency-fb?src=GoogleFonts
https://www.fonts.com/font/monotype/century-gothic/regular

and if uploaded to Font Squirrel, display the following message

'Font Bureau has requested that their font Agency FB Regular be blacklisted by the Generator. You will not be able to convert this font.'

I have tried the following codes (which worked with fonts which are not of this type)

@font-face
{
    font-family: 'airstrike';
    src: url('fonts/airstrike-webfont.woff2') format('woff2'),
         url('fonts/airstrike-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

Please experts, help me out with this basic (but detrimental to the design of my webpage) problem as this is one of the last ones remaining in my webpage.

Body:
Problem solved. I downloaded similar fonts of copyrighted originals from https://www.whatfontis.com/ took the .ttf file and uploaded it to https://www.fontsquirrel.com/ where it got converted into two files of .woff and .woff2 extensions and a sample stylesheet was provided. I just copied the code in my .css file and modified it accordingly. Here is the code i used

@font-face
{
    font-family: 'agency';
    src: url('fonts/agency-webfont.woff2') format('woff2'),
        url('fonts/agency-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}


问:
how to open a bootstrap4 popup on window load if the a php session variable is not set?
I want to open a bootstrap4 popup on window load event if the php session variable is not set.

```<code> session_start();
    if(!isset($_SESSION['templateid'])){
         // open popup code
    }
</code>```

how can I do this on window on load event?

答:
Well, you can create a variable that will serve as a flag for opening the pop up, something like this:

```<code>session_start();
$openPopup = (!isset($_SESSION['templateid'])) ? true : false;
</code>```

then use the value of $openPopup to check whether to open the popup or not in your script:

```<code><script>
$(function() {
    var openPopup = <?php echo $openPopup ?>;
    if(openPopup) {
        //open popup here
    }
});
</script>
</code>```

Body:
I want to open a bootstrap4 popup on window load event if the php session variable is not set.

 session_start();
    if(!isset($_SESSION['templateid'])){
         // open popup code
    }

how can I do this on window on load event?

Body:
Well, you can create a variable that will serve as a flag for opening the pop up, something like this:

session_start();
$openPopup = (!isset($_SESSION['templateid'])) ? true : false;

then use the value of $openPopup to check whether to open the popup or not in your script:

<script>
$(function() {
    var openPopup = <?php echo $openPopup ?>;
    if(openPopup) {
        //open popup here
    }
});
</script>


问:
Compare functions in haskell
I have a list of commands ([Command]) which looks like [forward 15, left 20, right 10].
I want to add forward 15 to [Command] whenever I see a forward 15 command. I used elem and == to compare whether the element is forward 15 or not but it gives me No instance for (Eq Command) arising error.
Also, in another function, I want to add [left 15, forward 15, forward 15, right 15, right 15, forward 15, forward 15, left 15] to [Command] whenever I see 4 consecutive forward 15 commands.
Thus my question is how to compare functions, because forward is a function and I can't compare it using elem or ==.

Command is defined as a type, not as a data, hence I can't use deriving Eq.

```<code>type Command = Funcs -> (Picture, Funcs)

data Funcs = Funcs {pen :: Bool, angle :: Float, point :: Point, penColor :: Color} deriving (Eq, Show)

forward :: Float -> Command
forward x = ....
</code>```

答:
I recommend making a new data type for commands, and an interpreter into the Command semantic domain. For example:

```<code>data ReifiedCommand
    = Forward Float
    | Backward Float
    | Left Float
    | Right Float
    deriving (Eq, Ord, Read, Show)

interpret :: ReifiedCommand -> Command
interpret (Forward x) = forward x
interpret (Backward x) = backward x
interpret (Left x) = left x
interpret (Right x) = right x
</code>```

Now you may compare ReifiedCommands for equality and do whatever inspection you need to do to build a suitable [ReifiedCommand], and then all at once at the end you may interpret these into a [Command] (or, more likely I think, even a single Command).

Title: Compare functions in haskell

Body:
I have a list of commands ([Command]) which looks like [forward 15, left 20, right 10].
I want to add forward 15 to [Command] whenever I see a forward 15 command. I used elem and == to compare whether the element is forward 15 or not but it gives me No instance for (Eq Command) arising error.
Also, in another function, I want to add [left 15, forward 15, forward 15, right 15, right 15, forward 15, forward 15, left 15] to [Command] whenever I see 4 consecutive forward 15 commands.
Thus my question is how to compare functions, because forward is a function and I can't compare it using elem or ==.

Command is defined as a type, not as a data, hence I can't use deriving Eq.

type Command = Funcs -> (Picture, Funcs)

data Funcs = Funcs {pen :: Bool, angle :: Float, point :: Point, penColor :: Color} deriving (Eq, Show)

forward :: Float -> Command
forward x = ....

Body:
I recommend making a new data type for commands, and an interpreter into the Command semantic domain. For example:

data ReifiedCommand
    = Forward Float
    | Backward Float
    | Left Float
    | Right Float
    deriving (Eq, Ord, Read, Show)

interpret :: ReifiedCommand -> Command
interpret (Forward x) = forward x
interpret (Backward x) = backward x
interpret (Left x) = left x
interpret (Right x) = right x

Now you may compare ReifiedCommands for equality and do whatever inspection you need to do to build a suitable [ReifiedCommand], and then all at once at the end you may interpret these into a [Command] (or, more likely I think, even a single Command).


问:
Powershell File Lock function is not opening excel File
I've written a function to check if an excel file is being used/locked by another process/user in a shared network drive, and if used, to pause the script and keep checking till it's available as the next action is to move it out of it's folder. However when I'm using System.IO to read the file, it does not open the file. I've tested on my local drive and this does open the file, but does this not work in Network Drives?

$IsLocked = $True

Function Test-IsFileLocked {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName','PSPath')]
        [string[]]$Path
    )
    Process {
           while($isLocked -eq $True){
            If ([System.IO.File]::Exists($Path)) {
                Try {
                    $FileStream = [System.IO.File]::Open($Path,'Open','Write')
                    $FileStream.Close()
                    $FileStream.Dispose()
                    $IsLocked = $False
                }  Catch {
                    $IsLocked = $True
                    echo "file in use, trying again in 10 secs.."
                    Start-Sleep -s 10

                }
            }
          }
     }
}
```

<p>This is where the code does not pick up/open the excel file in my function</p>

<pre class="lang-bsh prettyprint-override"><code>$FileStream = [System.IO.File]::Open($Path,'Open','Write')
</code>```

This is where the program calls the function.Loop through a folder of items in the network drive and if the item matches the pattern, then the function will be called to check if the file is in use:

$DirectoryWithExcelFile = Get-ChildItem -Path "Z:\NetworkDriveFolder\"
```

<pre class="lang-bsh prettyprint-override"><code>$DestinationFolder = "Z:\DestinationFolder\"
</code>```

$pattern = "abc"
foreach($file in $DirectoryWithExcelFile){

if($file.Name -match $pattern){
 Test-IsFileLocked -Path $file
 $destFolder = $DestinationFolder+$file.Name
 Move-item $file.FullName -destination $destFolder
     break
  }
}
```

答:
You have to place the close and dispose in the finally part of the try so if it throws an exception it disposes of the lock. There's no guarantee it's a file lock exception either so you are better to throw the exception, catch the exception you're expecting or write it out

```<code>$IsLocked = $True

Function Test-IsFileLocked {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName','PSPath')]
        [string]$Path
    )
    Process {
           while($isLocked -eq $True){
            If ([System.IO.File]::Exists($Path)) {
                Try {
                    $FileStream = [System.IO.File]::Open($Path,'Open','Write')
                    $IsLocked = $False
                }  Catch [System.IO.IOException] {
                    $IsLocked = $True
                    echo "file in use, trying again in 10 secs.."
                    Start-Sleep -s 10

                } Catch {
                    # source https://stackoverflow.com/questions/38419325/catching-full-exception-message
                    $formatstring = "{0} : {1}`n{2}`n" +
                                    "    + CategoryInfo          : {3}`n" +
                                    "    + FullyQualifiedErrorId : {4}`n"
                    $fields = $_.InvocationInfo.MyCommand.Name,
                              $_.ErrorDetails.Message,
                              $_.InvocationInfo.PositionMessage,
                              $_.CategoryInfo.ToString(),
                              $_.FullyQualifiedErrorId

                    $formatstring -f $fields
                    write-output $formatstring

                } finally {
                    if($FileStream) {
                        $FileStream.Close()
                        $FileStream.Dispose()
                    }
                }
            }
          }
     }
}
</code>```

Edit:
Path should be a string, not a string array unless you have multiple paths in which case rename to $Paths and loop through them  $Paths| % { $Path = $_; #do stuff here }

Body:
I've written a function to check if an excel file is being used/locked by another process/user in a shared network drive, and if used, to pause the script and keep checking till it's available as the next action is to move it out of it's folder. However when I'm using System.IO to read the file, it does not open the file. I've tested on my local drive and this does open the file, but does this not work in Network Drives?

$IsLocked = $True

Function Test-IsFileLocked {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName','PSPath')]
        [string[]]$Path
    )
    Process {
           while($isLocked -eq $True){
            If ([System.IO.File]::Exists($Path)) {
                Try {
                    $FileStream = [System.IO.File]::Open($Path,'Open','Write')
                    $FileStream.Close()
                    $FileStream.Dispose()
                    $IsLocked = $False
                }  Catch {
                    $IsLocked = $True
                    echo "file in use, trying again in 10 secs.."
                    Start-Sleep -s 10

                }
            }
          }
     }
}

This is where the code does not pick up/open the excel file in my function

$FileStream = [System.IO.File]::Open($Path,'Open','Write')

This is where the program calls the function.Loop through a folder of items in the network drive and if the item matches the pattern, then the function will be called to check if the file is in use:

$DirectoryWithExcelFile = Get-ChildItem -Path "Z:\NetworkDriveFolder\"

$DestinationFolder = "Z:\DestinationFolder\"

$pattern = "abc"
foreach($file in $DirectoryWithExcelFile){

if($file.Name -match $pattern){
 Test-IsFileLocked -Path $file
 $destFolder = $DestinationFolder+$file.Name
 Move-item $file.FullName -destination $destFolder
     break
  }
}

Body:
You have to place the close and dispose in the finally part of the try so if it throws an exception it disposes of the lock. There's no guarantee it's a file lock exception either so you are better to throw the exception, catch the exception you're expecting or write it out

$IsLocked = $True

Function Test-IsFileLocked {
    [cmdletbinding()]
    Param (
        [parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName','PSPath')]
        [string]$Path
    )
    Process {
           while($isLocked -eq $True){
            If ([System.IO.File]::Exists($Path)) {
                Try {
                    $FileStream = [System.IO.File]::Open($Path,'Open','Write')
                    $IsLocked = $False
                }  Catch [System.IO.IOException] {
                    $IsLocked = $True
                    echo "file in use, trying again in 10 secs.."
                    Start-Sleep -s 10

                } Catch {
                    # source https://stackoverflow.com/questions/38419325/catching-full-exception-message
                    $formatstring = "{0} : {1}`n{2}`n" +
                                    "    + CategoryInfo          : {3}`n" +
                                    "    + FullyQualifiedErrorId : {4}`n"
                    $fields = $_.InvocationInfo.MyCommand.Name,
                              $_.ErrorDetails.Message,
                              $_.InvocationInfo.PositionMessage,
                              $_.CategoryInfo.ToString(),
                              $_.FullyQualifiedErrorId

                    $formatstring -f $fields
                    write-output $formatstring

                } finally {
                    if($FileStream) {
                        $FileStream.Close()
                        $FileStream.Dispose()
                    }
                }
            }
          }
     }
}

Edit:
Path should be a string, not a string array unless you have multiple paths in which case rename to $Paths and loop through them  $Paths| % { $Path = $_; #do stuff here }


问:
Vue js is it ok to register all components globally?
Is it ok/good practice to register all components globally?

Reason

to avoid doing of imports of components manually when other components needed them.

a bit annoyed seeing component with lots of import when the app gets bigger.

Are there any downside of this?

答:
You generally shouldn't register a component globally if you aren't going to use it frequently throughout your application. Quoting the docs ...

Global registration often isn’t ideal. For example, if you’re using a
build system like Webpack, globally registering all components means
that even if you stop using a component, it could still be included in
your final build. This unnecessarily increases the amount of
JavaScript your users have to download.


问:
Can't get uniqueness validation test pass with shoulda matchers
I have a shoulda matcher in my achievement_spec.rb and I can't get it pass:

Spec:

```<code>- require 'rails_helper'
   RSpec.describe Achievement, type: :model do
   describe 'validations' do
     it { should validate_presence_of(:title) }
     it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you
   can't have two achievements with same title")}
     it { should validate_presence_of(:user) }
     it { should belong_to(:user) }
end
end
</code>```

Model:

```<code>- class Achievement < ActiveRecord::Base    belongs_to :user

    validates :title, presence: true
    validates :user, presence: true
    validates :title, uniqueness: {
        scope: :user_id,
        message: "you can't have two achievements with the same title"
}

    enum privacy: [ :public_access, :private_access, :friends_access ]

     def description_html
       Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(description)
end
end
</code>```

Error:

```<code>- .F..

   Failures:

     1) Achievement validations should validate that :title is
   case-sensitively unique within the scope of :user_id, producing a
   custom validation error on failure
        Failure/Error: it { should validate_uniqueness_of(:title).scoped_to(:user_id).with_message("you
   can't have two achievements with same title") }

          Achievement did not properly validate that :title is case-sensitively
          unique within the scope of :user_id, producing a custom validation error
          on failure.
            After taking the given Achievement, setting its :title to ‹"an
            arbitrary value"›, and saving it as the existing record, then making a
            new Achievement and setting its :title to ‹"an arbitrary value"› as
            well and its :user_id to a different value, ‹nil›, the matcher
            expected the new Achievement to be invalid and to produce the
            validation error "you can't have two achievements with same title" on
            :title. The record was indeed invalid, but it produced these
            validation errors instead:

            * user: ["can't be blank"]
            * title: ["you can't have two achievements with the same title"]
        # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'

   Finished in 0.16555 seconds (files took 3.13 seconds to load) 4
   examples, 1 failure

   Failed examples:

   rspec ./spec/models/achievement_spec.rb:29 # Achievement validations
   should validate that :title is case-sensitively unique within the
   scope of :user_id, producing a custom validation error on failure

   [Finished in 4.1s with exit code 1] [cmd: ['rspec', '-I
   /home/mayur/Downloads/MyWork/ruby/i-rock/spec/models',
   '/home/mayur/Downloads/MyWork/ruby/i-rock/spec/models/achievement_spec.rb']]
   [dir: /home/mayur/Downloads/MyWork/ruby/i-rock] [path:
   /usr/local/rvm/gems/ruby-2.2.4/bin:/usr/local/rvm/gems/ruby-2.2.4@global/bin:/usr/local/rvm/rubies/ruby-2.2.4/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/local/rvm/bin:/home/mayur/.local/bin:/home/mayur/bin]
</code>```

How can I get rid of above error?

I tried below solution but getting same error:

Change in model:

```<code>validates :title, uniqueness: {
        case_sensitive: false,
        scope: :user_id,
        message: "you can't have two achievements with the same title"
    }
</code>```

Change in spec:

```<code>it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }
</code>```

Error Again:

```<code>.F..

Failures:

  1) Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure
     Failure/Error: it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }

       Achievement did not properly validate that :title is case-insensitively
       unique within the scope of :user_id, producing a custom validation error
       on failure.
         After taking the given Achievement, setting its :title to ‹"an
         arbitrary value"›, and saving it as the existing record, then making a
         new Achievement and setting its :title to ‹"an arbitrary value"› as
         well and its :user_id to a different value, ‹nil›, the matcher
         expected the new Achievement to be invalid and to produce the
         validation error "you can't have two achievements with same title" on
         :title. The record was indeed invalid, but it produced these
         validation errors instead:

         * user: ["can't be blank"]
         * title: ["you can't have two achievements with the same title"]
     # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'

Finished in 0.13566 seconds (files took 3.14 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/models/achievement_spec.rb:29 # Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure
</code>```

答:
The failure is occurring due to the error message defined in your spec not matching what's in your model. You're missing the word the in your spec:

Spec

```<code>...  .with_message("you can't have two achievements with same title")}
</code>```

Model

```<code>...  message: "you can't have two achievements with the same title"
</code>```

Fixing what's defined in your spec in .with_message to match what's defined in your model within the uniqueness validation message on title should resolve the failure.

Body:
I have a shoulda matcher in my achievement_spec.rb and I can't get it pass:

Spec:

- require 'rails_helper'
   RSpec.describe Achievement, type: :model do
   describe 'validations' do
     it { should validate_presence_of(:title) }
     it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you
   can't have two achievements with same title")}
     it { should validate_presence_of(:user) }
     it { should belong_to(:user) }
end
end

Model:

- class Achievement < ActiveRecord::Base    belongs_to :user

    validates :title, presence: true
    validates :user, presence: true
    validates :title, uniqueness: {
        scope: :user_id,
        message: "you can't have two achievements with the same title"
}

    enum privacy: [ :public_access, :private_access, :friends_access ]

     def description_html
       Redcarpet::Markdown.new(Redcarpet::Render::HTML).render(description)
end
end

Error:

- .F..

   Failures:

     1) Achievement validations should validate that :title is
   case-sensitively unique within the scope of :user_id, producing a
   custom validation error on failure
        Failure/Error: it { should validate_uniqueness_of(:title).scoped_to(:user_id).with_message("you
   can't have two achievements with same title") }

          Achievement did not properly validate that :title is case-sensitively
          unique within the scope of :user_id, producing a custom validation error
          on failure.
            After taking the given Achievement, setting its :title to ‹"an
            arbitrary value"›, and saving it as the existing record, then making a
            new Achievement and setting its :title to ‹"an arbitrary value"› as
            well and its :user_id to a different value, ‹nil›, the matcher
            expected the new Achievement to be invalid and to produce the
            validation error "you can't have two achievements with same title" on
            :title. The record was indeed invalid, but it produced these
            validation errors instead:

            * user: ["can't be blank"]
            * title: ["you can't have two achievements with the same title"]
        # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'

   Finished in 0.16555 seconds (files took 3.13 seconds to load) 4
   examples, 1 failure

   Failed examples:

   rspec ./spec/models/achievement_spec.rb:29 # Achievement validations
   should validate that :title is case-sensitively unique within the
   scope of :user_id, producing a custom validation error on failure

   [Finished in 4.1s with exit code 1] [cmd: ['rspec', '-I
   /home/mayur/Downloads/MyWork/ruby/i-rock/spec/models',
   '/home/mayur/Downloads/MyWork/ruby/i-rock/spec/models/achievement_spec.rb']]
   [dir: /home/mayur/Downloads/MyWork/ruby/i-rock] [path:
   /usr/local/rvm/gems/ruby-2.2.4/bin:/usr/local/rvm/gems/ruby-2.2.4@global/bin:/usr/local/rvm/rubies/ruby-2.2.4/bin:/usr/lib64/qt-3.3/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/usr/sbin:/usr/local/rvm/bin:/home/mayur/.local/bin:/home/mayur/bin]

How can I get rid of above error?

I tried below solution but getting same error:

Change in model:

validates :title, uniqueness: {
        case_sensitive: false,
        scope: :user_id,
        message: "you can't have two achievements with the same title"
    }

Change in spec:

it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }

Error Again:

.F..

Failures:

  1) Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure
     Failure/Error: it { should validate_uniqueness_of(:title).case_insensitive.scoped_to(:user_id).with_message("you can't have two achievements with same title") }

       Achievement did not properly validate that :title is case-insensitively
       unique within the scope of :user_id, producing a custom validation error
       on failure.
         After taking the given Achievement, setting its :title to ‹"an
         arbitrary value"›, and saving it as the existing record, then making a
         new Achievement and setting its :title to ‹"an arbitrary value"› as
         well and its :user_id to a different value, ‹nil›, the matcher
         expected the new Achievement to be invalid and to produce the
         validation error "you can't have two achievements with same title" on
         :title. The record was indeed invalid, but it produced these
         validation errors instead:

         * user: ["can't be blank"]
         * title: ["you can't have two achievements with the same title"]
     # ./spec/models/achievement_spec.rb:29:in `block (3 levels) in <top (required)>'

Finished in 0.13566 seconds (files took 3.14 seconds to load)
4 examples, 1 failure

Failed examples:

rspec ./spec/models/achievement_spec.rb:29 # Achievement validations should validate that :title is case-insensitively unique within the scope of :user_id, producing a custom validation error on failure

Body:
The failure is occurring due to the error message defined in your spec not matching what's in your model. You're missing the word the in your spec:

Spec

...  .with_message("you can't have two achievements with same title")}

Model

...  message: "you can't have two achievements with the same title"

Fixing what's defined in your spec in .with_message to match what's defined in your model within the uniqueness validation message on title should resolve the failure.


问:
What are the implications of the recursive joining of Promises in terms of Monads?
I know that Javascript's promises are technically neither functors nor monads in the sense of Haskell, because (among other things)

they include a bind operation that falls back to map when a pure function is passed in (and thus has an ambiguous type)

both the Promise constructor and resolve (aka return) join nested promises recursively

The first issue can easily be bypassed by always providing a function with the right type a -> Promise b.

The second issue obviously violates the parametricity trait of parametric polymorphic functions, i.e. one cannot construct a m (m a) structure. But what would this structure mean in the context of promises/asynchronous computations? I cannot think of a meaningful semantics for Promise (Promise a), where Promise is a monad. So what do we lose? What are the implications of the recursive joining?

Provided we are pretty pragmatic (and that's what we should be when we're programming Javascript), can't we claim that a Promise is a monad in Javascript if we take care of the edge cases?

答:
I know that Javascript's promises are technically neither functors nor monads in the sense of Haskell

Not only in the sense of Haskell, in any other way as well.

they include a bind operation that falls back to map when a pure function is passed in (and thus has an ambiguous type)

there is no bind operator provided by JS native promises

both the Promise constructor and resolve (aka return) join nested promises recursively

I presume you mean unwrapping "theneables", i.e. calling functions stored under then prop whenever there is such function.

The first issue can easily be bypassed by always providing a function with the right type a -> Promise b.

This would not resemble map e.g. when map(f) is used for
f = x => {then: a => a}.

The second issue obviously violates the parametricity trait of parametric polymorphic functions, i.e. one cannot construct a m (m a) structure.

Indeed.

But what would this structure mean in the context of promises/asynchronous computations? I cannot think of a meaningful semantics for Promise (Promise a), where Promise is a monad. So what do we lose? What are the implications of the recursive joining?

You need to allow storing arbitrary values. Promises are not allowed to store theneables (without unwrapping), which is the problem. So you need to change semantics of both objects and methods. Allow objects to store theneables without change and implement .bind aka .chain that unwraps (or joins) theneables precisely once - no recursion.

This is what creed does for promise-like objects and cpsfy for callback-based (aka continuation passing style) functions.

Provided we are pretty pragmatic (and that's what we should be when we're programming Javascript), can't we claim that a Promise is a monad in Javascript if we take care of the edge cases?

Writing safe, succinct and composable code is pragmatic. Risking introduce subtle bugs via leaky abstractions that might crash critical software with far going consequences is not.
Every edge case is a potential source of such risk.

In that respect, claiming that Promise is a monad does more harm than help, beside being incorrect. It does harm because you cannot safely apply monadic transformations to promises. E.g. it is unsafe to use any code conforming to the monadic interface with promises as if they were monads. If used correctly, monads are there to help abstracting and reusing your code, not to introduce lines of checking and hunting for edge cases.


问:
Move angular Project to another folder gave me error
I've created an angular application though angular cli, when I've moved it to another location it didn't work and I've to fix all issues I've found while running npm install, is this valid or am I missing a step, also when production this will be the case as well? ,
EDIT:
error like: module '@data' is missing</p>

答:
attempt 1
I used 'ng new newprojectname' and then merged the original SRC folder into the new SRC folder, can't compile successfully when 'ng serve' runs

attempt 2
I tried creating the project folder first, copied in the SRC folder and the e2e folder and the files in the root of the project folder.  Ran 'NPM install' .  And when I run 'ng serve' it tells me that "the serve command must be run in an angular project, but a project definition cannot be found."
ran 'ng update @angular/cli' and then got the following when running ng serve...
This version of CLI is only compatible with Angular versions ^8.0.0-beta || >=8.0.0 <9.0.0,
but Angular version 7.2.15 was found instead.

Please visit the link below to find instructions on how to update Angular.
https://angular-update-guide.firebaseapp.com/

getting closer to fixing this I hope

ran 'ng update @angular/cli @angular/core' and that got me back to where I need to be...
okay, it can 'see' the project now and tries to compile it, albeit there is an error with a promise response, I may need to update that code for v8


问:
convert lists to data frames
I'm a beginner in R. I'm working in a data to expand my knowledge especially in data manipulation.

The task is to split my data set based on a parameter(column). Then to calculate the standard deviation for each group, then to provide some graphs. I did split my data set to about 3000 list, but I'm stuck in converting the lists into separate data sets so I can collect the SD for each data set. Or if there is an efficient way to do it in one code.

this is what I did so far.

```<code>xx <- read.table("NetworkRail1.csv",sep=",",header=TRUE)

selected <- select(xx,ID, Location, Top70m)

splitNR <- split(selected, selected$Location %% 0.125)
</code>```

答:
If your problem is to save the different components of the list separately, you can try this:</p>

```<code>list2env(splitNR, envir=.GlobalEnv)
</code>```

Title: convert lists to data frames

Body:
I'm a beginner in R. I'm working in a data to expand my knowledge especially in data manipulation.

The task is to split my data set based on a parameter(column). Then to calculate the standard deviation for each group, then to provide some graphs. I did split my data set to about 3000 list, but I'm stuck in converting the lists into separate data sets so I can collect the SD for each data set. Or if there is an efficient way to do it in one code.

this is what I did so far.

xx <- read.table("NetworkRail1.csv",sep=",",header=TRUE)

selected <- select(xx,ID, Location, Top70m)

splitNR <- split(selected, selected$Location %% 0.125)

Body:
If your problem is to save the different components of the list separately, you can try this:

list2env(splitNR, envir=.GlobalEnv)


问:
jQuery Datepicker Expiration date
I am using jQuery UI's Datepicker plugin. When the user logs in, I need to display an error message once the Expiration Date becomes past due. I tried adding the if statement below, but it isn't working. Any ideas?</p>

```<code>    $("#expDate").datepicker({
        changeMonth: true,
        changeYear: true,
        minDate: 0
    });

   if (Date.parse(expDate) < jQuery.now()) {
      $("#expDate").addClass("error");// . for class  expDate
  }
</code>```

答:
Expire date validation using jQuery

Gemfile:

```<code>gem 'bootstrap-datepicker-rails'
</code>```

application.js

```<code>//= require datapicker/bootstrap-datepicker.js
</code>```

application.css.scss

```<code>*= require datapicker/datepicker3.css
</code>```

application.js:

```<code>    $(document).ready(function(){

      $('.datepicker').datepicker({
        format: "yy-mm-dd",
        startDate: new Date('2019-1-1'),
        endDate: new Date('2025-12-31')
      });
    };

});
</code>```

Title: jQuery Datepicker Expiration date

Body:
I am using jQuery UI's Datepicker plugin. When the user logs in, I need to display an error message once the Expiration Date becomes past due. I tried adding the if statement below, but it isn't working. Any ideas?

    $("#expDate").datepicker({
        changeMonth: true,
        changeYear: true,
        minDate: 0
    });

   if (Date.parse(expDate) < jQuery.now()) {
      $("#expDate").addClass("error");// . for class  expDate
  }

Body:
Expire date validation using jQuery

Gemfile:

gem 'bootstrap-datepicker-rails'

application.js

//= require datapicker/bootstrap-datepicker.js

application.css.scss

*= require datapicker/datepicker3.css

application.js:

    $(document).ready(function(){

      $('.datepicker').datepicker({
        format: "yy-mm-dd",
        startDate: new Date('2019-1-1'),
        endDate: new Date('2025-12-31')
      });
    };

});


问:
How to rename migrations table in entity framework?
I would like rename the migrations table from dbo.__MigrationHistory to SYSTEM.MigrationsHistory. How can I do it?

I need inherit from IdentityDbContext not from HistoryContextfor this reason I can't use the code: modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM")

I attach the code that I am using:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // ACCOUNT
            modelBuilder.Entity<ApplicationUser>().ToTable(tableName: "Users", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationRole>().ToTable(tableName: "Roles", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserLogin>().ToTable(tableName: "UserLogins", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserRole>().ToTable(tableName: "UserRoles", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserClaim>().ToTable(tableName: "UserClaims", schemaName: "ACCOUNT");

            // SYSTEM
            // modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM");
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }
```

Thanks in advance

Regards

答:
Steps for rename migrations table

Create class MyHistoryContext:

    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.Migrations.History;

    namespace CustomizableMigrationsHistoryTableSample
    {
        public class MyHistoryContext : HistoryContext
        {
            public MyHistoryContext(DbConnection dbConnection, string defaultSchema)
                : base(dbConnection, defaultSchema)
            {
            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM");
            }
        }
    }

```

<ol start="2">
<li>Create class <code>ModelConfiguration</code></li>
</ol>

<pre class="lang-cs prettyprint-override"><code>    using System.Data.Entity;

    namespace CustomizableMigrationsHistoryTableSample
    {
        public class ModelConfiguration : DbConfiguration
        {
            public ModelConfiguration()
            {
                this.SetHistoryContext("System.Data.SqlClient",
                    (connection, defaultSchema) => new MyHistoryContext(connection, defaultSchema));
            }
        }
    }
</code>```

If you have existing migrations, you will need to delete migrations and database for execute the next commands:

For create migrations folder and configuration class:

enable-migrations
```

<p>For add migration <code>first_migration</code></p>

<pre class="lang-sh prettyprint-override"><code>add-migration <migration_name>
</code>```

For apply migration(s) in data base

update-database
```

Credits: Ivan Stoev

Before you start you need to know that you can customize the migrations history table only before you apply the first migration..

Detailed information:
Customizing the migrations history table

Body:
I would like rename the migrations table from dbo.__MigrationHistory to SYSTEM.MigrationsHistory. How can I do it?

I need inherit from IdentityDbContext not from HistoryContextfor this reason I can't use the code: modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM")

I attach the code that I am using:

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, long, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
        public ApplicationDbContext()
            : base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // ACCOUNT
            modelBuilder.Entity<ApplicationUser>().ToTable(tableName: "Users", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationRole>().ToTable(tableName: "Roles", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserLogin>().ToTable(tableName: "UserLogins", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserRole>().ToTable(tableName: "UserRoles", schemaName: "ACCOUNT");
            modelBuilder.Entity<ApplicationUserClaim>().ToTable(tableName: "UserClaims", schemaName: "ACCOUNT");

            // SYSTEM
            // modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM");
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }
    }

Thanks in advance

Regards

Body:
Steps for rename migrations table

Create class MyHistoryContext:

    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.Migrations.History;

    namespace CustomizableMigrationsHistoryTableSample
    {
        public class MyHistoryContext : HistoryContext
        {
            public MyHistoryContext(DbConnection dbConnection, string defaultSchema)
                : base(dbConnection, defaultSchema)
            {
            }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                base.OnModelCreating(modelBuilder);
                modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistory", schemaName: "SYSTEM");
            }
        }
    }

Create class ModelConfiguration

    using System.Data.Entity;

    namespace CustomizableMigrationsHistoryTableSample
    {
        public class ModelConfiguration : DbConfiguration
        {
            public ModelConfiguration()
            {
                this.SetHistoryContext("System.Data.SqlClient",
                    (connection, defaultSchema) => new MyHistoryContext(connection, defaultSchema));
            }
        }
    }

If you have existing migrations, you will need to delete migrations and database for execute the next commands:

For create migrations folder and configuration class:

enable-migrations

For add migration first_migration

add-migration <migration_name>

For apply migration(s) in data base

update-database

Credits: Ivan Stoev

Before you start you need to know that you can customize the migrations history table only before you apply the first migration..

Detailed information:
Customizing the migrations history table


问:
fgets() issues with for loop in C
Why am I getting the following output when fgets is outside for loop:

Jim, Engineer

Jim, Engineer

Jim, Engineer

Jim, Engineer

and the following output when fgets is inside for loop:

Jim, Engineer

Pam, Nurse

Scar, Troublemaker

John, Smith

```<code>int main()
{
    int i;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    for (i=0; i < 4; i++){
        fgets(line, 255, fpointer);
        printf("%s", line);
    }
    fclose(fpointer);

    return 0
}
</code>```

within fget(), "i" is not passed as an argument so how is it still iterating over each line in the .txt file?

答:
While you already have a fine answer explaining the movement of the file position indicator with a file-stream each time a call to fgets() (or any other input function is made), one additional necessary point not to be overlooked is to Always check the return of the input function to ensure the call succeeded before using the information read.

In your case, when using the for loop, if there are less then 4 lines in the file, or if a stream-error occurs, you blindly pass the line to printf for output without ever knowing if it contains valid data. This is an invitation for Undefined Behavior. Always check the return.

When reading data, you generally want to control the input loop with the read function itself. In other cases, such as when requesting specific user input, you want to loop continually until the needed information is provided. In both cases you are checking and using the return of the input function to determine whether the loop continues.

To read all lines in the file, presuming that was your input, you would simply do:

```<code>#include <stdio.h>
#include <string.h>

int main()
{
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    while (fgets(line, 255, fpointer)) {    /* control read loop with fgets */
        line[strcspn (line, "\r\n")] = 0;   /* trim \n from end of line */
        puts (line);
    }
    fclose(fpointer);

    return 0;
}
</code>```

If your intent is to read a specific number of lines, then simply include a counter, e.g. to read 4 lines:

```<code>int main()
{
    size_t n = 0;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    /* control read loop with counter and fgets */
    while (n < 4 && fgets(line, 255, fpointer)) {
        line[strcspn (line, "\r\n")] = 0;   /* trim \n from end of line */
        puts (line);
        n++;
    }
    fclose(fpointer);

    return 0;
}
</code>```

That way you have incorporated the return of fgets() and your line-count into the loop conditional.

(note: the use of strcspn, which returns the number of characters in the string NOT part of the exclude set "\r\n", provides the length of the string excluding the line-ending allowing you to simply overwrite the first line-ending character with '\0' or its numeric equivalent 0. It essentially does the following:)

```<code>        size_t len = strlen (line);
        if (len && len - 1 == '\n')
            line[--len] = 0;        /* trim \n from end of line */
</code>```

Let me know if you have further questions.

Title: fgets() issues with for loop in C

Body:
Why am I getting the following output when fgets is outside for loop:

Jim, Engineer

Jim, Engineer

Jim, Engineer

Jim, Engineer

and the following output when fgets is inside for loop:

Jim, Engineer

Pam, Nurse

Scar, Troublemaker

John, Smith

int main()
{
    int i;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    for (i=0; i < 4; i++){
        fgets(line, 255, fpointer);
        printf("%s", line);
    }
    fclose(fpointer);

    return 0
}

within fget(), "i" is not passed as an argument so how is it still iterating over each line in the .txt file?

Body:
While you already have a fine answer explaining the movement of the file position indicator with a file-stream each time a call to fgets() (or any other input function is made), one additional necessary point not to be overlooked is to Always check the return of the input function to ensure the call succeeded before using the information read.

In your case, when using the for loop, if there are less then 4 lines in the file, or if a stream-error occurs, you blindly pass the line to printf for output without ever knowing if it contains valid data. This is an invitation for Undefined Behavior. Always check the return.

When reading data, you generally want to control the input loop with the read function itself. In other cases, such as when requesting specific user input, you want to loop continually until the needed information is provided. In both cases you are checking and using the return of the input function to determine whether the loop continues.

To read all lines in the file, presuming that was your input, you would simply do:

#include <stdio.h>
#include <string.h>

int main()
{
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    while (fgets(line, 255, fpointer)) {    /* control read loop with fgets */
        line[strcspn (line, "\r\n")] = 0;   /* trim \n from end of line */
        puts (line);
    }
    fclose(fpointer);

    return 0;
}

If your intent is to read a specific number of lines, then simply include a counter, e.g. to read 4 lines:

int main()
{
    size_t n = 0;
    char line[255];
    FILE *fpointer = fopen("employees.txt", "r");

    /* control read loop with counter and fgets */
    while (n < 4 && fgets(line, 255, fpointer)) {
        line[strcspn (line, "\r\n")] = 0;   /* trim \n from end of line */
        puts (line);
        n++;
    }
    fclose(fpointer);

    return 0;
}

That way you have incorporated the return of fgets() and your line-count into the loop conditional.

(note: the use of strcspn, which returns the number of characters in the string NOT part of the exclude set "\r\n", provides the length of the string excluding the line-ending allowing you to simply overwrite the first line-ending character with '\0' or its numeric equivalent 0. It essentially does the following:)

        size_t len = strlen (line);
        if (len && len - 1 == '\n')
            line[--len] = 0;        /* trim \n from end of line */

Let me know if you have further questions.