问:
On edit how to pre-populate x-editable popup with existing text from a text field inside  tag
I am rendering around 100+ fields after loading data from DB, my intention is to show these fields as normal editable text fields with data in them.
But when user clicks on any of these fields, An x-editable popup should appear and that it should have the text field's value pre-filled in it (so that user dont have to type everything).

Here is html code:

```<code><a href="#" data-type="text" id="abn" data-pk="1" data-url="/post" data-title="Enter ABN">
 <input type="text" id="abn" name="abn" class="form-control" value="<?php echo $drvData->ABN; ?>" >
</a>
</code>```

in JS i m just doing this:

```<code>$.fn.editable.defaults.mode = 'popup';
$('#abn').editable();
</code>```

But the problem is that if i set x-editable attribute "data-value" it will show like a href not like a text field. but if I use

```<code><input type="text" value="<?php echo $drvData->ABN;?>" ...>
</code>```

it shows popup as empty, anybody can pls help me, i think it has something to do with .editable() to pass the value on but not sure how to do it.

答:
I am not sure this is the right way to solve the problem but it had worked perfect for me:

Inside the  tag instead of using  i have used  and done something like this:

```<code><a href="#" data-type="text" id="ABN" data-pk="1" data-url="/post" data-placement="right" data-title="Enter ABN">
<textarea id="abn" name="abn" class="form-control" >
<?php echo $drvData->ABN; ?>
</textarea>
</a>
</code>```

and in CSS i have done this to show text area as input field:

```<code><style> textarea {  height: 38px;  resize: none;} </style>
</code>```

FYI i m using: $.fn.editable.defaults.mode = 'popup';

I did a lot searching but could not find anything where you can embed an input field inside anchor tag except this work around, I had to make it working so i did it this way :)

Title: On edit how to pre-populate x-editable popup with existing text from a text field inside <a> tag

Body:
I am rendering around 100+ fields after loading data from DB, my intention is to show these fields as normal editable text fields with data in them.
But when user clicks on any of these fields, An x-editable popup should appear and that it should have the text field's value pre-filled in it (so that user dont have to type everything).

Here is html code:

 <input type="text" id="abn" name="abn" class="form-control" value="<?php echo $drvData->ABN; ?>" >

in JS i m just doing this:

$.fn.editable.defaults.mode = 'popup';
$('#abn').editable();

But the problem is that if i set x-editable attribute "data-value" it will show like a href not like a text field. but if I use

<input type="text" value="<?php echo $drvData->ABN;?>" ...>

it shows popup as empty, anybody can pls help me, i think it has something to do with .editable() to pass the value on but not sure how to do it.

Body:
I am not sure this is the right way to solve the problem but it had worked perfect for me:

Inside the  tag instead of using  i have used  and done something like this:

<a href="#" data-type="text" id="ABN" data-pk="1" data-url="/post" data-placement="right" data-title="Enter ABN">
<textarea id="abn" name="abn" class="form-control" >
<?php echo $drvData->ABN; ?>
</textarea>
</a>

and in CSS i have done this to show text area as input field:

<style> textarea {  height: 38px;  resize: none;} </style>

FYI i m using: $.fn.editable.defaults.mode = 'popup';

I did a lot searching but could not find anything where you can embed an input field inside anchor tag except this work around, I had to make it working so i did it this way :)


来源: stackexchange

问:
How to use a value from function x for constructors in functions y
I have the function NodeTransitionFunction(Integer exp, Integer KVal) which needs to calculate f(x) = (x ^ exp) % KVal.

Then there is a function Integer apply(Integer val) which needs to calculate f(val).

Now to set the constructor for NodeTransitionFunction, how do I get the argument val from the apply function?

or am I completely trying to solve this the wrong way?

```<code>public class NodeTransitionFunction {

    public NodeTransitionFunction(Integer exp, Integer KVal) {
        // CONSTUCTOR: Sets the class to calculate f(x) = (x ^ exp) mod KVal

        // TODO
    }

    public Integer apply(Integer val) {
        // PRE: -
        // POST: Implements f(val)
        // TODO

        return null;
    }

    public static void main(String[] args) {
        NodeTransitionFunction f = new NodeTransitionFunction(3, 33);

        System.out.println(f.apply(5));
    }

}
</code>```

答:
I think what you are asking is how to pass a function to the constructor so that it can be later applied. If that's the case you don't really need a class at all: what you are defining is a IntUnaryOperator - i.e. a function that takes an int and returns an int.

So:

```<code>IntUnaryOperator makeNodeTransitionFunction(double exp, double mod) {
    return x -> Math.round(Math.mod(Math.power(x, exp), mod));
}
</code>```

Then applying it as a matter of:

```<code>makeNodeTransitionFunction(7, 11).apply(5)
</code>```

If you need it to be in a class then you can make the IntUnaryOperator a private field that is assigned in the constructor. The apply method would then just delegate to the field.

ContentLicense: CC BY-SA 4.0

Body:
I have the function NodeTransitionFunction(Integer exp, Integer KVal) which needs to calculate f(x) = (x ^ exp) % KVal.

Then there is a function Integer apply(Integer val) which needs to calculate f(val).

Now to set the constructor for NodeTransitionFunction, how do I get the argument val from the apply function?

or am I completely trying to solve this the wrong way?

public class NodeTransitionFunction {

    public NodeTransitionFunction(Integer exp, Integer KVal) {
        // CONSTUCTOR: Sets the class to calculate f(x) = (x ^ exp) mod KVal

        // TODO
    }

    public Integer apply(Integer val) {
        // PRE: -
        // POST: Implements f(val)
        // TODO

        return null;
    }

    public static void main(String[] args) {
        NodeTransitionFunction f = new NodeTransitionFunction(3, 33);

        System.out.println(f.apply(5));
    }

}

Body:
I think what you are asking is how to pass a function to the constructor so that it can be later applied. If that's the case you don't really need a class at all: what you are defining is a IntUnaryOperator - i.e. a function that takes an int and returns an int.

So:

IntUnaryOperator makeNodeTransitionFunction(double exp, double mod) {
    return x -> Math.round(Math.mod(Math.power(x, exp), mod));
}

Then applying it as a matter of:

makeNodeTransitionFunction(7, 11).apply(5)

If you need it to be in a class then you can make the IntUnaryOperator a private field that is assigned in the constructor. The apply method would then just delegate to the field.


问:
.htaccess in subfolder
I install a new cms (phpmydirectory) in a subfolder. In the root there is a wordpress with friendly url's.

When I activate the friendly url's in phpmydirectory, I get an 404 error in the categories and locations, but no in the listings. The 404 error appear in the blog template and URL.

How fix the -htaccess so the subfolder read the .htaccess in the subfolder ando no the one in root?

答:
Apache always reads all .htaccess files along the path to the root directory. This cannot be changed (except for disallowing use of .htaccess alltogether). The best you can get is making sure that rules for mod_rewrite in the parent directory do not apply. This might be possible using

```<code>RewriteRule ^(.*)$ $1 [L]
</code>```

as the last rule in your phpmydirectory directory.

ContentLicense: CC BY-SA 3.0

Title: .htaccess in subfolder

Body:
Apache always reads all .htaccess files along the path to the root directory. This cannot be changed (except for disallowing use of .htaccess alltogether). The best you can get is making sure that rules for mod_rewrite in the parent directory do not apply. This might be possible using

RewriteRule ^(.*)$ $1 [L]

as the last rule in your phpmydirectory directory.


问:
my code which i written it throws me an Invalid syntax error at try:
I have tried to do it without def and that worked this is the code i dont really know what to do i tried to give indentation correctly also

But when i run this it throws the error invalid syntax

```<code>import ray

ray.init()

@ray.remote
try:
    Func1()
except:
    pass

ray.get([func1.remote()])

def func1():
    for i in range (99999):
        print("h")```

The error is invalid syntax at try:

This is the code that worked for me

try:
    do_something()
except:
    pass

```

答:
You cannot have a decorator like @ray.remote on top of a try/except, which causes the SyntaxError.

You need to wrap your try/except around a function, and decorate that function. For example

```<code>@ray.remote
def Func2():
    try:
        Func1()
    except:
        pass
</code>```

Body:
I have tried to do it without def and that worked this is the code i dont really know what to do i tried to give indentation correctly also

But when i run this it throws the error invalid syntax

import ray

ray.init()

@ray.remote
try:
    Func1()
except:
    pass

ray.get([func1.remote()])

def func1():
    for i in range (99999):
        print("h")```

The error is invalid syntax at try:

This is the code that worked for me

try:
    do_something()
except:
    pass

Body:
You cannot have a decorator like @ray.remote on top of a try/except, which causes the SyntaxError.

You need to wrap your try/except around a function, and decorate that function. For example

@ray.remote
def Func2():
    try:
        Func1()
    except:
        pass


问:
Convert wide pandas dataframe of daily data by week into long dataframe of daily data
I am working with a pandas dataframe where each row includes the start date for the week, and the daily data for that week. For example:

```<code>    start_date  mon  tue  wed   thu   fri   sat  sun
    2017-01-01  10   15   8     19    20    21   4
</code>```

I would like to do time series analysis and need the data in the following format:

```<code>    date         amount
    2017-01-01   10
    2017-01-02   15
    2017-01-03   8
    2017-01-04   19
    2017-01-05   20
    2017-01-06   21
    2017-01-07   4
</code>```

I believe I can use pandas melt to convert the dataset from wide to long, but I am struggling with how to best fill in the dates.

I have tried the following approach, but it seems like a work around:

```<code>df = pd.DataFrame({'start_date': {0: '2017-01-01'}, 'mon': {0: 10},
                   'tue': {0: 15}, 'wed': {0: 8}, 'thu': {0: '19'},
                   'fri': {0: 20}, 'sat': {0: 21}, 'sun': {0: 4}})

df = df.melt(id_vars='start_date', value_name="amount")

day_add = {'mon': 0,
           'tue': 1,
           'wed': 2,
           'thu': 3,
           'fri': 4,
           'sat': 5,
           'sun': 6,
           }

df = df.replace({"variable": day_add})

df['date'] = pd.to_datetime(df['start_date'], infer_datetime_format=True) +
             pd.to_timedelta(df['variable'], unit='d')

print(df[['date', 'amount']].sort_values(by=['date']))
</code>```

Results from the current code:

```<code>        date amount
1 2017-01-01     10
5 2017-01-02     15
6 2017-01-03      8
4 2017-01-04     19
0 2017-01-05     20
2 2017-01-06     21
3 2017-01-07      4
</code>```

Alternative approaches are welcome.

答:
Your solution is pretty good. The only thing I'd change (possibly) is substituting the replace call with a fast(er) map call which you can do in-line.

For completeness, here's a similar solution using stack. This is almost the same as using melt. I've also showed how I'd use map here:

```<code>u = df.set_index('start_date').stack()
u.index = (
    pd.to_datetime(u.index.get_level_values(0))
  + pd.to_timedelta(u.index.get_level_values(1).map(day_add), unit='d'))

u.rename_axis('date').reset_index(name='amount')

        date amount
0 2017-01-01     10
1 2017-01-02     15
2 2017-01-03      8
3 2017-01-04     19
4 2017-01-05     20
5 2017-01-06     21
6 2017-01-07      4
</code>```

Body:
I am working with a pandas dataframe where each row includes the start date for the week, and the daily data for that week. For example:

    start_date  mon  tue  wed   thu   fri   sat  sun
    2017-01-01  10   15   8     19    20    21   4

I would like to do time series analysis and need the data in the following format:

    date         amount
    2017-01-01   10
    2017-01-02   15
    2017-01-03   8
    2017-01-04   19
    2017-01-05   20
    2017-01-06   21
    2017-01-07   4

I believe I can use pandas melt to convert the dataset from wide to long, but I am struggling with how to best fill in the dates.

I have tried the following approach, but it seems like a work around:

df = pd.DataFrame({'start_date': {0: '2017-01-01'}, 'mon': {0: 10},
                   'tue': {0: 15}, 'wed': {0: 8}, 'thu': {0: '19'},
                   'fri': {0: 20}, 'sat': {0: 21}, 'sun': {0: 4}})

df = df.melt(id_vars='start_date', value_name="amount")

day_add = {'mon': 0,
           'tue': 1,
           'wed': 2,
           'thu': 3,
           'fri': 4,
           'sat': 5,
           'sun': 6,
           }

df = df.replace({"variable": day_add})

df['date'] = pd.to_datetime(df['start_date'], infer_datetime_format=True) +
             pd.to_timedelta(df['variable'], unit='d')

print(df[['date', 'amount']].sort_values(by=['date']))

Results from the current code:

        date amount
1 2017-01-01     10
5 2017-01-02     15
6 2017-01-03      8
4 2017-01-04     19
0 2017-01-05     20
2 2017-01-06     21
3 2017-01-07      4

Alternative approaches are welcome.

Body:
Your solution is pretty good. The only thing I'd change (possibly) is substituting the replace call with a fast(er) map call which you can do in-line.

For completeness, here's a similar solution using stack. This is almost the same as using melt. I've also showed how I'd use map here:

u = df.set_index('start_date').stack()
u.index = (
    pd.to_datetime(u.index.get_level_values(0))
  + pd.to_timedelta(u.index.get_level_values(1).map(day_add), unit='d'))

u.rename_axis('date').reset_index(name='amount')

        date amount
0 2017-01-01     10
1 2017-01-02     15
2 2017-01-03      8
3 2017-01-04     19
4 2017-01-05     20
5 2017-01-06     21
6 2017-01-07      4


问:
Bash get the command that is piping into a script
Take the following example:

```<code>ls -l | grep -i readme | ./myscript.sh
</code>```

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

答:
No, it's not possible.

At the OS level, pipelines are implemented with the mkfifo(), dup2(), fork() and execve() syscalls. This doesn't provide a way to tell a program what the commands connected to its stdin are. Indeed, there's not guaranteed to be a string representing a pipeline of programs being used to generate stdin at all, even if your stdin really is a FIFO connected to another program's stdout; it could be that that pipeline was generated by programs calling execve() and friends directly.

The best available workaround is to invert your process flow.

It's not what you asked for, but it's what you can get.

```<code>#!/usr/bin/env bash
printf -v cmd_str '%q ' "$@"  # generate a shell command representing our arguments

while IFS= read -r line; do
  printf 'Output from %s: %s\n' "$cmd_str" "$line"
done < <("$@")       # actually run those arguments as a command, and read from it
</code>```

...and then have your script start the things it reads input from, rather than receiving them on stdin.

...thereafter, ./yourscript ls -l, or ./yourscript sh -c 'ls -l | grep -i readme'. (Of course, never use this except as an example; see ParsingLs).

Body:
Take the following example:

ls -l | grep -i readme | ./myscript.sh

What I am trying to do is get ls -l | grep -i readme as a string variable in myscript.sh. So essentially I am trying to get the whole command before the last pipe to use inside myscript.sh.

Is this possible?

Body:
No, it's not possible.

At the OS level, pipelines are implemented with the mkfifo(), dup2(), fork() and execve() syscalls. This doesn't provide a way to tell a program what the commands connected to its stdin are. Indeed, there's not guaranteed to be a string representing a pipeline of programs being used to generate stdin at all, even if your stdin really is a FIFO connected to another program's stdout; it could be that that pipeline was generated by programs calling execve() and friends directly.

The best available workaround is to invert your process flow.

It's not what you asked for, but it's what you can get.

#!/usr/bin/env bash
printf -v cmd_str '%q ' "$@"  # generate a shell command representing our arguments

while IFS= read -r line; do
  printf 'Output from %s: %s\n' "$cmd_str" "$line"
done < <("$@")       # actually run those arguments as a command, and read from it

...and then have your script start the things it reads input from, rather than receiving them on stdin.

...thereafter, ./yourscript ls -l, or ./yourscript sh -c 'ls -l | grep -i readme'. (Of course, never use this except as an example; see ParsingLs).


问:
Applying query options on typeless entity
How can I apply the query options on a non clr type. The .ApplyTo method is throwing an error when I'm using it.

Error:

"The query option is not bound to any CLR type. 'ApplyTo' is only
  supported with a query option bound to a CLR type."

```<code>var x = (EdmCollectionType)Request.GetODataPath().EdmType;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);
ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request);

//codes.....

queryOptions.ApplyTo(Products);
</code>```

答:
```<code>ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);
</code>```

In the above line, we need to explicitly pass the Class Type obj to ODataQueryContext.
Let's assume a type named A which has been created at runtime.

```<code>Type a = //Get the type at runtime ;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), a);
</code>```

This should resovle the exception.

Now, come to ApplyTo() we can pass an instance of type A to it.

```<code>object instance = Activator.CreateInstance(a);
odataQuerySetting.ApplyTo(instance,, new ODataQuerySettings() { });
</code>```

However, we would like to run ApplyTo() against a list of objects as well as one instance.
Array class could help us to accomplish this. Suppose we need to create 10 instances:

```<code>Array values = Array.CreateInstance(a, 10);
for (int i = 0; i < 10; i++)
        {
            values.SetValue(Activator.CreateInstance(t), i);
        }
</code>```

Needless to say that we can add properties to our instances as we would like to and then pass it to SetValue().
Finally, the ApplyTo() can be executed against our list as follow:

```<code>  queryOptions.ApplyTo(values.AsQueryable());
</code>```

Note: if you get the status:406 then one possible cause could be the JsonFormat. use a custom MediaTypeFormatter to resolve that.

I hope that this might help someone.

Body:
How can I apply the query options on a non clr type. The .ApplyTo method is throwing an error when I'm using it.

Error:

"The query option is not bound to any CLR type. 'ApplyTo' is only
  supported with a query option bound to a CLR type."

var x = (EdmCollectionType)Request.GetODataPath().EdmType;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);
ODataQueryOptions queryOptions = new ODataQueryOptions(queryContext, Request);

//codes.....

queryOptions.ApplyTo(Products);

Body:
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), x.ElementType.Definition);

In the above line, we need to explicitly pass the Class Type obj to ODataQueryContext.
Let's assume a type named A which has been created at runtime.

Type a = //Get the type at runtime ;
ODataQueryContext queryContext = new ODataQueryContext(Request.GetEdmModel(), a);

This should resovle the exception.

Now, come to ApplyTo() we can pass an instance of type A to it.

object instance = Activator.CreateInstance(a);
odataQuerySetting.ApplyTo(instance,, new ODataQuerySettings() { });

However, we would like to run ApplyTo() against a list of objects as well as one instance.
Array class could help us to accomplish this. Suppose we need to create 10 instances:

Array values = Array.CreateInstance(a, 10);
for (int i = 0; i < 10; i++)
        {
            values.SetValue(Activator.CreateInstance(t), i);
        }

Needless to say that we can add properties to our instances as we would like to and then pass it to SetValue().
Finally, the ApplyTo() can be executed against our list as follow:

  queryOptions.ApplyTo(values.AsQueryable());

Note: if you get the status:406 then one possible cause could be the JsonFormat. use a custom MediaTypeFormatter to resolve that.

I hope that this might help someone.


问:
Is it possible to assign and verify a constexpr structure in C++14?
I implemented a getop() in C++. This is a class with all sorts of bells and whistles.

One of those bells would be a way to verify that the user enters valid options at compile time. Already I have part of that for the flags (not shown here) but I've been trying to make it work for the struct option and at this time I've not had much success.

First of all, the code allows me to define an array of options using  the define_option() function. I want to be able to specify the fields of the option structure in any order and have some sanity checks on them. So I use a list of arguments to a template function. Each argument is a class which gets instantiated on the spot and then the define_option() selects the correct class for each field, extracting the value.

Up to here, everything works like a charm. Pretty basic C++.

Where I'm having a problem is inside the define_option() class. Say for instance that I were to try the following:

```<code>... define_option(...)
{
    ...
    option opt = { ... };
    static_assert(opt.f_short_name != '\0', "this failed");
    ...
}
</code>```

Here I get an error. static_assert() tells me that opt is not constant.

a.cpp:168:1: error: non-constant condition for static assertion

So next my step is to mark the opt variable a constexpr (something the error says to do to resolve the static_assert().)

```<code>... define_option(...)
{
    ...
    constexpr option opt = { ... };
    ...
}
</code>```

Now even without the static_assert(), the code doesn't compile. I get the following error:

a.cpp:168:5: error: ‘args#0’ is not a constant expression

I'm thinking that it's not really doable from within the define_option() function, even though it's possible to check the resulting list of options as shown in the working example below. So in the end the opt global variable is a static fully defined at compile time (no code necessary to re-work on the table at runtime) but that doesn't help me since I can't make sure that the arguments for each option will work as expected.

I have an online running sample on coliru.

```<code>// compiled with: g++ -std=c++14 -o a ~/tmp/a.cpp
//
#include <iostream>

typedef char32_t            short_name_t;
constexpr short_name_t      NO_SHORT_NAME = L'\0';

struct option
{
    short_name_t        f_short_name = NO_SHORT_NAME;
    char const *        f_name = nullptr;
};

template<typename T, T default_value>
class OptionValue
{
public:
    typedef T   value_t;

    constexpr OptionValue<T, default_value>()
        : f_value(default_value)
    {
    }

    constexpr OptionValue<T, default_value>(T const v)
        : f_value(v)
    {
    }

    constexpr value_t get() const
    {
        return f_value;
    }

private:
    value_t     f_value;
};

class ShortName
    : public OptionValue<short_name_t, NO_SHORT_NAME>
{
public:
    constexpr ShortName()
        : OptionValue<short_name_t, NO_SHORT_NAME>()
    {
    }

    constexpr ShortName(short_name_t name)
        : OptionValue<short_name_t, NO_SHORT_NAME>(name)
    {
    }
};

class Name
    : public OptionValue<char const *, nullptr>
{
public:
    constexpr Name()
        : OptionValue<char const *, nullptr>()
    {
    }

    constexpr Name(char const * name)
        : OptionValue<char const *, nullptr>(name)
    {
    }
};

template<typename T, typename F, class ...ARGS>
constexpr typename std::enable_if<std::is_same<T, F>::value, typename T::value_t>::type find_option(F first, ARGS ...args)
{
    return first.get();
}

template<typename T, typename F, class ...ARGS>
constexpr typename std::enable_if<!std::is_same<T, F>::value, typename T::value_t>::type find_option(F first, ARGS ...args)
{
    return find_option<T>(args...);
}

template<class ...ARGS>
constexpr option define_option(ARGS ...args)
{
    option opt =
    {
        .f_short_name =          find_option<ShortName   >(args..., ShortName()),
        .f_name =                find_option<Name        >(args...),
    };

    return opt;
}

constexpr option const opt[] =
{
    define_option(
        Name("--help"),
        ShortName('h')
    )
};

// this test works as expected here
// but it does not work from inside define_option()
//
static_assert(opt[0].f_name[0] != '-', "Wrong start?!");

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

    std::cerr << "opt[0].f_short_name = " << opt[0].f_short_name << std::endl;

    return 0;
}
</code>```

At this time I'm limited to C++14. If there is a C++17 solution, I'd still be interested.

答:
Just add something that makes the call non-constant. Say, throw an exception.

```<code>template<class ...ARGS>
constexpr option define_option(ARGS ...args)
{
    option opt =
    {
        .f_short_name =          find_option<ShortName   >(args..., ShortName()),
        .f_name =                find_option<Name        >(args...),
    };
    if(/* check fails */) throw something;

    return opt;
}
</code>```

Then when you try to do

```<code>constexpr option const opt[] =
{
    define_option(
        Name("--help"),
        ShortName('h')
    )
};
</code>```

and the check fails, the compiler will complain that this call to define_option is not a constant expression and cannot be used to initialize a constexpr variable.

You can even rig something to produce a linker error if this function is ever called at runtime. See e.g. this question.

Body:
I implemented a getop() in C++. This is a class with all sorts of bells and whistles.

One of those bells would be a way to verify that the user enters valid options at compile time. Already I have part of that for the flags (not shown here) but I've been trying to make it work for the struct option and at this time I've not had much success.

First of all, the code allows me to define an array of options using  the define_option() function. I want to be able to specify the fields of the option structure in any order and have some sanity checks on them. So I use a list of arguments to a template function. Each argument is a class which gets instantiated on the spot and then the define_option() selects the correct class for each field, extracting the value.

Up to here, everything works like a charm. Pretty basic C++.

Where I'm having a problem is inside the define_option() class. Say for instance that I were to try the following:

... define_option(...)
{
    ...
    option opt = { ... };
    static_assert(opt.f_short_name != '\0', "this failed");
    ...
}

Here I get an error. static_assert() tells me that opt is not constant.

a.cpp:168:1: error: non-constant condition for static assertion

So next my step is to mark the opt variable a constexpr (something the error says to do to resolve the static_assert().)

... define_option(...)
{
    ...
    constexpr option opt = { ... };
    ...
}

Now even without the static_assert(), the code doesn't compile. I get the following error:

a.cpp:168:5: error: ‘args#0’ is not a constant expression

I'm thinking that it's not really doable from within the define_option() function, even though it's possible to check the resulting list of options as shown in the working example below. So in the end the opt global variable is a static fully defined at compile time (no code necessary to re-work on the table at runtime) but that doesn't help me since I can't make sure that the arguments for each option will work as expected.

I have an online running sample on coliru.

// compiled with: g++ -std=c++14 -o a ~/tmp/a.cpp
//
#include <iostream>

typedef char32_t            short_name_t;
constexpr short_name_t      NO_SHORT_NAME = L'\0';

struct option
{
    short_name_t        f_short_name = NO_SHORT_NAME;
    char const *        f_name = nullptr;
};

template<typename T, T default_value>
class OptionValue
{
public:
    typedef T   value_t;

    constexpr OptionValue<T, default_value>()
        : f_value(default_value)
    {
    }

    constexpr OptionValue<T, default_value>(T const v)
        : f_value(v)
    {
    }

    constexpr value_t get() const
    {
        return f_value;
    }

private:
    value_t     f_value;
};

class ShortName
    : public OptionValue<short_name_t, NO_SHORT_NAME>
{
public:
    constexpr ShortName()
        : OptionValue<short_name_t, NO_SHORT_NAME>()
    {
    }

    constexpr ShortName(short_name_t name)
        : OptionValue<short_name_t, NO_SHORT_NAME>(name)
    {
    }
};

class Name
    : public OptionValue<char const *, nullptr>
{
public:
    constexpr Name()
        : OptionValue<char const *, nullptr>()
    {
    }

    constexpr Name(char const * name)
        : OptionValue<char const *, nullptr>(name)
    {
    }
};

template<typename T, typename F, class ...ARGS>
constexpr typename std::enable_if<std::is_same<T, F>::value, typename T::value_t>::type find_option(F first, ARGS ...args)
{
    return first.get();
}

template<typename T, typename F, class ...ARGS>
constexpr typename std::enable_if<!std::is_same<T, F>::value, typename T::value_t>::type find_option(F first, ARGS ...args)
{
    return find_option<T>(args...);
}

template<class ...ARGS>
constexpr option define_option(ARGS ...args)
{
    option opt =
    {
        .f_short_name =          find_option<ShortName   >(args..., ShortName()),
        .f_name =                find_option<Name        >(args...),
    };

    return opt;
}

constexpr option const opt[] =
{
    define_option(
        Name("--help"),
        ShortName('h')
    )
};

// this test works as expected here
// but it does not work from inside define_option()
//
static_assert(opt[0].f_name[0] != '-', "Wrong start?!");

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

    std::cerr << "opt[0].f_short_name = " << opt[0].f_short_name << std::endl;

    return 0;
}

At this time I'm limited to C++14. If there is a C++17 solution, I'd still be interested.

Body:
Just add something that makes the call non-constant. Say, throw an exception.

template<class ...ARGS>
constexpr option define_option(ARGS ...args)
{
    option opt =
    {
        .f_short_name =          find_option<ShortName   >(args..., ShortName()),
        .f_name =                find_option<Name        >(args...),
    };
    if(/* check fails */) throw something;

    return opt;
}

Then when you try to do

constexpr option const opt[] =
{
    define_option(
        Name("--help"),
        ShortName('h')
    )
};

and the check fails, the compiler will complain that this call to define_option is not a constant expression and cannot be used to initialize a constexpr variable.

You can even rig something to produce a linker error if this function is ever called at runtime. See e.g. this question.


问:
How could I use regular expression to split Chinese characters at right position?
I want to split specific Chinese characters in some lines. Actually, it worked, but the position of the split character was wrong. How could I split it at right position?

I split Chinese characters by regular expression in python 3.6

```<code>str = '我到家'
pattern = '([\u4e00-\u9fa5]?(?:到))'
compiled_pattern = re.compile(pattern)
new_str = re.split(compiled_pattern, str)
print(new_str)
</code>```

The output by my code is

```<code>['', '我到', '家']
</code>```

But what I want is

```<code>['我', '到', '家']
</code>```

How could I fix it and spit the character at right position?

答:
Try this:</p>

```<code>str = '我到家'
pattern = '(我)(到)(家)'
compiled_pattern = re.compile(pattern)
new_str = list(re.findall(compiled_pattern,str)[0])
print(new_str)
</code>```

Body:
I want to split specific Chinese characters in some lines. Actually, it worked, but the position of the split character was wrong. How could I split it at right position?

I split Chinese characters by regular expression in python 3.6

str = '我到家'
pattern = '([\u4e00-\u9fa5]?(?:到))'
compiled_pattern = re.compile(pattern)
new_str = re.split(compiled_pattern, str)
print(new_str)

The output by my code is

['', '我到', '家']

But what I want is

['我', '到', '家']

How could I fix it and spit the character at right position?

Body:
Try this:

str = '我到家'
pattern = '(我)(到)(家)'
compiled_pattern = re.compile(pattern)
new_str = list(re.findall(compiled_pattern,str)[0])
print(new_str)


问:
use joomla com_media image selection in my custom component
hi
i want to use com_media image selection in my own component. the link is:

```<code>index.php?option=com_media&view=images&tmpl=component&
e_name=smallimage
</code>```

the image goes to editor while i want it's address go to

```<code><input class="inputbox" type="text" name="smallimage" id="smallimage" size="40"
maxlength="255" value="<?php echo $row->smallimage; ?>" title=
"<?php echo JText::_('SMALLIMAGETIP' ); ?>" />
</code>```

i am using joomla 1.5

any suggestion?

thanks

答:
If you're using Joomla 1.6 the easy way is let Joomla do all the work for you. How?

First you need to include in you xml form (/model/forms/YOURFORM.xml) something like that...

```<code><field name="imageurl" type="media" directory="CUSTOMDIRECTORY?"
                hide_none="1" label="COM_YOURCOMPONENT_IMG_LABEL"
                size="40"
                description="COM_YOURCOMPONENT_IMG_DESCRIPTION" />
</code>```

Haven't you got a getForm() in your model?

```<code>public function getForm($data = array(), $loadData = true)
    {

        // Get the form.
        try {
            //throw new Exception(JText::_('JLIB_FORM_ERROR_NO_DATA'));
            $form = $this->loadForm('com_kfiles', 'files');
        } catch (Exception $e) {
            echo "e";
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }

        if (empty($form)) {
            return false;
        }

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

In your view (/views/xxxx/view.html.php) you need to load your form

```<code>$this->form = $this->get('Form');
</code>```

Finally you only need to print the element in the template wherever you want.

```<code>echo $this->form->getLabel('imageurl');
echo $this->form->getInput('imageurl');
</code>```

Bye

Body:
hi
i want to use com_media image selection in my own component. the link is:

index.php?option=com_media&view=images&tmpl=component&
e_name=smallimage

the image goes to editor while i want it's address go to

<input class="inputbox" type="text" name="smallimage" id="smallimage" size="40"
maxlength="255" value="<?php echo $row->smallimage; ?>" title=
"<?php echo JText::_('SMALLIMAGETIP' ); ?>" />

i am using joomla 1.5

any suggestion?

thanks

Body:
If you're using Joomla 1.6 the easy way is let Joomla do all the work for you. How?

First you need to include in you xml form (/model/forms/YOURFORM.xml) something like that...

<field name="imageurl" type="media" directory="CUSTOMDIRECTORY?"
                hide_none="1" label="COM_YOURCOMPONENT_IMG_LABEL"
                size="40"
                description="COM_YOURCOMPONENT_IMG_DESCRIPTION" />

Haven't you got a getForm() in your model?

public function getForm($data = array(), $loadData = true)
    {

        // Get the form.
        try {
            //throw new Exception(JText::_('JLIB_FORM_ERROR_NO_DATA'));
            $form = $this->loadForm('com_kfiles', 'files');
        } catch (Exception $e) {
            echo "e";
            echo 'Caught exception: ',  $e->getMessage(), "\n";
        }

        if (empty($form)) {
            return false;
        }

        return $form;
    }

In your view (/views/xxxx/view.html.php) you need to load your form

$this->form = $this->get('Form');

Finally you only need to print the element in the template wherever you want.

echo $this->form->getLabel('imageurl');
echo $this->form->getInput('imageurl');

Bye


问:
JavaScript (jQuery) sometimes does not work when you link it as a separate file
I found these sample code from  here

The code is like this:

```<code><script>
    $("#modal2Button").click(function() {
      $("#modal1").fadeOut();
      setTimeout(function() {
        $("#modal2").fadeIn();
      }, 400)
    });

    $("#close-button").click(function() {
      setTimeout(function() {
        $("#modal1").fadeIn();
        $("#modal2").fadeOut();
      }, 1000)

    });
</script>
</code>```

When I paste the jQuery as a separate file and link it inside the

```<code><head>
<script src="sample_code.js"></script>
</head>
</code>```

and for some reason that does not work?

Any help will be much appreciate!

Body:
I found these sample code from  here

The code is like this:

When I paste the jQuery as a separate file and link it inside the

and for some reason that does not work?

Any help will be much appreciate!

Body:
Yes, Definitely it will not work because the DOM Elements are yet not loaded, and you are accessing them, so their will be an error undefined id modal2Button same for the next one.

If you run your js file when all DOM Elements are loaded their will be no problem..

You can do that via following:

Move your script tag at the bottom of html or just before the body tags ends

Use async or defer in <script> | script notes | script tag - async and defer

Use onload function in your js


问:
REST API design for data synchronization service
What is best practice for data synchronization operation between client and server?

We have 2 (or more) resources:

cars -> year, model, engine

toys -> color, brand, weight

And we need to get updated resources from server in case of any updates on them. For example: someone made changes from another client on the same data and we need to transfer those updates to our client application.

Request:

http://api.example.com/sync?data=cars,toys (verb?)

http://api.example.com/synchronizations?data=cars,toys (virtual resource "synchronizations")

Response with mixed data:

status code: 200

```<code>{
  message: "ok",
  data: {
    cars: [
        {
          year: 2015,
          model: "Fiat 500"
          engine: 0.9
        },
        {
          year: 2004,
          model: "Nissan Sunny"
          engine: 1.3
        }
    ],
    toys: [
        {
          color: "yellow",
          brand: "Bruder"
          weight: 2
        }
    ],
  }
}
</code>```

or response with status code 204 if no updates available. In my opinion making separated http calls in not a good solution. What if we have 100 resources (=100 http calls)?

答:
I am not an expert, but one method I have used in the past is to ask for a "signature" of the data, as opposed to always going and getting the data.  The signature can be a hash of the data you are looking for.  So, flow would be something like:

Get signature hash of the data

```<code>http://api.example.com/sync/signature/cars
</code>```

Which returns the signature hash

Check if the signature is different from the last time you retrieved the data

If the signature is different, go and get the data

```<code>http://api.example.com/sync/cars
</code>```

Have the REST also add the new signature to the data

```<code>{
  message: "ok",
  data: {
    cars: [
        {
          year: 2015,
          model: "Fiat 500"
          engine: 0.9
        },
        {
          year: 2004,
          model: "Nissan Sunny"
          engine: 1.3
        },
    ],
    signature: "570a90bfbf8c7eab5dc5d4e26832d5b1"
  }
}
</code>```

Body:
What is best practice for data synchronization operation between client and server?

We have 2 (or more) resources:

cars -> year, model, engine

toys -> color, brand, weight

And we need to get updated resources from server in case of any updates on them. For example: someone made changes from another client on the same data and we need to transfer those updates to our client application.

Request:

http://api.example.com/sync?data=cars,toys (verb?)

http://api.example.com/synchronizations?data=cars,toys (virtual resource "synchronizations")

Response with mixed data:

status code: 200

{
  message: "ok",
  data: {
    cars: [
        {
          year: 2015,
          model: "Fiat 500"
          engine: 0.9
        },
        {
          year: 2004,
          model: "Nissan Sunny"
          engine: 1.3
        }
    ],
    toys: [
        {
          color: "yellow",
          brand: "Bruder"
          weight: 2
        }
    ],
  }
}

or response with status code 204 if no updates available. In my opinion making separated http calls in not a good solution. What if we have 100 resources (=100 http calls)?

Body:
I am not an expert, but one method I have used in the past is to ask for a "signature" of the data, as opposed to always going and getting the data.  The signature can be a hash of the data you are looking for.  So, flow would be something like:

Get signature hash of the data

http://api.example.com/sync/signature/cars

Which returns the signature hash

Check if the signature is different from the last time you retrieved the data

If the signature is different, go and get the data

http://api.example.com/sync/cars

Have the REST also add the new signature to the data

{
  message: "ok",
  data: {
    cars: [
        {
          year: 2015,
          model: "Fiat 500"
          engine: 0.9
        },
        {
          year: 2004,
          model: "Nissan Sunny"
          engine: 1.3
        },
    ],
    signature: "570a90bfbf8c7eab5dc5d4e26832d5b1"
  }
}


问:
what does Mono.defer() do?
I've come across Mono.defer() in some Spring webflux code

I looked up the method in the docs but don't understand the explanation:

"Create a Mono provider that will supply a target Mono to subscribe to
for each Subscriber downstream"

please could I have an explanation and an example. Is there a place with a bunch of Reactor example code (their unit tests?) that I might reference.

thanks

答:
I was attempting defer for a different use case. Wrote the below code to check and sharing as it might help others. My use case was to chain two Monos and ensure that the first one is complete before the second one is taken up. And second one contained a blocking call whose result is used to respond a Mono either with empty or error response. Without defer, my blocking call is executed irrespective of the result of first one. But while using defer the blocking call is executed only when the first Mono completes. Code below:

```<code>public static void main(String[] args) {
    long cur = System.currentTimeMillis();
    boolean succeed = true;

    Mono<Integer> monoJust = Mono.create(consumer -> {
        System.out.println("MonoJust inside " + (System.currentTimeMillis() - cur));
        if (succeed) {
            consumer.success(1);
        } else {
            consumer.error(new RuntimeException("aaa"));
        }
    });

    Mono<String> monoJustStr = Mono.create(consumer -> {
        System.out.println("MonoJustStr inside: " + (System.currentTimeMillis() - cur));
        consumer.success("one");
    });

    System.out.println("##1##: Begin");
    monoJust.then(evaluator() ? Mono.empty() : monoJustStr).subscribe(d -> System.out.println("##1##: "+d), e-> System.err.println(e));
    System.out.println("##1##: Done: "+(System.currentTimeMillis() - cur));

    System.out.println("\n\n\n##2##: Begin");
    monoJust.then(Mono.defer(() -> evaluator() ? Mono.empty() : monoJustStr)).subscribe(d -> System.out.println("##2##: "+d), e-> System.err.println(e));
    System.out.println("##2##: Done: " + (System.currentTimeMillis() - cur));

}

private static boolean evaluator() {
    System.out.println("Inside Evaluator");
    return false;
}
</code>```

Output with succeed=true - Observe the sequence of "Inside Evaluator" and "MonoJust inside"

```<code>##1##: Begin
Inside Evaluator
MonoJust inside 540
MonoJustStr inside: 542
##1##: one
##1##: Done: 542

##2##: Begin
MonoJust inside 544
Inside Evaluator
MonoJustStr inside: 544
##2##: one
##2##: Done: 544
</code>```

Below is output with succeed = false - Note that evaluator is not called.

```<code>##1##: Begin
Inside Evaluator
MonoJust inside 565
java.lang.RuntimeException: aaa
##1##: Done: 567

##2##: Begin
MonoJust inside 569
java.lang.RuntimeException: aaa
##2##: Done: 569
</code>```

Title: what does Mono.defer() do?

Body:
I was attempting defer for a different use case. Wrote the below code to check and sharing as it might help others. My use case was to chain two Monos and ensure that the first one is complete before the second one is taken up. And second one contained a blocking call whose result is used to respond a Mono either with empty or error response. Without defer, my blocking call is executed irrespective of the result of first one. But while using defer the blocking call is executed only when the first Mono completes. Code below:

public static void main(String[] args) {
    long cur = System.currentTimeMillis();
    boolean succeed = true;

    Mono<Integer> monoJust = Mono.create(consumer -> {
        System.out.println("MonoJust inside " + (System.currentTimeMillis() - cur));
        if (succeed) {
            consumer.success(1);
        } else {
            consumer.error(new RuntimeException("aaa"));
        }
    });

    Mono<String> monoJustStr = Mono.create(consumer -> {
        System.out.println("MonoJustStr inside: " + (System.currentTimeMillis() - cur));
        consumer.success("one");
    });

    System.out.println("##1##: Begin");
    monoJust.then(evaluator() ? Mono.empty() : monoJustStr).subscribe(d -> System.out.println("##1##: "+d), e-> System.err.println(e));
    System.out.println("##1##: Done: "+(System.currentTimeMillis() - cur));

    System.out.println("\n\n\n##2##: Begin");
    monoJust.then(Mono.defer(() -> evaluator() ? Mono.empty() : monoJustStr)).subscribe(d -> System.out.println("##2##: "+d), e-> System.err.println(e));
    System.out.println("##2##: Done: " + (System.currentTimeMillis() - cur));

}

private static boolean evaluator() {
    System.out.println("Inside Evaluator");
    return false;
}

Output with succeed=true - Observe the sequence of "Inside Evaluator" and "MonoJust inside"

##1##: Begin
Inside Evaluator
MonoJust inside 540
MonoJustStr inside: 542
##1##: one
##1##: Done: 542

##2##: Begin
MonoJust inside 544
Inside Evaluator
MonoJustStr inside: 544
##2##: one
##2##: Done: 544

Below is output with succeed = false - Note that evaluator is not called.

##1##: Begin
Inside Evaluator
MonoJust inside 565
java.lang.RuntimeException: aaa
##1##: Done: 567

##2##: Begin
MonoJust inside 569
java.lang.RuntimeException: aaa
##2##: Done: 569


问:
Azure Active Directory B2B cost when user is not assigned a license
I noticed when I went to the Azure portal under Active Directory, I could assign a user the license to Azure AD Premium P2 (I have a trial).

However, I also noticed that I don't need to assign a user this license (in the step above), and the user is able to reset their password.

I know that users can only reset their password if we are not using the free version of Azure AD.

Does this mean that the user above who is able to access the password reset page is counted part of the cost ($11.52 per month per user in this case), even though they haven't been assigned an explicit license in their profile?

答:
It seems you are wanted to know whether the cost calculated if the user assigned to the specific licence.

For your understanding, in each subscriptions how many users has this role access would not be counted as cost , let's say, you have 10 users with this access but 2/3 user used it. So bill will be calculated for 2/3 uses not 10 users even you assigned 10 users for this.

Cost usually be calculated upon total uses. So don't worry about the cost on azure cloud. It has uses friendly metrics.

Usually prices Default usage quota is 50,000 objects. If you exceeded the this limit then the new metrics would be applied as per your uses.

Note: For more details you could check this docs. Check your bills here


问:
Error: Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience
I am developing a chrome extension in which on button click I need data from ajax GET and after that need to go for further processing. For that, I want synchronous ajax call, but it is giving me an error

Error: Synchronous XMLHttpRequest on the main thread is deprecated
  because of its detrimental effects on the end user's experience.

I know this error is because I set async=false, but unless and until I don't get data from API, I cannot go for further processing. Below is my code:

```<code>var nonce;
window.addEventListener('load', function load(event){
    var createButton = document.getElementById('send');
    createButton.addEventListener('click', function() {
       signTransaction('abc',12,'abc');
    });
});
function signTransaction(to,amount,inputhex){
    nonce = getNonce();
    console.log(nonce);
    tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
}
function getNonce() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.xx.xx:9999/getAccount?address=xxxxxxxxx', false);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
      } else {
        console.log('error');
      }
    }
    // Send request
    request.send(null);
    return nonce;
   }
</code>```

You can check in code, In signTransaction() first I need nonce from getNonce() function and then can go further. So, I set async false to this function.
Can somebody help me with this?

答:
Per MDN:

```<code>Do not use synchronous requests outside Web Workers.
</code>```

You could adjust the logic between the two functions such that you define signTransaction() to take in the output of your XML request, then nest signTransaction within getNonce.  In that sense, getNonce becomes the controller and signTransaction is an intermediate output back into getNonce.

```<code>function signTransaction(to,amount,inputhex, nonceResponse){
    let tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
    return transaction

}

function getNonce(to,amount,inputhex) {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.51.212:9999/getAccount?
                         address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
        return signTransaction(to,amount,inputhex,data)
      } else {
        console.log('error');
      }
}
</code>```

You could also use ES6 async/await syntax to take advantage of promises and yield program flow during completion of async operations:

```<code>
async function signTransaction(to,amount,inputhex){
    nonce = await getNonce(); // `await` call yields flow back to the thread while the other async function getNonce() is executed
    tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
}

async function getNonce() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.51.212:9999/getAccount?address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
        return nonce; // returning here resolves the promise that is implicitly returned from an async function with the value returned from your XML call.  This value triggers continuation of the signTransaction function with XML call result
      } else {
        console.log('error');
      }
    }
    // Send request
    request.send(null);
}
</code>```

Body:
I am developing a chrome extension in which on button click I need data from ajax GET and after that need to go for further processing. For that, I want synchronous ajax call, but it is giving me an error

Error: Synchronous XMLHttpRequest on the main thread is deprecated
  because of its detrimental effects on the end user's experience.

I know this error is because I set async=false, but unless and until I don't get data from API, I cannot go for further processing. Below is my code:

var nonce;
window.addEventListener('load', function load(event){
    var createButton = document.getElementById('send');
    createButton.addEventListener('click', function() {
       signTransaction('abc',12,'abc');
    });
});
function signTransaction(to,amount,inputhex){
    nonce = getNonce();
    console.log(nonce);
    tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
}
function getNonce() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.xx.xx:9999/getAccount?address=xxxxxxxxx', false);
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
      } else {
        console.log('error');
      }
    }
    // Send request
    request.send(null);
    return nonce;
   }

You can check in code, In signTransaction() first I need nonce from getNonce() function and then can go further. So, I set async false to this function.
Can somebody help me with this?

Body:
Per MDN:

Do not use synchronous requests outside Web Workers.

You could adjust the logic between the two functions such that you define signTransaction() to take in the output of your XML request, then nest signTransaction within getNonce.  In that sense, getNonce becomes the controller and signTransaction is an intermediate output back into getNonce.

function signTransaction(to,amount,inputhex, nonceResponse){
    let tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
    return transaction

}

function getNonce(to,amount,inputhex) {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.51.212:9999/getAccount?
                         address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
        return signTransaction(to,amount,inputhex,data)
      } else {
        console.log('error');
      }
}

You could also use ES6 async/await syntax to take advantage of promises and yield program flow during completion of async operations:

async function signTransaction(to,amount,inputhex){
    nonce = await getNonce(); // `await` call yields flow back to the thread while the other async function getNonce() is executed
    tx = {
        To : to,
        PrivateKey : pri,
        Balance : amount,
        Nonce : String(nonce),
        Gas : "1",
        Type : "a64",
        Input : inputhex
    }
    let transaction = new sdag.Signs.NewTransaction(pri,tx);
}

async function getNonce() {
    var request = new XMLHttpRequest();
    request.open('GET', 'http://192.168.51.212:9999/getAccount?address=23471aa344372e9c798996aaf7a6159c1d8e3eac', true);
//third arg to request.open() could be omitted if intent is to process call asynchronously
    request.onload = function () {
      var data = JSON.parse(this.response);
      if (request.status >= 200 && request.status < 400) {
        nonce = data.Nonce;
        return nonce; // returning here resolves the promise that is implicitly returned from an async function with the value returned from your XML call.  This value triggers continuation of the signTransaction function with XML call result
      } else {
        console.log('error');
      }
    }
    // Send request
    request.send(null);
}


问:
The listview in my Fragment is not showing any data
I am creating a CategoryFragment that will display all the data that is added from my activity. The code is working fine, the data is added in the database, I have checked the data in Device File Explorer and the data that I added are there but they are not showing in my listview. Here are the codes:

CategoriesFragment.java

```<code>package com.example.devcash.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

import com.example.devcash.ADD_UI.AddCategoryActivity;
import com.example.devcash.CustomAdapters.CategoryAdapter;
import com.example.devcash.Database.DatabaseHelper;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoriesFragment extends Fragment implements SearchView.OnQueryTextListener {

    DatabaseHelper db;
    ListView lv;
    CategoryAdapter categoryAdapter;

    public CategoriesFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_categories, container, false);

        //add floating action button
        FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
        categories_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // when add fab is pressed, go to add product activity
                Intent addcategory = new Intent(getActivity(), AddCategoryActivity.class);
                startActivity(addcategory);
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //handles listview
        ListView lvcategories = (ListView) view.findViewById(R.id.categorylist_listview);
        db = new DatabaseHelper(getActivity());

        ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();

        lvcategories.setAdapter(categoryAdapter);

        categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
        categoryListArrayList = db.getAllCategory();

        getActivity().setTitle("Categories");
    }

    //handles the search menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.searchmenu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(this);
        searchView.setQueryHint("Search..");

        super.onCreateOptionsMenu(menu, inflater);
    }
    }
</code>```

fragmentcategories.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.CategoriesFragment"
    android:padding="@dimen/text_padding">

        <ListView
            android:id="@+id/categorylist_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="1dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/addcategories_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add"
        android:tint="@color/whiteBG"
        android:backgroundTint="@color/colorPrimary"/>

</FrameLayout>
</code>```

CategoryAdapter.java

```<code> package com.example.devcash.CustomAdapters;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.example.devcash.Lists.CategoryList;
    import com.example.devcash.R;

    import java.util.ArrayList;

    public class CategoryAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<CategoryList> categoryListArrayList;

    public CategoryAdapter(Context context, ArrayList<CategoryList> categoryListArrayList) {
        this.context = context;
        this.categoryListArrayList = categoryListArrayList;
    }

    @Override
    public int getCount() {
        return categoryListArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return categoryListArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if(convertView == null){
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.category_customlayout, null, true);

            holder.textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        //display the data into the CategoryFragment
        holder.textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());

        return convertView;
    }

    private class ViewHolder{
        protected TextView textCategoryName;
    }
}
</code>```

答:
First of all, you need to rearrange this code

```<code>ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
lvcategories.setAdapter(categoryAdapter);
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
categoryListArrayList = db.getAllCategory();
</code>```

To

```<code>ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryListArrayList = db.getAllCategory();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);
</code>```

And in adapter code for inflating view you need to pass parent value not null.

Use this

```<code>LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, parent, false); // You just pass null instead of parent
</code>```

instead of

```<code>LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, null, true);
</code>```

Hope this will help.

Body:
I am creating a CategoryFragment that will display all the data that is added from my activity. The code is working fine, the data is added in the database, I have checked the data in Device File Explorer and the data that I added are there but they are not showing in my listview. Here are the codes:

CategoriesFragment.java

package com.example.devcash.Fragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;

import com.example.devcash.ADD_UI.AddCategoryActivity;
import com.example.devcash.CustomAdapters.CategoryAdapter;
import com.example.devcash.Database.DatabaseHelper;
import com.example.devcash.Lists.CategoryList;
import com.example.devcash.R;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoriesFragment extends Fragment implements SearchView.OnQueryTextListener {

    DatabaseHelper db;
    ListView lv;
    CategoryAdapter categoryAdapter;

    public CategoriesFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_categories, container, false);

        //add floating action button
        FloatingActionButton categories_fab = view.findViewById(R.id.addcategories_fab);
        categories_fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // when add fab is pressed, go to add product activity
                Intent addcategory = new Intent(getActivity(), AddCategoryActivity.class);
                startActivity(addcategory);
            }
        });

        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        //handles listview
        ListView lvcategories = (ListView) view.findViewById(R.id.categorylist_listview);
        db = new DatabaseHelper(getActivity());

        ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();

        lvcategories.setAdapter(categoryAdapter);

        categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
        categoryListArrayList = db.getAllCategory();

        getActivity().setTitle("Categories");
    }

    //handles the search menu
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.searchmenu, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setOnQueryTextListener(this);
        searchView.setQueryHint("Search..");

        super.onCreateOptionsMenu(menu, inflater);
    }
    }

fragmentcategories.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Fragments.CategoriesFragment"
    android:padding="@dimen/text_padding">

        <ListView
            android:id="@+id/categorylist_listview"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dividerHeight="1dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/addcategories_fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@drawable/ic_add"
        android:tint="@color/whiteBG"
        android:backgroundTint="@color/colorPrimary"/>

</FrameLayout>

CategoryAdapter.java

 package com.example.devcash.CustomAdapters;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    import com.example.devcash.Lists.CategoryList;
    import com.example.devcash.R;

    import java.util.ArrayList;

    public class CategoryAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<CategoryList> categoryListArrayList;

    public CategoryAdapter(Context context, ArrayList<CategoryList> categoryListArrayList) {
        this.context = context;
        this.categoryListArrayList = categoryListArrayList;
    }

    @Override
    public int getCount() {
        return categoryListArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return categoryListArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        if(convertView == null){
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.category_customlayout, null, true);

            holder.textCategoryName = (TextView) convertView.findViewById(R.id.txtcategory_name);

            convertView.setTag(holder);
        }else{
            holder = (ViewHolder)convertView.getTag();
        }
        //display the data into the CategoryFragment
        holder.textCategoryName.setText(categoryListArrayList.get(position).getCategory_name());

        return convertView;
    }

    private class ViewHolder{
        protected TextView textCategoryName;
    }
}

Body:
First of all, you need to rearrange this code

ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
lvcategories.setAdapter(categoryAdapter);
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
categoryListArrayList = db.getAllCategory();

To

ArrayList<CategoryList> categoryListArrayList = new ArrayList<CategoryList>();
categoryListArrayList = db.getAllCategory();
categoryAdapter = new CategoryAdapter(getActivity(), categoryListArrayList);
lvcategories.setAdapter(categoryAdapter);

And in adapter code for inflating view you need to pass parent value not null.

Use this

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, parent, false); // You just pass null instead of parent

instead of

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.category_customlayout, null, true);

Hope this will help.


问:
Images not showing up on a mac
I have setup up a simple file upload system using laravel.
To store the image, I set up my controller as

```<code>public function store(Request $request)
{
    $menu = new Menu;
    $menu->title = $request->get('menuTitle');
    $menu->user_id = Auth::id();

    if($request->hasFile('menuImage')){
        $filenameWithExt = $request->file('menuImage')->getClientOriginalName();
        $fileName = pathinfo($filenameWithExt,PATHINFO_FILENAME);
        $ext = $request->file('menuImage')->getClientOriginalExtension();

        $fileNameToStore = $fileName.'_'.time().'.'.$ext;
        $path = $request->file('menuImage')->storeAs('public/menu',$fileNameToStore);
    }
    else{
        $fileNameToStore = 'blank.jpg';
    }
    $menu->image_name = $fileNameToStore;
    $menu->save();
    return redirect(route('menu.create'))->with('success',$menu->title." Added successfully");

}
</code>```

In the view I set it up as

```<code><a href="#">
      <img class="img-fluid rounded mb-3 mb-md-0"  src={{asset("/storage/menu/".$menu->image_name)}} alt="">
    </a>
</code>```

In the browser the link is

```<code><img class="img-fluid rounded mb-3 mb-md-0" src="http://127.0.0.1:8000/storage/menu/Screenshot_20190517_023111_1558916284.png" alt="">
</code>```

While developing, I was working on ubuntu and everything works fine. However, I transferred my files to my mac and using xampp I was able to get everything working. However the images do not load anymore. I get a 404 error when I check the console. However, the images are able to upload to the right folder.

答: You should run php artisan storage:link so that the storage/app/public will be linked to public/storage directory and your link will work again

Title: Images not showing up on a mac

Body:
I have setup up a simple file upload system using laravel.
To store the image, I set up my controller as

public function store(Request $request)
{
    $menu = new Menu;
    $menu->title = $request->get('menuTitle');
    $menu->user_id = Auth::id();

    if($request->hasFile('menuImage')){
        $filenameWithExt = $request->file('menuImage')->getClientOriginalName();
        $fileName = pathinfo($filenameWithExt,PATHINFO_FILENAME);
        $ext = $request->file('menuImage')->getClientOriginalExtension();

        $fileNameToStore = $fileName.'_'.time().'.'.$ext;
        $path = $request->file('menuImage')->storeAs('public/menu',$fileNameToStore);
    }
    else{
        $fileNameToStore = 'blank.jpg';
    }
    $menu->image_name = $fileNameToStore;
    $menu->save();
    return redirect(route('menu.create'))->with('success',$menu->title." Added successfully");

}

In the view I set it up as

      image_name)}} alt="">

In the browser the link is

While developing, I was working on ubuntu and everything works fine. However, I transferred my files to my mac and using xampp I was able to get everything working. However the images do not load anymore. I get a 404 error when I check the console. However, the images are able to upload to the right folder.


答:
This is simply a matter of making sure you're using the correct path to your JavaScript file:

```

Notice the ./ before the file name, which indicates the file is on the same level as your HTML file.

Title: JavaScript (jQuery) sometimes does not work when you link it as a separate file

Body:
This is simply a matter of making sure you're using the correct path to your JavaScript file:

<head>
  <script src="./sample_code.js"></script>
</head>

Notice the ./ before the file name, which indicates the file is on the same level as your HTML file.


问:
C# logic question
I have those boolean values:

```<code>bool test = false && true || true; // true
bool test1 = false && (true || true); // false
</code>```

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

答:
First one:

```<code>False and True or True
</code>```

One condition satisfied, So its return true

Second one:

```<code>False and (True or True) = False and True
</code>```

one condition failed, So its return false

Title: C# logic question

Body:
I have those boolean values:

bool test = false && true || true; // true
bool test1 = false && (true || true); // false

Now, can anybody explain why this is? Shouldnt those be the same?

Thanks :)

Body:
First one:

False and True or True

One condition satisfied, So its return true

Second one:

False and (True or True) = False and True

one condition failed, So its return false


问:
SageMath: running `make` ends with ImportError in dochtml phase
I am trying to install sagemath package in my macbook. I entered
./configure followed by make. Here are the last few
lines of output. Couldn't debug the cause.

```<code>[sagelib-8.7] Finished cleaning, time: 0.40 seconds.
[sagelib-8.7] if [ "$UNAME" = "CYGWIN" ]; then                         \
[sagelib-8.7]       sage-rebase.sh "$SAGE_LOCAL" 2>/dev/null;            \
[sagelib-8.7]   fi
[sagelib-8.7]
[sagelib-8.7] real  19m37.851s
[sagelib-8.7] user  59m16.416s
[sagelib-8.7] sys   2m58.759s
cp /Users/satya/Downloads/SageMath/src/bin/sage-env-config /Users/satya/Downloads/SageMath/local/bin/sage-env-config
cd ../.. && sage-logger -p './sage --docbuild --no-pdf-links all html ' logs/dochtml.log
[dochtml] Traceback (most recent call last):
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/runpy.py", line 163, in _run_module_as_main
[dochtml]     mod_name, _Error)
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/runpy.py", line 111, in _get_module_details
[dochtml]     __import__(mod_name)  # Do not catch exceptions initializing package
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage_setup/docbuild/__init__.py", line 60, in <module>
[dochtml]     import sage.all
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/all.py", line 98, in <module>
[dochtml]     from sage.symbolic.all   import *
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/all.py", line 3, in <module>
[dochtml]     from sage.libs.pynac.pynac import I
[dochtml]   File "sage/symbolic/expression.pxd", line 4, in init sage.libs.pynac.pynac (build/cythonized/sage/libs/pynac/pynac.cpp:30147)
[dochtml]   File "sage/symbolic/expression.pyx", line 161, in init sage.symbolic.expression (build/cythonized/sage/symbolic/expression.cpp:74075)
[dochtml] ImportError: dlopen(/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so, 2): Symbol not found: __ZNSt3__16vectorIN5GiNaC2exENS_9allocatorIS2_EEE11__vallocateEm
[dochtml]   Referenced from: /Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so
[dochtml]   Expected in: flat namespace
[dochtml]  in /Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so
make[3]: *** [doc-html] Error 1
make[2]: *** [all-start] Error 2

real    19m41.468s
user    59m18.862s
sys 3m0.256s
***************************************************************
Error building Sage.

The following package(s) may have failed to build (not necessarily
during this run of 'make all-start'):

The build directory may contain configuration files and other potentially
helpful information. WARNING: if you now run 'make' again, the build
directory will, by default, be deleted. Set the environment variable
SAGE_KEEP_BUILT_SPKGS to 'yes' to prevent this.

make[1]: *** [all-start] Error 1
make: *** [all] Error 2
</code>```

Any help would be appreciated.

答:
Running make for SageMath proceeds in two steps: make build
followed by make doc.

In your case, the make build phase seems to have completed,
and there was an issue only in the make doc phase.
This means you probably already have a functional SageMath,
with the drawback that the documentation failed to build.
So you might decide to try and use it as is.

Following @John Palmieri, I would recommend posting to sage-devel
or sage-support to get help debugging the make failure. It will
be useful to specify the operating system on which it occurred
(what version of macOS), if the buid was started from a directory
obtained by git clone or from a source tarball, what exact
sequence of operations were run.

Also, on your next attempt, you might want to move the SageMath
folder out of the Downloads folder before you run make, since
a Sage installation cannot be moved after it has been started once
(if Sage is moved, one has to run make again before it can be used).

Body:
I am trying to install sagemath package in my macbook. I entered
./configure followed by make. Here are the last few
lines of output. Couldn't debug the cause.

[sagelib-8.7] Finished cleaning, time: 0.40 seconds.
[sagelib-8.7] if [ "$UNAME" = "CYGWIN" ]; then                         \
[sagelib-8.7]       sage-rebase.sh "$SAGE_LOCAL" 2>/dev/null;            \
[sagelib-8.7]   fi
[sagelib-8.7]
[sagelib-8.7] real  19m37.851s
[sagelib-8.7] user  59m16.416s
[sagelib-8.7] sys   2m58.759s
cp /Users/satya/Downloads/SageMath/src/bin/sage-env-config /Users/satya/Downloads/SageMath/local/bin/sage-env-config
cd ../.. && sage-logger -p './sage --docbuild --no-pdf-links all html ' logs/dochtml.log
[dochtml] Traceback (most recent call last):
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/runpy.py", line 163, in _run_module_as_main
[dochtml]     mod_name, _Error)
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/runpy.py", line 111, in _get_module_details
[dochtml]     __import__(mod_name)  # Do not catch exceptions initializing package
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage_setup/docbuild/__init__.py", line 60, in <module>
[dochtml]     import sage.all
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/all.py", line 98, in <module>
[dochtml]     from sage.symbolic.all   import *
[dochtml]   File "/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/all.py", line 3, in <module>
[dochtml]     from sage.libs.pynac.pynac import I
[dochtml]   File "sage/symbolic/expression.pxd", line 4, in init sage.libs.pynac.pynac (build/cythonized/sage/libs/pynac/pynac.cpp:30147)
[dochtml]   File "sage/symbolic/expression.pyx", line 161, in init sage.symbolic.expression (build/cythonized/sage/symbolic/expression.cpp:74075)
[dochtml] ImportError: dlopen(/Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so, 2): Symbol not found: __ZNSt3__16vectorIN5GiNaC2exENS_9allocatorIS2_EEE11__vallocateEm
[dochtml]   Referenced from: /Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so
[dochtml]   Expected in: flat namespace
[dochtml]  in /Users/satya/Downloads/SageMath/local/lib/python2.7/site-packages/sage/symbolic/ring.so
make[3]: *** [doc-html] Error 1
make[2]: *** [all-start] Error 2

real    19m41.468s
user    59m18.862s
sys 3m0.256s
***************************************************************
Error building Sage.

The following package(s) may have failed to build (not necessarily
during this run of 'make all-start'):

The build directory may contain configuration files and other potentially
helpful information. WARNING: if you now run 'make' again, the build
directory will, by default, be deleted. Set the environment variable
SAGE_KEEP_BUILT_SPKGS to 'yes' to prevent this.

make[1]: *** [all-start] Error 1
make: *** [all] Error 2

Any help would be appreciated.


问:
SQL default value error when uploading files using laravel
i'm trying to upload multiple images using laravel and so far i've succeded, but the problem is that when i try to save text AND the files i get an error.
So far i've received so many errors that i can't remember all of then, but the latest is:

SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts (image, updated_at, created_at) values (["italian.jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))

i've set the sql properly, and as i said, if i remove the image upload it works, and if i remove the text fields it also work, but if i try both i doesnt.
if i remember correctly when i remove the required fields it also works.

public function store(Request $request)
    {
              //dd($request);

```<code>    $this->validate($request, [
        'title' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if($request->hasfile('image')){
        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;
        }
    } else{
        redirect('/posts')->with('Error', 'no image');
    }

    $post->image=json_encode($data);

    $post = Post::create($validatedData);

    return redirect('/posts')->with('success', 'yay');

}
</code>```

i also tried this, but it returns

Creating default object from empty value

```<code>public function store(Request $request)
{
     $validatedData = $request->validate([
        'title' => 'required|min:3|max:120',
        'category' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    if($request->hasfile('image'))
     {

        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;
        }
     }

     $post = new Post();
     $post->image=json_encode($data);

    $post->save();

    return back()->with('success', 'Yay');

}
</code>```

答:
i figured it out, hehe. just had to remove these lines:

'image' => 'required',
 'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'

Thanks anyways.

Body:
i'm trying to upload multiple images using laravel and so far i've succeded, but the problem is that when i try to save text AND the files i get an error.
So far i've received so many errors that i can't remember all of then, but the latest is:

SQLSTATE[HY000]: General error: 1364 Field 'title' doesn't have a default value (SQL: insert into posts (image, updated_at, created_at) values (["italian.jpg"], 2019-05-23 18:48:22, 2019-05-23 18:48:22))

i've set the sql properly, and as i said, if i remove the image upload it works, and if i remove the text fields it also work, but if i try both i doesnt.
if i remember correctly when i remove the required fields it also works.

public function store(Request $request)
    {
              //dd($request);

    $this->validate($request, [
        'title' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048'
    ]);

    if($request->hasfile('image')){
        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;
        }
    } else{
        redirect('/posts')->with('Error', 'no image');
    }

    $post->image=json_encode($data);

    $post = Post::create($validatedData);

    return redirect('/posts')->with('success', 'yay');

}

i also tried this, but it returns

Creating default object from empty value

public function store(Request $request)
{
     $validatedData = $request->validate([
        'title' => 'required|min:3|max:120',
        'category' => 'required|min:3|max:120',
        'text' => 'required',
        'image' => 'required',
        'image.*' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    ]);

    if($request->hasfile('image'))
     {

        foreach($request->file('image') as $image)
        {
            $name=$image->getClientOriginalName();
            $image->move(public_path().'/images/', $name);
            $data[] = $name;
        }
     }

     $post = new Post();
     $post->image=json_encode($data);

    $post->save();

    return back()->with('success', 'Yay');

}


问:
Gitlab CI execution error but pipeline success
I have a simple project .gitlab-ci.yaml

```<code>variables:
  GIT_STRATEGY: clone

stages:
 - build

build-and-run-tests:
  stage: build
  tags:
    - windows
  script:
    - call npm install
    - call npm run build-client-in-target
    - call npm run run-tests-on-target
</code>```

when I start the build pipeline, it fails while executing build-client-in-target, but the pipeline continues with success status

答:
you should move all preprocessing to before_script tag
and remove the call command

https://docs.gitlab.com/ee/ci/yaml/#before_script-and-after_script

```<code>variables:
  GIT_STRATEGY: clone

stages:
 - build

build-and-run-tests:
  stage: build
  tags:
    - windows
  before_script:
    - npm install
    - npm run build-client-in-target
  script:
    - npm run run-tests-on-targe
</code>```

Body:
I have a simple project .gitlab-ci.yaml

variables:
  GIT_STRATEGY: clone

stages:
 - build

build-and-run-tests:
  stage: build
  tags:
    - windows
  script:
    - call npm install
    - call npm run build-client-in-target
    - call npm run run-tests-on-target

when I start the build pipeline, it fails while executing build-client-in-target, but the pipeline continues with success status

Body:
you should move all preprocessing to before_script tag
and remove the call command

https://docs.gitlab.com/ee/ci/yaml/#before_script-and-after_script

variables:
  GIT_STRATEGY: clone

stages:
 - build

build-and-run-tests:
  stage: build
  tags:
    - windows
  before_script:
    - npm install
    - npm run build-client-in-target
  script:
    - npm run run-tests-on-targe