问:
Jest unit test for datetime passes on local, but fails in Jenkins CICD
I am using date-fns to parse some date-like strings into dates, then back into into a string, like so. My local unit tests are passing, but in Jenkins CICD, my unit tests fail. I am pretty sure it is due to the Jenkins machine being in GMT+0, while I am in a GMT+8 timezone. The results of the failed tests in Jenkins supports this, as the received values are 8 hours behind the expected values.

```<code>import { format } from 'date-fns';

function stringToTime(date: string) {
    const newDate = new Date(date);
    return format(newDate, 'k:mm'); // this returns a string
}
</code>```

And my unit tests:

```<code>const sampleText = 'Mon Aug 02 2021 22:00:15 GMT+0800';
const expectedText = '22:00';
expect(stringToTime(sampleText)).toEqual(expectedText); // this passes locally
</code>```

In my Jenkins CICD, I receive 14:00 instead. Is this a common problem, and what's a quick way I can fix up my unit tests so it can pass on Jenkins?

答:
I've always had trouble using the Date constructors when passing in a time string. Try using parseISO from date-fns like parseISO(date) instead of new Date(date).

also, you should import from 'date-fns/tmz' to pass in timezone information. That way you can ensure the timezones are consistent and parsed. here's an example from the docs: https://date-fns.org/v2.28.0/docs/Time-Zones

```<code>const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')

// Set the date to "2018-09-01T16:01:36.386Z"
const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin')

// Obtain a Date instance that will render the equivalent Berlin time for the UTC date
const date = new Date('2018-09-01T16:01:36.386Z')
const timeZone = 'Europe/Berlin'
const zonedDate = utcToZonedTime(date, timeZone)
// zonedDate could be used to initialize a date picker or display the formatted local date/time

// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
const pattern = 'd.M.yyyy HH:mm:ss.SSS \'GMT\' XXX (z)'
const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' })
</code>```

Body:
I am using date-fns to parse some date-like strings into dates, then back into into a string, like so. My local unit tests are passing, but in Jenkins CICD, my unit tests fail. I am pretty sure it is due to the Jenkins machine being in GMT+0, while I am in a GMT+8 timezone. The results of the failed tests in Jenkins supports this, as the received values are 8 hours behind the expected values.

import { format } from 'date-fns';

function stringToTime(date: string) {
    const newDate = new Date(date);
    return format(newDate, 'k:mm'); // this returns a string
}

And my unit tests:

const sampleText = 'Mon Aug 02 2021 22:00:15 GMT+0800';
const expectedText = '22:00';
expect(stringToTime(sampleText)).toEqual(expectedText); // this passes locally

In my Jenkins CICD, I receive 14:00 instead. Is this a common problem, and what's a quick way I can fix up my unit tests so it can pass on Jenkins?

Body:
I've always had trouble using the Date constructors when passing in a time string. Try using parseISO from date-fns like parseISO(date) instead of new Date(date).

also, you should import from 'date-fns/tmz' to pass in timezone information. That way you can ensure the timezones are consistent and parsed. here's an example from the docs: https://date-fns.org/v2.28.0/docs/Time-Zones

const { zonedTimeToUtc, utcToZonedTime, format } = require('date-fns-tz')

// Set the date to "2018-09-01T16:01:36.386Z"
const utcDate = zonedTimeToUtc('2018-09-01 18:01:36.386', 'Europe/Berlin')

// Obtain a Date instance that will render the equivalent Berlin time for the UTC date
const date = new Date('2018-09-01T16:01:36.386Z')
const timeZone = 'Europe/Berlin'
const zonedDate = utcToZonedTime(date, timeZone)
// zonedDate could be used to initialize a date picker or display the formatted local date/time

// Set the output to "1.9.2018 18:01:36.386 GMT+02:00 (CEST)"
const pattern = 'd.M.yyyy HH:mm:ss.SSS \'GMT\' XXX (z)'
const output = format(zonedDate, pattern, { timeZone: 'Europe/Berlin' })


来源: stackexchange

问:
How to make one method return different values for user with role ADMIN and USER?
I need to make the @Get method, and for users with ROLE_USER it should return other values than for users with ROLE_ADMIN.

The URL have to be the same.

How to do it with Spring Security?

答:
If your authentification passed well you could just inject @AuthenticationPrincipal:

```<code>@GetMapping("/get-url-here")
public String main(@AuthenticationPrincipal User user) {
    if (user.getRole().equals("ROLE_ADMIN")) {
        // set values for admin
    } else {
        // set for user
    }
    return "view-or-response-body";
}
</code>```

I assume that you have the User class configured, like:

```<code>public class User {
    public String role;
    // other fields, getters, setters
}
</code>```

Or role could be enum as well.

ContentLicense: CC BY-SA 4.0

Body:
If your authentification passed well you could just inject @AuthenticationPrincipal:

@GetMapping("/get-url-here")
public String main(@AuthenticationPrincipal User user) {
    if (user.getRole().equals("ROLE_ADMIN")) {
        // set values for admin
    } else {
        // set for user
    }
    return "view-or-response-body";
}

I assume that you have the User class configured, like:

public class User {
    public String role;
    // other fields, getters, setters
}

Or role could be enum as well.


问:
Azure DevOps CI / CD not installing latest flutter version
My Azure DevOps configuration ask CI / CD to install latest version of flutter as you can see in the snapshot:

But Flutter old stable version "2.2.1-stable" is getting install

It seems google has changed their flutter download url so Azure not
able to fetch latest version:

Download URL Flutter Stable 2.2.1 (OLD release URL):
https://storage.googleapis.com/flutter_infra/releases/stable/macos/flutter_macos_2.2.1-stable.zip

Download URL Flutter Stable 2.5.1 (New Release URL):
https://storage.googleapis.com/flutter_infra_release/releases/stable/macos/flutter_macos_2.5.1-stable.zip

They have not added any new release on the old URL so Azure fetching
always last stable release which is 2.2.1

Any solutions so Azure DevOps script can download always latest
version of Flutter?

答:
To get the latest version you can use:</p>
```<code> - script: |
      brew install --cask flutter
</code>```

Body:
To get the latest version you can use:

 - script: |
      brew install --cask flutter


问:
Is it possible to convert a legacy app to UWP using Windows 11 Home?
In an article I've read that Windows 10 Professional is required to use Desktop App Converter. Is this still true for Windows 11?

As I am using Windows 11 Home, will I be required to purchase Windows 11 Professional edition to do this?

答: "Desktop App Converter" has been deprecated. The replacement is the MSIX Packaging Tool. The documentation is on Microsoft Docs.</p>


问:
how to compare a date from a csv file with a variable in python
I have a function where I can read out my csv file. In my csv I have the following 2 information. the studentnumber and when the student passed the exam. I need to know which students have passed the exam in less then 4 weeks. How could I compare these 2 with eachother? the dates that I have in my csv file looks something like this: 21-10-2020 15:20

row[0] = studentsname

row[12] = passed date

I have tried doing something like this where I compare row[12] with the end_date but then I get an error message saying this

Error code:

'<' not supported between instances of 'str' and 'datetime.datetime'

My code:

```<code>from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file, 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            allPassedStudents.append(row[0])
            if row[12] < end_date:
                fastStudent.append[row[0]]
                print(fastStudent)
</code>```

答:
You are comparing variables that are of different types. To compare a string to a date you must convert one to a date or the other to a string. In this case you want to convert it to a date

```<code>from datetime import datetime
date_string = '2021-12-31'
datetime = datetime.strptime(date_string, '%Y-%m-%d')
print(datetime)
</code>```

datetime documentation for other string formats

Body:
I have a function where I can read out my csv file. In my csv I have the following 2 information. the studentnumber and when the student passed the exam. I need to know which students have passed the exam in less then 4 weeks. How could I compare these 2 with eachother? the dates that I have in my csv file looks something like this: 21-10-2020 15:20

row[0] = studentsname

row[12] = passed date

I have tried doing something like this where I compare row[12] with the end_date but then I get an error message saying this

Error code:

'<' not supported between instances of 'str' and 'datetime.datetime'

My code:

from datetime import datetime
end_date = datetime(day=5, month=10, year=2020, hour=23, minute=59)
fastStudent = []
allPassedStudents = []
with open("Mycsv_file, 'r') as read_obj:
    csv_dict_reader = csv.reader(read_obj, delimiter=';')
    for row in csv_dict_reader:
        if row[12]:
            allPassedStudents.append(row[0])
            if row[12] < end_date:
                fastStudent.append[row[0]]
                print(fastStudent)

Body:
You are comparing variables that are of different types. To compare a string to a date you must convert one to a date or the other to a string. In this case you want to convert it to a date

from datetime import datetime
date_string = '2021-12-31'
datetime = datetime.strptime(date_string, '%Y-%m-%d')
print(datetime)

datetime documentation for other string formats


问:
CakePHP 3 Plugin development controller could not be found error
I am trying to create an admin plugin for my website. I baked plugin then user model and controller but when I visit /admin/users/ or /admin/users/index it always gives an error as below:

Error: Admin.UsersController could not be found.

Error: Create the class UsersController below in file: C:\xampp\htdocs\cake3\plugins\Admin\src\Controller\UsersController.php

But of course I have the files in correct locations. Any ideas what causes this problem?

Thanks a lot for helps or even efforts.

Please ask any further info

答:
In my case, there is a cached file in tmp folder:
myapp_cake_routes_route_collection

I deleted the file and the path worked.

ContentLicense: CC BY-SA 3.0


问:
I installed a module but it the code returns "ModuleNotFoundError"
I installed a module named "tweepy" to use in my code using the following command: pip install tweepy, it installed perfectly like any other module I installed before the only problem is when I write: import tweepy at the top of my coding file, the code doesn't function and produces this error:
ModuleNotFoundError: No module named 'tweepy'

Notes:

I checked the lib directory and the module exists there

I tried uninstalling and reinstalling the module a couple of times and the issue isn't resolved

I tried installing it using pip3, same issue

I'm using Microsoft Visual Studio Code.

答:
Try this command instead:</p>
```<code>python3 -m pip install tweepy
</code>```

Body:
Try this command instead:

python3 -m pip install tweepy


问:
How to group a list of list that matches certain condition
I have a list of list.

```<code>[
  [4, 5, 6],
  [5, 6, 7],
  [8, 9, 10],
  [20, 21, 22],
  [22,23,24]
]
</code>```

if the upper_bound(5) of [5,6,7] is less than or equal to lower_bound(6) of [4,5,6] then grp them together and the final list should look like this.

```<code>[
  [
    [4, 5, 6],
    [5, 6, 7]
  ],
  [8, 9, 10],
  [
    [20, 21, 22],
    [22,23,24]
  ]

]
</code>```

How can i do this?

答:
This answer assumes that the items are always sequential, as in your example, and that no list completely contains another list.

First, it would be better to work with Ranges, so we first convert the lists to ranges.

Then we can write a recursive algorithm group_ranges/1, which checks each range with its predecessor. If it overlaps (using Range.disjoint?/2), add it to the group. If it doesn't overlap, start a new group.

Finally, since you want non-overlapping ranges to stand alone rather than be in a group of one, we handle that case once the grouping has completed. You could also convert the ranges back to lists at this stage, if that was a strict requirement.

defmodule Example do
  def run do
    [[4, 5, 6], [5, 6, 7], [8, 9, 10], [20, 21, 22], [22, 23, 24]]
    |> Enum.map(fn [head | tail] -> head..List.last(tail) end)
    |> group_ranges()
    |> Enum.map(fn
      [single] -> single
      group -> group
    end)
  end

  def group_ranges([current | rest]), do: do_group_ranges(rest, [current], [])

  defp do_group_ranges([], group, grouped) do
    Enum.reverse([Enum.reverse(group) | grouped])
  end

  defp do_group_ranges([current | rest], [prev | _] = group, grouped) do
    if Range.disjoint?(current, prev) do
      # Create a new group
      do_group_ranges(rest, [current], [Enum.reverse(group) | grouped])
    else
      # Add to existing group
      do_group_ranges(rest, [current | group], grouped)
    end
  end
end
```
<p>Result:</p>
<pre class="lang-elixir prettyprint-override"><code>iex(1)> Example.run
[[4..6, 5..7], 8..10, [20..22, 22..24]]
</code>```

Body:
I have a list of list.

[
  [4, 5, 6],
  [5, 6, 7],
  [8, 9, 10],
  [20, 21, 22],
  [22,23,24]
]

if the upper_bound(5) of [5,6,7] is less than or equal to lower_bound(6) of [4,5,6] then grp them together and the final list should look like this.

[
  [
    [4, 5, 6],
    [5, 6, 7]
  ],
  [8, 9, 10],
  [
    [20, 21, 22],
    [22,23,24]
  ]

]

How can i do this?

Body:
This answer assumes that the items are always sequential, as in your example, and that no list completely contains another list.

First, it would be better to work with Ranges, so we first convert the lists to ranges.

Then we can write a recursive algorithm group_ranges/1, which checks each range with its predecessor. If it overlaps (using Range.disjoint?/2), add it to the group. If it doesn't overlap, start a new group.

Finally, since you want non-overlapping ranges to stand alone rather than be in a group of one, we handle that case once the grouping has completed. You could also convert the ranges back to lists at this stage, if that was a strict requirement.

defmodule Example do
  def run do
    [[4, 5, 6], [5, 6, 7], [8, 9, 10], [20, 21, 22], [22, 23, 24]]
    |> Enum.map(fn [head | tail] -> head..List.last(tail) end)
    |> group_ranges()
    |> Enum.map(fn
      [single] -> single
      group -> group
    end)
  end

  def group_ranges([current | rest]), do: do_group_ranges(rest, [current], [])

  defp do_group_ranges([], group, grouped) do
    Enum.reverse([Enum.reverse(group) | grouped])
  end

  defp do_group_ranges([current | rest], [prev | _] = group, grouped) do
    if Range.disjoint?(current, prev) do
      # Create a new group
      do_group_ranges(rest, [current], [Enum.reverse(group) | grouped])
    else
      # Add to existing group
      do_group_ranges(rest, [current | group], grouped)
    end
  end
end

Result:

iex(1)> Example.run
[[4..6, 5..7], 8..10, [20..22, 22..24]]


问:
How to parse a full set of formula chain from an excel?
I have an excel file that has a complex calculation model, the performance of direct using apache POI is not acceptable to me. therefore I am thinking to extract the full set formula chain and parse it to java.

for example: If C1=A1+B1 and A1=A2+B2, B1=A3+B3 => C1 = A2+B2+A3+B3

I also noticed that there is an object called CalculationChain, it seems there is a convenient way to get the formula chain. rather than parse these nested Cells one by one.

Anyone can give an example to shed some light on?

答:
This is not a good answer, but it moves one step forward.</p>
```<code>XSSFEvaluationWorkbook xssfEvaluationWorkbook = XSSFEvaluationWorkbook.create(workbook);
Ptg[] ptg = FormulaParser.parse(cell.getCellFormula(), xssfEvaluationWorkbook, FormulaType.NAMEDRANGE, sheetIndex);
</code>```

Body:
This is not a good answer, but it moves one step forward.

XSSFEvaluationWorkbook xssfEvaluationWorkbook = XSSFEvaluationWorkbook.create(workbook);
Ptg[] ptg = FormulaParser.parse(cell.getCellFormula(), xssfEvaluationWorkbook, FormulaType.NAMEDRANGE, sheetIndex);


问:
LINQ to count number of rows in link table
I have the following model

```<code>public class Account
{
    public int Id { get; set; }
    public List<Note> Notes { get; set; }
}
</code>```

I'm trying to query my nhibernate repository to count the number of notes for a specific account.

return this.Data.Where(x => x.Id == accountId).Select(x => x.Notes).Count();

However no matter how many notes there are, it always returns 1.

I am trying to do this in the most efficient way possible without having to get the account object and then count the number of notes.

Can anyone suggest the Linq equivalent of the following SQL.

SELECT Count(*) FROM NoteToAccount WHERE AccountId=?

Where NoteToAccount is a link table which sits between the Account and Note tables.

答:
You are getting back an IEnumerable<List<Note>> which has one element which is the list of notes for the account.

You can use SelectMany instead of Select to flatten it down into one large entity, or you can use:

```<code>this.Data.First(x => x.Id == accountId).Notes.Count;
</code>```

I am, of course, assuming that accountId is the primary key, so you'll only ever get one item back. You could also use Single instead of First to ensure you get exactly one item back.

Body:
I have the following model

public class Account
{
    public int Id { get; set; }
    public List<Note> Notes { get; set; }
}

I'm trying to query my nhibernate repository to count the number of notes for a specific account.

return this.Data.Where(x => x.Id == accountId).Select(x => x.Notes).Count();

However no matter how many notes there are, it always returns 1.

I am trying to do this in the most efficient way possible without having to get the account object and then count the number of notes.

Can anyone suggest the Linq equivalent of the following SQL.

SELECT Count(*) FROM NoteToAccount WHERE AccountId=?

Where NoteToAccount is a link table which sits between the Account and Note tables.

Body:
You are getting back an IEnumerable<List<Note>> which has one element which is the list of notes for the account.

You can use SelectMany instead of Select to flatten it down into one large entity, or you can use:

this.Data.First(x => x.Id == accountId).Notes.Count;

I am, of course, assuming that accountId is the primary key, so you'll only ever get one item back. You could also use Single instead of First to ensure you get exactly one item back.


问:
In what case would I use a tuple as a dictionary key?
I was studying the difference between lists and tuples (in Python). An obvious one is that tuples are immutable (the values cannot be changed after initial assignment), while lists are mutable.

A sentence in the article got me:

Only immutable elements can be used as
  dictionary keys, and hence only tuples
  and not lists can be used as keys.

I have a hard time thinking of a situation where I would like to use a tuple as a dictionary key. Can you provide an example problem where this would be the natural, efficient, elegant, or obvious solution?

Edit:

Thanks for your examples. So far I take that a very important application is the caching of function values.

答:
I think tuples as dictionary keys will be good, if we are storing :-

Some points in the coordinate system.

helps in flag the position of the matrix that you want in the next iteration. for eg:-

flag = {(0,1): True, (1,0) = False}


问:
Modern apis with FastAPI - Redis Caching
I'm trying to implement the redis caching in my API for the first time it is a simple fastapi application which is using openweather api to query some weather information and my intention is to cache each json response in the redis server. I'hve  made it to work with single key city but with this approach validating query parameters not working with the error handling I put in the place.

caching.py

```<code>import sys
from datetime import timedelta
import json

import redis

from services.openweather_service import get_report

def redis_connect() -> redis.client.Redis:
    try:
        client = redis.Redis(
            host="localhost",
            port=6379,
            db=0,
        )
        ping = client.ping()
        if ping is True:
            return client
    except redis.ConnectionError:
        print("Connection Error!")
        sys.exit(1)

client = redis_connect()

def get_routes_from_cache(key: str) -> str:
    """Data from redis."""

    val = client.get(key)
    return val

def set_routes_to_cache(key: str, value: str) -> bool:
    """Data to redis."""

    state = client.setex(
        key,
        timedelta(hours=24),
        value=value,
    )
    return state

async def route_optima(city: str, state: str, country: str, units=None) -> dict:

    location = {"city": city, "state": state, "country": country, "units": units}

    # First it looks for the data in redis cache
    data = get_routes_from_cache(key=json.dumps(location))
    # print(data)
    # print(type(data))

    # If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data["cache"] = True
        return data

    else:
        # If cache is not found then sends request to the OpenWeather API
        data = await get_report(city, state, country, units)

        # This block sets saves the respose to redis and serves it directly
        data["cache"] = False
        data = json.dumps(data)
        state = set_routes_to_cache(key=json.dumps(location), value=json.dumps(data))

        if state is True:
            return json.dumps(data)
        return data
</code>```

Then I took a different approach by making the query params location = {"city": city, "state": state, "country": country, "units": units} as a key and the json response as a value but when app try to get the response from the cache here it got weird like right after passing the query params dict into the json.dumps it gives me the bytes object and so I decode it with decode("utf-8") but instead of coming back as a dict it gives me <class 'str'> type object. There I am lost... can anyone help me out here?

weather_api.py

```<code>from typing import Optional
import fastapi
from fastapi import Depends

from models.location import Location
from infrastructure.caching import route_optima
from models.validation_error import ValidationError

router = fastapi.APIRouter()

@router.get("/api/weather/{city}")
async def weather(loc: Location = Depends(), units: Optional[str] = "metric"):
    return await route_optima(loc.city, loc.state, loc.country, units)
</code>```

And if I am using the wrong approach here then please point to the best approach to take here.

答:
It turns out I was returning the wrong data it should be like this

```<code># If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data_dict["cache"] = True
        return data_dict
</code>```

and everything works fine.

Body:
I'm trying to implement the redis caching in my API for the first time it is a simple fastapi application which is using openweather api to query some weather information and my intention is to cache each json response in the redis server. I'hve  made it to work with single key city but with this approach validating query parameters not working with the error handling I put in the place.

caching.py

import sys
from datetime import timedelta
import json

import redis

from services.openweather_service import get_report

def redis_connect() -> redis.client.Redis:
    try:
        client = redis.Redis(
            host="localhost",
            port=6379,
            db=0,
        )
        ping = client.ping()
        if ping is True:
            return client
    except redis.ConnectionError:
        print("Connection Error!")
        sys.exit(1)

client = redis_connect()

def get_routes_from_cache(key: str) -> str:
    """Data from redis."""

    val = client.get(key)
    return val

def set_routes_to_cache(key: str, value: str) -> bool:
    """Data to redis."""

    state = client.setex(
        key,
        timedelta(hours=24),
        value=value,
    )
    return state

async def route_optima(city: str, state: str, country: str, units=None) -> dict:

    location = {"city": city, "state": state, "country": country, "units": units}

    # First it looks for the data in redis cache
    data = get_routes_from_cache(key=json.dumps(location))
    # print(data)
    # print(type(data))

    # If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data["cache"] = True
        return data

    else:
        # If cache is not found then sends request to the OpenWeather API
        data = await get_report(city, state, country, units)

        # This block sets saves the respose to redis and serves it directly
        data["cache"] = False
        data = json.dumps(data)
        state = set_routes_to_cache(key=json.dumps(location), value=json.dumps(data))

        if state is True:
            return json.dumps(data)
        return data

Then I took a different approach by making the query params location = {"city": city, "state": state, "country": country, "units": units} as a key and the json response as a value but when app try to get the response from the cache here it got weird like right after passing the query params dict into the json.dumps it gives me the bytes object and so I decode it with decode("utf-8") but instead of coming back as a dict it gives me <class 'str'> type object. There I am lost... can anyone help me out here?

weather_api.py

from typing import Optional
import fastapi
from fastapi import Depends

from models.location import Location
from infrastructure.caching import route_optima
from models.validation_error import ValidationError

router = fastapi.APIRouter()

@router.get("/api/weather/{city}")
async def weather(loc: Location = Depends(), units: Optional[str] = "metric"):
    return await route_optima(loc.city, loc.state, loc.country, units)

And if I am using the wrong approach here then please point to the best approach to take here.

Body:
It turns out I was returning the wrong data it should be like this

# If cache is found then serves the data from cache
    if data is not None:
        data = data.decode("UTF-8")
        data_dict = json.loads(data)
        print(data_dict)
        print(type(data_dict))
        data_dict["cache"] = True
        return data_dict

and everything works fine.


问:
Why can I not add more than one argument in my list on IDLE
I'm very new to programming and I've been using IDLE to start with Python. However, when I try to create a list with more than one argument (i.e.: my_list = list("Apples", "Oranges", "Grapefruits") and print it using my_list, I get the following response in the shell – TypeError: list expected at most 1 argument, got 3.

How can I add more than one argument into the list on IDLE?

答:
The Python built-in list receives a single argument: an interable, any Python object that you can iterate through (Python docs). You're providing 3 values instead of one. You may want to use an alternative syntax to create your list:

```<code>my_list = ["Apples", "Oranges", "Grapefruits"]
</code>```

This syntax results in the same list that you want to create

Body:
The Python built-in list receives a single argument: an interable, any Python object that you can iterate through (Python docs). You're providing 3 values instead of one. You may want to use an alternative syntax to create your list:

my_list = ["Apples", "Oranges", "Grapefruits"]

This syntax results in the same list that you want to create


问:
Warning: Failed prop type: Invalid prop `defaultValue` of type `string` supplied to `AutoCompleteSearch`, expected `function`
I dont know why, why I am having this kind of error MUI: A component is changing the default value state of an uncontrolled Autocomplete after being initialized. To suppress this warning opt to use a controlled Autocomplete. is there anything wrong with my code? please help thanks

LocationSearch.js

```<code>const propTypes = {
    defaultValue: PropTypes.String,
    getOptionLabel: PropTypes.func,
    value: '',
}
const defaultProps = {
    defaultValue: '',
    getOptionLabel: () => {},
}

const AutoCompleteSearch = ({
    defaultValue,
    getOptionLabel,
})
....

return(
   <Autocomplete
      defaultValue={defaultValue}
      getOptionLabel={getOptionLabel}
   />
)
</code>```

//parent

AddUser.js

```<code> import {LocationSearch} from '../../component/LocationSearch.js'

      <LocationSearch
        freeSolo
        getOptionLabel={(option) => option} // the value of option is the name of the company
        defaultValue={threatLocation.title} //same goes with the defaultValue
        value={suggestedLocations.title}

      />
</code>```

答:
About Prop types:

Given the LocationSearch signature provided in AddUser, you need to change both:

defaultValue to be a string
Per the mui Autocomplete API, it is of type any. Since you seem to infer it to be a string, you should probably change its type in the prop types.

getOptionLabel to add input parameter and return value.  Its signature is defined in mui Autocomplete API like so

Signature:
function(option: T) => string

The overall changes look like this:

const propTypes = {
    defaultValue: PropTypes.string,
    getOptionLabel: PropTypes.func,
}

// default string values are up to you
const defaultProps = {
    defaultValue: "",
    getOptionLabel: (option : string) => "",
}
```
<h2>About the uncontrolled state</h2>
<p>It's because you're using <code>defaultValue</code>.</p>
<p>In a controlled component, data is handled by the Autocomplete component via callbacks. The alternative is uncontrolled components, where data is handled by the DOM itself. Controlled vs uncontrolled components is discussed in React documentation.</p>
<p>As of your code, MUI Autocomplete Doc says:</p>
<blockquote>
<p>The default value. Use when the component is not controlled.</p>
</blockquote>
<p>To have controlled Autocomplete component, you should use <code>onOpen</code>, <code>onChange</code> callbacks and remove <code>defultValue</code>.  An example can be found in MUI Autocomplete demo:</p>
<pre class="lang-js prettyprint-override"><code>import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export default function ControllableStates() {
  const [value, setValue] = React.useState(options[0]);
  const [inputValue, setInputValue] = React.useState('');

  return (
    <div>
      <div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
      <div>{`inputValue: '${inputValue}'`}</div>
      <br />
      <Autocomplete
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        id="controllable-states-demo"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Controllable" />}
      />
    </div>
  );
}
</code>```

Note: you should not remove your questions once they are answered. Even if you have many of them in your post. It confuses future readers.

Body:
I dont know why, why I am having this kind of error MUI: A component is changing the default value state of an uncontrolled Autocomplete after being initialized. To suppress this warning opt to use a controlled Autocomplete. is there anything wrong with my code? please help thanks

LocationSearch.js

const propTypes = {
    defaultValue: PropTypes.String,
    getOptionLabel: PropTypes.func,
    value: '',
}
const defaultProps = {
    defaultValue: '',
    getOptionLabel: () => {},
}

const AutoCompleteSearch = ({
    defaultValue,
    getOptionLabel,
})
....

return(
   <Autocomplete
      defaultValue={defaultValue}
      getOptionLabel={getOptionLabel}
   />
)

//parent

AddUser.js

 import {LocationSearch} from '../../component/LocationSearch.js'

      <LocationSearch
        freeSolo
        getOptionLabel={(option) => option} // the value of option is the name of the company
        defaultValue={threatLocation.title} //same goes with the defaultValue
        value={suggestedLocations.title}

      />

Body:
About Prop types:

Given the LocationSearch signature provided in AddUser, you need to change both:

defaultValue to be a string
Per the mui Autocomplete API, it is of type any. Since you seem to infer it to be a string, you should probably change its type in the prop types.

getOptionLabel to add input parameter and return value.  Its signature is defined in mui Autocomplete API like so

Signature:
function(option: T) => string

The overall changes look like this:

const propTypes = {
    defaultValue: PropTypes.string,
    getOptionLabel: PropTypes.func,
}

// default string values are up to you
const defaultProps = {
    defaultValue: "",
    getOptionLabel: (option : string) => "",
}

About the uncontrolled state

It's because you're using defaultValue.

In a controlled component, data is handled by the Autocomplete component via callbacks. The alternative is uncontrolled components, where data is handled by the DOM itself. Controlled vs uncontrolled components is discussed in React documentation.

As of your code, MUI Autocomplete Doc says:

The default value. Use when the component is not controlled.

To have controlled Autocomplete component, you should use onOpen, onChange callbacks and remove defultValue.  An example can be found in MUI Autocomplete demo:

import * as React from 'react';
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

const options = ['Option 1', 'Option 2'];

export default function ControllableStates() {
  const [value, setValue] = React.useState(options[0]);
  const [inputValue, setInputValue] = React.useState('');

  return (
    <div>
      <div>{`value: ${value !== null ? `'${value}'` : 'null'}`}</div>
      <div>{`inputValue: '${inputValue}'`}</div>
      <br />
      <Autocomplete
        value={value}
        onChange={(event, newValue) => {
          setValue(newValue);
        }}
        inputValue={inputValue}
        onInputChange={(event, newInputValue) => {
          setInputValue(newInputValue);
        }}
        id="controllable-states-demo"
        options={options}
        sx={{ width: 300 }}
        renderInput={(params) => <TextField {...params} label="Controllable" />}
      />
    </div>
  );
}

Note: you should not remove your questions once they are answered. Even if you have many of them in your post. It confuses future readers.


问:
Movement controls using "WASD" in JavaScript
I am making a game right now, and the current movement is really choppy because when you press a button e.g. 'W'. it will take away from the 'top' position to give it the effect of moving up.

I was hoping to use 'this.x' and 'this.y' but I don't know much about it.

This is the current code I have:

```<code>window.addEventListener('keydown', (e) =>{
switch(e.key){
        case 'a':
        player.style.left = parseInt(player.style.left) - movePlayer + 'px';
        break;
        case 'd':
        player.style.left = parseInt(player.style.left) + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = parseInt(player.style.top) - movePlayer + 'px';
        break;
        case 's':
        player.style.top = parseInt(player.style.top) + movePlayer + 'px';
        break;
         }
   });
</code>```

答:
smooth

<button>Increase Speed</button>

```

Body:
I am making a game right now, and the current movement is really choppy because when you press a button e.g. 'W'. it will take away from the 'top' position to give it the effect of moving up.

I was hoping to use 'this.x' and 'this.y' but I don't know much about it.

This is the current code I have:

window.addEventListener('keydown', (e) =>{
switch(e.key){
        case 'a':
        player.style.left = parseInt(player.style.left) - movePlayer + 'px';
        break;
        case 'd':
        player.style.left = parseInt(player.style.left) + movePlayer + 'px';
        break;
        case 'w':
        player.style.top = parseInt(player.style.top) - movePlayer + 'px';
        break;
        case 's':
        player.style.top = parseInt(player.style.top) + movePlayer + 'px';
        break;
         }
   });

Body:
smooth

<div id="box" style="border: 2px solid black; width: 200px; height: 200px">
    <div id="sprite" style="left: 0; bottom: 0"></div>
</div>
<button>Increase Speed</button>

<style>
    #sprite {
        width: 25px;
        height: 25px;
        background: red;
        position: relative;
        transition: 0.1s linear;
    }
</style>

<script>
    const box = document.querySelector('#box');
    const sprite = document.querySelector('#sprite');
    const button = document.querySelector('button');
    let speed = 5;

    const toNum = (pxVal) => {
        return parseInt(pxVal, 10);
    };

    const handleMovement = (e) => {
        let left = toNum(sprite.style.left);
        const bottom = toNum(sprite.style.bottom);

        switch (e.key) {
            case 'a':
                if (left <= 0) return (sprite.style.left = 0);
                sprite.style.left = left - speed + 'px';
                break;
            case 'd':
                if (left >= 175) return (sprite.style.left = 175);
                sprite.style.left = left + speed + 'px';
                break;
            case 'w':
                if (bottom >= 0) return (sprite.style.bottom = 0);
                sprite.style.bottom = bottom + speed + 'px';
                break;
            case 's':
                if (bottom <= -175) return (sprite.style.bottom = -175);
                sprite.style.bottom = bottom - speed + 'px';
                break;
        }
    };

    window.addEventListener('keydown', handleMovement);

    button.addEventListener('click', () => (speed += 5));
</script>


问:
Liquibase lock - reasons?
I get this when running a lot of liquibase-scripts against a Oracle-server. SomeComputer is me.

Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Liquibase Update Failed: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
SEVERE 2013-03-20 16:59:liquibase: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
liquibase.exception.LockException: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
        at liquibase.lockservice.LockService.waitForLock(LockService.java:81)
        at liquibase.Liquibase.tag(Liquibase.java:507)
        at liquibase.integration.commandline.Main.doMigration(Main.java:643)
        at liquibase.integration.commandline.Main.main(Main.java:116)
```

Could it be that the number of simultaneous sessions/transactions are reached? Anyone has any ideas?

答:
I have previously just truncated the DatabaseChangeLogLock table when a lock remained after failure (and this generally still works for me).

However, this project (https://github.com/blagerweij/liquibase-sessionlock) now exists, which uses native database session locks for locking Liquibase when using Oracle, PostgreSQL and MySQL.

The JAR file can be dropped into an existing Liquibase 4.x+ application, and will be automatically detected by Liquibase. This will use session locks for locking.. which are automatically released if the application crashes or is shutdown whilst the lock is held. This will potentially stop the locked state from occuring (if you are using one of the supported databases)

Title: Liquibase lock - reasons?

Body:
I get this when running a lot of liquibase-scripts against a Oracle-server. SomeComputer is me.

Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Waiting for changelog lock....
Liquibase Update Failed: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
SEVERE 2013-03-20 16:59:liquibase: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
liquibase.exception.LockException: Could not acquire change log lock.  Currently locked by SomeComputer (192.168.15.X) since 2013-03-20 13:39
        at liquibase.lockservice.LockService.waitForLock(LockService.java:81)
        at liquibase.Liquibase.tag(Liquibase.java:507)
        at liquibase.integration.commandline.Main.doMigration(Main.java:643)
        at liquibase.integration.commandline.Main.main(Main.java:116)

Could it be that the number of simultaneous sessions/transactions are reached? Anyone has any ideas?


问:
Django- IndentationError
Hello everyone I am new to django please help me to solve error,I am using termux for it and Acoder for editing code
In my django urls.py code
In urls.py

In termux error showing like this
Error message of indentation in urls.py

答:
Try to put a comma at the end of the 2nd path specification in urls.py

It is usual to have a comma after every line under these circumstances, even the last one.

Without knowing more about your code, it is hard to say, but I would try that one first.

Title: Django- IndentationError


问:
Trying to get the sum of php array object in a nested loop
I know this is quite basic.

I'm trying to get the sum of qty for each of the keys from the below object but it doesn't return what I expect.

```<code>{
        "3": [
            {
                "id": 1,
                "qty": 4,
                "customer_id": 3,
                "cargo_id": 3,
                "customer": {
                    "id": 3,
                    "company_name": "Mertz and Sons",
                    "phone": "(586) 898-5987"
                },

            }
        ],
        "6": [
            {
                "id": 3,
                "qty": 9,
                "customer_id": 6,
                "cargo_id": 3,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                },
            },
            {
                "id": 4,
                "qty": 3,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                },

            }
        ]
    }
</code>```

Here is what I'm currently doing

```<code>$attrs = [];
foreach($record as $item=> $value){

            foreach($value as $k){
                $attrs['customer'] = $k['customer']['company_name'];
                $sum_ordered = 0;
                $sum_ordered += $k['qty'];
                $attrs['ordered_sum'] = $sum_ordered;
            }
            $output[] = $attrs;
}
echo json_encode($output);
</code>```

and this is the result I get, I can't figure out what is not right. I'm expecting 4 and 12 respectively as ordered_sum

```<code>[
   {"customer":"Mertz and Sons","ordered_sum":4},
   {"customer":"Turcotte PLC","ordered_sum":3}
]
</code>```

答:
Try this</p>
```<code><?php

$record = '{
    "3": [
        {
            "id": 1,
            "qty": 4,
            "customer_id": 3,
            "customer": {
                "id": 3,
                "company_name": "Mertz and Sons",
                "phone": "(586) 898-5987"
            }
        }
    ],
        "5": {
            "1": {
                "id": 2,
                "qty": 8,
                "customer_id": 5,
                "customer": {
                    "id": 5,
                    "company_name": "Reichert, Witting and Durgan",
                    "phone": "961.352.6817 x0265"
                }
            }
        },
        "6": {
            "2": {
                "id": 3,
                "qty": 9,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                }
            },
            "3": {
                "id": 4,
                "qty": 3,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                }
            }
        }
}';

$record = json_decode($record, true);

$output = [];
foreach($record as $item=> $value){
    $attrs = [
        'customer'    => '',
        'ordered_sum' => 0
    ];

    foreach($value as $k){
        $attrs['customer']     = $k['customer']['company_name'];
        $attrs['ordered_sum'] += $k['qty'];
    }

    $output[] = $attrs;
}

echo json_encode($output);
</code>```

Body:
I know this is quite basic.

I'm trying to get the sum of qty for each of the keys from the below object but it doesn't return what I expect.

{
        "3": [
            {
                "id": 1,
                "qty": 4,
                "customer_id": 3,
                "cargo_id": 3,
                "customer": {
                    "id": 3,
                    "company_name": "Mertz and Sons",
                    "phone": "(586) 898-5987"
                },

            }
        ],
        "6": [
            {
                "id": 3,
                "qty": 9,
                "customer_id": 6,
                "cargo_id": 3,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                },
            },
            {
                "id": 4,
                "qty": 3,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                },

            }
        ]
    }

Here is what I'm currently doing

$attrs = [];
foreach($record as $item=> $value){

            foreach($value as $k){
                $attrs['customer'] = $k['customer']['company_name'];
                $sum_ordered = 0;
                $sum_ordered += $k['qty'];
                $attrs['ordered_sum'] = $sum_ordered;
            }
            $output[] = $attrs;
}
echo json_encode($output);

and this is the result I get, I can't figure out what is not right. I'm expecting 4 and 12 respectively as ordered_sum

[
   {"customer":"Mertz and Sons","ordered_sum":4},
   {"customer":"Turcotte PLC","ordered_sum":3}
]

Body:
Try this

<?php

$record = '{
    "3": [
        {
            "id": 1,
            "qty": 4,
            "customer_id": 3,
            "customer": {
                "id": 3,
                "company_name": "Mertz and Sons",
                "phone": "(586) 898-5987"
            }
        }
    ],
        "5": {
            "1": {
                "id": 2,
                "qty": 8,
                "customer_id": 5,
                "customer": {
                    "id": 5,
                    "company_name": "Reichert, Witting and Durgan",
                    "phone": "961.352.6817 x0265"
                }
            }
        },
        "6": {
            "2": {
                "id": 3,
                "qty": 9,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                }
            },
            "3": {
                "id": 4,
                "qty": 3,
                "customer_id": 6,
                "customer": {
                    "id": 6,
                    "company_name": "Turcotte PLC",
                    "phone": "+13422302445"
                }
            }
        }
}';

$record = json_decode($record, true);

$output = [];
foreach($record as $item=> $value){
    $attrs = [
        'customer'    => '',
        'ordered_sum' => 0
    ];

    foreach($value as $k){
        $attrs['customer']     = $k['customer']['company_name'];
        $attrs['ordered_sum'] += $k['qty'];
    }

    $output[] = $attrs;
}

echo json_encode($output);


问:
Batch insertion of spreadsheet cells using gdata-objectivec-client not working
I am trying to add a batch of cells to a Google Spreadsheet using the GData Objective-C Client as described here: http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction#Batch_requests.

Here is the code of interest:

```<code>                      GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];
                  NSURL *batchUrl = [[batchFeed batchLink] URL];

                  NSMutableArray *cells = [NSMutableArray array];

                  GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                  GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];
                  [cells addObject:cellEntry];
                  [batchFeed setEntries:cells];

                  GDataBatchOperation *op;
                  op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                  [batchFeed setBatchOperation:op];

                  [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl completionHandler:nil];
</code>```

It doesn't work.  Clearly, the fetchFeedWithBatchFeed has no reference to my GDataWorksheetEntry object -- so it doesn't surprise me that it isn't working.

What am I leaving out?

Thanks in advance.

答:
And here is the final answer.

You must perform a query before the batch update to get the entries you are going to update.  Sounds obvious in retrospect.  Sure does make for a lot of nested blocks though.

```<code>                     NSURL *cellsFeedUrl = [[worksheetEntry cellsLink] URL];

                  GDataQuerySpreadsheet *querySpreadsheet = [GDataQuerySpreadsheet spreadsheetQueryWithFeedURL:cellsFeedUrl];
                  [querySpreadsheet setMinimumRow:1];
                  [querySpreadsheet setMaximumRow:1];
                  [querySpreadsheet setMinimumColumn:1];
                  [querySpreadsheet setMaximumColumn:7];
                  [querySpreadsheet setShouldReturnEmpty:TRUE];

                  [service fetchFeedWithQuery:querySpreadsheet completionHandler:
                   ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                       // Update one of these cells as a test.
                       GDataEntrySpreadsheetCell *spreadsheetCellEntry = [[feed entries] lastObject];
                       [[spreadsheetCellEntry cell] setInputString:@"test"];

                       NSArray *updatedEntries = [feed entries];
                       NSString *eTag = feed.ETag;

                       // Get worksheet cells feed
                       [service fetchFeedWithURL:cellsFeedUrl completionHandler:
                        ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                            NSURL *batchUrl = [[feed batchLink] URL];
                            GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];

                            [batchFeed setEntriesWithEntries:updatedEntries];

                            GDataBatchOperation *op;
                            op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationUpdate];
                            [batchFeed setBatchOperation:op];
                            [batchFeed setETag:eTag];

                            // Perform batch update
                            [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl
                                          completionHandler:
                             ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                                 // no op

                             }];
                        }];
                   }];
</code>```

Body:
I am trying to add a batch of cells to a Google Spreadsheet using the GData Objective-C Client as described here: http://code.google.com/p/gdata-objectivec-client/wiki/GDataObjCIntroduction#Batch_requests.

Here is the code of interest:

                      GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];
                  NSURL *batchUrl = [[batchFeed batchLink] URL];

                  NSMutableArray *cells = [NSMutableArray array];

                  GDataSpreadsheetCell *cell = [GDataSpreadsheetCell cellWithRow:1 column:1 inputString:@"test" numericValue:nil resultString:nil];

                  GDataEntrySpreadsheetCell *cellEntry = [GDataEntrySpreadsheetCell spreadsheetCellEntryWithCell:cell];
                  [cells addObject:cellEntry];
                  [batchFeed setEntries:cells];

                  GDataBatchOperation *op;
                  op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationInsert];
                  [batchFeed setBatchOperation:op];

                  [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl completionHandler:nil];

It doesn't work.  Clearly, the fetchFeedWithBatchFeed has no reference to my GDataWorksheetEntry object -- so it doesn't surprise me that it isn't working.

What am I leaving out?

Thanks in advance.

Body:
And here is the final answer.

You must perform a query before the batch update to get the entries you are going to update.  Sounds obvious in retrospect.  Sure does make for a lot of nested blocks though.

                     NSURL *cellsFeedUrl = [[worksheetEntry cellsLink] URL];

                  GDataQuerySpreadsheet *querySpreadsheet = [GDataQuerySpreadsheet spreadsheetQueryWithFeedURL:cellsFeedUrl];
                  [querySpreadsheet setMinimumRow:1];
                  [querySpreadsheet setMaximumRow:1];
                  [querySpreadsheet setMinimumColumn:1];
                  [querySpreadsheet setMaximumColumn:7];
                  [querySpreadsheet setShouldReturnEmpty:TRUE];

                  [service fetchFeedWithQuery:querySpreadsheet completionHandler:
                   ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                       // Update one of these cells as a test.
                       GDataEntrySpreadsheetCell *spreadsheetCellEntry = [[feed entries] lastObject];
                       [[spreadsheetCellEntry cell] setInputString:@"test"];

                       NSArray *updatedEntries = [feed entries];
                       NSString *eTag = feed.ETag;

                       // Get worksheet cells feed
                       [service fetchFeedWithURL:cellsFeedUrl completionHandler:
                        ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                            NSURL *batchUrl = [[feed batchLink] URL];
                            GDataFeedSpreadsheetCell *batchFeed = [GDataFeedSpreadsheetCell spreadsheetCellFeed];

                            [batchFeed setEntriesWithEntries:updatedEntries];

                            GDataBatchOperation *op;
                            op = [GDataBatchOperation batchOperationWithType:kGDataBatchOperationUpdate];
                            [batchFeed setBatchOperation:op];
                            [batchFeed setETag:eTag];

                            // Perform batch update
                            [service fetchFeedWithBatchFeed:batchFeed forBatchFeedURL:batchUrl
                                          completionHandler:
                             ^(GDataServiceTicket *ticket, GDataFeedBase *feed, NSError *error) {

                                 // no op

                             }];
                        }];
                   }];


问:
How to export .ASCII file in NetLogo 6.2?
I would like to know how I can transform a .csv file into raster (ASCII) within NetLogo 6.2?

Well, I can export in .csv to do the conversion later in .ASCII in another program such as R. However, I think it should be possible to export the output in .ASCII by NetLogo itself. At the same time, I would like to know if in terms of processing it would be better to export the output in .csv by NetLogo or in .ASCII? obs.: my world on NetLogo is relatively big

Thanks in advance

```<code>extensions [ gis ]

globals [ file output-filename ]

to setup
  clear-all
  reset-ticks
  set output-filename "output-data.csv"
  set-default-shape turtles "person"
  create-turtles 10 [
    setxy random-pxcor random-pycor
  ]
  initialize-data-file

end

to initialize-data-file
  file-close-all
  if file-exists? output-filename [
    file-delete output-filename
  ]
  file-open output-filename
  file-print ( word "xcor, ycor" )
end

to go
  ask turtles [
    wander-about
    if ticks mod 50 = 0  [
      write-output-data who xcor ycor
    ]
  ]
  tick
end

to write-output-data [ #turtle-id #xpos #ypos ]
  file-open output-filename
  file-print ( word #xpos ", " #ypos )
  file-flush

  ; set file gis:patch-dataset xcor ycor
  ;  gis:store-dataset file "test.asc"

end

to wander-about
  rt random 40
  lt random 40
  if not can-move? 1 [ rt 180 ]
  fd 1
end
</code>```

答:
You're on the right track using the GIS extension to export directly to ASCII. Whether you actually need to do this depends entirely on your application- as you say, it may be possible to do what you need simply by exporting a list of turtle coordinates, or of patch values, etc., depending on your needs. Whether you should use ASCII or csv is going to depend on your application, but: for all of my larger models where I actually need to export the whole world for analysis (and, more importantly, to go the other way and import my spatial data into NetLogo), I always use the GIS extension because it seems to be much faster. If I were only exporting turtle characteristics I would probably export to csv.

To answer your specific question here about how to export directly to ASC- here is one way. You need to set up some spatial information for the GIS extension to work with your data, but once you've done that you can create a raster dataset from patch values and export that to a .ASC file that will consist of the .ASC header in addition to a value for each patch in your world. With this example:

```<code>extensions [ gis ]

patches-own [ turtle-here ]

to setup
  ca
  resize-world 0 14 0 14
  ; Pull in some coordinate system
  gis:load-coordinate-system "utm_11.prj"
  ; Set some envelope. Unless you are actually spatially
  ; referencing your model, this is just a placeholder.
  ; If you are using actual spatial coordinates, set these
  ; appropriately or use gis:envelope-of
  gis:set-world-envelope [ 55000 50000 55000 50000 ]
  crt 10
  reset-ticks
end

to go
  ask turtles [
    rt random 80 - 40
    ifelse not can-move? 1
    [ rt 180 ]
    [ fd 1 ]
  ]

  if ticks = 50 [
    export-ascii
    stop
  ]
  tick
end

to export-ascii
  ask patches with [ any? turtles-here ] [
    set turtle-here 1
  ]
  let ras_out gis:patch-dataset turtle-here
  gis:store-dataset ras_out "any_turtle_here.asc"
end
</code>```

This exports an ascii file that stores the patches-own variable called turtle-here that simply indicates if a turtle is present on the patch at the time of export:

```<code>NCOLS 15
NROWS 15
XLLCORNER 50000
YLLCORNER 50000
CELLSIZE 333.333333
NODATA_VALUE NaN
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
</code>```

Body:
I would like to know how I can transform a .csv file into raster (ASCII) within NetLogo 6.2?

Well, I can export in .csv to do the conversion later in .ASCII in another program such as R. However, I think it should be possible to export the output in .ASCII by NetLogo itself. At the same time, I would like to know if in terms of processing it would be better to export the output in .csv by NetLogo or in .ASCII? obs.: my world on NetLogo is relatively big

Thanks in advance

extensions [ gis ]

globals [ file output-filename ]

to setup
  clear-all
  reset-ticks
  set output-filename "output-data.csv"
  set-default-shape turtles "person"
  create-turtles 10 [
    setxy random-pxcor random-pycor
  ]
  initialize-data-file

end

to initialize-data-file
  file-close-all
  if file-exists? output-filename [
    file-delete output-filename
  ]
  file-open output-filename
  file-print ( word "xcor, ycor" )
end

to go
  ask turtles [
    wander-about
    if ticks mod 50 = 0  [
      write-output-data who xcor ycor
    ]
  ]
  tick
end

to write-output-data [ #turtle-id #xpos #ypos ]
  file-open output-filename
  file-print ( word #xpos ", " #ypos )
  file-flush

  ; set file gis:patch-dataset xcor ycor
  ;  gis:store-dataset file "test.asc"

end

to wander-about
  rt random 40
  lt random 40
  if not can-move? 1 [ rt 180 ]
  fd 1
end

Body:
You're on the right track using the GIS extension to export directly to ASCII. Whether you actually need to do this depends entirely on your application- as you say, it may be possible to do what you need simply by exporting a list of turtle coordinates, or of patch values, etc., depending on your needs. Whether you should use ASCII or csv is going to depend on your application, but: for all of my larger models where I actually need to export the whole world for analysis (and, more importantly, to go the other way and import my spatial data into NetLogo), I always use the GIS extension because it seems to be much faster. If I were only exporting turtle characteristics I would probably export to csv.

To answer your specific question here about how to export directly to ASC- here is one way. You need to set up some spatial information for the GIS extension to work with your data, but once you've done that you can create a raster dataset from patch values and export that to a .ASC file that will consist of the .ASC header in addition to a value for each patch in your world. With this example:

extensions [ gis ]

patches-own [ turtle-here ]

to setup
  ca
  resize-world 0 14 0 14
  ; Pull in some coordinate system
  gis:load-coordinate-system "utm_11.prj"
  ; Set some envelope. Unless you are actually spatially
  ; referencing your model, this is just a placeholder.
  ; If you are using actual spatial coordinates, set these
  ; appropriately or use gis:envelope-of
  gis:set-world-envelope [ 55000 50000 55000 50000 ]
  crt 10
  reset-ticks
end

to go
  ask turtles [
    rt random 80 - 40
    ifelse not can-move? 1
    [ rt 180 ]
    [ fd 1 ]
  ]

  if ticks = 50 [
    export-ascii
    stop
  ]
  tick
end

to export-ascii
  ask patches with [ any? turtles-here ] [
    set turtle-here 1
  ]
  let ras_out gis:patch-dataset turtle-here
  gis:store-dataset ras_out "any_turtle_here.asc"
end

This exports an ascii file that stores the patches-own variable called turtle-here that simply indicates if a turtle is present on the patch at the time of export:

NCOLS 15
NROWS 15
XLLCORNER 50000
YLLCORNER 50000
CELLSIZE 333.333333
NODATA_VALUE NaN
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0


问:
Combine publishers: notify when ANY of the publishers changes a value
I'd like to trigger a "change" event on every change of either the username or password published properties and set a new Credentials published property derived of those two and emit an event.

What would be the simplest solution to achieve this result using SwiftUI & Combine?

Some sample code with the idea I'm trying to achieve:

```<code>import SwiftUI
import Combine
import Foundation

struct Credentials {
    let username: String
    let password: String

    init(username: String = "",
         password: String = "") {
        self.userName = username
        self.password = password
    }
}

final class ViewModel: ObservableObject {
    @Published var username = ""
    @Published var password = ""

    @Published var credentials = Credentials()

    init() {
        [$username, $password]// ..... What to do here?
// How to "subscribe" each of those properties to emit an event
// so that I get notified each time one of them changes

        credentials = Credentials(username: $username, password: $password)
    }
}

</code>```

Essentially, I'm looking to something similar to this answer:
Swift Combine: How to create a single publisher from a list of publishers?

But with the notification should be triggered each time any of the publishers produce a value, not all of them.

答:
Instead of using Publishers.MergeMany as in your linked question, you want to use .combineLatest(_:) on your first publisher, like so:

import SwiftUI
import Combine
import Foundation

struct Credentials {
    let username: String
    let password: String

    init(username: String = "",
         password: String = "") {
        self.userName = username
        self.password = password
    }
}

final class ViewModel: ObservableObject {
    @Published var username = ""
    @Published var password = ""

    @Published var credentials = Credentials()

    private var cancellable: Cancellable? = nil

    init() {
        cancellable = $username.combineLatest($password).sink { tuple in
            self.credentials = Credentials(username: tuple.0, password: tuple.1)
        }

        credentials = Credentials(username: username, password: password)
    }
}
```

(it's been a bit so this code may not run immediately, but hopefully you see where this is going).

Body:
I'd like to trigger a "change" event on every change of either the username or password published properties and set a new Credentials published property derived of those two and emit an event.

What would be the simplest solution to achieve this result using SwiftUI & Combine?

Some sample code with the idea I'm trying to achieve:

import SwiftUI
import Combine
import Foundation

struct Credentials {
    let username: String
    let password: String

    init(username: String = "",
         password: String = "") {
        self.userName = username
        self.password = password
    }
}

final class ViewModel: ObservableObject {
    @Published var username = ""
    @Published var password = ""

    @Published var credentials = Credentials()

    init() {
        [$username, $password]// ..... What to do here?
// How to "subscribe" each of those properties to emit an event
// so that I get notified each time one of them changes

        credentials = Credentials(username: $username, password: $password)
    }
}

Essentially, I'm looking to something similar to this answer:
Swift Combine: How to create a single publisher from a list of publishers?

But with the notification should be triggered each time any of the publishers produce a value, not all of them.

Body:
Instead of using Publishers.MergeMany as in your linked question, you want to use .combineLatest(_:) on your first publisher, like so:

import SwiftUI
import Combine
import Foundation

struct Credentials {
    let username: String
    let password: String

    init(username: String = "",
         password: String = "") {
        self.userName = username
        self.password = password
    }
}

final class ViewModel: ObservableObject {
    @Published var username = ""
    @Published var password = ""

    @Published var credentials = Credentials()

    private var cancellable: Cancellable? = nil

    init() {
        cancellable = $username.combineLatest($password).sink { tuple in
            self.credentials = Credentials(username: tuple.0, password: tuple.1)
        }

        credentials = Credentials(username: username, password: password)
    }
}

(it's been a bit so this code may not run immediately, but hopefully you see where this is going).


问:
Terraform environment specific variables
Anyone know if there's a way to populate variables in Terraform based on what the environment/workspace is? Preferably one that

populates the var namespace (ie not an external data source),

doesn't require a wrapper

like tf(){ terraform --var-file=$(get_tf_env).tfvars

takes effect by changing a terraform env/workspace, without any additional manual steps (ie steps that aren't triggered by running terraform env )?

答:
Handling environmental variables in Terraform Workspaces -Taking Advantage of Workspaces, by Miles Collier 2019 explains clearly how this works. This is just a summary.

In parameters.tf:

locals {
   env = {
      default = {
         instance_type  = "t2.micro"
         ami            = "ami-0ff8a91507f77f867"
         instance_count = 1
      }
      dev = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-0130c3a072f3832ff"
      }
      qa = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-00f0abdef923519b0"
         instance_count = 3
      }
      prod = {
         instance_type  = "c5.4xlarge"
         ami            = "ami-0422d936d535c63b1"
         instance_count = 6
      }
   }
environmentvars = "${contains(keys(local.env), terraform.workspace)}" ? terraform.workspace : "default"
   workspace       = "${merge(local.env["default"], local.env[local.environmentvars])}"
}
```
<p>To reference a variable, add to locals or pass this to a module:</p>
```instance_type = "${local.workspace["instance_type"]}"
```

This will use the value from the selected workspace, or the default value if either the variable is not defined for that workspace, or no workspace is selected. If not default is defined, it fails gracefully.

Use terraform workspace select dev to select the dev workspace.

Body:
Handling environmental variables in Terraform Workspaces -Taking Advantage of Workspaces, by Miles Collier 2019 explains clearly how this works. This is just a summary.

In parameters.tf:

locals {
   env = {
      default = {
         instance_type  = "t2.micro"
         ami            = "ami-0ff8a91507f77f867"
         instance_count = 1
      }
      dev = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-0130c3a072f3832ff"
      }
      qa = {
         instance_type  = "m5.2xlarge"
         ami            = "ami-00f0abdef923519b0"
         instance_count = 3
      }
      prod = {
         instance_type  = "c5.4xlarge"
         ami            = "ami-0422d936d535c63b1"
         instance_count = 6
      }
   }
environmentvars = "${contains(keys(local.env), terraform.workspace)}" ? terraform.workspace : "default"
   workspace       = "${merge(local.env["default"], local.env[local.environmentvars])}"
}

To reference a variable, add to locals or pass this to a module:

instance_type = "${local.workspace["instance_type"]}"

This will use the value from the selected workspace, or the default value if either the variable is not defined for that workspace, or no workspace is selected. If not default is defined, it fails gracefully.

Use terraform workspace select dev to select the dev workspace.


问:
Cannot read properties of undefined (reading 'name') Angular
I need your help. Now I'm trying to deal with routes in Angular. I took the data from JSON placeholder. I'm trying to display user details. Everything works for me, but in the console I get this error
Cannot read properties of undefined (reading 'name')

When I use the pipe in the file user-details.component.ts, everything works for me, I get a json object, but when I want to output a separate field from the model, I get an error. The data types from the model correspond to the data type from the json url.

What am I doing wrong? Thank you very much

users.component.ts

```<code>import {IUser} from "../models/user";
import { Component, OnInit } from '@angular/core';
import {UserService} from "../services/user.service";

@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

users: IUser[]

constructor(private userService: UserService) { }

ngOnInit(): void {
this.userService.getUsers().subscribe(value => this.users = value);
}

}
</code>```

user.component.ts

```<code>import { Component, OnInit, Input } from '@angular/core';
import {IUser} from "../models/user";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})

export class UserComponent implements OnInit {

@Input()
user: IUser

constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

ngOnInit(): void {}

goToDetails():void {
this.router.navigate([this.user.id],{relativeTo: this.activatedRoute, state: this.user})
}
}
</code>```

user-details.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {IUser} from "../models/user";

@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.css']
})

export class UserDetailsComponent implements OnInit {

fullUser: IUser;

 constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.activatedRoute.params.subscribe(params => {
  this.fullUser = this.router.getCurrentNavigation()?.extras.state as IUser
})
}
ngOnInit(): void {}
}
</code>```

user-details.component.html

```<code><div>
<!--{{fullUser | json}}-->
{{fullUser.name}}
</div>
</code>```

答:
Not needed with ngif and that check if object exists and it seems it does so this should not work? best practice you should create a user model for your object->

```<code>export interface User {
  name: string;
}
</code>```

then import and use the model definition, in that case name is defined

OR ugly fix to tryout ->

```<code>{{ user["fullUser"] && user["fullUser"]?.name}}
</code>```

Body:
I need your help. Now I'm trying to deal with routes in Angular. I took the data from JSON placeholder. I'm trying to display user details. Everything works for me, but in the console I get this error
Cannot read properties of undefined (reading 'name')

When I use the pipe in the file user-details.component.ts, everything works for me, I get a json object, but when I want to output a separate field from the model, I get an error. The data types from the model correspond to the data type from the json url.

What am I doing wrong? Thank you very much

users.component.ts

import {IUser} from "../models/user";
import { Component, OnInit } from '@angular/core';
import {UserService} from "../services/user.service";

@Component({
selector: 'app-users',
templateUrl: './users.component.html',
styleUrls: ['./users.component.css']
})

export class UsersComponent implements OnInit {

users: IUser[]

constructor(private userService: UserService) { }

ngOnInit(): void {
this.userService.getUsers().subscribe(value => this.users = value);
}

}

user.component.ts

import { Component, OnInit, Input } from '@angular/core';
import {IUser} from "../models/user";
import {ActivatedRoute, Router} from "@angular/router";

@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})

export class UserComponent implements OnInit {

@Input()
user: IUser

constructor(private router: Router, private activatedRoute: ActivatedRoute) { }

ngOnInit(): void {}

goToDetails():void {
this.router.navigate([this.user.id],{relativeTo: this.activatedRoute, state: this.user})
}
}

user-details.component.ts

import { Component, OnInit } from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {IUser} from "../models/user";

@Component({
selector: 'app-user-details',
templateUrl: './user-details.component.html',
styleUrls: ['./user-details.component.css']
})

export class UserDetailsComponent implements OnInit {

fullUser: IUser;

 constructor(private router: Router, private activatedRoute: ActivatedRoute) {
this.activatedRoute.params.subscribe(params => {
  this.fullUser = this.router.getCurrentNavigation()?.extras.state as IUser
})
}
ngOnInit(): void {}
}

user-details.component.html

{{fullUser.name}}

Body:
Not needed with ngif and that check if object exists and it seems it does so this should not work? best practice you should create a user model for your object->

export interface User {
  name: string;
}

then import and use the model definition, in that case name is defined

OR ugly fix to tryout ->

{{ user["fullUser"] && user["fullUser"]?.name}}


问:
What is the least privilege required for getting serviceaccounts including cluster-admin bound accounts?
I have a k8s cluster in minikube, configured a service account admin-user with the cluster-admin role, and am configuring the ServiceAccount below to use in my own application. Everything is applied in the same namespace and my spec is using the me serviceAccountName.

```<code>apiVersion: v1
kind: ServiceAccount
metadata:
  name: me

---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: myRole
rules:
  - apiGroups: [""]
    resources: ["serviceaccounts, secrets"]
    verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: myRoleBinding
subjects:
  - kind: ServiceAccount
    name: me
    namespace: namespace
roleRef:
  kind: Role
  name: myRole
  apiGroup: rbac.authorization.k8s.io
</code>```

My application uses the rest.InClusterConfig.

When executing client.CoreV1().ServiceAccounts("namespace").Get(ctx, "admin-user", meta.GetOptions{}) I get this error:

serviceaccounts "admin-user" is forbidden: User "system:serviceaccount:namespace:me" cannot get resource "serviceaccounts" in API group "" in the namespace "namespace"

When I bind the me ServiceAccount to the default view ClusterRole instead of myRole, my client call then works. From what I can tell, I am granting the same privileges necessary for serviceaccounts in myRole compared to view.

It seems I am not granting the correct privileges but I can't figure out what is necessary.

答:
Typo in resources: ["serviceaccounts, secrets"].

Should be resources: ["serviceaccounts", "secrets"].

Body:
I have a k8s cluster in minikube, configured a service account admin-user with the cluster-admin role, and am configuring the ServiceAccount below to use in my own application. Everything is applied in the same namespace and my spec is using the me serviceAccountName.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: me

---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: myRole
rules:
  - apiGroups: [""]
    resources: ["serviceaccounts, secrets"]
    verbs: ["get"]

---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: myRoleBinding
subjects:
  - kind: ServiceAccount
    name: me
    namespace: namespace
roleRef:
  kind: Role
  name: myRole
  apiGroup: rbac.authorization.k8s.io

My application uses the rest.InClusterConfig.

When executing client.CoreV1().ServiceAccounts("namespace").Get(ctx, "admin-user", meta.GetOptions{}) I get this error:

serviceaccounts "admin-user" is forbidden: User "system:serviceaccount:namespace:me" cannot get resource "serviceaccounts" in API group "" in the namespace "namespace"

When I bind the me ServiceAccount to the default view ClusterRole instead of myRole, my client call then works. From what I can tell, I am granting the same privileges necessary for serviceaccounts in myRole compared to view.

It seems I am not granting the correct privileges but I can't figure out what is necessary.


问:
Is it possible to assign the local variable after calling a global function with the same name?
Suppose I have defined a function foo:

```<code>def foo():
    print('hi')
    return np.array([1,2,3])
</code>```

I want to use the result it provides inside another function called 'execute', and assign that result to local variable having the same name 'foo':

```<code>def execute():
    foo = foo()
    foo -= 1
    print(foo)

execute()
</code>```

The above will result in "local variable 'foo' referenced before assignment".

Now if I use global inside my execute function:

```<code>def execute():
    global foo
    foo = foo()
    ...
</code>```

It will work but after calling it once it will rewrite the global function, which isn't what we want.

答:
You could use globals() directly:

def execute():
    foo = globals()["foo"]()
    foo -= 1
    print(foo)
```
<p>But really I think you should avoid the name conflict in the first place, which would be less confusing to readers:</p>
<pre class="lang-py prettyprint-override"><code>def execute():
    foo_result = foo()
    foo_result -= 1
    print(foo_result)
</code>```

Body:
Suppose I have defined a function foo:

def foo():
    print('hi')
    return np.array([1,2,3])

I want to use the result it provides inside another function called 'execute', and assign that result to local variable having the same name 'foo':

def execute():
    foo = foo()
    foo -= 1
    print(foo)

execute()

The above will result in "local variable 'foo' referenced before assignment".

Now if I use global inside my execute function:

def execute():
    global foo
    foo = foo()
    ...

It will work but after calling it once it will rewrite the global function, which isn't what we want.

Body:
You could use globals() directly:

def execute():
    foo = globals()["foo"]()
    foo -= 1
    print(foo)

But really I think you should avoid the name conflict in the first place, which would be less confusing to readers:

def execute():
    foo_result = foo()
    foo_result -= 1
    print(foo_result)


问:
Various CSS files for various Media queries
I'd want to utilize multiple CSS files for different screen sizes, and I've read some articles about it, but it doesn't work when I attempt it. I only have one CSS on the page, and it's getting a little messy, so I really need some help figuring out how to utilize several CSS in my HTML. Nothing seems to function when I try to upload numerous CSS files from external files.

Here's the HTML head, where I'm attempting to include several external CSS files.

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <link rel="stylesheet" href="./style450.css" media='screen (min-width: 10px) and (max-width: 450px)'>
    <link rel="stylesheet" href="./style700.css" media='screen (min-width: 451px) and (max-width: 700px)'>
    <link rel="stylesheet" href="./style991.css" media='screen (min-width: 701px) and (max-width: 991px)'>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <title>Developer Portfolio</title>
```

答:
You miss an and between screen and size

Check link for more details

You can also provide a media type or query inside a media attribute;
this resource will then only be loaded if the media condition is true.
For example:

```<code>
<meta content="width=device-width, initial-scale=1" name="viewport" />

<link href="print.css" rel="stylesheet" media="print">

 <link
href="mobile.css" rel="stylesheet" media="screen and (max-width:
600px)">
</code>```

Notice the and after screen

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <link rel="stylesheet" href="./style450.css" media='screen and (min-width: 10px) and (max-width: 450px)'>
    <link rel="stylesheet" href="./style700.css" media='screen and (min-width: 451px) and (max-width: 700px)'>
    <link rel="stylesheet" href="./style991.css" media='screen and (min-width: 701px) and (max-width: 991px)'>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <title>Developer Portfolio</title>
```
</div>
</div>
</p>
<p>Edit to use another way:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>@media screen and (min-width: 451px) and (max-width: 700px)
{
@import url('./style700.css');
}
@media screen and (min-width: 701px) and (max-width: 991px)
{
@import url('./style700.css');
}
@media screen and (min-width: 10px) and (max-width: 450px)
{
@import url('./style991.css');
}</code>```

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <title>Developer Portfolio</title>
```

Body:
You miss an and between screen and size

Check link for more details

You can also provide a media type or query inside a media attribute;
this resource will then only be loaded if the media condition is true.
For example:

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

<link href="print.css" rel="stylesheet" media="print">

 <link
href="mobile.css" rel="stylesheet" media="screen and (max-width:
600px)">

Notice the and after screen

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">
    <link rel="stylesheet" href="./style450.css" media='screen and (min-width: 10px) and (max-width: 450px)'>
    <link rel="stylesheet" href="./style700.css" media='screen and (min-width: 451px) and (max-width: 700px)'>
    <link rel="stylesheet" href="./style991.css" media='screen and (min-width: 701px) and (max-width: 991px)'>
    <script defer src="./script.js"></script>
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css"> -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <title>Developer Portfolio</title>
</head>

Edit to use another way:

@media screen and (min-width: 451px) and (max-width: 700px)
{
@import url('./style700.css');
}
@media screen and (min-width: 701px) and (max-width: 991px)
{
@import url('./style700.css');
}
@media screen and (min-width: 10px) and (max-width: 450px)
{
@import url('./style991.css');
}

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="./style.css">

    <script defer src="./script.js"></script>
    <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css"> -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">
    <title>Developer Portfolio</title>
</head>


问:
Efficient and scalable storage for JSON data with NoSQL databases
We are working on a project which should collect journal and audit data and store it in a datastore for archive purposes and some views. We are not quite sure which datastore would work for us.

we need to store small JSON documents, about 150 bytes, e.g. "audit:{timestamp: '86346512',host':'foo',username:'bar',task:'foo',result:0}" or "journal:{timestamp:'86346512',host':'foo',terminalid:1,type='bar',rc=0}"

we are expecting about one million entries per day, about 150 MB data

data will be stored and read but never modified

data should stored in an efficient way, e.g. binary format used by Apache Avro

after a retention time data may be deleted

custom queries, such as 'get audit for user and time period' or 'get journal for terminalid and time period'

replicated data base for failsafe

scalable

Currently we are evaluating NoSQL databases like Hadoop/Hbase, CouchDB, MongoDB and Cassandra. Are these databases the right datastore for us? Which of them would fit best?
Are there better options?

答:
One million inserts / day is about 10 inserts / second.  Most databases can deal with this, and its well below the max insertion rate we get from Cassandra on reasonable hardware (50k inserts / sec)

Your requirement "after a retention time data may be deleted" fits Cassandra's column TTLs nicely - when you insert data you can specify how long to keep it for, then background merge processes will drop that data when it reaches that timeout.

"data should stored in an efficient way, e.g. binary format used by Apache Avro" - Cassandra (like many other NOSQL stores) treats values as opaque byte sequences, so you can encode you values how ever you like.  You could also consider decomposing the value into a series of columns, which would allow you to do more complicated queries.

custom queries, such as 'get audit for user and time period' - in Cassandra, you would model this by having the row key to be the user id and the column key being the time of the event (most likely a timeuuid).  You would then use a get_slice call (or even better CQL) to satisfy this query

or 'get journal for terminalid and time period' - as above, have the row key be terminalid and column key be timestamp.  One thing to note is that in Cassandra (like many join-less stores), it is typical to insert the data more than once (in different arrangements) to optimise for different queries.

Cassandra has a very sophisticate replication model, where you can specify different consistency levels per operation.  Cassandra is also very scalable system with no single point of failure or bottleneck.  This is really the main difference between Cassandra and things like MongoDB or HBase (not that I want to start a flame!)

Having said all of this, your requirements could easily be satisfied by a more traditional database and simple master-slave replication, nothing here is too onerous


问:
PHP encapsulation without class?
Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:

```<code>//Include the file containing the class which contains the variable or function
include('SomePage.php');

//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();

//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;
</code>```

My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?

答:
This is a way to encapsulate without Class

```<code><?php

(function (){

$xyz = 'XYZ';

})();

echo $xyz; // warning: undefined
</code>```

Encapsulation Alternative

With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.

Example

```<code><?php

define('APP', 'woi49f25gtx');

(function () {

    $pre = 'functions__math__'; // "functions" is main category, "math" is sub.

    $GLOBALS[APP][$pre . 'allowedNumbers'] = [3,5,6];

    $GLOBALS[APP][$pre . 'square'] = function ($num) {
        return $num * $num;
    };

    $GLOBALS[APP][$pre . 'myMathFunction'] = function ($num) use ($pre) {
        if(in_array($num,$GLOBALS[APP][$pre . 'allowedNumbers'])) return 'not allowed';
        return $GLOBALS[APP][$pre . 'square']($num);
    };

})();

echo $GLOBALS[APP]['functions__math__myMathFunction'](4);
</code>```

Title: PHP encapsulation without class?

Body:
Is it possible to encapsulate, a variable or function let say, in PHP without wrapping them in a class? What I was doing is:

//Include the file containing the class which contains the variable or function
include('SomePage.php');

//Instantiate the class from "SomePage.php"
$NewObject = new SomeClassFromSomePage();

//Use the function or variable
echo $NewObject->SomeFuncFromSomeClass();
echo $NewObject->SomeVarFromSomeClass;

My intention is to avoid naming conflict. This routine, although it works, makes me tired. If I cannot do it without class, it is possible not to instantiate a class? and just use the variable or function instantly?

Body:
This is a way to encapsulate without Class

<?php

(function (){

$xyz = 'XYZ';

})();

echo $xyz; // warning: undefined

Encapsulation Alternative

With this method you can minimize unintentional using array key(uses it instead of variables). Can also use value stored in array anywhere after assigning. Shorter array key area length with variable in keys, inside encapsulation function; outside encapsulation function, variables can be used in keys but otherwise long discriptive keys. Nested encapsulation can also be used.

Example

<?php

define('APP', 'woi49f25gtx');

(function () {

    $pre = 'functions__math__'; // "functions" is main category, "math" is sub.

    $GLOBALS[APP][$pre . 'allowedNumbers'] = [3,5,6];

    $GLOBALS[APP][$pre . 'square'] = function ($num) {
        return $num * $num;
    };

    $GLOBALS[APP][$pre . 'myMathFunction'] = function ($num) use ($pre) {
        if(in_array($num,$GLOBALS[APP][$pre . 'allowedNumbers'])) return 'not allowed';
        return $GLOBALS[APP][$pre . 'square']($num);
    };

})();

echo $GLOBALS[APP]['functions__math__myMathFunction'](4);


答: In this example, it would perhaps be best to rename the function to get_foo() or make_foo() or generate_foo(), to disambiguate from the object foo it returns.

Title: Is it possible to assign the local variable after calling a global function with the same name?