问:
Any way to do a local CVS proxy/server?
I have an online CVS repository that I need to check code into. However, the server is outside my control and is often down.

So, is there a way to set up some sort of local CVS server/proxy such that I can check my code into the local CVS server regularly and have the local CVS server batch commit the changes to the online CVS repo periodically?

The local repository could possibly run some other SCM system, if that was necessary to prevent conflict with CVS. Online commits could possibly be done manually, or via cron. I'm open to suggestions.

I guess that my main concern would be the problems faced in trying to set up some sort of repository 'hierarchy'.

PS: I'm running Linux all along the 'hierarchy'.

Edit: Found a similar item here.

答: Use git locally, and then git-cvsexportcommit would be my suggestion. There's a blog post that talks about this at http://issaris.blogspot.com/2005/11/cvs-to-git-and-back.html although I'll be the first to admit that the export process isn't as easy to use as perhaps it could be.</p>

OwnerDisplayName: sybreon

ContentLicense: CC BY-SA 2.5

Title: Any way to do a local CVS proxy/server?

LastEditorDisplayName: sybreon

OwnerDisplayName: Brian Mitchell


来源: stackexchange

问:
Full height & width, fixed header, full content height with CSS
I have been searching for this on SO, but I just could not find something exactly similar.
What I am trying to achieve is to have a page, that is full in height and in width, but does have a fixed header. The content height needs to be the remaining area left, but that area needs to have a height of 100%, most of the html code found on SO is just using height: auto. Basically I want to do this so that I can style it: adding border etc. Here's the code so far:</p>

```<code><html>
<head>
    <title>Test</title>
    <style type="text/css">
    body, html {
    height:100%;
    }

    body {
    margin:0;
    padding:0;
    }

    #header{
    height:50px;
    background:green;
    width:100%;
    }

    #wrapper {
    background:blue;
    position:relative;
    min-height:100%;
    height:auto !important;
    height:100%;
    }

    #content {
        margin: 10px;
        background-color: black;
        height: 100%;
        width: 100%;
border: 3px dashed gray;
    }
    </style>
</head>
<body>
    <div id="wrapper">
    <div id="header">header</div>
    <div id="content"></div>
    </div>
</body>
</html>
</code>```

答:
See: http://jsbin.com/agiyer

Note that if the content is too tall to fit inside #content, it will simply be hidden.

HTML:

header

content

```
<p><strong>CSS:</strong></p>
<pre class="lang-css prettyprint-override"><code>#header {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    background: green
}
#content {
    position: absolute;
    top: 50px;
    left: 0;
    bottom: 0;
    right: 0;
    border: 3px dashed gray;
    background: #ccc
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been searching for this on SO, but I just could not find something exactly similar.
What I am trying to achieve is to have a page, that is full in height and in width, but does have a fixed header. The content height needs to be the remaining area left, but that area needs to have a height of 100%, most of the html code found on SO is just using height: auto. Basically I want to do this so that I can style it: adding border etc. Here's the code so far:

    <title>Test</title>

header

Body:
See: http://jsbin.com/agiyer

Note that if the content is too tall to fit inside #content, it will simply be hidden.

HTML:

<div id="header">header</div>
<div id="content">content</div>

CSS:

#header {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 50px;
    background: green
}
#content {
    position: absolute;
    top: 50px;
    left: 0;
    bottom: 0;
    right: 0;
    border: 3px dashed gray;
    background: #ccc
}

ContentLicense: CC BY-SA 4.0


问:
How to see Guzzle HTTP Client request/response in Symfony's profiler
I'm using Symfony 5.2 and in the debug toolbar there's an HTTP Client section

My understanding is that it's primary made for the symfony's own http client https://symfony.com/components/HttpClient because it has the HTTPClientDataCollector

I would like to know it's possible to make Guzzle also implement this kind of data collector ? if so how to do it ? having the http request and response in the profiler would help debugging.

答: You could install a eightpoints/guzzle-bundle</p>


问:
Tailwindcss not working with next.js; what is wrong with the configuration?
For some reason, tailwind is not rendering properly in next.js.

I'm wondering if something is wrong with my settings?

Styles folder - tailwind.css

@tailwind base;

```<code>/* Write your own custom base styles here */

/* Start purging... */
@tailwind components;
/* Stop purging. */

/* Write you own custom component styles here */
.btn-blue {
  @apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}

/* Start purging... */
@tailwind utilities;
/* Stop purging. */

/* Your own custom utilities */
</code>```

....

_app.js

```<code>import React from "react";
// import "styles/global.scss";

import 'styles/tailwind.css'

import NavbarCustom from "components/Layout/NavbarCustom";
import Footer from "components/Layout/Footer";
import "util/analytics.js";
import { ProvideAuth } from "util/auth.js";

function MyApp({ Component, pageProps }) {
  return (
    <ProvideAuth>
      <>
        <NavbarCustom
          bg="white"
          variant="light"
          expand="md"
          logo="icons/Logo_512px.png"
        />

        <Component {...pageProps} />
</code>```

What am I doing wrong? so confused, usually this sort of setup is fine.

This is the site btw - https://moodmap.app/ .

using the information below, made changes and still same issue weirdly.

https://moodmap.app/ is the site example.

tailwind.config.js

```<code>module.exports = {
  future: {
    removeDeprecatedGapUtilities: true,
  },
  purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {
        'accent-1': '#333',
      },
    },
  },
  variants: {},
  plugins: [],
}
</code>```

postcss.config.js

```<code>module.exports = {
    plugins: [
      'tailwindcss',
      'postcss-flexbugs-fixes',
      [
        'postcss-preset-env',
        {
          autoprefixer: {
            flexbox: 'no-2009',
          },
          stage: 3,
          features: {
            'custom-properties': false,
          },
        },
      ],
    ],
  }

{
  "name": "MoodMap",
  "version": "0.1.0",
  "private": true,
  "keywords": [
    "MoodMap"
  ],
  "dependencies": {
    "@analytics/google-analytics": "0.2.2",
    "@stripe/stripe-js": "^1.5.0",
    "analytics": "0.3.1",
    "fake-auth": "0.1.7",
    "mailchimp-api-v3": "1.13.1",
    "next": "9.5.3",
    "query-string": "6.9.0",
    "raw-body": "^2.4.1",
    "rc-year-calendar": "^1.0.2",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "react-hook-form": "4.10.1",
    "react-query": "2.12.1",
    "react-transition-group": "^4.4.1",
    "stripe": "^8.52.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "stripe-webhook": "stripe listen --forward-to localhost:3000/api/stripe-webhook"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "postcss-flexbugs-fixes": "^4.2.1",
    "postcss-preset-env": "^6.7.0",
    "stylelint": "^13.7.1",
    "stylelint-config-standard": "^20.0.0",
    "tailwindcss": "^1.8.9"
  }
}
</code>```

Thanks!

答:
postcss.config.js

    module.exports = {
      plugins: {
        tailwindcss: {},
        autoprefixer: {},
      },
    }
```
<h6>tailwind.config.js</h6>
<hr />
```    module.exports = {
      mode: 'jit',
      content: [
        "./**/*.{js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
```
<h6>global.css</h6>
<hr />
<pre class="lang-css prettyprint-override"><code>    @tailwind base;
    @tailwind components;
    @tailwind utilities;
</code>```

Body:
For some reason, tailwind is not rendering properly in next.js.

I'm wondering if something is wrong with my settings?

Styles folder - tailwind.css

@tailwind base;

/* Write your own custom base styles here */

/* Start purging... */
@tailwind components;
/* Stop purging. */

/* Write you own custom component styles here */
.btn-blue {
  @apply bg-blue-500 text-white font-bold py-2 px-4 rounded;
}

/* Start purging... */
@tailwind utilities;
/* Stop purging. */

/* Your own custom utilities */

....

_app.js

import React from "react";
// import "styles/global.scss";

import 'styles/tailwind.css'

import NavbarCustom from "components/Layout/NavbarCustom";
import Footer from "components/Layout/Footer";
import "util/analytics.js";
import { ProvideAuth } from "util/auth.js";

function MyApp({ Component, pageProps }) {
  return (
    <ProvideAuth>
      <>
        <NavbarCustom
          bg="white"
          variant="light"
          expand="md"
          logo="icons/Logo_512px.png"
        />

        <Component {...pageProps} />

What am I doing wrong? so confused, usually this sort of setup is fine.

This is the site btw - https://moodmap.app/ .

using the information below, made changes and still same issue weirdly.

https://moodmap.app/ is the site example.

tailwind.config.js

module.exports = {
  future: {
    removeDeprecatedGapUtilities: true,
  },
  purge: ['./components/**/*.{js,ts,jsx,tsx}', './pages/**/*.{js,ts,jsx,tsx}'],
  theme: {
    extend: {
      colors: {
        'accent-1': '#333',
      },
    },
  },
  variants: {},
  plugins: [],
}

postcss.config.js

module.exports = {
    plugins: [
      'tailwindcss',
      'postcss-flexbugs-fixes',
      [
        'postcss-preset-env',
        {
          autoprefixer: {
            flexbox: 'no-2009',
          },
          stage: 3,
          features: {
            'custom-properties': false,
          },
        },
      ],
    ],
  }

{
  "name": "MoodMap",
  "version": "0.1.0",
  "private": true,
  "keywords": [
    "MoodMap"
  ],
  "dependencies": {
    "@analytics/google-analytics": "0.2.2",
    "@stripe/stripe-js": "^1.5.0",
    "analytics": "0.3.1",
    "fake-auth": "0.1.7",
    "mailchimp-api-v3": "1.13.1",
    "next": "9.5.3",
    "query-string": "6.9.0",
    "raw-body": "^2.4.1",
    "rc-year-calendar": "^1.0.2",
    "react": "16.12.0",
    "react-dom": "16.12.0",
    "react-hook-form": "4.10.1",
    "react-query": "2.12.1",
    "react-transition-group": "^4.4.1",
    "stripe": "^8.52.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "stripe-webhook": "stripe listen --forward-to localhost:3000/api/stripe-webhook"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "postcss-flexbugs-fixes": "^4.2.1",
    "postcss-preset-env": "^6.7.0",
    "stylelint": "^13.7.1",
    "stylelint-config-standard": "^20.0.0",
    "tailwindcss": "^1.8.9"
  }
}

Thanks!

Body:
postcss.config.js

    module.exports = {
      plugins: {
        tailwindcss: {},
        autoprefixer: {},
      },
    }

tailwind.config.js

    module.exports = {
      mode: 'jit',
      content: [
        "./**/*.{js,ts,jsx,tsx}",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }

global.css

    @tailwind base;
    @tailwind components;
    @tailwind utilities;


问:
React Native - Animated Functional Components
I love the React Native animated API but it conflicts heavily with my preferred way of writing components which is completely stateless functional components.

Take this component as an example. How would I make the Image animated without reverting to class syntax and a state variable to drive the Image style?

```<code>const Logo = () => (
  <View style={styles.container}>
    <View style={styles.imageContainer}>
      <Animated.Image
        resizeMode='contain'
        style={styles.image}
        source={require(img/sample.png')}
      />
    </View>
  </View>
)

export default Logo
</code>```

答:
If there are still wondering how to solve this, I manage to do it this way

export const Toggle = () => {
  const progress = useRef(new Animated.Value(0)).current;

  useEffect(() => {
    Animated.timing(progress, {
      toValue: 1,
      duration: 5000,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start();
  }, [progress]);

  return <LottieView source={require('./json/toggle.json')} autoPlay loop />;
};```

Body:
I love the React Native animated API but it conflicts heavily with my preferred way of writing components which is completely stateless functional components.

Take this component as an example. How would I make the Image animated without reverting to class syntax and a state variable to drive the Image style?

const Logo = () => (
  <View style={styles.container}>
    <View style={styles.imageContainer}>
      <Animated.Image
        resizeMode='contain'
        style={styles.image}
        source={require(img/sample.png')}
      />
    </View>
  </View>
)

export default Logo


问:
how to merge two arrays of objects in javascript?
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.</p>
```<code>let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]
</code>```

答:
We can convert the arrays into objects for better time complexity and merge them using a spread operator and generate the array at the end.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]
function merge(arr1, arr2){
  const merged_dict = {}
  const r_arr = []
  const arr = [...arr1,...arr2]
  arr.forEach(ele => {
    if(merged_dict[ele.name]){
      merged_dict[ele.name] = {...merged_dict[ele.name],...ele};
    }
    else{
      merged_dict[ele.name] = ele;
    }
  });
  for(let key in merged_dict){
    r_arr.push(merged_dict[key])
  }
  return r_arr
}

arr3 = merge(arr1, arr2)
console.log(arr3)```

Body:
here is a sample example where there are two arrays and we have a merge() to which we pass the arrays. the merge() should return the merged array such that it should merge the objects which have same name.

let arr1 = [
  {
    name: "Person1",
    age: 20
  },
  {
    name: "Person2",
    age: 30
  }
]

let arr2 = [
  {
    name: "Person1",
    email: "person1@mail.com"
  },
  {
    name: "Person3",
    age: 25
  }
]

arr3 = merge(arr1, arr2)

output :
arr3 should be :
[
 {
    name: "Person1",
    age: 20,
    email: "person1@mail.com"
  },
   {
    name: "Person2",
    age: 30
  },
   {
    name: "Person3",
    age: 25
  }
]


问:
RuntimeWarning: coroutine 'function' was never awaited
I have a class PersonalMessage with a function sendPersonalMessage that sends a message to a user in telegram.

```<code>class PersonalMessage:
def __init__(self):
    self.api_id = api_id,
    self.api_hash = api_hash,
    self.token = token,
    self.user_id_1 = user_id_1,
    self.phone = phone

async def sendPersonalMessage(self, message, user_id):
    client = TelegramClient('session', api_id, api_hash)
    await client.connect()
    if not client.is_user_authorized():
        await client.send_code_request(phone)
        await client.sign_in(phone, input('Enter the code: '))
    try:
        receiver = InputPeerUser(user_id, 0)
        await client.send_message(receiver, message, parse_mode='html')
    except Exception as e:
        print(e)
    client.disconnect()
</code>```

when I try to call the function in the main .py file like this:

```<code>elif there_exists(['send', 'send']):
    speak("What should I send?")
    response = takeCommand()
    PersonalMessage().sendPersonalMessage(response, user_id_1)
</code>```

it gives me this error: RuntimeWarning: coroutine 'PersonalMessage().sendPersonalMessage(response, user_id_1)' was never awaited

答:
You should probably do await PersonalMessage().sendPersonalMessage(response, user_id_1) instead of using asyncio.run to execute this individual coroutine, unless you want to lose the benefits of using asyncio (ability to run other coroutines concurrently).

asyncio.run should be the entry point of your whole program, and all your functions dealing with I/O should be declared as async def. The answers here and here elaborate a bit further.

Body:
I have a class PersonalMessage with a function sendPersonalMessage that sends a message to a user in telegram.

class PersonalMessage:
def __init__(self):
    self.api_id = api_id,
    self.api_hash = api_hash,
    self.token = token,
    self.user_id_1 = user_id_1,
    self.phone = phone

async def sendPersonalMessage(self, message, user_id):
    client = TelegramClient('session', api_id, api_hash)
    await client.connect()
    if not client.is_user_authorized():
        await client.send_code_request(phone)
        await client.sign_in(phone, input('Enter the code: '))
    try:
        receiver = InputPeerUser(user_id, 0)
        await client.send_message(receiver, message, parse_mode='html')
    except Exception as e:
        print(e)
    client.disconnect()

when I try to call the function in the main .py file like this:

elif there_exists(['send', 'send']):
    speak("What should I send?")
    response = takeCommand()
    PersonalMessage().sendPersonalMessage(response, user_id_1)

it gives me this error: RuntimeWarning: coroutine 'PersonalMessage().sendPersonalMessage(response, user_id_1)' was never awaited


问:
Array of string that looks like a date
If I have an array like:
let array = ["Friday, 11 February","Tuesday, 10 February","Friday, 04 March",  "Thursday, 17 February", "Today", "Monday, 9 February"];.
What I try to do is to find the closest date to today or the smaller and I don't want to take "Today".
Until now I tried:

```<code>let array = ["Friday, 11 February","Tuesday, 10 February","Friday, 04 March",  "Thursday, 17 February", "Today", "Monday, 9 February"];
array = array.map(el => el.split(", ").slice(1).join()).filter(el =>el)
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let closest = "";

for(let i = 0; i < array.length; i++){
    for(let j = 1; j < array.length; j++){
    let numberOne = array[i].match(/\d+/)[0];
    let monthOne = array[i].match(/\b[a-zA-Z]+\b/g)[0];
    let numberTwo = array[j].match(/\d+/)[0];
    let monthTwo = array[j].match(/\b[a-zA-Z]+\b/g)[0];
    if(+(numberOne) < +(numberTwo) && months.indexOf(monthOne) <= months.indexOf(monthTwo)){
      closest = array[i]
    }

  }
}
console.log(closest)
</code>```

Everything is ok but I want to know if I can transform in a Date and sort by date. Anyone have a solution to this or a cleaner way to find the closest date? The array is dynamic and until now I didn't find any date which is before today and to take that one. Thank you!

答:
I thought about the possibility that some dates could be the next year. The best example the end of December and the begining of January and I write the next code, which I hope can help someone</p>
```<code>let array = [
  "Tuesday, 03 January",
  "Thursday, 05 January",
  "Thursday, 29 December",
  "Monday, 02 January",
  "Friday, 30 December"
];
let now = new Date();
var datesArray = array.map((el) => el + " " + now.getFullYear());
datesArray = datesArray.map((el) => new Date(el));
datesArray = datesArray.map(el => {
  if (el.getTime() < now.getTime()) {
    return el = el.setFullYear(el.getFullYear() + 1)
  }else{
    return el = el.setFullYear(el.getFullYear())
  }
})
const closestIndex = datesArray.findIndex(el => el === Math.min(...datesArray));
console.log(array[closestIndex])
</code>```

Title: Array of string that looks like a date

Body:
If I have an array like:
let array = ["Friday, 11 February","Tuesday, 10 February","Friday, 04 March",  "Thursday, 17 February", "Today", "Monday, 9 February"];.
What I try to do is to find the closest date to today or the smaller and I don't want to take "Today".
Until now I tried:

let array = ["Friday, 11 February","Tuesday, 10 February","Friday, 04 March",  "Thursday, 17 February", "Today", "Monday, 9 February"];
array = array.map(el => el.split(", ").slice(1).join()).filter(el =>el)
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
let closest = "";

for(let i = 0; i < array.length; i++){
    for(let j = 1; j < array.length; j++){
    let numberOne = array[i].match(/\d+/)[0];
    let monthOne = array[i].match(/\b[a-zA-Z]+\b/g)[0];
    let numberTwo = array[j].match(/\d+/)[0];
    let monthTwo = array[j].match(/\b[a-zA-Z]+\b/g)[0];
    if(+(numberOne) < +(numberTwo) && months.indexOf(monthOne) <= months.indexOf(monthTwo)){
      closest = array[i]
    }

  }
}
console.log(closest)

Everything is ok but I want to know if I can transform in a Date and sort by date. Anyone have a solution to this or a cleaner way to find the closest date? The array is dynamic and until now I didn't find any date which is before today and to take that one. Thank you!

Body:
I thought about the possibility that some dates could be the next year. The best example the end of December and the begining of January and I write the next code, which I hope can help someone

let array = [
  "Tuesday, 03 January",
  "Thursday, 05 January",
  "Thursday, 29 December",
  "Monday, 02 January",
  "Friday, 30 December"
];
let now = new Date();
var datesArray = array.map((el) => el + " " + now.getFullYear());
datesArray = datesArray.map((el) => new Date(el));
datesArray = datesArray.map(el => {
  if (el.getTime() < now.getTime()) {
    return el = el.setFullYear(el.getFullYear() + 1)
  }else{
    return el = el.setFullYear(el.getFullYear())
  }
})
const closestIndex = datesArray.findIndex(el => el === Math.min(...datesArray));
console.log(array[closestIndex])


问:
Hot reload not working properly for Tailwind on WSL2
o/

Just started a new personal project with Remix & TailwindCSS. Everything works fine with raw Remix install, but the css hot reload is broken when I add Tailwind. The first class added is applied, but not the next ones.

I think it must be related to WSL2 (Windows Subsystem for Linux), because it works fine on my linux laptop.

My config is exactly the one describe on Remix documentation.

Env

```<code>WSL2 with Ubuntu 20.04
node: v16.13.2 (also tried with v17.4.0)
npm: v8.4.0
</code>```

app/root.tsx

```<code>...
import tailwindStylesUrl from "./tailwind.css";

export const links: LinksFunction = () => {
  return [
    {
      rel: "stylesheet",
      href: tailwindStylesUrl,
    },
  ];
};
...
</code>```

tailwind.config.js

```<code>module.exports = {
  content: ["./app/**/*.{ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};
</code>```

package.json

```<code>...
"scripts": {
    "build": "npm run build:css && remix build",
    "build:css": "tailwindcss -o ./app/tailwind.css",
    "dev": "concurrently \"npm run dev:css\" \"remix dev\"",
    "dev:css": "tailwindcss -o ./app/tailwind.css --watch",
    "postinstall": "remix setup node",
    "start": "remix-serve build"
  },
  "dependencies": {
    "@remix-run/react": "^1.1.3",
    "@remix-run/serve": "^1.1.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "remix": "^1.1.3"
  },
  "devDependencies": {
    "@remix-run/dev": "^1.1.3",
    "@types/react": "^17.0.24",
    "@types/react-dom": "^17.0.9",
    "concurrently": "^7.0.0",
    "tailwindcss": "^3.0.17",
    "typescript": "^4.1.2"
  },
...
</code>```

console

```<code>$ npm run dev

> dev
> concurrently "npm run dev:css" "remix dev"

[0]
[0] > dev:css
[0] > tailwindcss -o ./app/tailwind.css --watch
[0]
[1] (node:16121) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
[1] (Use `node --trace-warnings ...` to show where the warning was created)
[1] (node:16121) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time
[1] Watching Remix app in development mode...
[1]  Built in 258ms
[1] Remix App Server started at http://xxx.xx.xxx.xx:3000
[0]
[0] Rebuilding...
[0] Done in 117ms.
[1]  File changed: app/tailwind.css
[1]  Rebuilding...
[1]  Rebuilt in 48ms
[0]
[0] Rebuilding...
[0] Done in 14ms.
[1]  File changed: app/root.tsx
[1]  Rebuilding...
[1]  Rebuilt in 51ms
</code>```

Thanks for your help

答:
U can try it add it to tailwind.config:

{
safelist: process.env !== 'production' ? [
   {
     pattern: /.*?/,
   },
 ] : [],
}
```

Body:
o/

Just started a new personal project with Remix & TailwindCSS. Everything works fine with raw Remix install, but the css hot reload is broken when I add Tailwind. The first class added is applied, but not the next ones.

I think it must be related to WSL2 (Windows Subsystem for Linux), because it works fine on my linux laptop.

My config is exactly the one describe on Remix documentation.

Env

WSL2 with Ubuntu 20.04
node: v16.13.2 (also tried with v17.4.0)
npm: v8.4.0

app/root.tsx

...
import tailwindStylesUrl from "./tailwind.css";

export const links: LinksFunction = () => {
  return [
    {
      rel: "stylesheet",
      href: tailwindStylesUrl,
    },
  ];
};
...

tailwind.config.js

module.exports = {
  content: ["./app/**/*.{ts,tsx}"],
  theme: {
    extend: {},
  },
  plugins: [],
};

package.json

...
"scripts": {
    "build": "npm run build:css && remix build",
    "build:css": "tailwindcss -o ./app/tailwind.css",
    "dev": "concurrently \"npm run dev:css\" \"remix dev\"",
    "dev:css": "tailwindcss -o ./app/tailwind.css --watch",
    "postinstall": "remix setup node",
    "start": "remix-serve build"
  },
  "dependencies": {
    "@remix-run/react": "^1.1.3",
    "@remix-run/serve": "^1.1.3",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "remix": "^1.1.3"
  },
  "devDependencies": {
    "@remix-run/dev": "^1.1.3",
    "@types/react": "^17.0.24",
    "@types/react-dom": "^17.0.9",
    "concurrently": "^7.0.0",
    "tailwindcss": "^3.0.17",
    "typescript": "^4.1.2"
  },
...

console

$ npm run dev

> dev
> concurrently "npm run dev:css" "remix dev"

[0]
[0] > dev:css
[0] > tailwindcss -o ./app/tailwind.css --watch
[0]
[1] (node:16121) ExperimentalWarning: stream/web is an experimental feature. This feature could change at any time
[1] (Use `node --trace-warnings ...` to show where the warning was created)
[1] (node:16121) ExperimentalWarning: buffer.Blob is an experimental feature. This feature could change at any time
[1] Watching Remix app in development mode...
[1]  Built in 258ms
[1] Remix App Server started at http://xxx.xx.xxx.xx:3000
[0]
[0] Rebuilding...
[0] Done in 117ms.
[1]  File changed: app/tailwind.css
[1]  Rebuilding...
[1]  Rebuilt in 48ms
[0]
[0] Rebuilding...
[0] Done in 14ms.
[1]  File changed: app/root.tsx
[1]  Rebuilding...
[1]  Rebuilt in 51ms

Thanks for your help


问:
Laravel: Storing image custom name to db
I want to store a file name to my db so it can retrieve that image and display it, I have implemented something that prevents files with the same name being added to my images folder by adding the time of upload in front of the actual file name as seen in the '$newImageName' variable, my question is how do I pass the '$newImageName' to be stored as that in the db given with the current code I have?

```<code>public function store(Request $request)
{
    $this->validate($request, [
        'subject' => 'required|min:5',
        'tags' => 'required',
        'thread' => 'required|min:25',
        'image' => 'required|mimes:png,jpg,jpeg'
    ]);

    $newImageName = time() . '-' . $request->subject . '.' . $request->image->extension();

    $request->image->move(public_path('images'), $newImageName);

    $thread = auth()->user()->marketthreads()->create($request->all());

    $thread->tags()->attach($request->tags);

    return back()->withMessage('Market thread has been created');
</code>```

Any help will be highly appreciated

Thank you :)

答:
You need to create a table in your database for storing the images. In your table, you basically need an ID and the name of the image file in your storage, in your case called $newImageName. You can do this by migration as below:

```<code>Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->string('filename');
    $table->timestamps();
});
</code>```

Tip: the timestamp store your image creation time so you wouldn't need to store it in your filename. Instead, later after the creation of the item, you can retrieve the ID generated by the new Object to use for your filename in order to prevent overwriting. This is a bit more secure approach as there is a nuance possibility of simultaneous uploads with the same name.

In your controller whenever you are uploading a new item, do accordingly:

```<code>$image = new Image();
$image->filename = $newImageName;
$image->save();
</code>```

This will save the Image filename in your DB for further usage.

Tip: If you want to go further on creating a more structured design, you can go ahead and create a Model for your Image and attach them to your other Models, in case of retrieving them in an easier way.

Body:
I want to store a file name to my db so it can retrieve that image and display it, I have implemented something that prevents files with the same name being added to my images folder by adding the time of upload in front of the actual file name as seen in the '$newImageName' variable, my question is how do I pass the '$newImageName' to be stored as that in the db given with the current code I have?

public function store(Request $request)
{
    $this->validate($request, [
        'subject' => 'required|min:5',
        'tags' => 'required',
        'thread' => 'required|min:25',
        'image' => 'required|mimes:png,jpg,jpeg'
    ]);

    $newImageName = time() . '-' . $request->subject . '.' . $request->image->extension();

    $request->image->move(public_path('images'), $newImageName);

    $thread = auth()->user()->marketthreads()->create($request->all());

    $thread->tags()->attach($request->tags);

    return back()->withMessage('Market thread has been created');

Any help will be highly appreciated

Thank you :)

Body:
You need to create a table in your database for storing the images. In your table, you basically need an ID and the name of the image file in your storage, in your case called $newImageName. You can do this by migration as below:

Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->string('filename');
    $table->timestamps();
});

Tip: the timestamp store your image creation time so you wouldn't need to store it in your filename. Instead, later after the creation of the item, you can retrieve the ID generated by the new Object to use for your filename in order to prevent overwriting. This is a bit more secure approach as there is a nuance possibility of simultaneous uploads with the same name.

In your controller whenever you are uploading a new item, do accordingly:

$image = new Image();
$image->filename = $newImageName;
$image->save();

This will save the Image filename in your DB for further usage.

Tip: If you want to go further on creating a more structured design, you can go ahead and create a Model for your Image and attach them to your other Models, in case of retrieving them in an easier way.


问:
PUT command Snowflake on VSCode
I use the snowflake driver for SQLTools on vscode and i'm connect to my snowflake account but i'm some issues when i want to put some files with extensions .csv from my local machine to my stage in snowflake. Indeed, when i use the command put file:///mypath/file.csv @nameofmystage; it works on terminal but not in the window vscode with extension Snowflake driver. However, others commands like copy into works on the driver vscode ...

The error's message is Unsupported feature 'unsupported_requested_format:snowflake'

thanks in advance for your help

答:
Based on the PUT documentation, currently PUT is not supported in .NET driver.

Snowflake Driver for SQLTools does not look like a driver from Snowflake, as it was not mentioned here:

Connectors & Drivers

I am not sure how the driver is built, but given both vscode and .NET are both MS product, I assume that it is not supported, but hope others can help to verify.

Title: PUT command Snowflake on VSCode


问:
display html select (from PHP) via jquery?
So I have a PHP backend that pulls some data from SQL,  let's just say its a list of user ID numbers.

I want to be able to display that list in an html select, via jquery, after a button click.

In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery.  Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.

How would you do it?

a fill-in-the-blanks code example follows:

idea 1:

```<code>function button_click() {

               $.ajax({
                url: "PHP_backend.php",  // this does the sql query and returns the results
                type: 'POST',
                data: 'returnquery',

                    success: function(result) {
                    //?????  put the result array or whatever into a submit, perhaps with a foreach or something similar..??

                    }
                }); // end ajax

            }
</code>```

Or idea 2:

```<code>$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}

function button_click() {
///  create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}
</code>```

答: if the web page is "public" (not for an intranet, behind a vpn), I strongly advise to not use any sql in jquery. It's simplistic to call the php ajax response file with arbitrary sql (ie what I want), and even modify anything in the data or database.</p>

Body:
So I have a PHP backend that pulls some data from SQL,  let's just say its a list of user ID numbers.

I want to be able to display that list in an html select, via jquery, after a button click.

In an attempt to partially answer my own question, I assume that I could either have a jquery function perform an ajax request, grab the data from PHP/SQL, and then somehow spit out the select with jquery.  Or, I could perhaps do the SQL query via PHP right there on the page, and somehow have the jquery function grab the output from that and put it into a select.

How would you do it?

a fill-in-the-blanks code example follows:

idea 1:

function button_click() {

               $.ajax({
                url: "PHP_backend.php",  // this does the sql query and returns the results
                type: 'POST',
                data: 'returnquery',

                    success: function(result) {
                    //?????  put the result array or whatever into a submit, perhaps with a foreach or something similar..??

                    }
                }); // end ajax

            }

Or idea 2:

$result = mysql_query("SELECT userIDnumbers FROM users",$db);
while ($row = mysql_fetch_array($result)){
/// throw these results into an array or similar, $userIDarray[]
/// maybe I could have this PHP create hidden html fields for each row, and insert its value, and then get that via jquery
}

function button_click() {
///  create the html select, displaying the values from the sql query
/// get values from hidden html fields?
}


问:
How to store the result of remote hive query to a file
I'm trying to run a hive query on Google Compute Engine. My Hadoop service is on Google Dataproc.
I submit the hive job using this command -

```<code>gcloud dataproc jobs submit hive --region=my-region --cluster=my-cluster-name -f file.hql > result.txt
</code>```

and

```<code>gcloud dataproc jobs submit hive --region=my-region --cluster=my-cluster-name -e="use test;select * from emp;" > result.txt
</code>```

I expect to see the result of the query in result.txt but this is all I get in the txt file -

```<code>done: true
driverControlFilesUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/27f9-f4a5-4df2-a311-e41a92/jobs/ea7ab2164/
driverOutputResourceUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/1f309-f4a5-4df2-a311-e4182/jobs/eafab0e2164/driveroutput
hiveJob:
queryFileUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/1ff9-f4a5-4df2-a311-e412/jobs/ea781f64/staging/file.hql
jobUuid: 91db33-ee0e-391b-b46d-37b276
placement:
  clusterName: my-cluster-name
  clusterUuid: my-cluster-uuid
reference:
  jobId: ea7ab0e2164
  projectId: my-project
status:
  state: DONE
  stateStartTime: '2022-02-07T09:33:44.317237Z'
statusHistory:
- state: PENDING
  stateStartTime: '2022-02-07T09:33:16.724561Z'
- state: SETUP_DONE
  stateStartTime: '2022-02-07T09:33:16.762680Z'
- details: Agent reported job success
  state: RUNNING
  stateStartTime: '2022-02-07T09:33:18.403518Z'
yarnApplications:
- name: HIVE-94a5b7-8bc7-4dc9-a016-81ab721
  progress: 1.0
  state: RUNNING
  trackingUrl: http://my-cluster-name:8088/proxy/application_1692_0008/
</code>```

Any help would be appreciated. Thanks.

答: Query result is in stderr. Try &> result.txt to redirect both stdout and stderr, or 2> result.txt to redirect stderr only.

Body:
I'm trying to run a hive query on Google Compute Engine. My Hadoop service is on Google Dataproc.
I submit the hive job using this command -

gcloud dataproc jobs submit hive --region=my-region --cluster=my-cluster-name -f file.hql > result.txt

and

gcloud dataproc jobs submit hive --region=my-region --cluster=my-cluster-name -e="use test;select * from emp;" > result.txt

I expect to see the result of the query in result.txt but this is all I get in the txt file -

done: true
driverControlFilesUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/27f9-f4a5-4df2-a311-e41a92/jobs/ea7ab2164/
driverOutputResourceUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/1f309-f4a5-4df2-a311-e4182/jobs/eafab0e2164/driveroutput
hiveJob:
queryFileUri: gs://my-gcs-bucket-for-dataproc/google-cloud-dataproc-metainfo/1ff9-f4a5-4df2-a311-e412/jobs/ea781f64/staging/file.hql
jobUuid: 91db33-ee0e-391b-b46d-37b276
placement:
  clusterName: my-cluster-name
  clusterUuid: my-cluster-uuid
reference:
  jobId: ea7ab0e2164
  projectId: my-project
status:
  state: DONE
  stateStartTime: '2022-02-07T09:33:44.317237Z'
statusHistory:
- state: PENDING
  stateStartTime: '2022-02-07T09:33:16.724561Z'
- state: SETUP_DONE
  stateStartTime: '2022-02-07T09:33:16.762680Z'
- details: Agent reported job success
  state: RUNNING
  stateStartTime: '2022-02-07T09:33:18.403518Z'
yarnApplications:
- name: HIVE-94a5b7-8bc7-4dc9-a016-81ab721
  progress: 1.0
  state: RUNNING
  trackingUrl: http://my-cluster-name:8088/proxy/application_1692_0008/

Any help would be appreciated. Thanks.


问:
.NET 6 Minimal API and multipart/form-data
Using the .NET 6 Minimal API, I'm trying to handle multipart/form-data in the POST method. However, with the following code:

app.MapPost("/tickets", async (IFreshdeskApiService s, [FromForm] CreateTicketDto dto) => await s.Add(dto))
   .Accepts<CreateTicketDto>("multipart/form-data");
```
<p>I'm receiving 400 Bad Request with body:</p>
<pre class="lang-json prettyprint-override"><code>{
    "error": "Expected a supported JSON media type but got \"multipart/form-data; boundary=--------------------------391539519671819893009831\"."
}
</code>```

I switched to the non-minimal API (i.e. using app.MapControllers()), but is there any way to handle this in minimal API?

答:
Please see the Explicit Parameter Binding section of Minimal APIs overview:

Binding from form values is not supported in .NET 6.

So, unfortunately, using [FromForm] attribute and binding from forms is not supported in .NET 6 in minimal APIs.

Custom Model Binding Workaround

There is a workaround using custom model binding.  This was inspired by Ben Foster's post Custom Model Binding in ASP.NET 6.0 Minimal APIs.  The basic idea is to add a BindAsync method to your type/class with the following signature:

public static ValueTask<TModel?> BindAsync(HttpContext httpContext, ParameterInfo parameter)
```
<p>For your example I created a simple <code>record</code> with 3 properties <code>Id</code>, <code>Name</code> and <code>Status</code>.  Then you use <code>HttpContext.Request.Form</code> collection to get the required values from the <code>Request</code>:</p>
<pre class="lang-cs prettyprint-override"><code>public record CreateTicketDto(int Id, string Name, string Status)
{
    public static ValueTask<CreateTicketDto?> BindAsync(HttpContext httpContext, ParameterInfo parameter)
    {
        // parse any values required from the Request
        int.TryParse(httpContext.Request.Form["Id"], out var id);

        // return the CreateTicketDto
        return ValueTask.FromResult<CreateTicketDto?>(
            new CreateTicketDto(
                id,
                httpContext.Request.Form["Name"],
                httpContext.Request.Form["Status"]
            )
        );
    }
}
</code>```

Now you can send data to the API using FormData without receiving an error.

Personally, I would remove the [FromForm] attribute from the endpoint, however, in my testing it works with or without it.  The above technique will work with class types too, not just records.

Simpler alternative

A simpler implementation is to pass HttpContext into the action and read all values from the ctx.Request.Form collection. In this case your action might look something like the following:

app.MapPost("/tickets", (HttpContext ctx, IFreshdeskApiService s) =>
{
    // read value from Form collection
    int.TryParse(ctx.Request.Form["Id"], out var id);
    var name = ctx.Request.Form["Name"];
    var status = ctx.Request.Form["Status"];

    var dto = new CreateTicketDto(id, name, status);

    s.Add(dto);
    return Results.Accepted(value: dto);
});
```

Body:
Using the .NET 6 Minimal API, I'm trying to handle multipart/form-data in the POST method. However, with the following code:

app.MapPost("/tickets", async (IFreshdeskApiService s, [FromForm] CreateTicketDto dto) => await s.Add(dto))
   .Accepts<CreateTicketDto>("multipart/form-data");

I'm receiving 400 Bad Request with body:

{
    "error": "Expected a supported JSON media type but got \"multipart/form-data; boundary=--------------------------391539519671819893009831\"."
}

I switched to the non-minimal API (i.e. using app.MapControllers()), but is there any way to handle this in minimal API?

Body:
Please see the Explicit Parameter Binding section of Minimal APIs overview:

Binding from form values is not supported in .NET 6.

So, unfortunately, using [FromForm] attribute and binding from forms is not supported in .NET 6 in minimal APIs.

Custom Model Binding Workaround

There is a workaround using custom model binding.  This was inspired by Ben Foster's post Custom Model Binding in ASP.NET 6.0 Minimal APIs.  The basic idea is to add a BindAsync method to your type/class with the following signature:

public static ValueTask<TModel?> BindAsync(HttpContext httpContext, ParameterInfo parameter)

For your example I created a simple record with 3 properties Id, Name and Status.  Then you use HttpContext.Request.Form collection to get the required values from the Request:

public record CreateTicketDto(int Id, string Name, string Status)
{
    public static ValueTask<CreateTicketDto?> BindAsync(HttpContext httpContext, ParameterInfo parameter)
    {
        // parse any values required from the Request
        int.TryParse(httpContext.Request.Form["Id"], out var id);

        // return the CreateTicketDto
        return ValueTask.FromResult<CreateTicketDto?>(
            new CreateTicketDto(
                id,
                httpContext.Request.Form["Name"],
                httpContext.Request.Form["Status"]
            )
        );
    }
}

Now you can send data to the API using FormData without receiving an error.

Personally, I would remove the [FromForm] attribute from the endpoint, however, in my testing it works with or without it.  The above technique will work with class types too, not just records.

Simpler alternative

A simpler implementation is to pass HttpContext into the action and read all values from the ctx.Request.Form collection. In this case your action might look something like the following:

app.MapPost("/tickets", (HttpContext ctx, IFreshdeskApiService s) =>
{
    // read value from Form collection
    int.TryParse(ctx.Request.Form["Id"], out var id);
    var name = ctx.Request.Form["Name"];
    var status = ctx.Request.Form["Status"];

    var dto = new CreateTicketDto(id, name, status);

    s.Add(dto);
    return Results.Accepted(value: dto);
});


问:
Azure Machine Learning Service - Environment variables defined in Environment not accessible from init() method in entry_script
I am deploying a model to AKS via AML using the python-sdk, and I am facing a problem accessing the environment variables defined for the Environment object myenvused for the deployment.

```<code># add environment variable
myenv.environment_variables = {'SOME_ENV_VARIABLE': 'ABC'}
# register to workspace
myenv.register(ws)
</code>```

This environment object is stated in the inference configuration for the deployment:

```<code>myenv = Environment.get(workspace=ws,name="myenv")
inference_config = InferenceConfig(entry_script='score.py',
                                      source_directory=os.path.abspath(__file__ + "//.."),
                                      environment=myenv,
                                      enable_gpu=True,
                                      description="...")
</code>```

When the model executes, the init() method in the entry_script score.py should be able to access these environment variables by calling os.environ['SOME_ENV_VARIABLE']. However, that is not working. The conda and pip packages defined in myenv are present in the image.

Shouldn't it be possible to access these env variables from the entry_script?

答:
I just tested environment_variables from an Environment ojb. It works. I also included a couple of environment variables for an inference environment.

python sdk v1.38.0.

The solution I used more or less the same as what was described above. After model was deployed in ACI, the environment variables are visible from properties (Containers -> Properties) e.g., enter image description here

Body:
I am deploying a model to AKS via AML using the python-sdk, and I am facing a problem accessing the environment variables defined for the Environment object myenvused for the deployment.

# add environment variable
myenv.environment_variables = {'SOME_ENV_VARIABLE': 'ABC'}
# register to workspace
myenv.register(ws)

This environment object is stated in the inference configuration for the deployment:

myenv = Environment.get(workspace=ws,name="myenv")
inference_config = InferenceConfig(entry_script='score.py',
                                      source_directory=os.path.abspath(__file__ + "//.."),
                                      environment=myenv,
                                      enable_gpu=True,
                                      description="...")

When the model executes, the init() method in the entry_script score.py should be able to access these environment variables by calling os.environ['SOME_ENV_VARIABLE']. However, that is not working. The conda and pip packages defined in myenv are present in the image.

Shouldn't it be possible to access these env variables from the entry_script?


问:
Doctrine 2 | Criteria vs DQL | Performance & Usability
I was wondering what is the best practice for fetching collections by complex queries in Doctrine 2. I have been using the Cirteria matching functionality, but I want to know if it is usable for large scale databases.

```<code>$expr = Criteria::expr();
$criteria = Criteria::create();
$criteria->where(
  $expr->andX(
    $expr->gte('start', $start),
    $expr->lte('end', $end)
  )
);

$result = (new ArrayCollection($em->getRepository(Entity::class)->findAll())->matching($criteria);
</code>```

What is the difference in performace with same filter written in DQL.

```<code>$qb = $em->createQueryBuilder();
$qb->select('e')
    ->from('Entity', 'e')
    ->where('e.start >= :start')
    ->andWhere('e.end <= :end')
    ->setParameters(array('start' => $start, 'end' => $end));

return $qb->getQuery()->getArrayResult();
</code>```

And a native SQL one.

```<code>$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entity', 'e');

$query = $this->_em->createNativeQuery('SELECT * FROM Entity WHERE start >= ? AND end <= ?', $rsm);
$query->setParameter(1, $start);
$query->setParameter(2, $end);

$result = $query->getResult();
</code>```

I really like the criteria one as it is easy to read and easy to maintain. But is it usable? How does the performace suffer when fetching 1 000, 10 000 or even 100 000 records.

The second question is does the Doctrine Criteria fetches all result and then filters them or does it create the specific query first?
The docs says this, but does it apply to my case?

"Collections have a filtering API that allows to slice parts of data from a collection. If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections."

Doctrine 2 Criteria documentation

答:
The problem is that you are using Criteria to match records after calling findAll() in your Repo. You should use criteria direct over your Repo, not to the array collection.

                    $criteria = new Criteria();
                    $criteria->where(Criteria::expr()->gte('legajo', $this->legajoDesde));
                    $criteria->andWhere(Criteria::expr()->lte('legajo', $this->legajoHasta));
                    $criteria->andWhere(Criteria::expr()->eq('idOrganizacion', $this->idOrganizacion));
                    $criteria->orderBy(['legajo' => Criteria::ASC]);
                    $empleados = $empleadoRepository->matching($criteria);
```

Body:
I was wondering what is the best practice for fetching collections by complex queries in Doctrine 2. I have been using the Cirteria matching functionality, but I want to know if it is usable for large scale databases.

$expr = Criteria::expr();
$criteria = Criteria::create();
$criteria->where(
  $expr->andX(
    $expr->gte('start', $start),
    $expr->lte('end', $end)
  )
);

$result = (new ArrayCollection($em->getRepository(Entity::class)->findAll())->matching($criteria);

What is the difference in performace with same filter written in DQL.

$qb = $em->createQueryBuilder();
$qb->select('e')
    ->from('Entity', 'e')
    ->where('e.start >= :start')
    ->andWhere('e.end <= :end')
    ->setParameters(array('start' => $start, 'end' => $end));

return $qb->getQuery()->getArrayResult();

And a native SQL one.

$rsm = new ResultSetMapping;
$rsm->addEntityResult('Entity', 'e');

$query = $this->_em->createNativeQuery('SELECT * FROM Entity WHERE start >= ? AND end <= ?', $rsm);
$query->setParameter(1, $start);
$query->setParameter(2, $end);

$result = $query->getResult();

I really like the criteria one as it is easy to read and easy to maintain. But is it usable? How does the performace suffer when fetching 1 000, 10 000 or even 100 000 records.

The second question is does the Doctrine Criteria fetches all result and then filters them or does it create the specific query first?
The docs says this, but does it apply to my case?

"Collections have a filtering API that allows to slice parts of data from a collection. If the collection has not been loaded from the database yet, the filtering API can work on the SQL level to make optimized access to large collections."

Doctrine 2 Criteria documentation


问:
SQLAlchemy engine.connect() fails for Snowflake using keypair authentication
My goal is to be able to write a pandas dataframe to Snowflake using the to_sql() function. I am able to successfuly query from Snowflake using read_sql() with no problems. It appears that to_sql() requires a slightly different configuration I can't figure out. I've tried two different approaches that I've outlined below.

I'm guessing, but could be wrong that the keypair authentication seems to be the problem. When I remove the private key parameter in both approaches, I get an error that the password is missing, rather than the particularly unclear errors I get otherwise. Perhaps not having the password specified is short circuiting the attempt and I really have another problem.

Alternately, if there is a better way to write an entire pandas dataframe to Snowflake I'm happy to entertain other options.

<s>Method 1 Snowflake Connector</s>

edit: it appears that sqllite is the only database supported if the connection isn't a SQLAlchemy connection.

This approach fails with DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting

```<code>import snowflake

conn = snowflake.connector.connect(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    private_key=pkb,
)

df.to_sql('TABLENAME', con=conn, if_exists='replace', index=False)
</code>```

Method 2 - SQLAlchemy Engine

I've found documentation on how to use a private key with SQLAlchemy. However, it fails with ValueError: Invalid IPv6 URL on the call to engine.connect()...

```<code>from snowflake.sqlalchemy import URL
from sqlalchemy import create_engine

engine = create_engine(URL(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    connect_args={
        'private_key': pkb,
    }
))

with engine.connect() as conn:
    df.to_sql('TABLENAME', con=conn, if_exists='replace', index=False)
</code>```

The traceback for both these errors are very long, but I'm happy to post them if it would help troubleshoot.

答:
The problem with #2 is that you missed a closure. The connect_args is part of the sqlalchemy.crate_engine call, not the snowflake.sqlalchemy.URL one.

Corrected code (as documented at the snowflake-sqlalchemy GitHub README):

```<code>engine = create_engine(URL(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    ),
    connect_args={
        'private_key': pkb,
    }
)
</code>```

Body:
My goal is to be able to write a pandas dataframe to Snowflake using the to_sql() function. I am able to successfuly query from Snowflake using read_sql() with no problems. It appears that to_sql() requires a slightly different configuration I can't figure out. I've tried two different approaches that I've outlined below.

I'm guessing, but could be wrong that the keypair authentication seems to be the problem. When I remove the private key parameter in both approaches, I get an error that the password is missing, rather than the particularly unclear errors I get otherwise. Perhaps not having the password specified is short circuiting the attempt and I really have another problem.

Alternately, if there is a better way to write an entire pandas dataframe to Snowflake I'm happy to entertain other options.

<s>Method 1 Snowflake Connector</s>

edit: it appears that sqllite is the only database supported if the connection isn't a SQLAlchemy connection.

This approach fails with DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master WHERE type='table' AND name=?;': not all arguments converted during string formatting

import snowflake

conn = snowflake.connector.connect(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    private_key=pkb,
)

df.to_sql('TABLENAME', con=conn, if_exists='replace', index=False)

Method 2 - SQLAlchemy Engine

I've found documentation on how to use a private key with SQLAlchemy. However, it fails with ValueError: Invalid IPv6 URL on the call to engine.connect()...

from snowflake.sqlalchemy import URL
from sqlalchemy import create_engine

engine = create_engine(URL(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    connect_args={
        'private_key': pkb,
    }
))

with engine.connect() as conn:
    df.to_sql('TABLENAME', con=conn, if_exists='replace', index=False)

The traceback for both these errors are very long, but I'm happy to post them if it would help troubleshoot.

Body:
The problem with #2 is that you missed a closure. The connect_args is part of the sqlalchemy.crate_engine call, not the snowflake.sqlalchemy.URL one.

Corrected code (as documented at the snowflake-sqlalchemy GitHub README):

engine = create_engine(URL(
    account=acct,
    warehouse=wh,
    database=db,
    schema=sc,
    user=usr,
    ),
    connect_args={
        'private_key': pkb,
    }
)


问:
Get net::ERR from failed fetch in a try catch, it's not in the caught error
I am expecting an error, and don't need help preventing it. I want to handle it better.

I'm wrapping a fetch from isomorphic-fetch with a try catch,

let response;
try {
  response = await fetch(getFoosFromFooville(), { method: 'GET'})
} catch (error) {
  // TODO handle error; for not just print it
  console.log(error)
}
```
<p>And in the dev console I see an error like:</p>
```GET https://example.com/foos/fooville net::ERR_SOMETHING_RELEVANT_TO_FOOS
```
<p>That's not from my catch block. The console.log statement in the catch block just prints:</p>
```TypeError: Failed to fetch
  at Object.fooFetch (fooFetching.js?beef:42)
  at ...
```

It's much more useful if I could get the net::ERR_SOMETHING_RELEVANT and handle that.

Is that something I can do, or is it the library or native javascript it polyfills?

答:
Try this:

```<code>fetch(getFoosFromFooville(), { method: 'GET'})
  .then((response)=>
    console.log(response)
  })
  .catch((error)=>{
    console.log(error)
  })
</code>```

You can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Body:
I am expecting an error, and don't need help preventing it. I want to handle it better.

I'm wrapping a fetch from isomorphic-fetch with a try catch,

let response;
try {
  response = await fetch(getFoosFromFooville(), { method: 'GET'})
} catch (error) {
  // TODO handle error; for not just print it
  console.log(error)
}

And in the dev console I see an error like:

GET https://example.com/foos/fooville net::ERR_SOMETHING_RELEVANT_TO_FOOS

That's not from my catch block. The console.log statement in the catch block just prints:

TypeError: Failed to fetch
  at Object.fooFetch (fooFetching.js?beef:42)
  at ...

It's much more useful if I could get the net::ERR_SOMETHING_RELEVANT and handle that.

Is that something I can do, or is it the library or native javascript it polyfills?

Body:
Try this:

fetch(getFoosFromFooville(), { method: 'GET'})
  .then((response)=>
    console.log(response)
  })
  .catch((error)=>{
    console.log(error)
  })

You can read more about it here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch


问:
How to add value on a specific row if there is no value for the cell
I want to add some value like '#Nothing#' to my dataframe if row comes from left-only column and had nothing in the cell or if row comes from right-only column and has nothing in the cell. If something is in the cell, it should be left as it is.

The exercise was to join two dataframes in order to compare. I have used merge function with indicator set to true, so I know which rows come from which dataframe, my problem is how to fill empty cells in such rows with the value I want. If both leave it as it were.

The table looks like this now:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One

Three

left_only

Two

Four
right_only

One
Two

Four
both

The table looks should look like this:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One
#Nothing#
Three
#Nothing#
left_only

#Nothing#
Two
#Nothing#
Four
right_only

One
Two

Four
both

I had an idea to make few datamframes from the main one like this and then concat them, but I am getting this error:

```<code>data = {'some_name1_A': ['One', None, 'One', None], 'some_name1_B': [None, 'Two', None, 'Two'], 'some_name2_A': ['Three', None, 'Three', None],
        'some_name2_B': [None, 'Four', None, 'Four'], '_merge': ['left_only', 'right_only', 'both', 'right_only']}
df = pd.DataFrame(data)

df_A = df.loc[df_A['_merge'] == 'left_only']
df_A.fillna('#Nothing#', inplace=True)
df_B = df.loc[df_B['_merge'] == 'right_only']
df_B.fillna('#Nothing#', inplace=True)
</code>```

ValueError: Cannot setitem on a Categorical with a new category, set the categories first

答:
Make a fillna() on the rows that do not have both in column _merge:

>>> # avoid duplicate typing and create the selection rule once
>>> indx = df._merge != 'both'

>>> # modify only those rows (where 'indx' is True)
>>> df.loc[indx] = df.loc[indx].fillna('bla')
```
<p>Result:</p>
<pre class="lang-py prettyprint-override"><code>>>> df
  some_name1_A some_name1_B some_name2_A some_name2_B      _merge
0          One          bla        Three          bla   left_only
1          bla          Two          bla         Four  right_only
2          One         None        Three         None        both
3          bla          Two          bla         Four  right_only
</code>```

Body:
I want to add some value like '#Nothing#' to my dataframe if row comes from left-only column and had nothing in the cell or if row comes from right-only column and has nothing in the cell. If something is in the cell, it should be left as it is.

The exercise was to join two dataframes in order to compare. I have used merge function with indicator set to true, so I know which rows come from which dataframe, my problem is how to fill empty cells in such rows with the value I want. If both leave it as it were.

The table looks like this now:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One

Three

left_only

Two

Four
right_only

One
Two

Four
both

The table looks should look like this:

some_name1_A
some_name1_B
some_name2_A
some_name2_B
_merge

One
#Nothing#
Three
#Nothing#
left_only

#Nothing#
Two
#Nothing#
Four
right_only

One
Two

Four
both

I had an idea to make few datamframes from the main one like this and then concat them, but I am getting this error:

data = {'some_name1_A': ['One', None, 'One', None], 'some_name1_B': [None, 'Two', None, 'Two'], 'some_name2_A': ['Three', None, 'Three', None],
        'some_name2_B': [None, 'Four', None, 'Four'], '_merge': ['left_only', 'right_only', 'both', 'right_only']}
df = pd.DataFrame(data)

df_A = df.loc[df_A['_merge'] == 'left_only']
df_A.fillna('#Nothing#', inplace=True)
df_B = df.loc[df_B['_merge'] == 'right_only']
df_B.fillna('#Nothing#', inplace=True)

ValueError: Cannot setitem on a Categorical with a new category, set the categories first

Body:
Make a fillna() on the rows that do not have both in column _merge:

>>> # avoid duplicate typing and create the selection rule once
>>> indx = df._merge != 'both'

>>> # modify only those rows (where 'indx' is True)
>>> df.loc[indx] = df.loc[indx].fillna('bla')

Result:

>>> df
  some_name1_A some_name1_B some_name2_A some_name2_B      _merge
0          One          bla        Three          bla   left_only
1          bla          Two          bla         Four  right_only
2          One         None        Three         None        both
3          bla          Two          bla         Four  right_only


问:
Getting an error on json POST request with Cakephp
I'm relatively new to Cakephp and unfortunately have to work with it for this project.  The problem that I am having is my POST request is returning an error even though I am echoing a json string properly.

Here is my html and embedded javascript

```<code> <div class="submit">
   <input type="submit" onclick="results();" id="submit"></submit>
</div>
<script type="text/javascript">
function results() {
    var data = $('#ListingResultsForm').serialize();

    $.ajax({
        type: 'post',
        url: '/listings/results',
        data: data,
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {
            console.log(textStatus);
            console.log(jqXHR);
            console.log(data);
        },
        error: function(textStatus, errorThrown, jqXHR) {
            console.log(textStatus);
            console.log(jqXHR);
            console.log(errorThrown);
        }
    });
    return false;
}
</code>```

And here is my controller

```<code>function results() {
    $this->layout = 'ajax';
    $this->autoLayout = false;
    $this->autoRender = false;
    $conditions = array();
    if (!empty($this->data)) {
        ($this->data['Listing']['listing_countyid'] !== '') ?   $conditions['listing_countyid'] = $this->data['Listing']['listing_countyid'] : '';
        ($this->data['Listing']['listing_area'] !== '') ? $conditions['listing_area'] = $this->data['Listing']['listing_area'] : '';
        ($this->data['Listing']['listing_neighborhood'] !== '') ? $conditions['listing_neighborhood'] = $this->data['Listing']['listing_neighborhood'] : '';
        ($this->data['Listing']['min_price'] !== '') ? $conditions['listing_listprice >='] = $this->data['Listing']['min_price'] : '';
        ($this->data['Listing']['max_price'] !== '') ? $conditions['listing_listprice <='] = $this->data['Listing']['max_price'] : '';
        ($this->data['Listing']['min_listing_sqfttotal'] !== '') ? $conditions['listing_sqfttotal >='] = $this->data['Listing']['min_listing_sqfttotal'] : '';
        ($this->data['Listing']['max_listing_sqfttotal'] !== '') ? $conditions['listing_sqfttotal <='] = $this->data['Listing']['max_listing_sqfttotal'] : '';
        ($this->data['Listing']['min_stories'] !== '') ? $conditions['listing_stories >='] = $this->data['Listing']['min_stories'] : '';
        ($this->data['Listing']['listing_yearbuilt'] !== '') ? $conditions['listing_yearbuilt >='] = $this->data['Listing']['listing_yearbuilt'] : '';
        ($this->data['Listing']['min_bathrooms'] !== '') ?  $conditions['listing_bathstotal >='] = $this->data['Listing']['min_bathrooms'] : '';
        ($this->data['Listing']['max_bathrooms'] !== '') ?  $conditions['listing_bathstotal <='] = $this->data['Listing']['max_bathrooms'] : '';
        ($this->data['Listing']['min_bedrooms'] !== '') ? $conditions['listing_bedrooms >='] = $this->data['Listing']['min_bedrooms'] : '';
        ($this->data['Listing']['max_bedrooms'] !== '') ? $conditions['listing_bedrooms <='] = $this->data['Listing']['max_bedrooms'] : '';
        ($this->data['Listing']['level1_mstr'] !== '') ? $conditions['listing_roommasterbrlevel'] = $this->data['Listing']['level1_mstr'] : '';
        ($this->data['Listing']['level1_laundry'] !== '') ? $conditions['listing_roomlaundrylevel'] = $this->data['Listing']['level1_laundry'] : '';
        ($this->data['Listing']['heat_type'] !== '') ? $conditions['listing_heatsystem'] = $this->data['Listing']['heat_type'] : '';
        ($this->data['Listing']['cool_type'] !== '') ? $conditions['listing_coolsystem'] = $this->data['Listing']['cool_type'] : '';
        ($this->data['Listing']['irrigation_system'] !== '') ? $conditions['listing_irrigationsrc'] = $this->data['Listing']['irrigation_system'] : '';
        ($this->data['Listing']['fireplace'] !== '') ? $conditions['listing_fireplaces'] = $this->data['Listing']['fireplace'] : '';
        ($this->data['Listing']['handicap'] !== '') ? $conditions['listing_handicap'] = $this->data['Listing']['handicap'] : '';
        ($this->data['Listing']['fence'] !== '') ? $conditions['listing_fence'] = $this->data['Listing']['fence'] : '';
        $items = $this->Idx->find('all', array('conditions'=> $conditions));
        $this->header('Content-Type: application/json');
        echo json_encode($items);
        return;
    }
}
</code>```

Any help is greatly appreciated.

答:
See the accepted answer to this question, it highlights the proper "Cake" way of delivering json in your app.

Simply echo'ing in your controller is not very MVC and you are probably just getting errors in your response due to not having a view..

Body:
I'm relatively new to Cakephp and unfortunately have to work with it for this project.  The problem that I am having is my POST request is returning an error even though I am echoing a json string properly.

Here is my html and embedded javascript

   <input type="submit" onclick="results();" id="submit"></submit>


问:
Rails 7 - link_to with method :delete still performs GET request
I am trying to get this link to work, performing a DELETE request:

```<code><%= link_to "Sign Out", destroy_user_session_path, method: :delete %>
</code>```

However when I click on it, my browser still performs a GET request (which fails for obvious reasons):

I have read on multiple other forum posts, that this might have something to do with jquery not being included. They mentioned you would need to un-comment a line in app/javascript/application.js, however mine is pretty empty:

```<code>// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
</code>```

These forum posts were also quite old, so I suspect something has changed in the meantime.

答:
There are (at least) two ways to delete something in rails 7:

Using button_to (preferred IMHO):

```<code><%= button_to 'Sign Out', destroy_user_session_path, method: :delete %>
</code>```

Renders an HTML form which sends a POST request with a hidden _method attribute with 'delete' value. Rails will treat this as if it has a DELETE method (and route it to products#destroy or whatever your routes are saying). Do not use this one within another form (HTML forbids one form inside another).

Using link_to:

```<code><%= link_to 'Sign Out', destroy_user_session_path, data: {turbo_method: :delete} %>
</code>```

Renders a simple a tag with data-turbo-method attribute. This link sends a real DELETE request.

If your destroy action ends with a redirect_to, some browsers will redirect to a new location with DELETE method (causing errors), so make sure to add status: :see_other parameter to redirect_to, like the guides suggest.

Confirmation

If you want to add confirmation prompt to a button above:

```<code><%= button_to 'Sign Out', destroy_user_session_path, method: :delete,
  form: {data: {turbo_confirm: 'Are you sure?'}} %>
</code>```

If you want to add confirmation to a link above:

```<code><%= link_to 'Sign Out', destroy_user_session_path,
  data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>
</code>```

Body:
I am trying to get this link to work, performing a DELETE request:

<%= link_to "Sign Out", destroy_user_session_path, method: :delete %>

However when I click on it, my browser still performs a GET request (which fails for obvious reasons):

I have read on multiple other forum posts, that this might have something to do with jquery not being included. They mentioned you would need to un-comment a line in app/javascript/application.js, however mine is pretty empty:

// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"

These forum posts were also quite old, so I suspect something has changed in the meantime.

Body:
There are (at least) two ways to delete something in rails 7:

Using button_to (preferred IMHO):

<%= button_to 'Sign Out', destroy_user_session_path, method: :delete %>

Renders an HTML form which sends a POST request with a hidden _method attribute with 'delete' value. Rails will treat this as if it has a DELETE method (and route it to products#destroy or whatever your routes are saying). Do not use this one within another form (HTML forbids one form inside another).

Using link_to:

<%= link_to 'Sign Out', destroy_user_session_path, data: {turbo_method: :delete} %>

Renders a simple a tag with data-turbo-method attribute. This link sends a real DELETE request.

If your destroy action ends with a redirect_to, some browsers will redirect to a new location with DELETE method (causing errors), so make sure to add status: :see_other parameter to redirect_to, like the guides suggest.

Confirmation

If you want to add confirmation prompt to a button above:

<%= button_to 'Sign Out', destroy_user_session_path, method: :delete,
  form: {data: {turbo_confirm: 'Are you sure?'}} %>

If you want to add confirmation to a link above:

<%= link_to 'Sign Out', destroy_user_session_path,
  data: {turbo_method: :delete, turbo_confirm: 'Are you sure?'} %>


问:
Replace consecutive identic elements in the beginning of an array with 0
I want to replace the N first identic consecutive numbers from an array with 0.

```<code>import numpy as np

x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])
</code>```

OUT -> np.array([0, 0, 0, 0 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

Loop works, but what would be a faster-vectorized implementation?

```<code>i = 0
first = x[0]
while x[i] == first and i <= x.size - 1:
    x[i] = 0
    i += 1
</code>```

答:
My solution is based on itertools.groupby, so start from import itertools.

This function creates groups of consecutive equal values, contrary to e.g.
the pandasonic version of groupby, which collects withis a single group all
equal values from the input.

Another important feature is that you can assign any value to N and
replaced will be only the first N of a sequence of consecutive values.

To test my code, I set N = 4 and defined the source array as:

```<code>x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 2, 2, 2])
</code>```

Note that it contains 5 consecutive values of 2 at the end.

Then, to get the expected result, run:

```<code>rv = []
for key, grp in itertools.groupby(x):
    lst = list(grp)
    lgth = len(lst)
    if lgth >= N:
        lst[0:N] = [0] * N
    rv.extend(lst)
xNew = np.array(rv)
</code>```

The result is:

```<code>[0, 0, 0, 0, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 0, 0, 0, 0, 2]
</code>```

Note that a sequence of 4 zeroes occurs:

at the beginning (all 4 values of 1 have been replaced),

almost at the end (from 5 values of 2 first 4 have been replaced).

Body:
I want to replace the N first identic consecutive numbers from an array with 0.

import numpy as np

x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

OUT -> np.array([0, 0, 0, 0 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2])

Loop works, but what would be a faster-vectorized implementation?

i = 0
first = x[0]
while x[i] == first and i <= x.size - 1:
    x[i] = 0
    i += 1

Body:
My solution is based on itertools.groupby, so start from import itertools.

This function creates groups of consecutive equal values, contrary to e.g.
the pandasonic version of groupby, which collects withis a single group all
equal values from the input.

Another important feature is that you can assign any value to N and
replaced will be only the first N of a sequence of consecutive values.

To test my code, I set N = 4 and defined the source array as:

x = np.array([1, 1, 1, 1, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2, 2, 2, 2])

Note that it contains 5 consecutive values of 2 at the end.

Then, to get the expected result, run:

rv = []
for key, grp in itertools.groupby(x):
    lst = list(grp)
    lgth = len(lst)
    if lgth >= N:
        lst[0:N] = [0] * N
    rv.extend(lst)
xNew = np.array(rv)

The result is:

[0, 0, 0, 0, 2, 3, 1, 2, 3, 2, 2, 2, 3, 3, 3, 1, 1, 0, 0, 0, 0, 2]

Note that a sequence of 4 zeroes occurs:

at the beginning (all 4 values of 1 have been replaced),

almost at the end (from 5 values of 2 first 4 have been replaced).


问:
Remote IP address with node-js behind amazon ELB
I have a node application on an instance-store amazon machine behind the elastic load balancer (elb). However, the remote IP adress seems to always be the same. I used this code to get the client's IP address in node (via connect/express):

req.socket.remoteAddress
```

I didn't get anything else from the node documentation. Any hint?

答:
In case if express.js is in use:

```<code>app.set('trust proxy', 2)
</code>```

Instead of

```<code>app.enable('trust proxy')
</code>```

Because the app.enable('trust proxy') uses the leftmost ip from the x-forwarded-for header and so can be easily spoofed by just providing x-forwarded-for header manually.

While the app.set('trust proxy', 2) has the number of hops specified that being counted from right to left of the x-forwarded-for header. I.e. if there is an AWS load balancer than 2 will be the right number to count because each new hop ip is added to the end of the x-forwarded-for header.

If you're using something else then do the similar way. Just get the req.headers['x-forwarded-for'], split by coma and then count hops from  right to left until load balancer ip is not excluded.

Body:
I have a node application on an instance-store amazon machine behind the elastic load balancer (elb). However, the remote IP adress seems to always be the same. I used this code to get the client's IP address in node (via connect/express):

req.socket.remoteAddress

I didn't get anything else from the node documentation. Any hint?

Body:
In case if express.js is in use:

app.set('trust proxy', 2)

Instead of

app.enable('trust proxy')

Because the app.enable('trust proxy') uses the leftmost ip from the x-forwarded-for header and so can be easily spoofed by just providing x-forwarded-for header manually.

While the app.set('trust proxy', 2) has the number of hops specified that being counted from right to left of the x-forwarded-for header. I.e. if there is an AWS load balancer than 2 will be the right number to count because each new hop ip is added to the end of the x-forwarded-for header.

If you're using something else then do the similar way. Just get the req.headers['x-forwarded-for'], split by coma and then count hops from  right to left until load balancer ip is not excluded.


问:
Angular ng-select : selectedItems.map is not a function
When I'm using ng-select in reactive form angular I get this error:

ERROR TypeError: selectedItems.map is not a function

I have 3 select the first two work very well but in this third one I get the error ! to map item i'm using the function (the ng-select is inside *ngFor) :

```<code>//for mappinig item :
mapLabelValueBS(objet) {
return objet.map(data => {
 return {
   id: data,
   text: data.name
 }
})
}
//this is the one that is causing the problem
<ng-select
  [allowClear]="true"
  [items]="mapLabelValueBS(filieres)"
  placeholder="Filière non sélectionné"
  (selected)="selecteFiliere($event)"
  formControlName="filiere">
</ng-select>
</code>```

the result in my page (when I click on the field it doubles itself) :

答:
I had same problem, because the list of items was undefined sometime in the middle of page preparing, so I added a silly condition to show those select only when the list of items is ready:</p>
```<code><ng-select
  *ngIf="selectedItems.map"
  [allowClear]="true"
  [items]="jsonData | keyvalue"
  placeholder="Filière non sélectionné"
  (selected)="selecteFiliere($event)"
  formControlName="filiere">
</ng-select>
</code>```

Body:
When I'm using ng-select in reactive form angular I get this error:

ERROR TypeError: selectedItems.map is not a function

I have 3 select the first two work very well but in this third one I get the error ! to map item i'm using the function (the ng-select is inside *ngFor) :

//for mappinig item :
mapLabelValueBS(objet) {
return objet.map(data => {
 return {
   id: data,
   text: data.name
 }
})
}
//this is the one that is causing the problem
<ng-select
  [allowClear]="true"
  [items]="mapLabelValueBS(filieres)"
  placeholder="Filière non sélectionné"
  (selected)="selecteFiliere($event)"
  formControlName="filiere">
</ng-select>

the result in my page (when I click on the field it doubles itself) :

Body:
I had same problem, because the list of items was undefined sometime in the middle of page preparing, so I added a silly condition to show those select only when the list of items is ready:

<ng-select
  *ngIf="selectedItems.map"
  [allowClear]="true"
  [items]="jsonData | keyvalue"
  placeholder="Filière non sélectionné"
  (selected)="selecteFiliere($event)"
  formControlName="filiere">
</ng-select>


问:
Zigzag or wavy lines in matplotlib
Is there an easy way to draw a zigzag or wavy line in matplotlib?

I'm aware of the different line styles (http://matplotlib.org/examples/lines_bars_and_markers/line_styles_reference.html), and I'm of course aware that instead of plotting

```<code>plt.figure(); plt.plot(n.linspace(0.7,1.42,100),[0.7]*100)
</code>```

I could plot

```<code>plt.figure(); plt.plot(n.linspace(0.7,1.42,100),[0.69,0.71]*50)
</code>```

for a zigzag-line, but I was wondering whether there was a more straightforward way?

答:
You can apply the change in rcParams['path.sketch'] dictionary only to selected curves using with.

```<code>import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# prepare some fancy data
x = np.linspace(0,5,200)
y_0 = 10*x**0.2-x**1.5
y_1 = 20*np.sin(x)
y_2 = x**2

# prepare figure and axis
fig, ax = plt.subplots(nrows=1, ncols = 1, figsize = (5,3), dpi = 128)

# plot with some normal style
ax.plot(x, y_0, color = 'gray', ls='-.', lw = 2, label = 'normal style')

# now plot the wavy-like style!!!!
with mpl.rc_context({'path.sketch': (5, 15, 1)}):
    ax.plot(x, y_1, color = 'blue', label = 'wavy style!')

# again plot with some different normal style
ax.plot(x, y_2, color = 'orange', ls = '-', lw = 3, label = 'again normal style')

ax.legend(loc='best') # turn on legend with automatic best location
plt.show()
</code>```

Title: Zigzag or wavy lines in matplotlib

Body:
Is there an easy way to draw a zigzag or wavy line in matplotlib?

I'm aware of the different line styles (http://matplotlib.org/examples/lines_bars_and_markers/line_styles_reference.html), and I'm of course aware that instead of plotting

plt.figure(); plt.plot(n.linspace(0.7,1.42,100),[0.7]*100)

I could plot

plt.figure(); plt.plot(n.linspace(0.7,1.42,100),[0.69,0.71]*50)

for a zigzag-line, but I was wondering whether there was a more straightforward way?

Body:
You can apply the change in rcParams['path.sketch'] dictionary only to selected curves using with.

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

# prepare some fancy data
x = np.linspace(0,5,200)
y_0 = 10*x**0.2-x**1.5
y_1 = 20*np.sin(x)
y_2 = x**2

# prepare figure and axis
fig, ax = plt.subplots(nrows=1, ncols = 1, figsize = (5,3), dpi = 128)

# plot with some normal style
ax.plot(x, y_0, color = 'gray', ls='-.', lw = 2, label = 'normal style')

# now plot the wavy-like style!!!!
with mpl.rc_context({'path.sketch': (5, 15, 1)}):
    ax.plot(x, y_1, color = 'blue', label = 'wavy style!')

# again plot with some different normal style
ax.plot(x, y_2, color = 'orange', ls = '-', lw = 3, label = 'again normal style')

ax.legend(loc='best') # turn on legend with automatic best location
plt.show()


问:
I tried everything but it's show this error in React-Native
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native</p>
```<code>error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

  * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##
</code>```

答:
First make sure your environment is setup correctly as the documentation says.

If so, try these things:

cd android then ./gradlew clean

or else try to do delete node modules and run npm install

Body:
I Just Started Learning React Native after I completed my react js and this error show every time I create new React-Native Project and I loose hope to learn React-Native

error Failed to install the app. Make sure you have the Android development environment
set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01
Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http://schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http://schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http://schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http://schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http://schemas.android.com/sdk/android/repo/sys-img2/01

FAILURE: Build failed with an exception.

  * What went wrong:
    Execution failed for task ':app:processDebugMainManifest'.
    > Unable to make field private final java.lang.String java.io.File.path accessible: module java.base does not "opens java.io" to unnamed module @36838899

  * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  * Get more help at https://help.gradle.org

 BUILD FAILED in 12s

at makeError (D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:174:9)
at D:\React-Native\React Native Cli\AwesomeProject\node_modules\execa\index.js:278:16
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async runOnAllDevices (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\runOnAllDevices.js:109:5)
at async Command.handleAction (D:\React-Native\React Native Cli\AwesomeProject\node_modules\@react-native-community\cli\build\index.js:192:9)## Heading ##


问:
2checkout. How to sync Return URL order parameters with my orders in database?
I have a database, in which user orders are recorded.
Process:

The user goes to the product page on the site (I get the products through the admin panel's API), selects the product, clicks on the generated buy link goes to the payment page.

At this moment, this order is written to my database with the details of the order with the status "Unpaid".

Next, the user makes a payment and then clicks on the return URL and is redirected to my site.

Further on my site I get the data using the PHP GET method. Then, in case of successful payment, I need to change the status of the order to "Paid" in my database.

How can I identify the order that was recorded in the database before paying for the goods and the data that came through the return URL after the payment?

Here is my code of creating buy link and return URL, I dont know about correctness:

```<code>public function generateBuyLink($code, $qty)
    {
        $merchant = 'merchant=' . $this->merchantCode;
        $template = 'tpl=' . $this->template;
        $productCode = 'prod=' . $code;
        $quantity = 'qty=' . $qty;

        $data = strlen($this->redirectUrl) . $this->redirectUrl;
        $signature = 'signature=' . hash_hmac('md5', $data, $this->secretKey);
        $returnUrl = 'return-url=' . urlencode($this->redirectUrl);

        $buyLink = $this->buyLink . $merchant . '&' . $returnUrl . '&' . $template . '&' . $productCode . '&' . $quantity . '&' . $signature;

        // I get this link in the end:
        // https://secure.2checkout.com/checkout/buy?merchant=250366051775&return-url=https%3A%2F%2Fmy-site.loc%2Fuser%2Fcallback&return-type=link&tpl=default&prod=431956EE48&qty=1&signature=f701a8c816b1e880624ab0ea23d4c17bfdf05c5a843db2d3fcf86c57b32a0648
        return $buyLink;
    }
</code>```

答: The return URL should not be encoded.</p>

Body:
I have a database, in which user orders are recorded.
Process:

The user goes to the product page on the site (I get the products through the admin panel's API), selects the product, clicks on the generated buy link goes to the payment page.

At this moment, this order is written to my database with the details of the order with the status "Unpaid".

Next, the user makes a payment and then clicks on the return URL and is redirected to my site.

Further on my site I get the data using the PHP GET method. Then, in case of successful payment, I need to change the status of the order to "Paid" in my database.

How can I identify the order that was recorded in the database before paying for the goods and the data that came through the return URL after the payment?

Here is my code of creating buy link and return URL, I dont know about correctness:

public function generateBuyLink($code, $qty)
    {
        $merchant = 'merchant=' . $this->merchantCode;
        $template = 'tpl=' . $this->template;
        $productCode = 'prod=' . $code;
        $quantity = 'qty=' . $qty;

        $data = strlen($this->redirectUrl) . $this->redirectUrl;
        $signature = 'signature=' . hash_hmac('md5', $data, $this->secretKey);
        $returnUrl = 'return-url=' . urlencode($this->redirectUrl);

        $buyLink = $this->buyLink . $merchant . '&' . $returnUrl . '&' . $template . '&' . $productCode . '&' . $quantity . '&' . $signature;

        // I get this link in the end:
        // https://secure.2checkout.com/checkout/buy?merchant=250366051775&return-url=https%3A%2F%2Fmy-site.loc%2Fuser%2Fcallback&return-type=link&tpl=default&prod=431956EE48&qty=1&signature=f701a8c816b1e880624ab0ea23d4c17bfdf05c5a843db2d3fcf86c57b32a0648
        return $buyLink;
    }

Body: The return URL should not be encoded.


问:
Can we convert react-select styles to styled-components
Is there any way to convert the following styles (react-select) to the styled-components?

```<code>export const styles: StylesConfig<options, IsMulti> = {

    valueContainer: (provided, state) => ({
        ...provided,
        height: "30px",
    }),

    option: (provided, state) => ({
        ...provided,
        '&:hover': { backgroundColor: "#F7F7F7" },
        color: "#F7F7F7",
    }),

    control: (provided, state) => {
        return {
            ...provided,
            fontWeight: 100,
            '&:hover': {
                background: `linear-gradient(#F7F7F7, #F7F7F7), linear-gradient(75deg, #FD6453 50%, #FCD889 50%) border-box;`,
            },
        };
    }
};

</code>```

I used the below code

```<code>
import Select from "react-select";
---------------
---------------
---------------
<Select
   options={options}
   getOptionLabel={getOptionLabel}
   getOptionValue={getOptionValue}
   onChange={onChange}
   styles={styles}
/>
</code>```

Or is any alternative solution for this?
Thanks

答: I found a solution in github - https://github.com/JedWatson/react-select/issues/4230</p>

Body:
Is there any way to convert the following styles (react-select) to the styled-components?

export const styles: StylesConfig<options, IsMulti> = {

    valueContainer: (provided, state) => ({
        ...provided,
        height: "30px",
    }),

    option: (provided, state) => ({
        ...provided,
        '&:hover': { backgroundColor: "#F7F7F7" },
        color: "#F7F7F7",
    }),

    control: (provided, state) => {
        return {
            ...provided,
            fontWeight: 100,
            '&:hover': {
                background: `linear-gradient(#F7F7F7, #F7F7F7), linear-gradient(75deg, #FD6453 50%, #FCD889 50%) border-box;`,
            },
        };
    }
};

I used the below code

import Select from "react-select";
---------------
---------------
---------------
<Select
   options={options}
   getOptionLabel={getOptionLabel}
   getOptionValue={getOptionValue}
   onChange={onChange}
   styles={styles}
/>

Or is any alternative solution for this?
Thanks


问:
PyCharm Terminal has different Python than Mac Terminal
Running the below.

PyCharm shows:

```<code>% python -V
Python 2.7.16

% where python
bash: where: command not found
</code>```

whereas in Terminal it shows:

```<code>% python -V
Python 3.8.12

% where python
/Users/ryo/opt/anaconda3/bin/python
</code>```

Why is the PyCharm terminal using a different version of Python compared to my iOS Terminal? Any direction would be appreciated - I've Googled this extensively and searched through StackOverflow but this apparently simple problem is beyond me.

Not sure if it has anything to do with my PATH variable but pasted below for reference:

Mac Terminal

```<code>$PATH
/Users/ryo/opt/anaconda3/bin:/Users/ryo/opt/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
</code>```

The interpreter looks like this.

答: PyCharm as a convenience will set your terminal python to the project interpreter you have in your settings.  You can change it by going to Settings -> Project: <project name> -> Python Interpreter</p>

Body:
Running the below.

PyCharm shows:

% python -V
Python 2.7.16

% where python
bash: where: command not found

whereas in Terminal it shows:

% python -V
Python 3.8.12

% where python
/Users/ryo/opt/anaconda3/bin/python

Why is the PyCharm terminal using a different version of Python compared to my iOS Terminal? Any direction would be appreciated - I've Googled this extensively and searched through StackOverflow but this apparently simple problem is beyond me.

Not sure if it has anything to do with my PATH variable but pasted below for reference:

Mac Terminal

$PATH
/Users/ryo/opt/anaconda3/bin:/Users/ryo/opt/anaconda3/condabin:/Library/Frameworks/Python.framework/Versions/3.10/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

The interpreter looks like this.