问:
Running out of disk space EC2
I ran into some issues with my EC2 micro instance and had to terminate it and create a new one in its place. But it seems even though the old instance is no longer visible in the list, it is still using up some space on my disk. My df -h is listed below:

```<code>Filesystem    Size    Used    Avail    Use%

/dev/xvda1    7.8G    7.0G    719M     91% /
</code>```

When I go to the EC22 console I see there are 3 volumes each 8gb in the list. One of them is attached (/dev/xvda) and this one is showing as "in-use". The other 2 are simply showing as "Available"

Is the terminated instance really using up my disk space? If yes, how to free it up?

答:
These 2 steps add an extra hard drive to your EC2 and format it for use:

Attach an extra hard drive (EBS: Elastic Block Storage) to an EC2

Format an EBS drive attached to an EC2

Here's pricing info.  Free Tier includes 30GB.  Afterward it's $1.25/month for 10GB on a General Purpose SSD (gp2).

To see how much space you are using/need:

Check your current disk use/available in Linux with df -h.

Check the size of a directory in Linux with du -sh [path].

Title: Running out of disk space EC2

Body:
I ran into some issues with my EC2 micro instance and had to terminate it and create a new one in its place. But it seems even though the old instance is no longer visible in the list, it is still using up some space on my disk. My df -h is listed below:

Filesystem    Size    Used    Avail    Use%

/dev/xvda1    7.8G    7.0G    719M     91% /

When I go to the EC22 console I see there are 3 volumes each 8gb in the list. One of them is attached (/dev/xvda) and this one is showing as "in-use". The other 2 are simply showing as "Available"

Is the terminated instance really using up my disk space? If yes, how to free it up?


来源: stackexchange

问:
Does `cor()` only work for numeric variables?
I'm interested in the correlation of x with y. x is an ordinal (Likert-type) variable. y is a continuous variable.

But when I use cor(x, y, method = "spearman") I get an error saying

'x' must be numeric`

Spearman's rho doesn't necessarily require x to be numeric. So I wonder how I can run this function?

set.seed(0)

x <- sample(c("None", "Little", "Often", "Always"), 20, replace = TRUE)
y <- round(runif(length(x), 100, 300))
data <- data.frame(subject=seq_len(length(x)), x, y)

cor(x, y, method = "spearman") # Error: 'x' must be numeric

#data:
   subject      x   y
1        1 Little 255
2        2   None 287
3        3 Always 142
4        4  Often 230
5        5   None 125
6        6 Little 153
7        7   None 177
8        8  Often 103
9        9  Often 176
10      10 Little 274
11      11 Little 168
12      12  Often 196
13      13  Often 220
14      14   None 199
15      15   None 137
16      16   None 265
17      17 Little 234
18      18 Little 259
19      19 Little 122
20      20 Little 245
```

答:
You can recode the values:</p>
```<code>data <- data %>% mutate(x2 = recode(x, "None" = 0, "Little" =1 , "Often"=2, "Always"=3))
cor(data$x2, data$y, method = "spearman")
[1] -0.1930743
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can recode the values:

data <- data %>% mutate(x2 = recode(x, "None" = 0, "Little" =1 , "Often"=2, "Always"=3))
cor(data$x2, data$y, method = "spearman")
[1] -0.1930743


问:
JSON Parse error: Unexpected identifier "undefined"
i just switched to a mac today and i noticed the JSON.parse that works on other browsers, throws this error on safari.

```<code>Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
</code>```

This is the JSON response from my PHP code

```<code>   {"dataPointsX": "[\"31 Jan\",\"01 Feb\",\"02 Feb\",\"03 Feb\",\"04 Feb\",\"05 Feb\",\"06 Feb\"]", "dataPointsY": "[\"0\",\"0\",\"7287\",\"24572\",\"30657\",\"27865\",\"0\"]", "dataPoints2Y": "[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]"}
</code>```

This is my Javascript code

```<code>$.get('chartdata.php', async function (res) {
   console.log(res)
   var res = JSON.parse(res);
});
</code>```

Please help

UPDATE

I have updated my PHP to echo this

```<code>{"dataPointsX":["31 Jan","01 Feb","02 Feb","03 Feb","04 Feb","05 Feb","06 Feb"],"dataPointsY":["0","0","7287","24572","30632","27820","0"],"dataPoints2Y":["0","0","0","0","0","0","0"]}
</code>```

It works on chrome, safari still throwing this error

```<code>Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
</code>```

Console.log(JSON.parse(res)) shows this on chrome

```<code>dataPoints2Y: (7) ['0', '0', '0', '0', '0', '0', '0']
dataPointsX: (7) ['31 Jan', '01 Feb', '02 Feb', '03 Feb', '04 Feb', '05 Feb', '06 Feb']
dataPointsY: (7) ['0', '0', '7287', '24572', '30489', '27744', '0']
[[Prototype]]: Object
</code>```

答:
It looks like your PHP code is JSON encoding content that's already JSON encoded, maybe something like this:

```<code>$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => json_encode($points)]);
</code>```

This yields the oddly quoted string:

```<code>{"dataPointsX":"[\"31 Jan\",\"01 Feb\",\"03 Feb\"]"}
</code>```

You only want to call json_encode() once:

```<code>$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => $points]);
</code>```

Body:
i just switched to a mac today and i noticed the JSON.parse that works on other browsers, throws this error on safari.

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

This is the JSON response from my PHP code

   {"dataPointsX": "[\"31 Jan\",\"01 Feb\",\"02 Feb\",\"03 Feb\",\"04 Feb\",\"05 Feb\",\"06 Feb\"]", "dataPointsY": "[\"0\",\"0\",\"7287\",\"24572\",\"30657\",\"27865\",\"0\"]", "dataPoints2Y": "[\"0\",\"0\",\"0\",\"0\",\"0\",\"0\",\"0\"]"}

This is my Javascript code

$.get('chartdata.php', async function (res) {
   console.log(res)
   var res = JSON.parse(res);
});

Please help

UPDATE

I have updated my PHP to echo this

{"dataPointsX":["31 Jan","01 Feb","02 Feb","03 Feb","04 Feb","05 Feb","06 Feb"],"dataPointsY":["0","0","7287","24572","30632","27820","0"],"dataPoints2Y":["0","0","0","0","0","0","0"]}

It works on chrome, safari still throwing this error

Unhandled Promise Rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"

Console.log(JSON.parse(res)) shows this on chrome

dataPoints2Y: (7) ['0', '0', '0', '0', '0', '0', '0']
dataPointsX: (7) ['31 Jan', '01 Feb', '02 Feb', '03 Feb', '04 Feb', '05 Feb', '06 Feb']
dataPointsY: (7) ['0', '0', '7287', '24572', '30489', '27744', '0']
[[Prototype]]: Object

Body:
It looks like your PHP code is JSON encoding content that's already JSON encoded, maybe something like this:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => json_encode($points)]);

This yields the oddly quoted string:

{"dataPointsX":"[\"31 Jan\",\"01 Feb\",\"03 Feb\"]"}

You only want to call json_encode() once:

$points = ['31 Jan', '01 Feb', '03 Feb'];
echo json_encode(['dataPointsX' => $points]);


问:
Generate table from diagram in MagicDraw
I see that Magic Draw supports both graphical and tabular notations. However, I would like to know if they can be synchronized to one another or they only function separately. So, if I create a class diagram with the graphical editor, can I generate a table from it in MagicDraw? And whenever I make the changes to one editor, the changes to be reflected in the other editor?

Thank you!

答:
The answer is complex.

First, diagrams are views of the model. Tables, as just another kind of diagrams, are therefore views of the model. In other words, changing an element in a table will change the element in any diagram it is displayed.

Now it gets complex - but how you use the tool can simplify the. You seemed to ask, can a table be synchronized with a table and a table with a diagram? A table can be based on a scope, a query, or by composition (drag an element onto the table or create on the table). Scope or query is is a lot better because they can be used to match the diagram or package where the diagram puts its data (by default, the package where the diagram is stored).

However, diagrams are intended to be expressions of the human for us humans. Thus the diagram does not automatically add elements if they were added in a table.

How do we square the circle? How do we add (or even detect) an element created on a diagram? There is a way to get a list of diagrams (https://community.nomagic.com/usage-in-diagram-displayed-in-generic-table-t5789.html ). Using a similar technique a rule could be created to warn about elements that are not on any diagram. It is still up to you to add the element to the diagram with this information at hand (or write a fancy plugin).


答:
Spearman's rho does require that the data be ordered, which characters are not and even regular factors are not (this is a little bit subtle — they do have an ordering which is used when listing factor levels, plotting, etc., but this ordering is not assumed to have any statistical meaning). It would make sense if cor() allowed ordered factors (factor(..., ordered = TRUE) or ordered(...), but it doesn't. As ?cor says:

The inputs must be numeric (as determined by ‘is.numeric’: logical
values are also allowed for historical compatibility): the
‘"kendall"’ and ‘"spearman"’ methods make sense for ordered inputs
but ‘xtfrm’ can be used to find a suitable prior transformation to
numbers.

However, assuming that you have a factor variable and the order of levels is what you want, then using as.integer() in cor() should work fine.  (In fact, the xtfrm.factor() method is just a wrapper for as.integer().)

xf <- ordered(x, levels = c("None", "Little", "Often", "Always"))
cor(as.integer(xf), y, method = "spearman")
## or
cor(xtfrm(xf), y, method = "spearman")
```

Title: Does `cor()` only work for numeric variables?

Body:
I'm interested in the correlation of x with y. x is an ordinal (Likert-type) variable. y is a continuous variable.

But when I use cor(x, y, method = "spearman") I get an error saying

'x' must be numeric`

Spearman's rho doesn't necessarily require x to be numeric. So I wonder how I can run this function?

set.seed(0)

x <- sample(c("None", "Little", "Often", "Always"), 20, replace = TRUE)
y <- round(runif(length(x), 100, 300))
data <- data.frame(subject=seq_len(length(x)), x, y)

cor(x, y, method = "spearman") # Error: 'x' must be numeric

#data:
   subject      x   y
1        1 Little 255
2        2   None 287
3        3 Always 142
4        4  Often 230
5        5   None 125
6        6 Little 153
7        7   None 177
8        8  Often 103
9        9  Often 176
10      10 Little 274
11      11 Little 168
12      12  Often 196
13      13  Often 220
14      14   None 199
15      15   None 137
16      16   None 265
17      17 Little 234
18      18 Little 259
19      19 Little 122
20      20 Little 245


问:
How to set username in Firebase auth
Hello how can I set username on Signup for Firebase User. I use firebase Authentication API. I thought about try / catch block and setting User properties like

```<code>const user = auth.currentUser;
user.name = 'John123'
</code>```

Is it possible?

```<code>const onSubmitHandler = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        createUserWithEmailAndPassword(auth, email, password)

    }
</code>```

答:
Firebase Authentication has a display name for each user, which can be whatever you want it to be. To set it, call updateProfile as shown in the documentation on updating the user's profile:

```<code>await createUserWithEmailAndPassword(auth, email, password);
updateProfile(auth.currentUser, {
  displayName: "John123"
})
</code>```

Title: How to set username in Firebase auth

Body:
Hello how can I set username on Signup for Firebase User. I use firebase Authentication API. I thought about try / catch block and setting User properties like

const user = auth.currentUser;
user.name = 'John123'

Is it possible?

const onSubmitHandler = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        createUserWithEmailAndPassword(auth, email, password)

    }

Body:
Firebase Authentication has a display name for each user, which can be whatever you want it to be. To set it, call updateProfile as shown in the documentation on updating the user's profile:

await createUserWithEmailAndPassword(auth, email, password);
updateProfile(auth.currentUser, {
  displayName: "John123"
})


问:
Really dumb question about what's more efficient than elif spam and dictionaries
My code needs to check which product/thing a number corresponds to.

Which means if I input a number, I need to know which product it corresponds to.

As far as I know, I have no idea how to do this other than elif spamming, but that makes a huge mess with a massive wall of elifs.

I've also tried reading into python dictionaries but my small brain doesn't comprehend how to pick out the value if I only have the key.

I feel like dictionaries were made for this but I still can't figure out how it works.

Is there a way to be more efficient in finding what product == number if I only have the number and a list of objects?
Example:

```<code>if thing == 1:
    print("a")
elif thing == 2:
    print("b")
elif thing == 3:
    print("c")
</code>```

and so on

答:
The solution with dictionaries you are struggling with is</p>
```<code>things = {1: "a", 2: "b", 3: "c"}

print(things[thing])
</code>```

Body:
My code needs to check which product/thing a number corresponds to.

Which means if I input a number, I need to know which product it corresponds to.

As far as I know, I have no idea how to do this other than elif spamming, but that makes a huge mess with a massive wall of elifs.

I've also tried reading into python dictionaries but my small brain doesn't comprehend how to pick out the value if I only have the key.

I feel like dictionaries were made for this but I still can't figure out how it works.

Is there a way to be more efficient in finding what product == number if I only have the number and a list of objects?
Example:

if thing == 1:
    print("a")
elif thing == 2:
    print("b")
elif thing == 3:
    print("c")

and so on

Body:
The solution with dictionaries you are struggling with is

things = {1: "a", 2: "b", 3: "c"}

print(things[thing])


问:
NextJS component level SASS styling
I am working on a simple NextJS app, but I am having trouble with component level styling using SASS/SCSS. Everything looks fine when the user first lands on the page, but when the user navigates to a page /about for example or from /about to /, the component styles didn't get render, the user needs to refresh the page to see the styles

⚙ SETTINGS

./package.json

```<code>"dependencies": {
  "@zeit/next-css": "1.0.1",
  "@zeit/next-sass": "1.0.1",
  "autoprefixer": "^9.7.0",
  "next": "^9.3.1",
  "node-sass": "4.13.1",
  "react": "^16.13.0",
  "react-dom": "^16.13.0",
  "webpack": "^4.42.0"
}
</code>```

./next.config.js

```<code>const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withCss(
  withSass({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
          },
        },
      });
      return config;
    },
  }),
);
</code>```

./postcss.config.js

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

module.exports = {
  plugins: [autoprefixer],
};
</code>```

 PAGES

./pages/index.js

```<code>import React from 'react';
import Layout from '../components/Layout';
import Home from '../components/Home';

class Index extends React.PureComponent {
  render() {
    <Layout>
      <Home />
    </Layout>
  }
}

export default Index;
</code>```

./pages/about.js

```<code>import React from 'react';
import Layout from '../components/Layout';
import Company from '../components/Company';

class About extends React.PureComponent {
  render() {
    <Layout>
      <Company />
    </Layout>
  }
}

export default About;
</code>```

 COMPONENTS

./components/Layout.js

```<code>import React from 'react';
import AppBar from '../AppBar/AppBar';
import './Layout.scss';

class Layout extends React.PureComponent {
  render() {
    const { children } = this.props;

    return (
      <>
        <AppBar />
        <main className="Layout">
          {children}
        </main>
      </>
    );
  }
}

export default Layout;
</code>```

./components/Layout.scss

```<code>.Layout {
  background: #f00;
}
</code>```

./components/AppBar.js

```<code>import Link from 'next/link';
import './AppBar.scss';

export default () => (
  <header className="AppBar">
    <Link href="/">
      <a>Home</a>
    </Link>
    <Link href="/about">
      <a>About</a>
    </Link>
  </header>
)
</code>```

./components/AppBar.scss

```<code>.AppBar {
  background: #0f0;
}
</code>```

./components/Home.js

```<code>import './Home.scss';

export default () => (
  <div className="Home">Home</div>
)
</code>```

./components/Home.scss

```<code>const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withCss(
  withSass({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
          },
        },
      });
      return config;
    },
  }),
);
</code>```0

./components/Company.js

```<code>const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withCss(
  withSass({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
          },
        },
      });
      return config;
    },
  }),
);
</code>```1

./components/Company.scss

```<code>const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withCss(
  withSass({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
          },
        },
      });
      return config;
    },
  }),
);
</code>```2

答:
For anyone who is looking for a working answer after nextjs 11. You can refer to  this repo, or read full details in this article

Here is full next config code that I have used

```<code>const withTM = require('next-transpile-modules')([]);

const withPlugins = require('next-compose-plugins');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = withPlugins([withTM], {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex((r) => r.oneOf);
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.');
    }
    config.module.rules.splice(cssRulesIdx, 1);

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'static/chunks/pages/[contenthash].css',
        chunkFilename: 'static/chunks/pages/[contenthash].css',
      }),
    );

    config.module.rules.push({
      test: /\.(sa|sc|c)ss$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    });

    config.module.rules.push({
      test: /\.tsx/,
      use: [defaultLoaders.babel],
    });

    return config;
  },
});
</code>```

Title: NextJS component level SASS styling

Body:
I am working on a simple NextJS app, but I am having trouble with component level styling using SASS/SCSS. Everything looks fine when the user first lands on the page, but when the user navigates to a page /about for example or from /about to /, the component styles didn't get render, the user needs to refresh the page to see the styles

⚙ SETTINGS

./package.json

"dependencies": {
  "@zeit/next-css": "1.0.1",
  "@zeit/next-sass": "1.0.1",
  "autoprefixer": "^9.7.0",
  "next": "^9.3.1",
  "node-sass": "4.13.1",
  "react": "^16.13.0",
  "react-dom": "^16.13.0",
  "webpack": "^4.42.0"
}

./next.config.js

const webpack = require('webpack');
const withSass = require('@zeit/next-sass');
const withCss = require('@zeit/next-css');

module.exports = withCss(
  withSass({
    webpack(config) {
      config.module.rules.push({
        test: /\.(eot|woff?2|ttf|otf|svg|png|jpe?g|gif)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 100000,
          },
        },
      });
      return config;
    },
  }),
);

./postcss.config.js

const autoprefixer = require('autoprefixer');

module.exports = {
  plugins: [autoprefixer],
};

 PAGES

./pages/index.js

import React from 'react';
import Layout from '../components/Layout';
import Home from '../components/Home';

class Index extends React.PureComponent {
  render() {
    <Layout>
      <Home />
    </Layout>
  }
}

export default Index;

./pages/about.js

import React from 'react';
import Layout from '../components/Layout';
import Company from '../components/Company';

class About extends React.PureComponent {
  render() {
    <Layout>
      <Company />
    </Layout>
  }
}

export default About;

 COMPONENTS

./components/Layout.js

import React from 'react';
import AppBar from '../AppBar/AppBar';
import './Layout.scss';

class Layout extends React.PureComponent {
  render() {
    const { children } = this.props;

    return (
      <>
        <AppBar />

          {children}

      </>
    );
  }
}

export default Layout;

./components/Layout.scss

.Layout {
  background: #f00;
}

./components/AppBar.js

import Link from 'next/link';
import './AppBar.scss';

export default () => (

    <Link href="/">
      Home
    </Link>
    <Link href="/about">
      About
    </Link>

)

./components/AppBar.scss

.AppBar {
  background: #0f0;
}

./components/Home.js

import './Home.scss';

export default () => (

Home

)

./components/Home.scss

.Home {
  background: #00f;
}

./components/Company.js

import './Company.scss';

export default () => (

Company

)

./components/Company.scss

.Company {
  background: #ff0;
}

Body:
For anyone who is looking for a working answer after nextjs 11. You can refer to  this repo, or read full details in this article

Here is full next config code that I have used

const withTM = require('next-transpile-modules')([]);

const withPlugins = require('next-compose-plugins');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = withPlugins([withTM], {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex((r) => r.oneOf);
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.');
    }
    config.module.rules.splice(cssRulesIdx, 1);

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'static/chunks/pages/[contenthash].css',
        chunkFilename: 'static/chunks/pages/[contenthash].css',
      }),
    );

    config.module.rules.push({
      test: /\.(sa|sc|c)ss$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    });

    config.module.rules.push({
      test: /\.tsx/,
      use: [defaultLoaders.babel],
    });

    return config;
  },
});


问:
Is there a problem with my cucumber in the terminal?
I'm running into a couple issues with my app. I'm following this tutorial.

https://code.tutsplus.com/tutorials/ruby-for-newbies-testing-web-apps-with-capybara-and-cucumber--net-21446

As far as I'm concerned I have followed the tutorial to a T. But when i go to run the code using the cucumber keyword in my windows CMD, it throws the following error.

```<code>Feature: Viewer visits the Home Page
    In order to read the Page
    As a Viewer
    I want to see the home page of my app

  Scenario: View home page                     # features/home_page.feature:6
including Capybara::DSL in the global scope is not recommended!
E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/rspec-expectations-3.10.2/lib/rspec/matchers.rb:965:in `method_missing': undefined method `map' for nil:NilClass (NoMethodError)
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:205:in `stringify_namespaced_modules'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:169:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:121:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:126:in `to_s'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:53:in `rescue in execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:24:in `execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/bin/cucumber:9:in `<top (required)>'
        from E:/Ruby30-x64/bin/cucumber:25:in `load'
        from E:/Ruby30-x64/bin/cucumber:25:in `<main>'
E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/rspec-expectations-3.10.2/lib/rspec/matchers.rb:965:in `method_missing': undefined method `map' for nil:NilClass (NoMethodError)
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:205:in `stringify_namespaced_modules'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:169:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:121:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:126:in `to_s'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:54:in `handlers_for'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:34:in `broadcast'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:40:in `method_missing'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/runner.rb:37:in `around_hook'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/around_hook.rb:12:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:80:in `block (2 levels) in compose_around_hooks'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:81:in `compose_around_hooks'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:29:in `block in describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/runner.rb:19:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/prepare_world.rb:11:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:57:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/retry.rb:18:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/quit.rb:11:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:21:in `block in done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:20:in `map'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:20:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/filters/locations_filter.rb:20:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/filters/tag_filter.rb:18:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/compiler.rb:31:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/gherkin/parser.rb:46:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core.rb:35:in `parse'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core.rb:24:in `compile'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/runtime.rb:83:in `run!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:29:in `execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/bin/cucumber:9:in `<top (required)>'
        from E:/Ruby30-x64/bin/cucumber:25:in `load'
        from E:/Ruby30-x64/bin/cucumber:25:in `<main>'
</code>```

Is there something wrong with my cucumber gem? or is it another issue? If you'd like I can also post the rest of my code it was just a few files. Help?

答: The tutorial you’re following is from 11 years ago. My guess is just that the tutorial is massively out of date.</p>

Body:
I'm running into a couple issues with my app. I'm following this tutorial.

https://code.tutsplus.com/tutorials/ruby-for-newbies-testing-web-apps-with-capybara-and-cucumber--net-21446

As far as I'm concerned I have followed the tutorial to a T. But when i go to run the code using the cucumber keyword in my windows CMD, it throws the following error.

Feature: Viewer visits the Home Page
    In order to read the Page
    As a Viewer
    I want to see the home page of my app

  Scenario: View home page                     # features/home_page.feature:6
including Capybara::DSL in the global scope is not recommended!
E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/rspec-expectations-3.10.2/lib/rspec/matchers.rb:965:in `method_missing': undefined method `map' for nil:NilClass (NoMethodError)
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:205:in `stringify_namespaced_modules'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:169:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:121:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:126:in `to_s'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:53:in `rescue in execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:24:in `execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/bin/cucumber:9:in `<top (required)>'
        from E:/Ruby30-x64/bin/cucumber:25:in `load'
        from E:/Ruby30-x64/bin/cucumber:25:in `'
E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/rspec-expectations-3.10.2/lib/rspec/matchers.rb:965:in `method_missing': undefined method `map' for nil:NilClass (NoMethodError)
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:205:in `stringify_namespaced_modules'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:169:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:121:in `inspect'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/glue/proto_world.rb:126:in `to_s'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:54:in `handlers_for'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:34:in `broadcast'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/event_bus.rb:40:in `method_missing'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/runner.rb:37:in `around_hook'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/around_hook.rb:12:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:80:in `block (2 levels) in compose_around_hooks'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:81:in `compose_around_hooks'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:29:in `block in describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/runner.rb:19:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/prepare_world.rb:11:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:57:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/retry.rb:18:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/quit.rb:11:in `test_case'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/case.rb:28:in `describe_to'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:21:in `block in done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:20:in `map'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/filters/broadcast_test_run_started_event.rb:20:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/filters/locations_filter.rb:20:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/filter.rb:62:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/test/filters/tag_filter.rb:18:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/compiler.rb:31:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core/gherkin/parser.rb:46:in `done'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core.rb:35:in `parse'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-core-10.1.1/lib/cucumber/core.rb:24:in `compile'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/runtime.rb:83:in `run!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/lib/cucumber/cli/main.rb:29:in `execute!'
        from E:/Ruby30-x64/lib/ruby/gems/3.0.0/gems/cucumber-7.1.0/bin/cucumber:9:in `<top (required)>'
        from E:/Ruby30-x64/bin/cucumber:25:in `load'
        from E:/Ruby30-x64/bin/cucumber:25:in `'

Is there something wrong with my cucumber gem? or is it another issue? If you'd like I can also post the rest of my code it was just a few files. Help?


问:
How do I specify the date locale when Dserializing YAML using YamlDotNet?
In a YAML document, I've got a date formatted using an EN-GB locale (so 07/02/2019 is 2nd February 2019)

When I deserialize the document using YamlDotNet, it interprets this as an EN-US date so it stores it as July 2nd 2019

```<code># Date in test.yaml:
date: 07/02/2019

# Code to deserialize document to object:
var myObject= new DeserializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .Build()
                .Deserialize<MyObject>(File.ReadAllText(args[0]));
</code>```

Is there any way to specify whihc locate should be used when dates should be converted when using DeserializerBuilder?

答:
I suspect you need to set the Culture to the Thread explicitly:

CultureInfo newCulture = CultureInfo.CreateSpecificCulture("en-GB");
Thread.CurrentThread.CurrentUICulture = newCulture;
// Maybe this one below isn't necessary...
Thread.CurrentThread.CurrentCulture = newCulture;
```

Body:
In a YAML document, I've got a date formatted using an EN-GB locale (so 07/02/2019 is 2nd February 2019)

When I deserialize the document using YamlDotNet, it interprets this as an EN-US date so it stores it as July 2nd 2019

# Date in test.yaml:
date: 07/02/2019

# Code to deserialize document to object:
var myObject= new DeserializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .Build()
                .Deserialize<MyObject>(File.ReadAllText(args[0]));

Is there any way to specify whihc locate should be used when dates should be converted when using DeserializerBuilder?


问:
Search for same values into multiple csv files
I have a folder with 100+ csv files with several columns and hundreds of rows.Im trying to find a way to export into a new csv all the values (from a specific column) that exists into more than 1 file.

ex.

1.csv

```<code>ID,LOC,DATA
01,DUBAI,**AA**
02,LONDON,AB
03,ROME,AW
</code>```

2.csv

```<code>ID,LOC,DATA
04,NEW YORK,AC
05,CHICAGO,**AA**
06,LOS ANGELES,AR
</code>```

3.csv

```<code>ID,LOC,DATA
07,BERLIN,**AA**
08,TOKYO,**AA**
09,MOSCOW,AL
</code>```

In the example above the desired export is the AA value.
edit.It would be handy if at the end the exported value would come with whole row

答:
You can use pythons built-in Counter to count the occurrences of each value:</p>
```<code>import csv
from collections import Counter
import os

if __name__ == "__main__":
    column_name = "DATA"
    counter = Counter()
    headers = None
    rows = []

    directory = os.path.join("/path/to/csv/files/")
    for root, dirs, files in os.walk(directory):
        files = [file for file in files if file.endswith(".csv")]
        for file in files:
            with open(file, "r") as f:
                data = list(csv.reader(f))
                if data:
                    headers = data.pop(0)

                    for i in range(len(headers)):
                        if headers[i] == column_name:
                            column_data = list(zip(*data))[i]
                            counter.update(column_data)

        for file in files:
            with open(file, "r") as f:
                data = list(csv.DictReader(f))
                for row in data:
                    if counter[row[column_name]] > 1:
                        rows.append(row.values())

    with open("output.csv", "w") as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)

</code>```

Body:
I have a folder with 100+ csv files with several columns and hundreds of rows.Im trying to find a way to export into a new csv all the values (from a specific column) that exists into more than 1 file.

ex.

1.csv

ID,LOC,DATA
01,DUBAI,**AA**
02,LONDON,AB
03,ROME,AW

2.csv

ID,LOC,DATA
04,NEW YORK,AC
05,CHICAGO,**AA**
06,LOS ANGELES,AR

3.csv

ID,LOC,DATA
07,BERLIN,**AA**
08,TOKYO,**AA**
09,MOSCOW,AL

In the example above the desired export is the AA value.
edit.It would be handy if at the end the exported value would come with whole row

Body:
You can use pythons built-in Counter to count the occurrences of each value:

import csv
from collections import Counter
import os

if __name__ == "__main__":
    column_name = "DATA"
    counter = Counter()
    headers = None
    rows = []

    directory = os.path.join("/path/to/csv/files/")
    for root, dirs, files in os.walk(directory):
        files = [file for file in files if file.endswith(".csv")]
        for file in files:
            with open(file, "r") as f:
                data = list(csv.reader(f))
                if data:
                    headers = data.pop(0)

                    for i in range(len(headers)):
                        if headers[i] == column_name:
                            column_data = list(zip(*data))[i]
                            counter.update(column_data)

        for file in files:
            with open(file, "r") as f:
                data = list(csv.DictReader(f))
                for row in data:
                    if counter[row[column_name]] > 1:
                        rows.append(row.values())

    with open("output.csv", "w") as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        writer.writerows(rows)


问:
how to count observations used and deleted when using a regression in r
I have a dataset I am working with that has multiple variables. Some of these variables have observations that are NA. After running the regression there are some observations deleted because of the NA. I subset my data with the following code:

```<code>jsubset= jtrain %>% select(2,11,23,24,28)
</code>```

Which returned the following output:
jsubset

```<code>A tibble: 471 x 5
    fcode   d89 cgrant clemploy cgrant_1
    <dbl> <dbl>  <dbl>    <dbl>    <dbl>
 1 410032     0      0  NA            NA
 2 410032     0      0   0.270         0
 3 410032     1      0  -0.0630        0
 4 410440     0      0  NA            NA
 5 410440     0      0   0.0800        0
 6 410440     1      0   0.0741        0
 7 410495     0      0  NA            NA
 8 410495     0      0   0.223         0
 9 410495     1      0  -0.0408        0
10 410500     0      0  NA            NA
 ... with 461 more rows
</code>```

How would I separate FCODES that have values for the remaining columns and FCODES that while they have values for some columns there are NA? Or is it easier to count observations used and deleted from the regression? I know the command in STATA is e(sample) that does this easier but trying to replicate in R.

Body:
I have a dataset I am working with that has multiple variables. Some of these variables have observations that are NA. After running the regression there are some observations deleted because of the NA. I subset my data with the following code:

jsubset= jtrain %>% select(2,11,23,24,28)

Which returned the following output:
jsubset

A tibble: 471 x 5
    fcode   d89 cgrant clemploy cgrant_1
    <dbl> <dbl>  <dbl>    <dbl>    <dbl>
 1 410032     0      0  NA            NA
 2 410032     0      0   0.270         0
 3 410032     1      0  -0.0630        0
 4 410440     0      0  NA            NA
 5 410440     0      0   0.0800        0
 6 410440     1      0   0.0741        0
 7 410495     0      0  NA            NA
 8 410495     0      0   0.223         0
 9 410495     1      0  -0.0408        0
10 410500     0      0  NA            NA
 ... with 461 more rows

How would I separate FCODES that have values for the remaining columns and FCODES that while they have values for some columns there are NA? Or is it easier to count observations used and deleted from the regression? I know the command in STATA is e(sample) that does this easier but trying to replicate in R.

Body:
You can use filter with if_any() for both cases. Taking your sample:

library(dplyr)
df <- read.csv(text="
 fcode   d89 cgrant clemploy cgrant_1
 410032     0      0  NA            NA
 410032     0      0   0.270         0
 410032     1      0  -0.0630        0
 410440     0      0  NA            NA
 410440     0      0   0.0800        0
 410440     1      0   0.0741        0
 410495     0      0  NA            NA
 410495     0      0   0.223         0
 410495     1      0  -0.0408        0
 410500     0      0  NA            NA", sep="")

df_no_na <- df %>%
        filter(!if_any(everything(), is.na))

df_na <- df %>%
        filter(if_any(everything(), is.na))

df_no_na:

   fcode d89 cgrant clemploy cgrant_1
1 410032   0      0   0.2700        0
2 410032   1      0  -0.0630        0
3 410440   0      0   0.0800        0
4 410440   1      0   0.0741        0
5 410495   0      0   0.2230        0
6 410495   1      0  -0.0408        0

df_na:

   fcode d89 cgrant clemploy cgrant_1
1 410032   0      0       NA       NA
2 410440   0      0       NA       NA
3 410495   0      0       NA       NA
4 410500   0      0       NA       NA


问:
Sort NSmutableArray that contains 2 types of object?
I have an NSMutableArray that contains 2 types of Objects.

Both objects contain a field for dates (date Strings with different formats) with different names.

What's the best and fastest way to sort them all based on the date? Is it possible to use an NSSortDescriptor in this situation?

答:
If you are targeting Mac OS X v10.6 or iOS4 and higher you can sort using comparator similar to this

```<code>NSDateFormatter *formatter1 = ...; //create and configure date formatter for Class1
NSDateFormatter *formatter2 = ...; //create and configure date formatter for Class2

[arrayOfObjects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = nil, *date2 = nil;
    //Get first objects date
    if([obj1 isKindOfClass:[Class1 class]])
    {
        date1 = [formatter1 dateFromString:[obj1 class1Date]];
    }
    else if([obj1 isKindOfClass:[Class2 class]])
    {
        date1 = [formatter2 dateFromString:[obj1 class2Date]];
    }

    //Get second objects date
    if([obj2 isKindOfClass:[Class1 class]])
    {
        date2 = [formatter1 dateFromString:[obj2 class1Date]];
    }
    else if([obj2 isKindOfClass:[Class2 class]])
    {
        date2 = [formatter2 dateFromString:[obj2 class2Date]];
    }

    NSAssert(date1 != nil, @"Could not parse date from %@", obj1);
    NSAssert(date2 != nil, @"Could not parse date from %@", obj2);

    return [date1 compare:date2];
}];
</code>```

Besides checking for the class you could also check if it responds to selector.

ContentLicense: CC BY-SA 3.0

Body:
If you are targeting Mac OS X v10.6 or iOS4 and higher you can sort using comparator similar to this

NSDateFormatter *formatter1 = ...; //create and configure date formatter for Class1
NSDateFormatter *formatter2 = ...; //create and configure date formatter for Class2

[arrayOfObjects sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSDate *date1 = nil, *date2 = nil;
    //Get first objects date
    if([obj1 isKindOfClass:[Class1 class]])
    {
        date1 = [formatter1 dateFromString:[obj1 class1Date]];
    }
    else if([obj1 isKindOfClass:[Class2 class]])
    {
        date1 = [formatter2 dateFromString:[obj1 class2Date]];
    }

    //Get second objects date
    if([obj2 isKindOfClass:[Class1 class]])
    {
        date2 = [formatter1 dateFromString:[obj2 class1Date]];
    }
    else if([obj2 isKindOfClass:[Class2 class]])
    {
        date2 = [formatter2 dateFromString:[obj2 class2Date]];
    }

    NSAssert(date1 != nil, @"Could not parse date from %@", obj1);
    NSAssert(date2 != nil, @"Could not parse date from %@", obj2);

    return [date1 compare:date2];
}];

Besides checking for the class you could also check if it responds to selector.


问:
Architecture-Specific Build Settings in Xcode 13
I'm trying to use architecture-specific build settings in my Xcode Framework so that I can handle the case of the Apple Silicon Mac and the Intel Mac separately. I need to use this build setting as a macro in Metal to check whether the half data type is supported on the CPU (it's supported on Apple Silicon but not supported on Intel).

My current implementation uses an xcconfig file with the following line:

IS_X86_64[arch=x86_64] = 1

Then, in my build settings I have the following user-defined condition (from the xcconfig):

I then create the macro IS_INTEL so it can be used in Metal:

Here's The Problem

In theory I feel like this should work. However, running my Metal app on my Intel mac yields 0 for IS_X86_64. The first thing I did was check whether I set up my build setting correctly and replaced

IS_X86_64[arch=x86_64] = 1
with
IS_X86_64[arch=*] = 1

This worked so I knew that the problem had to be that my current architecture wasn't being represented correctly. Diving further into why this was happening, it turns out that the value for CURRENT_ARCH (which should hold the value for the current device architecture that the project is being run on) is undefined_arch.

In their Xcode 10 release notes, apple mentioned something about undefined_arch saying:

The new build system passes undefined_arch as the value for the ARCH environment variable when running shell script build phases. The value was previously not well defined. Any shell scripts depending on this value must behave correctly for all defined architectures being built, available via the ARCHS environment variable.

However, I'm not building my project on the shell and I don't have any shell scripts.
Does anyone know how I can fix this so that architecture-specific build settings behave as they should?

答:
You can check the architecture via built-in macros. You can see how they are used in usr/include/TargetConditionals.h:

```<code>#if __is_target_arch(x86_64)
    ...
#endif
</code>```

More macros:

```<code>__is_target_arch(arm64)
__is_target_arch(arm64e)
__is_target_os(ios)
__is_target_environment(macabi)
__is_target_environment(simulator)
</code>```

Body:
You can check the architecture via built-in macros. You can see how they are used in usr/include/TargetConditionals.h:

#if __is_target_arch(x86_64)
    ...
#endif

More macros:

__is_target_arch(arm64)
__is_target_arch(arm64e)
__is_target_os(ios)
__is_target_environment(macabi)
__is_target_environment(simulator)


问:
How to remove rows with same id in different data frames?
```<code>df1
   id value
1  1    10
2  2    20
3  3    30
4  4    40
5  5    50

df2
   id value
1  2    25
2  3    35

I would like to have the following df3:

df3
   id value
1  1    10
2  4    40
3  5    50
</code>```

In other words, I would like to remove only the same ID between df1 and df2. How could I do that?

答:
I created new dummy data to simplify the example. Feel free to apply to other dataframes</p>
```<code># dummy df
df <- data.table(id = 1:2); df
   id
1:  1
2:  2

# dummy df1
df1 <- data.table(id = 2:3); df1
   id
1:  2
2:  3

# common rows
x <- intersect(unique(df$id), unique(df1$id))

# exclude
rbind(df, df1)[!id %in% x]
   id
1:  1
2:  3
</code>```

Body:
df1
   id value
1  1    10
2  2    20
3  3    30
4  4    40
5  5    50

df2
   id value
1  2    25
2  3    35

I would like to have the following df3:

df3
   id value
1  1    10
2  4    40
3  5    50

In other words, I would like to remove only the same ID between df1 and df2. How could I do that?

Body:
I created new dummy data to simplify the example. Feel free to apply to other dataframes

# dummy df
df <- data.table(id = 1:2); df
   id
1:  1
2:  2

# dummy df1
df1 <- data.table(id = 2:3); df1
   id
1:  2
2:  3

# common rows
x <- intersect(unique(df$id), unique(df1$id))

# exclude
rbind(df, df1)[!id %in% x]
   id
1:  1
2:  3


问:
Google Apps Script only works when manually triggered, not by any other trigger
I'm a bit struggling to understand this matter:
My code meant to delete rox X if the colour of a cell in row X column Y is RED (f4c7c3).
For example :

The code works great thanks to a few questions I saw around here that helped me make it better, but it will only work when I click run. If I'm using any trigger (I want to use a time-driven trigger every day between midnight and 1 AM, but I've tried them all), it shows that it was completed, but nothing happens to the spreadsheet.

Here is my code, I'd appreciate your help with that issue:

```<code>function DeleteRow(column,color) {   //Delete row if the color in the Date column is F4C7C3
  var column = (typeof(column)!='undefined')?column:4;
  var color = (typeof(color)!='undefined')?color:'#f4c7c3';
  var ss = SpreadsheetApp.openById("1Ichlawob5EHzSK4ljRSJfViugFWugTzHOMId3q5LL6w");
  var sht = ss.setActiveSheet(ss.getSheets()[0]);
  var rng = ss.getDataRange();
  var rngA = rng.getBackgrounds()
  for(var i=rngA.length-1;i>-1;i--)
  {
    if(rngA[i][column-1]==color)
    {
      sht.deleteRow(i+1);
    }
  }
}

</code>```

BTW, just got a summary that shows the error even though the executions indicate successfully-

答:
Try to replace the line:

```<code>var column = (typeof(column)!='undefined')?column:4;
</code>```

To:

```<code>var column = (typeof(column)=='number')?column:4;
</code>```

Or just:

```<code>var column = 4;
</code>```

Explanation

Whenever you're firing a function via a trigger the function gets an 'event object' as a first and only argument. You're actually calling DeleteRow(e) instead of DeleteRow(). Where the e is the event object. It's not undefined and its not a number.

Body:
I'm a bit struggling to understand this matter:
My code meant to delete rox X if the colour of a cell in row X column Y is RED (f4c7c3).
For example :

The code works great thanks to a few questions I saw around here that helped me make it better, but it will only work when I click run. If I'm using any trigger (I want to use a time-driven trigger every day between midnight and 1 AM, but I've tried them all), it shows that it was completed, but nothing happens to the spreadsheet.

Here is my code, I'd appreciate your help with that issue:

function DeleteRow(column,color) {   //Delete row if the color in the Date column is F4C7C3
  var column = (typeof(column)!='undefined')?column:4;
  var color = (typeof(color)!='undefined')?color:'#f4c7c3';
  var ss = SpreadsheetApp.openById("1Ichlawob5EHzSK4ljRSJfViugFWugTzHOMId3q5LL6w");
  var sht = ss.setActiveSheet(ss.getSheets()[0]);
  var rng = ss.getDataRange();
  var rngA = rng.getBackgrounds()
  for(var i=rngA.length-1;i>-1;i--)
  {
    if(rngA[i][column-1]==color)
    {
      sht.deleteRow(i+1);
    }
  }
}

BTW, just got a summary that shows the error even though the executions indicate successfully-

Body:
Try to replace the line:

var column = (typeof(column)!='undefined')?column:4;

To:

var column = (typeof(column)=='number')?column:4;

Or just:

var column = 4;

Explanation

Whenever you're firing a function via a trigger the function gets an 'event object' as a first and only argument. You're actually calling DeleteRow(e) instead of DeleteRow(). Where the e is the event object. It's not undefined and its not a number.


问:
Use sleep function but allow for input to end macro?
i have a macro that loops and uses the sleep function for a random interval between 5 seconds and 120 seconds after each loop. When the macro goes to sleep after carrying operations i am unable to end the macro without resorting to using control break where control break seems to work intermittently. So my question is this. How would i go about putting the macro to sleep for any amount of time but to also be able to terminate the macro at any time during sleep without control break?</p>

答:
A different approach to pausing in line would be to use Application.OnTime ...

```<code>Public Sub PauseInBackground()
    Dim lngSeconds As Long, strNextTime As String

    Randomize (Second(Time))
    lngSeconds = Rnd() * 120

    strNextTime = Format(DateAdd("s", lngSeconds, DateValue("01/01/1800")), "hh:mm:ss")

    Debug.Print "Next Time = " & strNextTime

    Application.OnTime Now + TimeValue(strNextTime), "RoutineToRun"
End Sub

Public Sub RoutineToRun()
    Debug.Print "Now = " & Now()

    ' Your code/logic

    PauseInBackground
End Sub
</code>```

... it won't pause the macro in place.

https://learn.microsoft.com/en-us/office/vba/api/excel.application.ontime

Body:
A different approach to pausing in line would be to use Application.OnTime ...

Public Sub PauseInBackground()
    Dim lngSeconds As Long, strNextTime As String

    Randomize (Second(Time))
    lngSeconds = Rnd() * 120

    strNextTime = Format(DateAdd("s", lngSeconds, DateValue("01/01/1800")), "hh:mm:ss")

    Debug.Print "Next Time = " & strNextTime

    Application.OnTime Now + TimeValue(strNextTime), "RoutineToRun"
End Sub

Public Sub RoutineToRun()
    Debug.Print "Now = " & Now()

    ' Your code/logic

    PauseInBackground
End Sub

... it won't pause the macro in place.

https://learn.microsoft.com/en-us/office/vba/api/excel.application.ontime


问:
ERROR: brownie.exceptions.RPCConnectionError: Able to launch RPC client, but unable to connect
The ganache-cli is unable to connect to the mainnet fork, as a result of which I can't run brownie test --networks mainnet-fork

My test.py file looks like this:

```<code>from brownie import Lottery, accounts, network, config

def test_eth_amount():
    account = accounts[0]
    lottery = Lottery.deploy(
        config["networks"][network.show_active()]["eth_usd_price_feed"],
        {"from": account},
    )
    print(lottery)
    assert lottery.getEntranceFee() > 18000000000000000
    assert lottery.getEntranceFee() < 21000000000000000
</code>```

And brownie-config file is:

```<code>dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@0.2.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
      # - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'
# dotenv: .env
networks:
  mainnet-fork:
    eth_usd_price_feed: '0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419'
</code>```

But even then brownie can't connect to mainnet-fork!

The error message looks like this:

```<code>Launching 'ganache-cli.cmd --accounts 10 --fork https://eth-mainnet.alchemyapi.io/v2/w1kKuepExg3kpo_V4Dr4XHArsk3IWb0Y --mnemonic brownie --port 8545 --hardfork istanbul'...
Terminating local RPC client...
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 269, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 322, in _main
INTERNALERROR>     config.hook.pytest_collection(session=session)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 60, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_result.py", line 60, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 333, in pytest_collection
INTERNALERROR>     session.perform_collect()
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 641, in perform_collect
INTERNALERROR>     hook.pytest_collection_finish(session=self)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 55, in _multicall
INTERNALERROR>     gen.send(outcome)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\test\managers\runner.py", line 258, in pytest_collection_finish
INTERNALERROR>     brownie.network.connect(CONFIG.argv["network"])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\network\main.py", line 50, in connect
INTERNALERROR>     rpc.launch(active["cmd"], **active["cmd_settings"])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\network\rpc\__init__.py", line 95, in launch
INTERNALERROR>     raise RPCConnectionError(cmd, self.process, uri)
INTERNALERROR> brownie.exceptions.RPCConnectionError: Able to launch RPC client, but unable to connect.
INTERNALERROR>
INTERNALERROR> Command: ganache-cli
INTERNALERROR> URI: https://127.0.0.1:8545
INTERNALERROR> Exit Code: 15
</code>```

My mainnet-fork network details also doesn't seem suspicious:

```<code>Network 'mainnet-fork' has been modified
  └─mainnet-fork
    ├─id: mainnet-fork
    ├─cmd: ganache-cli
    ├─cmd_settings: {'accounts': 10, 'fork': 'https://eth-mainnet.alchemyapi.io/v2/w1kKuepExg3kpo_V4Dr4XHArsk3IWb0Y', 'mnemonic': 'brownie', 'port': 8545}
    └─host: https://127.0.0.1
</code>```

If the RPC doesn't connect to the proper network, It'll be difficult for me to continue with the course.

答:
You just need to wait for the deploy transaction to finish:

from brownie import Lottery, accounts, network, config

def test_eth_amount():
    account = accounts[0]
    lottery = Lottery.deploy(
        config["networks"][network.show_active()]["eth_usd_price_feed"],
        {"from": account},
    )
    lottery.tx.wait(1)
    print(lottery)
    assert lottery.getEntranceFee() > 18000000000000000
    assert lottery.getEntranceFee() < 21000000000000000
```

Body:
The ganache-cli is unable to connect to the mainnet fork, as a result of which I can't run brownie test --networks mainnet-fork

My test.py file looks like this:

from brownie import Lottery, accounts, network, config

def test_eth_amount():
    account = accounts[0]
    lottery = Lottery.deploy(
        config["networks"][network.show_active()]["eth_usd_price_feed"],
        {"from": account},
    )
    print(lottery)
    assert lottery.getEntranceFee() > 18000000000000000
    assert lottery.getEntranceFee() < 21000000000000000

And brownie-config file is:

dependencies:
  # - <organization/repo>@<version>
  - smartcontractkit/chainlink-brownie-contracts@0.2.1
compiler:
  solc:
    remappings:
      - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
      # - '@chainlink=smartcontractkit/chainlink-brownie-contracts@1.1.1'
# dotenv: .env
networks:
  mainnet-fork:
    eth_usd_price_feed: '0x5f4ec3df9cbd43714fe2740f5e3616155c5b8419'

But even then brownie can't connect to mainnet-fork!

The error message looks like this:

Launching 'ganache-cli.cmd --accounts 10 --fork https://eth-mainnet.alchemyapi.io/v2/w1kKuepExg3kpo_V4Dr4XHArsk3IWb0Y --mnemonic brownie --port 8545 --hardfork istanbul'...
Terminating local RPC client...
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 269, in wrap_session
INTERNALERROR>     session.exitstatus = doit(config, session) or 0
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 322, in _main
INTERNALERROR>     config.hook.pytest_collection(session=session)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 60, in _multicall
INTERNALERROR>     return outcome.get_result()
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_result.py", line 60, in get_result
INTERNALERROR>     raise ex[1].with_traceback(ex[2])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 39, in _multicall
INTERNALERROR>     res = hook_impl.function(*args)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 333, in pytest_collection
INTERNALERROR>     session.perform_collect()
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\_pytest\main.py", line 641, in perform_collect
INTERNALERROR>     hook.pytest_collection_finish(session=self)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_hooks.py", line 265, in __call__
INTERNALERROR>     return self._hookexec(self.name, self.get_hookimpls(), kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_manager.py", line 80, in _hookexec
INTERNALERROR>     return self._inner_hookexec(hook_name, methods, kwargs, firstresult)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\pluggy\_callers.py", line 55, in _multicall
INTERNALERROR>     gen.send(outcome)
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\test\managers\runner.py", line 258, in pytest_collection_finish
INTERNALERROR>     brownie.network.connect(CONFIG.argv["network"])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\network\main.py", line 50, in connect
INTERNALERROR>     rpc.launch(active["cmd"], **active["cmd_settings"])
INTERNALERROR>   File "c:\users\hp\development\demos\brownie_simple_storage\venv\lib\site-packages\brownie\network\rpc\__init__.py", line 95, in launch
INTERNALERROR>     raise RPCConnectionError(cmd, self.process, uri)
INTERNALERROR> brownie.exceptions.RPCConnectionError: Able to launch RPC client, but unable to connect.
INTERNALERROR>
INTERNALERROR> Command: ganache-cli
INTERNALERROR> URI: https://127.0.0.1:8545
INTERNALERROR> Exit Code: 15

My mainnet-fork network details also doesn't seem suspicious:

Network 'mainnet-fork' has been modified
  └─mainnet-fork
    ├─id: mainnet-fork
    ├─cmd: ganache-cli
    ├─cmd_settings: {'accounts': 10, 'fork': 'https://eth-mainnet.alchemyapi.io/v2/w1kKuepExg3kpo_V4Dr4XHArsk3IWb0Y', 'mnemonic': 'brownie', 'port': 8545}
    └─host: https://127.0.0.1

If the RPC doesn't connect to the proper network, It'll be difficult for me to continue with the course.


问:
How to properly use Sass with NextJS
I have been styling my NextJS app with scss modules and It was working fine. I came back later to work on some other stuff and I was suddenly being hit with this error:

```<code>Syntax error: Invalid CSS after "...ound: variables": expected expression (e.g. 1px, bold), was ".$main-gradient-bac"

</code>```

I am confused because I had not made any changes and it had been running fine earlier and I have not made any changes to it since then. I made sure I installed sass like NextJS docs recommeneded npm i sass. I am using next version 9.5.1

here is my package.json:

```<code>"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest"
  },
  "dependencies": {
    "@stripe/stripe-js": "^1.9.0",
    "aws-sdk": "^2.738.0",
    "axios": "^0.19.2",
    "jwt-decode": "^2.2.0",
    "next": "^9.5.1",
    "node-sass": "^4.14.1",
    "react": "16.13.1",
    "react-aws-s3": "^1.3.0",
    "react-dom": "16.13.1",
    "sass": "^1.26.10",
    "swr": "^0.3.0"
  },
  "devDependencies": {
    "@testing-library/dom": "^7.22.2",
    "@testing-library/jest-dom": "^5.11.3",
    "@testing-library/react": "^10.4.8",
    "babel-jest": "^26.3.0",
    "eslint": "^7.2.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-node": "^4.1.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.20.5",
    "eslint-plugin-react-hooks": "^4.0.0",
    "jest": "^26.4.0",
    "jest-dom": "^4.0.0",
    "prettier": "^2.0.5"
  }
}
</code>```

And this is the file that I am recieving the error for. It's not specific to just this file though. I comment out this one it shoots out errors for my other .scss files:

```<code>@use 'variables';

html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  background: variables.$main-gradient-background;
  scroll-behavior: smooth;
}

a {
  color: lightseagreen;
  text-decoration: none;
}

button {
  background-color: black;
}

input {
  background-color: grey;
}

* {
  box-sizing: border-box;
  color: variables.$primary-color;
  font-family: variables.$primary-p-font;
  line-height: 1.45em;
  font-size: variables.$primary-font-size;
}

h1 {
  font-family: variables.$header-font;
}

h2 {
  font-family: variables.$header-font;
}

h3 {
  font-family: variables.$header-font;
}
</code>```

答:
node-sass is deprecated and will no longer work with modern versions of nextjs

For anyone who is looking for a working answer after nextjs 11. You can refer to  this repo, or read full details in this article

Here is full next config code that I have used

```<code>const withTM = require('next-transpile-modules')([]);

const withPlugins = require('next-compose-plugins');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = withPlugins([withTM], {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex((r) => r.oneOf);
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.');
    }
    config.module.rules.splice(cssRulesIdx, 1);

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'static/chunks/pages/[contenthash].css',
        chunkFilename: 'static/chunks/pages/[contenthash].css',
      }),
    );

    config.module.rules.push({
      test: /\.(sa|sc|c)ss$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    });

    config.module.rules.push({
      test: /\.tsx/,
      use: [defaultLoaders.babel],
    });

    return config;
  },
});
</code>```

Title: How to properly use Sass with NextJS

Body:
I have been styling my NextJS app with scss modules and It was working fine. I came back later to work on some other stuff and I was suddenly being hit with this error:

Syntax error: Invalid CSS after "...ound: variables": expected expression (e.g. 1px, bold), was ".$main-gradient-bac"

I am confused because I had not made any changes and it had been running fine earlier and I have not made any changes to it since then. I made sure I installed sass like NextJS docs recommeneded npm i sass. I am using next version 9.5.1

here is my package.json:

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest"
  },
  "dependencies": {
    "@stripe/stripe-js": "^1.9.0",
    "aws-sdk": "^2.738.0",
    "axios": "^0.19.2",
    "jwt-decode": "^2.2.0",
    "next": "^9.5.1",
    "node-sass": "^4.14.1",
    "react": "16.13.1",
    "react-aws-s3": "^1.3.0",
    "react-dom": "16.13.1",
    "sass": "^1.26.10",
    "swr": "^0.3.0"
  },
  "devDependencies": {
    "@testing-library/dom": "^7.22.2",
    "@testing-library/jest-dom": "^5.11.3",
    "@testing-library/react": "^10.4.8",
    "babel-jest": "^26.3.0",
    "eslint": "^7.2.0",
    "eslint-config-airbnb": "^18.2.0",
    "eslint-config-node": "^4.1.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-import": "^2.22.0",
    "eslint-plugin-jsx-a11y": "^6.3.1",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.20.5",
    "eslint-plugin-react-hooks": "^4.0.0",
    "jest": "^26.4.0",
    "jest-dom": "^4.0.0",
    "prettier": "^2.0.5"
  }
}

And this is the file that I am recieving the error for. It's not specific to just this file though. I comment out this one it shoots out errors for my other .scss files:

@use 'variables';

html,
body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
    Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
  background: variables.$main-gradient-background;
  scroll-behavior: smooth;
}

a {
  color: lightseagreen;
  text-decoration: none;
}

button {
  background-color: black;
}

input {
  background-color: grey;
}

* {
  box-sizing: border-box;
  color: variables.$primary-color;
  font-family: variables.$primary-p-font;
  line-height: 1.45em;
  font-size: variables.$primary-font-size;
}

h1 {
  font-family: variables.$header-font;
}

h2 {
  font-family: variables.$header-font;
}

h3 {
  font-family: variables.$header-font;
}

Body:
node-sass is deprecated and will no longer work with modern versions of nextjs

For anyone who is looking for a working answer after nextjs 11. You can refer to  this repo, or read full details in this article

Here is full next config code that I have used

const withTM = require('next-transpile-modules')([]);

const withPlugins = require('next-compose-plugins');

const MiniCssExtractPlugin = require('mini-css-extract-plugin');

module.exports = withPlugins([withTM], {
  reactStrictMode: true,
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    // Find and remove NextJS css rules.
    const cssRulesIdx = config.module.rules.findIndex((r) => r.oneOf);
    if (cssRulesIdx === -1) {
      throw new Error('Could not find NextJS CSS rule to overwrite.');
    }
    config.module.rules.splice(cssRulesIdx, 1);

    // Add a simpler rule for global css anywhere.
    config.plugins.push(
      new MiniCssExtractPlugin({
        // Options similar to the same options in webpackOptions.output
        // both options are optional
        filename: 'static/chunks/pages/[contenthash].css',
        chunkFilename: 'static/chunks/pages/[contenthash].css',
      }),
    );

    config.module.rules.push({
      test: /\.(sa|sc|c)ss$/i,
      use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
    });

    config.module.rules.push({
      test: /\.tsx/,
      use: [defaultLoaders.babel],
    });

    return config;
  },
});


问:
How to exclude package from Scala SBT
I am at loss. I am using Scala with SBT and I had to add databricks dependency (link dependencies i get when I install databricks-connect) via unmanagedBase in the build.sbt and now when I try to run the application I get this error. I have tried excluding packages but nothing helps. Maybe I am doing it wrong. Could someone please help me. What package should I exclude to make this thing work since I am getting org.slf4j.impl.Log4jLoggerFactory cannot be cast to ch.qos.logback.classic.LoggerContext?

答:
To understand what is happening (and to prevent this in the future), you probably need to read and understand SLF4J user manual.

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks, such as java.util.logging, logback and reload4j.

In Binding with a logging framework at deployment time section it says:

slf4j-log4j12-1.7.35.jar

Binding/provider for log4j version 1.2, a widely used logging framework.

logback-classic-1.2.10.jar (requires logback-core-1.2.10.jar)

There are also SLF4J bindings/providers external to the SLF4J project, e.g. logback which implements SLF4J natively.

First you'd have to decide if you want log4j as the logger implementation or logback. The screenshot doesn't show org.slf4j:slf4j-log4j12:something, but is it included?

Assuming you want to exclude log4j binding, then that's the one you need to exclude.

To exclude something from all dependencies in a subproject:

excludeDependencies ++= Seq(
  ExclusionRule("org.slf4j", "slf4j-log4j12")
)
```

For more details, see Exclude Transitive Dependencies.

Title: How to exclude package from Scala SBT

Body:
To understand what is happening (and to prevent this in the future), you probably need to read and understand SLF4J user manual.

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks, such as java.util.logging, logback and reload4j.

In Binding with a logging framework at deployment time section it says:

slf4j-log4j12-1.7.35.jar

Binding/provider for log4j version 1.2, a widely used logging framework.

logback-classic-1.2.10.jar (requires logback-core-1.2.10.jar)

There are also SLF4J bindings/providers external to the SLF4J project, e.g. logback which implements SLF4J natively.

First you'd have to decide if you want log4j as the logger implementation or logback. The screenshot doesn't show org.slf4j:slf4j-log4j12:something, but is it included?

Assuming you want to exclude log4j binding, then that's the one you need to exclude.

To exclude something from all dependencies in a subproject:

excludeDependencies ++= Seq(
  ExclusionRule("org.slf4j", "slf4j-log4j12")
)

For more details, see Exclude Transitive Dependencies.


问:
hide items in xcode app?
I am newbie to iPhone development. I have a Root.plist under Settings.bundl like below image.
While doing Adhoc testing with users. we used Item 0, Item 1, Item 2 for testing. because there is web service url in item1. Now we are planning to move this app to app store. So we dont need show this information settings to user. How can I hide these items to user? but we still need this info for app usage.

答:
I recommend NSUserDefaults. When you set something in NSUserDefaults, it stays there until changed (between loads as well).

```<code>NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
</code>```

That creates an instance of NSUserDefaults and to add an object it's essentially a dictionary...

```<code>[prefs setObject:@"NO" forKey:@"didCrash"];
</code>```

Good luck!

Title: hide items in xcode app?

Body:
I recommend NSUserDefaults. When you set something in NSUserDefaults, it stays there until changed (between loads as well).

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

That creates an instance of NSUserDefaults and to add an object it's essentially a dictionary...

[prefs setObject:@"NO" forKey:@"didCrash"];

Good luck!


答:
If you just want an alphabetical letter from any number, you can make a list of the alphabet and index it at "thing" spot.

```<code>alphabet[(thing - 1) % 26]
</code>```

I subtracted 1 to make it zero-indexed, and % 26 ensures that it works even if the variable "thing" is too large. Alphabet can be defined a couple ways

```<code>from string import ascii_lowercase
alphabet = list(ascii_lowercase)
</code>```

or

```<code>alphabet = [chr(i) for i in range(97, 123)]
</code>```

Title: Really dumb question about what's more efficient than elif spam and dictionaries

Body:
My code needs to check which product/thing a number corresponds to.

Which means if I input a number, I need to know which product it corresponds to.

As far as I know, I have no idea how to do this other than elif spamming, but that makes a huge mess with a massive wall of elifs.

I've also tried reading into python dictionaries but my small brain doesn't comprehend how to pick out the value if I only have the key.

I feel like dictionaries were made for this but I still can't figure out how it works.

Is there a way to be more efficient in finding what product == number if I only have the number and a list of objects?
Example:

if thing == 1:
    print("a")
elif thing == 2:
    print("b")
elif thing == 3:
    print("c")

and so on

Body:
If you just want an alphabetical letter from any number, you can make a list of the alphabet and index it at "thing" spot.

alphabet[(thing - 1) % 26]

I subtracted 1 to make it zero-indexed, and % 26 ensures that it works even if the variable "thing" is too large. Alphabet can be defined a couple ways

from string import ascii_lowercase
alphabet = list(ascii_lowercase)

or

alphabet = [chr(i) for i in range(97, 123)]


问:
Rearrange txt content Script
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

</code>```

But combining them is the problem. I have tried something close to this:

```<code>with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1
</code>```

答:
you can read in the items like this:

```<code>with open('test.txt','r') as in_file:
    dict_predators = {}
    for line in in_file:
        dict_predators[line.split(':')[0]] = line.split(':')[1].replace('\n', '').split(',')
</code>```

first split the line by the ':' use both of those elements one the first part as the key in a dictionary and the second part as a list for the value in the dictionary (I used replace to get rid of the newline character) and then used split by ',' to make them into strings (with a space before because you were already going to use a space when you print them back out)

And you can write them to a file like this:

```<code>with open('test2.txt','w') as in_file:
    for k,v in dict_predators.items():  # go through all the elements in the dictionary
        for item in v:  # go through all the elements of the list of values at that key
            in_file.write(f"{k}{item}\n")
</code>```

Title: Rearrange txt content Script

Body:
I have a list of predators and their corresponding preys in this format:

Wolf: Sheep, Chicken, Rabbit

Lion: Zebra, Giraffe, Gazelle

And want to transform it to this format:

Wolf Sheep

Wolf Chicken

Wolf Rabbit

Lion Zebra

Lion Giraffe

Lion Gazelle

So far, I have tried this code in order to separate predators and preys

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    pred = []
    for line in split:
        pred.append(line[0])

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    split = (line.split(":") for line in stripped if line)
    preys = []
    for line in split:
        preys.append(line[1])
    prey = (line.split(",") for line in preys if line)

But combining them is the problem. I have tried something close to this:

with open('test.txt','r') as in_file:
    stripped = (line.strip() for line in in_file)
    i=0
    while i < line_count:
        rows.append(pred[i])
        for line in prey:
            rows.append(line[0])
        i+=1

Body:
you can read in the items like this:

with open('test.txt','r') as in_file:
    dict_predators = {}
    for line in in_file:
        dict_predators[line.split(':')[0]] = line.split(':')[1].replace('\n', '').split(',')

first split the line by the ':' use both of those elements one the first part as the key in a dictionary and the second part as a list for the value in the dictionary (I used replace to get rid of the newline character) and then used split by ',' to make them into strings (with a space before because you were already going to use a space when you print them back out)

And you can write them to a file like this:

with open('test2.txt','w') as in_file:
    for k,v in dict_predators.items():  # go through all the elements in the dictionary
        for item in v:  # go through all the elements of the list of values at that key
            in_file.write(f"{k}{item}\n")


问:
Firestore how to display an array of items in a collection
I want to display the user's order history in user profile. Thus, I'm trying to fetch the order (which has an array of items) that matches with a userId and show it in their profile. Below is a screenshot of my firestore db.

*FB version 9, on react native

enter image description here

答:
We need to define a relationship between an order and the user who ordered it.

assume that we have orders collection with the following documents:

 {
  "R09_iuyb0gty": {
    orderId: "R09_iuyb0gty",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },

  "990_ggt6098765": {
    orderId: "990_ggt6098765",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },
}
```
<p>Filters and return user specific orders</p>
<pre class="lang-js prettyprint-override"><code>
import { collection, doc, setDoc, getDocs } from "firebase/firestore";
import { getAuth } from "firebase/auth";

const getUserId = () => {
  const auth = getAuth();
  const user = auth.currentUser;

  return user.uid || null;
};

async function getOrdersByUser() {
  const userId = getUserId();

  if (!userId) return;

  const ordersRef = collection(db, "orders");
  const q = query(ordersRef, where("orderBy.userId", "==", userId));
  const querySnapshot = await getDocs(q);

  let orders = [];
  querySnapshot.forEach((doc) => {
    if (doc.data()) {
      orders.push(doc.data());
    }
  });

  return orders;
}

</code>```

Fetch user's orders when component mounted

useEffect(async () => {
  const userOrders = await getOrdersByUser();

  console.log({ userOrders });
}, []);

```

Body:
We need to define a relationship between an order and the user who ordered it.

assume that we have orders collection with the following documents:

 {
  "R09_iuyb0gty": {
    orderId: "R09_iuyb0gty",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },

  "990_ggt6098765": {
    orderId: "990_ggt6098765",
    createdAt: "",
    orderBy: {
      userId: "yhnbauytfredd",
      name: "Paul Allen",
    },
    items: [
      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },

      {
        cafeName: " StarBuck",
        image: "https://...",
        name: "Espresso Cona Panna",
        price: "1.3 KD",
      },
    ],
  },
}

Filters and return user specific orders

import { collection, doc, setDoc, getDocs } from "firebase/firestore";
import { getAuth } from "firebase/auth";

const getUserId = () => {
  const auth = getAuth();
  const user = auth.currentUser;

  return user.uid || null;
};

async function getOrdersByUser() {
  const userId = getUserId();

  if (!userId) return;

  const ordersRef = collection(db, "orders");
  const q = query(ordersRef, where("orderBy.userId", "==", userId));
  const querySnapshot = await getDocs(q);

  let orders = [];
  querySnapshot.forEach((doc) => {
    if (doc.data()) {
      orders.push(doc.data());
    }
  });

  return orders;
}

Fetch user's orders when component mounted

useEffect(async () => {
  const userOrders = await getOrdersByUser();

  console.log({ userOrders });
}, []);


问:
Laravel return after post is null with stored procedure
I have store method with return like this :

```<code>return redirect()->route('hasil.transaksi', ["data" => $data]);
</code>```

with the route like this :

```<code>ROUTE::GET('hasil-transaksi', [KasirRajalController::class, 'hasilTransaksi'])->name('hasil.transaksi');
</code>```

And method return like this :

```<code>    public function hasilTransaksi(Request $request)
{
    $data["info"] = DB::select("EXEC spx_kasirirj_GetData
    @sdata = 2,
    @where = '" . $request->no_transaksi . "'
    ");

    dd($data);
}
</code>```

URL after store like this :

```<code>http://127.0.0.1:8000/hasil-transaksi?data%5B0%5D%5B%5D=0000260&data%5B0%5D%5Bno_transaksi%5D=KRJ22010001
</code>```

I want to catch no_transaksi=KRJ22010001  to paste in the method return above. But i don't get it, the result is null.

enter image description here

Please, help?

Full dd($request) :
enter image description here

答:
There are multiple things to review in your code:

return redirect()->route('hasil.transaksi', ["data" => $data]);

This will do a GET redirect, so the $data object will be added as GET parameter and encoded (from object to string). That is why your URL only parameter is "data" (http://127.0.0.1:8000/hasil-transaksi?data=) and then the encoded data.

Your decoded URL data looks like this data[0][]=0000260&data[0][no_transaksi]=KRJ22010001.

This format seems a bit strange, but I don't have enough code to confirm. You could do this (assuming you don't need your 0000260 parameter [that should be keyed]):

return redirect()->route('hasil.transaksi', ["no_transaksi" => $data[0]['no_transaksi']]);

This should generate a correct URL ?no_transaksi=xx and so $request->no_transaksi should work (that you should also sanitize).

@where = '" . $request->no_transaksi . "'

As @Joundill mentioned, this part of your raw query is opened to SQL injection. If you don't use Eloquent, Models or Requests, you should at least sanitize and validate the no_transaksi request param value.

Body:
I have store method with return like this :

return redirect()->route('hasil.transaksi', ["data" => $data]);

with the route like this :

ROUTE::GET('hasil-transaksi', [KasirRajalController::class, 'hasilTransaksi'])->name('hasil.transaksi');

And method return like this :

    public function hasilTransaksi(Request $request)
{
    $data["info"] = DB::select("EXEC spx_kasirirj_GetData
    @sdata = 2,
    @where = '" . $request->no_transaksi . "'
    ");

    dd($data);
}

URL after store like this :

http://127.0.0.1:8000/hasil-transaksi?data%5B0%5D%5B%5D=0000260&data%5B0%5D%5Bno_transaksi%5D=KRJ22010001

I want to catch no_transaksi=KRJ22010001  to paste in the method return above. But i don't get it, the result is null.

enter image description here

Please, help?

Full dd($request) :
enter image description here


问:
SQL 2005 Security Best Practices
What is the best way to encrypt a SQL 2005 database?

I have found things about the  with SQL 2008, and I've seen how to do column encryption in SQL 2005 - but it seems more difficult to access the table values then because you need to create a function or a view/stored procedure.

I also tried doing the file level security by using windows encryption (via a certificate) to encrypt the folder which held the database files, but then SQL Server Management Studio gave me errors on permissions (even after I gave it permissions).

I need to secure client data on our servers and I need to do it in a way that will not slow down our server too much, though I know it's inevitable due to the extra layer that encryption poses.

Am I missing something, or am I wrong? Please advise.

答:
Upgrade to SQL Server 2008 and use Transparent Database Encryption. Unlike column level encryption of SQL Server 2005, the 2008 TDE is, as the name implies, transparent. Requires no application changes. Also, the data is searchable, something which is always desirable but very difficult to achieve with column encryption or with client side encryption.

File level encryption does not really work with SQL Server. However, BitLocker does work with SQL Server so encrypting the entire volume with BitLocker is another viable alternative.

Title: SQL 2005 Security Best Practices


问:
Clear table using a button in objective-c
I'm trying to clear all from a table using a button.  Basically reset the table.  I use the following to remove one slice at a time but how do I clear all from the table?  Thank you in advance!</p>
```<code>- (IBAction)handleRemoveSliceTapped:(NSButton *)sender {
NSInteger selectedRow = [self.sliceTable selectedRow];
if (selectedRow < 0) {
    return;
}
if ([self.sliceTimes count] == 0)  {
    return;
}

NSIndexSet *removalSet = [NSIndexSet indexSetWithIndex:selectedRow];
[self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
[self.sliceTimes removeObjectAtIndex:selectedRow];
[self.sliceTable reloadData];
</code>```

答:
If your NSTableViewDataSource numberOfRowsInTableView returns 0, the table will become empty.

Therefore, you can just clear your view model, and reload the table:

```<code>[self.sliceTimes removeAllObjects];
[self.sliceTable reloadData];
</code>```

This is without animation. If you need the animation, include all row indexes in your NSIndexSet, and do the updates between beginUpdates/endUpdates (see https://developer.apple.com/documentation/appkit/nstableview/1527288-beginupdates?language=objc ):

```<code>NSIndexSet *removalSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.sliceTimes.count)];
[self.sliceTable beginUpdates];
[self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
[self.sliceTimes removeAllObjects];
[self.sliceTable endUpdates];
</code>```

Body:
I'm trying to clear all from a table using a button.  Basically reset the table.  I use the following to remove one slice at a time but how do I clear all from the table?  Thank you in advance!

- (IBAction)handleRemoveSliceTapped:(NSButton *)sender {
NSInteger selectedRow = [self.sliceTable selectedRow];
if (selectedRow < 0) {
    return;
}
if ([self.sliceTimes count] == 0)  {
    return;
}

NSIndexSet *removalSet = [NSIndexSet indexSetWithIndex:selectedRow];
[self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
[self.sliceTimes removeObjectAtIndex:selectedRow];
[self.sliceTable reloadData];

Body:
If your NSTableViewDataSource numberOfRowsInTableView returns 0, the table will become empty.

Therefore, you can just clear your view model, and reload the table:

[self.sliceTimes removeAllObjects];
[self.sliceTable reloadData];

This is without animation. If you need the animation, include all row indexes in your NSIndexSet, and do the updates between beginUpdates/endUpdates (see https://developer.apple.com/documentation/appkit/nstableview/1527288-beginupdates?language=objc ):

NSIndexSet *removalSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, self.sliceTimes.count)];
[self.sliceTable beginUpdates];
[self.sliceTable removeRowsAtIndexes:removalSet withAnimation:NSTableViewAnimationSlideUp];
[self.sliceTimes removeAllObjects];
[self.sliceTable endUpdates];