问:
How to remove components created with Angular-CLI
I am working on angular2 for my new project, newly with this technology. I have set-up my project with angular CLI (Reference site https://github.com/angular/angular-cli).
I have created 4 components using command ng generate component my-new-component
For testing purpose, created one component app-testing, need to remove that component from my project. Else need to rename for that component. I have tried several like. ng destroy component app-testing but showing error The destroy command is not supported by Angular-CLI., Please help me with solution.
Thanks in advance.

答: I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me. </p>


来源: stackexchange

问:
Extract Value from XML having same tag name in SQL Server
I have XML variable defined below and its value.

I want to fetch the text defined between tag <TextNodeChild> in single query.

Kindly help.

```<code>Declare @XMLVariable =
'<?xml version="1.0"?>
 <root>
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'
</code>```

I need output like this:

```<code>12345
67890
12389
</code>```

答:
You could use the XQuery (i.e. XML query) .nodes() method

```<code>SELECT
    TextNodeParent = n.value('.[1]', 'NVARCHAR(max)')
FROM
    @XMLVariable.nodes('root/TextNodeParent/*') as p(n)
</code>```

EDIT : If you want to just the select the TextNodeChild node data then little change in xml path  as follow

```<code> @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as p(n)
</code>```

Result

```<code>TextNodeParent
12345
67890
12389
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have XML variable defined below and its value.

I want to fetch the text defined between tag <TextNodeChild> in single query.

Kindly help.

Declare @XMLVariable =
'<?xml version="1.0"?>
 <root>
     <TextNodeParent>
         <TextNodeChild>12345</TextNodeChild>
         <TextNodeChild>67890</TextNodeChild>
         <TextNodeChild>12389</TextNodeChild>
     </TextNodeParent>
 </root>'

I need output like this:

12345
67890
12389

Body:
You could use the XQuery (i.e. XML query) .nodes() method

SELECT
    TextNodeParent = n.value('.[1]', 'NVARCHAR(max)')
FROM
    @XMLVariable.nodes('root/TextNodeParent/*') as p(n)

EDIT : If you want to just the select the TextNodeChild node data then little change in xml path  as follow

 @XMLVariable.nodes('root/TextNodeParent/TextNodeChild') as p(n)

Result

TextNodeParent
12345
67890
12389


问:
bash variable capture stderr and stdout separately or get exit value
I need to capture the output and error of a command in my bash script and know whether the command succeeded or not.

At the moment, I am capturing both like this:

```<code>output=$(mycommand 2>&1)
</code>```

I then need to check the exit value of mycommand. If it failed, I need to do some stuff with the output, if the command succeeded, I don't need to touch the output.

Since I am capturing the output, checking $? is always a 0 since bash succeeded at capturing the output into the variable.

This is a very time sensitive script, so we are trying to avoid any slower solutions like outputting to a file and re-reading it in.

If I could capture stdout to one variable and stderr to another, that would solve my problem because I could just check if the error variable was empty or not.

Thanks.

答:
The problem only seems to manifest when the output is captured to a local variable within a function:

```<code>$ echo $BASH_VERSION
3.2.48(1)-release
$ false; echo $?
1
$ echo $?
0
$ x=$(false 2>&1) ; echo $?
1
$ function f {
> local x=$(false 2>&1) ; echo $?
> }
$ f
0
$ function g {
> x=$(false 2>&1) ; echo $?
> }
$ g
1
</code>```

Notice that only function f, which captures x to a local, can express the behavior.  Particularly, function g which does the same thing, but without the 'local' keyword, works.

One can therefore not use a local variable, and perhaps 'unset' it after use.

EDIT NVRAM points out that the local declaration can be made beforehand to avoid the issue:

```<code>$ function h {
>   local x
>   x=$(false 2>&1) ; echo $?
> }
$ h
1
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to capture the output and error of a command in my bash script and know whether the command succeeded or not.

At the moment, I am capturing both like this:

output=$(mycommand 2>&1)

I then need to check the exit value of mycommand. If it failed, I need to do some stuff with the output, if the command succeeded, I don't need to touch the output.

Since I am capturing the output, checking $? is always a 0 since bash succeeded at capturing the output into the variable.

This is a very time sensitive script, so we are trying to avoid any slower solutions like outputting to a file and re-reading it in.

If I could capture stdout to one variable and stderr to another, that would solve my problem because I could just check if the error variable was empty or not.

Thanks.

Body:
The problem only seems to manifest when the output is captured to a local variable within a function:

$ echo $BASH_VERSION
3.2.48(1)-release
$ false; echo $?
1
$ echo $?
0
$ x=$(false 2>&1) ; echo $?
1
$ function f {
> local x=$(false 2>&1) ; echo $?
> }
$ f
0
$ function g {
> x=$(false 2>&1) ; echo $?
> }
$ g
1

Notice that only function f, which captures x to a local, can express the behavior.  Particularly, function g which does the same thing, but without the 'local' keyword, works.

One can therefore not use a local variable, and perhaps 'unset' it after use.

EDIT NVRAM points out that the local declaration can be made beforehand to avoid the issue:

$ function h {
>   local x
>   x=$(false 2>&1) ; echo $?
> }
$ h
1


答:
This is an easy workaround, based on the answer provided here

Just add a line break; \n, at the start of your axes title; xlab("\nYour_x_Label") (Or at the end if you need to move your y label).

It doesn't offer as much control as Eduardo's suggestion in the comments; theme(axis.title.x = element_text(vjust=-0.5)), or use of margin, but it is much simpler!

ContentLicense: CC BY-SA 4.0

Title: move axis labels ggplot

Body:
I have produced a fact graph in ggplot2 and the x axis title (bottom) is touching the scale values slightly (it's worsened when I plot to .pdf device).  How do I move the axis title down a smidge?

DF<-structure(list(race = structure(c(3L, 1L, 3L, 2L, 3L, 1L, 2L,
2L, 2L, 3L, 2L, 1L, 3L, 3L, 3L, 3L, 2L, 1L, 2L, 3L), .Label = c("asian",
"black", "white"), class = "factor"), gender = structure(c(1L,
1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L,
2L, 2L, 2L), .Label = c("female", "male"), class = "factor"),
    score = c(0.0360497844302483, 0.149771418578119, 0.703017688328021,
    1.32540102136392, 0.627084455719946, -0.320051801571444,
    0.852281028633536, -0.440056896755573, 0.621765489966213,
    0.58981396944136, 1.95257757882381, 0.127301498272644, -0.0906338578670778,
    -0.637727808028146, -0.449607617033673, 1.03162398117388,
    0.334259623567608, 0.0912327543652576, -0.0789977852804991,
    0.511696466039959), time1 = c(75.9849658266583, 38.7148843859919,
    54.3512613852158, 37.3210772390582, 83.8061071736856, 14.3853324033061,
    79.2285735003004, 31.1324602891428, 22.2294730114138, 26.427263191766,
    40.5529893144888, 19.2463281412667, 8.45085646487301, 97.6770352620696,
    61.1874163107771, 31.3727683430548, 99.4155144857594, 79.0996849438957,
    21.2504885323517, 94.1079332400361)), .Names = c("race",
"gender", "score", "time1"), class = "data.frame", row.names = c(NA,
-20L))

require(ggplot2)
p <- ggplot(DF, aes(score, time1, group=gender))
p + geom_point(aes(shape=19)) + facet_grid(race~gender) + scale_x_continuous('BLAH BLAH') +
scale_y_continuous('Some MOre Of theat Good Blahing')

In my data BLAH BLAH is touching the numbers.  I need it to move down.  How?


问:
Java Handler Post Delayed task is not accurate timer
I have created two Handlers, which each have Runnable Tasks which run in a loop through:

```<code>// do it again 1 hundeth of a sec later
QuestionHandler.postDelayed(QuestionHandlerTask, 10);
</code>```

And through:

```<code>// and do it again 1 sec later
GameHandler.postDelayed(GameHandlerTask, 1000);
</code>```

Both the tasks start at 10 and count downwards and their results are displayed in labels. The reason i have used 2 handler's is because i want 1 timer to count down by milleseconds and 1 to count down by seconds.

However, the GameHandlerTask that runs once per second runs significantly faster than the other. By the time it reaches 1 the QuestionHandlerTask is still at 4 seconds:

Is this a commonly known problem or have i done something seriously wrong? Is there some way i can make it so my timers run at the same speed? Is there other methods that i can use that would be better in this circumstance (where i want precise timing)?

答:
This is because the screen cannot refresh 100 times per second, which is what is happening with the 10 millisecond timer. So the screen tries to show every single value that you told it to show, but can only do so at its maximum refresh rate.

It is not the timer that is slow, it is the screen that can't keep up with the timer.

To solve this, try to calculate how much does the number need to go down by in 40 milliseconds, and you start a timer of 40ms. This will update the screen 25 times a second, which the screen should be able to handle.

Body:
I have created two Handlers, which each have Runnable Tasks which run in a loop through:

// do it again 1 hundeth of a sec later
QuestionHandler.postDelayed(QuestionHandlerTask, 10);

And through:

// and do it again 1 sec later
GameHandler.postDelayed(GameHandlerTask, 1000);

Both the tasks start at 10 and count downwards and their results are displayed in labels. The reason i have used 2 handler's is because i want 1 timer to count down by milleseconds and 1 to count down by seconds.

However, the GameHandlerTask that runs once per second runs significantly faster than the other. By the time it reaches 1 the QuestionHandlerTask is still at 4 seconds:

Is this a commonly known problem or have i done something seriously wrong? Is there some way i can make it so my timers run at the same speed? Is there other methods that i can use that would be better in this circumstance (where i want precise timing)?


问:
Odoo 10 - Disable default "My opportunities" filter in CRM
When user checks sales flow (opportunities) in Odoo 10 CRM module, the "My opportunities" filter is enabled by default.

Is it possible to configure behaviour so user has no such filter and he/she sees all opportunities?

Thanks

答:
There are two ways to remove default filter "My Opportunities" on the CRM leads by Editing Action.

1. Edit action from UI

Activate developer mode. and from the debug edit the action.

2. Edit action from XML

in below record search_default_assigned_to_me is responsible for setting the default filter.

```<code><record model="ir.actions.act_window" id="crm.crm_lead_opportunities_tree_view">
    <field name="context">{
        'default_type': 'opportunity',
        'default_user_id': uid,
        'search_default_assigned_to_me': 0,
        }
    </field>
</record>
</code>```

Hope this helps!

Body:
There are two ways to remove default filter "My Opportunities" on the CRM leads by Editing Action.

1. Edit action from UI

Activate developer mode. and from the debug edit the action.

2. Edit action from XML

in below record search_default_assigned_to_me is responsible for setting the default filter.

<record model="ir.actions.act_window" id="crm.crm_lead_opportunities_tree_view">
    <field name="context">{
        'default_type': 'opportunity',
        'default_user_id': uid,
        'search_default_assigned_to_me': 0,
        }
    </field>
</record>

Hope this helps!


问:
How to launch a YouTube URL on Windows Phone 7
I would like to launch directly to the YouTube player on Windows Phone 7.

I tried using WebBrowserTask and giving a YouTube URL, it opens up the browser and brings me to a page with a thumbnail of the YouTube video, I need to click on the thumbnail before the video plays.

I like to skip the extra click. I like the user to click a button in my app, and it should play the video directly. Is there a way to do it?

答:
Once you have the Youtube app installed, from within you application you can start the WebBrowserTask and do the follwing:

```<code>        Regex Youtube = new Regex("youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)");

        Match youtubeMatch = Youtube.Match(YOUTUBE_VIDEO_URL);

        string id = string.Empty;

        if (youtubeMatch.Success)
            id = youtubeMatch.Groups[1].Value;

        WebBrowserTask webBrowserTask = new WebBrowserTask();

        webBrowserTask.URL = "vnd.youtube:"+ id +"?vndapp=youtube_mobile";
        webBrowserTask.Show();
</code>```

That should launch the browser, then automatically launch the Youtube App. Cheers!

Body:
Once you have the Youtube app installed, from within you application you can start the WebBrowserTask and do the follwing:

        Regex Youtube = new Regex("youtu(?:\\.be|be\\.com)/(?:.*v(?:/|=)|(?:.*/)?)([a-zA-Z0-9-_]+)");

        Match youtubeMatch = Youtube.Match(YOUTUBE_VIDEO_URL);

        string id = string.Empty;

        if (youtubeMatch.Success)
            id = youtubeMatch.Groups[1].Value;

        WebBrowserTask webBrowserTask = new WebBrowserTask();

        webBrowserTask.URL = "vnd.youtube:"+ id +"?vndapp=youtube_mobile";
        webBrowserTask.Show();

That should launch the browser, then automatically launch the Youtube App. Cheers!


问:
How to check MySQL returned an empty result set?
I am curious if my query returns an empty result set and my fetching method is PDO::FETCH_ASSOC what is the actual value of that as it is fetched in an array? Is it just false or an empty array or 0 ?

And how can I check that let´s say in the following context:
$ajResult = $query1->fetchAll(PDO::FETCH_ASSOC); if ($ajResult ???? ) {....} else {};

答:
Use rowCount

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

```<code>if ($query1->rowCount() > 0) {
  // not empty
} else {
   echo 'nothing';
}
</code>```

Since fetchAll returns an array, you can use count to get the number of rows returned from the query.

```<code>if (count($ajResult)) {...}
</code>```

Body:
Use rowCount

PDOStatement::rowCount — Returns the number of rows affected by the last SQL statement

if ($query1->rowCount() > 0) {
  // not empty
} else {
   echo 'nothing';
}

Since fetchAll returns an array, you can use count to get the number of rows returned from the query.

if (count($ajResult)) {...}


问:
Debug complex return statement
I am using totalview as a linux C++ debugger. Functions in our code often look something like this

```<code>double foo() {
    int a = 2;
    int b = 3;
    return bar(a,b);
}
</code>```

where some preliminary work is done and than a more or less complex function bar is called a the return statement.

This is hard to debug with totalview, since the interesting return value can not be observed easily. Totalview can not evaluate the expressing bar(a,b). I can rewrite the code as

```<code>double foo() {
    int a = 2;
    int b = 3;
    const auto retVal = bar(a,b);
    return retVal;
}
</code>```

Now, I can place a breakpoint at the return value and observe the in- and output of my function bar.

How can I do this without introducing a new (useless) variable?

答:
Let the compiler optimise out the "useless" variable, by a process called named return value optimisation, and leave it in. (Personally though I would help the compiler as much as possible by using the return type of the function explicitly rather than auto; so there's no potential type conversion at the return stage.). For what it's worth, I do this all the time, even with heavy objects such as std::vector. You can always check the generated assembler if you suspect the compiler is making superfluous copies.

Then you can set a breakpoint at the appropriate place as you know.

In some debuggers you can inspect the function return value directly by peeking at a register, but this is by no means universal.

Reference: http://en.cppreference.com/w/cpp/language/copy_elision

Title: Debug complex return statement

Body:
I am using totalview as a linux C++ debugger. Functions in our code often look something like this

double foo() {
    int a = 2;
    int b = 3;
    return bar(a,b);
}

where some preliminary work is done and than a more or less complex function bar is called a the return statement.

This is hard to debug with totalview, since the interesting return value can not be observed easily. Totalview can not evaluate the expressing bar(a,b). I can rewrite the code as

double foo() {
    int a = 2;
    int b = 3;
    const auto retVal = bar(a,b);
    return retVal;
}

Now, I can place a breakpoint at the return value and observe the in- and output of my function bar.

How can I do this without introducing a new (useless) variable?


答:
You can use the TIME() function to extract the time part of the datatime,
So you can do something like this:
select * FROM table t
where TIME(f.time) between '17:30:00' AND '18:30:00'</p>

Title: query for time in mysql between hours

Body:
how to get a list of rows that is between 17:30 till tomarrow 8:30.

--------------------------------------
| id | user_id | action |     time    |
--------------------------------------
| 1  |   25    | enter  | 1512459905
| 2  |   19    |  exit  | 1512125105
| 3  |   31    | enter  | 1514581905  |
--------------------------------------

mysql table have a time column with unix timestamp and i want get a list every day that between 17:30 till 8:30


问:
ItemClick for a MvxLinearLayout? MvvmCross 5
I'm using the following code as described in this thread to execute an event when a LinearLayout is clicked in ListView. It used to work perfectly but after update to MvvmCross 5, it does not work anymore because the mvxDataConsumer becomes null when parsed to IMvxDataConsumer and I can't figure out the reason why?

```<code>public class MvxClickableLinearLayout : MvxLinearLayout
{
    public MvxClickableLinearLayout(Context context, IAttributeSet attrs)
        : this(context, attrs, new MvxClickableLinearLayoutAdapter(context))
    {
    }

    public MvxClickableLinearLayout(Context context, IAttributeSet attrs, MvxClickableLinearLayoutAdapter adapter)
        : base(context, attrs, adapter)
    {
        var mvxClickableLinearLayoutAdapter = Adapter as MvxClickableLinearLayoutAdapter;
        if (mvxClickableLinearLayoutAdapter != null)
        {
            mvxClickableLinearLayoutAdapter.OnItemClick = OnItemClick;
        }
    }

    public ICommand ItemClick { get; set; }

    public void OnItemClick(object item)
    {
        if (ItemClick != null && ItemClick.CanExecute(item))
        {
            ItemClick.Execute(item);
        }
    }
}

public class MvxClickableLinearLayoutAdapter : MvxAdapterWithChangedEvent, View.IOnClickListener
{
    public delegate void ItemClickDelegate(object item);

    public ItemClickDelegate OnItemClick;

    public MvxClickableLinearLayoutAdapter(Context context)
        : base(context)
    {
    }

    public void OnClick(View view)
    {
        var mvxDataConsumer = view as IMvxDataConsumer;

        if (mvxDataConsumer != null && OnItemClick != null)
        {
            OnItemClick(mvxDataConsumer.DataContext);
        }
    }

    protected override View GetView(int position, View convertView, ViewGroup parent, int templateId)
    {
        View view = base.GetView(position, convertView, parent, templateId);
        view.SetOnClickListener(this);
        return view;
    }
}
</code>```

axml:

```<code><Controls.MvxClickableLinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    local:MvxBind="ItemsSource Items;ItemClick GoToCommand"
    local:MvxItemTemplate="@layout/main_list_item" />
</code>```

答:
In your OnClick method in MvxClickableLinearLayoutAdapter class, change:

var mvxDataConsumer = view as IMvxDataConsumer;

to:

var mvxDataConsumer = view?.Tag as IMvxDataConsumer;

It should work now. In MvvmCross 5, it is now a view holder, not the view itself.

Body:
I'm using the following code as described in this thread to execute an event when a LinearLayout is clicked in ListView. It used to work perfectly but after update to MvvmCross 5, it does not work anymore because the mvxDataConsumer becomes null when parsed to IMvxDataConsumer and I can't figure out the reason why?

public class MvxClickableLinearLayout : MvxLinearLayout
{
    public MvxClickableLinearLayout(Context context, IAttributeSet attrs)
        : this(context, attrs, new MvxClickableLinearLayoutAdapter(context))
    {
    }

    public MvxClickableLinearLayout(Context context, IAttributeSet attrs, MvxClickableLinearLayoutAdapter adapter)
        : base(context, attrs, adapter)
    {
        var mvxClickableLinearLayoutAdapter = Adapter as MvxClickableLinearLayoutAdapter;
        if (mvxClickableLinearLayoutAdapter != null)
        {
            mvxClickableLinearLayoutAdapter.OnItemClick = OnItemClick;
        }
    }

    public ICommand ItemClick { get; set; }

    public void OnItemClick(object item)
    {
        if (ItemClick != null && ItemClick.CanExecute(item))
        {
            ItemClick.Execute(item);
        }
    }
}

public class MvxClickableLinearLayoutAdapter : MvxAdapterWithChangedEvent, View.IOnClickListener
{
    public delegate void ItemClickDelegate(object item);

    public ItemClickDelegate OnItemClick;

    public MvxClickableLinearLayoutAdapter(Context context)
        : base(context)
    {
    }

    public void OnClick(View view)
    {
        var mvxDataConsumer = view as IMvxDataConsumer;

        if (mvxDataConsumer != null && OnItemClick != null)
        {
            OnItemClick(mvxDataConsumer.DataContext);
        }
    }

    protected override View GetView(int position, View convertView, ViewGroup parent, int templateId)
    {
        View view = base.GetView(position, convertView, parent, templateId);
        view.SetOnClickListener(this);
        return view;
    }
}

axml:

<Controls.MvxClickableLinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    local:MvxBind="ItemsSource Items;ItemClick GoToCommand"
    local:MvxItemTemplate="@layout/main_list_item" />


问:
How to find object value from property path in Javascript object
I explain the problem with sample.

For example i have javascript object. It looks like:

```<code>var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }
</code>```

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

```<code>path = ["points",0,"x"]
or
path= ["obj","name"]
</code>```

So my question is that how to generate json object from these path.

For example i have to generate that

```<code>trial.points[0].x        or    trial.obj.name
</code>```

How to do that ?  thank you for your answer.

答:
You can use array#reduce and pass your object and path as variables. Array#reduce will return the value corresponding to a path.

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} },
    path1 = ["points",0,"x"],
    path2= ["obj","name"],
    valueAtPath = (object, path) => path.reduce((r,p) => r[p], object);

console.log(valueAtPath(trial, path1));
console.log(valueAtPath(trial, path2));```

Body:
I explain the problem with sample.

For example i have javascript object. It looks like:

var trial= { points:[{x:1,y:2},{x:5,y:2},{x:3,y:4}] , obj:{id:5,name:"MyName"} }

I use deep diff module to find difference between two json array. Then it find the differences and find difference path. If value of x is changed, then it finds.

For example

path = ["points",0,"x"]
or
path= ["obj","name"]

So my question is that how to generate json object from these path.

For example i have to generate that

trial.points[0].x        or    trial.obj.name

How to do that ?  thank you for your answer.


问:
What is the double dash in this bash script excerpt doing
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

```<code> case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac
</code>```

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?

答:
compgen is a bash builtin command, and the man pages say:

Unless  otherwise  noted,  each  builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options.

Since $cur is a variable that contains options (starting with -), the -- is required (as mentioned in the man pages) to make a distinction between compgen options and input to be processed.

The following command is turning the option --d in --debug:

```<code>compgen -W '-a -d -f -l -t -h --aoption --debug --file --log --test --help --' -- --d
--debug
</code>```

If you remove the separator --, the command throws an error, because compgen doesn't have any option starting with --d:

```<code>compgen -W '-a -d -f -l -t -h --aoption --debug --file --log --test --help --' --d
-bash: compgen: --: invalid option
compgen: usage: compgen [-abcdefgjksuv] [-o option]  [-A action] [-G globpat] [-W wordlist]  [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]
</code>```

The ;; is a separator used in the case, esac statement to terminate in your example the section started with -*). Look at bash man pages for Compound Commands to get more info.

Body:
I'm looking at an excerpt of bash and I'm trying to understand what exactly is happening here, particularly in the COMPREPLY assignment:

 case "$cur" in
    -*)
    COMPREPLY=( $( compgen -W '-a -d -f -l -t -h --aoption --debug \
                               --file --log --test --help --' -- $cur ) );;
#   Generate the completion matches and load them into $COMPREPLY array.
#   xx) May add more cases here.
#   yy)
#   zz)
  esac

I understand we're assigning a value to COMPREPLY here based on the output of compgen, but what exactly is -- doing in this assignment? Also, why the double semi-colon?

Body:
compgen is a bash builtin command, and the man pages say:

Unless  otherwise  noted,  each  builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options.

Since $cur is a variable that contains options (starting with -), the -- is required (as mentioned in the man pages) to make a distinction between compgen options and input to be processed.

The following command is turning the option --d in --debug:

compgen -W '-a -d -f -l -t -h --aoption --debug --file --log --test --help --' -- --d
--debug

If you remove the separator --, the command throws an error, because compgen doesn't have any option starting with --d:

compgen -W '-a -d -f -l -t -h --aoption --debug --file --log --test --help --' --d
-bash: compgen: --: invalid option
compgen: usage: compgen [-abcdefgjksuv] [-o option]  [-A action] [-G globpat] [-W wordlist]  [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] [word]

The ;; is a separator used in the case, esac statement to terminate in your example the section started with -*). Look at bash man pages for Compound Commands to get more info.


答:
fetchAll returns an array of the rows, so if the array has 0 elements...

```<code>if ( count($ajResult) == 0 ) {....} else {}
</code>```

Title: How to check MySQL returned an empty result set?

Body:
I am curious if my query returns an empty result set and my fetching method is PDO::FETCH_ASSOC what is the actual value of that as it is fetched in an array? Is it just false or an empty array or 0 ?

And how can I check that let´s say in the following context:
$ajResult = $query1->fetchAll(PDO::FETCH_ASSOC); if ($ajResult ???? ) {....} else {};

Body:
fetchAll returns an array of the rows, so if the array has 0 elements...

if ( count($ajResult) == 0 ) {....} else {}


问:
Xpath-like package for Python to find keys on all level in lists and dicts
Given is a data structure which has the key TEXT in arbitrary positions in the structure like this example:

```<code>{'info': [
    {'TEXT': 'SUBINLIST'},
          {'duda': {
              'TEXT': 'SUBSUB',
              'walter': 'jaja'}}
          {'hey': [
              {'jess': 'morning'},
              {'TEXT': 'DEEPEST'}
          ]}
    ],
 'TEXT': 'TOPLEVEL'}
</code>```

I want to find the values of the TEXT keys. Is there a XPath-like package for Python where I can define an appropriate path expression so that I get for the example the following result returned:

```<code>['SUBINLIST', 'SUBSUB', 'DEEPEST', 'TOPLEVEL']
</code>```

Note: I do not want to find the keys through a recursive Python function, but via an call to a package/library/module (which obviously will do that internally as well).

I tried jsonpath-rw, but could not come up with an expression which finds the values in arbitrarily nested dicts and lists.

答:
You can try jsonpath as below:

```<code>import jsonpath

my_dict = {'info': [{'TEXT': 'SUBINLIST'},{'duda': {'TEXT': 'SUBSUB','walter': 'jaja'}}, {'hey': [{'jess': 'morning'}, {'TEXT': DEEPEST'}]}], 'TEXT': 'TOPLEVEL'}
print(jsonpath.jsonpath(my_dict, "$..TEXT"))
</code>```

Output:

```<code>['TOPLEVEL', 'SUBINLIST', 'SUBSUB', 'DEEPEST']
</code>```

Body:
Given is a data structure which has the key TEXT in arbitrary positions in the structure like this example:

{'info': [
    {'TEXT': 'SUBINLIST'},
          {'duda': {
              'TEXT': 'SUBSUB',
              'walter': 'jaja'}}
          {'hey': [
              {'jess': 'morning'},
              {'TEXT': 'DEEPEST'}
          ]}
    ],
 'TEXT': 'TOPLEVEL'}

I want to find the values of the TEXT keys. Is there a XPath-like package for Python where I can define an appropriate path expression so that I get for the example the following result returned:

['SUBINLIST', 'SUBSUB', 'DEEPEST', 'TOPLEVEL']

Note: I do not want to find the keys through a recursive Python function, but via an call to a package/library/module (which obviously will do that internally as well).

I tried jsonpath-rw, but could not come up with an expression which finds the values in arbitrarily nested dicts and lists.

Body:
You can try jsonpath as below:

import jsonpath

my_dict = {'info': [{'TEXT': 'SUBINLIST'},{'duda': {'TEXT': 'SUBSUB','walter': 'jaja'}}, {'hey': [{'jess': 'morning'}, {'TEXT': DEEPEST'}]}], 'TEXT': 'TOPLEVEL'}
print(jsonpath.jsonpath(my_dict, "$..TEXT"))

Output:

['TOPLEVEL', 'SUBINLIST', 'SUBSUB', 'DEEPEST']


问:
How to prevent jquery funcions overriding
```<code><script src="<c:url value="/ruleengineui/resources/js/vendor/jquery.js" />"></script>
<script src="<c:url value="/ruleengineui/resources/js/Dummyjs/jquery-1.7.2.min.js"/>"></script>
</code>```

I am importing above two files to my jsp file. But the second file will override the first one.How can I solve this problem.

Thanks

答:
Check out http://jsfiddle.net/9ezy09ep/54/, and use the External Resources in that page.</p>

```<code>$(selector).dialog();
$(selector).jqGrid({});
</code>```

Body:
Check out http://jsfiddle.net/9ezy09ep/54/, and use the External Resources in that page.

$(selector).dialog();
$(selector).jqGrid({});


问:
TensorFlow estimator.predict() gives WARNING:tensorflow:Input graph does not contain a QueueRunner
I'm trying to get a prediction with a custom input function with estimator.predict, but it gives me this:

WARNING:tensorflow:Input graph does not contain a QueueRunner. That means predict yields forever. This is probably a mistake.

It doesn't give me an error, but predict just says that its restoring parameters and doesn't return the actual predictions. Here is my code:

```<code>test_data = [0.03, 0.91, 0.95, 0.10, 0.56, 0.93]
test_data_in = { k: test_data[index] for index, k in enumerate(FEATURES) }
print(test_data_in)

def predict_input_fn(data_set):
    feature_cols = { k: tf.reshape(tf.constant(data_set[k], dtype=tf.float32), [-1]) for k in FEATURES }
    return feature_cols

predictions = estimator.predict(input_fn=lambda: predict_input_fn(test_data_in))
print(list(predictions))
</code>```

I've looked at this issue, but I couldn't find a solution related to my problem. Why does TensorFlow show this warning and how do I get rid of it?

答:
I hit this too, reading the thread https://github.com/tensorflow/tensorflow/issues/11621

I think your program is perfectly correct and it's the warning that's wrong :). It was added long before the Datasets API existed, and was well intentioned. (AFAICT the predict() API relies on your input terminating with a tf.errors.OutOfRangeError and before Datasets existed only QueueRunner-based pipelines would terminate that way, so it probably was an error if no queue runners existed.)
  @xiejw Should we remove this warning, or is there a more cunning way to detect the error condition?

Hopefully they will remove the error when it's unnecessary.

Body:
I'm trying to get a prediction with a custom input function with estimator.predict, but it gives me this:

WARNING:tensorflow:Input graph does not contain a QueueRunner. That means predict yields forever. This is probably a mistake.

It doesn't give me an error, but predict just says that its restoring parameters and doesn't return the actual predictions. Here is my code:

test_data = [0.03, 0.91, 0.95, 0.10, 0.56, 0.93]
test_data_in = { k: test_data[index] for index, k in enumerate(FEATURES) }
print(test_data_in)

def predict_input_fn(data_set):
    feature_cols = { k: tf.reshape(tf.constant(data_set[k], dtype=tf.float32), [-1]) for k in FEATURES }
    return feature_cols

predictions = estimator.predict(input_fn=lambda: predict_input_fn(test_data_in))
print(list(predictions))

I've looked at this issue, but I couldn't find a solution related to my problem. Why does TensorFlow show this warning and how do I get rid of it?


问:
R: find largest interval in dates with condition
I have a data frame with date and price. For some dates, price is NA. I'm trying to find the largest interval in dates between "last" (in a continuous sequence) NA price and last non-NA price. I'm completely lost - I suspect difftime needs to be used but I cannot come up with a condition for this.

E.g.:

```<code> DF = structure(list(rollup_date = c("2017-05-01 00:00:00", "2017-05-02 00:00:00",
"2017-05-03 00:00:00", "2017-05-04 00:00:00", "2017-05-05 00:00:00",
"2017-05-06 00:00:00", "2017-05-07 00:00:00", "2017-05-08 00:00:00",
"2017-05-09 00:00:00", "2017-05-10 00:00:00", "2017-05-11 00:00:00",
"2017-05-12 00:00:00", "2017-05-13 00:00:00", "2017-05-14 00:00:00",
"2017-05-15 00:00:00"), RegularPrice = c(6.47, 6.47, 6.47, 6.47,
NA, NA, NA, NA, NA, NA, NA, 6.47, NA, 6.47, 6.47)), .Names = c("rollup_date",
"RegularPrice"), row.names = 145624:145638, class = "data.frame")
</code>```

So, outputs here are 7 days (5/11 - 5/04) and 1 day (5/13 - 5/12). All solutions can be stored and then I just pick largest.

答:
For the sake of completeness, here is also a data.table solution:

```<code>library(data.table)
setDT(DF)[, rollup_date := as.Date(rollup_date)][
  , .(last(RegularPrice), last(rollup_date)), by = rleid(is.na(RegularPrice))][
    , diff.days := V2 - shift(V2)][
      is.na(V1)]
</code>```

```<code>   rleid V1         V2 diff.days
1:     2 NA 2017-05-11    7 days
2:     4 NA 2017-05-13    1 days
</code>```

Explanation

After coercion to data.table, rollup_date is converted from character to class Date (POSIXct is not needed here). Then the data is grouped by contiguous streaks of NA and non-NA values using the rleid() function, picking the last values in each group. The intermediate result is aggregated to 5 rows.

Finally, the date difference between each group is calculated and returned only for NA rows.

Prerequisite

The data needs to be sorted by rollup_date which apparently is the case for the sample data provided by the OP but was not explicitely mentioned.

Alternative solution

The aggregation consists of just picking the values in last row in each group. No other computation like sum() or mean() is involved. This is like filtering DF.

This can be achieved as well by returning the relevant row ids .I and using this to select the respective rows from DF:

```<code>DF[, last(.I), by = rleid(is.na(RegularPrice))][, V1]
</code>```

```<code>[1]  4 11 12 13 15
</code>```

So, the complete solution becomes

```<code>setDT(DF)[, rollup_date := as.Date(rollup_date)][
  DF[, last(.I), by = rleid(is.na(RegularPrice))][, V1]][
  , diff.days := rollup_date - shift(rollup_date)][
    is.na(RegularPrice)]
</code>```

```<code>   rollup_date RegularPrice diff.days
1:  2017-05-11           NA    7 days
2:  2017-05-13           NA    1 days
</code>```

Body:
I have a data frame with date and price. For some dates, price is NA. I'm trying to find the largest interval in dates between "last" (in a continuous sequence) NA price and last non-NA price. I'm completely lost - I suspect difftime needs to be used but I cannot come up with a condition for this.

E.g.:

 DF = structure(list(rollup_date = c("2017-05-01 00:00:00", "2017-05-02 00:00:00",
"2017-05-03 00:00:00", "2017-05-04 00:00:00", "2017-05-05 00:00:00",
"2017-05-06 00:00:00", "2017-05-07 00:00:00", "2017-05-08 00:00:00",
"2017-05-09 00:00:00", "2017-05-10 00:00:00", "2017-05-11 00:00:00",
"2017-05-12 00:00:00", "2017-05-13 00:00:00", "2017-05-14 00:00:00",
"2017-05-15 00:00:00"), RegularPrice = c(6.47, 6.47, 6.47, 6.47,
NA, NA, NA, NA, NA, NA, NA, 6.47, NA, 6.47, 6.47)), .Names = c("rollup_date",
"RegularPrice"), row.names = 145624:145638, class = "data.frame")

So, outputs here are 7 days (5/11 - 5/04) and 1 day (5/13 - 5/12). All solutions can be stored and then I just pick largest.

Body:
For the sake of completeness, here is also a data.table solution:

library(data.table)
setDT(DF)[, rollup_date := as.Date(rollup_date)][
  , .(last(RegularPrice), last(rollup_date)), by = rleid(is.na(RegularPrice))][
    , diff.days := V2 - shift(V2)][
      is.na(V1)]

   rleid V1         V2 diff.days
1:     2 NA 2017-05-11    7 days
2:     4 NA 2017-05-13    1 days

Explanation

After coercion to data.table, rollup_date is converted from character to class Date (POSIXct is not needed here). Then the data is grouped by contiguous streaks of NA and non-NA values using the rleid() function, picking the last values in each group. The intermediate result is aggregated to 5 rows.

Finally, the date difference between each group is calculated and returned only for NA rows.

Prerequisite

The data needs to be sorted by rollup_date which apparently is the case for the sample data provided by the OP but was not explicitely mentioned.

Alternative solution

The aggregation consists of just picking the values in last row in each group. No other computation like sum() or mean() is involved. This is like filtering DF.

This can be achieved as well by returning the relevant row ids .I and using this to select the respective rows from DF:

DF[, last(.I), by = rleid(is.na(RegularPrice))][, V1]

[1]  4 11 12 13 15

So, the complete solution becomes

setDT(DF)[, rollup_date := as.Date(rollup_date)][
  DF[, last(.I), by = rleid(is.na(RegularPrice))][, V1]][
  , diff.days := rollup_date - shift(rollup_date)][
    is.na(RegularPrice)]

   rollup_date RegularPrice diff.days
1:  2017-05-11           NA    7 days
2:  2017-05-13           NA    1 days


问:
I want to get only count from the control file
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

```<code>AA.dat  200
</code>```

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

答:
Or equally simply with read if you know the file format beforehand, e.g.

```<code>read -r stuff cnt <AA.dat
</code>```

Where you simply read the first line in the file into two variables. stuff will hold the first whitespace separated string, cnt will hold the remainder of the line 200 in your case, e.g.:

```<code>$ read -r stuff cnt <AA.dat; echo "cnt: $cnt"
cnt: 200
</code>```

awk is another easy way to access the second column of data. In its simplest form it will output the second column for all lines (in your case 1-line):

```<code>$ awk '{print $2}' AA.dat
200
</code>```

shell also provides for parameter expansion with substring removal and substring replacement. Both can be use to isolate 200 after reading the full line into a single variable.

Shell depending (with bash, etc), you can also read the line into an array and then make use of the element of interest. There are a number of ways to handle it.

Take your pick. The only note would be using a shell builtin prevents invoking a separate subshell for whatever utility you use instead. If you are calling the utility repeatedly within a loop on a large file -- utilities (as opposed to builtins) can dramatically increase the script run-time. If you just call it a handful of times, the differences is negligible.

Body:
I want to get only count from a control file. The control file's name is AA.dat (for example) and the data in the file will be as follows.

AA.dat  200

From the above file I want to pick only the value 200. When I try to use the cut command I am not able to get the result.

Body:
Or equally simply with read if you know the file format beforehand, e.g.

read -r stuff cnt <AA.dat

Where you simply read the first line in the file into two variables. stuff will hold the first whitespace separated string, cnt will hold the remainder of the line 200 in your case, e.g.:

$ read -r stuff cnt <AA.dat; echo "cnt: $cnt"
cnt: 200

awk is another easy way to access the second column of data. In its simplest form it will output the second column for all lines (in your case 1-line):

$ awk '{print $2}' AA.dat
200

shell also provides for parameter expansion with substring removal and substring replacement. Both can be use to isolate 200 after reading the full line into a single variable.

Shell depending (with bash, etc), you can also read the line into an array and then make use of the element of interest. There are a number of ways to handle it.

Take your pick. The only note would be using a shell builtin prevents invoking a separate subshell for whatever utility you use instead. If you are calling the utility repeatedly within a loop on a large file -- utilities (as opposed to builtins) can dramatically increase the script run-time. If you just call it a handful of times, the differences is negligible.


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

Title: how to know if a $string ends with ','?

Body:
if (substr($str, -1) === ',')
{
 echo 'it is';
}


问:
Miss inpout file @androidsdk//:build-tools/26.0.1/aapt when compiling tensorflow android demo with bazel
I want to compile the Tensorflow Android demo in Ubuntu with Bazel

I also tried this command after searching but another error occurred:

sudo apt-get install lib32stdc++6 lib32z1

I changed WORKSPACE file buildtools to 26.0.2,and the result of compilation is as follows:

What I can do?

答:
Use path names with ASCII characters only. I'm not sure Bazel works correctly with paths that contain non-ASCII characters.

Make sure you installed the Android SDK.

Open /home/fancy/AI/tensorflow/WORKSPACE in an editor, and make sure that:

the android_sdk_repository and android_ndk_repository rules are uncommented (don't have a # before them), and

these rules have a path attribute, which specifies the absolute path to the Android SDK and NDK, respectively


问:
How to extend UWP app's window into multiple screen
I'm trying to make UWP (Universal Windows Platform) application with visual C# and xaml which is displayed into multiple screen with full screen mode.

So, at first I added the code to enter into full screen mode in App.xaml.cs like below.

```<code>Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TryEnterFullScreenMode();
</code>```

I'm not sure how to extend the window into multiple screen.
I use two 4K displays but the application is displayed in one screen with full screen mode.

The resolution of 1 display is 3840*2160, so the application should be displayed in the size of 3840*4320 with full screen mode.

The OS presentation setting of multiple screen is "Extend".

Anybody know how to extend application window?

The application target of windows is "Windows 10 Fall Creators Update 16299"

答:
Windows does not support natively mosaic mode.

You can connect n number of monitors, but you still only will be able to configure them with extend functionality.

Given that multiple displays requires a good and/or powerful multiple graphic cards.

Third party manufacturers like Nvidia, developed a set of drivers that can support this functionality, so, the way to go is not native to Microsoft, there is not support on the .NET framework for this.

Body:
I'm trying to make UWP (Universal Windows Platform) application with visual C# and xaml which is displayed into multiple screen with full screen mode.

So, at first I added the code to enter into full screen mode in App.xaml.cs like below.

Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TryEnterFullScreenMode();

I'm not sure how to extend the window into multiple screen.
I use two 4K displays but the application is displayed in one screen with full screen mode.

The resolution of 1 display is 3840*2160, so the application should be displayed in the size of 3840*4320 with full screen mode.

The OS presentation setting of multiple screen is "Extend".

Anybody know how to extend application window?

The application target of windows is "Windows 10 Fall Creators Update 16299"


问:
why api key is creating without SH1 on android api console?
While creating map `api key` on api console earlier it shows package name and `SH1` option. But, now it is not showing.

What is the difference between key created by google and key created by package name?

答: when you create a new app on Google API console it generates an API key for you and you can generate your own key from the console, Any API key has to be restricted to be related to your app and track all API calls and requests made by your app through that key, Keys are restricted by adding the package name and SHA-1 fingerprint of your app which are unique to your app, You can ignore key restriction in debugging mode but if you decided to release your app key restriction will be required before publishing.</p>


问:
Printing an Array List full of a new type of object
I am working on a Java program, where I have an ArrayList called "CD" and inside this CD there are "Songs", and each song is an object in my Song class, and it has the arguments: String artist, String album, and int year. Any general suggestions about how to print this such that it also prints the contents of each song?

P.S. I know there are similar questions on here but I am still having trouble getting it to print exactly what I am wanting it to, and I have tried using iterator.

Thanks for all help in advance!

答:
You need to implement the toString() method in your Song class.

Without this method implemented, Java will only print the reference address of the object.
For your Songclass, the  toString() method could look like this:

```<code>public String toString(){
    return "Artist:"+artists+", Song name:"+ songName+", Album:"+album+", Year:"+year;
}
</code>```

After that, you can simply print your array with
System.out.println(Arrays.toString(cd));

Body:
You need to implement the toString() method in your Song class.

Without this method implemented, Java will only print the reference address of the object.
For your Songclass, the  toString() method could look like this:

public String toString(){
    return "Artist:"+artists+", Song name:"+ songName+", Album:"+album+", Year:"+year;
}

After that, you can simply print your array with
System.out.println(Arrays.toString(cd));


问:
Java source vs. Android SDK differences?
If I look at the source code for AudioManager, there is:

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";
```

However, is not visible by Eclipse, even when you specify the minimum SDK level.

How can this happen?

Is this part of the API or not?

Thanks

答:
You missed the part above, the @hide indicating it is not included in the SDK:</p>

```<code>/**
 * @hide Broadcast intent when the volume for a particular stream type changes.
 * Includes the stream, the new volume and previous volumes
 *
 * @see #EXTRA_VOLUME_STREAM_TYPE
 * @see #EXTRA_VOLUME_STREAM_VALUE
 * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
 */
</code>```

Body:
If I look at the source code for AudioManager, there is:

@SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
public static final String VOLUME_CHANGED_ACTION = "android.media.VOLUME_CHANGED_ACTION";

However, is not visible by Eclipse, even when you specify the minimum SDK level.

How can this happen?

Is this part of the API or not?

Thanks

Body:
You missed the part above, the @hide indicating it is not included in the SDK:

/**
 * @hide Broadcast intent when the volume for a particular stream type changes.
 * Includes the stream, the new volume and previous volumes
 *
 * @see #EXTRA_VOLUME_STREAM_TYPE
 * @see #EXTRA_VOLUME_STREAM_VALUE
 * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
 */


问:
GIT: how to stash a file after being edited locally
I've run "git add file" on local file and now I'm trying stash the action.

```<code>git status

\# On branch feature/something

\# Changes to be committed:

\#   (use "git reset HEAD <file>..." to unstage)

\#  modified:   utils.py
</code>```

When I run git diff utils.py response is Empty

How do I stash this changes I've done locally
Thanks!

答: Just use the command git stash “name_of_the_file” this will stash the modified file in the currently checked out branch.

Body:
I've run "git add file" on local file and now I'm trying stash the action.

git status

\# On branch feature/something

\# Changes to be committed:

\#   (use "git reset HEAD <file>..." to unstage)

\#  modified:   utils.py

When I run git diff utils.py response is Empty

How do I stash this changes I've done locally
Thanks!


问:
How to print the list of filesystem in Linux kernel?
What I'm trying to do is to list the all of the registered filesystem in a linux kernel module.I tried writing code like below in reference to find_filesystem(http://elixir.free-electrons.com/linux/v3.19/source/fs/filesystems.c) in fs/filesystems.c.

```<code>#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>       // for basic filesystem

MODULE_LICENSE("Dual BSD/GPL");

static struct file_system_type *file_systems;

void list_filesystem(void){
    struct file_system_type **p;
    for(p=&file_systems; *p; p=&(*p)->next){
        printk(KERN_INFO "%s\n",(*p)->name);
    }
}
static int __init filesystem_list_init(void){
    printk(KERN_INFO "Loaded list_filesystem module\n");
    list_filesystem();
    return 0;
}

static void __exit filesystem_list_exit(void){
    printk(KERN_INFO "list_filesystem module unloaded \n");
}

/* Declaration of the init and exit functions */
module_init(filesystem_list_init);
module_exit(filesystem_list_exit);
</code>```

I expected that this list all of the filesystem.
but it doesn't show any filesystem name.
so please let me know what' wrong with this code and how this should be modified.

答:
In your module you cannot iterate over filesystems list, because the head of that list - file_systems variable - is inaccessible for you: the source file which implements filesystem list declares the variable as static. You have tried to create your own instance of variable, but this is just a new list. As nobody fills it, it is empty.

Current implementation of the filesystem's list doesn't provide methods for iterate over original list in an outer code. One may only obtain filesystem list in textual representation by reading file /proc/filesystems.

Body:
What I'm trying to do is to list the all of the registered filesystem in a linux kernel module.I tried writing code like below in reference to find_filesystem(http://elixir.free-electrons.com/linux/v3.19/source/fs/filesystems.c) in fs/filesystems.c.

#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>       // for basic filesystem

MODULE_LICENSE("Dual BSD/GPL");

static struct file_system_type *file_systems;

void list_filesystem(void){
    struct file_system_type **p;
    for(p=&file_systems; *p; p=&(*p)->next){
        printk(KERN_INFO "%s\n",(*p)->name);
    }
}
static int __init filesystem_list_init(void){
    printk(KERN_INFO "Loaded list_filesystem module\n");
    list_filesystem();
    return 0;
}

static void __exit filesystem_list_exit(void){
    printk(KERN_INFO "list_filesystem module unloaded \n");
}

/* Declaration of the init and exit functions */
module_init(filesystem_list_init);
module_exit(filesystem_list_exit);

I expected that this list all of the filesystem.
but it doesn't show any filesystem name.
so please let me know what' wrong with this code and how this should be modified.


问:
How to stop on the Sign Up Form when web page performs Postback?
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

```<code>function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}
</code>```

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

```<code>function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}
</code>```

Sign Up Form:-

The .aspx code of anchors and buttons is:

```<code><label id="lblSignup" style="float: right">
    For new account?
  <a href="javascript:;" id="signup" onclick="signupClick()">Sign Up</a>
</label>
  <label id="lblLogin" style="float: right; display: none">
      For existing account?
  <a href="javascript:;" id="login" onclick="loginClick()">Login</a>
  </label>
</div>
<label style="width: 28%">
  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />
</label>
<label style="width: 70%; float: right">
  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />
</label>
</code>```

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

```<code>private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}
</code>```

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

答:
The server side code needs to tell the client side know the form fields (Sign Up or Login) to be shown base on the validation result, one way to do that is adding a protected property in your code behind, like:

```<code>protected bool showSignUpDialog = false;
</code>```

on validation failed:

```<code>if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
{
    txtCustName.Visible = true;
    txtEmail.Visible = true;
    txtPassword.Visible = true;
    txtConfirmPassword.Visible = true;
    //etc....

    ShowMessage("Fill all cradentials of customer.");
    showSignUpDialog = true;
}
</code>```

in your javascript section, utilize the showSignUpDialog and existing loginClick/signupClick:

```<code>$(document).ready(function () {
    <% if (showSignUpDialog) {%>
        signupClick();
    <% } else {%>
        loginClick();
    <% } %>
});
</code>```

by default the showSignUpDialog is false so it will call the loginClick() to show the login fields, which is the default behavior from your demo

Body:
I'm working on my final year project. In which:

I have Login and Signup forms on one page (WebForm):

When user click on anchor Sign Up the DropDown ddlType (hides) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Displays) in Javascript client side:

function signupClick() {
  document.getElementById('divType').style.display = 'block' ? 'none' : 'block';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'inherit';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'none';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'inherit';

  document.getElementById('lblLogin').style.display = 'inherit';
  document.getElementById('lblSignup').style.display = 'none';
}

Login Form:-

And when user click on anchor Login the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) in Javascript client side:

function loginClick() {
  document.getElementById('divType').style.display = 'none' ? 'block' : 'none';

  document.getElementById('<%=txtCustName.ClientID%>').style.display = 'none';
  document.getElementById('<%=txtConfirmPassword.ClientID%>').style.display = 'none';

  document.getElementById('<%=btnLogin.ClientID%>').style.display = 'inherit';
  document.getElementById('<%=btnSignUp.ClientID%>').style.display = 'none';

  document.getElementById('lblLogin').style.display = 'none';
  document.getElementById('lblSignup').style.display = 'inherit';
}

Sign Up Form:-

The .aspx code of anchors and buttons is:

    For new account?
  Sign Up

      For existing account?
  Login

  <asp:HyperLink ID="hlHome" NavigateUrl="Index.aspx" Text="Home" CssClass="btn btn-default" Width="100%" runat="server" />

  <asp:Button ID="btnLogin" OnClick="btnLogin_Click" CssClass="btn btn-success" Width="100%" runat="server" Text="Login" />
  <asp:Button ID="btnSignUp" OnClick="btnSignUp_Click" Style="display: none" Width="100%" CssClass="btn btn-primary" runat="server" Text="Sign Up" />

Question:

When user click on button Sign Up the DropDown ddlType (Displays) and TextBoxes - txtCustName, txtEmail and txtConfirmPassword (Hides) but I want to prevent this condition and the sign up form should be shown:

private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('" + msg + "');", true);
}
protected void btnSignUp_Click(object sender, EventArgs e)
{
    string cusname = txtCustName.Text;
    string email = txtEmail.Text;
    string pass = txtPassword.Text;
    string confirm = txtConfirmPassword.Text;

    if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
    {
        ShowMessage("Fill all cradentials of customer.");
    }
    else
    {
        //.. Register user

        Response.Redirect("~/CustomerPanel/Dashboard.aspx");
    }
}

--- JavaScript Function ---
function AutoHideAlert(msg) {
  // lblAlert is an asp:Label for displaying alert message
  var al = document.getElementById('<%=lblAlert.ClientID%>');

  al.innerText = msg;

  // alert is a DIV to show message
  $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
      $("#alert").slideUp(500);
  });
}

How I can stop it on the Sign Up Form?

Updated:

My problem is when click on Sign Up button it sets to the Login form as like:

Body:
The server side code needs to tell the client side know the form fields (Sign Up or Login) to be shown base on the validation result, one way to do that is adding a protected property in your code behind, like:

protected bool showSignUpDialog = false;

on validation failed:

if (string.IsNullOrEmpty(cusname) || string.IsNullOrEmpty(email) || string.IsNullOrEmpty(pass) || string.IsNullOrEmpty(confirm))
{
    txtCustName.Visible = true;
    txtEmail.Visible = true;
    txtPassword.Visible = true;
    txtConfirmPassword.Visible = true;
    //etc....

    ShowMessage("Fill all cradentials of customer.");
    showSignUpDialog = true;
}

in your javascript section, utilize the showSignUpDialog and existing loginClick/signupClick:

$(document).ready(function () {
    <% if (showSignUpDialog) {%>
        signupClick();
    <% } else {%>
        loginClick();
    <% } %>
});

by default the showSignUpDialog is false so it will call the loginClick() to show the login fields, which is the default behavior from your demo


问:
App not opened programmatically?
I installed Meeseva app on my device. When I try to open it programmatically it's not opening.

```<code>if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"Meeseva App://location?id=1"]]) {
    NSString *mystr=[[NSString alloc] initWithFormat:@"Meeseva App://location?id=1"];
    NSURL *myurl=[[NSURL alloc] initWithString:mystr];
    [[UIApplication sharedApplication] openURL:myurl];
}
</code>```

When I opened fb, twitter, google+ and etc... all are opening successfully.
Can any solve this this issue?

App link is
https://itunes.apple.com/in/app/meeseva-app/id1121539928?mt=8

Is there any another way to open installed app programatically?

答:
You need to find out what the correct URL scheme of the Meeseva App is. Meeseva App:// does not seem to be a valid URL scheme as it has a space in the middle.

For example the Google Maps URL scheme is comgooglemaps://, not Google Maps://

Usually developers make their URL scheme public in their documentation. However this is a feature that needs to be implemented and apps don't support this "out of the box". If the developer did not implement this, the app can't be opened via link.

Alternatively it is possible that the app reacts on "universal links". That means if there is a website for the app, iOS might ask you whether to open that website in the app or in Safari. In that case you could simply link to the website and let the user decide how the link should be opened. However, again, this needs to be implemented by the developer. If the app does not support universal links either, there's no way for you to open the app at all.

Title: App not opened programmatically?

Body:
I installed Meeseva app on my device. When I try to open it programmatically it's not opening.

if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"Meeseva App://location?id=1"]]) {
    NSString *mystr=[[NSString alloc] initWithFormat:@"Meeseva App://location?id=1"];
    NSURL *myurl=[[NSURL alloc] initWithString:mystr];
    [[UIApplication sharedApplication] openURL:myurl];
}

When I opened fb, twitter, google+ and etc... all are opening successfully.
Can any solve this this issue?

App link is
https://itunes.apple.com/in/app/meeseva-app/id1121539928?mt=8

Is there any another way to open installed app programatically?


问:
How to download an table using rhandsontable in rshiny?
I have written the following server code to display the content. How to download the file after I edit the hands-on table </p>

```<code>#server
 value <- eventReactive(input$file, {
   theFile <- input$file
   if(is.null(theFile)) {
    return(NULL)}
 file.rename(theFile$datapath,paste(theFile$datapath, ".xlsx", sep=""))
 Data <- read_excel(paste(theFile$datapath, ".xlsx", sep = ""), 1)
 Data
})

output$contents <- renderRHandsontable({
  rhandsontable(value())
 })
</code>```

答:
I would add an actionButton in ui.R and use it to save the file.

actionButton in ui.R:

```<code>actionButton("savefile", "Save", width = '100%')
</code>```

To save the file, in server.R:

```<code>observeEvent(input$savefile,
                {

                   if (!is.null(isolate(input$contents)))
                   {
                       #Convert to R object
                       x <- hot_to_r(isolate(input$contents))
                       write.table(x, file = 'employee_input.txt', row.names=FALSE, quote = TRUE, sep = ",",
                       na = "NA", dec = ".")
                   }
                }
            )
</code>```

Body:
I have written the following server code to display the content. How to download the file after I edit the hands-on table

#server
 value <- eventReactive(input$file, {
   theFile <- input$file
   if(is.null(theFile)) {
    return(NULL)}
 file.rename(theFile$datapath,paste(theFile$datapath, ".xlsx", sep=""))
 Data <- read_excel(paste(theFile$datapath, ".xlsx", sep = ""), 1)
 Data
})

output$contents <- renderRHandsontable({
  rhandsontable(value())
 })

Body:
I would add an actionButton in ui.R and use it to save the file.

actionButton in ui.R:

actionButton("savefile", "Save", width = '100%')

To save the file, in server.R:

observeEvent(input$savefile,
                {

                   if (!is.null(isolate(input$contents)))
                   {
                       #Convert to R object
                       x <- hot_to_r(isolate(input$contents))
                       write.table(x, file = 'employee_input.txt', row.names=FALSE, quote = TRUE, sep = ",",
                       na = "NA", dec = ".")
                   }
                }
            )


问:
How do I write a JUnit test to consume a PagedResources<T> in Spring Boot?
In this example I face a problem to write a junit test, which consumes a HAL-formatted rest-service. As I understand I can use MockRestServiceServer to fake a communication. You can find here two simple spring applications; one which provides a HAL-formatted rest-service and one which consumes it. Everything works fine, when both services are started up.

So, when you start both services with the command mvn spring-boot:run and you navigate to http://localhost:8080/products/list, then you can see the consumed rest-service.

The consumer itself uses a modified RestTemplate to request a response entity from the type PagedResources. My consumer-test defines a response body, which looks exactly similar to a normal request from the "provider" service.

My Test

```<code>package consumer;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.util.AssertionErrors.assertEquals;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

import consumer.model.Product;
import consumer.service.ProductServiceImpl;
import consumer.service.util.CustomRestTemplate;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ConsumerApplication.class)
@WebAppConfiguration
@IntegrationTest
public class ConsumerApplicationTests {
    private MockRestServiceServer mockServer;
    private RestTemplate restTemplate;

    @Mock
    private CustomRestTemplate customRestTemplate;

    @InjectMocks
    private ProductServiceImpl productServiceImpl;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        this.restTemplate = new RestTemplate();
        this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
        String responseBody = "\"_links\" : {    \"self\" : {      \"href\" : \"http://localhost:1234/products/list\"    }  },  \"_embedded\" : {    \"products\" : [ {      \"name\" : \"Product 1\",      \"price\" : 0.99,      \"_links\" : {        \"self\" : {          \"href\" : \"http://localhost:1234/v1/products/list/product/1\"        }      }    }]  }}";
        this.mockServer.expect(requestTo("http://localhost:1234/products?size=" + Integer.MAX_VALUE)).andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess(responseBody, MediaType.parseMediaTypes("application/hal+json").get(0)));
    }

    @Test
    public void contextLoads() {
        when(customRestTemplate.getRestTemplateJackson2HttpMessageConverter()).thenReturn(restTemplate);

        List<Product> productList = productServiceImpl.retrieveAllProduct();
        assertEquals("Expected one product", 1, productList.size());
        mockServer.verify();
    }

}
</code>```

When I execute the test I receive that error:

```<code>org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:572)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:476)
at consumer.service.ProductServiceImpl.retrieveAllProduct(ProductServiceImpl.java:35)
at consumer.ConsumerApplicationTests.contextLoads(ConsumerApplicationTests.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:770)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:277)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:289)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1141)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:135)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2221)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:205)
... 39 more
</code>```

If I am not completely wrong, the error occurrs because PagedResources does not have a String constructor. So what would be the best solution to test that code?

Thank you in advance!

答:
Check this answer. It was very useful for me. Basically, what you have todo is to remove the PagedResourcesAssembler parameter from the Controller. And build it into the method.</p>

```<code>@RequestMapping(method=RequestMethod.GET)
public ResponseEntity<PagedResources<AccountResource>> getAccounts(
        @RequestParam(value="name", required = false) String name,
        @RequestParam(value="username", required = false) String username,
        @RequestParam(value="email", required = false) String email,
        @RequestParam(value="lastName", required = false) String lastName,
        @RequestParam(value="size", required = true, defaultValue = "10") Integer size,
        @RequestParam(value="page", required = true, defaultValue = "0") int page,
        @RequestParam(value="sort", required = false, defaultValue = "username") String sort,
        @RequestParam(value="direction", required = false, defaultValue = "asc") String direction,
        UriComponentsBuilder uriBuilder,
        HttpServletRequest request,
        HttpServletResponse response) {

    // Build page request
    AccountList list = null;
    Page<Account> resultPage = null;
    Direction sortDirection = Direction.ASC;
    if(direction.equals("desc")) {
        sortDirection = Direction.DESC;
    }
    PageRequest pReq = new PageRequest(page, size, sortDirection, sort);

    resultPage = accountService.findAll(pReq);

    HateoasPageableHandlerMethodArgumentResolver resolver = new HateoasPageableHandlerMethodArgumentResolver();
    PagedResourcesAssembler<Account> accountPageAssembler = new PagedResourcesAssembler<Account>(resolver, null);
    return new ResponseEntity<PagedResources<AccountResource>>(accountPageAssembler.toResource(resultPage, new AccountResourceAsm()), HttpStatus.OK);
}
</code>```

Body:
In this example I face a problem to write a junit test, which consumes a HAL-formatted rest-service. As I understand I can use MockRestServiceServer to fake a communication. You can find here two simple spring applications; one which provides a HAL-formatted rest-service and one which consumes it. Everything works fine, when both services are started up.

So, when you start both services with the command mvn spring-boot:run and you navigate to http://localhost:8080/products/list, then you can see the consumed rest-service.

The consumer itself uses a modified RestTemplate to request a response entity from the type PagedResources. My consumer-test defines a response body, which looks exactly similar to a normal request from the "provider" service.

My Test

package consumer;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.method;
import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo;
import static org.springframework.test.web.client.response.MockRestResponseCreators.withSuccess;
import static org.springframework.test.util.AssertionErrors.assertEquals;

import java.util.List;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.client.MockRestServiceServer;
import org.springframework.web.client.RestTemplate;

import consumer.model.Product;
import consumer.service.ProductServiceImpl;
import consumer.service.util.CustomRestTemplate;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ConsumerApplication.class)
@WebAppConfiguration
@IntegrationTest
public class ConsumerApplicationTests {
    private MockRestServiceServer mockServer;
    private RestTemplate restTemplate;

    @Mock
    private CustomRestTemplate customRestTemplate;

    @InjectMocks
    private ProductServiceImpl productServiceImpl;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        this.restTemplate = new RestTemplate();
        this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
        String responseBody = "\"_links\" : {    \"self\" : {      \"href\" : \"http://localhost:1234/products/list\"    }  },  \"_embedded\" : {    \"products\" : [ {      \"name\" : \"Product 1\",      \"price\" : 0.99,      \"_links\" : {        \"self\" : {          \"href\" : \"http://localhost:1234/v1/products/list/product/1\"        }      }    }]  }}";
        this.mockServer.expect(requestTo("http://localhost:1234/products?size=" + Integer.MAX_VALUE)).andExpect(method(HttpMethod.GET))
        .andRespond(withSuccess(responseBody, MediaType.parseMediaTypes("application/hal+json").get(0)));
    }

    @Test
    public void contextLoads() {
        when(customRestTemplate.getRestTemplateJackson2HttpMessageConverter()).thenReturn(restTemplate);

        List<Product> productList = productServiceImpl.retrieveAllProduct();
        assertEquals("Expected one product", 1, productList.size());
        mockServer.verify();
    }

}

When I execute the test I receive that error:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:208)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.read(AbstractJackson2HttpMessageConverter.java:200)
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:97)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:809)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:793)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:572)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:530)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:476)
at consumer.service.ProductServiceImpl.retrieveAllProduct(ProductServiceImpl.java:35)
at consumer.ConsumerApplicationTests.contextLoads(ConsumerApplicationTests.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:73)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:224)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [simple type, class org.springframework.hateoas.PagedResources<consumer.model.Product>] from String value ('_links'); no single-String constructor/factory method
at [Source: java.io.ByteArrayInputStream@1966492; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:770)
at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:277)
at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:289)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1141)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:135)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:126)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2221)
at org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.readJavaType(AbstractJackson2HttpMessageConverter.java:205)
... 39 more

If I am not completely wrong, the error occurrs because PagedResources does not have a String constructor. So what would be the best solution to test that code?

Thank you in advance!

Body:
Check this answer. It was very useful for me. Basically, what you have todo is to remove the PagedResourcesAssembler parameter from the Controller. And build it into the method.

@RequestMapping(method=RequestMethod.GET)
public ResponseEntity<PagedResources<AccountResource>> getAccounts(
        @RequestParam(value="name", required = false) String name,
        @RequestParam(value="username", required = false) String username,
        @RequestParam(value="email", required = false) String email,
        @RequestParam(value="lastName", required = false) String lastName,
        @RequestParam(value="size", required = true, defaultValue = "10") Integer size,
        @RequestParam(value="page", required = true, defaultValue = "0") int page,
        @RequestParam(value="sort", required = false, defaultValue = "username") String sort,
        @RequestParam(value="direction", required = false, defaultValue = "asc") String direction,
        UriComponentsBuilder uriBuilder,
        HttpServletRequest request,
        HttpServletResponse response) {

    // Build page request
    AccountList list = null;
    Page<Account> resultPage = null;
    Direction sortDirection = Direction.ASC;
    if(direction.equals("desc")) {
        sortDirection = Direction.DESC;
    }
    PageRequest pReq = new PageRequest(page, size, sortDirection, sort);

    resultPage = accountService.findAll(pReq);

    HateoasPageableHandlerMethodArgumentResolver resolver = new HateoasPageableHandlerMethodArgumentResolver();
    PagedResourcesAssembler<Account> accountPageAssembler = new PagedResourcesAssembler<Account>(resolver, null);
    return new ResponseEntity<PagedResources<AccountResource>>(accountPageAssembler.toResource(resultPage, new AccountResourceAsm()), HttpStatus.OK);
}


问:
Get depth value in JOGL
First of all, I'm new on coding 3D-Graphics, and I hope this isn't a too stupid question.

I need to draw a depth map on a simple shape with JOGL. To draw this shape, I have followed this tutorial here:

https://www.tutorialspoint.com/jogl/jogl_3d_triangle.htm

Now I want to display the colours on this shape according on the distance of each fragment to the focus point, pretty much on what is shown here:
https://learnopengl.com/#!Advanced-OpenGL/Depth-testing
section Visualizing the depth buffer.

While there they just use the gl_FragCoord.z value, I somehow fail to find the equivalent in JOGL.

Does someone know how to access this value? Or maybe I have to use some other approach?

Thankyou very much in advance for your help.

答: Because it's GLSL keyword. You must to write your own shader for using this value.</p>

Title: Get depth value in JOGL


答:
Write as toString() method in your Song class

```<code>public String toString()
{
   return artist + " " + album + " " + year;
}
</code>```

then call the method toString().Example System.out.println(MyList.toString())

Title: Printing an Array List full of a new type of object

Body:
I am working on a Java program, where I have an ArrayList called "CD" and inside this CD there are "Songs", and each song is an object in my Song class, and it has the arguments: String artist, String album, and int year. Any general suggestions about how to print this such that it also prints the contents of each song?

P.S. I know there are similar questions on here but I am still having trouble getting it to print exactly what I am wanting it to, and I have tried using iterator.

Thanks for all help in advance!

Body:
Write as toString() method in your Song class

public String toString()
{
   return artist + " " + album + " " + year;
}

then call the method toString().Example System.out.println(MyList.toString())


问:
Alter PHP Array
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

```<code>$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];
</code>```

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

```<code>$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];
</code>```

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

```<code>foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}
</code>```

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

答:
I achieved this by removing the row if it satisfies the logic.

Mutative, but satisfies the requirement correctly.

Tested, works properly.

check out https://eval.in/912439 for the snippet and output

Code

```<code>$directories = array_flip($directories);

foreach ($directories as $dir => $key) {
  $parent_dir = preg_match('/(.*)\//', $dir, $match);
  if (isset($match[1])) {
    unset($directories[$match[1]]);
  }
}

$directories = array_keys($directories);
</code>```

Title: Alter PHP Array

Body:
I'm need an array of all the folders in a directory, im using laravel to get an array of folders in the directory using the below code.

Storage::allDirectories('/public');

this returns an array like below.

$directories = [
    "Gallery",
    "Images",
    "Images/Proof",
    "Images/Proof/Another",
];

I need a way to remove duplicate parent directories, so for example Images will be remove if Images/Proof/Another exists or something like that, i just need to build an array of a directory and its subfolders as one array, if that makes sense.

so for example:

$directories = [
    ["Gallery"],
    ["Images/Proof/Another"],
];

Or something like this, I can't think of a way to get this to work.

I'm building a custom media manager component if anyone was wondering, some exist but i have no control over them so i built my own.

all help is appreciated.

Can you post the code you have tried so far

For 1 i can't get my head around the logic, thats why im asking what i've done "Which i dont see how it would help at all"

foreach (Storage::allDirectories('/public') as $folder)
{
    $all_folders[] = $exploded('/',$folder);
}

Im trying to separate the array into smaller arrays and check each exploded bit against another. But this has me running in circles.

Body:
I achieved this by removing the row if it satisfies the logic.

Mutative, but satisfies the requirement correctly.

Tested, works properly.

check out https://eval.in/912439 for the snippet and output

Code

$directories = array_flip($directories);

foreach ($directories as $dir => $key) {
  $parent_dir = preg_match('/(.*)\//', $dir, $match);
  if (isset($match[1])) {
    unset($directories[$match[1]]);
  }
}

$directories = array_keys($directories);


问:
d3 js bar chart not working in mozilla firefox
I have implemented a d3 js bar chart with reference to the following jsfiddle link.It working fine with chrome.In firefox web browser  tags are hidden.</p>

```<code><body>   <h1>D3.js Bar Chart Demo</h1>   <p>
    Click on the bar to delete it.   </p>   <div>
    <button onclick="changeData()">New</button>
    <button onclick="appendData()">Append</button>
    <button onclick="sortData()">Sort</button>   </div>   <svg id="chart"></svg>   <p>
    Click on the bar to delete it.   </p>   <div>
    <button onclick="changeData()">New</button>
    <button onclick="appendData()">Append</button>
    <button onclick="sortData()">Sort</button>   </div>   <div class="trans-fore">
    <div id="tooltip"></div>   </div> </body>
</code>```

答:
The problem is about the clipPath element. Chrome is quite permissive about element declaration but not Firefox.
To get your fiddle working, change:

```<code>svg.append('clippath')
  .attr('id', 'chart-area')
  .append('rect')
  .attr({
  x: Chart.margin.left + Chart.sideWidth,
  y: Chart.margin.top,
  width: BarArea.width,
  height: BarArea.height,
});
</code>```

To:

```<code>svg.append('defs').append('clipPath')
  .attr('id', 'chart-area')
  .append('rect')
  .attr({
  x: Chart.margin.left + Chart.sideWidth,
  y: Chart.margin.top,
  width: BarArea.width,
  height: BarArea.height,
});
</code>```

Here is the working fiddle.

Body:
I have implemented a d3 js bar chart with reference to the following jsfiddle link.It working fine with chrome.In firefox web browser  tags are hidden.

D3.js Bar Chart Demo

    Click on the bar to delete it.

    <button onclick="changeData()">New</button>
    <button onclick="appendData()">Append</button>
    <button onclick="sortData()">Sort</button>
   <svg id="chart"></svg>

    Click on the bar to delete it.

    <button onclick="changeData()">New</button>
    <button onclick="appendData()">Append</button>
    <button onclick="sortData()">Sort</button>

Body:
The problem is about the clipPath element. Chrome is quite permissive about element declaration but not Firefox.
To get your fiddle working, change:

svg.append('clippath')
  .attr('id', 'chart-area')
  .append('rect')
  .attr({
  x: Chart.margin.left + Chart.sideWidth,
  y: Chart.margin.top,
  width: BarArea.width,
  height: BarArea.height,
});

To:

svg.append('defs').append('clipPath')
  .attr('id', 'chart-area')
  .append('rect')
  .attr({
  x: Chart.margin.left + Chart.sideWidth,
  y: Chart.margin.top,
  width: BarArea.width,
  height: BarArea.height,
});

Here is the working fiddle.