问:
Why am I getting SyntaxError: Cannot use import statement outside a module
I'm trying to integrating the google calendar API to my NextJs application using the gapi-script (https://www.npmjs.com/package/gapi-script) but I found this error when importing the gapi-script:

SyntaxError: Cannot use import statement outside a module

I tried the next dynamic import and the react useEffect, but it doesn't work.

```<code>  import {
  Box, Container, Text, Stack, Spacer, Button,
} from '@chakra-ui/react';
import { StarIcon } from '@chakra-ui/icons';
import { useState, useEffect } from 'react';
// import { gapi } from 'gapi-script';
import DatePicker from 'react-datepicker';
import dynamic from 'next/dynamic';
import GoBack from '../../../components/GoBack';
import Template from '../../../templates/empresa';
import 'react-datepicker/dist/react-datepicker.css';

const sobreVaga = () => {
  const [startDate, setStartDate] = useState(new Date());

  const CLIENT_ID = '545217530327-icjp9agk335v7qr6v7hhatmhui5h5qme.apps.googleusercontent.com';
  const API_KEY = 'AIzaSyC1nbNHQQB1LIPZwI9JB13AHweFGBD_dnM';
  const DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'];
  const SCOPES = 'https://www.googleapis.com/auth/calendar';
  const handleClick = () => {
    const gapi = document.createElement('script');
    gapi.src = 'https://apis.google.com/js/client.js';
    gapi.load('client:auth2', () => {
      gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES,
      });

      gapi.client.load('calendar', 'v3', () => console.log('bam!'));

      gapi.auth2.getAuthInstance().signIn()
        .then(() => {
          const event = {
            summary: 'Awesome Event!',
            location: '800 Howard St., San Francisco, CA 94103',
            description: 'Really great refreshments',
            start: {
              dateTime: startDate,
              timeZone: 'America/Los_Angeles',
            },
            end: {
              dateTime: startDate,
              timeZone: 'America/Los_Angeles',
            },
            recurrence: [
              'RRULE:FREQ=DAILY;COUNT=2',
            ],
            attendees: [
              { email: 'lpage@example.com' },
              { email: 'sbrin@example.com' },
            ],
            reminders: {
              useDefault: false,
              overrides: [
                { method: 'email', minutes: 24 * 60 },
                { method: 'popup', minutes: 10 },
              ],
            },
          };

          const request = window.gapi.client.calendar.events.insert({
            calendarId: 'primary',
            resource: event,
          });

          request.execute((event) => {
            console.log(event);
            window.open(event.htmlLink);
          });
        });
    });
  };

  return (
    <Template>
      <Box background="#A8A8A8" color="white" paddingY={10}>
        <Container maxW="container.xl" mb="6">
          <GoBack />
          <Stack spacing="0.5">
            <Text>Área de atuação</Text>
            <Text fontSize="2xl">Nome da vaga - Senioridade </Text>
            <Text fontSize="md">Cidade - estado</Text>
          </Stack>
        </Container>
        <Container maxW="container.xl">
          <Box>
            <Stack spacing="2">
              <Text>Prazo de entrega: x dias </Text>
              <Text>Fase do projeto: entrevista </Text>
            </Stack>
          </Box>
        </Container>
      </Box>
      <Container mt="10">
        <Box
          height="500"
          overflowY="auto"
          css={{
            '&::-webkit-scrollbar': {
              width: '4px',
            },
            '&::-webkit-scrollbar-track': {
              width: '6px',
            },
            '&::-webkit-scrollbar-thumb': {
              background: 'Gray',
              borderRadius: '24px',
            },
          }}
        >
          <Stack>
            <Box
              width="100%"
              height="140"
              bg="#A8A8A8"
              borderWidth="1px"
              borderRadius="lg"
              color="white"
              display="flex"
            >
              <Stack ml="5" mt="3">
                <Text
                  as="u"
                  fontsize="xl"
                  align="left"
                >
                  Nome do candidato
                </Text>
                <Text
                  fontsize="xl"
                  align="left"
                >
                  Entrevista: não agendada
                </Text>
              </Stack>
              <Box>
                <StarIcon as="button" mt="3" ml="40" />
                <Spacer />
                <Box display="flex" align="right" mt="5" />
              </Box>
              <DatePicker
                selected={startDate}
                onChange={(date) => setStartDate(date)}
                locale="pt-BR"
                showTimeSelect
                timeFormat="p"
                timeIntervals={15}
                dateFormat="Pp"
              />
              <Button onClick={handleClick}> Hora da vdd *--*</Button>
              <Box />
            </Box>
          </Stack>
        </Box>
      </Container>
    </Template>
  );
};

export default sobreVaga;
 here
</code>```

答:
inside handleClick function, Please replace

const handleClick = () => {
   const gapi = document.createElement('script');
   gapi.src = 'https://apis.google.com/js/client.js';
```
<p>with</p>
<pre class="lang-js prettyprint-override"><code>const handleClick = async () => {
   const gapi = await import('gapi-script').then((pack) => pack.gapi);
</code>```

It will work.

Body:
I'm trying to integrating the google calendar API to my NextJs application using the gapi-script (https://www.npmjs.com/package/gapi-script) but I found this error when importing the gapi-script:

SyntaxError: Cannot use import statement outside a module

I tried the next dynamic import and the react useEffect, but it doesn't work.

  import {
  Box, Container, Text, Stack, Spacer, Button,
} from '@chakra-ui/react';
import { StarIcon } from '@chakra-ui/icons';
import { useState, useEffect } from 'react';
// import { gapi } from 'gapi-script';
import DatePicker from 'react-datepicker';
import dynamic from 'next/dynamic';
import GoBack from '../../../components/GoBack';
import Template from '../../../templates/empresa';
import 'react-datepicker/dist/react-datepicker.css';

const sobreVaga = () => {
  const [startDate, setStartDate] = useState(new Date());

  const CLIENT_ID = '545217530327-icjp9agk335v7qr6v7hhatmhui5h5qme.apps.googleusercontent.com';
  const API_KEY = 'AIzaSyC1nbNHQQB1LIPZwI9JB13AHweFGBD_dnM';
  const DISCOVERY_DOCS = ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'];
  const SCOPES = 'https://www.googleapis.com/auth/calendar';
  const handleClick = () => {
    const gapi = document.createElement('script');
    gapi.src = 'https://apis.google.com/js/client.js';
    gapi.load('client:auth2', () => {
      gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES,
      });

      gapi.client.load('calendar', 'v3', () => console.log('bam!'));

      gapi.auth2.getAuthInstance().signIn()
        .then(() => {
          const event = {
            summary: 'Awesome Event!',
            location: '800 Howard St., San Francisco, CA 94103',
            description: 'Really great refreshments',
            start: {
              dateTime: startDate,
              timeZone: 'America/Los_Angeles',
            },
            end: {
              dateTime: startDate,
              timeZone: 'America/Los_Angeles',
            },
            recurrence: [
              'RRULE:FREQ=DAILY;COUNT=2',
            ],
            attendees: [
              { email: 'lpage@example.com' },
              { email: 'sbrin@example.com' },
            ],
            reminders: {
              useDefault: false,
              overrides: [
                { method: 'email', minutes: 24 * 60 },
                { method: 'popup', minutes: 10 },
              ],
            },
          };

          const request = window.gapi.client.calendar.events.insert({
            calendarId: 'primary',
            resource: event,
          });

          request.execute((event) => {
            console.log(event);
            window.open(event.htmlLink);
          });
        });
    });
  };

  return (
    <Template>
      <Box background="#A8A8A8" color="white" paddingY={10}>
        <Container maxW="container.xl" mb="6">
          <GoBack />
          <Stack spacing="0.5">
            <Text>Área de atuação</Text>
            <Text fontSize="2xl">Nome da vaga - Senioridade </Text>
            <Text fontSize="md">Cidade - estado</Text>
          </Stack>
        </Container>
        <Container maxW="container.xl">
          <Box>
            <Stack spacing="2">
              <Text>Prazo de entrega: x dias </Text>
              <Text>Fase do projeto: entrevista </Text>
            </Stack>
          </Box>
        </Container>
      </Box>
      <Container mt="10">
        <Box
          height="500"
          overflowY="auto"
          css={{
            '&::-webkit-scrollbar': {
              width: '4px',
            },
            '&::-webkit-scrollbar-track': {
              width: '6px',
            },
            '&::-webkit-scrollbar-thumb': {
              background: 'Gray',
              borderRadius: '24px',
            },
          }}
        >
          <Stack>
            <Box
              width="100%"
              height="140"
              bg="#A8A8A8"
              borderWidth="1px"
              borderRadius="lg"
              color="white"
              display="flex"
            >
              <Stack ml="5" mt="3">
                <Text
                  as="u"
                  fontsize="xl"
                  align="left"
                >
                  Nome do candidato
                </Text>
                <Text
                  fontsize="xl"
                  align="left"
                >
                  Entrevista: não agendada
                </Text>
              </Stack>
              <Box>
                <StarIcon as="button" mt="3" ml="40" />
                <Spacer />
                <Box display="flex" align="right" mt="5" />
              </Box>
              <DatePicker
                selected={startDate}
                onChange={(date) => setStartDate(date)}
                locale="pt-BR"
                showTimeSelect
                timeFormat="p"
                timeIntervals={15}
                dateFormat="Pp"
              />
              <Button onClick={handleClick}> Hora da vdd *--*</Button>
              <Box />
            </Box>
          </Stack>
        </Box>
      </Container>
    </Template>
  );
};

export default sobreVaga;
 here

Body:
inside handleClick function, Please replace

const handleClick = () => {
   const gapi = document.createElement('script');
   gapi.src = 'https://apis.google.com/js/client.js';

with

const handleClick = async () => {
   const gapi = await import('gapi-script').then((pack) => pack.gapi);

It will work.


来源: stackexchange

问:
Are GUID collisions possible?
I'm working on a database in SQL Server 2000 that uses a GUID for each user that uses the app it's tied to. Somehow, two users ended up with the same GUID. I know that microsoft uses an algorithm to generate a random GUID that has an extremely low chance of causing collisons, but is a collision still possible?</p>

答: Don’t worry about what it is. Make it impossible. Mix the improbability of GUID with the impossibility of sequential. Just add a  database sequential I’d to the GUID and call it done. You may need to change the data type from GUID to String-ish but they are not that different storage wise.</p>

OwnerDisplayName: Jason Baker

ContentLicense: CC BY-SA 3.0

Title: Are GUID collisions possible?

LastEditorDisplayName: Scott Saad

ContentLicense: CC BY-SA 4.0


问:
How to measure current size of .NET Memory Cache 4.0?
Currently we're using the .NET Memory Cache 4.0 for the Caching requirements. (not ASP.NET Cache, not any external Cache)

Looking at the '.NET Memory Cache 4.0' performance counters, there is data around Cache Hits, Misses, Entries, Trims etc. but nothing related to Size.

Is there is a way of measuring/knowing the current size of the Cache used by the Production Application?

I want to be able to capture this data at various points in time and get the average size of the cache.

答:
Since .NET 4.7 you can use GetLastSize()

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.caching.memorycache.getlastsize?view=dotnet-plat-ext-6.0


问:
Is the class component of React JS going to obsolete?
I am aware that React’s official documentation states that there's no plan to deprecate class components any time soon. But, according to some website and article, the class components are going to obsolete.</p>

答:
There is no plans to remove class components. Library developers recommend use functional components in new code.

You can write functional or class components if you can keep code clean and easy to understand for any develop.


问:
How method hiding works in C#? (Part Two)
The following program prints

```<code>A:C(A,B)
B:C(A,B)
</code>```

(as it should)

```<code>public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}
</code>```

however, if I change keyword 'new' to 'override' in class B like so:

```<code>    public override void Print(C c)
</code>```

all of a sudden program starts to print:

```<code>A:C(A,B)
B:I(A)
</code>```

Why?

答:
This is to do with how overloaded methods are resolved.

Effectively (simplified somewhat), the compiler first looks at the declared type of the expression (B) in this case and looks for candidate methods which are first declared in that type. If there are any methods which are appropriate (i.e. where all the arguments can be converted to the method's parameter types) then it doesn't look at any parent types. This means that overridden methods, where the initial declaration is in a parent type, don't get a look-in if there are any "freshly declared" appropriate methods in the derived type.

Here's a slightly simpler example:

```<code>using System;

class Base
{
    public virtual void Foo(int x)
    {
        Console.WriteLine("Base.Foo(int)");
    }
}

class Derived : Base
{
    public override void Foo(int x)
    {
        Console.WriteLine("Derived.Foo(int)");
    }

    public void Foo(double d)
    {
        Console.WriteLine("Derived.Foo(double)");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        d.Foo(10);
    }
}
</code>```

This prints Derived.Foo(double) - even though the compiler knows there is a matching method with a parameter of type int, and the argument is type int, and the conversion from int to int is "better" than the conversion from int to double, the fact that only the Foo(double) method is originally declared in Derived means the compiler ignores Foo(int).

This is highly surprising IMO. I can see why it would be the case if Derived didn't override Foo - otherwise introducing a new, more specific, method in the base class could change the behaviour unexpectedly - but clearly Derived here knows about Base.Foo(int) as it's overriding it. This is one of the (relatively few) points where I believe the C# designers made the wrong decision.

ContentLicense: CC BY-SA 2.5

Body:
The following program prints

A:C(A,B)
B:C(A,B)

(as it should)

public interface I
{
    string A();
}

public class C : I
{
    public string A()
    {
        return "A";
    }

    public string B()
    {
        return "B";
    }
}

public class A
{
    public virtual void Print(C c)
    {
        Console.WriteLine("A:C(" + c.A() + "," + c.B() + ")");
    }
}

public class B : A
{
    public new void Print(C c)
    {
        Console.WriteLine("B:C(" + c.A() + "," + c.B() + ")");
    }

    public void Print(I i)
    {
        Console.WriteLine("B:I(" + i.A() + ")");
    }
}

class Program
{
    public static void Main(string[] args)
    {
        A a = new A();
        B b = new B();
        C c = new C();
        a.Print(c);
        b.Print(c);
    }
}

however, if I change keyword 'new' to 'override' in class B like so:

    public override void Print(C c)

all of a sudden program starts to print:

A:C(A,B)
B:I(A)

Why?

Body:
This is to do with how overloaded methods are resolved.

Effectively (simplified somewhat), the compiler first looks at the declared type of the expression (B) in this case and looks for candidate methods which are first declared in that type. If there are any methods which are appropriate (i.e. where all the arguments can be converted to the method's parameter types) then it doesn't look at any parent types. This means that overridden methods, where the initial declaration is in a parent type, don't get a look-in if there are any "freshly declared" appropriate methods in the derived type.

Here's a slightly simpler example:

using System;

class Base
{
    public virtual void Foo(int x)
    {
        Console.WriteLine("Base.Foo(int)");
    }
}

class Derived : Base
{
    public override void Foo(int x)
    {
        Console.WriteLine("Derived.Foo(int)");
    }

    public void Foo(double d)
    {
        Console.WriteLine("Derived.Foo(double)");
    }
}

class Test
{
    static void Main()
    {
        Derived d = new Derived();
        d.Foo(10);
    }
}

This prints Derived.Foo(double) - even though the compiler knows there is a matching method with a parameter of type int, and the argument is type int, and the conversion from int to int is "better" than the conversion from int to double, the fact that only the Foo(double) method is originally declared in Derived means the compiler ignores Foo(int).

This is highly surprising IMO. I can see why it would be the case if Derived didn't override Foo - otherwise introducing a new, more specific, method in the base class could change the behaviour unexpectedly - but clearly Derived here knows about Base.Foo(int) as it's overriding it. This is one of the (relatively few) points where I believe the C# designers made the wrong decision.

OwnerDisplayName: Jon Skeet

LastEditorDisplayName: Jon Skeet


问:
[PHP][MySQL]How To SELECT data with two constrain?
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

```<code>Tid=user02 and Fid=user01
</code>```

and cons2 is

```<code>Tid=user01 and Fid=user02
</code>```

the data I want to output is something like:

```<code>$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');
</code>```

+

```<code>$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');
</code>```

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

答:
You can OR the two conditions resulting in a single query:

```<code>SELECT * FROM chat
   WHERE (Tid='user02' AND Fid='user01')
      OR (Tid='user01' AND Fid='user02')
</code>```

Body:
I'm new to PHP+MySQL programming

I want to SELCET data using tow constrain at once,

the cons1 is

Tid=user02 and Fid=user01

and cons2 is

Tid=user01 and Fid=user02

the data I want to output is something like:

$result1 = mysql_query("SELECT * FROM myTable WHERE Tid='user02' AND Fid='user01');

+

$result2 = mysql_query("SELECT * FROM myTable WHERE Tid='user01' AND Fid='user02');

= what I want

can it be done in single line?

or can make a result which stored $result1 and $result2

thanks for taking time reading my question

Body:
You can OR the two conditions resulting in a single query:

SELECT * FROM chat
   WHERE (Tid='user02' AND Fid='user01')
      OR (Tid='user01' AND Fid='user02')


问:
Python program for soccer odds
```<code>match = input('Enter match? ')
odd1 = input("Enter tip for home: ")
if(not odd1.replace(".","").isnumeric()):
    print("Sorry home tip is not numeric")
    exit(0)
if(float(odd1)<=1):
    print("Odd cannot be less than one")
    exit(0)
odd2 = input("Enter tip for draw: ")
if(not odd2.replace(".","").isnumeric()):
    print("Sorry draw tip is not numeric")
    exit(0)
if(float(odd2)<=1):
    print("Odd cannot be less than one")
    exit(0)
odd3 = input("Enter tip for away: ")
#isnumberic() is it number
if(not odd3.replace(".","").isnumeric()):
    print("Sorry your tip is not numeric")
    exit(0)
if(float(odd3)<=1):
    print("Odd cannot be less than one")
    exit(0)

print("Thank you, your odd is: ")
print("Match: ", match)
print("Home: ", odd1)
print("Draw: ", odd2)
print("Away: ", odd3)
</code>```

Generally replace(val1, val2) method changes old value with a new one which is second argument. Why in this code checks if number is float. If I type float number in odd1 without replace, I am getting the message Sorry home tip is not numeric?

答:
odd1.replace(".","") means that change every dot in the string odd1 into to nothing (means delete it) generally .replace() is used to search about a char in a string and replace it with another
for example

```<code>s = "Hello. world"

r = s.replace(".", ",")

print(r)
</code>```

this code replace every dot in the string s with a comma

and then .isnumeric() tests if the value of odd1 after replacing is a number or not

Title: Python program for soccer odds

Body:
match = input('Enter match? ')
odd1 = input("Enter tip for home: ")
if(not odd1.replace(".","").isnumeric()):
    print("Sorry home tip is not numeric")
    exit(0)
if(float(odd1)<=1):
    print("Odd cannot be less than one")
    exit(0)
odd2 = input("Enter tip for draw: ")
if(not odd2.replace(".","").isnumeric()):
    print("Sorry draw tip is not numeric")
    exit(0)
if(float(odd2)<=1):
    print("Odd cannot be less than one")
    exit(0)
odd3 = input("Enter tip for away: ")
#isnumberic() is it number
if(not odd3.replace(".","").isnumeric()):
    print("Sorry your tip is not numeric")
    exit(0)
if(float(odd3)<=1):
    print("Odd cannot be less than one")
    exit(0)

print("Thank you, your odd is: ")
print("Match: ", match)
print("Home: ", odd1)
print("Draw: ", odd2)
print("Away: ", odd3)

Generally replace(val1, val2) method changes old value with a new one which is second argument. Why in this code checks if number is float. If I type float number in odd1 without replace, I am getting the message Sorry home tip is not numeric?

Body:
odd1.replace(".","") means that change every dot in the string odd1 into to nothing (means delete it) generally .replace() is used to search about a char in a string and replace it with another
for example

s = "Hello. world"

r = s.replace(".", ",")

print(r)

this code replace every dot in the string s with a comma

and then .isnumeric() tests if the value of odd1 after replacing is a number or not


问:
How to update the state with the latest fetched item with an interval callback function inside useEffect?
I'm quite new to the React-TS world and I have recently been playing with useState and useEffect hooks only basically.

I have the following functional component inside which I'd like to fetch N items the first time and then start a periodic function that fetches the last item from the response data, updating the current state.

const fetcher = async (url: string) => await axios.get(url).then((res: AxiosResponse) => res.data);

type AirflowData = {
  value: number; // perc values from 0 to 1
  timestamp: number; // UTC time
};

const ActionDetector: React.FC = () => {
  const [alerts, setAlerts] = useState<AirflowData[]>([]);

  useEffect(() => {
    // Fetch the latest N alerts first
    getAlerts(100);
    // Then start fetching the last alert every N milliseconds
    const interval = setInterval(() => getLatestAlert(), 1000);

    // Clear interval
    return () => {
      clearInterval(interval);
    };
  }, []);

  /**
   * Return the alert data after fetching it.
   * @param numAlerts number of the last N alerts to return
   */
  const getAlerts = async (numAlerts: number) => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    setAlerts(fetchedAlerts.slice(-numAlerts));
  };
  /**
   * Return the latest alert data available.
   */
  const getLatestAlert = async () => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
    const latestAlert = alerts.slice(-1)[0];

    if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
      // Append the alert only if different from the previous one
      setAlerts([...alerts, latestFetchedAlert]);
    }
  };

  console.log(alerts);

  return <></>
}

export default ActionDetector
```

The problem with this approach is that latestAlert is always undefined and that is due, if I understood how React works under the hood correctly, to the initial state change re-rendering trigger. After getAlerts() is called and fires setAlerts(...), the component starts the re-rendering and so, since getLatestAlert() is called inside the useEffect only the first time (the first render), it always read alerts as the initialized empty array.

I don't know if this is the correct reason behind this, but how can I achieve what I'm trying to do the right way?

答:
The fundamental issue is that when updating state based on existing state, you need to be sure you have the latest state information. Your getLatestAlerts function closes over the alerts constant that was in scope when it was created, so it only ever uses that version of the constant (not the updated one from a subsequent render). Your useEffect setInterval callback closes over the getLatestAlerts function that was in scope when it was created, and only ever uses that version of the function.

To be sure you have the latest state, use the callback version of the state setter instead of the constant:

```<code>const getLatestAlert = async () => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
    if (latestFetchedAlert) {
        setAlerts(alerts => {
            const latestAlert = alerts.slice(-1)[0];

            if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
                // Append the alert only if different from the previous one
                alerts = [...alerts, latestFetchedAlert];
            }
            return alerts;
        });
    }
};
</code>```

Purely as a side note, I wouldn't use the idiom you seem to be using to get the last item from an array, array.slice(-1)[0]. Instead, I'd either use array[array.length - 1], or use the at method which just achieved Stage 4 and will be in this year's spec (it's easily polyfilled for older environments).

Body:
I'm quite new to the React-TS world and I have recently been playing with useState and useEffect hooks only basically.

I have the following functional component inside which I'd like to fetch N items the first time and then start a periodic function that fetches the last item from the response data, updating the current state.

const fetcher = async (url: string) => await axios.get(url).then((res: AxiosResponse) => res.data);

type AirflowData = {
  value: number; // perc values from 0 to 1
  timestamp: number; // UTC time
};

const ActionDetector: React.FC = () => {
  const [alerts, setAlerts] = useState<AirflowData[]>([]);

  useEffect(() => {
    // Fetch the latest N alerts first
    getAlerts(100);
    // Then start fetching the last alert every N milliseconds
    const interval = setInterval(() => getLatestAlert(), 1000);

    // Clear interval
    return () => {
      clearInterval(interval);
    };
  }, []);

  /**
   * Return the alert data after fetching it.
   * @param numAlerts number of the last N alerts to return
   */
  const getAlerts = async (numAlerts: number) => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    setAlerts(fetchedAlerts.slice(-numAlerts));
  };
  /**
   * Return the latest alert data available.
   */
  const getLatestAlert = async () => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
    const latestAlert = alerts.slice(-1)[0];

    if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
      // Append the alert only if different from the previous one
      setAlerts([...alerts, latestFetchedAlert]);
    }
  };

  console.log(alerts);

  return <></>
}

export default ActionDetector

The problem with this approach is that latestAlert is always undefined and that is due, if I understood how React works under the hood correctly, to the initial state change re-rendering trigger. After getAlerts() is called and fires setAlerts(...), the component starts the re-rendering and so, since getLatestAlert() is called inside the useEffect only the first time (the first render), it always read alerts as the initialized empty array.

I don't know if this is the correct reason behind this, but how can I achieve what I'm trying to do the right way?

Body:
The fundamental issue is that when updating state based on existing state, you need to be sure you have the latest state information. Your getLatestAlerts function closes over the alerts constant that was in scope when it was created, so it only ever uses that version of the constant (not the updated one from a subsequent render). Your useEffect setInterval callback closes over the getLatestAlerts function that was in scope when it was created, and only ever uses that version of the function.

To be sure you have the latest state, use the callback version of the state setter instead of the constant:

const getLatestAlert = async () => {
    const fetchedAlerts: AirflowData[] = await fetcher("http://localhost:9500/alerts");
    const latestFetchedAlert = fetchedAlerts.slice(-1)[0];
    if (latestFetchedAlert) {
        setAlerts(alerts => {
            const latestAlert = alerts.slice(-1)[0];

            if (latestFetchedAlert && latestAlert && latestFetchedAlert.timestamp !== latestAlert.timestamp) {
                // Append the alert only if different from the previous one
                alerts = [...alerts, latestFetchedAlert];
            }
            return alerts;
        });
    }
};

Purely as a side note, I wouldn't use the idiom you seem to be using to get the last item from an array, array.slice(-1)[0]. Instead, I'd either use array[array.length - 1], or use the at method which just achieved Stage 4 and will be in this year's spec (it's easily polyfilled for older environments).


问:
make whole layout scrollable if it contains childlayout inside
I want to make my view scrollable, my view contains childs layouts inside linear layout.

My code is below; please make it scrollable, so that every content can be shown ...

```<code>    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#1A77BD">
    <RelativeLayout
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#FFFFFF">
        <TextView
            android:layout_marginTop="3dip"
            android:id="@+id/version"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="TYPE"
            android:layout_marginLeft="5dip"
            android:textColor="#000000" />
        <Spinner
            android:id="@+id/spinner1"
            android:layout_marginTop="0dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:id="@+id/update_me"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="DATE"
            android:layout_marginTop="80dip"
            android:layout_marginLeft="5dip"
            android:textColor="#000000" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="2dip"
            android:textColor="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="COUNTRY" />
        <Spinner
            android:id="@+id/spinner3"
            android:layout_marginTop="0dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="52dip"
            android:textColor="#000000"
            android:id="@+id/savecorp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="STATE" />
        <EditText
            android:id="@+id/spinner3"
            android:layout_marginTop="45dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="102dip"
            android:textColor="#000000"
            android:id="@+id/saveuserid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CITY" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="95dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="152dip"
            android:id="@+id/savepassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="VENDOR"
            android:textColor="#000000" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="140dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="15dip"
            android:textColor="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AMOUNT:" />
        <Spinner
            android:layout_marginLeft="200dip"
            android:id="@+id/spinner5"
            android:layout_marginTop="0dip"
            android:layout_width="100dip"
            android:layout_height="40dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="5dip"
            android:textColor="#000000"
            android:layout_width="fill_parent"
            android:layout_height="25dip"
            android:text="NOTES:" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="15dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <Button
            android:id="@+id/attachreciepts"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="5dip"
            android:layout_marginBottom="5dip"
            android:layout_marginRight="5dip"
            android:background="#000000"
            android:textColor="#FFFFFF"
            android:layout_width="fill_parent"
            android:layout_height="30dip"
            android:text="Attach Receipts" />
    </RelativeLayout>
    <Button
        android:id="@+id/attachreciepts"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:background="#000000"
        android:textColor="#FFFFFF"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:text="Attach Receipts" />
</LinearLayout>
</code>```

答:
Just wrap everything in a </p>

```<code><ScrollView android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
*your code*
</ScrollView>
</code>```

Body:
I want to make my view scrollable, my view contains childs layouts inside linear layout.

My code is below; please make it scrollable, so that every content can be shown ...

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#1A77BD">
    <RelativeLayout
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:background="#FFFFFF">
        <TextView
            android:layout_marginTop="3dip"
            android:id="@+id/version"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="TYPE"
            android:layout_marginLeft="5dip"
            android:textColor="#000000" />
        <Spinner
            android:id="@+id/spinner1"
            android:layout_marginTop="0dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:id="@+id/update_me"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="DATE"
            android:layout_marginTop="80dip"
            android:layout_marginLeft="5dip"
            android:textColor="#000000" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="2dip"
            android:textColor="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="COUNTRY" />
        <Spinner
            android:id="@+id/spinner3"
            android:layout_marginTop="0dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="52dip"
            android:textColor="#000000"
            android:id="@+id/savecorp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="STATE" />
        <EditText
            android:id="@+id/spinner3"
            android:layout_marginTop="45dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="102dip"
            android:textColor="#000000"
            android:id="@+id/saveuserid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="CITY" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="95dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
        <TextView
            android:layout_marginLeft="5dip"
            android:layout_marginTop="152dip"
            android:id="@+id/savepassword"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="VENDOR"
            android:textColor="#000000" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="140dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="15dip"
            android:textColor="#000000"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="AMOUNT:" />
        <Spinner
            android:layout_marginLeft="200dip"
            android:id="@+id/spinner5"
            android:layout_marginTop="0dip"
            android:layout_width="100dip"
            android:layout_height="40dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <TextView
            android:id="@+id/accsetting"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="5dip"
            android:textColor="#000000"
            android:layout_width="fill_parent"
            android:layout_height="25dip"
            android:text="NOTES:" />
        <EditText
            android:id="@+id/spinner4"
            android:layout_marginTop="15dip"
            android:layout_marginLeft="100dip"
            android:layout_height="40dip"
            android:layout_width="200dip" />
    </RelativeLayout>
    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="40dip"
        android:layout_marginTop="15dip"
        android:layout_marginLeft="8dip"
        android:layout_marginRight="8dip"
        android:background="#FFFFFF">
        <Button
            android:id="@+id/attachreciepts"
            android:layout_marginLeft="5dip"
            android:layout_marginTop="5dip"
            android:layout_marginBottom="5dip"
            android:layout_marginRight="5dip"
            android:background="#000000"
            android:textColor="#FFFFFF"
            android:layout_width="fill_parent"
            android:layout_height="30dip"
            android:text="Attach Receipts" />
    </RelativeLayout>
    <Button
        android:id="@+id/attachreciepts"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:background="#000000"
        android:textColor="#FFFFFF"
        android:layout_width="fill_parent"
        android:layout_height="30dip"
        android:text="Attach Receipts" />
</LinearLayout>

Body:
Just wrap everything in a

<ScrollView android:id="@+id/scrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
*your code*
</ScrollView>


问:
React Native Generating Signed APK "KeyStore file not set for signing config release"
I am trying to generate a signed APK. I have my password.keystore file located in \Dictionary\android\app and when i ran gradlew assembleRelease on cmd, the error:

Execution failed for task ':app:validateSigningRelease'.

Keystore file not set for signing config release

Where should I store my password.keystore file? Because when I commented off the if (project.hasProperty("password.keystore") { it seems to work but with the following error instead:

Unable to process incoming event 'ProgressComplete ' (ProgressCompleteEvent)

How should I write my if condition or where should I store the password.keystore file?

The source code is as follows:

```<code>signingConfigs {
  release {
    if (project.hasProperty("password.keystore")) {
      storeFile file("password.keystore")
      storePassword "password"
      keyAlias "username"
      keyPassword "password"
    }
  }
}
</code>```

答:
Try to do like this :</p>
```<code>           release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
            storeFile file('MYAPP_UPLOAD_STORE_FILE')
            storePassword 'MYAPP_UPLOAD_STORE_PASSWORD'
            keyAlias 'MYAPP_UPLOAD_KEY_ALIAS'
            keyPassword 'MYAPP_UPLOAD_KEY_PASSWORD'
        }
    }
</code>```

Body:
I am trying to generate a signed APK. I have my password.keystore file located in \Dictionary\android\app and when i ran gradlew assembleRelease on cmd, the error:

Execution failed for task ':app:validateSigningRelease'.

Keystore file not set for signing config release

Where should I store my password.keystore file? Because when I commented off the if (project.hasProperty("password.keystore") { it seems to work but with the following error instead:

Unable to process incoming event 'ProgressComplete ' (ProgressCompleteEvent)

How should I write my if condition or where should I store the password.keystore file?

The source code is as follows:

signingConfigs {
  release {
    if (project.hasProperty("password.keystore")) {
      storeFile file("password.keystore")
      storePassword "password"
      keyAlias "username"
      keyPassword "password"
    }
  }
}

Body:
Try to do like this :

           release {
            if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
            storeFile file('MYAPP_UPLOAD_STORE_FILE')
            storePassword 'MYAPP_UPLOAD_STORE_PASSWORD'
            keyAlias 'MYAPP_UPLOAD_KEY_ALIAS'
            keyPassword 'MYAPP_UPLOAD_KEY_PASSWORD'
        }
    }


问:
airflow DAG triggering for time consuming runs
I am completely new to Airflow and am trying to grasp the concepts of scheduling and default args.

I have a scenario where I would like to schedule my DAG hourly to do some data transfer task between a source and a database. What I am trying to understand is, lets say one of my DAG runs has triggered at 00:00 AM. Now if it takes more than an hour for this run to successfully complete all of its tasks (say 1 hour 30 min), does it mean that the next DAG run that was supposed to be triggered at 01:00 AM will NOT get triggered but the DAG run from 02:00 AM will get triggered?

答:
Yes.
In order to avoid, you need catchup=True for the DAG object.

Reference : https://airflow.apache.org/docs/apache-airflow/stable/dag-run.html

(Search for Catchup)


问:
INSERT INTO table from 2 unrelated tables
Not sure how to achieve the result, need your help

Source A:

```<code>SELECT SourceAID
FROM [dbo].[SourceA]
</code>```

Source B:

```<code>SELECT SourceBID
FROM [dbo].[SourceB]
</code>```

Result table (select example):

```<code>SELECT SourceAID
      ,SourceBID
      ,Value
  FROM [dbo].[Result]
</code>```

Idea of insert: For each SourceAID, i need to insert records with all SourceBID. There is no any reference between these 2 tables.

Idea by hand looks like this:

```<code> INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
  VALUES ('AID_1', 'BID_1', NULL),
('AID_1', 'BID_2', NULL),
('AID_1', 'BID_3', NULL),
('AID_2', 'BID_1', NULL),
('AID_2', 'BID_2', NULL),
('AID_2', 'BID_3', NULL)
</code>```

and so on

答:
As @Larnu said.

Use some following code:

```<code>INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
SELECT
    SA.SourceAID,
    SB.SourceBID,
    NULL
FROM
    [dbo].[SourceA] AS SA
    CROSS JOIN [dbo].[SourceB] AS SB
</code>```

Body:
Not sure how to achieve the result, need your help

Source A:

SELECT SourceAID
FROM [dbo].[SourceA]

Source B:

SELECT SourceBID
FROM [dbo].[SourceB]

Result table (select example):

SELECT SourceAID
      ,SourceBID
      ,Value
  FROM [dbo].[Result]

Idea of insert: For each SourceAID, i need to insert records with all SourceBID. There is no any reference between these 2 tables.

Idea by hand looks like this:

 INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
  VALUES ('AID_1', 'BID_1', NULL),
('AID_1', 'BID_2', NULL),
('AID_1', 'BID_3', NULL),
('AID_2', 'BID_1', NULL),
('AID_2', 'BID_2', NULL),
('AID_2', 'BID_3', NULL)

and so on

Body:
As @Larnu said.

Use some following code:

INSERT INTO [dbo].[Result] ([SourceAID], [SourceBID], [Value])
SELECT
    SA.SourceAID,
    SB.SourceBID,
    NULL
FROM
    [dbo].[SourceA] AS SA
    CROSS JOIN [dbo].[SourceB] AS SB


问:
How to Display Particulate range of image from list in CarouselSlider.builder in Flutter?
I want to display Images from list in CarouselSlider.builder from index 1 to 3.

Here as below I got all Data from Api in _imageList.

```<code>List<ImageModel> _imageList = [];

@override
  void initState() {
    super.initState();
    ApiHelper().getImageList().then((images) {
      setState(() {
        _imageList = images;
      });
    });
  }
</code>```

Here is my Image Slider Code as below.

```<code>CarouselSlider.builder(
                              itemCount: _imageList.length,
                              itemBuilder:
                                  (BuildContext context, int index, realindex) {
                                return Image.network(
                                  "$imageUrl" + _imageList[index].imgPath!,
                                  width: MediaQuery.of(context).size.width - 40,
                                  fit: BoxFit.fill,
                                );
                              },
                              options: CarouselOptions(
                                viewportFraction: 1,
                                enlargeCenterPage: true,
                                initialPage: 1,
                              ),
                            ),
</code>```

So how can i do this?
Thank you.

答:
in your initState method you can just create a sublist of the images list so your imageList only contains the indices 1-3.

_imageList = images.sublist(1, 4);
```

Body:
I want to display Images from list in CarouselSlider.builder from index 1 to 3.

Here as below I got all Data from Api in _imageList.

List<ImageModel> _imageList = [];

@override
  void initState() {
    super.initState();
    ApiHelper().getImageList().then((images) {
      setState(() {
        _imageList = images;
      });
    });
  }

Here is my Image Slider Code as below.

CarouselSlider.builder(
                              itemCount: _imageList.length,
                              itemBuilder:
                                  (BuildContext context, int index, realindex) {
                                return Image.network(
                                  "$imageUrl" + _imageList[index].imgPath!,
                                  width: MediaQuery.of(context).size.width - 40,
                                  fit: BoxFit.fill,
                                );
                              },
                              options: CarouselOptions(
                                viewportFraction: 1,
                                enlargeCenterPage: true,
                                initialPage: 1,
                              ),
                            ),

So how can i do this?
Thank you.


问:
How to use select statement in join condition in Impala sql
I am learning Impala sql and need to convert a sql query into impala equivalent which is something like this:

```<code>select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2
       on t2.c1=t1.c1 and (t2.c2 is null
                           or t2.c2 in (select c1 from table3
                                                 where 'some conditions')
                          )
</code>```

When I am executing this query in impala I am getting error as "Could not resolve table reference table3". Although this table3 is present in the database which I am using.

Can anyone please guide what is happening and why am I getting this table not found error.

Also please suggest how to implement this sql code into Impala equivalent.

答:
It does not support queries in ON join condition, rewrite query like this:</p>
```<code>select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2 on t2.c1=t1.c1
       left join (--prevent unintended duplication by join if c1 is not unique
                  select distinct c1 from
                  table3 where 'some conditions') t3 on t2.c2=c3.c1
 where t2.c2 is null --not joined with c3 because of null
    or t3.c1 is not null --or joined with c3
</code>```

Body:
I am learning Impala sql and need to convert a sql query into impala equivalent which is something like this:

select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2
       on t2.c1=t1.c1 and (t2.c2 is null
                           or t2.c2 in (select c1 from table3
                                                 where 'some conditions')
                          )

When I am executing this query in impala I am getting error as "Could not resolve table reference table3". Although this table3 is present in the database which I am using.

Can anyone please guide what is happening and why am I getting this table not found error.

Also please suggest how to implement this sql code into Impala equivalent.

Body:
It does not support queries in ON join condition, rewrite query like this:

select distinct t1.c1, t1.c2
  from table1 t1
       join table2 t2 on t2.c1=t1.c1
       left join (--prevent unintended duplication by join if c1 is not unique
                  select distinct c1 from
                  table3 where 'some conditions') t3 on t2.c2=c3.c1
 where t2.c2 is null --not joined with c3 because of null
    or t3.c1 is not null --or joined with c3


问:
How to insert huge html content into Oracle table
I have following huge HTML string and I need to insert it into Oracle table. What is the most suitable data type to store those data? I searched on google and found some source, Clob is most suitable for that. is it correct? If Clob but How can I insert following data into Clob column?

```<code><!DOCTYPE html><html><head><style></style> </head><body><div style="display: flex; justify-content:center;"> <div style="padding: 0.75em; z-index: -1; background: rgb(79,206,213); background: linear-gradient(180deg, rgba(79,206,213,.1) 0%, rgba(20,173,227,.1) 50%, rgba(253,0,243,.1) 100%);"> <div style="border-radius: 1em; padding: 3em 1em 1em 1em; z-index: 0; background: white;"> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><img width="109" src="" alt="image"></p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'> </p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'>Transaction Summary</p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="font-size:12px;line-height:107%;color:#AFABAB;">Amount</span></p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="font-size:11px;line-height:107%;color:#AFABAB;">LKR </span><strong><span style="font-size:16px;line-height:107%;color:#0070C0;">2,000.00</span></strong></p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="font-size:12px;line-height:107%;">Commercial Bank</span></p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="font-size:12px;line-height:107%;"> </span></p> <ul style="display: flex;flex-direction:column;list-style:none;width:319.5pt;row-gap: .5em;margin-bottom: 2em; padding: 0 2em; font-family:'Calibri',sans-serif;"> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Payment type</span> <span style="color:blackt;text-align:right;">Card</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Paid to</span> <span style="color:blackt;text-align:right;">12345678</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Bank</span> <span style="color:blackt;text-align:right;">BTC</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Date of time</span> <span style="color:blackt;text-align:right;">16-Aug-2021 11:50</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Payment Status</span> <span style="color:blackt;text-align:right;">Success</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Reference number</span> <span style="color:blackt;text-align:right;">3243322</span> </li> <li style="border:1px solid #e3e3e3;padding: .4em; border-radius: .5em; display:grid; grid-template-columns: 1fr 1fr;align-items:center;"> <span style="color:grey;">Remark</span> <span style="color:blackt;text-align:right;">Monthly bonus</span> </li> </ul> <p style='border-top:1px solid #e3e3e3; margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="color:#2E75B6;"> </span></p> <p style='margin-top:0in;margin-right:0in;margin-bottom:8.0pt;margin-left:0in;line-height:107%;font-size:15px;font-family:"Calibri",sans-serif;text-align:center;'><span style="color:#2E75B6;">Aug-2021 12:56 PM</span></p> </div> </div> </div></body></html>
</code>```

答:
You can try,  divide html string with less than 4000 chars and concatenate them with || and use the to_clob method

```<code>update YOURTABLENAME set YOURCOLUMN = to_clob('HTML string with less than 4000 chars')
             || to_clob('HTML string with less than 4000')
</code>```

Body:
I have following huge HTML string and I need to insert it into Oracle table. What is the most suitable data type to store those data? I searched on google and found some source, Clob is most suitable for that. is it correct? If Clob but How can I insert following data into Clob column?

<!DOCTYPE html>

Transaction Summary

Amount

LKR 2,000.00

Commercial Bank

 Payment type Card

 Paid to 12345678

 Bank BTC

 Date of time 16-Aug-2021 11:50

 Payment Status Success

 Reference number 3243322

 Remark Monthly bonus

Aug-2021 12:56 PM

Body:
You can try,  divide html string with less than 4000 chars and concatenate them with || and use the to_clob method

update YOURTABLENAME set YOURCOLUMN = to_clob('HTML string with less than 4000 chars')
             || to_clob('HTML string with less than 4000')


问:
Can I send an alert when a message is published to a pubsub topic?
We are using pubsub & a cloud function to process a stream of incoming data. I am setting up a dead letter topic to handle cases where a message cannot be processed, as described at Cloud Pub/Sub > Guides > Handling message failures.

I've configured a subscription on the dead-letter topic to retain messages for 7 days, we're doing this using terraform:

resource "google_pubsub_subscription" "dead_letter_monitoring" {
  project = var.project_id
  name    = "var.dead_letter_sub_name
  topic   = google_pubsub_topic.dead_letter.name
  expiration_policy { ttl = "" }

  message_retention_duration = "604800s" # 7 days
  retain_acked_messages      = true

  ack_deadline_seconds = 600
}
```

We've tested our cloud function robustly and consequently our expectation is that messages will appear on this dead-letter topic very very rarely, perhaps never. Nevertheless we're putting it in place just to make sure that we catch any anomalies.

Given the rarity of which we expect messages to appear on the dead-letter-topic we need to set up an alert to send an email when such a message appears. Is it possible to do this? I've taken a look through the alerts one can create at https://console.cloud.google.com/monitoring/alerting/policies/create however I didn't see anything that could accomplish this.

I know that I could write a cloud function to consume a message from the subscription and act upon it accordingly however I'd rather not have to do that, a monitoring alert feels like a much more elegant way of achieving this.

is this possible?

答:
Yes, you can use Cloud Monitoring for that. Create a new policy and perform that configuration

Select PubSub Topic and Published message. Observe the value every minute and count them (aligner in the advanced option). Now, in the config, when it's above 0 from the most recent value, the alert is raised.

To filter on only your topic you can add a filter by topic_id on your topic name.

Then, configure your alert to send an email. It should work!

Body:
We are using pubsub & a cloud function to process a stream of incoming data. I am setting up a dead letter topic to handle cases where a message cannot be processed, as described at Cloud Pub/Sub > Guides > Handling message failures.

I've configured a subscription on the dead-letter topic to retain messages for 7 days, we're doing this using terraform:

resource "google_pubsub_subscription" "dead_letter_monitoring" {
  project = var.project_id
  name    = "var.dead_letter_sub_name
  topic   = google_pubsub_topic.dead_letter.name
  expiration_policy { ttl = "" }

  message_retention_duration = "604800s" # 7 days
  retain_acked_messages      = true

  ack_deadline_seconds = 600
}

We've tested our cloud function robustly and consequently our expectation is that messages will appear on this dead-letter topic very very rarely, perhaps never. Nevertheless we're putting it in place just to make sure that we catch any anomalies.

Given the rarity of which we expect messages to appear on the dead-letter-topic we need to set up an alert to send an email when such a message appears. Is it possible to do this? I've taken a look through the alerts one can create at https://console.cloud.google.com/monitoring/alerting/policies/create however I didn't see anything that could accomplish this.

I know that I could write a cloud function to consume a message from the subscription and act upon it accordingly however I'd rather not have to do that, a monitoring alert feels like a much more elegant way of achieving this.

is this possible?


问:
Making a discord bot move a member to the afk channel once they deafen
ok so basically I want to make a bot to move a user to afk as soon as they deafen, I know very little about coding and wanted some help.

all I really want is for it to do is to scan all voice channels and move any deafened user it sees to the afk channel

here is the code i have:

```<code>     channel = self.bot.get_channel(800674042247118878)
     if after.deaf and after.channel:
        await member.move_to(.afkChannelId);
</code>```

again I have absolutely no clue how to code and am basically just using what I could find

ty for the help <3

答:
You should check VOICE_STATE_UPDATE. This event is raised when a user's voice state changes. This includes when a user joins, leaves, or moves between voice channels, as well as their mute and deaf status for themselves and on the server.</p>
```<code>@bot.event
async def on_voice_state_update(member, before, after):
    if member.VoiceState.self_deaf:
         await member.move_to(afkchannel)
</code>```

Body:
ok so basically I want to make a bot to move a user to afk as soon as they deafen, I know very little about coding and wanted some help.

all I really want is for it to do is to scan all voice channels and move any deafened user it sees to the afk channel

here is the code i have:

     channel = self.bot.get_channel(800674042247118878)
     if after.deaf and after.channel:
        await member.move_to(.afkChannelId);

again I have absolutely no clue how to code and am basically just using what I could find

ty for the help <3

Body:
You should check VOICE_STATE_UPDATE. This event is raised when a user's voice state changes. This includes when a user joins, leaves, or moves between voice channels, as well as their mute and deaf status for themselves and on the server.

@bot.event
async def on_voice_state_update(member, before, after):
    if member.VoiceState.self_deaf:
         await member.move_to(afkchannel)


问:
Why ListView Items becomes not clickable after scroll
I created a custom ListView with ImageView and TextViews and every thing worked fine until i tried to implement onItemClick, which for the time being only shows a Toast.

The problem occurs when i scroll down my ListView: it won't receive any clicks.

Funny thing is that when i use the keyboard to move from item to item it works and when i hit enter the Toast is shown

This is the code i used for onItemClick listener.

```<code>@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    RestaurantReservationBean clickedItem = resultArray.get(position);

    Toast.makeText(this, clickedItem.getName()+", "+clickedItem.getCost(), 1000).show();
}
</code>```

答:
i think i solved this problem: after going through some documentation i figured out that this problem comes from the textviews and imagesview on top of each row which block the onitemselected listener. so i tryed to refresh the list view after scroll and it worked just fine. here's what i did hoping it 'll help those who may come accross this problem</p>

```<code>listView.setOnScrollListener(new OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE )
            {
              listView.invalidateViews();
            }

        }

        @Override
        public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {}
    });
</code>```

Body:
I created a custom ListView with ImageView and TextViews and every thing worked fine until i tried to implement onItemClick, which for the time being only shows a Toast.

The problem occurs when i scroll down my ListView: it won't receive any clicks.

Funny thing is that when i use the keyboard to move from item to item it works and when i hit enter the Toast is shown

This is the code i used for onItemClick listener.

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    RestaurantReservationBean clickedItem = resultArray.get(position);

    Toast.makeText(this, clickedItem.getName()+", "+clickedItem.getCost(), 1000).show();
}

Body:
i think i solved this problem: after going through some documentation i figured out that this problem comes from the textviews and imagesview on top of each row which block the onitemselected listener. so i tryed to refresh the list view after scroll and it worked just fine. here's what i did hoping it 'll help those who may come accross this problem

listView.setOnScrollListener(new OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            if ( scrollState == OnScrollListener.SCROLL_STATE_IDLE )
            {
              listView.invalidateViews();
            }

        }

        @Override
        public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {}
    });


问:
Django CSRF validation fails on POST requests : referer checking failed - no Referer
My Django website is in HTTPS. When I am trying to POST data to the website from a script I get this error : "referer checking failed - no Referer". It seems to be a CSRF issue but I do not know how to solve it.

Example :

```<code>import requests
r = requests.post('https://mywebsite/mypage', data = {'key':'value'})
print r.text
</code>```

gives me this output :

```<code>[...]

<p>Reason given for failure:</p>
```
Referer checking failed - no Referer.
```

<p>In general, this can occur when there is a genuine Cross Site Request Forgery, or when
<a
href="https://docs.djangoproject.com/en/1.8/ref/csrf/">Django's
CSRF mechanism</a> has not been used correctly.  For POST forms, you need to
ensure:</p>

<ul>
<li>Your browser is accepting cookies.</li>

<li>The view function passes a <code>request</code> to the template's <a
href="https://docs.djangoproject.com/en/dev/topics/templates/#django.template.backends.base.Template.render"><code>render</code></a>
method.</li>

<li>In the template, there is a <code>{% csrf_token
%}</code> template tag inside each POST form that
targets an internal URL.</li>

<li>If you are not using <code>CsrfViewMiddleware</code>, then you must use
<code>csrf_protect</code> on any views that use the <code>csrf_token</code>
template tag, as well as those that accept the POST data.</li>

</ul>

[...]
</code>```

Do I need to pass a referer to my headers before sending the POST data - which would not be convenient ? Or should I disable CSRF for this page ?

Thanks

答:
Upgrading Django might fix the missing Referer error.

As of Django 4.0 (release notes), the backend will first check the Origin header before falling back to the Referer header (source):

CsrfViewMiddleware verifies the Origin header, if provided by the browser, against the current host and the CSRF_TRUSTED_ORIGINS setting. This provides protection against cross-subdomain attacks.

In addition, for HTTPS requests, if the Origin header isn’t provided, CsrfViewMiddleware performs strict referer checking. This means that even if a subdomain can set or modify cookies on your domain, it can’t force a user to post to your application since that request won’t come from your own exact domain.

Body:
My Django website is in HTTPS. When I am trying to POST data to the website from a script I get this error : "referer checking failed - no Referer". It seems to be a CSRF issue but I do not know how to solve it.

Example :

import requests
r = requests.post('https://mywebsite/mypage', data = {'key':'value'})
print r.text

gives me this output :

[...]

Reason given for failure:

Referer checking failed - no Referer.

In general, this can occur when there is a genuine Cross Site Request Forgery, or when
Django's
CSRF mechanism has not been used correctly.  For POST forms, you need to
ensure:

Your browser is accepting cookies.

The view function passes a request to the template's render
method.

In the template, there is a {% csrf_token
%} template tag inside each POST form that
targets an internal URL.

If you are not using CsrfViewMiddleware, then you must use
csrf_protect on any views that use the csrf_token
template tag, as well as those that accept the POST data.

[...]

Do I need to pass a referer to my headers before sending the POST data - which would not be convenient ? Or should I disable CSRF for this page ?

Thanks


问:
What is the best way of updating data in SpringBoot?
For put request, Do I always have to check the old data and change the changed fields in order to update the existing data? Is it the right way to check for each data change?</p>

答:
I do not know of any project which takes the effort to only update fields that were actually changed.

Usually what you'd do is that you just override all fields in your table with the new value as this is the easiest and most reliable way of doing so.
Also consider, that custom logic that decides what to update also needs to be maintained and can have bugs. If you end up having a bug in that logic, most likely, you'll realize that you have data consistency errors which might be unfixable.

Most likely, when you use Spring Boot, you would probably also use Spring Data JPA and Hibernate which are going to take care of mapping your objects to your database. In that case, Hibernate is going to decide on the update strategy you use anyways.

If you are worried about data consistency and concurrent updates to the same record, I would recommend looking into Optimistic Locking, which is an easy way to handle that issue. It's very easy to setup by just adding a version column to your table.


问:
REST Complex/Composite/Nested Resources
I'm trying to wrap my head around the best way to address concepts in a REST based API. Flat resources that don't contain other resources are no problem. Where I'm running into trouble are the complex resources.

For instance, I have a resource for a comic book. ComicBook has all sorts of properties on it like author, issue number, date, etc.

A comic book also has a list of 1..n covers. These covers are complex objects. They contain a lot of information about the cover: the artist, a date, and even a base 64 encoded image of the cover.

For a GET on ComicBook I could just return the comic, and all of the covers including their base64'ed images. That's probably not a big deal for getting a single comic. But suppose I am building a client app that wants to list all of the comics in the system in a table.

The table will contain a few properties from the ComicBook resource, but we're certainly not going to want to display all the covers in the table. Returning 1000 comic books, each with multiple covers would result in a ridiculously large amount of data coming across the wire, data that isn't necessary to the end user in that case.

My instinct is to make Cover a resource and have ComicBook contain covers. So now Cover is a URI. GET on comic book works now, instead of the huge Cover resource we send back a URI for each cover and clients can retrieve the Cover resources as they require them.

Now I have a problem with creating new comics. Surely I'm going to want to create at least one cover when I create a Comic, in fact that's probably a business rule.

So now I'm stuck, I either force the clients to enforce business rules by first submitting a Cover, getting the URI for that cover, then POSTing a ComicBook with that URI in the list, or my POST on ComicBook takes in a different looking resource than it spits out. The incoming resources for POST and GET are deep copies, where the outgoing GETs contain references to dependent resources.

The Cover resource is probably necessary in any case because I'm sure as a client I'd want to address covers direction in some cases. So the problem exists in a general form regardless of the size of the dependent resource. In general how do you handle complex resources without forcing the client to just "know" how those resources are composed?

答:
Treating covers as resources is definitely in the spirit of REST, particularly HATEOAS.  So yes, a GET request to http://example.com/comic-books/1 would give you a representation of book 1, with properties including a set of URIs for covers. So far so good.

Your question is how to deal with comic book creation.  If your business rule was that a book would have 0 or more covers, then you have no problem:

```<code>POST http://example.com/comic-books
</code>```

with coverless comic book data will create a new comic book and return the server generated id (lets say it comes back as 8), and now you can add covers to it like so:

```<code>POST http://example.com/comic-books/8/covers
</code>```

with the cover in the entity body.

Now you have a good question which is what happens if your business rule says there always must be at least one cover.  Here are some choices, the first of which you identified in your question:

Force the creation of a cover first, now essentially making cover a non-dependent resource, or you place the initial cover in the entity body of the POST that creates the comic book. This as you say means that the representation you POST to create will differ from the representation you GET.

Define the notion of a primary, or initial, or preferred, or otherwise-designated cover.  This is likely a modeling hack, and if you did that it would be like tweaking your object model (your conceptual or business model) in order to fit a technology.  Not a great idea.

You should weigh these two choices against simply allowing coverless comics.

Which of the three choices should you take?  Not knowing too much about your situation, but answer the general 1..N dependent resource question, I would say:

If you can go with 0..N for your RESTful service layer, great.  Perhaps a layer between your RESTful SOA can handle the further business constraint if at least one is required.  (Not sure how that would look but it might be worth exploring.... end users don't usually see the SOA anyway.)

If you simply must model a 1..N constraint, then ask yourself whether covers might just be sharable resources, in other words, they might exist on things other than comic books.  Now they are not dependent resources and you can create them first and supply URIs in your POST that creates comic books.

If you need 1..N and covers remain dependent, simply relax your instinct to keep the representations in POST and GET the same, or make them the same.

The last item is explained like so:

```<code><comic-book>
  <name>...</name>
  <edition>...</edition>
  <cover-image>...BASE64...</cover-image>
  <cover-image>...BASE64...</cover-image>
  <cover>...URI...</cover>
  <cover>...URI...</cover>
</comic-book>
</code>```

When you POST you allow existing uris if you have them (borrowed from other books) but also put in one or more initial images.  If you are creating a book and your entity has no initial cover-image, return a 409 or similar response.  On GET you can return URIs..

So basically you're allowing the POST and GET representations to "be the same" but you just choose not to "use" cover-image on GET nor cover on POST.  Hope that makes sense.

Title: REST Complex/Composite/Nested Resources

Body:
Treating covers as resources is definitely in the spirit of REST, particularly HATEOAS.  So yes, a GET request to http://example.com/comic-books/1 would give you a representation of book 1, with properties including a set of URIs for covers. So far so good.

Your question is how to deal with comic book creation.  If your business rule was that a book would have 0 or more covers, then you have no problem:

POST http://example.com/comic-books

with coverless comic book data will create a new comic book and return the server generated id (lets say it comes back as 8), and now you can add covers to it like so:

POST http://example.com/comic-books/8/covers

with the cover in the entity body.

Now you have a good question which is what happens if your business rule says there always must be at least one cover.  Here are some choices, the first of which you identified in your question:

Force the creation of a cover first, now essentially making cover a non-dependent resource, or you place the initial cover in the entity body of the POST that creates the comic book. This as you say means that the representation you POST to create will differ from the representation you GET.

Define the notion of a primary, or initial, or preferred, or otherwise-designated cover.  This is likely a modeling hack, and if you did that it would be like tweaking your object model (your conceptual or business model) in order to fit a technology.  Not a great idea.

You should weigh these two choices against simply allowing coverless comics.

Which of the three choices should you take?  Not knowing too much about your situation, but answer the general 1..N dependent resource question, I would say:

If you can go with 0..N for your RESTful service layer, great.  Perhaps a layer between your RESTful SOA can handle the further business constraint if at least one is required.  (Not sure how that would look but it might be worth exploring.... end users don't usually see the SOA anyway.)

If you simply must model a 1..N constraint, then ask yourself whether covers might just be sharable resources, in other words, they might exist on things other than comic books.  Now they are not dependent resources and you can create them first and supply URIs in your POST that creates comic books.

If you need 1..N and covers remain dependent, simply relax your instinct to keep the representations in POST and GET the same, or make them the same.

The last item is explained like so:

<comic-book>
  <name>...</name>
  <edition>...</edition>
  <cover-image>...BASE64...</cover-image>
  <cover-image>...BASE64...</cover-image>
  <cover>...URI...</cover>
  <cover>...URI...</cover>
</comic-book>

When you POST you allow existing uris if you have them (borrowed from other books) but also put in one or more initial images.  If you are creating a book and your entity has no initial cover-image, return a 409 or similar response.  On GET you can return URIs..

So basically you're allowing the POST and GET representations to "be the same" but you just choose not to "use" cover-image on GET nor cover on POST.  Hope that makes sense.


问:
Tutorial teaching Ruby syntax/knowledge required to easily learn rails
I am trying to learn ROR these days and have basic knowledge of ruby, but often working with rails, I get to the point where it seems as if I don't know a bit about ruby.

Just to explain the point, in rails we use has_many keyword. I did not learn any such thing when I was going through ruby tutorials but just came to know that it has something to do with meta-programming in ruby (I have no idea what is meta programming).

So I would like to know if there is any book/tutorial which explain all the points/syntax/concepts of ruby, which a newbie would see while programming in rails.

Thanks to "Jonas Elfström", in simple words, what I am looking for is to know "how Rails uses Ruby"

Thanks.

答: I tried lately this: http://pine.fm/LearnToProgram/ which helped me a lot because there are one or two concepts that had slipped. I started long ago with an arcane version of this.</p>


问:
ERROR: Step ‘Publish JUnit test result report’ failed: No test report files were found. Configuration error?
I am setting up an Android project from git in Jenkins, I am getting below error :

Recording test results ERROR: Step ‘Publish JUnit test result report’
  failed: No test report files were found. Configuration error?
  Finished: FAILURE

My project have 59 testcases i want to get the test report execution result to be created when Jenkins job is executed.

I have set up the publish JUnit test result report in the POST Build Actions.

答: junit search files only in current workspace and not from file system root</p>


问:
React Native Firebase onAuthStateChanged returns user after signOut
I'm struggling with signing out in my app. I'm using freshly installed managed Expo app with dev-client and @react-natice-firebase/auth, all in their current version. For the user state i'm using Recoil. Sign in works just fine, the problem occurs when signing out. Here is my AuthProvider.ts

```<code>import React, { FC, Fragment, useEffect } from 'react';

import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
import { useSetRecoilState } from 'recoil';

import { firebaseUser } from '../../../state/user/atoms/firebaseUser';

export const AuthProvider: FC = ({ children }) => {
  const setUser = useSetRecoilState(firebaseUser);
  const onAuthStateChanged = (user: FirebaseAuthTypes.User | null) => setUser(user);

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);

    return subscriber;
  }, []);

  return <Fragment children={children} />;
};
</code>```

And the function I use to sign out:

```<code>const logout = () => async () => await auth().signOut()

<MainButton action={logout()} label={'Logout'} />
</code>```

After sign in the onAuthStateChanged listener returns user object, but after hitting 'Logout' button it returns the user object again instead of null and the interface doesn't update. After hitting it again, console returns an error:

[Unhandled promise rejection: Error: [auth/no-current-user] No user currently signed in.]

onAuthStateChanged is not called again, user state persists and the interface doesn't update.

User state is cleared after restarting the app and the sign in works just fine again. The behaviour is similar when switching users (eg. from anonymous to signed in).

答:
In your useEffect, you need to actually call the 'unsubscribe' function provided by useAuthStateChanged.</p>
```<code>useEffect(() => {
    const unsubscribe = auth().onAuthStateChanged(onAuthStateChanged);

    return () => unsubscribe();
}, []);
</code>```

Body:
I'm struggling with signing out in my app. I'm using freshly installed managed Expo app with dev-client and @react-natice-firebase/auth, all in their current version. For the user state i'm using Recoil. Sign in works just fine, the problem occurs when signing out. Here is my AuthProvider.ts

import React, { FC, Fragment, useEffect } from 'react';

import auth, { FirebaseAuthTypes } from '@react-native-firebase/auth';
import { useSetRecoilState } from 'recoil';

import { firebaseUser } from '../../../state/user/atoms/firebaseUser';

export const AuthProvider: FC = ({ children }) => {
  const setUser = useSetRecoilState(firebaseUser);
  const onAuthStateChanged = (user: FirebaseAuthTypes.User | null) => setUser(user);

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);

    return subscriber;
  }, []);

  return <Fragment children={children} />;
};

And the function I use to sign out:

const logout = () => async () => await auth().signOut()

<MainButton action={logout()} label={'Logout'} />

After sign in the onAuthStateChanged listener returns user object, but after hitting 'Logout' button it returns the user object again instead of null and the interface doesn't update. After hitting it again, console returns an error:

[Unhandled promise rejection: Error: [auth/no-current-user] No user currently signed in.]

onAuthStateChanged is not called again, user state persists and the interface doesn't update.

User state is cleared after restarting the app and the sign in works just fine again. The behaviour is similar when switching users (eg. from anonymous to signed in).

Body:
In your useEffect, you need to actually call the 'unsubscribe' function provided by useAuthStateChanged.

useEffect(() => {
    const unsubscribe = auth().onAuthStateChanged(onAuthStateChanged);

    return () => unsubscribe();
}, []);


问:
Problem with flex-box vertical align middle (align-items: center)
I'd like the navigation arrows to align vertically middle.

On the live site they are off-center.

There is compromising CSS I can't change which sets a top: 40% for the arrows (.owl-nav button).

I've tried unseting their top, but this pushes them to underneath the image.

I've tried setting top: calc(50% - 37.5px); (minus half the button's height of 75px) but this is off-center. Is my math right here?

I've been able to get it working below by using a fixed height for .owl-nav.pp-carousel-nav but on the live page the .owl-items are not of fixed width and height, they are responsive.

.owl-carousel .owl-stage {
  position: relative;
}
.pp-content-post-carousel {
  position: relative;
}
.landscape-carousel-container {
  width: 100%;
}
.landscape-carousel-content {
  width: 100%;
}
.landscape-carousel-overlay {
  position: absolute;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  width: 100%;
  height: 236px;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  opacity: 0;
  transition: .4s ease !important;
  border-radius: 15px;
  background-color: #22a1d9;
}
.landscape-carousel-img {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  height: 236px;
  margin-bottom: 10px;
  padding-bottom: 0px;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  background-color: rgba(14,34,129,0);
  background-image: url("https://cdn-ehbod.nitrocdn.com/MnwLQZiWrxfKgQoPapfeSJHycGHMrPjW/assets/static/optimized/rev-315e7f6/img/background-image.svg");
  background-position: 50% 50%;
  background-size: cover;
  background-repeat: no-repeat;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
  cursor: pointer;
  border-radius: 15px;
  border: 3px solid #dfefef;
}
.owl-nav.pp-carousel-nav {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  height: 242px;
  width: 370px;
  position: absolute;
  top: 10px;
}
.owl-nav button {
  position: absolute;
  line-height: 1;
  margin: 0;
  font-size: 20px;
  background: none !important;
  z-index: 1;
  border: none;
  background-color: transparent;
}
.owl-nav button.owl-prev {
  left: -15px;
}
.owl-nav button.owl-next {
  right: -15px;
}
.owl-nav button svg {
  width: 51px;
  height: 51px;
  color: white;
  padding-top: 10px;
  padding-right: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
}
.sr-only {display: none;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="owl-item cloned" style="width: 370px;">
  <div class="pp-content-post pp-content-carousel-post pp-grid-custom post-6474 templates type-templates status-publish hentry templatecategory-hospitality templatecategory-landscape-liquor-hospitality-2 templatecategory-liquor" itemscope="" itemtype="https://schema.org/CreativeWork" data-id="6474" style="visibility: visible; height: 269.2px;">
    <div class="landscape-carousel-container">
      <div class="landscape-carousel-content">
        <div class="landscape-carousel-overlay">
          Edit this Template         </div>
        <div style="background-image: url("https://cdn-ehbod.nitrocdn.com/MnwLQZiWrxfKgQoPapfeSJHycGHMrPjW/assets/static/optimized/rev-315e7f6/wp-content/uploads/2021/06/landscape_Hospitality_Liquor_001.jpg");" class="landscape-carousel-img lazyloaded" nitro-lazy-bg="https://cdn-ehbod.nitrocdn.com/MnwLQZiWrxfKgQoPapfeSJHycGHMrPjW/assets/static/optimized/rev-315e7f6/wp-content/uploads/2021/06/landscape_Hospitality_Liquor_001.jpg"></div>
        <div>Liquor Store - Many Bottles</div>
      </div>
    </div>
  </div>
</div>
<div class="owl-nav pp-carousel-nav">
  <button type="button" role="presentation" class="owl-prev">
    <svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512">
      <path fill="currentColor" d="M25.1 247.5l117.8-116c4.7-4.7 12.3-4.7 17 0l7.1 7.1c4.7 4.7 4.7 12.3 0 17L64.7 256l102.2 100.4c4.7 4.7 4.7 12.3 0 17l-7.1 7.1c-4.7 4.7-12.3 4.7-17 0L25 264.5c-4.6-4.7-4.6-12.3.1-17z" class=""></path>
    </svg>
    <span class="sr-only">Previous</span>
  </button>
  <button type="button" role="presentation" class="owl-next">
    <svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512">
      <path fill="currentColor" d="M166.9 264.5l-117.8 116c-4.7 4.7-12.3 4.7-17 0l-7.1-7.1c-4.7-4.7-4.7-12.3 0-17L127.3 256 25.1 155.6c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0l117.8 116c4.6 4.7 4.6 12.3-.1 17z" class=""></path>
    </svg>
    <span class="sr-only">Next</span>
  </button>
</div></code>```

答:
Here the answer as stated in the comment:

The problem is caused by the navigation elements parent box. It also includes the text below - therefore, you don't center it relative to the image, but to the image & its descriptive text. As you probably cannot change the html structure here I suggest you simply change the css calculation by to something like

top: calc(50% - 45px);
```

Body:
I'd like the navigation arrows to align vertically middle.

On the live site they are off-center.

There is compromising CSS I can't change which sets a top: 40% for the arrows (.owl-nav button).

I've tried unseting their top, but this pushes them to underneath the image.

I've tried setting top: calc(50% - 37.5px); (minus half the button's height of 75px) but this is off-center. Is my math right here?

I've been able to get it working below by using a fixed height for .owl-nav.pp-carousel-nav but on the live page the .owl-items are not of fixed width and height, they are responsive.

.owl-carousel .owl-stage {
  position: relative;
}
.pp-content-post-carousel {
  position: relative;
}
.landscape-carousel-container {
  width: 100%;
}
.landscape-carousel-content {
  width: 100%;
}
.landscape-carousel-overlay {
  position: absolute;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  width: 100%;
  height: 236px;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  opacity: 0;
  transition: .4s ease !important;
  border-radius: 15px;
  background-color: #22a1d9;
}
.landscape-carousel-img {
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  height: 236px;
  margin-bottom: 10px;
  padding-bottom: 0px;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  background-color: rgba(14,34,129,0);
  background-image: url("https://cdn-ehbod.nitrocdn.com/MnwLQZiWrxfKgQoPapfeSJHycGHMrPjW/assets/static/optimized/rev-315e7f6/img/background-image.svg");
  background-position: 50% 50%;
  background-size: cover;
  background-repeat: no-repeat;
  -webkit-transition: all 200ms ease;
  transition: all 200ms ease;
  cursor: pointer;
  border-radius: 15px;
  border: 3px solid #dfefef;
}
.owl-nav.pp-carousel-nav {
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  height: 242px;
  width: 370px;
  position: absolute;
  top: 10px;
}
.owl-nav button {
  position: absolute;
  line-height: 1;
  margin: 0;
  font-size: 20px;
  background: none !important;
  z-index: 1;
  border: none;
  background-color: transparent;
}
.owl-nav button.owl-prev {
  left: -15px;
}
.owl-nav button.owl-next {
  right: -15px;
}
.owl-nav button svg {
  width: 51px;
  height: 51px;
  color: white;
  padding-top: 10px;
  padding-right: 10px;
  padding-bottom: 10px;
  padding-left: 10px;
}
.sr-only {display: none;}

          Edit this Template

Liquor Store - Many Bottles

  <button type="button" role="presentation" class="owl-prev">
    <svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512">
      <path fill="currentColor" d="M25.1 247.5l117.8-116c4.7-4.7 12.3-4.7 17 0l7.1 7.1c4.7 4.7 4.7 12.3 0 17L64.7 256l102.2 100.4c4.7 4.7 4.7 12.3 0 17l-7.1 7.1c-4.7 4.7-12.3 4.7-17 0L25 264.5c-4.6-4.7-4.6-12.3.1-17z" class=""></path>
    </svg>
    Previous
  </button>
  <button type="button" role="presentation" class="owl-next">
    <svg aria-hidden="true" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 192 512">
      <path fill="currentColor" d="M166.9 264.5l-117.8 116c-4.7 4.7-12.3 4.7-17 0l-7.1-7.1c-4.7-4.7-4.7-12.3 0-17L127.3 256 25.1 155.6c-4.7-4.7-4.7-12.3 0-17l7.1-7.1c4.7-4.7 12.3-4.7 17 0l117.8 116c4.6 4.7 4.6 12.3-.1 17z" class=""></path>
    </svg>
    Next
  </button>