问:
OSB transform String to DateTime (xsl or xquery)
I'm working with Oracle OSB and I have the following incoming xml message:

```<code><db:InputParameters>
    <db:DETAILS>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
    </db:DETAILS>
</db:InputParameters>
</code>```

The element "Date" is a "string" -> according to the xsd. But the application that I'm sending this message to, expects a "DateTime" type. So I need to transform the element "Date" from type "String" to type "DateTime". Keep in mind that the incoming message has more than one element called "Date". I tried a For Each stage with a replace action but I couldn't get it to work.

Also, I tried to concat ":00" to the "Date" element with the expression: fn:concat($body/*:inputparameters/*:DETAILS/*:DETAILS_ITEM/*:Date,':00')
This didn't seem to work either.

What would be the most simple solution to this?

Thanks for the help.

答:
With some help from a colleague I found the following solution.

In the first pipeline that picks up the incoming message from the queue, I added a "For-each stage" with a "replace stage" inside that looks like this:

```<code>For Each [ curValue ] in [*:InputParameters/*:DETAILS/*:DETAILS_ITEM/*:Date]
of [ body ]
Indexed by [ curIndex ] with total count in [ curCount ]
Do (

Replace [ node contents ] of [ *:InputParameters/*:DETAILS/*:DETAILS_ITEM[$curIndex]/*:Date]
in [ body ] with [ fn:concat($curValue,":00")]
</code>```

Body:
I'm working with Oracle OSB and I have the following incoming xml message:

<db:InputParameters>
    <db:DETAILS>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
        <db:DETAILS_ITEM>
            <db:Mutate>W</db:Mutate>
            <db:Date>2020-04-06T14:43</db:Date>
            <db:Account>T</db:Account>
        </db:DETAILS_ITEM>
    </db:DETAILS>
</db:InputParameters>

The element "Date" is a "string" -> according to the xsd. But the application that I'm sending this message to, expects a "DateTime" type. So I need to transform the element "Date" from type "String" to type "DateTime". Keep in mind that the incoming message has more than one element called "Date". I tried a For Each stage with a replace action but I couldn't get it to work.

Also, I tried to concat ":00" to the "Date" element with the expression: fn:concat($body/*:inputparameters/*:DETAILS/*:DETAILS_ITEM/*:Date,':00')
This didn't seem to work either.

What would be the most simple solution to this?

Thanks for the help.

Body:
With some help from a colleague I found the following solution.

In the first pipeline that picks up the incoming message from the queue, I added a "For-each stage" with a "replace stage" inside that looks like this:

For Each [ curValue ] in [*:InputParameters/*:DETAILS/*:DETAILS_ITEM/*:Date]
of [ body ]
Indexed by [ curIndex ] with total count in [ curCount ]
Do (

Replace [ node contents ] of [ *:InputParameters/*:DETAILS/*:DETAILS_ITEM[$curIndex]/*:Date]
in [ body ] with [ fn:concat($curValue,":00")]


来源: stackexchange

问:
Data JPA Test with reactive spring
I want to test the repository layer and I'm using spring webflux. My test class is as follows

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}

</code>```

Even though this would work in spring-mvc when using spring-weblux I get the following error.

```<code>Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
...

Caused by: org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.
</code>```

How to resolve this? If I am to start the whole application context with @SpringBootApplication it works. Any other options without using that?

答:
If you are using Spring Boot 2+ then only @DataJpaTest is enough on test class.
So your test class should be</p>

```<code>@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Data JPA Test with reactive spring

Body:
I want to test the repository layer and I'm using spring webflux. My test class is as follows

@RunWith(SpringRunner.class)
@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}

Even though this would work in spring-mvc when using spring-weblux I get the following error.

Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
...

Caused by: org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.

How to resolve this? If I am to start the whole application context with @SpringBootApplication it works. Any other options without using that?

Body:
If you are using Spring Boot 2+ then only @DataJpaTest is enough on test class.
So your test class should be

@DataJpaTest
public class DataTester {
    @Autowired
    private MyRepository repository;

    @Test
    .....

}


问:
Split a string but a delimiter, only outside of [...] pair
How can i split a string, using ";" as a delimiter but only when this delimiter is NOT inside any [...].
e.g</p>

```<code>[a;b]c;d[e;f]  => <0>[a;b]c  <1>d[e;f]
a;b;c[e;f;g]   => <0>a <1>b <2>c[e;f;g]
abcd[e;f]      => <0>abcd[e;f]
</code>```

答:
The following code will handle the nested brackets and works faster than regular expression. I have run 100000 iterations for the following code and received an elapsed time of 322ms vs 1116ms for code using RegExp.Split().</p>

```<code>        List<string> list_OutputStr = new List<string>();
        int i_NestedBracketsCount = 0;
        StringBuilder sb = new StringBuilder();
        foreach (char ch in s_InputStr)
        {
            if (ch.Equals(';') && i_NestedBracketsCount == 0) { list_OutputStr.Add(sb.ToString()); sb.Clear(); continue; }
            else if (ch.Equals('[')) i_NestedBracketsCount++;
            else if (ch.Equals(']')) i_NestedBracketsCount--;
            sb.Append(ch);
        }
        if (sb.Length > 0) list_OutputStr.Add(sb.ToString());

        foreach (string str in list_OutputStr)
            Console.Write(str + "\t");
</code>```

Body:
How can i split a string, using ";" as a delimiter but only when this delimiter is NOT inside any [...].
e.g

[a;b]c;d[e;f]  => <0>[a;b]c  <1>d[e;f]
a;b;c[e;f;g]   => <0>a <1>b <2>c[e;f;g]
abcd[e;f]      => <0>abcd[e;f]

Body:
The following code will handle the nested brackets and works faster than regular expression. I have run 100000 iterations for the following code and received an elapsed time of 322ms vs 1116ms for code using RegExp.Split().

        List<string> list_OutputStr = new List<string>();
        int i_NestedBracketsCount = 0;
        StringBuilder sb = new StringBuilder();
        foreach (char ch in s_InputStr)
        {
            if (ch.Equals(';') && i_NestedBracketsCount == 0) { list_OutputStr.Add(sb.ToString()); sb.Clear(); continue; }
            else if (ch.Equals('[')) i_NestedBracketsCount++;
            else if (ch.Equals(']')) i_NestedBracketsCount--;
            sb.Append(ch);
        }
        if (sb.Length > 0) list_OutputStr.Add(sb.ToString());

        foreach (string str in list_OutputStr)
            Console.Write(str + "\t");


问:
Unable to fetch all the links from a webpage using requests
I'm trying to get all the links connected to each image in this webpage.

I can get all the links if I let a selenium script scroll downward until it reaches the bottom. One such link that I wish to scrape is this one.

Now, my goal here is to parse all those links using requests. What I have notice that the links that I want to parse are built using such B-uPwZsJtnB shortcode.

However,
I'm trying to scrape those different shortcode available in a script tag found in page source in that webpage. There are around 600 shortcodes in that page. The script that I've created can parse only the first 70 such shortcode which ultimately can built 70 qualified links.

How can I grab all 600 links using requests?

I've tried so far with:

```<code>import re
import json
import requests

base_link = 'https://www.instagram.com/p/{}/'
lead_url = 'https://www.instagram.com/explore/tags/baltimorepizza/'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    req = s.get(lead_url)
    script_tag = re.findall(r"window\._sharedData[^{]+(.*?);",req.text)[0]
    for item in json.loads(script_tag)['entry_data']['TagPage']:
        tag_items = item['graphql']['hashtag']['edge_hashtag_to_media']['edges']
        for elem in tag_items:
            profile_link = base_link.format(elem['node']['shortcode'])
            print(profile_link)
</code>```

答:
If you want to do it with requests then please consider to query XHR/Ajax Http requests for imitating Lazy load. See the following picture:

You make queries to the instagram.com server similar to Scrape a JS Lazy load page by Python requests post.

Disclaimer

You might not succeed to complete that task due to some dynamic cookie values or other scraping prevention imposed by Instagram.

Body:
I'm trying to get all the links connected to each image in this webpage.

I can get all the links if I let a selenium script scroll downward until it reaches the bottom. One such link that I wish to scrape is this one.

Now, my goal here is to parse all those links using requests. What I have notice that the links that I want to parse are built using such B-uPwZsJtnB shortcode.

However,
I'm trying to scrape those different shortcode available in a script tag found in page source in that webpage. There are around 600 shortcodes in that page. The script that I've created can parse only the first 70 such shortcode which ultimately can built 70 qualified links.

How can I grab all 600 links using requests?

I've tried so far with:

import re
import json
import requests

base_link = 'https://www.instagram.com/p/{}/'
lead_url = 'https://www.instagram.com/explore/tags/baltimorepizza/'

with requests.Session() as s:
    s.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36'
    req = s.get(lead_url)
    script_tag = re.findall(r"window\._sharedData[^{]+(.*?);",req.text)[0]
    for item in json.loads(script_tag)['entry_data']['TagPage']:
        tag_items = item['graphql']['hashtag']['edge_hashtag_to_media']['edges']
        for elem in tag_items:
            profile_link = base_link.format(elem['node']['shortcode'])
            print(profile_link)


问:
Passing a number to a function in react js
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

```<code>import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(
        <div>
            Counter : {this.state.counter}</div>
        );
    }
}

export default lesson2
</code>```

This is my App.js

```<code>import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (
    <div className="App">

        <p>
          <Variable name='D' />
          <Lesson2 increment={10}/>
        </p>

    </div>
  );
}

export default App;
</code>```

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.

答: The add() function is not used at all inn Your code

Body:
I want to pass a number to the function.I follow same way to pass both string and integer values. I can pass the string value. But I can't pass the integer value in that way.

This is my lesson2.js file

import React from 'react'

class lesson2 extends React.Component{

    constructor(props){
        super(props);
        this.state = {counter:1}
    }

    add(){
        this.setState(function(state,props){
            return{
                counter: state.counter + props.increment
            };
        })
    }

    render(){
        return(

            Counter : {this.state.counter}

        );
    }
}

export default lesson2

This is my App.js

import React from 'react';
import './App.css';
import Variable from './Components/variable_dec'
import Lesson2 from './Components/lesson2'

function App() {
  return (

          <Variable name='D' />
          <Lesson2 increment={10}/>

  );
}

export default App;

This is my output. But in my correct output should be Counter : 11. The problem is that the increment value doesn't add to the counter. So hope your help to solve my problem.


问:
Java Records StackOverflow RuntimeException
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

```<code>    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)
</code>```

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

```<code>// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}
</code>```

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()

答:
It has nothing to do with Record#toString in particular. Take a closer look at your declaration:

```<code>public record Course(String name, Student topper) {}
public record Student(String name, List<Course> enrolled) {}
</code>```

Course#toString needs Student#toString and Student#toString needs Course#toString. So if you try to print Student then all enrolled Course will be printed along. Those Courses needs Student so they will print Student inside. This loop will continue till you get StackOverflow exception.

To avoid this kind of scenario, you should rearrange your code so they don't depend on each other. You can create an id per instance. An example would be:

```<code>public record Course(String name, String studentId) {}
public record Student(String name, String studentId, List<Course> courses) {}
</code>```

Body:
I am learning Java Records, preview feature and I am getting a StackOverflow exception when I run the below piece of code .

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    public class Example {
        public record Course(String name, Student topper) { }
        public record Student(String name, List<Course> enrolled) {}

        public static void main(String[] args) {
            Student john = new Student("John", new ArrayList<>());
            john.enrolled().add(new Course("Enrolled for Math", john));
            john.enrolled().add(new Course("Enrolled for History", john));
            System.out.println(john);
        }
    }

Below is the exception trace :

 java --enable-preview Example
 Exception in thread "main" java.lang.StackOverflowError
    at Example$Course.toString(Example.java:6)
    at java.base/java.lang.String.valueOf(String.java:3388)
    at java.base/java.lang.StringBuilder.append(StringBuilder.java:167)
    at java.base/java.util.AbstractCollection.toString(AbstractCollection.java:457)

From the exception I realize that it has to do with toString() and when I have override toString() in the records as below code I don't see the Exception .

// code with implementation of toString()
public class Example {

    public record Course(String name, Student topper) {
    public String toString()
        {
            return name;
        }
   }
   public record Student(String name, List<Course> enrolled) {
   public String toString()
        {
             return this.name+" : "+enrolled.stream().map(s->s.toString()).collect(Collectors.joining(","));
        }
   }
   public static void main(String... args) {
       Student john = new Student("John", new ArrayList<>());
       john.enrolled().add(new Course("Enrolled for Math", john));
       john.enrolled().add(new Course("Enrolled for History", john));
       System.out.println(john);
   }
}

This code prints John : Enrolled for Math,Enrolled for History . Can someone please explain why if I don't override  toString() I get StackOverflow? Also I see StackOverflow when I print john.hashCode()

Body:
It has nothing to do with Record#toString in particular. Take a closer look at your declaration:

public record Course(String name, Student topper) {}
public record Student(String name, List<Course> enrolled) {}

Course#toString needs Student#toString and Student#toString needs Course#toString. So if you try to print Student then all enrolled Course will be printed along. Those Courses needs Student so they will print Student inside. This loop will continue till you get StackOverflow exception.

To avoid this kind of scenario, you should rearrange your code so they don't depend on each other. You can create an id per instance. An example would be:

public record Course(String name, String studentId) {}
public record Student(String name, String studentId, List<Course> courses) {}


问:
Style Cop For Validating Markup?
Is it possible to use StyleCop to validate the markup of an ASP.NET page or user control, to ensure the developer is following standards?

Thanks.

答: No. StyleCop is for C#, not HTML. You can use the built in validation inside Visual Studio.</p>

ContentLicense: CC BY-SA 3.0

Title: Style Cop For Validating Markup?


问:
Swift function swizzling / runtime
Before Swift, in Objective-C I would swizzle or hook methods in a class using <objc/runtime.h>.

If anyone has any info on the topic of modifying Swift's runtime and hooking functions like CydiaSubstrate and other libraries that helped in this area, please inform me.

答:
A safe, easy, powerful and efficient hook framework for iOS (Support Swift and Objective-C). https://github.com/623637646/SwiftHook

For example, this is your class

class MyObject {
    @objc dynamic func noArgsNoReturnFunc() {
    }
    @objc dynamic func sumFunc(a: Int, b: Int) -> Int {
        return a + b
    }
    @objc dynamic class func classMethodNoArgsNoReturnFunc() {
    }
}
```

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The key words of methods <code>@objc</code> and <code>dynamic</code> are necessary</strong></p>

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The class doesn't have to inherit from NSObject. If the class is written by Objective-C, Just hook it without any more effort</strong></p>

<ol>
<li>Perform the hook closure before executing specified instance's method.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
</code>```

Perform the hook closure after executing specified instance's method. And get the parameters.

let object = MyObject()
let token = try? hookAfter(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4
    } as @convention(block) (Int, Int) -> Void)
_ = object.sumFunc(a: 3, b: 4)
token?.cancelHook() // cancel the hook
```

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>The key word <code>@convention(block)</code> is necessary</strong></p>

<p><img src="https://via.placeholder.com/15/f03c15/000000?text=+" alt="#f03c15"> <strong>For hook at <code>before</code> and <code>after</code>. The closure's args have to be empty or the same as method. The return type has to be <code>void</code></strong></p>

<ol start="3">
<li>Totally override the mehtod for specified instance. You can call original with the same parameters or different parameters. Don't even call the original method if you want.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let object = MyObject()
let token = try? hookInstead(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { original, a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4

    // run original function
    let result = original(a, b) // Or change the parameters: let result = original(-1, -2)
    print("original result is \(result)") // result = 7
    return 9
    } as @convention(block) ((Int, Int) -> Int, Int, Int) -> Int)
let result = object.sumFunc(a: 3, b: 4) // result
print("hooked result is \(result)") // result = 9
token?.cancelHook() // cancel the hook
</code>```

 For hook with instead. The closure's first argument has to be a closure which has the same types with the method. The rest args and return type have to be the same as the method.

Perform the hook closure before executing the method of all instances of the class.

let token = try? hookBefore(targetClass: MyObject.self, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject().noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
```

<ol start="5">
<li>Perform the hook closure before executing the class method.</li>
</ol>

<pre class="lang-swift prettyprint-override"><code>let token = try? hookClassMethodBefore(targetClass: MyObject.self, selector: #selector(MyObject.classMethodNoArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject.classMethodNoArgsNoReturnFunc()
token?.cancelHook() // cancel the hook
</code>```

Title: Swift function swizzling / runtime

Body:
A safe, easy, powerful and efficient hook framework for iOS (Support Swift and Objective-C). https://github.com/623637646/SwiftHook

For example, this is your class

class MyObject {
    @objc dynamic func noArgsNoReturnFunc() {
    }
    @objc dynamic func sumFunc(a: Int, b: Int) -> Int {
        return a + b
    }
    @objc dynamic class func classMethodNoArgsNoReturnFunc() {
    }
}

 The key words of methods @objc and dynamic are necessary

 The class doesn't have to inherit from NSObject. If the class is written by Objective-C, Just hook it without any more effort

Perform the hook closure before executing specified instance's method.

let object = MyObject()
let token = try? hookBefore(object: object, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
object.noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook

Perform the hook closure after executing specified instance's method. And get the parameters.

let object = MyObject()
let token = try? hookAfter(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4
    } as @convention(block) (Int, Int) -> Void)
_ = object.sumFunc(a: 3, b: 4)
token?.cancelHook() // cancel the hook

 The key word @convention(block) is necessary

 For hook at before and after. The closure's args have to be empty or the same as method. The return type has to be void

Totally override the mehtod for specified instance. You can call original with the same parameters or different parameters. Don't even call the original method if you want.

let object = MyObject()
let token = try? hookInstead(object: object, selector: #selector(MyObject.sumFunc(a:b:)), closure: { original, a, b in
    // get the arguments of the function
    print("arg1 is \(a)") // arg1 is 3
    print("arg2 is \(b)") // arg2 is 4

    // run original function
    let result = original(a, b) // Or change the parameters: let result = original(-1, -2)
    print("original result is \(result)") // result = 7
    return 9
    } as @convention(block) ((Int, Int) -> Int, Int, Int) -> Int)
let result = object.sumFunc(a: 3, b: 4) // result
print("hooked result is \(result)") // result = 9
token?.cancelHook() // cancel the hook

 For hook with instead. The closure's first argument has to be a closure which has the same types with the method. The rest args and return type have to be the same as the method.

Perform the hook closure before executing the method of all instances of the class.

let token = try? hookBefore(targetClass: MyObject.self, selector: #selector(MyObject.noArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject().noArgsNoReturnFunc()
token?.cancelHook() // cancel the hook

Perform the hook closure before executing the class method.

let token = try? hookClassMethodBefore(targetClass: MyObject.self, selector: #selector(MyObject.classMethodNoArgsNoReturnFunc)) {
    // run your code
    print("hooked!")
}
MyObject.classMethodNoArgsNoReturnFunc()
token?.cancelHook() // cancel the hook


问:
Error to insert capture image data to ImageView in fragment
I want to display a photo from device camera to an Image View I did it before with activity but when I try it on fragment I found that problem:

```<code> java.lang.RuntimeException: Failure delivering result
 ResultInfo{who=null, request=1888, result=-1, data=Intent {
 act=inline-data (has extras) }} to activity
 {com.example.uhf/com.example.uhf.activity.UHFMainActivity}:
 java.lang.NullPointerException: Attempt to invoke virtual method 'void
 android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a
 null object reference
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4295)
</code>```

my code is too simple:

```<code>ImageView person_photo;
private static final int CAMERA_REQUEST = 1888;

 Button open_camera = (Button)getView().findViewById(R.id.take_photo);
        open_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i,CAMERA_REQUEST);

            }
        });

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != RESULT_CANCELED){
            if (requestCode == CAMERA_REQUEST) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                person_photo.setImageBitmap(photo);
            }
        }

    }
</code>```

答:
get the reference of the person_image view.

```<code>person_photo= (ImageView)findViewById(R.id.person_photo_id);
</code>```

I hope works!

Body:
I want to display a photo from device camera to an Image View I did it before with activity but when I try it on fragment I found that problem:

 java.lang.RuntimeException: Failure delivering result
 ResultInfo{who=null, request=1888, result=-1, data=Intent {
 act=inline-data (has extras) }} to activity
 {com.example.uhf/com.example.uhf.activity.UHFMainActivity}:
 java.lang.NullPointerException: Attempt to invoke virtual method 'void
 android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a
 null object reference
         at android.app.ActivityThread.deliverResults(ActivityThread.java:4295)

my code is too simple:

ImageView person_photo;
private static final int CAMERA_REQUEST = 1888;

 Button open_camera = (Button)getView().findViewById(R.id.take_photo);
        open_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(i,CAMERA_REQUEST);

            }
        });

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode != RESULT_CANCELED){
            if (requestCode == CAMERA_REQUEST) {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                person_photo.setImageBitmap(photo);
            }
        }

    }

Body:
get the reference of the person_image view.

person_photo= (ImageView)findViewById(R.id.person_photo_id);

I hope works!


问:
Mathtex and libpng kivy recipe
I need this library to be compiled with kivy/buildozer: https://code.google.com/p/mathtex/

It depends on freetype, numpy and libpng.

Since I'm total newbie in bash scripting, can someone write python-for-android recipe for this?
Freetype and numpy recipes already exist, so, I guess, I need recipe for libpng and mathtex.

Thank you.

答: Try to make your own recipe using the this link and place it in the folder named recipe in the pythonforandroid. rename the recipe file as__init__.py.

Title: Mathtex and libpng kivy recipe


问:
Blazor concurrency problem using Entity Framework Core
My goal

I want to create a new IdentityUser and show all the users already created through the same Blazor page. This page has:

a form through you will create an IdentityUser

a third-party's grid component (DevExpress Blazor DxDataGrid) that shows all users using UserManager.Users property. This component accepts an IQueryable as a data source.

Problem

When I create a new user through the form (1) I will get the following concurrency error:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread-safe.

I think the problem is related to the fact that CreateAsync(IdentityUser user) and UserManager.Users are referring the same DbContext

The problem isn't related to the third-party's component because I reproduce the same problem replacing it with a simple list.

Step to reproduce the problem

create a new Blazor server-side project with authentication

change Index.razor with the following code:

```<code>@page "/"

<h1>Hello, world!</h1>

number of users: @Users.Count()
<button @onclick="@(async () => await Add())">click me</button>
<ul>
@foreach(var user in Users)
{
    <li>@user.UserName</li>
}
</ul>

@code {
    [Inject] UserManager<IdentityUser> UserManager { get; set; }

    IQueryable<IdentityUser> Users;

    protected override void OnInitialized()
    {
        Users = UserManager.Users;
    }

    public async Task Add()
    {
        await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
    }
}
</code>```

What I noticed

If I change Entity Framework provider from SqlServer to Sqlite then the error will never show.

System info

ASP.NET Core 3.1.0 Blazor Server-side

Entity Framework Core 3.1.0 based on SqlServer provider

What I have already seen

Blazor A second operation started on this context before a previous operation completed: the solution proposed doesn't work for me because even if I change my DbContext scope from Scoped to Transient I still using the same instance of UserManager and its contains the same instance of DbContext

other guys on StackOverflow suggests creating a new instance of DbContext per request. I don't like this solution because it is against Dependency Injection principles. Anyway, I can't apply this solution because DbContext is wrapped inside UserManager

Create a generator of DbContext: this solution is pretty like the previous one.

Using Entity Framework Core with Blazor

Why I want to use IQueryable

I want to pass an IQueryable as a data source for my third-party's component because its can apply pagination and filtering directly to the Query. Furthermore IQueryable is sensitive to CUD
 operations.

答:
I downloaded your sample and was able to reproduce your problem. The problem is caused because Blazor will re-render the component as soon as you await in code called from EventCallback (i.e. your Add method).

```<code>public async Task Add()
{
    await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
}
</code>```

If you add a System.Diagnostics.WriteLine to the start of Add and to the end of Add, and then also add one at the top of your Razor page and one at the bottom, you will see the following output when you click your button.

```<code>//First render
Start: BuildRenderTree
End: BuildRenderTree

//Button clicked
Start: Add
(This is where the `await` occurs`)
Start: BuildRenderTree
Exception thrown
</code>```

You can prevent this mid-method rerender like so....

```<code>protected override bool ShouldRender() => MayRender;

public async Task Add()
{
    MayRender = false;
    try
    {
        await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
    }
    finally
    {
        MayRender = true;
    }
}
</code>```

This will prevent re-rendering whilst your method is running. Note that if you define Users as IdentityUser[] Users you will not see this problem because the array is not set until after the await has completed and is not lazy evaluated, so you don't get this reentrancy problem.

I believe you want to use IQueryable<T> because you need to pass it to 3rd party components. The problem is, different components can be rendered on different threads, so if you pass IQueryable<T> to other components then

They might render on different threads and cause the same problem.

They most likely will have an await in the code that consumes the IQueryable<T> and you'll have the same problem again.

Ideally, what you need is for the 3rd party component to have an event that asks you for data, giving you some kind of query definition (page number etc). I know Telerik Grid does this, as do others.

That way you can do the following

Acquire a lock

Run the query with the filter applied

Release the lock

Pass the results to the component

You cannot use lock() in async code, so you'd need to use something like SpinLock to lock a resource.

```<code>private SpinLock Lock = new SpinLock();

private async Task<WhatTelerikNeeds> ReadData(SomeFilterFromTelerik filter)
{
  bool gotLock = false;
  while (!gotLock) Lock.Enter(ref gotLock);
  try
  {
    IUserIdentity result = await ApplyFilter(MyDbContext.Users, filter).ToArrayAsync().ConfigureAwait(false);
    return new WhatTelerikNeeds(result);
  }
  finally
  {
    Lock.Exit();
  }
}
</code>```

Body:
My goal

I want to create a new IdentityUser and show all the users already created through the same Blazor page. This page has:

a form through you will create an IdentityUser

a third-party's grid component (DevExpress Blazor DxDataGrid) that shows all users using UserManager.Users property. This component accepts an IQueryable as a data source.

Problem

When I create a new user through the form (1) I will get the following concurrency error:

InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread-safe.

I think the problem is related to the fact that CreateAsync(IdentityUser user) and UserManager.Users are referring the same DbContext

The problem isn't related to the third-party's component because I reproduce the same problem replacing it with a simple list.

Step to reproduce the problem

create a new Blazor server-side project with authentication

change Index.razor with the following code:

@page "/"

Hello, world!

number of users: @Users.Count()
<button @onclick="@(async () => await Add())">click me</button>

@foreach(var user in Users)
{

@user.UserName

}

@code {
    [Inject] UserManager<IdentityUser> UserManager { get; set; }

    IQueryable<IdentityUser> Users;

    protected override void OnInitialized()
    {
        Users = UserManager.Users;
    }

    public async Task Add()
    {
        await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
    }
}

What I noticed

If I change Entity Framework provider from SqlServer to Sqlite then the error will never show.

System info

ASP.NET Core 3.1.0 Blazor Server-side

Entity Framework Core 3.1.0 based on SqlServer provider

What I have already seen

Blazor A second operation started on this context before a previous operation completed: the solution proposed doesn't work for me because even if I change my DbContext scope from Scoped to Transient I still using the same instance of UserManager and its contains the same instance of DbContext

other guys on StackOverflow suggests creating a new instance of DbContext per request. I don't like this solution because it is against Dependency Injection principles. Anyway, I can't apply this solution because DbContext is wrapped inside UserManager

Create a generator of DbContext: this solution is pretty like the previous one.

Using Entity Framework Core with Blazor

Why I want to use IQueryable

I want to pass an IQueryable as a data source for my third-party's component because its can apply pagination and filtering directly to the Query. Furthermore IQueryable is sensitive to CUD
 operations.

Body:
I downloaded your sample and was able to reproduce your problem. The problem is caused because Blazor will re-render the component as soon as you await in code called from EventCallback (i.e. your Add method).

public async Task Add()
{
    await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
}

If you add a System.Diagnostics.WriteLine to the start of Add and to the end of Add, and then also add one at the top of your Razor page and one at the bottom, you will see the following output when you click your button.

//First render
Start: BuildRenderTree
End: BuildRenderTree

//Button clicked
Start: Add
(This is where the `await` occurs`)
Start: BuildRenderTree
Exception thrown

You can prevent this mid-method rerender like so....

protected override bool ShouldRender() => MayRender;

public async Task Add()
{
    MayRender = false;
    try
    {
        await UserManager.CreateAsync(new IdentityUser { UserName = $"test_{Guid.NewGuid().ToString()}" });
    }
    finally
    {
        MayRender = true;
    }
}

This will prevent re-rendering whilst your method is running. Note that if you define Users as IdentityUser[] Users you will not see this problem because the array is not set until after the await has completed and is not lazy evaluated, so you don't get this reentrancy problem.

I believe you want to use IQueryable<T> because you need to pass it to 3rd party components. The problem is, different components can be rendered on different threads, so if you pass IQueryable<T> to other components then

They might render on different threads and cause the same problem.

They most likely will have an await in the code that consumes the IQueryable<T> and you'll have the same problem again.

Ideally, what you need is for the 3rd party component to have an event that asks you for data, giving you some kind of query definition (page number etc). I know Telerik Grid does this, as do others.

That way you can do the following

Acquire a lock

Run the query with the filter applied

Release the lock

Pass the results to the component

You cannot use lock() in async code, so you'd need to use something like SpinLock to lock a resource.

private SpinLock Lock = new SpinLock();

private async Task<WhatTelerikNeeds> ReadData(SomeFilterFromTelerik filter)
{
  bool gotLock = false;
  while (!gotLock) Lock.Enter(ref gotLock);
  try
  {
    IUserIdentity result = await ApplyFilter(MyDbContext.Users, filter).ToArrayAsync().ConfigureAwait(false);
    return new WhatTelerikNeeds(result);
  }
  finally
  {
    Lock.Exit();
  }
}


问:
Invalid JSON primitive: object
I am trying to send a stringified JSON object to MVC method via the following jQuery Ajax call:

```<code>$.ajax({
           type: "POST",
           url: "UpdateItem",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           processData : false,
           data:
               {
                    item: JSON.stringify(_item)
               },
           success: function (data) {
               alert(data);
           },
           error: function (x, t, m, b) {
               DisplayErrorMessage(x.responseText);
           }
       });
</code>```

and the stringified version of my data is as follows:

```<code>{
    "Id": 4,
    "ParentId": 1,
    "TypeId": 2,
    "TypeText": "Solid",
    "ItemNo": 8,
    "StandartTypeId": 7,
    "StandartTypeText": "Dept",
    "GradeTypeId": 6,
    "GradeTypeText": null,
    "Thickness": 0.044,
    "ThicknessToleranceId": 1,
    "ThicknessToleranceText": null,
    "Width": 42,
    "MinWeightId": 6,
    "MinWeight": null,
    "MinWeight2": null,
    "MaxWeightId": 8,
    "MaxWeight1": null,
    "MaxWeight2": null,
    "DefId": null,
    "Quantity": 330690,
    "QuantityToleranceId": 3,
    "QuantityToleranceText": "",
    "ProductionDate": "2014-11-05T22:00:00.000Z",
    "PortId": 3,
    "PortText": null,
    "DeliveryDate": "2014-10-08T21:00:00.000Z",
    "MaterialTypeId": 2,
    "MaterialTypeText": "",
    "FeePrepaid": 30,
    "Price": 525,
    "Extra1": 0,
    "Extra1": 0,
    "CurrencyId": 2,
    "CurrencyText": "",
    "StatusId": 2,
    "StatusText": "",
    "ReasonId": null,
    "ReasonText": null,
    "Note": "New note",
    "CreateDate": "2014-11-06T09:12:29.661Z",
    "CreateUserId": 0,
    "CreateUserText": "",
    "CancelDate": null,
    "CancelUserId": null,
    "CancelUserText": null,
    "ChemicalProperties": null,
    "TechnicalProperties": null,
    "Remarks": null
}
</code>```

I have successfully validated my JSON object via http://jsonlint.com/.

I try to get the response into the following method :

```<code>public JsonResult UpdateItem(string json)
{
    var js = new JavaScriptSerializer();
    var deserializedItem = (object[])js.DeserializeObject(json);

    return Json(null);
}
</code>```

But when I try to post via Ajax I get the following error Message before ASP.NET MVC Controller method call:

Invalid JSON primitive: object.
  Exception Details: System.ArgumentException: Invalid JSON primitive: object.

And my Stack Trace is as follows:

```<code>[ArgumentException: Invalid JSON primitive: object.]
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +915
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +597
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth) +354
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +531
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) +108
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +210
System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input) +86
System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +191
System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +19
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +34
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +171
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +460
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +281
System.Web.Mvc.ControllerBase.get_ValueProvider() +40
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +60
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
</code>```

答:
Just run with my code
In my reactjs

```<code>$.ajax({
            type: 'POST',
            url: 'http://example.com/ExampleService/ExampleMethod',
            //data: JSON.stringify({transferData: objImages}), => Wrong
            //data: { transferData: JSON.stringify(objImages) }, => Wrong
            //data: JSON.stringify(objImages), => Wrong
            data: JSON.stringify({ 'transferData': JSON.stringify(objImages) }), // transferData is name
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });
</code>```

In asp.net mvc webservice

```<code>public ActionResult ExampleMethod(string transferData)
    {
        //dynamic transferObj = JsonConvert.DeserializeObject(transferData);
        //return Json(transferObj);

        return Json(transferData);
    }
</code>```

Title: Invalid JSON primitive: object

Body:
I am trying to send a stringified JSON object to MVC method via the following jQuery Ajax call:

$.ajax({
           type: "POST",
           url: "UpdateItem",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           processData : false,
           data:
               {
                    item: JSON.stringify(_item)
               },
           success: function (data) {
               alert(data);
           },
           error: function (x, t, m, b) {
               DisplayErrorMessage(x.responseText);
           }
       });

and the stringified version of my data is as follows:

{
    "Id": 4,
    "ParentId": 1,
    "TypeId": 2,
    "TypeText": "Solid",
    "ItemNo": 8,
    "StandartTypeId": 7,
    "StandartTypeText": "Dept",
    "GradeTypeId": 6,
    "GradeTypeText": null,
    "Thickness": 0.044,
    "ThicknessToleranceId": 1,
    "ThicknessToleranceText": null,
    "Width": 42,
    "MinWeightId": 6,
    "MinWeight": null,
    "MinWeight2": null,
    "MaxWeightId": 8,
    "MaxWeight1": null,
    "MaxWeight2": null,
    "DefId": null,
    "Quantity": 330690,
    "QuantityToleranceId": 3,
    "QuantityToleranceText": "",
    "ProductionDate": "2014-11-05T22:00:00.000Z",
    "PortId": 3,
    "PortText": null,
    "DeliveryDate": "2014-10-08T21:00:00.000Z",
    "MaterialTypeId": 2,
    "MaterialTypeText": "",
    "FeePrepaid": 30,
    "Price": 525,
    "Extra1": 0,
    "Extra1": 0,
    "CurrencyId": 2,
    "CurrencyText": "",
    "StatusId": 2,
    "StatusText": "",
    "ReasonId": null,
    "ReasonText": null,
    "Note": "New note",
    "CreateDate": "2014-11-06T09:12:29.661Z",
    "CreateUserId": 0,
    "CreateUserText": "",
    "CancelDate": null,
    "CancelUserId": null,
    "CancelUserText": null,
    "ChemicalProperties": null,
    "TechnicalProperties": null,
    "Remarks": null
}

I have successfully validated my JSON object via http://jsonlint.com/.

I try to get the response into the following method :

public JsonResult UpdateItem(string json)
{
    var js = new JavaScriptSerializer();
    var deserializedItem = (object[])js.DeserializeObject(json);

    return Json(null);
}

But when I try to post via Ajax I get the following error Message before ASP.NET MVC Controller method call:

Invalid JSON primitive: object.
  Exception Details: System.ArgumentException: Invalid JSON primitive: object.

And my Stack Trace is as follows:

[ArgumentException: Invalid JSON primitive: object.]
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject() +915
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +597
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeList(Int32 depth) +354
System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth) +531
System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer) +108
System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit) +210
System.Web.Script.Serialization.JavaScriptSerializer.DeserializeObject(String input) +86
System.Web.Mvc.JsonValueProviderFactory.GetDeserializedObject(ControllerContext controllerContext) +191
System.Web.Mvc.JsonValueProviderFactory.GetValueProvider(ControllerContext controllerContext) +19
System.Web.Mvc.<>c__DisplayClassc.<GetValueProvider>b__7(ValueProviderFactory factory) +34
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +171
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +460
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
System.Web.Mvc.ValueProviderFactoryCollection.GetValueProvider(ControllerContext controllerContext) +281
System.Web.Mvc.ControllerBase.get_ValueProvider() +40
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +60
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +117
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Body:
Just run with my code
In my reactjs

$.ajax({
            type: 'POST',
            url: 'http://example.com/ExampleService/ExampleMethod',
            //data: JSON.stringify({transferData: objImages}), => Wrong
            //data: { transferData: JSON.stringify(objImages) }, => Wrong
            //data: JSON.stringify(objImages), => Wrong
            data: JSON.stringify({ 'transferData': JSON.stringify(objImages) }), // transferData is name
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function (data) {
                alert(data);
            },
            failure: function (errMsg) {
                alert(errMsg);
            }
        });

In asp.net mvc webservice

public ActionResult ExampleMethod(string transferData)
    {
        //dynamic transferObj = JsonConvert.DeserializeObject(transferData);
        //return Json(transferObj);

        return Json(transferData);
    }


问:
value of a textarea element
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
  </div>
</form></code>```

It gives undefined as output

答:
function postComment(element) {
  const content = element.previousElementSibling.value;
  console.log(content);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
  </div>
</form></code>```

Your problem is that you use previousSibling when it should be previousElementSibling.

Title: value of a textarea element

Body:
I want to use value of a textarea element, but I am not able to get it

function postComment(element) {
  const content = element.previousSibling.value;
  console.log(content);
}

<form action="" class="comment-editor">

    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>

</form>

It gives undefined as output

Body:
function postComment(element) {
  const content = element.previousElementSibling.value;
  console.log(content);
}

<form action="" class="comment-editor">
  <div class="form-group">
    <textarea class="form-control" name="" id="someid" rows="4"></textarea>
    <button type="button" class="btn btn-primary my-2" onClick="postComment(this)">Comment</button>
  </div>
</form>

Your problem is that you use previousSibling when it should be previousElementSibling.


问:
How do I add things like a background or an input box to a new window that's opened?
I want to know how to customize the new window that is opened, by pressing a button in the main window. Here is the code I am using:

```<code>from tkinter import *
import tkinter as tk

root = Tk()

def create_window():
    tk.Toplevel(root)

button1 = Button(root, text = "Add a task", command = create_window)
button1.place(x=1, y=1)

root.mainloop()
</code>```

Here is the code im using, I want to add an input box where I can write stuff into and the things I write go on the first window. Is that a little too complicated for a beginner like me?

```<code>from tkinter import *
import tkinter as tk

root = Tk()

def create_window():
    tk.Toplevel(root)

button1 = Button(root, text = "Add a task", command = create_window) #Makes a button with a commmand to open another window
button1.place(x=1, y=1) #Button position

root.state("zoomed") #Maximizes the window

root.mainloop()
</code>```

答:
You can change the configuration of a tk.TopLevel upon clicking a button. In the following example, the background color of each opened TopLevel window is randomly set/reset upon pressing the Customize button:

```<code>import random
import tkinter as tk
from _tkinter import TclError

COLORS = ['blue', 'yellow', 'red', 'green']

def create_window():
    toplevels.append(tk.Toplevel(root))

def customize_top():
    for toplevel in toplevels:
        try:
            toplevel.configure(bg=random.choice(COLORS))
        except TclError:
            pass

root = tk.Tk()

toplevels = []

button1 = tk.Button(root, text = "Add a task", command=create_window)
button1.pack()
button2 = tk.Button(root, text = "Customize", command=customize_top)
button2.pack()

root.mainloop()
</code>```

Body:
I want to know how to customize the new window that is opened, by pressing a button in the main window. Here is the code I am using:

from tkinter import *
import tkinter as tk

root = Tk()

def create_window():
    tk.Toplevel(root)

button1 = Button(root, text = "Add a task", command = create_window)
button1.place(x=1, y=1)

root.mainloop()

Here is the code im using, I want to add an input box where I can write stuff into and the things I write go on the first window. Is that a little too complicated for a beginner like me?

from tkinter import *
import tkinter as tk

root = Tk()

def create_window():
    tk.Toplevel(root)

button1 = Button(root, text = "Add a task", command = create_window) #Makes a button with a commmand to open another window
button1.place(x=1, y=1) #Button position

root.state("zoomed") #Maximizes the window

root.mainloop()

Body:
You can change the configuration of a tk.TopLevel upon clicking a button. In the following example, the background color of each opened TopLevel window is randomly set/reset upon pressing the Customize button:

import random
import tkinter as tk
from _tkinter import TclError

COLORS = ['blue', 'yellow', 'red', 'green']

def create_window():
    toplevels.append(tk.Toplevel(root))

def customize_top():
    for toplevel in toplevels:
        try:
            toplevel.configure(bg=random.choice(COLORS))
        except TclError:
            pass

root = tk.Tk()

toplevels = []

button1 = tk.Button(root, text = "Add a task", command=create_window)
button1.pack()
button2 = tk.Button(root, text = "Customize", command=customize_top)
button2.pack()

root.mainloop()


问:
How to render the Vue component to a another (new) page in Vue-js using router?
Currently my App renders on the same page, but I want it to render to a new page. I tried rendering by using render: h => h(App), but it still renders on the same page.

Here's the Vue file from where the router will be linked (Risks.vue):

```<code><router-link to="/risk-info">
<td>{{item.Model}}</td>
<td>{{item.Vulnerability}}</td>
<td>{{item.Unresolved}}</td>
</router-link>
<router-view/>
</code>```

The below file links my router to the Component (index.js):

```<code>import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/risk-info',
    name: 'RiskInfo',
    component: () => import('../components/breakdown/risks/VulnerabilityDetails.vue')
  }
]

const router = new VueRouter({
  routes
})

export default router
</code>```

And lastly, this is the file that defines the Vue object (main.js):

```<code>new Vue({
  router,
  render: h => h(App),
  store,
}).$mount('#app')
</code>```

答:
If you mean, how can you open the link in a new tab, then you can use the target attribute on a <router-link>

```<code><router-link to="/risk-info" target="_blank">...</router-link>
</code>```

Although obviously you'll lose any application state, as it'll load a new instance of your app.

Body:
Currently my App renders on the same page, but I want it to render to a new page. I tried rendering by using render: h => h(App), but it still renders on the same page.

Here's the Vue file from where the router will be linked (Risks.vue):

<router-link to="/risk-info">
{{item.Model}}
{{item.Vulnerability}}
{{item.Unresolved}}
</router-link>
<router-view/>

The below file links my router to the Component (index.js):

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/risk-info',
    name: 'RiskInfo',
    component: () => import('../components/breakdown/risks/VulnerabilityDetails.vue')
  }
]

const router = new VueRouter({
  routes
})

export default router

And lastly, this is the file that defines the Vue object (main.js):

new Vue({
  router,
  render: h => h(App),
  store,
}).$mount('#app')

Body:
If you mean, how can you open the link in a new tab, then you can use the target attribute on a <router-link>

<router-link to="/risk-info" target="_blank">...</router-link>

Although obviously you'll lose any application state, as it'll load a new instance of your app.


问:
While doing form validation on submit a form, the component is not updating in React
I have a login in react,

```<code>import React, { Fragment, useState } from 'react';
import { useHistory } from "react-router-dom";
import { useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';

import { auth } from '../actions';

export const Login = () => {
   let history = useHistory();
   const dispatch = useDispatch();

   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');
   const [error, setError] = useState({email: '', password: ''});

   const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|.
    (\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);

   const handleChange = e => {
      e.persist();
      const { name, value } = e.target;
      let validationError = error;

      switch(name) {
        case 'email':
            setEmail(value);
            validationError.email = validEmailRegex.test(value) ? '' : 'Email is not valid';
            break;
        case 'password':
            setPassword(value)
            validationError.password = value.length < 8 ? 'Password must be 8 characters
            long!': '';
            break;
        case 'submit':
            validationError.email = email.length < 1 ? 'Email is required'  : '';
            validationError.password = password.length < 1 ? 'Password is required'  : '';
        default:
            break;
      };
    setError(validationError);
    console.log('in change', error)
   };

const validateForm = (errors) => {
    let valid = true;
    Object.values(errors).forEach(
      // if we have an error string set valid to false
      (val) => val.length > 0 && (valid = false)
    );
    return valid;
};

const validate = () => {
    console.log('email,password', email, password);
    let validationError = error;
    if(!email){
        validationError.email = 'Email is required';
    }
    if(!password){
        validationError.password = 'Password is required';
    }
    setError(validationError);
    console.log('in validate',error)
};

const onSubmit = e => {
    e.preventDefault();
    validate();
    console.log('error on submit', error);
    if(validateForm(error)) {
        dispatch(auth(email, password, true));
        history.replace('/home');
      }else{
        console.error('Invalid Form', error)
      }
};
return (
    <Fragment>
        <div className="w-full max-w-sm container mt-20 mx-auto">
            <form onSubmit={onSubmit}>
                <div className="w-full mb-5">
                    <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" htmlFor="email">
                        Email
                    </label>
                    <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600" value={email} name='email' onChange={(e) => handleChange(e)} type="text" placeholder="Email" />
                    { error && <span style={{color: "red"}}>{error['email']}</span>}
                </div>
                <div className="w-full  mb-5">
                    <label className="block uppercase tracking-wide text-gray-700 text-xs font-bold mb-2" htmlFor="password">
                        Password
                    </label>
                    <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600" value={password} name='password' onChange={(e) => handleChange(e)} type="password" placeholder="Password" />
                    { error && <span style={{color: "red"}}>{error['password']}</span>}
                </div>
                <div className="flex items-center justify-between">
                    <button className="mt-5 bg-green-400 w-full hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                        Login
                    </button>
                </div>
                <div className="text-center mt-4 text-gray-500"><Link to='/'>Cancel</Link></div>
            </form>
        </div>
    </Fragment>
)
</code>```

}

I have added field validation in onchange and in submit, the onchange validation is working correctly and showing erros. Validation on submit is also wokring fine, but still the component is not showing error when I try submit without any change in fields.

I am new to react, I dont know if this is the correct way to do that. Thanks in advance.

答:
I put your code in a code sandbox and it seems to work just fine. Note that i removed className properties and commented stuff that is not necessary to test your issue like redux imports.

Since I removed the className properties this could be an CSS issue, where your error span is actually rendered but not visible (check out the dev tools of your browser to see if the span is really not there).

Also I would recommend you to use a library if you use a lot of forms, since state handling + validation could get quite complicated and there are plenty solutions out there.

I wrote my own library - react-fluent-form - feel free to check that out.

EDIT

The issue here is that when you update the error object using setError you always pass the same object reference:

// this is not doing a copy
// validationError will have the same reference as error
let validationError = error;

// ...

// following line will not trigger a rerender
setError(validationError);
```

<p>Since <code>error</code> and <code>validationError</code> have the same reference, <code>react</code> will asume no change has happened, thus it will cause bail out of a state update. If you work with complex types (like objects or arrays) in state you always need to create a new reference instead of adapting the previous one:</p>

<pre class="lang-js prettyprint-override"><code>// this is an actual copy using the spread operator
// validationError will have different reference than error
let validationError = {...error};

// ...

// triggers rerender as expected
setError(validationError);
</code>```

EDIT 2

I added a return value for validate to use the updated validationError object when calling validateForm.

const validate = () => {
    //..
    let validationError = { ...error };

    // ...

    return validationError;
};

const onSubmit = e => {
    // ...
    const validationError = validate();

    if (validateForm(validationError)) {
    //...
    }
};
```

See the updated code sandbox.

Body:
I have a login in react,

import React, { Fragment, useState } from 'react';
import { useHistory } from "react-router-dom";
import { useDispatch } from 'react-redux';
import { Link } from 'react-router-dom';

import { auth } from '../actions';

export const Login = () => {
   let history = useHistory();
   const dispatch = useDispatch();

   const [email, setEmail] = useState('');
   const [password, setPassword] = useState('');
   const [error, setError] = useState({email: '', password: ''});

   const validEmailRegex = RegExp(/^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|.
    (\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i);

   const handleChange = e => {
      e.persist();
      const { name, value } = e.target;
      let validationError = error;

      switch(name) {
        case 'email':
            setEmail(value);
            validationError.email = validEmailRegex.test(value) ? '' : 'Email is not valid';
            break;
        case 'password':
            setPassword(value)
            validationError.password = value.length < 8 ? 'Password must be 8 characters
            long!': '';
            break;
        case 'submit':
            validationError.email = email.length < 1 ? 'Email is required'  : '';
            validationError.password = password.length < 1 ? 'Password is required'  : '';
        default:
            break;
      };
    setError(validationError);
    console.log('in change', error)
   };

const validateForm = (errors) => {
    let valid = true;
    Object.values(errors).forEach(
      // if we have an error string set valid to false
      (val) => val.length > 0 && (valid = false)
    );
    return valid;
};

const validate = () => {
    console.log('email,password', email, password);
    let validationError = error;
    if(!email){
        validationError.email = 'Email is required';
    }
    if(!password){
        validationError.password = 'Password is required';
    }
    setError(validationError);
    console.log('in validate',error)
};

const onSubmit = e => {
    e.preventDefault();
    validate();
    console.log('error on submit', error);
    if(validateForm(error)) {
        dispatch(auth(email, password, true));
        history.replace('/home');
      }else{
        console.error('Invalid Form', error)
      }
};
return (
    <Fragment>

            <form onSubmit={onSubmit}>

                        Email

                    <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600" value={email} name='email' onChange={(e) => handleChange(e)} type="text" placeholder="Email" />
                    { error && {error['email']}}

                        Password

                    <input className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:text-gray-600" value={password} name='password' onChange={(e) => handleChange(e)} type="password" placeholder="Password" />
                    { error && {error['password']}}

                    <button className="mt-5 bg-green-400 w-full hover:bg-green-500 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline">
                        Login
                    </button>

<Link to='/'>Cancel</Link>

            </form>

    </Fragment>
)

}

I have added field validation in onchange and in submit, the onchange validation is working correctly and showing erros. Validation on submit is also wokring fine, but still the component is not showing error when I try submit without any change in fields.

I am new to react, I dont know if this is the correct way to do that. Thanks in advance.

Body:
I put your code in a code sandbox and it seems to work just fine. Note that i removed className properties and commented stuff that is not necessary to test your issue like redux imports.

Since I removed the className properties this could be an CSS issue, where your error span is actually rendered but not visible (check out the dev tools of your browser to see if the span is really not there).

Also I would recommend you to use a library if you use a lot of forms, since state handling + validation could get quite complicated and there are plenty solutions out there.

I wrote my own library - react-fluent-form - feel free to check that out.

EDIT

The issue here is that when you update the error object using setError you always pass the same object reference:

// this is not doing a copy
// validationError will have the same reference as error
let validationError = error;

// ...

// following line will not trigger a rerender
setError(validationError);

Since error and validationError have the same reference, react will asume no change has happened, thus it will cause bail out of a state update. If you work with complex types (like objects or arrays) in state you always need to create a new reference instead of adapting the previous one:

// this is an actual copy using the spread operator
// validationError will have different reference than error
let validationError = {...error};

// ...

// triggers rerender as expected
setError(validationError);

EDIT 2

I added a return value for validate to use the updated validationError object when calling validateForm.

const validate = () => {
    //..
    let validationError = { ...error };

    // ...

    return validationError;
};

const onSubmit = e => {
    // ...
    const validationError = validate();

    if (validateForm(validationError)) {
    //...
    }
};

See the updated code sandbox.


问:
design container with fixed value
I am trying to create a Card in React which look like the first one on the left:

So I have created a class as below (plz do not take care of the immage, I just play with the text position for now)

```<code>import React from 'react';
import BlueButton from '../materialdesign/BlueButton'
import TextContents from '../../assets/translations/TextContents';
import { Container } from 'react-bootstrap';

class ClassCard extends React.Component {

    render() {
        const tileStyle = {
            postion: "absolute",
            topMargin: "100px !important",
            textAlign: "center",
            width: "300px",
            height: "460px",
            margin: "20px",
            backgroundColor: "#999999",
            boxShadow: "0px 8px 18px 0 rgba(0,0,0,0.14)",
            borderRadius: 21,
        }

        const titleStyle = {
            display: "inline-block",
            width: "200px",
            fontFamily: "Fredoka One",
            fontSize: 20 ,
            fontWeight: "bold",
            color: "#ffffffff",
        }

        const descStyle = {
            display: "inline-block",
            width: "200px",
            fontFamily: "Source Sans Pro",
            fontSize: 14 ,
            fontWeight: "bold",
            textAlign: "center",
            color: "#ffffffff",
        }

        return(
                <Container style={tileStyle}>
                    <div>
                        <p style={titleStyle}>{this.props.title}</p>
                        <p style={descStyle}>{this.props.desc}</p>
                    </div>
                    <div style={{position: "relative", bottom: "-100px", top:"auto !important"}}>
                        <BlueButton textSize="14" link_href="#" text={TextContents.BookBtn} />
                    </div>
                </Container>
        );
    }
}

export default ClassCard;

</code>```

I am trying to make sure that the title is always fixed at the same margin from the top, same for the descriptio and also the book button always at the same place from the bottom. The goal is to make sure that if all the cards are aligned, it has all title, desc and button aligned.

Also, I can't find a way to create an animation to do a nice effect. What I am trying to achieve is when the card is selected or the mouse point is hover, you can see title, desc and button. When not focus or selected or hover, every look like slide down to only display the title. like seen on the second picture on the image above.

The effect should look like slide up and down

Any idea how to fix the position of the text and do this animation

Thanks a lot

答:
use position:absoulut to do the positioning

```<code><head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            width: 40%;
            position: relative;
            display: inline-block;
            height: 500px;
            background: lightblue;
        }

        .title {
            position: absolute;
            top: 10%;
        }
        .des {
            position: absolute;
            top: 30%;
        }
        .btn {
            position: absolute;
            top: 50%;
        }
    </style>
</head>

<body>
    <div class="container">
        <p class="title">This is a title</p>
        <p class="des">This is a discription</p>
        <button class="btn">buttom</button>
    </div>
    <div class="container">
        <p class="title">This is a title</p>
        <button class="btn">buttom</button>
    </div>

</body>
</code>```

codepen

Title: design container with fixed value

Body:
I am trying to create a Card in React which look like the first one on the left:

So I have created a class as below (plz do not take care of the immage, I just play with the text position for now)

import React from 'react';
import BlueButton from '../materialdesign/BlueButton'
import TextContents from '../../assets/translations/TextContents';
import { Container } from 'react-bootstrap';

class ClassCard extends React.Component {

    render() {
        const tileStyle = {
            postion: "absolute",
            topMargin: "100px !important",
            textAlign: "center",
            width: "300px",
            height: "460px",
            margin: "20px",
            backgroundColor: "#999999",
            boxShadow: "0px 8px 18px 0 rgba(0,0,0,0.14)",
            borderRadius: 21,
        }

        const titleStyle = {
            display: "inline-block",
            width: "200px",
            fontFamily: "Fredoka One",
            fontSize: 20 ,
            fontWeight: "bold",
            color: "#ffffffff",
        }

        const descStyle = {
            display: "inline-block",
            width: "200px",
            fontFamily: "Source Sans Pro",
            fontSize: 14 ,
            fontWeight: "bold",
            textAlign: "center",
            color: "#ffffffff",
        }

        return(
                <Container style={tileStyle}>

{this.props.title}

{this.props.desc}

                        <BlueButton textSize="14" link_href="#" text={TextContents.BookBtn} />

                </Container>
        );
    }
}

export default ClassCard;

I am trying to make sure that the title is always fixed at the same margin from the top, same for the descriptio and also the book button always at the same place from the bottom. The goal is to make sure that if all the cards are aligned, it has all title, desc and button aligned.

Also, I can't find a way to create an animation to do a nice effect. What I am trying to achieve is when the card is selected or the mouse point is hover, you can see title, desc and button. When not focus or selected or hover, every look like slide down to only display the title. like seen on the second picture on the image above.

The effect should look like slide up and down

Any idea how to fix the position of the text and do this animation

Thanks a lot

Body:
use position:absoulut to do the positioning

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .container {
            width: 40%;
            position: relative;
            display: inline-block;
            height: 500px;
            background: lightblue;
        }

        .title {
            position: absolute;
            top: 10%;
        }
        .des {
            position: absolute;
            top: 30%;
        }
        .btn {
            position: absolute;
            top: 50%;
        }
    </style>
</head>

<body>
    <div class="container">
        <p class="title">This is a title</p>
        <p class="des">This is a discription</p>
        <button class="btn">buttom</button>
    </div>
    <div class="container">
        <p class="title">This is a title</p>
        <button class="btn">buttom</button>
    </div>

</body>

codepen


问:
On the Kafka Java consumer client, is there a way to monitor health status as opposed to simply no-data?
I have a typical kafka consumer/producer app that is polling all the time for data.  Sometimes, there might be no data for hours, but sometimes there could be thousands of messages per second.  Because of this, the application is built so it's always polling, with a 500ms duration timeout.

However, I've noticed that sometimes, if the kafka cluster goes down, the consumer client, once started, won't throw an exception, it will simply timeout at 500ms, and continue returning empty ConsumerRecords<K,V>. So, as far as the application is concerned, there is no data to consume, when in reality, the whole Kafka cluster could be unreachable, but the app itself has no idea.

I checked the docs, and I couldn't find a way to validate consumer health, other than maybe closing the connection and subscribing to the topic every single time, but I really don't want to do that on a long-running application.

What's the best way to validate that the consumer is active and healthy while polling, ideally from the same thread/client object, so that the app can distinguish between no data and an unreachable kafka cluster situation?

答:
I am sure this is not the best way to achieve what you are looking for.

But one simple way which I had implemented in my application is by maintaining a static counter in the application indicating emptyRecordSetReceived. Whenever I receive an empty record set by the poll operation I increment this counter.

This counter was emitted to the Graphite at periodic interval (say every minute) with the help of the Metric registry from the application.

Now let's say you know the maximum time frame for which the message will not be available to consume by this application. For example, say 6 hours. Given that you are polling every 500 Millisecond, you know that if we do not receive the message for 6 hours, the counter would increase by

```<code>2 poll in 1 second * 60 seconds * 60 minutes * 6 hours = 43200.
</code>```

We had placed an alerting check based on this counter value reported to Graphite. This metric used to give me a decent idea if it is a genuine problem from the application or something else is down from the Broker or producer side.

This is just the naive way I had solved this use case to some extent. I would love to hear how it is actually done without maintaining these counters.

Body:
I am sure this is not the best way to achieve what you are looking for.

But one simple way which I had implemented in my application is by maintaining a static counter in the application indicating emptyRecordSetReceived. Whenever I receive an empty record set by the poll operation I increment this counter.

This counter was emitted to the Graphite at periodic interval (say every minute) with the help of the Metric registry from the application.

Now let's say you know the maximum time frame for which the message will not be available to consume by this application. For example, say 6 hours. Given that you are polling every 500 Millisecond, you know that if we do not receive the message for 6 hours, the counter would increase by

2 poll in 1 second * 60 seconds * 60 minutes * 6 hours = 43200.

We had placed an alerting check based on this counter value reported to Graphite. This metric used to give me a decent idea if it is a genuine problem from the application or something else is down from the Broker or producer side.

This is just the naive way I had solved this use case to some extent. I would love to hear how it is actually done without maintaining these counters.


问:
Laravel Project - Sending null request
I am working on laravel project and the part of project I am having issues with is edit users profile.
Every user have right to edit his/hers profile informations etc. but seems like when I fill all fields except password it changed. I tried to

```<code>dd($request->all())
</code>```

and it showed me that

```<code>'password' => null,
</code>```

Is it possible to check if some fields does not have inserted value and if they are empty to not be sent in request? I tried

```<code>$request->filled('password')
</code>```

and

```<code>$request->has('password')
</code>```

but in both cases it sent null.

The problem with this is when I log out and try to login I cant because the password is changed but I dont know which is. Then I need to use tinker to change it back.

Here is current part from controller and blade.php

Controller

```<code>if($request->filled('password')){
    $user->password = bcrypt($request->password);
}

$user->save();
$user->profile->save();
</code>```

Blade

```<code><div class="form-group">
    <label for="password">New password</label>
    <input type="password" name="password" class="form-control">
</div>
</code>```

Forgot to mention when I fill password field and update it works just fine. Problem is when it is sent empty.

答:
I think you just simply to check password is null in your controller:

if($request->input('password')){
    $user->password = bcrypt($request->input('password'));
}
```

Title: Laravel Project - Sending null request

Body:
I am working on laravel project and the part of project I am having issues with is edit users profile.
Every user have right to edit his/hers profile informations etc. but seems like when I fill all fields except password it changed. I tried to

dd($request->all())

and it showed me that

'password' => null,

Is it possible to check if some fields does not have inserted value and if they are empty to not be sent in request? I tried

$request->filled('password')

and

$request->has('password')

but in both cases it sent null.

The problem with this is when I log out and try to login I cant because the password is changed but I dont know which is. Then I need to use tinker to change it back.

Here is current part from controller and blade.php

Controller

if($request->filled('password')){
    $user->password = bcrypt($request->password);
}

$user->save();
$user->profile->save();

Blade

    New password
    <input type="password" name="password" class="form-control">

Forgot to mention when I fill password field and update it works just fine. Problem is when it is sent empty.


问:
how to joint four single byte data to four byte data entire
I want to combine four single bytes of data to one datum of four bytes.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    unsigned long int sdata = 0x12*(16^6) + 0x34*(16^4) + 0x56*(16^2) + 0x78;
    printf("%x %d", sdata, sizeof(sdata));
    return 0;
}
```

<p>The screen prints:</p>

<pre class="lang-none prettyprint-override"><code>c20 4
</code>```

I want to get:

sdata = 0x12345678
```

The type unsigned long int is a 4 byte data type, so why can't it save the data? Why is the output wrong?

答:
unsigned long int is not always 4 bytes, in many implementations it's 8 bytes.

As was said in the comments ^ does not represent power in C, it's a bitwise operator.

Your printf specifiers are not correct, you should use %lx in the first (or %#lx if you'd like to print the 0x prefix) and %zu in the second.

Demo

Casting to unsigned long will avoid integer overflow, more so because there are some implementations in which int type is 2 bytes in size.

```<code>unsigned long int sdata = (unsigned long int)0x12*16*16*16*16*16*16 + (unsigned long int)0x34*16*16*16*16 + 0x56*(16*16) + 0x78;
printf("%#lx %zu", sdata, sizeof(sdata));
</code>```

Output:

```<code>0x12345678 8 //in this demo, as you can see, unsinged long int is 8 bytes
</code>```

Or just use binary operations if you can, as demonstrated by @chmike

Body:
I want to combine four single bytes of data to one datum of four bytes.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {

    unsigned long int sdata = 0x12*(16^6) + 0x34*(16^4) + 0x56*(16^2) + 0x78;
    printf("%x %d", sdata, sizeof(sdata));
    return 0;
}

The screen prints:

c20 4

I want to get:

sdata = 0x12345678

The type unsigned long int is a 4 byte data type, so why can't it save the data? Why is the output wrong?

Body:
unsigned long int is not always 4 bytes, in many implementations it's 8 bytes.

As was said in the comments ^ does not represent power in C, it's a bitwise operator.

Your printf specifiers are not correct, you should use %lx in the first (or %#lx if you'd like to print the 0x prefix) and %zu in the second.

Demo

Casting to unsigned long will avoid integer overflow, more so because there are some implementations in which int type is 2 bytes in size.

unsigned long int sdata = (unsigned long int)0x12*16*16*16*16*16*16 + (unsigned long int)0x34*16*16*16*16 + 0x56*(16*16) + 0x78;
printf("%#lx %zu", sdata, sizeof(sdata));

Output:

0x12345678 8 //in this demo, as you can see, unsinged long int is 8 bytes

Or just use binary operations if you can, as demonstrated by @chmike


问:
EXIT_FAILURE vs exit(1)?
What's the difference? Which is preferred, or when should I use each one respectively?</p>

答: Not only VMS has its own rules also AmigaDOS defines a return code below 5 as okay.</p>

Title: EXIT_FAILURE vs exit(1)?


问:
Url forwarding does not work when the target has a base url (NodeJs http-express-proxy)
I am calling a backend API service with this line in my NodeJs application (Angular):

```<code>this.http.get<Car[]>('/server/api/v1/cars')
</code>```

But get the following error : GET http://127.0.0.1:4200/server/api/v1/cars 404 (Not Found)

I did expect the url to be translated to http://127.0.0.1:8080/api-baseurl/api/v1/cars with the following server.js (run withnode server.js) :

```<code>const proxy = require('express-http-proxy');
.
.
app.use('/server', proxy('http://localhost:8080/api-baseurl'));
</code>```

But it looks like proxy does not handle forwarding when the target has a base url : using this line app.use('/server', proxy('http://localhost:8080/api-baseurl')); worked when the api did not have a base url, but that is non the case anymore.

答:
I got the answer. What I did not understand form https://www.npmjs.com/package/express-http-proxy is that the first proxy() parameter matches the host, not the specific resource path. ProxyReqPathResolver must be used for the resource path, a function in which I can edit the path :

```<code>const proxy = require('express-http-proxy');
.
.
// Set our api routes proxy to point to backend server
app.use('/server', proxy('http://localhost:8080', {
    proxyReqPathResolver: function (req) {
                updatedPathComplete = '/api-baseurl' + req.url;
                console.log('proxy on /server: ' + req.url + ' => ' + updatedPathComplete);
                return updatedPathComplete;
    }
}));
</code>```

In the console log :

```<code>> node server-prod.js
API running on 4200
proxy on /server: /api/v1/cars => /api-baseurl/api/v1/cars
</code>```

Body:
I am calling a backend API service with this line in my NodeJs application (Angular):

this.http.get<Car[]>('/server/api/v1/cars')

But get the following error : GET http://127.0.0.1:4200/server/api/v1/cars 404 (Not Found)

I did expect the url to be translated to http://127.0.0.1:8080/api-baseurl/api/v1/cars with the following server.js (run withnode server.js) :

const proxy = require('express-http-proxy');
.
.
app.use('/server', proxy('http://localhost:8080/api-baseurl'));

But it looks like proxy does not handle forwarding when the target has a base url : using this line app.use('/server', proxy('http://localhost:8080/api-baseurl')); worked when the api did not have a base url, but that is non the case anymore.

Body:
I got the answer. What I did not understand form https://www.npmjs.com/package/express-http-proxy is that the first proxy() parameter matches the host, not the specific resource path. ProxyReqPathResolver must be used for the resource path, a function in which I can edit the path :

const proxy = require('express-http-proxy');
.
.
// Set our api routes proxy to point to backend server
app.use('/server', proxy('http://localhost:8080', {
    proxyReqPathResolver: function (req) {
                updatedPathComplete = '/api-baseurl' + req.url;
                console.log('proxy on /server: ' + req.url + ' => ' + updatedPathComplete);
                return updatedPathComplete;
    }
}));

In the console log :

> node server-prod.js
API running on 4200
proxy on /server: /api/v1/cars => /api-baseurl/api/v1/cars


问:
How can I prevent a user using inspect element to enable a disabled element?
I have a button as follows:

```<code><input type="submit" class="button" value="FooBar" name="FooBar" id="FooBar" disabled="disabled">
</code>```

I am enabling this button only when certain parameters are met. To test whether it was secure, I pressed F12 (or right click -> Inspect Element) and edited out the text disabled="disabled".  Doing this overrides my code and that is scary. How can I prevent someone from changing it in this manner?

I am using php and jquery in this page and using the latter to enable or disable the button.  I have checked the jquery click function and it not only executes, but shows the button as not disabled. The alert below reads Disabled: false

```<code>$("#FooBar").click(function(){
    alert('Disabled: ' + $(this).is('[disabled=disabled]'));
})
</code>```

So how can I prevent a user from changing the button disabled state and thus overriding my logic?

答:
You can disable the right-click by doing:

```<code>document.addEventListener('contextmenu', event => event.preventDefault());
</code>```

but it is not recommended. Why? It achieves nothing other than the annoying user

OR

Alternatively, a better approach is to recheck your validations in submit action and simply returns if it fails, in this case, if user inspects and changed the state of a button, the button stays idle and will not allow to proceed

```<code>$("#FooBar").click(function() {
    if (!this.acceptenceCriteria()) {
        return;
    }
    alert('Disabled: ' + $(this).is('[disabled=disabled]'));
})
</code>```

Body:
I have a button as follows:

<input type="submit" class="button" value="FooBar" name="FooBar" id="FooBar" disabled="disabled">

I am enabling this button only when certain parameters are met. To test whether it was secure, I pressed F12 (or right click -> Inspect Element) and edited out the text disabled="disabled".  Doing this overrides my code and that is scary. How can I prevent someone from changing it in this manner?

I am using php and jquery in this page and using the latter to enable or disable the button.  I have checked the jquery click function and it not only executes, but shows the button as not disabled. The alert below reads Disabled: false

$("#FooBar").click(function(){
    alert('Disabled: ' + $(this).is('[disabled=disabled]'));
})

So how can I prevent a user from changing the button disabled state and thus overriding my logic?

Body:
You can disable the right-click by doing:

document.addEventListener('contextmenu', event => event.preventDefault());

but it is not recommended. Why? It achieves nothing other than the annoying user

OR

Alternatively, a better approach is to recheck your validations in submit action and simply returns if it fails, in this case, if user inspects and changed the state of a button, the button stays idle and will not allow to proceed

$("#FooBar").click(function() {
    if (!this.acceptenceCriteria()) {
        return;
    }
    alert('Disabled: ' + $(this).is('[disabled=disabled]'));
})