问:
Find XmlElement in List<> using array of matching attribute names ... Using Linq
I have an XmlElement with several attributes

```<code>xeObject = <Object Name="Object1" Site="Site1" ... />
</code>```

I also have a list of XmlElements with several (possibly different) attributes

```<code>l_xeObject = <Object ... /><Object ... /> ... <Object ... />
</code>```

I would like a function call like

```<code>FindMatchingElements(xeObject, l_xeObject, "Name", "Site")
</code>```

where any elements in l_xeObject that have the same values as xeObject.Name and xeObject.Site are returned!

Can i do this with Linq?

... I already have the following function

```<code>public static List<XmlElement> GetXmlElementsFromListWithMatchingAttribute
    (XmlElement xeMatchOn, string sMatchingAttributeName, List<XmlElement> l_xeSearchIn)
{
    return (l_xeSearchIn
        .Where(xe => xe.Attributes[sMatchingAttributeName].Value
            == xeMatchOn.Attributes[sMatchingAttributeName].Value)
        ).ToList();
}
</code>```

but it only uses one attribute.

Thanks to Frédéric for the answer i needed.

答:
You can use All() to match several attributes and GetAttribute() to avoid having to check for null:

```<code>public static IEnumerable<XmlElement> FindMatchingElements(XmlElement match,
    IEnumerable<XmlElement> elements, params string[] attributeNames)
{
    // Argument validation omitted for brevity.

    return elements.Where(
        element => attributeNames.All(
            name => element.GetAttribute(name) == match.GetAttribute(name)));
}
</code>```

That said, if you really want to parse or generate XML markup with LINQ, consider using LINQ to XML instead of the DOM classes.

Body:
I have an XmlElement with several attributes

xeObject = <Object Name="Object1" Site="Site1" ... />

I also have a list of XmlElements with several (possibly different) attributes

l_xeObject = <Object ... /><Object ... /> ... <Object ... />

I would like a function call like

FindMatchingElements(xeObject, l_xeObject, "Name", "Site")

where any elements in l_xeObject that have the same values as xeObject.Name and xeObject.Site are returned!

Can i do this with Linq?

... I already have the following function

public static List<XmlElement> GetXmlElementsFromListWithMatchingAttribute
    (XmlElement xeMatchOn, string sMatchingAttributeName, List<XmlElement> l_xeSearchIn)
{
    return (l_xeSearchIn
        .Where(xe => xe.Attributes[sMatchingAttributeName].Value
            == xeMatchOn.Attributes[sMatchingAttributeName].Value)
        ).ToList();
}

but it only uses one attribute.

Thanks to Frédéric for the answer i needed.

Body:
You can use All() to match several attributes and GetAttribute() to avoid having to check for null:

public static IEnumerable<XmlElement> FindMatchingElements(XmlElement match,
    IEnumerable<XmlElement> elements, params string[] attributeNames)
{
    // Argument validation omitted for brevity.

    return elements.Where(
        element => attributeNames.All(
            name => element.GetAttribute(name) == match.GetAttribute(name)));
}

That said, if you really want to parse or generate XML markup with LINQ, consider using LINQ to XML instead of the DOM classes.


来源: stackexchange

问:
How do you evaluate only one part of an equation in python?
```<code>import math

term = ['math.sqrt', 'math.pi', 'math.sin', 'math.cos', 'math.tan',
'math.log', 'math.log', 'math.pow', 'math.cosh', 'math.sinh',
'math.tanh', 'math.sqrt', 'math.pi', 'math.radians',
'math.e','math.radians']
replace = ['√', 'π', 'sin', 'cos', 'tan', 'log', 'ln', 'pow', 'cosh',
'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e', 'rad']

equation = input('')

for word in replace:
    equation = equation.replace(word, term[replace.index(word)])
</code>```

I am trying to evaluate only the calculations in 'equation' that are also found in the 'term' and afterwards replace the values that we found in 'equation'

Ex.
input: x + 5 - sqrt(4) = 9

then my program will replace sqrt(4) with math.sqrt(4)

then it should calculate math.sqrt(4); so math.sqrt(4) = 2

and lastly replace the 2 with sqrt(4) in 'equation'; so, equation = x + 5 - 2 = 9

答:
I can help you, but with using an eval statement, which is generally considered somewhat of bad practice

The solution, in one line, is:

```<code>' '.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')])
</code>```

Let's break it down:

equation.split(' ') splits the equation string into a list of strings separated by an empty space: ['x', '+', '5', '-', 'math.sqrt(4)', '=', '9']

[str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')] runs str(eval(s)) on any element of the list that satisfies the condition ('(' in s and ')' in s) (I'm assuming that you only open and close parentheses on the function itself).

str(eval(s)) evaluates the function as it is written, and then casts it back to string.

' '.join([...]) joins the list elements, putting the spaces back in place.

The results comes out as:

```<code>'x + 5 - 2.0 = 9'
</code>```

Just remember putting your spaces in the right places in the input.

ContentLicense: CC BY-SA 4.0

Body:
import math

term = ['math.sqrt', 'math.pi', 'math.sin', 'math.cos', 'math.tan',
'math.log', 'math.log', 'math.pow', 'math.cosh', 'math.sinh',
'math.tanh', 'math.sqrt', 'math.pi', 'math.radians',
'math.e','math.radians']
replace = ['√', 'π', 'sin', 'cos', 'tan', 'log', 'ln', 'pow', 'cosh',
'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e', 'rad']

equation = input('')

for word in replace:
    equation = equation.replace(word, term[replace.index(word)])

I am trying to evaluate only the calculations in 'equation' that are also found in the 'term' and afterwards replace the values that we found in 'equation'

Ex.
input: x + 5 - sqrt(4) = 9

then my program will replace sqrt(4) with math.sqrt(4)

then it should calculate math.sqrt(4); so math.sqrt(4) = 2

and lastly replace the 2 with sqrt(4) in 'equation'; so, equation = x + 5 - 2 = 9

Body:
I can help you, but with using an eval statement, which is generally considered somewhat of bad practice

The solution, in one line, is:

' '.join([str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')])

Let's break it down:

equation.split(' ') splits the equation string into a list of strings separated by an empty space: ['x', '+', '5', '-', 'math.sqrt(4)', '=', '9']

[str(eval(s)) if ('(' in s and ')' in s) else s for s in equation.split(' ')] runs str(eval(s)) on any element of the list that satisfies the condition ('(' in s and ')' in s) (I'm assuming that you only open and close parentheses on the function itself).

str(eval(s)) evaluates the function as it is written, and then casts it back to string.

' '.join([...]) joins the list elements, putting the spaces back in place.

The results comes out as:

'x + 5 - 2.0 = 9'

Just remember putting your spaces in the right places in the input.


问:
Why doesn't my sprite move correctly in pygame?
My second game is a platformer. I drew all the spites, drew the background and the platform, but I cant move my character more than 45 pixels one way, even when it is supposed to move 5 pixels. I also copied some code from here and there, so I cant just search it up. This is very puzzling, please help.
Here is the code:</p>

```<code>import sys
import pygame

screen = pygame.display.set_mode((1300, 700), pygame.RESIZABLE)
global bg
bg = pygame.image.load('Pictures/badground.png')
w = (0, 0, 0)
screen.fill(w)
screen.blit(bg, (0, 0))
level = 0
walking_l = (pygame.image.load('Pictures/walk_l.png'))
walking_r = (pygame.image.load('Pictures/walk_r.png'))
walking_l_2 = (pygame.image.load('Pictures/_stand.png'))
walking_r_2 = (pygame.image.load('Pictures/stand.png'))
stand = (pygame.image.load('Pictures/rstand.png'))
pf = (pygame.image.load('Pictures/platform.png'))
pygame.display.set_caption('Platformed')

class player(object):
    def __init__(self, speed, width, height):
        self.speed = speed
        self.x = 650
        self.y = 350
        self.width = width
        self.height = height
        self.walk_l = False
        self.walk_r = False
        self.stand = True
        self.jump = False
        self.walk_count = 0

    def reprint_win(self):
        screen.fill(w)
        screen.blit(bg, (0, 0))

    def walk(self):
        k = pygame.key.get_pressed()
        if k[pygame.K_a]:
            self.x -= self.speed
            self.stand = False
            self.walk_l = True
            self.walk_r = False
            self.jump = False
            print(self.x)
            screen.fill(w)
            screen.blit(bg, (0, 0))
        elif k[pygame.K_d]:
            self.x += self.speed
            self.stand = False
            self.walk_r = True
            self.walk_l = False
            self.jump = False
            print(self.y)
            screen.fill(w)
            screen.blit(bg, (0, 0))
        elif k[pygame.K_w] and self.walk_r and not self.jump:
            self.stand = False
            self.walk_r = True
            self.walk_l = False
            self.jump = True
            screen.fill(w)
            screen.blit(bg, (0, 0))
        else:
            self.stand = True
            self.walk_r = False
            self.walk_l = False
            self.jump = False
            screen.fill(w)
            screen.blit(bg, (0, 0))

while True:
    for e in pygame.event.get():
        man = player(5, 64, 64)
        if e.type == pygame.QUIT:
            sys.exit()
        if e.type == pygame.KEYDOWN:
            man.walk()
            screen.blit(stand, (man.x, man.y))
            pygame.display.update()
        elif e.type == pygame.KEYDOWN:
            man.walk()
            screen.blit(stand, (man.x, man.y))
            pygame.display.update()
</code>```

答:
The method walk() of the class player changes the instance attribute, but id doesn't draw anything.

Add a method draw, which draw the player dependent on the instance attributes:

class player(object):
    # [...]

    def walk(self):
        self.stand, self.walk_l, self.walk_r, self.jump = False, False, False, False
        k = pygame.key.get_pressed()
        if k[pygame.K_a]:
            self.x -= self.speed
            self.walk_l = True
        elif k[pygame.K_d]:
            self.x += self.speed
            self.walk_r = True
        elif k[pygame.K_w] and self.walk_r and not self.jump:
            self.jump = True
        else:
            self.stand = True

    def draw(self, surf):
        if self.walk_l:
            surf.blit(walking_l, (self.x, self.y))
        elif self.walk_r:
            surf.blit(walking_r, (self.x, self.y))
        else:
            surf.blit(stand, (self.x, self.y))
```

<p>You have to draw the entire scene in every frame. Do the drawing to the application loop rather then the event loop.<br>
Furthermore the instance of <code>palyer</code> has to be created before the application loop and invoke <code>man.mvoe()</code> in every frame.<br>
Use <code>pygame.time.Clock()</code> <code>.tick()</code> to control the frames per second:</p>

<pre class="lang-py prettyprint-override"><code>man = player(5, 64, 64)

clock = pygame.time.Clock()
FPS = 60
while True:
    clock.tick(FPS)

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()

    man.walk()

    screen.blit(bg, (0, 0))
    man.draw(screen)
    pygame.display.update()
</code>```

Body:
My second game is a platformer. I drew all the spites, drew the background and the platform, but I cant move my character more than 45 pixels one way, even when it is supposed to move 5 pixels. I also copied some code from here and there, so I cant just search it up. This is very puzzling, please help.
Here is the code:

import sys
import pygame

screen = pygame.display.set_mode((1300, 700), pygame.RESIZABLE)
global bg
bg = pygame.image.load('Pictures/badground.png')
w = (0, 0, 0)
screen.fill(w)
screen.blit(bg, (0, 0))
level = 0
walking_l = (pygame.image.load('Pictures/walk_l.png'))
walking_r = (pygame.image.load('Pictures/walk_r.png'))
walking_l_2 = (pygame.image.load('Pictures/_stand.png'))
walking_r_2 = (pygame.image.load('Pictures/stand.png'))
stand = (pygame.image.load('Pictures/rstand.png'))
pf = (pygame.image.load('Pictures/platform.png'))
pygame.display.set_caption('Platformed')

class player(object):
    def __init__(self, speed, width, height):
        self.speed = speed
        self.x = 650
        self.y = 350
        self.width = width
        self.height = height
        self.walk_l = False
        self.walk_r = False
        self.stand = True
        self.jump = False
        self.walk_count = 0

    def reprint_win(self):
        screen.fill(w)
        screen.blit(bg, (0, 0))

    def walk(self):
        k = pygame.key.get_pressed()
        if k[pygame.K_a]:
            self.x -= self.speed
            self.stand = False
            self.walk_l = True
            self.walk_r = False
            self.jump = False
            print(self.x)
            screen.fill(w)
            screen.blit(bg, (0, 0))
        elif k[pygame.K_d]:
            self.x += self.speed
            self.stand = False
            self.walk_r = True
            self.walk_l = False
            self.jump = False
            print(self.y)
            screen.fill(w)
            screen.blit(bg, (0, 0))
        elif k[pygame.K_w] and self.walk_r and not self.jump:
            self.stand = False
            self.walk_r = True
            self.walk_l = False
            self.jump = True
            screen.fill(w)
            screen.blit(bg, (0, 0))
        else:
            self.stand = True
            self.walk_r = False
            self.walk_l = False
            self.jump = False
            screen.fill(w)
            screen.blit(bg, (0, 0))

while True:
    for e in pygame.event.get():
        man = player(5, 64, 64)
        if e.type == pygame.QUIT:
            sys.exit()
        if e.type == pygame.KEYDOWN:
            man.walk()
            screen.blit(stand, (man.x, man.y))
            pygame.display.update()
        elif e.type == pygame.KEYDOWN:
            man.walk()
            screen.blit(stand, (man.x, man.y))
            pygame.display.update()

Body:
The method walk() of the class player changes the instance attribute, but id doesn't draw anything.

Add a method draw, which draw the player dependent on the instance attributes:

class player(object):
    # [...]

    def walk(self):
        self.stand, self.walk_l, self.walk_r, self.jump = False, False, False, False
        k = pygame.key.get_pressed()
        if k[pygame.K_a]:
            self.x -= self.speed
            self.walk_l = True
        elif k[pygame.K_d]:
            self.x += self.speed
            self.walk_r = True
        elif k[pygame.K_w] and self.walk_r and not self.jump:
            self.jump = True
        else:
            self.stand = True

    def draw(self, surf):
        if self.walk_l:
            surf.blit(walking_l, (self.x, self.y))
        elif self.walk_r:
            surf.blit(walking_r, (self.x, self.y))
        else:
            surf.blit(stand, (self.x, self.y))

You have to draw the entire scene in every frame. Do the drawing to the application loop rather then the event loop.

Furthermore the instance of palyer has to be created before the application loop and invoke man.mvoe() in every frame.

Use pygame.time.Clock() .tick() to control the frames per second:

man = player(5, 64, 64)

clock = pygame.time.Clock()
FPS = 60
while True:
    clock.tick(FPS)

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()

    man.walk()

    screen.blit(bg, (0, 0))
    man.draw(screen)
    pygame.display.update()


问:
RxJS - Properly merging two arrays from two seperate $http streams
Currently learning RxJS, I'm not gonna lie, I had difficulties understanding it, especially in terms of "Why do we even want to use if we have promises"
But now I think I made small step further.

I know I should avoid nested subscriptions.
Trying to write as short as possible code to merge two streams result into single variable.

So I have two arrays simulating result of streams, which I want to join.
Fights array should became new obj array inside boxers objects

```<code>const boxers = [
    {
        user_id:1,
        first_name:'Lennox ',
        last_name:'Lewis',
        nationality:"UK"
    },
    {
        user_id:2,
        first_name:'Mike',
        last_name:'Tyson',
        nationality:'USA'
    },
     {
        user_id:3,
        first_name:'Riddick',
        last_name:'Bowe',
        nationality:'USA'
    },
];

const fights = [
    {
        fight_id:1,
        user_id:1,
        opponnent_id:2,
        winner_id:1,
        venue:'Memphis Pyramid, Tennessee'
    }
]
</code>```

And then I wrote code:

```<code>const boxersWithFights2 = boxersStream.pipe(
    flatMap(boxers => {
        return fightsStream.pipe(
            flatMap(fights => {
                boxers.map(boxer => boxer.fights = fights.filter(fight => fight.user_id === boxer.user_id ||fight.opponnent_id === boxer.user_id ))
                return boxers;
            })
        )
    }
));
</code>```

Surprisingly this works as expected.
When I subscribe to boxersWithFights, it console.logs me with properly mapped objects.
So it probably also work when returned from external api, but then I would of course need another map() operator.

My question: Is this code written well? Can it be written to be more clean & elegant ?

I also know I could do that easier with e.g. forkJoin, but I really wanted to test flatMap(mergeMap) operator.

答:
You shouldn't mutate data in the stream but boxer.fights = does it.
Also you can combine the streams together via forkJoin because they don't depend on each other.

Try to use map operator instead:

const boxersWithFights2 = forkJoin([boxersStream, fightsStream]).pipe(
    map(([boxers, fights]) => {
      return boxers.map(boxer => ({
        ...boxer,
        fights: fights.filter(fight => fight.user_id === boxer.user_id ||fight.opponnent_id === boxer.user_id ),
    })),
));
```

Body:
Currently learning RxJS, I'm not gonna lie, I had difficulties understanding it, especially in terms of "Why do we even want to use if we have promises"
But now I think I made small step further.

I know I should avoid nested subscriptions.
Trying to write as short as possible code to merge two streams result into single variable.

So I have two arrays simulating result of streams, which I want to join.
Fights array should became new obj array inside boxers objects

const boxers = [
    {
        user_id:1,
        first_name:'Lennox ',
        last_name:'Lewis',
        nationality:"UK"
    },
    {
        user_id:2,
        first_name:'Mike',
        last_name:'Tyson',
        nationality:'USA'
    },
     {
        user_id:3,
        first_name:'Riddick',
        last_name:'Bowe',
        nationality:'USA'
    },
];

const fights = [
    {
        fight_id:1,
        user_id:1,
        opponnent_id:2,
        winner_id:1,
        venue:'Memphis Pyramid, Tennessee'
    }
]

And then I wrote code:

const boxersWithFights2 = boxersStream.pipe(
    flatMap(boxers => {
        return fightsStream.pipe(
            flatMap(fights => {
                boxers.map(boxer => boxer.fights = fights.filter(fight => fight.user_id === boxer.user_id ||fight.opponnent_id === boxer.user_id ))
                return boxers;
            })
        )
    }
));

Surprisingly this works as expected.
When I subscribe to boxersWithFights, it console.logs me with properly mapped objects.
So it probably also work when returned from external api, but then I would of course need another map() operator.

My question: Is this code written well? Can it be written to be more clean & elegant ?

I also know I could do that easier with e.g. forkJoin, but I really wanted to test flatMap(mergeMap) operator.


问:
Strange .net webservice 503 issue
I have a fairly strange(IMO) issue here with a webservice provided by a third party.

On calling the webservice on the live server, all works as expected. Calling it on a development setup, sometimes returns with a 503 - Service unavailable, other times it works. Intermittent....
Both of these tests are done from the same client, so I don't think its a network level problem.

Now, the strange thing is, if I place a breakpoint on the line before the webservice call, and step over the call, it works. Even running the code(F5) past this breakpoint allows it to succeed. Adding a System.Threading.Thread.Sleep(1000); before the call(to simulate a breakpoint, of sorts), doesnt have any effect.

I don't have access to the remote servers, I know its server 2003/IIS 6.0 though, and the company that provides the system the webservice interfaces with, claim there's no issue with their server / software.

So before I go seriously pointing the finger, anyone experienced anything like this before, or anything else I can try?

答:
In the end, this was caused by a issue on a transparent(ip spoofing) proxy, that sits upstream between my system and the remote system. The proxy was returning the 503, but under the guise of the target host.

I only managed to find this by fluke, how would I have identified this if I was to look for this type of issue, as theres nothing in the http headers /raw dump that jump out at me to point to this issue?

ContentLicense: CC BY-SA 3.0

Title: Strange .net webservice 503 issue


问:
Helm subcharts names and URL variables configuratiion
Requirement: deploy multiple releases of chart A to single k8s namespace

I have a complex problem with subcharts name configuration. Relations between my charts are:

```<code>A
|- B
   |- C
      |- D - postgres
      |- E - graphql-engine
|- F - postgres
|- G - graphql-engine
</code>```

A depends on B, F, G

B depends on C

C depends on D, E

And the chart of type graphql-engine can requires zero or N variables based on application which for it is (if you know this app it should be backend URL, action URL, trigger URL etc.). In instance E the variables should points to aplication C and in instance G they should points to A.

I made Helm chart for graphql-engine with this part in Deployment`s container section:

```<code>          env:
{{- range $k, $v := .Values.environmentVariables }}
            - name: {{ quote $k }}
              value: {{ quote "$v" }}
{{- end }}
</code>```

To have a right names of subcharts I am doing this in A`s variables.yaml file:

```<code>B:
  C:
    nameOverride: A-B-C
    D:
      nameOverride: A-B-C-D
    E:
      nameOverride: A-B-C-E
F:
  nameOverride: A-F
G:
  nameOverride: A-G
</code>```

Default chart`s _helpers.tpl file prefixs nameOverride variable with .Release.Name variable.
It is not nice and optimal but I did not find a way to made this process to be dynamically created. Is here someone who knows better way to do this naming? That is my first question.

To simplify my problem. I need to put variable list like this:

VAR1="http://{{ .Release.Name }}-A-B-C:8080/graphql"

VAR2="http://{{ .Release.Name }}-A-B-C:8080/actions"

into E chart from A chart. But I did not find a way to let Go templating expand .Release.Name variable. I made this in A variables.yaml:

```<code>B:
  C:
    nameOverride: A-B-C
    D:
      nameOverride: A-B-C-D
    E:
      nameOverride: A-B-C-E
      extraVariables:
        VAR1: "http://{{ .Release.Name }}-A-B-C:8080/graphql"
        VAR2: "http://{{ .Release.Name }}-A-B-C:8080/actions"
F:
  nameOverride: A-F
G:
  nameOverride: A-G
  extraVariables:
    VAR1: "http://{{ .Release.Name }}-A:8080/graphql"
</code>```

But I did not find a way how to use tpl Helm function in range part with dollar variable input. Or another possibility to accomplish this. I tried just include some "template" which I can made in A chart but it had bad Vars context and is used in every graphql-engine chart instance and it is not right in this.

The real A application have more levels of dependencies but it is not important to this problem. Is this wrong way to do that? How are you creating names of k8s objects and how are you setting URL variables for you applications?

Thank you!

答:
And answer to question about looping over list with tpl function calling is this. You just have to change context of tpl.</p>

```<code>{{- range $k, $v := .Values.environmentVariables }}
            - name: {{ quote $k }}
              value: {{ tpl $v $ }}
{{- end }}
</code>```

Body:
Requirement: deploy multiple releases of chart A to single k8s namespace

I have a complex problem with subcharts name configuration. Relations between my charts are:

A
|- B
   |- C
      |- D - postgres
      |- E - graphql-engine
|- F - postgres
|- G - graphql-engine

A depends on B, F, G

B depends on C

C depends on D, E

And the chart of type graphql-engine can requires zero or N variables based on application which for it is (if you know this app it should be backend URL, action URL, trigger URL etc.). In instance E the variables should points to aplication C and in instance G they should points to A.

I made Helm chart for graphql-engine with this part in Deployment`s container section:

          env:
{{- range $k, $v := .Values.environmentVariables }}
            - name: {{ quote $k }}
              value: {{ quote "$v" }}
{{- end }}

To have a right names of subcharts I am doing this in A`s variables.yaml file:

B:
  C:
    nameOverride: A-B-C
    D:
      nameOverride: A-B-C-D
    E:
      nameOverride: A-B-C-E
F:
  nameOverride: A-F
G:
  nameOverride: A-G

Default chart`s _helpers.tpl file prefixs nameOverride variable with .Release.Name variable.
It is not nice and optimal but I did not find a way to made this process to be dynamically created. Is here someone who knows better way to do this naming? That is my first question.

To simplify my problem. I need to put variable list like this:

VAR1="http://{{ .Release.Name }}-A-B-C:8080/graphql"

VAR2="http://{{ .Release.Name }}-A-B-C:8080/actions"

into E chart from A chart. But I did not find a way to let Go templating expand .Release.Name variable. I made this in A variables.yaml:

B:
  C:
    nameOverride: A-B-C
    D:
      nameOverride: A-B-C-D
    E:
      nameOverride: A-B-C-E
      extraVariables:
        VAR1: "http://{{ .Release.Name }}-A-B-C:8080/graphql"
        VAR2: "http://{{ .Release.Name }}-A-B-C:8080/actions"
F:
  nameOverride: A-F
G:
  nameOverride: A-G
  extraVariables:
    VAR1: "http://{{ .Release.Name }}-A:8080/graphql"

But I did not find a way how to use tpl Helm function in range part with dollar variable input. Or another possibility to accomplish this. I tried just include some "template" which I can made in A chart but it had bad Vars context and is used in every graphql-engine chart instance and it is not right in this.

The real A application have more levels of dependencies but it is not important to this problem. Is this wrong way to do that? How are you creating names of k8s objects and how are you setting URL variables for you applications?

Thank you!

Body:
And answer to question about looping over list with tpl function calling is this. You just have to change context of tpl.

{{- range $k, $v := .Values.environmentVariables }}
            - name: {{ quote $k }}
              value: {{ tpl $v $ }}
{{- end }}


问:
How to send one view controller values to another view controller table view in swift?
I have three view controllers like below

Add address Table view this is AddAddressViewcontroller, if i select addaddress button it goes to profileviewcontroller if i tap continue it goes to ZoomMapviewcontroller here is i confirm then i need to show that below label text in  AddAddressViewcontroller Add address Table view how to do that.

ZoomMapviewcontroller code:

```<code>protocol DataEnteredDelegate: class {
func userDidEnterInformation(info: DataEnteredModelSave)
}

class NewZoomAddressViewController: UIViewController {
weak var delegate: DataEnteredDelegate? = nil

var zipName: String?
var localityName: String?
var sublocalityName: String?

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
}
@IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AddAddressViewController") as! AddAddressViewController
   guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
        else { return }
    let enteredData = DataEnteredModelSave(pinCode: zipName, streetField: sublocalityName, cityField: localityName)
    delegate?.userDidEnterInformation(info: enteredData)
    self.navigationController?.pushViewController(viewController, animated: true)

}
}
</code>```

here how to send zipName, locality, subLocality valuew to Addaddressviewcontroller tableview

AddAddressViewcontroller code:

```<code> class AddAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

var city: String?
var pincode: String?
var locality: String?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = "\(city!) \(pincode!) \(locality!)" // here i need ZoomMapviewcontroller valuew in row

}
}
</code>```

please help me with code, i got stuck here from long time

答:
There are 2 approaches here..

First method is assuming you have correctly set the DataEnteredDelegate in the AddAddressViewController. Your mistake here is, you are calling a delegate method in an already existing AddAddressViewcontroller instance in the navigationController stack and pushing a new AddAddressViewcontroller into that stack again.

Second method, if you really want to push (which is unnecessary as per me) a new AddAddressViewController instance to the navigationController stack again.

First approach :-
You've already an AddAddressViewController instance in your navigationController stack. So you just need to pop back to that view controller. So your confirmBtn action in NewZoomAddressViewController will be :-

```<code>@IBAction func confirmBtn(_ sender: Any) {

    guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
    else { return }

    if let viewControllers = self.navigationController?.viewControllers {
        for aViewController in viewControllers {
            if aViewController.isKind(of: AddAddressViewController.self) {
                let addAddressVC = aViewController as? AddAddressViewController
                let enteredData = DataEnteredModelSave(pinCode: zipName, streetField: sublocalityName, cityField: localityName)
                delegate?.userDidEnterInformation(info: enteredData)
                self.navigationController?.popToViewController(aViewController, animated: true)
                break
            }
        }
    }
}
</code>```

Second Approach :- In this case there is no need for delegate. You can directly pass the zipName, sublocalityName and localityName  to the new AddAddressViewController.

```<code>@IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AddAddressViewController") as! AddAddressViewController
    guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
        else { return }
    viewController.city = localityName
    viewController.pincode = zipName
    viewController.locality = localityName
    self.navigationController?.pushViewController(viewController, animated: true)
}
</code>```

Body:
I have three view controllers like below

Add address Table view this is AddAddressViewcontroller, if i select addaddress button it goes to profileviewcontroller if i tap continue it goes to ZoomMapviewcontroller here is i confirm then i need to show that below label text in  AddAddressViewcontroller Add address Table view how to do that.

ZoomMapviewcontroller code:

protocol DataEnteredDelegate: class {
func userDidEnterInformation(info: DataEnteredModelSave)
}

class NewZoomAddressViewController: UIViewController {
weak var delegate: DataEnteredDelegate? = nil

var zipName: String?
var localityName: String?
var sublocalityName: String?

@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var addressLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
}
@IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AddAddressViewController") as! AddAddressViewController
   guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
        else { return }
    let enteredData = DataEnteredModelSave(pinCode: zipName, streetField: sublocalityName, cityField: localityName)
    delegate?.userDidEnterInformation(info: enteredData)
    self.navigationController?.pushViewController(viewController, animated: true)

}
}

here how to send zipName, locality, subLocality valuew to Addaddressviewcontroller tableview

AddAddressViewcontroller code:

 class AddAddressViewController: UIViewController,DataEnteredDelegate {
@IBOutlet var addressEDITTableview: UITableView!

var city: String?
var pincode: String?
var locality: String?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: EditAddressTableViewCell = tableView.dequeueReusableCell(withIdentifier: "EditAddressTableViewCell") as! EditAddressTableViewCell
    cell.nameHeader.text = "header"
    cell.addressLabel.text = "\(city!) \(pincode!) \(locality!)" // here i need ZoomMapviewcontroller valuew in row

}
}

please help me with code, i got stuck here from long time

Body:
There are 2 approaches here..

First method is assuming you have correctly set the DataEnteredDelegate in the AddAddressViewController. Your mistake here is, you are calling a delegate method in an already existing AddAddressViewcontroller instance in the navigationController stack and pushing a new AddAddressViewcontroller into that stack again.

Second method, if you really want to push (which is unnecessary as per me) a new AddAddressViewController instance to the navigationController stack again.

First approach :-
You've already an AddAddressViewController instance in your navigationController stack. So you just need to pop back to that view controller. So your confirmBtn action in NewZoomAddressViewController will be :-

@IBAction func confirmBtn(_ sender: Any) {

    guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
    else { return }

    if let viewControllers = self.navigationController?.viewControllers {
        for aViewController in viewControllers {
            if aViewController.isKind(of: AddAddressViewController.self) {
                let addAddressVC = aViewController as? AddAddressViewController
                let enteredData = DataEnteredModelSave(pinCode: zipName, streetField: sublocalityName, cityField: localityName)
                delegate?.userDidEnterInformation(info: enteredData)
                self.navigationController?.popToViewController(aViewController, animated: true)
                break
            }
        }
    }
}

Second Approach :- In this case there is no need for delegate. You can directly pass the zipName, sublocalityName and localityName  to the new AddAddressViewController.

@IBAction func confirmBtn(_ sender: Any) {

    let viewController = self.storyboard?.instantiateViewController(withIdentifier: "AddAddressViewController") as! AddAddressViewController
    guard
        let zipName = zipName,
        let sublocalityName = sublocalityName,
        let localityName = localityName
        else { return }
    viewController.city = localityName
    viewController.pincode = zipName
    viewController.locality = localityName
    self.navigationController?.pushViewController(viewController, animated: true)
}


问:
EF Core check if object in related table exists, if not - add it
I have the following class:

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}
</code>```

and an ItemCategory class:

```<code>public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}
</code>```

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

答:
You must define foreign key property  in the dependent entity class And when you add a new item, set the CategoryID instead of Category .</p>

```<code>public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    public int CategoryID { get; set; }

    public ItemCategory Category { get; set; }
}
</code>```

Body:
I have the following class:

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    [Required]
    public ItemCategory Category { get; set; }
}

and an ItemCategory class:

public class ItemCategory
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    public string Name { get; set; }
}

I want each item to have one category and a category to be able to have many items. I am using code first and so far everything looks good - using migrations EF created an "Items" and "ItemCategories" tables with the appropriate foreign keys ("Items" table has a column "CategoryID" that references the "ID" column of the "ItemCategories" table). My problem is that if I have a category of, say, "Book" with ID 1 and I add a new Item with category "Book" in the "ItemCategories" a second entry is inserted that has ID 2 and name "Book". I want to change this behaviour to the following:

When a new Item is added, check if its Category.Name already exists in "ItemCategories". If it does set the "CategoryID" to its ID. If it does not - add a new record to "ItemCategories" and set "CategoryID" to its ID.

How do I achieve that?

Body:
You must define foreign key property  in the dependent entity class And when you add a new item, set the CategoryID instead of Category .

public class Item
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    [Required]
    [MaxLength(255)]
    public string Name { get; set; }

    public int CategoryID { get; set; }

    public ItemCategory Category { get; set; }
}


问:
Managing Jekyll Pages in Folders (on github-pages)
I have a Jekyll website hosted on GitHub Pages. Now I am having so many pages and I would like to manage them in a folder called _pages. I ideally want to have this structure:

```<code>root
  |-> _pages
      |-> Index.md
      |-> contact.md
      |-> cv
          |-> cv.md
          |-> my_cv.pdf
  |-> _posts
  |-> [other things such as config and gemfile]
</code>```

This I have done defining default permalinks in the _config.yml adding:

```<code>include:
  - _pages

defaults:
  - scope:
      path: "_pages"
      type: "pages"
    values:
      permalink: /:basename/ # make URL of pages in the folder _pages as on the root.
</code>```

That works perfectly.

However, as you see inside the _pages I would like to have another subfolder named cv and put my cv.md and my_cv.pdf in the same folder (in the actual website I have much more of these files for pages.). Ultimately I would like to have a benefit of using [Download my CV](my_cv.pdf) relative local linking, which I suppose because the pdf and the .md file are in the same folder it will recognize it. However it is not the case. cv.md has the permalink of /cv/ and not the cv folder. So when I use [Download my CV](my_cv.pdf) it creates root/cv/my_cv.pdf where this pdf file actually does not exist!

How can I manage to fix this thing? what is your trick?

答:
You cannot put static files in a directory starting with an underscore. They will not be available in/after the build process:

Which folder should I put my static files in Jekyll?

Body:
I have a Jekyll website hosted on GitHub Pages. Now I am having so many pages and I would like to manage them in a folder called _pages. I ideally want to have this structure:

root
  |-> _pages
      |-> Index.md
      |-> contact.md
      |-> cv
          |-> cv.md
          |-> my_cv.pdf
  |-> _posts
  |-> [other things such as config and gemfile]

This I have done defining default permalinks in the _config.yml adding:

include:
  - _pages

defaults:
  - scope:
      path: "_pages"
      type: "pages"
    values:
      permalink: /:basename/ # make URL of pages in the folder _pages as on the root.

That works perfectly.

However, as you see inside the _pages I would like to have another subfolder named cv and put my cv.md and my_cv.pdf in the same folder (in the actual website I have much more of these files for pages.). Ultimately I would like to have a benefit of using [Download my CV](my_cv.pdf) relative local linking, which I suppose because the pdf and the .md file are in the same folder it will recognize it. However it is not the case. cv.md has the permalink of /cv/ and not the cv folder. So when I use [Download my CV](my_cv.pdf) it creates root/cv/my_cv.pdf where this pdf file actually does not exist!

How can I manage to fix this thing? what is your trick?


问:
Is it better to have an "ORDER BY" column in a different table?
I have the following table which stores images:

```<code>id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows
</code>```

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

```<code>id        image_id       priority
1            1              1
2            12             2
3            22             1
</code>```

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?

答:
To achieve faster execution of queries it is always preferable to have a denormalized table - with all the data in one place.

Joins lead to slower execution times so make two tables only if you want to have a better schema and reduce data redundancy.

Body:
I have the following table which stores images:

id        image        priority      client_id      some_data       some_more_data    ....
1         img_1.png        1            1          text ...        text ...
12        img_2.png        2            3          text ...        text ...
22        img_3.png        1            1          text ...        text ...
....
..
Around 2,000,000 rows

Let's say I need to obtain the images for client 1 in order of their priorities. I can execute a simple query like select image from images order by priority.

Since a large number of rows are involved, is it better to have a separate table for which simply stores the image_id and priority like this

id        image_id       priority
1            1              1
2            12             2
3            22             1

So in order to get the same result, I'll use a simple join: select a.image from priorities b join images a on a.id = b.image_id order by b.priority

Which of the two will be faster?


问:
IE hang for 5 minutes when calling synchronous xmlhttprequest
I have a web application and use ajax to call back to my webserver to fetch data.

Sometimes(at rather unpredictable moments, but it can be reproduced) IE hangs completely for 5 minutes(the window says Not Responding) and then comes back and the xmlhttprequest object responds with error 12002.

The way I can reproduce it is as follows.

Open window(B) from main window(A) using button

Window A calls synchronous ajax(PROC1) when button is clicked to open window B. PROC1 Runs file.

New window(B) has ajax code(PROC2) and calls server asynchronous. Runs fine

User closes Window B after PROC2 completed but before data is returned.

In Main Window(a) user clicks button again. PROC1 runs again but now the send() call blocks for 5 minutes.

Please help. I've been looking for 3 days.

Please note:
* I can't test it in firefox (the app is not firefox compatible)
* I have to use synchronous calls (that's the way the app is constructed and it would take too much developer effort to rewrite it)

Why does this happen and how to I fix this?

答:
Thanks for answering Martijn.

It didn't solve my issues. I think what I'm seeing is best described on this website:
http://bytes.com/groups/javascript/643080-ajax-crashes-ie-close-window

In my situation I have an unstable connection or a slow webserver and when the connection is too slow and the browser and the webserver still have a connection then freezes.

OwnerDisplayName: Jaap Geurts

ContentLicense: CC BY-SA 2.5


问:
On Windows with Winrun4j how do I specify Java gclog location that understands APPDATA location
I want to enable garbage collection logging for Java application running on Windows

Like standard Windows programs the application is installed in C:/Program Files/CompanyName/SoftwareName and my application logs are stored in C:/Users/username/Roaming/SoftwareName

and in my code I identify the location of C:/Users/username/AppData with

```<code>System.getenv("APPDATA");
</code>```

Now I want the garbage logs to also go in that location, but I cannot see how I could specify that.

Also problematically if i just specify a filename and try to create in C:/Program Files/CompanyName/SoftwareName instead with

```<code>-Xlog:gc*:file=gc.log:time:filecount=7,filesize=8M
</code>```

then JVM fails to start because on Windows programs do not have permissions to create files in this folder after installation

Now if i was starting application in a batch script I suppose I could use %APPDATA% in the batch but I am using winrun4j so I do not see I have access to such variables from the .ini file.

答:
Okay I found I could use %APPDATA% in the .ini file as well

e.g

```<code>vmarg.1=-Xlog:gc*:file=%APPDATA%\SoftwareName\Logs\gc.log:time:filecount=7,filesize=2M
</code>```

Body:
I want to enable garbage collection logging for Java application running on Windows

Like standard Windows programs the application is installed in C:/Program Files/CompanyName/SoftwareName and my application logs are stored in C:/Users/username/Roaming/SoftwareName

and in my code I identify the location of C:/Users/username/AppData with

System.getenv("APPDATA");

Now I want the garbage logs to also go in that location, but I cannot see how I could specify that.

Also problematically if i just specify a filename and try to create in C:/Program Files/CompanyName/SoftwareName instead with

-Xlog:gc*:file=gc.log:time:filecount=7,filesize=8M

then JVM fails to start because on Windows programs do not have permissions to create files in this folder after installation

Now if i was starting application in a batch script I suppose I could use %APPDATA% in the batch but I am using winrun4j so I do not see I have access to such variables from the .ini file.

Body:
Okay I found I could use %APPDATA% in the .ini file as well

e.g

vmarg.1=-Xlog:gc*:file=%APPDATA%\SoftwareName\Logs\gc.log:time:filecount=7,filesize=2M


问:
New line after input
I would like to have the following output:

```<code>Type in something random:
2
</code>```

I used the following code:

```<code>input("Type in something random:")
</code>```

and my output is

```<code>Type in something random:2
</code>```

(Output for when the user inputs "2")

How can I have the output given to me in  a new line, as demonstrated above?

I am using Python 3.

答:
Try adding \n

```<code>print("Type in something random: \n2")

Type in something random:
2
</code>```

Title: New line after input

Body:
I would like to have the following output:

Type in something random:
2

I used the following code:

input("Type in something random:")

and my output is

Type in something random:2

(Output for when the user inputs "2")

How can I have the output given to me in  a new line, as demonstrated above?

I am using Python 3.

Body:
Try adding \n

print("Type in something random: \n2")

Type in something random:
2


问:
How to get the transaction ID in paypal node.js react?
I am currently working on react js project where I need two main functionalities of Paypal one is to make payment and other is to make a refund on that payment ( sometimes partial refund on a subset of that payment).

I am following this sdk of the node.js implementation, https://github.com/paypal/Checkout-NodeJS-SDK

but I want to extract the transaction ID and token and such details which I am not able to find in this SDK.

I am just getting the
order ID
capture ID
refund ID but not the transaction ID , so how do I get that ?

also , I am suggested to use smart payment buttons but if I am using the smart payment buttons, I am able to perform the checkout operation,but getting different set of details like

payment ID ,
payment token and I don't know how to perform the refund for that payment?

答:
A capture ID is a transaction ID.

As discussed in comments elsewhere, the confusion was that the buyer/sender has its own transaction ID.

(For every PayPal transaction, the sender and the receiver each have their own transaction ID)


问:
How i save the opened levels in my android app
I have a quiz game that i coded by java (using android studio).
My question is how i save the levels that the user opened , when the user closes the app, nothing is saved and the user has to start playing the game from level 1 again , i tried to use SharedPreferences but it doesn't work,cause i have many categories in my app and each one has many levels ,so even when SharedPreferences  work it will not help cause it will save the level of all the categories what the user doesn't open it

edit:sorry I forget to say I using realtime database (firebase) in my app&is there are way exepet room database

```<code>public class SetsActivity extends AppCompatActivity {

private GridView gridView;
private AppCompatDialog loadingDialoge;
private sets_adapter adapter;
private AdView mAdView;
private  int l,sets,level;
private String title;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sets);

    Toolbar toolbar=findViewById(R.id.sets_toolbar);
    gridView=findViewById(R.id.sets_gv);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(title);

    l=getIntent().getIntExtra("lvl",0);
    title=getIntent().getStringExtra("title");
    sets=getIntent().getIntExtra("sets",0);

    loadlvl();

    adapter=new sets_adapter(sets,title,level);

    gridView.setAdapter(adapter);

}

//on back item click
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId()==android.R.id.home)
        finish();
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPause() {
    savelevel();
    super.onPause();
    finish();
}

private void savelevel(){
    SharedPreferences savechange = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savechange.edit();
    editor.putInt("lvl",l);
    editor.commit();
}

private void loadlvl(){
    SharedPreferences savechange = this.getPreferences( Context.MODE_PRIVATE);
    level=savechange.getInt("lvl",-1);

}
</code>```

}

答:
In addition to the Apollo answer. Worked with a similar task, so I decided to supplement answer.

Create Level class:

```<code>@Entity
public class Level {
    @PrimaryKey
    public int id;

    @ColumnInfo(name = "number")
    public int number;

    @ColumnInfo(name = "level_name")
    public String levelName;

    @ColumnInfo(name = "is_open")
    public boolean isOpen;

    public Level(int id, int number, String levelName, boolean isOpen) {
        this.id = id;
        this.levelName = levelName;
        this.isOpen = isOpen;
        this.number = number;
    }
}
</code>```

Dao class:

```<code>@Dao
public interface LevelDao {
    @Insert
    void insertAll(Level... levels);

    @Query("UPDATE level SET is_open = :isOpen WHERE level_name = :levelName")
    void updateLevel(String levelName, boolean isOpen);

    @Query("SELECT * FROM level WHERE number LIKE :numberLevel")
    Level findByNumber(int numberLevel);
    ...
}
</code>```

LevelDatabase class:

```<code>@Database(entities = {Level.class}, version = 1)
public abstract class LevelDatabase extends RoomDatabase {
    public abstract LevelDao levelDao();
}
</code>```

When you have first start of application, open only the first level:

```<code>AsyncTask.execute(() -> {
    dbLevels = Room.databaseBuilder(this.getApplicationContext(), LevelDatabase.class,
        "levels-database").addCallback(dbCallback).build();
    LevelDao dao = dbLevels.levelDao();
});
...
// only called once
RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {
    public void onCreate(@NonNull SupportSQLiteDatabase db) {
        Executors.newSingleThreadScheduledExecutor().execute(() -> {
            Level level1 = new Level(0, 1, "level1", true);
            Level level2 = new Level(1, 2, "level2", false);
            dbLevels.levelDao().insertAll(level1, level2);
        });
    }
};
</code>```

To open a level during the game:

```<code>AsyncTask.execute(() -> {
    LevelDatabase dbLevels = Room.databaseBuilder(gameActivity.getApplicationContext(),
        LevelDatabase.class, "levels-database").build();
    LevelDao dao = dbLevels.levelDao();
    dao.updateLevel("level2", true);
});
</code>```

Check if open:

```<code>dao.findByNumber(2).isOpen;
</code>```

Body:
I have a quiz game that i coded by java (using android studio).
My question is how i save the levels that the user opened , when the user closes the app, nothing is saved and the user has to start playing the game from level 1 again , i tried to use SharedPreferences but it doesn't work,cause i have many categories in my app and each one has many levels ,so even when SharedPreferences  work it will not help cause it will save the level of all the categories what the user doesn't open it

edit:sorry I forget to say I using realtime database (firebase) in my app&is there are way exepet room database

public class SetsActivity extends AppCompatActivity {

private GridView gridView;
private AppCompatDialog loadingDialoge;
private sets_adapter adapter;
private AdView mAdView;
private  int l,sets,level;
private String title;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sets);

    Toolbar toolbar=findViewById(R.id.sets_toolbar);
    gridView=findViewById(R.id.sets_gv);

    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(title);

    l=getIntent().getIntExtra("lvl",0);
    title=getIntent().getStringExtra("title");
    sets=getIntent().getIntExtra("sets",0);

    loadlvl();

    adapter=new sets_adapter(sets,title,level);

    gridView.setAdapter(adapter);

}

//on back item click
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    if (item.getItemId()==android.R.id.home)
        finish();
    return super.onOptionsItemSelected(item);
}

@Override
protected void onPause() {
    savelevel();
    super.onPause();
    finish();
}

private void savelevel(){
    SharedPreferences savechange = this.getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = savechange.edit();
    editor.putInt("lvl",l);
    editor.commit();
}

private void loadlvl(){
    SharedPreferences savechange = this.getPreferences( Context.MODE_PRIVATE);
    level=savechange.getInt("lvl",-1);

}

}

Body:
In addition to the Apollo answer. Worked with a similar task, so I decided to supplement answer.

Create Level class:

@Entity
public class Level {
    @PrimaryKey
    public int id;

    @ColumnInfo(name = "number")
    public int number;

    @ColumnInfo(name = "level_name")
    public String levelName;

    @ColumnInfo(name = "is_open")
    public boolean isOpen;

    public Level(int id, int number, String levelName, boolean isOpen) {
        this.id = id;
        this.levelName = levelName;
        this.isOpen = isOpen;
        this.number = number;
    }
}

Dao class:

@Dao
public interface LevelDao {
    @Insert
    void insertAll(Level... levels);

    @Query("UPDATE level SET is_open = :isOpen WHERE level_name = :levelName")
    void updateLevel(String levelName, boolean isOpen);

    @Query("SELECT * FROM level WHERE number LIKE :numberLevel")
    Level findByNumber(int numberLevel);
    ...
}

LevelDatabase class:

@Database(entities = {Level.class}, version = 1)
public abstract class LevelDatabase extends RoomDatabase {
    public abstract LevelDao levelDao();
}

When you have first start of application, open only the first level:

AsyncTask.execute(() -> {
    dbLevels = Room.databaseBuilder(this.getApplicationContext(), LevelDatabase.class,
        "levels-database").addCallback(dbCallback).build();
    LevelDao dao = dbLevels.levelDao();
});
...
// only called once
RoomDatabase.Callback dbCallback = new RoomDatabase.Callback() {
    public void onCreate(@NonNull SupportSQLiteDatabase db) {
        Executors.newSingleThreadScheduledExecutor().execute(() -> {
            Level level1 = new Level(0, 1, "level1", true);
            Level level2 = new Level(1, 2, "level2", false);
            dbLevels.levelDao().insertAll(level1, level2);
        });
    }
};

To open a level during the game:

AsyncTask.execute(() -> {
    LevelDatabase dbLevels = Room.databaseBuilder(gameActivity.getApplicationContext(),
        LevelDatabase.class, "levels-database").build();
    LevelDao dao = dbLevels.levelDao();
    dao.updateLevel("level2", true);
});

Check if open:

dao.findByNumber(2).isOpen;


问:
Unable to add firewall rules
I am trying to add firewall rule But it can't be added(Eror: Failed to add rule ....Please add it manually). Then I have try to add it manually but problem is still cant save rule even manually (Error :Failed to Save Server Firewall Rules)
This was running before some days but not working now. Unable to access azure sql database. Please help me to solve this </p>

答:
In Case this helps anyone:
I was able to add a firewall rule by deleting some existing rules then adding a new one. Be careful when deleting the existing rules so, that may not potentially influence any client accessing the server.</p>

Title: Unable to add firewall rules


问:
Gource on Windows
We're having problems on windows creating a video file from gource (gource). We can run gource and watch the video live but don't seem to be able to get any useful physical output.</p>

答:
Presets are now deprecated.

Here's what I used.

```<code>gource -f -3840x2160 --camera-mode  track  --file-idle-time 150  --max-file-lag 4 --seconds-per-day 2 --highlight-all-users --output-framerate 30 --output-ppm-stream output.ppm

ffmpeg -i output.ppm -c:v libx264 -crf 24 -preset veryslow output.mp4
</code>```

More info here:

https://superuser.com/questions/490683/cheat-sheets-and-presets-settings-that-actually-work-with-ffmpeg-1-0

FFmpeg does not include text file based presets and profiles anymore
  for libx264, i.e. what you've used with the -vpre option. These have
  been depreciated and removed in favor of accessing the actual x264
  presets, profiles (and tunes) with the -preset, -profile:v, and -tune
  options. The old text files only emulated the official x264 presets
  and profiles, and due to several limitations could not offer full
  functionality that the new system provides. It is also much easier to
  maintain.

Title: Gource on Windows

Body:
Presets are now deprecated.

Here's what I used.

gource -f -3840x2160 --camera-mode  track  --file-idle-time 150  --max-file-lag 4 --seconds-per-day 2 --highlight-all-users --output-framerate 30 --output-ppm-stream output.ppm

ffmpeg -i output.ppm -c:v libx264 -crf 24 -preset veryslow output.mp4

More info here:

https://superuser.com/questions/490683/cheat-sheets-and-presets-settings-that-actually-work-with-ffmpeg-1-0

FFmpeg does not include text file based presets and profiles anymore
  for libx264, i.e. what you've used with the -vpre option. These have
  been depreciated and removed in favor of accessing the actual x264
  presets, profiles (and tunes) with the -preset, -profile:v, and -tune
  options. The old text files only emulated the official x264 presets
  and profiles, and due to several limitations could not offer full
  functionality that the new system provides. It is also much easier to
  maintain.


问:
"psql: could not connect to server" on OSX: no postmaster.pid to delete
This weekend, I upgraded OSX Catalina (to 10.15.4) and XCode (from 11.2 to 11.4). I also ran brew upgrade, which may have upgraded Postgres, though I'm not sure. Anyway, I currently have Postgres 11.4 installed.

But now I can't connect to Postgres:

```<code>% brew services stop postgresql
% brew services start postgresql
% psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
</code>```

I've read all the answers suggesting deleting postmaster.pid, but there's no postmaster.pid file that I can find to delete - not in /usr/local/var/postgres or anywhere else.

What should I do?

UPDATE: If I try to start with pg_ctl (rather than brew services) then I see this error:

```<code>% pg_ctl start -D /usr/local/var/postgres
waiting for server to start....2020-04-14 12:20:36.279 BST [99028] LOG:  listening on IPv6 address "::1", port 5432
2020-04-14 12:20:36.279 BST [99028] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-04-14 12:20:36.280 BST [99028] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2020-04-14 12:20:36.290 BST [99028] LOG:  redirecting log output to logging collector process
2020-04-14 12:20:36.290 BST [99028] HINT:  Future log output will appear in directory "log".
dyld: lazy symbol binding failed: Symbol not found: _RAND_cleanup
  Referenced from: /usr/local/Cellar/postgresql/11.4/bin/postgres
  Expected in: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib

dyld: Symbol not found: _RAND_cleanup
  Referenced from: /usr/local/Cellar/postgresql/11.4/bin/postgres
  Expected in: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib

 stopped waiting
</code>```

So I wonder if it could be something to do with libcrypto?

答:
Same issue after upgrading to MacOS 10.15.5, but with postgres 9.4.18
This version indeed has a dependency with libssl.1.0.0.dylib.

```<code>> otool -L '/usr/local/Cellar/postgresql@9.4/9.4.18/bin/postgres'
/usr/local/Cellar/postgresql@9.4/9.4.18/bin/postgres:
    /usr/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.9.0)
    /usr/lib/libpam.2.dylib (compatibility version 3.0.0, current version 3.0.0)
    /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/Kerberos.framework/Versions/A/Kerberos (compatibility version 5.0.0, current version 6.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.50.4)
    /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP (compatibility version 1.0.0, current version 2.4.0)
</code>```

What fixed it was to upgrade postgres.

```<code>> brew upgrade 'postgresql@9.4'
==> Upgrading 1 outdated package:
postgresql@9.4 9.4.18 -> 9.4.26
</code>```

Then

```<code>> otool -L '/usr/local/Cellar/postgresql@9.4/9.4.26/bin/postgres'
/usr/local/Cellar/postgresql@9.4/9.4.26/bin/postgres:
    /usr/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.9.0)
    /usr/lib/libpam.2.dylib (compatibility version 3.0.0, current version 3.0.0)
    /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib (compatibility version 1.1.0, current version 1.1.0)
    /usr/local/opt/openssl@1.1/lib/libcrypto.1.1.dylib (compatibility version 1.1.0, current version 1.1.0)
    /System/Library/Frameworks/Kerberos.framework/Versions/A/Kerberos (compatibility version 5.0.0, current version 6.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.100.1)
    /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP (compatibility version 1.0.0, current version 2.4.0)
</code>```

And starting postgres is now OK.

```<code>> pg_ctl -D /usr/local/var/postgresql@9.4 start
</code>```

Body:
This weekend, I upgraded OSX Catalina (to 10.15.4) and XCode (from 11.2 to 11.4). I also ran brew upgrade, which may have upgraded Postgres, though I'm not sure. Anyway, I currently have Postgres 11.4 installed.

But now I can't connect to Postgres:

% brew services stop postgresql
% brew services start postgresql
% psql
psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

I've read all the answers suggesting deleting postmaster.pid, but there's no postmaster.pid file that I can find to delete - not in /usr/local/var/postgres or anywhere else.

What should I do?

UPDATE: If I try to start with pg_ctl (rather than brew services) then I see this error:

% pg_ctl start -D /usr/local/var/postgres
waiting for server to start....2020-04-14 12:20:36.279 BST [99028] LOG:  listening on IPv6 address "::1", port 5432
2020-04-14 12:20:36.279 BST [99028] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2020-04-14 12:20:36.280 BST [99028] LOG:  listening on Unix socket "/tmp/.s.PGSQL.5432"
2020-04-14 12:20:36.290 BST [99028] LOG:  redirecting log output to logging collector process
2020-04-14 12:20:36.290 BST [99028] HINT:  Future log output will appear in directory "log".
dyld: lazy symbol binding failed: Symbol not found: _RAND_cleanup
  Referenced from: /usr/local/Cellar/postgresql/11.4/bin/postgres
  Expected in: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib

dyld: Symbol not found: _RAND_cleanup
  Referenced from: /usr/local/Cellar/postgresql/11.4/bin/postgres
  Expected in: /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib

 stopped waiting

So I wonder if it could be something to do with libcrypto?

Body:
Same issue after upgrading to MacOS 10.15.5, but with postgres 9.4.18
This version indeed has a dependency with libssl.1.0.0.dylib.

> otool -L '/usr/local/Cellar/postgresql@9.4/9.4.18/bin/postgres'
/usr/local/Cellar/postgresql@9.4/9.4.18/bin/postgres:
    /usr/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.9.0)
    /usr/lib/libpam.2.dylib (compatibility version 3.0.0, current version 3.0.0)
    /usr/local/opt/openssl/lib/libssl.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    /usr/local/opt/openssl/lib/libcrypto.1.0.0.dylib (compatibility version 1.0.0, current version 1.0.0)
    /System/Library/Frameworks/Kerberos.framework/Versions/A/Kerberos (compatibility version 5.0.0, current version 6.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.50.4)
    /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP (compatibility version 1.0.0, current version 2.4.0)

What fixed it was to upgrade postgres.

> brew upgrade 'postgresql@9.4'
==> Upgrading 1 outdated package:
postgresql@9.4 9.4.18 -> 9.4.26

Then

> otool -L '/usr/local/Cellar/postgresql@9.4/9.4.26/bin/postgres'
/usr/local/Cellar/postgresql@9.4/9.4.26/bin/postgres:
    /usr/lib/libxml2.2.dylib (compatibility version 10.0.0, current version 10.9.0)
    /usr/lib/libpam.2.dylib (compatibility version 3.0.0, current version 3.0.0)
    /usr/local/opt/openssl@1.1/lib/libssl.1.1.dylib (compatibility version 1.1.0, current version 1.1.0)
    /usr/local/opt/openssl@1.1/lib/libcrypto.1.1.dylib (compatibility version 1.1.0, current version 1.1.0)
    /System/Library/Frameworks/Kerberos.framework/Versions/A/Kerberos (compatibility version 5.0.0, current version 6.0.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.100.1)
    /System/Library/Frameworks/LDAP.framework/Versions/A/LDAP (compatibility version 1.0.0, current version 2.4.0)

And starting postgres is now OK.

> pg_ctl -D /usr/local/var/postgresql@9.4 start


问:
OpenFire server does not work with websockets
I am not able to use OpenFire server through WebSockets. This is the code client side I use to connect to the server:

```<code>    var ws = new WebSocket('ws://35.228.94.32:7070/ws-xmpp');

    ws.onopen = () => {
        // connection opened
        console.log('open')
    };

    ws.onmessage = (e) => {
        // a message was received
        console.log(e.data);
    };

    ws.onerror = (e) => {
        // an error occurred
        console.log("Error occured", e, e.message);
    };

    ws.onclose = (e) => {
        // connection closed
        console.log("Closing: ", e);
    };
</code>```

This is the error I receive:

Error occured {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"} failed to connect to /35.228.94.32 (port 7070) from
  /192.168.232.2 (port 54028) after 10000ms

Closing:  {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"}

I think it is a problem of OpenFire with websockets because if I try using xmpp protocol, it works. Can you help me?

答: I've found the problem and it was not related to OpenFire. I run OpenFire on a Google Cloud machine and, by default, Google uses a firewall to block incoming requests. Hence, allowing requests to port 7070, it works. </p>

Body:
I am not able to use OpenFire server through WebSockets. This is the code client side I use to connect to the server:

    var ws = new WebSocket('ws://35.228.94.32:7070/ws-xmpp');

    ws.onopen = () => {
        // connection opened
        console.log('open')
    };

    ws.onmessage = (e) => {
        // a message was received
        console.log(e.data);
    };

    ws.onerror = (e) => {
        // an error occurred
        console.log("Error occured", e, e.message);
    };

    ws.onclose = (e) => {
        // connection closed
        console.log("Closing: ", e);
    };

This is the error I receive:

Error occured {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"} failed to connect to /35.228.94.32 (port 7070) from
  /192.168.232.2 (port 54028) after 10000ms

Closing:  {"isTrusted": false, "message": "failed to connect to
  /35.228.94.32 (port 7070) from /192.168.232.2 (port 54028) after
  10000ms"}

I think it is a problem of OpenFire with websockets because if I try using xmpp protocol, it works. Can you help me?


问:
'ng' is not recognized as an internal or external command, on windows 64 bit system
I have successfully installed node 8.11.1 and npm 5.6.0
After that I have installed angular CLI also as below

npm install -g @angular/cli

When I am trying to create project using below command

ng new MyApp

I am getting error as "ng is not recognized as an internal or external command, operable program or batch file"

Please provide solution for the same if I am doing anythin wrong please let me know.

Complete details are showing in attached screen shot

答:
ng is not recognized as an internal or external command, operable program or batch file

Many of us has face this error, while working with angular in windows
system. So to solve this error just in command prompt/Power shell,  u
have to install the lower version of angular or the same version of
angular as that of ur project of angular version.

You have to run command npm i @angular/cli at
C:\Users\Dell\AppData\roaming\npm>  at this file path and all the
error of ng will resolved


问:
How to configure an Android Virtual Device to work on my home computer
My computer confguration is:
Processor: Interl Celeron 1.8 MHz
RAM: 1 GB

When I've run Android emulator it stuck in a cycle, because of lack of memory. How to setup it to run on my computer? Is there any chance?
intepenit

Thanks.

答: If you just want to run your applications (no debug) then you could try YouWave</p>


问:
Custom typing definitions file is ignored after Upgrade to Angular 9
First, the project was building perfectly when it was in V8.x, I didn.t changed any thing.

I called

ng update @angular/cli --force to update, the '--force' is only to bypass one package i.e. angular-in-memory-web-api

I have a definition file that contains some definition :

```<code>// *********** typings.d.ts

 /* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
   id: string;
}

declare var KTMenu: any;
declare var KTOffcanvas: any;
declare var KTScrolltop: any;
declare var KTHeader: any;
declare var KTToggle: any;
declare var KTUtil: any;
declare var KTPortlet: any;
declare var KTDialog: any;
declare var KTWizard: any;
declare var Chart: any;

declare module "*.png" {
    const content: any;
   export default content;
}

declare module "*.html" {
   const content: any;
   export default content;
}

declare module "*.jpg" {
     const content: any;
   export default content;
 }

declare module "*.svg" {
   const content: any;
   export default content;
 }
</code>```

the tsconfig

```<code> // tsconfig.json

 {
        "compileOnSave": false,
        "compilerOptions": {
        "resolveJsonModule": true,
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "module": "esnext",
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2018",
            "dom"
        ]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "strictInjectionParameters": true
    }
 }
</code>```

the tscoconfig.app.json

```<code> {
   "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
     "baseUrl": "./",
     "types": []
   },
  "files": [
    "main.ts",
    "polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
   ]
 }
</code>```

the webpack.config

```<code>    /**
    * Main file of webpack config.
    * Please do not modified unless you know what to do
    */
    const path = require("path");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const WebpackRTLPlugin = require("webpack-rtl-plugin");
    const WebpackMessages = require("webpack-messages");
    const del = require("del");

    // theme name
    const themeName = "metronic";
    // global variables
    const rootPath = path.resolve(__dirname);
    const distPath = rootPath + "/src/assets";

    const entries = {
      "css/style.angular": "./src/assets/sass/style.angular.scss"
    };

    // remove older folders and files
    (async () => {
       await del.sync(distPath + "/css", { force: true });
    })();

    const mainConfig = function () {
        return {
           mode: "development",
          stats: "errors-only",
          performance: {
             hints: false
         },
         entry: entries,
         output: {
                // main output path in assets folder
               path: distPath,
              // output path based on the entries' filename
               filename: "[name].js"
           },
          resolve: { extensions: ['.scss'] },
         plugins: [
               // webpack log message
                new WebpackMessages({
                   name: themeName,
                   logger: str => console.log(`>> ${str}`)
               }),
               // create css file
               new MiniCssExtractPlugin({
                   filename: "[name].css",
                }),
                new WebpackRTLPlugin({
                   filename: "[name].rtl.css",
               }),
              {
                  apply: (compiler) => {
                        // hook name
                        compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
                            (async () => {
                               await del.sync(distPath + "/css/*.js", { force: true });
                         })();
                        });
                    }
                },
            ],
            module: {
                rules: [
                    {//**
                        test: /\.(png|jpe?g|gif|jp2|webp|svg)$/,
                        loader: 'file-loader',
                        exclude: /node_modules/,
                        options: {
                            name: 'media/[name].[ext]'
                        }
                    },
                    //{
                    //    test: /\.(mp4)$/i,
                    //    loader: "file-loader?name=/videos/[name].[ext]",
                    //    exclude: /node_modules/
                    //},
                    {
                        test: /\.scss$/,
                        use: [
                            MiniCssExtractPlugin.loader,
                            "css-loader",
                            {
                                loader: "sass-loader",
                              options: {
                                    sourceMap: true,
                                }
                            },
                        ]
                    },
                ]
            },
        }
    };

    module.exports = function () {
       return [mainConfig()];
    };
</code>```

The problem that all variables and modules defined in the typings.d.ts are not recognized and the build command keeps showing - error TS2304: Cannot find name 'KTUtil'  — KTUtil is example

答:
I've got the same issue when I migrate to Angular 9.

I fix it just adding typings.d.ts in your tsconfig.app.json

```<code>{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "baseUrl": "./",
        "types": []
    },
    "files": ["main.ts", "polyfills.ts"],
    "include": ["src/**/*.d.ts", "typings.d.ts"]
}
</code>```

Body:
First, the project was building perfectly when it was in V8.x, I didn.t changed any thing.

I called

ng update @angular/cli --force to update, the '--force' is only to bypass one package i.e. angular-in-memory-web-api

I have a definition file that contains some definition :

// *********** typings.d.ts

 /* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
   id: string;
}

declare var KTMenu: any;
declare var KTOffcanvas: any;
declare var KTScrolltop: any;
declare var KTHeader: any;
declare var KTToggle: any;
declare var KTUtil: any;
declare var KTPortlet: any;
declare var KTDialog: any;
declare var KTWizard: any;
declare var Chart: any;

declare module "*.png" {
    const content: any;
   export default content;
}

declare module "*.html" {
   const content: any;
   export default content;
}

declare module "*.jpg" {
     const content: any;
   export default content;
 }

declare module "*.svg" {
   const content: any;
   export default content;
 }

the tsconfig

 // tsconfig.json

 {
        "compileOnSave": false,
        "compilerOptions": {
        "resolveJsonModule": true,
        "baseUrl": "./",
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "downlevelIteration": true,
        "experimentalDecorators": true,
        "module": "esnext",
        "moduleResolution": "node",
        "importHelpers": true,
        "target": "es2015",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2018",
            "dom"
        ]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "strictInjectionParameters": true
    }
 }

the tscoconfig.app.json

 {
   "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
     "baseUrl": "./",
     "types": []
   },
  "files": [
    "main.ts",
    "polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
   ]
 }

the webpack.config

    /**
    * Main file of webpack config.
    * Please do not modified unless you know what to do
    */
    const path = require("path");
    const MiniCssExtractPlugin = require("mini-css-extract-plugin");
    const WebpackRTLPlugin = require("webpack-rtl-plugin");
    const WebpackMessages = require("webpack-messages");
    const del = require("del");

    // theme name
    const themeName = "metronic";
    // global variables
    const rootPath = path.resolve(__dirname);
    const distPath = rootPath + "/src/assets";

    const entries = {
      "css/style.angular": "./src/assets/sass/style.angular.scss"
    };

    // remove older folders and files
    (async () => {
       await del.sync(distPath + "/css", { force: true });
    })();

    const mainConfig = function () {
        return {
           mode: "development",
          stats: "errors-only",
          performance: {
             hints: false
         },
         entry: entries,
         output: {
                // main output path in assets folder
               path: distPath,
              // output path based on the entries' filename
               filename: "[name].js"
           },
          resolve: { extensions: ['.scss'] },
         plugins: [
               // webpack log message
                new WebpackMessages({
                   name: themeName,
                   logger: str => console.log(`>> ${str}`)
               }),
               // create css file
               new MiniCssExtractPlugin({
                   filename: "[name].css",
                }),
                new WebpackRTLPlugin({
                   filename: "[name].rtl.css",
               }),
              {
                  apply: (compiler) => {
                        // hook name
                        compiler.hooks.afterEmit.tap('AfterEmitPlugin', (compilation) => {
                            (async () => {
                               await del.sync(distPath + "/css/*.js", { force: true });
                         })();
                        });
                    }
                },
            ],
            module: {
                rules: [
                    {//**
                        test: /\.(png|jpe?g|gif|jp2|webp|svg)$/,
                        loader: 'file-loader',
                        exclude: /node_modules/,
                        options: {
                            name: 'media/[name].[ext]'
                        }
                    },
                    //{
                    //    test: /\.(mp4)$/i,
                    //    loader: "file-loader?name=/videos/[name].[ext]",
                    //    exclude: /node_modules/
                    //},
                    {
                        test: /\.scss$/,
                        use: [
                            MiniCssExtractPlugin.loader,
                            "css-loader",
                            {
                                loader: "sass-loader",
                              options: {
                                    sourceMap: true,
                                }
                            },
                        ]
                    },
                ]
            },
        }
    };

    module.exports = function () {
       return [mainConfig()];
    };

The problem that all variables and modules defined in the typings.d.ts are not recognized and the build command keeps showing - error TS2304: Cannot find name 'KTUtil'  — KTUtil is example

Body:
I've got the same issue when I migrate to Angular 9.

I fix it just adding typings.d.ts in your tsconfig.app.json

{
    "extends": "../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "baseUrl": "./",
        "types": []
    },
    "files": ["main.ts", "polyfills.ts"],
    "include": ["src/**/*.d.ts", "typings.d.ts"]
}


问:
How to convert a Julian day (not date) and Gregorian year to a Gregorian date with PHP?
Here's an PHP example to go from Julian date to Gregorian date:

```<code>$jd = gregoriantojd(10,3,1975);
echo($jd . "<br />");

$gregorian = jdtogregorian($jd);
echo($gregorian);

Output:
2442689
10/3/1975
</code>```

This works if you have the full Julian date, but what if you only have a Julian day like '254' and the year '2012'? How do you get to a Gregorian date with just the Julian day and Gregorian year with PHP?

Here's a graph of Julian days:

http://landweb.nascom.nasa.gov/browse/calendar.html

Is this possible with PHP?

Edit: Based on the answers, here's what I came up with, although there may be an easier way:

```<code>$JulianDay = 77;
$Year = 1977;
$DateYear = date("Y/m/d", mktime(0, 0, 0, 1, 1, $Year));
$GregDate = new DateTime($DateYear);
$GregDate->modify("+$JulianDay day");
$Date = $GregDate->format('Y/m/d');
echo $Date; // '1977/03/19'
</code>```

答:
You can use below function in php to do the same.

```<code>function d2julian($indate) {
    $year = ltrim(date('y', $indate),'0');     /* Year part with leading zeroes stripped    */
    if ($year == 0) $outdate = '00';
    else if ($year < 10) $outdate = '0' . $year;
    else $outdate = $year;

    $day = ltrim(date('z',$indate)+1,'0');    /* Day with leading zeroes stripped            */
    if ($day < 10) $outdate .= '00' . $day;
    else if ($day < 100) $outdate .= '0' . $day;
    else $outdate .= $day;

    return $outdate;
}
</code>```

Hope this helps. Let me know in case you have any questions.

Body:
Here's an PHP example to go from Julian date to Gregorian date:

$jd = gregoriantojd(10,3,1975);
echo($jd . "
");

$gregorian = jdtogregorian($jd);
echo($gregorian);

Output:
2442689
10/3/1975

This works if you have the full Julian date, but what if you only have a Julian day like '254' and the year '2012'? How do you get to a Gregorian date with just the Julian day and Gregorian year with PHP?

Here's a graph of Julian days:

http://landweb.nascom.nasa.gov/browse/calendar.html

Is this possible with PHP?

Edit: Based on the answers, here's what I came up with, although there may be an easier way:

$JulianDay = 77;
$Year = 1977;
$DateYear = date("Y/m/d", mktime(0, 0, 0, 1, 1, $Year));
$GregDate = new DateTime($DateYear);
$GregDate->modify("+$JulianDay day");
$Date = $GregDate->format('Y/m/d');
echo $Date; // '1977/03/19'

Body:
You can use below function in php to do the same.

function d2julian($indate) {
    $year = ltrim(date('y', $indate),'0');     /* Year part with leading zeroes stripped    */
    if ($year == 0) $outdate = '00';
    else if ($year < 10) $outdate = '0' . $year;
    else $outdate = $year;

    $day = ltrim(date('z',$indate)+1,'0');    /* Day with leading zeroes stripped            */
    if ($day < 10) $outdate .= '00' . $day;
    else if ($day < 100) $outdate .= '0' . $day;
    else $outdate .= $day;

    return $outdate;
}

Hope this helps. Let me know in case you have any questions.


问:
Delete all apps and services in specific space
Is there a foundry script or command to cleanup all space apps/services, the problem that we have many apps which is related to services and you cannot delete them until you delete all apps, is there any script or command which can help ?

I dont want to hard-code all the apps and services,  is there a way for a given space delete all apps and services instances?
is it possible to make mass delete for services?

答:
You cannot delete all App from Cloudfoundry in a single shot. Cloudfoundry document doest not explain a way to delete all App.

You can delete one App at a time in cloudfoundry. Please refer below link to delete an APP.Click here

Many apps use services and routes. Deleting an app does not delete the services used by the app, and you must explicitly remove routes between your app and the Internet.


问:
WIX Installer - Unable to change and save the platform to 64 bit

IDE:- VS.NET 2013 (Update 2)

WIX version used : 3.9

Windows service MSI :- I am unable to change the platform to x64 bit and save it. If i change it to x64 option and save the build properties and close the property window, then reopen the property window again. The x86 option pops up again.. Although, the DLL's used in the project are coming as 64 bit based.

It is very annoying and frustrating. After i hit the Build on the ServiceSetup project, the .MSI file get generated. The MSI contains the windows service .exe file which unfortunately is 32 bit based. I want the windows service .exe file to be 64 bit.

Please suggest any soln.

答:
Justin's solution didn't work for me. Although I could create the x64 platform, x86 stubbornly came back as the only option. My solution is as follows:

(1) Create a new Setup Project for WiX v3.

(2) Close the solution and open the .wixproj file in an extern editor like notepad+.

(3) The file contains only PropertyGroup elements for x86. After that insert the following PropertyGroup elements:

```<code><!-- Insert -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
  <DefineConstants>Debug</DefineConstants>
  <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  <IntermediateOutputPath>obj\$(Platform)\$(Configuration)\</IntermediateOutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
  <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  <IntermediateOutputPath>obj\$(Platform)\$(Configuration)\</IntermediateOutputPath>
</PropertyGroup>
</code>```

(4) Reopen the project. Select Configuration Manager.

Under Project contexts, you can now select x64 in the drop down list. Do it.

(5) The drop down list of Active solution platform still only has x86. Select “New…” In the “New Solution Platform” dialog create the x64 platform.

(6) In the final step synchronize the settings of the solution platform with the project platform so that the four configuration | platform pairs are the same.

Source for step 3: WIX project fails building in X64 platform.

Body:
Justin's solution didn't work for me. Although I could create the x64 platform, x86 stubbornly came back as the only option. My solution is as follows:

(1) Create a new Setup Project for WiX v3.

(2) Close the solution and open the .wixproj file in an extern editor like notepad+.

(3) The file contains only PropertyGroup elements for x86. After that insert the following PropertyGroup elements:

<!-- Insert -->
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x64' ">
  <DefineConstants>Debug</DefineConstants>
  <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  <IntermediateOutputPath>obj\$(Platform)\$(Configuration)\</IntermediateOutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x64' ">
  <OutputPath>bin\$(Platform)\$(Configuration)\</OutputPath>
  <IntermediateOutputPath>obj\$(Platform)\$(Configuration)\</IntermediateOutputPath>
</PropertyGroup>

(4) Reopen the project. Select Configuration Manager.

Under Project contexts, you can now select x64 in the drop down list. Do it.

(5) The drop down list of Active solution platform still only has x86. Select “New…” In the “New Solution Platform” dialog create the x64 platform.

(6) In the final step synchronize the settings of the solution platform with the project platform so that the four configuration | platform pairs are the same.

Source for step 3: WIX project fails building in X64 platform.