问:
Teradata SQL returning previous two months, based on CURRENT_DATE
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

```<code>SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;
</code>```

Expected output is:

```<code>+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+
</code>```

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')
</code>```

and it works perfectly. The below one returns results ok, but only for 1 month.

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)
</code>```

Tried to add a comma and add the same line with -2, did not work:

```<code>AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)
</code>```

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

答:
Why not use an or</p>

```<code>select * from table where
   (SOME_DATE =  To_char(ADD_MONTHS(CURRENT_DATE , -2),'YYYY-MM') OR
   SOME_DATE =  To_char(ADD_MONTHS(CURRENT_DATE , -1),'YYYY-MM'))
</code>```

Body:
TLDR:
I want to get a table with the previous two months in Teradata, based on CURRENT_DATE. Currently I can only get the previous month:

SELECT
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM') MM;

Expected output is:

+--------+
|   MM   |
+--------+
| 2020-01|
| 2019-12|
+--------+

Long version:
I want something, that could be used in a bigger query like this, valid for every day of the year, without hardcoding the dates. The bigger query with the hardcoded dates looks like this:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN ('2020-01', '2019-12')

and it works perfectly. The below one returns results ok, but only for 1 month.

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM')
)

Tried to add a comma and add the same line with -2, did not work:

AND TO_CHAR(SOME_DATE, 'YYYY-MM') IN
(
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -1), 'YYYY-MM'),
TO_CHAR(ADD_MONTHS(CURRENT_DATE  - EXTRACT(DAY FROM CURRENT_DATE )+1, -2), 'YYYY-MM')
)

the error is:

SELECT Failed 3706: Syntax error: expected something between ')' and '.'.

Body:
Why not use an or

select * from table where
   (SOME_DATE =  To_char(ADD_MONTHS(CURRENT_DATE , -2),'YYYY-MM') OR
   SOME_DATE =  To_char(ADD_MONTHS(CURRENT_DATE , -1),'YYYY-MM'))


来源: stackexchange

问:
How to create Progress Bar like Image in Android
How to create below Image type of Progress ring in my Android app. I Want to show it 10 second before my whole app is loading on device. and also I want to rotate it. like window device rotate. Any Help be appreciated. I am new to Andorid.

Image :

答:
Use Lottie animation.
See: https://github.com/airbnb/lottie-android
The LottieDrawable from library contains method progress(), which sets right frame if loaded image is progress image.

ContentLicense: CC BY-SA 3.0

ContentLicense: CC BY-SA 4.0


问:
Hibernate not respecting MySQL auto_increment primary key field
I am trying to learn how Hibernate works, and I am running into an almost unacceptable learning curve. I can't see how to get Hibernate to respect the auto_increment policy for my objects. Instead, it is overwriting entries in the database with existing IDs, beginning with 1.

I have a simple Foo object, backed by a MySQL table defined like this:

```<code>CREATE TABLE `Foo` (
  `fooId` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`fooId`),
)
</code>```

I have confirmed that inserting multiple Foo objects by hand with SQL (insert into Foo values();) does the right thing.

My Java class has the ID specified using annotations like this:

```<code>@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="fooId")
private Integer id;
</code>```

I then execute some test code that simply instantiates Foo objects and saves them to the database (using session.save(obj)). It seems that it uses its own primary key sequence, beginning with one, and does not look at the table's key policy. It overwrites whatever was there.

I have tried variations on the @GeneratedValue bit (using all possible strategies, leaving off the parenthetic clause). Somebody even suggested leaving off the GeneratedValue entirely. Nothing seems to work.

Am I leaving something out? What am I missing? Is Hibernate really this hard?

(If anybody has an alternative Java database persistence option, please suggest one. I am making prototypes, not long-lasting mondo-engineered projects.)

答:
I think GenerationType.AUTO is right as is <id ...><generator class="native" /></id>

Picks an appropriate strategy for the particular database.

http://www.hibernate.org/hib_docs/ejb3-api/javax/persistence/GenerationType.html

http://www.hibernate.org/hib_docs/reference/en/html/mapping.html

OwnerDisplayName: Gabe Johnson

ContentLicense: CC BY-SA 2.5

Body:
I am trying to learn how Hibernate works, and I am running into an almost unacceptable learning curve. I can't see how to get Hibernate to respect the auto_increment policy for my objects. Instead, it is overwriting entries in the database with existing IDs, beginning with 1.

I have a simple Foo object, backed by a MySQL table defined like this:

CREATE TABLE `Foo` (
  `fooId` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`fooId`),
)

I have confirmed that inserting multiple Foo objects by hand with SQL (insert into Foo values();) does the right thing.

My Java class has the ID specified using annotations like this:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="fooId")
private Integer id;

I then execute some test code that simply instantiates Foo objects and saves them to the database (using session.save(obj)). It seems that it uses its own primary key sequence, beginning with one, and does not look at the table's key policy. It overwrites whatever was there.

I have tried variations on the @GeneratedValue bit (using all possible strategies, leaving off the parenthetic clause). Somebody even suggested leaving off the GeneratedValue entirely. Nothing seems to work.

Am I leaving something out? What am I missing? Is Hibernate really this hard?

(If anybody has an alternative Java database persistence option, please suggest one. I am making prototypes, not long-lasting mondo-engineered projects.)

OwnerDisplayName: cherouvim


问:
how to create a mutlilingual route in Zend Framework?
I need a route in Zend Framework that maps the following uri's to EventController > indexAction.

```<code>:lang/programma/:name/:page
:lang/programme/:name/:page
:lang/event/:name/:page
</code>```

The second parameter has to be "programma" OR "programme" OR "event".
 I could simply create 3 different routes for this but I think it is possible to do this in just one.

Any idea how to achieve this?

答: Use Zend_Translate and Zend_Controller_Router_Route::setDefaultTranslator(). A detailed description can be found in the Documentation.

Body:
I need a route in Zend Framework that maps the following uri's to EventController > indexAction.

:lang/programma/:name/:page
:lang/programme/:name/:page
:lang/event/:name/:page

The second parameter has to be "programma" OR "programme" OR "event".
 I could simply create 3 different routes for this but I think it is possible to do this in just one.

Any idea how to achieve this?


问:
Beans created by ImportBeanDefinitionRegistrar during autoconfiguration are not eligible for all bean postprocessors
I have implemented ImportBeanDefinitionRegistrar to create bean definitions from external source. It has to be registrar since I do not know in advance how many bean definitions will be created.

When I use the registrar on my Application class like this:

```<code>@SpringBootApplication
@Import(GenesysRegistrar.class)
public class IntegrationServer {
...
}
</code>```

everything works fine.

I wanted to make the import automatic for every application that uses the JAR that contains the registrar so I have created following class:

```<code>@Configuration
@Import(GenesysRegistrar.class)
public class GenesysAutoConfiguration {
    /**/
}

</code>```

and registered it in META-INF/spring.factories under key org.springframework.boot.autoconfigure.EnableAutoConfiguration.

Now auto-configuration works, but I get following messages in log:

```<code>Bean 'xxx' of type [XXX] is not eligible for getting processed by all BeanPostProcessors
</code>```

What is the difference between importing the registry from aplication class and from autoconfiguration class? I have found that following post processors are created AFTER my beans:

```<code>methodValidationPostProcessor
persistenceExceptionTranslationPostProcessor
webServerFactoryCustomizerBeanPostProcessor
errorPageRegistrarBeanPostProcessor
</code>```

I have tried to put @AutoConfigureOrder(Integer.MAX_VALUE) on my auto-configuration class, but it does not change anything.

Any ideas how can I fix the order so beans from definitions created by my registrar are processed after all post processors? Why Spring creates them before all post processors? Any why the issue does not happen when using @Import on application class?

答:
Early initialized beans are dependencies injected to other bean factoy by constructor injection.

If the bean factory uses property injection instead of construcotr injection it does not happen.

Question is if constructor injection on factory bean is "bad practise" - have not found anything that prohibits it.

Created ticket to spring-boot (as it happens only during boot auto-configuraiton):
Issue #20219

Body:
I have implemented ImportBeanDefinitionRegistrar to create bean definitions from external source. It has to be registrar since I do not know in advance how many bean definitions will be created.

When I use the registrar on my Application class like this:

@SpringBootApplication
@Import(GenesysRegistrar.class)
public class IntegrationServer {
...
}

everything works fine.

I wanted to make the import automatic for every application that uses the JAR that contains the registrar so I have created following class:

@Configuration
@Import(GenesysRegistrar.class)
public class GenesysAutoConfiguration {
    /**/
}

and registered it in META-INF/spring.factories under key org.springframework.boot.autoconfigure.EnableAutoConfiguration.

Now auto-configuration works, but I get following messages in log:

Bean 'xxx' of type [XXX] is not eligible for getting processed by all BeanPostProcessors

What is the difference between importing the registry from aplication class and from autoconfiguration class? I have found that following post processors are created AFTER my beans:

methodValidationPostProcessor
persistenceExceptionTranslationPostProcessor
webServerFactoryCustomizerBeanPostProcessor
errorPageRegistrarBeanPostProcessor

I have tried to put @AutoConfigureOrder(Integer.MAX_VALUE) on my auto-configuration class, but it does not change anything.

Any ideas how can I fix the order so beans from definitions created by my registrar are processed after all post processors? Why Spring creates them before all post processors? Any why the issue does not happen when using @Import on application class?


问:
How to pass a function with arguments and stop_condition in jthread?
I am trying to do something like this

```<code>#include <iostream>
#include <thread>
#include <chrono>

void doWork(char a, std::stop_token st = {}) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}

int main() {
    std::jthread t1{doWork, 'A'}, // error
                 t2{doWork, 'B'}; // error
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
</code>```

But it won't compile on gcc trunk with -std=c++2a:

```<code>/opt/compiler-explorer/gcc-trunk-20200219/include/c++/10.0.1/thread:537:20: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues

  537 |      static_assert(is_invocable_v<decay_t<_Callable>,

      |                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  538 |       decay_t<_Args>...>,

      |       ~~~~~~~~~~~~~~~~~~
</code>```

Is it even possible to do something like this?

I assumed that it should be possible, because I've seen a similar example with lambda (here):

```<code>//...
std::jthread t([&ready, &readyMutex, &readyCV] (std::stop_token st) {
    while (!stoken.stop_requested()) {
        //...
    }
});
</code>```

答:
You are almost correct in your implementation. The constraint on the invokable is that it accepts a std::stop_token as a first argument. So switching the order in the declaration of doWork will sort it out.

```<code>void doWork(std::stop_token st, char a) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}
</code>```

The token comes from the library implementation, so its construction is not meant to worry you anyway.

Body:
I am trying to do something like this

#include <iostream>
#include <thread>
#include <chrono>

void doWork(char a, std::stop_token st = {}) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}

int main() {
    std::jthread t1{doWork, 'A'}, // error
                 t2{doWork, 'B'}; // error
    std::this_thread::sleep_for(std::chrono::milliseconds(50));
}

But it won't compile on gcc trunk with -std=c++2a:

/opt/compiler-explorer/gcc-trunk-20200219/include/c++/10.0.1/thread:537:20: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues

  537 |      static_assert(is_invocable_v<decay_t<_Callable>,

      |                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  538 |       decay_t<_Args>...>,

      |       ~~~~~~~~~~~~~~~~~~

Is it even possible to do something like this?

I assumed that it should be possible, because I've seen a similar example with lambda (here):

//...
std::jthread t([&ready, &readyMutex, &readyCV] (std::stop_token st) {
    while (!stoken.stop_requested()) {
        //...
    }
});

Body:
You are almost correct in your implementation. The constraint on the invokable is that it accepts a std::stop_token as a first argument. So switching the order in the declaration of doWork will sort it out.

void doWork(std::stop_token st, char a) {
    while (!st.stop_requested()) {
        std::cout << a << '\n';
    }
}

The token comes from the library implementation, so its construction is not meant to worry you anyway.


问:
PartyNotKnownOnLedger (Party not known on ledger)
I am using DAML-on-Fabric (running DAML based on Hyperledger Fabric).

When I login with Alice and issue a IOU, the app shows PartyNotKnownOnLedger (Party not known on ledger).

How do I fix this?

答:
As of DAML 0.13.52, the sandbox shipped in the SDK implicitly "allocates" parties for you. This is usually not the case when using actual distributed ledgers (such as Hyperledger Fabric).

To allocate the party, you can either use the SDK assistant daml ledger allocate-parties command or apply the allocateParty function using DAML script (documentation here).

Alternatively, apps from other languages can use the AllocateParty RPC in the PartyManagementService in the Ledger API. The Ledger API has available bindings in Java and Scala; there is no available wrapper for the PartyManagementService but you can use the raw gRPC-generated code to use them (more on the Ledger API here).

Since the Ledger API is defined with gRPC you can use any other language with gRPC support (more on the topic here).


问:
How to show the input field value in another input field using reactjs?
I'm new to reactjs. I'm bit confused how to do it, i want to write something in first input field and at the same time it should reflect on the second input field. If i delete the value in the first input field then it should delete the second input field also. Can anybody help me in this?

Here is the Code:

```<code>import React, { Component } from "react";
import "./styles.css";
import { Form, Input, Button } from "semantic-ui-react";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      email: ""
    };
  }

  handleName = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    return (
      <div className="App">
        <Form>
          <Input
            placeholder="Name"
            onChange={this.handleName}
            name="name"
            value={this.state.name}
          />
          <Input
            placeholder="Email"
            onChange={this.handleName}
            name="email"
            value="@yahoo.com"
          />
        </Form>
        <Button>Submit</Button>
      </div>
    );
  }
}
export default App;

</code>```

code: "https://codesandbox.io/s/reverent-fast-3w8sz"

答: If you want to keep yahoo.com as suffix with the in the second input replace the value prop of the input field with value={`${this.state.name}yahoo.com`}. Hope this is what you are looking for

Body:
I'm new to reactjs. I'm bit confused how to do it, i want to write something in first input field and at the same time it should reflect on the second input field. If i delete the value in the first input field then it should delete the second input field also. Can anybody help me in this?

Here is the Code:

import React, { Component } from "react";
import "./styles.css";
import { Form, Input, Button } from "semantic-ui-react";

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: "",
      email: ""
    };
  }

  handleName = event => {
    this.setState({ [event.target.name]: event.target.value });
  };

  render() {
    return (

        <Form>
          <Input
            placeholder="Name"
            onChange={this.handleName}
            name="name"
            value={this.state.name}
          />
          <Input
            placeholder="Email"
            onChange={this.handleName}
            name="email"
            value="@yahoo.com"
          />
        </Form>
        <Button>Submit</Button>

    );
  }
}
export default App;

code: "https://codesandbox.io/s/reverent-fast-3w8sz"


问:
Should notifications be removed using removeObserver(self) in iOS?
Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

```<code>override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}
</code>```

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

```<code>override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}
</code>```

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self.

Is there any guideline from Apple about best practice of removing notification observers?

答:
The thing is it's not future safe to remove all notification in viewWillDisappear. It's not a good practice for an obvious reason but it's not documented.
After iOS 9 it's not necessary to call removeObserver because iOS not try to notify deallocated objects. In your case, you want to listen even if view controller is not visible but present in the navigation stack
you should do in deinit

```<code>    class ViewController: UIViewController {
    deinit {
     NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
    }
   }
</code>```

Body:
Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self.

Is there any guideline from Apple about best practice of removing notification observers?

Body:
The thing is it's not future safe to remove all notification in viewWillDisappear. It's not a good practice for an obvious reason but it's not documented.
After iOS 9 it's not necessary to call removeObserver because iOS not try to notify deallocated objects. In your case, you want to listen even if view controller is not visible but present in the navigation stack
you should do in deinit

    class ViewController: UIViewController {
    deinit {
     NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
    }
   }


问:
Regex ignore the delimiter in parentheses
Good morning,
I need a little of your help.
I need to split the text using REGEX, but to omit the content in parentheses

preg_match_all('/\((?:[^()]|(?R))+\)|\'[^\']*\'|[^(),]+/', $input_lines, $output_array);

I have this string:
Test A, Test B, Test C (data1, data1)

And pregmatch we do this:

```<code>0   =>  Test A
1   =>   Test B
2   =>   Test C
3   =>  (data1, data1)
</code>```

How do I achieve this result?

```<code>0   =>  Test A
1   =>  Test B
2   =>  Test C (data1, data1)
</code>```

I need to ignore the content in parentheses and separate only the rest.

Thank you in advance for any help.

EDIT

This aventually resolved my situation. I tried to use preg split.

preg_split('/,(?![^(]*\)) /', $input_line);

答:
What you might do is use the recursive pattern to recurse the first subpattern using (?1) to match all the parenthesis so the split does not split inside the parenthesis as well and use SKIP FAIL.

Then split on a comma followed by 0+ horizontal whitespace chars

```<code>(\((?:[^()]++|(?1))*\))(*SKIP)(*F)|,\h*
</code>```

Regex demo | Php demo

```<code>$re = '/(\((?:[^()]++|(?1))*\))(*SKIP)(*F)|,\h*/';
$strings = [
    "Test A, Test B, Test C (data1, data1)",
    "Test A, Test B, Test C (data1, data1), Test D (data1, data1), Test E (data1, data1(data, data))",
    "Test A, Test B, Test C (data1, data1), Test D (data1, data1), Test E ((data1, data1))"
];

foreach($strings as $s) {
    print_r(preg_split($re, $s));
}
</code>```

Output

```<code>Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
)
Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
    [3] => Test D (data1, data1)
    [4] => Test E (data1, data1(data, data))
)
Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
    [3] => Test D (data1, data1)
    [4] => Test E ((data1, data1))
)
</code>```

Body:
Good morning,
I need a little of your help.
I need to split the text using REGEX, but to omit the content in parentheses

preg_match_all('/\((?:[^()]|(?R))+\)|\'[^\']*\'|[^(),]+/', $input_lines, $output_array);

I have this string:
Test A, Test B, Test C (data1, data1)

And pregmatch we do this:

0   =>  Test A
1   =>   Test B
2   =>   Test C
3   =>  (data1, data1)

How do I achieve this result?

0   =>  Test A
1   =>  Test B
2   =>  Test C (data1, data1)

I need to ignore the content in parentheses and separate only the rest.

Thank you in advance for any help.

EDIT

This aventually resolved my situation. I tried to use preg split.

preg_split('/,(?![^(]*\)) /', $input_line);

Body:
What you might do is use the recursive pattern to recurse the first subpattern using (?1) to match all the parenthesis so the split does not split inside the parenthesis as well and use SKIP FAIL.

Then split on a comma followed by 0+ horizontal whitespace chars

(\((?:[^()]++|(?1))*\))(*SKIP)(*F)|,\h*

Regex demo | Php demo

$re = '/(\((?:[^()]++|(?1))*\))(*SKIP)(*F)|,\h*/';
$strings = [
    "Test A, Test B, Test C (data1, data1)",
    "Test A, Test B, Test C (data1, data1), Test D (data1, data1), Test E (data1, data1(data, data))",
    "Test A, Test B, Test C (data1, data1), Test D (data1, data1), Test E ((data1, data1))"
];

foreach($strings as $s) {
    print_r(preg_split($re, $s));
}

Output

Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
)
Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
    [3] => Test D (data1, data1)
    [4] => Test E (data1, data1(data, data))
)
Array
(
    [0] => Test A
    [1] => Test B
    [2] => Test C (data1, data1)
    [3] => Test D (data1, data1)
    [4] => Test E ((data1, data1))
)


问:
Change class for selected div only
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

```<code>@for (int i = 0; i < 5; i++)
{
    <div class="@divClass" @onclick="_ => ChangeDivClass()">@i</div>
}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}
</code>```

答:
try below code:

```<code>@if (items != null)
{
    @foreach (var item in items)
    {
        <div class="@RenderDomClass(item.Id)" @onclick="_ => ChangeColor(item.Id)">@item.Id</div>
    }
}

@functions{
    //Instead of these Mock data you should load your own data
    IList<Foo> items = new List<Foo>()
         {
            new Foo { Id =1, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =2, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =3, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =4, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =5, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =6, DomClasses=new List<string>(){string.Empty}},

        };

private void ChangeColor(int id)
{
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Contains("red"))
    {
        domClasses.Remove("red");
    }
    else
    {
        domClasses.Add("red");
    }

    RenderDomClass(id);
}

private string RenderDomClass(int id)
{
    var domClass = string.Empty;
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Count > 0)
    {
        foreach (var item in domClasses)
        {
            domClass += $" {item}";
        }
    }

    return domClass;
}

public class Foo
{
    public int Id { get; set; }
    public List<string> DomClasses { get; set; }
}
}
</code>```

The result of the above code is:

Fell free to ask question. Good Luck.

Title: Change class for selected div only

Body:
I would like it to only change the class for the clicked div. Currently it will change the class for all divs. I have written this as a Blazor component.

@for (int i = 0; i < 5; i++)
{

 ChangeDivClass()">@i

}

@code
{
    String divClass;

    private void ChangeDivClass()
    {
        if (divClass == "red")
        {
            divClass = String.Empty;
        }
        else
        {
            divClass = "red";
        }
    }
}

Body:
try below code:

@if (items != null)
{
    @foreach (var item in items)
    {
        <div class="@RenderDomClass(item.Id)" @onclick="_ => ChangeColor(item.Id)">@item.Id</div>
    }
}

@functions{
    //Instead of these Mock data you should load your own data
    IList<Foo> items = new List<Foo>()
         {
            new Foo { Id =1, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =2, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =3, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =4, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =5, DomClasses=new List<string>(){string.Empty}},
            new Foo { Id =6, DomClasses=new List<string>(){string.Empty}},

        };

private void ChangeColor(int id)
{
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Contains("red"))
    {
        domClasses.Remove("red");
    }
    else
    {
        domClasses.Add("red");
    }

    RenderDomClass(id);
}

private string RenderDomClass(int id)
{
    var domClass = string.Empty;
    var domClasses = items.SingleOrDefault(item => item.Id == id).DomClasses;
    if (domClasses.Count > 0)
    {
        foreach (var item in domClasses)
        {
            domClass += $" {item}";
        }
    }

    return domClass;
}

public class Foo
{
    public int Id { get; set; }
    public List<string> DomClasses { get; set; }
}
}

The result of the above code is:

Fell free to ask question. Good Luck.


问:
How to get a irrational number as a user input in python?
How to get a irrational number as a user input in python? Like squared root of 2

something like :

```<code>Irrational_Number = float(input("ENTER a Irrational Number : "))
   >>> ENTER a Irrational Number : (USER INPUT)
</code>```

and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.

How User Can do this Directly in command line python (3.8)

I searched this question everywhere but there is nothing about that...

答:
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.

That done, there's a few ways you can explore a solution:

The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:

```<code>numbers_as_words  = { "e",2.718281828459045
                      "pi",3.141592653589793
                      "phi",1.618033988749895
                      "sqr2",1.4142135623730951
                      "feet_to_meters",0.3048
                      "lbs_to_kg",0.453592
                      "miles_to_kilometers",1.60934
                      "gallons_to_litres",3.78541 }
</code>```

I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.

Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.

```<code>def replace_names_and_return_float(user_input, mapping):
    for k,v in mapping.items():
        user_input = user_input.replace(k,str(v))
    return float(user_input)

Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )
</code>```

Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.

If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.

Body:
How to get a irrational number as a user input in python? Like squared root of 2

something like :

Irrational_Number = float(input("ENTER a Irrational Number : "))
   >>> ENTER a Irrational Number : (USER INPUT)

and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.

How User Can do this Directly in command line python (3.8)

I searched this question everywhere but there is nothing about that...

Body:
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.

That done, there's a few ways you can explore a solution:

The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:

numbers_as_words  = { "e",2.718281828459045
                      "pi",3.141592653589793
                      "phi",1.618033988749895
                      "sqr2",1.4142135623730951
                      "feet_to_meters",0.3048
                      "lbs_to_kg",0.453592
                      "miles_to_kilometers",1.60934
                      "gallons_to_litres",3.78541 }

I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.

Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.

def replace_names_and_return_float(user_input, mapping):
    for k,v in mapping.items():
        user_input = user_input.replace(k,str(v))
    return float(user_input)

Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )

Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.

If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.


问:
R help - why can't I download the nortest package on my work computer?
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

```<code>install.packages("nortest")
</code>```

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

```<code>Error in read.dcf(file = tmpf) :
  Line starting '<head><title> ...' is malformed!
</code>```

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate

答: If you're on Windows, try using setInternet2 so that your IT network thinks that it is Internet Explorer connecting to the internet. Often useful for evading corporate lockdown.

Body:
I need to use R to do some stats at work. The problem is, when I try and download the nortest package, using the following function:

install.packages("nortest")

Or by selecting 'install packages' from the R menu (NB.: I am using a UK CRAN mirror), I get the following error message:

Error in read.dcf(file = tmpf) :
  Line starting '<title> ...' is malformed!

I spoke to the IT dept at work and they mentioned that because R is open source, there are blocks on downloading certain things - and we ran a check and the system was blocking my download of nortest, for security reasons. The IT guy did say he wouldn't mind lowering the block just once, if I could then save the (zip?) file so I didn't need to access the internet every time I loaded up the package.

The problem is, I have no idea how to get a copy of 'nortest' as a zip file. And then once I have it, I don't know how to save it so that it loads from a saved file rather than selecting 'install package' from the R menu.

Any help would be very much appreciated.

Thanks,

Kate


问:
how to get field value from model
I have a model for registering with some fields.
All fields are models I fill in through the form like this.

```<code>def get_name(request):
if request.method == 'POST':
    user_code = generate_code(8)
    subject = 'code'
    message = user_code
    phone=request.POST['phone']
    form = NameForm(request.POST)
    if form.is_valid():
        date_use = form.cleaned_data.get("date_visit")
        time_use = form.cleaned_data.get("time_visit")
        purpose_use = form.cleaned_data.get("purpose")
        if Registration.objects.filter(date_visit=date_use,time_visit=time_use,purpose=purpose_use).count()==0:
            Registration.objects.create(fio=request.POST['fio'],phone=request.POST['phone'],date_visit=request.POST['date_visit'],time_visit=request.POST['time_visit'],
                number_car=request.POST['number_car'],purpose=request.POST['purpose'],
                tso=request.POST['tso'])
            request.session["phone"] = phone
            request.session["code"] = user_code
            return HttpResponseRedirect('endreg')
else:
    form = NameForm()
return render(request, 'registers/detail.html', {'form': form})
</code>```

The model also has a field

```<code>date_register = models.DateTimeField(verbose_name = 'date register', auto_now_add=True)
</code>```

how can i write date_register value in request.session["date"] ?

答:
Instead of using Registration.objects.create(...) you can use .save method:

```<code>obj = Registration()
obj.fio = form.cleaned_data["fio"]
...
obj.save()
request.session["date"] = str(obj.date_register)
</code>```

Title: how to get field value from model

Body:
I have a model for registering with some fields.
All fields are models I fill in through the form like this.

def get_name(request):
if request.method == 'POST':
    user_code = generate_code(8)
    subject = 'code'
    message = user_code
    phone=request.POST['phone']
    form = NameForm(request.POST)
    if form.is_valid():
        date_use = form.cleaned_data.get("date_visit")
        time_use = form.cleaned_data.get("time_visit")
        purpose_use = form.cleaned_data.get("purpose")
        if Registration.objects.filter(date_visit=date_use,time_visit=time_use,purpose=purpose_use).count()==0:
            Registration.objects.create(fio=request.POST['fio'],phone=request.POST['phone'],date_visit=request.POST['date_visit'],time_visit=request.POST['time_visit'],
                number_car=request.POST['number_car'],purpose=request.POST['purpose'],
                tso=request.POST['tso'])
            request.session["phone"] = phone
            request.session["code"] = user_code
            return HttpResponseRedirect('endreg')
else:
    form = NameForm()
return render(request, 'registers/detail.html', {'form': form})

The model also has a field

date_register = models.DateTimeField(verbose_name = 'date register', auto_now_add=True)

how can i write date_register value in request.session["date"] ?

Body:
Instead of using Registration.objects.create(...) you can use .save method:

obj = Registration()
obj.fio = form.cleaned_data["fio"]
...
obj.save()
request.session["date"] = str(obj.date_register)


问:
How to fix SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference in Internet Explorer 11?
my code works fine on other browsers but on Internet Explorer 11 I get SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference. Does anyone know how to fix that bug? Here is my code:

var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text/plain", null)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sequence">
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="3">Yellow</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="5">Red</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="2">Green</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="1">Blue</div>
  <div draggable="true" ondragend="dragEnd()" ondragover="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="4">Orange</div>
</div></code>```

答:
I tested your code and the error occurred firstly in e.dataTransfer.setData("text/plain", null) with argument being not valid. There're two errors in this line：

IE only accepts text and URL as valid data types. You could refer to this article for explanation:

Even though Internet Explorer started out by introducing only "text" and "URL" as valid data types, HTML5 extends this to allow any MIME type to be specified. The values "text" and "URL" will be supported by HTML5 for backwards compatibility, but they are mapped to "text/plain" and "text/uri-list".

We should use a concrete value as data instead of null in IE. We can use the event target's id for the data.

So this line should be changed into: e.dataTransfer.setData("text", e.target.id).

After this, we need to change ondragover events to ondragenter as I find that ondragover won't be fired in IE. So the final code should be like below which can work well in IE 11:

```<code>var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text", e.target.id)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}
</code>```

Yellow

Red

Green

Blue

Orange

```

Online demo

Body:
my code works fine on other browsers but on Internet Explorer 11 I get SCRIPT5007: Unable to get property 'parentNode' of undefined or null reference. Does anyone know how to fix that bug? Here is my code:

var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text/plain", null)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}

Yellow

Red

Green

Blue

Orange

Body:
I tested your code and the error occurred firstly in e.dataTransfer.setData("text/plain", null) with argument being not valid. There're two errors in this line：

IE only accepts text and URL as valid data types. You could refer to this article for explanation:

Even though Internet Explorer started out by introducing only "text" and "URL" as valid data types, HTML5 extends this to allow any MIME type to be specified. The values "text" and "URL" will be supported by HTML5 for backwards compatibility, but they are mapped to "text/plain" and "text/uri-list".

We should use a concrete value as data instead of null in IE. We can use the event target's id for the data.

So this line should be changed into: e.dataTransfer.setData("text", e.target.id).

After this, we need to change ondragover events to ondragenter as I find that ondragover won't be fired in IE. So the final code should be like below which can work well in IE 11:

var selected

function dragOver(e) {
  if (isBefore(selected, e.target)) e.target.parentNode.insertBefore(selected, e.target)
  else e.target.parentNode.insertBefore(selected, e.target.nextSibling)
}

function dragEnd() {
  selected = null
}

function dragStart(e) {
  e.dataTransfer.effectAllowed = "move"
  e.dataTransfer.setData("text", e.target.id)
  selected = e.target
}

function isBefore(el1, el2) {
  var cur;
  if (el2.parentNode === el1.parentNode) {
    for (cur = el1.previousSibling; cur; cur = cur.previousSibling) {
      if (cur === el2) return true
    }
  } else return false;
}

<div class="sequence">
  <div draggable="true" ondragend="dragEnd()" ondragenter="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="3">Yellow</div>
  <div draggable="true" ondragend="dragEnd()" ondragenter="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="5">Red</div>
  <div draggable="true" ondragend="dragEnd()" ondragenter="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="2">Green</div>
  <div draggable="true" ondragend="dragEnd()" ondragenter="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="1">Blue</div>
  <div draggable="true" ondragend="dragEnd()" ondragenter="dragOver(event)" ondragstart="dragStart(event)" class="choice 2" id="4">Orange</div>
</div>

Online demo


问:
Error with redis and nodejs in kubernetes
I need to deploy web (angularjs), api (node.js) , redis. However, i am getting error reaching redis to api (node.js) using kubernetes.

```<code>[ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND redis redis:6379
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
</code>```

I tried multiple configuration but nothing worked.

```<code>const redis = new Redis('redis://redis:6379');
const redis = new Redis({ port: 6379, host: 'redis', connectTimeout: 10000 });
const client = redis.createClient(6379,"redis");
</code>```

Also, since standard redis image dont have the redis.conf, I added the redis.conf and bind 0.0.0.0 in it, protected-mode yes. I am still getting the error.

I put all the containers in one deployment i.e, web, api, redis and created the service using type: load balancer. I am able to access the application but i am getting the [ioredis] error.

```<code>Kubernetes version: 1.15.7
Cloud being used: (aws)
Installation method: kops
Host OS: ubuntu
</code>```

Any ideas and suggestion to resolve the redis error.
What is the best deployment strategy? i.e., how the web, api, redis to be distributed in k8s?

deployment yaml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-deployment
  labels:
    app: app1
    env: prod
spec:
  selector:
    matchLabels:
      app: app1
      env: prod
  replicas: 3
  template:
    metadata:
      labels:
        app: app1
        env: prod
    spec:
      containers:
      - name: web-angular-nginx
        image: xxxx.dkr.ecr.us-east-1.amazonaws.com/web
        ports:
        - containerPort: 8080
      - name: api-nodejs
        image: xxxx.dkr.ecr.us-east-1.amazonaws.com/api
        ports:
        - containerPort: 7000
      - name: xxxx.dkr.ecr.us-east-1.amazonaws.com/redis
        image: redis
        ports:
        - containerPort: 6379
</code>```

Service yaml

```<code>apiVersion: v1
kind: Service
metadata:
  name: app-svc
  labels:
    app: app1
spec:
  ports:
  - port: 80
    nodePort: 30001
    protocol: TCP
  selector:
    app: app1
    env: prod
  type: LoadBalancer
</code>```

Thanks

答:
ENOTFOUND is a connection issue - your node script is not able to connect to the Redis server at the specified address - check your redis server.

Add following line to your configuration:

```<code>const redis = require('ioredis');
</code>```

Also try delete the networks and replace redis section by:

```<code>redis:
    image: redis:latest
    command: ["redis-server", "--bind", "redis", "--port", "6379"]
</code>```

Edit NetworkManager.conf file:

```<code>$ vim /etc/NetworkManager/NetworkManager.conf
</code>```

Comment this line:

```<code>#dns=dnsmasq
</code>```

Finally

```<code>$ sudo service network-manager restart
$ sudo service docker restart
</code>```

More infromation you can find here: redis-kubernetes, ENOTFOUND, redis-enotfound.

Body:
I need to deploy web (angularjs), api (node.js) , redis. However, i am getting error reaching redis to api (node.js) using kubernetes.

[ioredis] Unhandled error event: Error: getaddrinfo ENOTFOUND redis redis:6379
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)

I tried multiple configuration but nothing worked.

const redis = new Redis('redis://redis:6379');
const redis = new Redis({ port: 6379, host: 'redis', connectTimeout: 10000 });
const client = redis.createClient(6379,"redis");

Also, since standard redis image dont have the redis.conf, I added the redis.conf and bind 0.0.0.0 in it, protected-mode yes. I am still getting the error.

I put all the containers in one deployment i.e, web, api, redis and created the service using type: load balancer. I am able to access the application but i am getting the [ioredis] error.

Kubernetes version: 1.15.7
Cloud being used: (aws)
Installation method: kops
Host OS: ubuntu

Any ideas and suggestion to resolve the redis error.
What is the best deployment strategy? i.e., how the web, api, redis to be distributed in k8s?

deployment yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: app-deployment
  labels:
    app: app1
    env: prod
spec:
  selector:
    matchLabels:
      app: app1
      env: prod
  replicas: 3
  template:
    metadata:
      labels:
        app: app1
        env: prod
    spec:
      containers:
      - name: web-angular-nginx
        image: xxxx.dkr.ecr.us-east-1.amazonaws.com/web
        ports:
        - containerPort: 8080
      - name: api-nodejs
        image: xxxx.dkr.ecr.us-east-1.amazonaws.com/api
        ports:
        - containerPort: 7000
      - name: xxxx.dkr.ecr.us-east-1.amazonaws.com/redis
        image: redis
        ports:
        - containerPort: 6379

Service yaml

apiVersion: v1
kind: Service
metadata:
  name: app-svc
  labels:
    app: app1
spec:
  ports:
  - port: 80
    nodePort: 30001
    protocol: TCP
  selector:
    app: app1
    env: prod
  type: LoadBalancer

Thanks

Body:
ENOTFOUND is a connection issue - your node script is not able to connect to the Redis server at the specified address - check your redis server.

Add following line to your configuration:

const redis = require('ioredis');

Also try delete the networks and replace redis section by:

redis:
    image: redis:latest
    command: ["redis-server", "--bind", "redis", "--port", "6379"]

Edit NetworkManager.conf file:

$ vim /etc/NetworkManager/NetworkManager.conf

Comment this line:

#dns=dnsmasq

Finally

$ sudo service network-manager restart
$ sudo service docker restart

More infromation you can find here: redis-kubernetes, ENOTFOUND, redis-enotfound.


问:
View config 'forceFit' in extjs4?
In extjs3 Ext.grid.View had a config property forceFit.

What is the equivalant to this in extjs4?

答:
forceFit itself! The property has been moved from View class to the Panel. Refer the Ext.grid.Panel documentation.

Rather than using viewConfig, you can now directly put it in config of your grid.

Title: View config 'forceFit' in extjs4?


问:
TS2339: Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

```<code> ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }
</code>```

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?

答: You need to get the current value from the BehaviorSubject with either value or getValue() and sort it like this: this.dataSource.value.sort(this.matSort).

Body:
I am looking to create a dynamic table using angular material where i can add/remove data dynamically.
Being very new to Angular , i have referred follwing stackblitz to create the table.

https://stackblitz.com/edit/angular-material-editable-table-fazhbc

While all my changes work - i am not able to sort the data at

 ngAfterViewInit() {
    this.dataSource.sort = this.matSort;
  }

The error i get
TS2339:  Property 'sort' does not exist on type 'BehaviorSubject<AbstractControl[]

is the sorting isn't supported like in material table data source or am i missing something ?


问:
How to remove blank pages after each page in pdf view ( rdlc report )
I am using RDLC report in visual studio 2012. Report seems great when view in browser but in PDF view, blank page is attached after each report page.I have been to various links but they did not work for me.Any help would be appreciated. </p>

答:
I solved my problem by changing the margins in page properties.
The page had 0,5cm in each side, so I removed, and solved the problem.</p>


问:
Split x axis for every value in graph, in Power BI
I have the following graph in Power BI:

and I'm trying to recreate the below graph from Excel (note the X axis with the months February and January, with the Operation Text:

As you can see, my attempt only displays the Operation Text rather than the month and Operation Text).

Here is what my current axis looks like:

Changing the axis to have Actual Start Date on top, rather than the Operation Text:

Makes my graph look like this:

Is it possible to achieve the same outcome as in Excel, with the values in my graph showing the two months side by side, for each operation text? If so, how can I do this?

I've tried looking into the X axis 'format' settings and wasn't able to see anything obvious to help achieve this. In addition, unfortunately the graph I'm looking to recreate is only a screenshot so I am unable to see how it achieves that outcome.

EDIT:

As suggested, I attempted to place Operation Text into the Legend field in my Visualisations section but I am unable to, due to the fact that I have two Value fields (the two columns Actual Hours and Estimated Hours).

答: Have you tried moving your date or operation text column in legend section ?..not 100% but something close to your requirement you can achieve


问:
TapGestureRecognition in Xamarin Forms Listview
I need to check if the empty part of a Xamarin Forms Listview is tapped. For example, there are 5 rows and the space below those filled rows is tapped a method should be called.
I tried adding Tapgesturerecognizer to the Listview and the page containing the listview but this didnt work.
Is there a way to check if someone tapped the empty space in the listview?</p>

```<code><ListView x:Name="ItemsListView"
                ItemsSource="{Binding Items}"
                VerticalOptions="FillAndExpand"
                HasUnevenRows="true"
                RefreshCommand="{Binding LoadItemsCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                CachingStrategy="RecycleElement"
                ItemSelected="OnItemSelected">
            <d:ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>First Item</x:String>
                    <x:String>Second Item</x:String>
                    <x:String>Third Item</x:String>
                    <x:String>Fourth Item</x:String>
                    <x:String>Fifth Item</x:String>
                    <x:String>Sixth Item</x:String>
                </x:Array>
            </d:ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10">
                            <Label Text="{Binding Text}"
                                d:Text="{Binding .}"
                                LineBreakMode="NoWrap"
                                Style="{DynamicResource ListItemTextStyle}"
                                FontSize="16" />
                            <Label Text="{Binding Description}"
                                d:Text="Item descripton"
                                LineBreakMode="NoWrap"
                                Style="{DynamicResource ListItemDetailTextStyle}"
                                FontSize="13" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
            <ListView.GestureRecognizers>
                <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1"></TapGestureRecognizer>
            </ListView.GestureRecognizers>
        </ListView>
</code>```

答:
Checkout this https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/listview/interactivity#selection-and-taps.
it discusses the selection activity in the ListView so u can execute some logic When an item is selected

Update:
Remove Code in the Screenshot then configure the ListView item selection as shown in the link.

then put the ListView (make sure that the list view fill only the space it needs) In a StackLayout and Configure the Tapped event of the stackLayout with the logic u need to execute on clicking the empty page.

Body:
I need to check if the empty part of a Xamarin Forms Listview is tapped. For example, there are 5 rows and the space below those filled rows is tapped a method should be called.
I tried adding Tapgesturerecognizer to the Listview and the page containing the listview but this didnt work.
Is there a way to check if someone tapped the empty space in the listview?

<ListView x:Name="ItemsListView"
                ItemsSource="{Binding Items}"
                VerticalOptions="FillAndExpand"
                HasUnevenRows="true"
                RefreshCommand="{Binding LoadItemsCommand}"
                IsPullToRefreshEnabled="true"
                IsRefreshing="{Binding IsBusy, Mode=OneWay}"
                CachingStrategy="RecycleElement"
                ItemSelected="OnItemSelected">
            <d:ListView.ItemsSource>
                <x:Array Type="{x:Type x:String}">
                    <x:String>First Item</x:String>
                    <x:String>Second Item</x:String>
                    <x:String>Third Item</x:String>
                    <x:String>Fourth Item</x:String>
                    <x:String>Fifth Item</x:String>
                    <x:String>Sixth Item</x:String>
                </x:Array>
            </d:ListView.ItemsSource>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout Padding="10">

                        </StackLayout>
                    </ViewCell>
                </DataTemplate>

            </ListView.ItemTemplate>
            <ListView.GestureRecognizers>
                <TapGestureRecognizer Tapped="OnTapGestureRecognizerTapped" NumberOfTapsRequired="1"></TapGestureRecognizer>
            </ListView.GestureRecognizers>
        </ListView>


问:
Is there a Javascript support library for html5 file API and upload?
until now I was using flash based swfupload and its swfupload.js which provides users with callbacks from flash and a possibility to set it up.

I was wondering if there is anything like this for HTML5 File API. I'm asking before I make it from scratch myself. I don't want to reinvent a wheel when there might be a good library out there already.

答:
I've played with this in the past:
http://aquantum-demo.appspot.com/file-upload

Seemed reasonable for what I was doing.


问:
How to run bootRun with spring profile via gradle task
I'm trying to set up gradle to launch the bootRun process with various spring profiles enabled.

My current bootRun configuration looks like:

```<code>bootRun {
    // pass command line options from gradle to bootRun
    // usage: gradlew bootRun "-Dspring.profiles.active=local,protractor"
    if (System.properties.containsKey('spring.profiles.active')) {
        systemProperty "spring.profiles.active", System.properties['spring.profiles.active']
    }
}
</code>```

I'd like to set system properties with a gradle task, and then execute bootRun.

My attempt looked like this:

```<code>task bootRunDev

bootRunDev  {
    System.setProperty("spring.profiles.active", "Dev")
}
</code>```

A few questions:

is systemProperty a part of the spring boot bootRun configuration?

is it possible to set a system property in another task?

What should my next step be? I need to get bootRunDev configuration to happen before bootRun

Is there another approach I should look into

-Eric

答:
In your build.gradle file simply use the following snippet

```<code>bootRun {
  args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}
</code>```

And then run following command to use dev profile:

```<code>./gradlew bootRun -Pprofile=dev
</code>```

Body:
I'm trying to set up gradle to launch the bootRun process with various spring profiles enabled.

My current bootRun configuration looks like:

bootRun {
    // pass command line options from gradle to bootRun
    // usage: gradlew bootRun "-Dspring.profiles.active=local,protractor"
    if (System.properties.containsKey('spring.profiles.active')) {
        systemProperty "spring.profiles.active", System.properties['spring.profiles.active']
    }
}

I'd like to set system properties with a gradle task, and then execute bootRun.

My attempt looked like this:

task bootRunDev

bootRunDev  {
    System.setProperty("spring.profiles.active", "Dev")
}

A few questions:

is systemProperty a part of the spring boot bootRun configuration?

is it possible to set a system property in another task?

What should my next step be? I need to get bootRunDev configuration to happen before bootRun

Is there another approach I should look into

-Eric

Body:
In your build.gradle file simply use the following snippet

bootRun {
  args = ["--spring.profiles.active=${project.properties['profile'] ?: 'prod'}"]
}

And then run following command to use dev profile:

./gradlew bootRun -Pprofile=dev


问:
How to use React.FC<props> type when the children can either be a React node or a function
I have this sample component

```<code>import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (
    <div>
      {typeof props.children === "function"
        ? props.children(val)
        : props.children}
    </div>
  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;
</code>```

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

```<code>type Props = {
  children: (x: number) => ReactNode;
};
</code>```

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

答:
tldr:

The React.FC type is the cause for above error:

It already includes default children typed as ReactNode, which get merged (&) with your own children type contained in Props.

ReactNode is a fairly wide type limiting the compiler's ability to narrow down the children union type to a callable function in combination with point 1.

A solution is to omit FC and use a more narrow type than ReactNode to benefit type safety:

```<code>type Renderable = number | string | ReactElement | Renderable[]
type Props = {
  children: ((x: number) => Renderable) | Renderable;
};
</code>```

More details

First of all, here are the built-in React types:

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;

interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean
  | null | undefined;

interface FunctionComponent
 {
  (props: PropsWithChildren
, context?: any): ReactElement | null;
  propTypes?: WeakValidationMap
;
  contextTypes?: ValidationMap<any>;
  defaultProps?: Partial
;
  displayName?: string;
}

type PropsWithChildren
 = P & { children?: ReactNode };```
</div>
</div>
</p>
<p>1.) You use <code>FC<Props></code> to type <code>Comp</code>. <code>FC</code> internally <em>already</em> includes a <code>children</code> declaration typed as <code>ReactNode</code>, which gets merged with <code>children</code> definition from <code>Props</code>:</p>
```type Props = { children: ((x: number) => ReactNode) | ReactNode } &
  { children?: ReactNode }
// this is how the actual/effective props rather look like
```
<p>2.) Looking at <code>ReactNode</code> type, you'll see that types get considerably more complex. <code>ReactNode</code> includes type <code>{}</code> via <code>ReactFragment</code>, which is the <strong>supertype of everything except <code>null</code> and <code>undefined</code></strong>. I don't know the exact decisions behind this type shape, microsoft/TypeScript#21699 hints at historical and backward-compatiblity reasons.</p>
<p>As a consequence, <code>children</code> types are wider than intended. This causes your original errors: type guard <code>typeof props.children === "function"</code> cannot narrow the type "muddle" properly to <code>function</code> anymore.</p>
<h2>Solutions</h2>
<h3>Omit <code>React.FC</code></h3>
<p>In the end, <code>React.FC</code> is just a function type with extra properties like <code>propTypes</code>, <code>displayName</code> etc. with opinionated, wide <code>children</code> type. Omitting <code>FC</code> here will result in safer, more understandable types for compiler and IDE display. If I take your definition <code>Anything that can be rendered</code> for <code>children</code>, that could be:</p>
```import React, { ReactChild } from "react";
// You could keep `ReactNode`, though we can do better with more narrow types
type Renderable = ReactChild | Renderable[]

type Props = {
  children: ((x: number) => Renderable) | Renderable;
};

const Comp = (props: Props) => {...} // leave out `FC` type
```
<h3>Custom <code>FC</code> type without <code>children</code></h3>
<p>You could define your own <code>FC</code> version, that contains everything from <code>React.FC</code> except those wide <code>children</code> types:</p>
```type FC_NoChildren
 = { [K in keyof FC
]: FC
[K] } & // propTypes etc.
{ (props: P, context?: any): ReactElement | null } // changed call signature

const Comp: FC_NoChildren<Props> = props => ...
```

Playground sample

Body:
I have this sample component

import React, { FC, ReactNode, useMemo } from "react";
import PropTypes from "prop-types";

type Props = {
  children: ((x: number) => ReactNode) | ReactNode;
};

const Comp: FC<Props> = function Comp(props) {
  const val = useMemo(() => {
    return 1;
  }, []);

  return (

      {typeof props.children === "function"
        ? props.children(val)
        : props.children}

  );
};

Comp.propTypes = {
  children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired
};

export default Comp;

My intent here is that the children prop of the component can either be

a node, which is described as

Anything that can be rendered: numbers, strings, elements or an array (or fragment) containing these types.

a function, (or a "render prop") which simply gets a value from inside the component and returns another node

the point here is to be explicit, that the children can either be the one (node, which is pretty much everything) or the other (which is simply a function)

The problem

I am facing the following issues however with the type check.

if I leave the code as presented here, I get the following error message on the line ? props.children(val)

This expression is not callable.
  Not all constituents of type 'Function | ((x: number) => ReactNode) | (string & {}) | (number & {}) | (false & {}) | (true & {}) | ({} & string) | ({} & number) | ({} & false) | ({} & true) | (((x: number) => ReactNode) & string)

I do not understand this error.

if I change the Props type to be

type Props = {
  children: (x: number) => ReactNode;
};

and rely on React's own type PropsWithChildren
 = P & { children?: ReactNode }; to handle the case where children is not a function, then I get the error

(property) children?: PropTypes.Validator<(x: number) => React.ReactNode>
  Type 'Validator' is not assignable to type 'Validator<(x: number) => ReactNode>'.
    Type 'ReactNodeLike' is not assignable to type '(x: number) => ReactNode'.
      Type 'string' is not assignable to type '(x: number) => ReactNode'.ts(2322)
  Comp.tsx(5, 3): The expected type comes from property 'children' which is declared here on type

on the line children: PropTypes.oneOfType([PropTypes.node, PropTypes.func]).isRequired

The only solution is to leave the Props type as

type Props = {
  children: (x: number) => ReactNode;
};

and also change the Comp.propTypes to be children: PropTypes.func.isRequired, which is not what I want, since I want to be explicit.

The question

How can I keep the code explicit, as presented at the start of this question, and also not have the type checking throw errors on me?

CodeSandbox link

Body:
tldr:

The React.FC type is the cause for <a href="https://www.typescriptlang.org/play/?jsx=2&ssl=8&ssc=13&pln=8&pc=22#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecBiAwtsujAHIQAmS2ArgM5ICySIEcAvnAGZQQg4AIiioMQgNwBYAFChIsOAAV+YACoBPMEga9+goWFUBaGFp2TZss9uWrdAXlyy4cNAAtgAGyqiAdgBccAAUwQAeQX50IABGSFAAlHAOAHyIYhTUSEkAPulklDTSMpzFsmgQfgzwhAJgQUQAPCoQYAxpTjx0fhjAlXC14MFGrQxJOC5uldVwAG4oXslwjCxsEKFJqc4yrq6iMHRQfnAAjMWunNgA2gC6CWU7cPuHx8GTro1UwLMp77s4NiQEB4cBGbQAdB5vL4kMcHPDhF0ejA+n4hH9dnAAPyg+yQzw+fzBeZeBIY3ZBMEMfHQ-ycP6NAD0Xx+k3uslKVhkgzA4LBmm0jm2rihhNhQRa6nM1MqSAA8jwBUhgldJUrqX4stg1dLwUi0HdwcAGMgAI50YCiKgch5IMIKeA0HgoOheGp1CRAA" rel="nofollow noreferrer">above error:

It already includes default children typed as ReactNode, which get merged (&) with your own children type contained in Props.

ReactNode is a fairly wide type limiting the compiler's ability to narrow down the children union type to a callable function in combination with point 1.

A solution is to omit FC and use a more narrow type than ReactNode to benefit type safety:

type Renderable = number | string | ReactElement | Renderable[]
type Props = {
  children: ((x: number) => Renderable) | Renderable;
};

More details

First of all, here are the built-in React types:

type ReactText = string | number;
type ReactChild = ReactElement | ReactText;

interface ReactNodeArray extends Array<ReactNode> {}
type ReactFragment = {} | ReactNodeArray;
type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean
  | null | undefined;

interface FunctionComponent<P = {}> {
  (props: PropsWithChildren<P>, context?: any): ReactElement | null;
  propTypes?: WeakValidationMap<P>;
  contextTypes?: ValidationMap<any>;
  defaultProps?: Partial<P>;
  displayName?: string;
}

type PropsWithChildren<P> = P & { children?: ReactNode };

1.) You use FC<Props> to type Comp. FC internally already includes a children declaration typed as ReactNode, which gets merged with children definition from Props:

type Props = { children: ((x: number) => ReactNode) | ReactNode } &
  { children?: ReactNode }
// this is how the actual/effective props rather look like

2.) Looking at ReactNode type, you'll see that types get considerably more complex. ReactNode includes type {} via ReactFragment, which is the supertype of everything except null and undefined. I don't know the exact decisions behind this type shape, microsoft/TypeScript#21699 hints at historical and backward-compatiblity reasons.

As a consequence, children types are wider than intended. This causes your original errors: type guard typeof props.children === "function" cannot narrow the type "muddle" properly to function anymore.

Solutions

Omit React.FC

In the end, React.FC is just a function type with extra properties like propTypes, displayName etc. with opinionated, wide children type. Omitting FC here will result in safer, more understandable types for compiler and IDE display. If I take your definition Anything that can be rendered for children, that could be:

import React, { ReactChild } from "react";
// You could keep `ReactNode`, though we can do better with more narrow types
type Renderable = ReactChild | Renderable[]

type Props = {
  children: ((x: number) => Renderable) | Renderable;
};

const Comp = (props: Props) => {...} // leave out `FC` type

Custom FC type without children

You could define your own FC version, that contains everything from React.FC except those wide children types:

type FC_NoChildren<P = {}> = { [K in keyof FC<P>]: FC<P>[K] } & // propTypes etc.
{ (props: P, context?: any): ReactElement | null } // changed call signature

const Comp: FC_NoChildren<Props> = props => ...

<a href="https://www.typescriptlang.org/play/?jsx=2#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecBiAwtgK4DOSAskiBNsujIQBbAA2AJvahgKJs0kAO3gBfOADMoEEHABEUHjDkBuALAAoUJFhwACtLAAVAJ5gkZSdNlywhgLQwzF1Zs1PziYRyRQUAIwE4AF4vRhZ2DjgAHy8hHz9ApABtAF03DQ8kfUNLUJxNODg0Vk5FIQAuOAAKaoAPKqESEH9fAEoQgD44hICBDtjkeN8%20pHUNUXHNNAghMnhCGTAQyRIhDGBZuEXwarsIMDIqgwOyDoKNIpm5%20AA3FDYV8ioaCFqO4O6LoqLFGBIoEI4ABGcZFUTYNJtKaXOB-AFA6qFH4AHg4wFunWRP1wWQgEjg%200OADoSpFyiFgqE5BI1htZnJsTi4AB%20Qm5UmlDjlar3NhtJk4qpEsic8nCURMlEAenRmOR0M0kwyOzAxKJpnMeVwyLJZWEx0MmosxNmSAA8hJjdVkidjM5RUIID5sHbjaLaetUm1icAyMgAI4kYCKDhKmFZAiEAD6ADkIBF9UIUXoVjhRN18nBkgBpODAIEAayQJnxUZTnVSVSIFdzqTg4gAZHBpdL2Qd3XAkDA0MTNHg9rljthrjAkHUYCyqighCY2lUGHwBCBhPBYk02I9xK3ig9HmRgABzIQof6KDLXebbJYAJmrMfjie5whTuUz7cOXTgaIxWNhODxAkRTFJNKWpT16SERlYSKNlgL1Z8hGqAAWG8BRguBhQ5BDyklDQZTlP8gA" rel="nofollow noreferrer">Playground sample


问:
How can I ship my app with a pre-populated Core Data database?
My app uses Core Data and I want some default entries to be inside.
What's best practices of how to do that?</p>

答: I would just create a database and put add it to my target so that Xcode copies it into the app bundle. At the first launch just copy it from the app bundle to eg. the documents directory or wherever your app expects the database.</p>


问:
Find and replace tagged words from string using python?
I need to find and replace some tagged words from a paragraph.

```<code>str = "my name is [tag1]alan[/tag1] . i am a [tag2]python[/tag2] developer."
</code>```

tag1 and tag2 are words I need to find and replace their middle content with another word.
tags are not limited. it may have more than 10. but every tag is enclosed in the same way, like in square brackets, [tag][/tag].

I want a result like this,

```<code>str = "my name is alan . i am a python developer."
</code>```

Is there any way to do it using regex? without using beautifulsoup.

答:
Using Regex.

Ex:

```<code>import re

string = "my name is [tag1]alan[/tag1]. i am a [tag2]python[/tag2] developer."
print(re.sub(r"(\[.*?\])", "", string))
# --> my name is alan. i am a python developer.
</code>```

Body:
I need to find and replace some tagged words from a paragraph.

str = "my name is [tag1]alan[/tag1] . i am a [tag2]python[/tag2] developer."

tag1 and tag2 are words I need to find and replace their middle content with another word.
tags are not limited. it may have more than 10. but every tag is enclosed in the same way, like in square brackets, [tag][/tag].

I want a result like this,

str = "my name is alan . i am a python developer."

Is there any way to do it using regex? without using beautifulsoup.

Body:
Using Regex.

Ex:

import re

string = "my name is [tag1]alan[/tag1]. i am a [tag2]python[/tag2] developer."
print(re.sub(r"(\[.*?\])", "", string))
# --> my name is alan. i am a python developer.


问:
Vuetify text field inside loop loses focus after one input
I have the following Vuetify layout in my page:

```<code><v-hover
  v-for="(prop, index) in obj.props"
  :key="prop"
  v-slot:default="{ hover }">
  <v-card flat tile
    width="120"
    class="mr-2 d-flex">
    <v-text-field single-line flat dense required
      v-model="obj.props[index]"
      type="number"
      label="Prop"
      height="30" />
    <v-fade-transition>
      <v-btn text icon small
        color="error"
        class="customPropCardRemove mt-2"
        :class="{ 'showCustomPropCardRemove': hover}"
        @click="removeCustomProp(obj, index)">
        <font-awesome-icon
          color="error"
          icon="times"
          class="fa-sm" />
      </v-btn>
    </v-fade-transition>
  </v-card>
</v-hover>
</code>```

Basically it's a text field with adjacent button inside a card. The button fades in when hovering over the card. That works. However, the text field looses focus after a single input.

I thought maybe the v-hover/v-fade-transition somehow affects it, so I tried to remove it and keep the button constantly visible:

```<code><v-card flat tile
  v-for="(prop, index) in obj.props"
  :key="prop"
  width="120"
  class="mr-2 d-flex">
  <v-text-field single-line flat dense required
    v-model="obj.props[index]"
    label="Prop"
    height="30" />
  <v-btn text icon small
    color="error"
    class="mt-2"
    @click="removeCustomProp(obj, index)">
      <font-awesome-icon
        color="error"
        icon="times"
        class="fa-sm" />
   </v-btn>
 </v-card>
</code>```

But the issue still persists. Any ideas why is it happening and how to fix it?

答:
OK, I found what was causing this problem:

```<code><v-card flat tile
  v-for="(prop, index) in obj.props"
  :key="prop"
  width="120"
  class="mr-2 d-flex">
  <v-text-field single-line flat dense required
    v-model="obj.props[index]"
    label="Prop"
    height="30" />
 .....
</code>```

:key="prop" and v-model="obj.props[index]" are the same string. So once I input something in the text field - it causes the key to change, thus re-render the list and, consequentially, lose focus.
I changed :key="index" and it worked just fine.

Body:
I have the following Vuetify layout in my page:

<v-hover
  v-for="(prop, index) in obj.props"
  :key="prop"
  v-slot:default="{ hover }">
  <v-card flat tile
    width="120"
    class="mr-2 d-flex">
    <v-text-field single-line flat dense required
      v-model="obj.props[index]"
      type="number"
      label="Prop"
      height="30" />
    <v-fade-transition>
      <v-btn text icon small
        color="error"
        class="customPropCardRemove mt-2"
        :class="{ 'showCustomPropCardRemove': hover}"
        @click="removeCustomProp(obj, index)">

      </v-btn>
    </v-fade-transition>
  </v-card>
</v-hover>

Basically it's a text field with adjacent button inside a card. The button fades in when hovering over the card. That works. However, the text field looses focus after a single input.

I thought maybe the v-hover/v-fade-transition somehow affects it, so I tried to remove it and keep the button constantly visible:

<v-card flat tile
  v-for="(prop, index) in obj.props"
  :key="prop"
  width="120"
  class="mr-2 d-flex">
  <v-text-field single-line flat dense required
    v-model="obj.props[index]"
    label="Prop"
    height="30" />
  <v-btn text icon small
    color="error"
    class="mt-2"
    @click="removeCustomProp(obj, index)">

   </v-btn>
 </v-card>

But the issue still persists. Any ideas why is it happening and how to fix it?

Body:
OK, I found what was causing this problem:

<v-card flat tile
  v-for="(prop, index) in obj.props"
  :key="prop"
  width="120"
  class="mr-2 d-flex">
  <v-text-field single-line flat dense required
    v-model="obj.props[index]"
    label="Prop"
    height="30" />
 .....

:key="prop" and v-model="obj.props[index]" are the same string. So once I input something in the text field - it causes the key to change, thus re-render the list and, consequentially, lose focus.
I changed :key="index" and it worked just fine.


问:
Is graph-database right to identify a business route?
I have a business logic to identify the cost effective route that benefits business. The route here means, technically, an api/connectivity (service-provider) the application should connect to fulfil the transaction, and the benefit here is the price the business gets in fulfilling the transaction.

A route has to be identified based on different parameters - some are, value of the transaction, the connectivity to the service-provider to perform the transaction, the priority flag set on service-provider, transaction counters for service-providers, the client who performs the transaction, the type of transaction performed, the properties present in the transaction that a service-provider expects, the service-providers charges (the lowest), and others.

As of now these properties are squeezed into relational database, the routes are queried with a mid-complex query. I am interested to see if graph database like Apache Tinkerpop is right for such usecases. I already have used a graphdb for a kind-of product recommendation engine based on customer relationships. One thing to note is, the business continues to change the routes anytime based on the traffic & demand.

I will add details if required.

答:
First of all, I'd say this is a typical graph database use case.

What you need is a shortest path algorithm to help you find the most cost effective path for businesses. Taking the parameters you mentioned in the question into consideration, you might need to use them as vertices, edges (relationships), or properties on vertex/edge in a graph model.

Now I am trying to provide a model based on your description and my understanding. It's by no means a complete (or correct) model since I am sure there's much info missing here. Just a sample for your reference.

Typically in a property graph model there will be three concepts:

Vertex

Edge/Relationship

Properties for a vertex or an edge

Based on the information you provided, the graph model can have:

Vertices - service-provider, with priority, charges and transaction counters as its properties；the client

Edges - Transaction, with value of the transaction as its property

You can come up with something like this:

The basic unit of the graph model

Finally, if your data set is not too large, say under 1 billion (vertices and edges together), most graph databases can handle that. As to their performance, if your data can be placed in single node (host), then there's not much difference.


问:
How to convert a list to json in python
have a list with values

```<code>test = ["mark","will","john"]

</code>```

using for loop how to convert this into JSON like this

```<code>test =[{"name":"mark"},{"name":"john"},{"name":"will"}]
</code>```

Tried this

```<code>for i in test :
    print({"name":i})

</code>```

答:
Create a dictionary within a list comprehension:

```<code>test = ["mark","will","john"]
json_list = [{"name": n} for n in test]
</code>```

same as:

```<code>json_list = []
for n in test:
    json_list.append({"name" : n})
</code>```

then dump to json:

```<code>import json
json.dumps(json_list)
</code>```

Title: How to convert a list to json in python

Body:
have a list with values

test = ["mark","will","john"]

using for loop how to convert this into JSON like this

test =[{"name":"mark"},{"name":"john"},{"name":"will"}]

Tried this

for i in test :
    print({"name":i})

Body:
Create a dictionary within a list comprehension:

test = ["mark","will","john"]
json_list = [{"name": n} for n in test]

same as:

json_list = []
for n in test:
    json_list.append({"name" : n})

then dump to json:

import json
json.dumps(json_list)


问:
Failed to find target with hash string 'android-24'

I am getting this error after changing all the Google libraries to 24.0.0 and changing the compileSdkVersion and targetSdkVersion to 24.
As you can see in the attached images I installed all Android N packages, but there only stands: "Partially installed".
How can I fix this?

答: open android studio as Run as administrator. It automatically installs missed sdks and all. </p>


问:
Ruby: What does the line "m = Hash.new {|h,k| h[k] = []}" accomplish that "Hash.new" doesn't?
While studying this Railscast I came across the following bit of source code from Rack:

```<code>def self.middleware
  @middleware ||= begin
    m = Hash.new {|h,k| h[k] = []}
    m["deployment"].concat [
      [Rack::ContentLength],
      [Rack::Chunked],
      logging_middleware
    ]
    m["development"].concat m["deployment"] + [[Rack::ShowExceptions], [Rack::Lint]]
    m
  end
end
</code>```

My question is about the third line. What does passing the block {|h,k| h[k] = []} to Hash.new accomplish? I tried it in IRB and it doesn't seem to do anything different from a regular Hash.new:

```<code>2.0.0p247 :003 > m1 = Hash.new
 => {}
2.0.0p247 :004 > m2 = Hash.new{|h,k| h[k] = []}
 => {}
2.0.0p247 :005 > m1 == m2
 => true
</code>```

... but I'm going to guess that the guys who wrote Rack know more about Ruby than I do. What's the reasoning behind including that block?

答:
This creates default object ([] in this case) as value for every key. It calls h1[:a] = [] implicitly resulting in addition of key in the hash.

```<code>h1 = Hash.new {|h,k| h[k] = []}
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = []
h1 #= {:a=>[1], :b=>[]}
</code>```

This returns a single default object as value for all keys.

```<code>h1 = Hash.new([])
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = [1]
h1 #= {}
</code>```

This returns default object as value for all keys. But does not add key to the hash.

```<code>h1 = Hash.new{[]}
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = []
h1 #= {}
</code>```

Body:
While studying this Railscast I came across the following bit of source code from Rack:

def self.middleware
  @middleware ||= begin
    m = Hash.new {|h,k| h[k] = []}
    m["deployment"].concat [
      [Rack::ContentLength],
      [Rack::Chunked],
      logging_middleware
    ]
    m["development"].concat m["deployment"] + [[Rack::ShowExceptions], [Rack::Lint]]
    m
  end
end

My question is about the third line. What does passing the block {|h,k| h[k] = []} to Hash.new accomplish? I tried it in IRB and it doesn't seem to do anything different from a regular Hash.new:

2.0.0p247 :003 > m1 = Hash.new
 => {}
2.0.0p247 :004 > m2 = Hash.new{|h,k| h[k] = []}
 => {}
2.0.0p247 :005 > m1 == m2
 => true

... but I'm going to guess that the guys who wrote Rack know more about Ruby than I do. What's the reasoning behind including that block?

Body:
This creates default object ([] in this case) as value for every key. It calls h1[:a] = [] implicitly resulting in addition of key in the hash.

h1 = Hash.new {|h,k| h[k] = []}
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = []
h1 #= {:a=>[1], :b=>[]}

This returns a single default object as value for all keys.

h1 = Hash.new([])
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = [1]
h1 #= {}

This returns default object as value for all keys. But does not add key to the hash.

h1 = Hash.new{[]}
h1[:a] # = []
h1[:a].push(1) # = [1]
h1[:b] # = []
h1 #= {}


问:
adding existing GCP service account to Terraform root module for cloudbuild to build Terraform configuration
Asking the community if it's possible to do the following. (had no luck in finding further information)

I create a ci/cd pipeline with Github/cloudbuild/Terraform. I have cloudbuild build terraform configuration upon github pull request and merge to new branch. However, I have cloudbuild service account (Default) use with least privilege.
Question adheres, I would like terraform to pull permission from an existing service account with least privilege to prevent any exploits, etc. once cloudbuild gets pull build triggers to init terraform configuration. At this time, i.e terraform will extract existing external SA to obtain permission to build TF.
I tried to use service account, and binding roles to that service account but error happens that
states service account already existences.
Next step, is for me to use a module but I think this is also going to create a new SA with replicated roles.
If this is confusing I do apologize, I will help in refining the question to be more concise.

答:
You have 2 solutions:

Use the Cloud Build service account when you execute your Terraform. Your provider look like this:

```<code>provider "google" {
//  Useless with Cloud Build
//  credentials = file("${var.CREDENTIAL_FILE}}")
  project = var.PROJECT_ID
  region = "europe-west1"
}
</code>```

But this solution implies to grant several roles to Cloud Build only for Terraform process. A custom role is a good choice for granting only what is required.

The second solution is to use a service account key file. Here again 2 solutions:

Cloud Build creates the service account, grant all the role on it, generates a key and passes it to terraform. After the terraform execution, the service account is deleted by Cloud Build. Good solution, but you have to grant Cloud Build service account the capability to grant itself any roles and to generate a json Key file. That's a lot a responsibility!

Use an existing service account and the key generated on it. But you have to secure the key and to rotate it regularly. I recommend you to securely store it in secret manager, but for the rotation, you have to manage it by yourselves, today. With this process, Cloud Build download the key (in secret manager) and pass it to terraform. Here again, the Cloud Build service account has the right to access to secrets, that is a critical privilege. The step in Cloud Build is something like this:

```<code>steps:
        - name: gcr.io/cloud-builders/gcloud:latest
          entrypoint: "bash"
          args:
                  - "-c"
                  - |
                      gcloud beta secrets versions access --secret=test-secret latest > my-secret-file.txt
</code>```

Body:
You have 2 solutions:

Use the Cloud Build service account when you execute your Terraform. Your provider look like this:

provider "google" {
//  Useless with Cloud Build
//  credentials = file("${var.CREDENTIAL_FILE}}")
  project = var.PROJECT_ID
  region = "europe-west1"
}

But this solution implies to grant several roles to Cloud Build only for Terraform process. A custom role is a good choice for granting only what is required.

The second solution is to use a service account key file. Here again 2 solutions:

Cloud Build creates the service account, grant all the role on it, generates a key and passes it to terraform. After the terraform execution, the service account is deleted by Cloud Build. Good solution, but you have to grant Cloud Build service account the capability to grant itself any roles and to generate a json Key file. That's a lot a responsibility!

Use an existing service account and the key generated on it. But you have to secure the key and to rotate it regularly. I recommend you to securely store it in secret manager, but for the rotation, you have to manage it by yourselves, today. With this process, Cloud Build download the key (in secret manager) and pass it to terraform. Here again, the Cloud Build service account has the right to access to secrets, that is a critical privilege. The step in Cloud Build is something like this:

steps:
        - name: gcr.io/cloud-builders/gcloud:latest
          entrypoint: "bash"
          args:
                  - "-c"
                  - |
                      gcloud beta secrets versions access --secret=test-secret latest > my-secret-file.txt