问:
ReferenceError: monaco is not defined
I am trying to use the microsoft monaco editor with angular 2. My component is

```<code>declare const monaco: any;
declare const require: any;

export class MonacoEditorComponent implements AfterViewInit {
   ngAfterViewInit() {

        let onGotAmdLoader = () => {
            // Load monaco
            (<any>window).require(["vs/editor/editor.main"], () => {

                this.initMonaco();
            });
        };

        // Load AMD loader if necessary
        if (!(<any>window).require) {
            let loaderScript = document.createElement("script");
            loaderScript.type = "text/javascript";
            loaderScript.src = "vs/loader.js";
            loaderScript.addEventListener("load", onGotAmdLoader);
            document.body.appendChild(loaderScript);
        } else {
            onGotAmdLoader();
        }
    }

    initMonaco() {
        let myDiv: HTMLDivElement = this.editorContent.nativeElement;
        let options = this.options;
        options.value = this._value;
        options.language = this.language;
        this._editor = monaco.editor.create(myDiv, options);
   }
}
</code>```

So basically, I am trying to load the monaco first by checking the if condition on the window.require, once the monaco's main editor.main file is loaded I am trying to create a editor using monaco.editor.create(). But even after loading editor.main.js it is unable to resolve the monaco. I tried to debug and see the value of monaco in initMonaco function, it is showing as not available. Am I doing something wrong?

Note: vs is already resolved to the monaco-editor/min/vs already, and it is able to load the js file to browser also. Also, all variables used like options and _value are declared in the component(I removed them from here).

答: If someone else is also looking for this, I was able to solve the problem, Actually the problem is monaco will load only with it's own loader, we are using systemjs loader in our project. When we tried with the loader provided by monaco loader it worked fine. The difference is monaco loader is adding some extra functions like config to the loader, which are not available in the systemjs loader.</p>

Title: ReferenceError: monaco is not defined

Body:
I am trying to use the microsoft monaco editor with angular 2. My component is

declare const monaco: any;
declare const require: any;

export class MonacoEditorComponent implements AfterViewInit {
   ngAfterViewInit() {

        let onGotAmdLoader = () => {
            // Load monaco
            (<any>window).require(["vs/editor/editor.main"], () => {

                this.initMonaco();
            });
        };

        // Load AMD loader if necessary
        if (!(<any>window).require) {
            let loaderScript = document.createElement("script");
            loaderScript.type = "text/javascript";
            loaderScript.src = "vs/loader.js";
            loaderScript.addEventListener("load", onGotAmdLoader);
            document.body.appendChild(loaderScript);
        } else {
            onGotAmdLoader();
        }
    }

    initMonaco() {
        let myDiv: HTMLDivElement = this.editorContent.nativeElement;
        let options = this.options;
        options.value = this._value;
        options.language = this.language;
        this._editor = monaco.editor.create(myDiv, options);
   }
}

So basically, I am trying to load the monaco first by checking the if condition on the window.require, once the monaco's main editor.main file is loaded I am trying to create a editor using monaco.editor.create(). But even after loading editor.main.js it is unable to resolve the monaco. I tried to debug and see the value of monaco in initMonaco function, it is showing as not available. Am I doing something wrong?

Note: vs is already resolved to the monaco-editor/min/vs already, and it is able to load the js file to browser also. Also, all variables used like options and _value are declared in the component(I removed them from here).


来源: stackexchange

问:
The sum seems to be 40 but how
I am trying to explore php and to learn it a little bit but when i tried this

```<code>    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";
</code>```

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.

ContentLicense: CC BY-SA 3.0

Title: The sum seems to be 40 but how

Body:
I am trying to explore php and to learn it a little bit but when i tried this

    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.

Body:
This is simple math, the php code does exactly what it looks like it does. Am I missing something?

loop 1:

    $i = 1
    $s = 0 + (2*1 + 5) = 7

loop 2:

    $i = 2
    $s = 7 + (2*2 + 5) = 7 + 4 + 5 = 16

loop 3:

    $i = 3
    $s = 16 + (2*3 + 5) = 16 + 6 + 5 = 27

loop 4:

    $i = 4
    $s = 27 + (2*4 + 5) = 27 + 8 + 5 = 40


答:
its very simple, since i<=($n+2) the total iterations will be 4.
for first iteration,

```<code>$i=1 the value of s = 0+(2*1+5) = 7
$i=2 now s = 7+(2*2+5) = 16
$i=3 now s = 16+(2*3+5) = 27
$i=4 now s = 27+(2*4+5) = 40
</code>```

Hope this explains.

Title: The sum seems to be 40 but how

Body:
its very simple, since i<=($n+2) the total iterations will be 4.
for first iteration,

$i=1 the value of s = 0+(2*1+5) = 7
$i=2 now s = 7+(2*2+5) = 16
$i=3 now s = 16+(2*3+5) = 27
$i=4 now s = 27+(2*4+5) = 40

Hope this explains.


问:
Anyobject is not a subtype of NSLayoutConstraint
I am upgrading to Swift3, below code was working fine in Swift 2.3 but it is not working with Swift 3

```<code>    let constraints: NSArray = contentView.constraints as NSArray
    let indexOfConstraint = constraints.indexOfObject (passingTest: { (constraint, idx, stop) in
        return ((constraint as AnyObject).firstItem as! UIView).tag == bubbleTag && (constraint.firstAttribute == NSLayoutAttribute.left || constraint.firstAttribute == NSLayoutAttribute.right)
    })
</code>```

I am getting following compiler error:

```<code>'(AnyObject)' is not a subtype of 'NSLayoutConstraint'
</code>```

How can I fix this?

答:
I think you might need something like this...</p>

```<code>contentView.constraints.index(where: { constraint in
    guard let firstItemView = constraint.firstItem as? UIView else {
        return false
    }

    return firstItemView.tag == bubbleTag && (constraint.firstAttribute == .left || constraint.firstAttribute == .right)
})
</code>```

Body:
I am upgrading to Swift3, below code was working fine in Swift 2.3 but it is not working with Swift 3

    let constraints: NSArray = contentView.constraints as NSArray
    let indexOfConstraint = constraints.indexOfObject (passingTest: { (constraint, idx, stop) in
        return ((constraint as AnyObject).firstItem as! UIView).tag == bubbleTag && (constraint.firstAttribute == NSLayoutAttribute.left || constraint.firstAttribute == NSLayoutAttribute.right)
    })

I am getting following compiler error:

'(AnyObject)' is not a subtype of 'NSLayoutConstraint'

How can I fix this?

Body:
I think you might need something like this...

contentView.constraints.index(where: { constraint in
    guard let firstItemView = constraint.firstItem as? UIView else {
        return false
    }

    return firstItemView.tag == bubbleTag && (constraint.firstAttribute == .left || constraint.firstAttribute == .right)
})


问:
In git or git-svn, how do I modify history to only contain files which exist on my current HEAD?
Five years ago Niklas asked this quite similar question - I'll give it another try with different wording.

I want to migrate an existing Subversion repository to git and use the chance to get rid of all history that doesn't affect my current trunk/master HEAD before I share it with my colleagues (all other history should stay intact of course).

My idea was to first git svn clone the repository (without the branches intentionally):

```<code>git svn clone http://my/old/svn/repo/trunk new-git-repo
</code>```

.. and then to remove all files I don't need any more with some magic like this:

```<code>for f in $(all_deleted_files)
do
    git filter-branch --tree-filter 'rm -f ${f}' HEAD
done
</code>```

Of course the big question is now: how do I get all_deleted_files?

I could write a nice Python script and collect all files in all commits and subtract those which still exist on HEAD. But is this the only possible way?

Has someone done this before and wants to impress me with his/her script?

With a different (Subversion specific) approach - might it possible to not clone files which later got deleted anyway in the first place?

答:
I don't think someone (or many) did this before as it doesn't make too much sense for most repos. Usually different files in the same repo form one unit, so leaving out the history of later deleted files corrupts the whole history for most repos. And if some file was renamed, you will also loose the history before the renaming.

If you anyway really want to do this, something like the following should do:

```<code>git filter-branch --prune-empty --tag-filter cat --tree-filter 'files="$(git diff master --no-renames --diff-filter ACMRTUXB --name-only)" && if [ -n "$files" ]; then rm -f $files; fi' master
</code>```

Body:
Five years ago Niklas asked this quite similar question - I'll give it another try with different wording.

I want to migrate an existing Subversion repository to git and use the chance to get rid of all history that doesn't affect my current trunk/master HEAD before I share it with my colleagues (all other history should stay intact of course).

My idea was to first git svn clone the repository (without the branches intentionally):

git svn clone http://my/old/svn/repo/trunk new-git-repo

.. and then to remove all files I don't need any more with some magic like this:

for f in $(all_deleted_files)
do
    git filter-branch --tree-filter 'rm -f ${f}' HEAD
done

Of course the big question is now: how do I get all_deleted_files?

I could write a nice Python script and collect all files in all commits and subtract those which still exist on HEAD. But is this the only possible way?

Has someone done this before and wants to impress me with his/her script?

With a different (Subversion specific) approach - might it possible to not clone files which later got deleted anyway in the first place?

Body:
I don't think someone (or many) did this before as it doesn't make too much sense for most repos. Usually different files in the same repo form one unit, so leaving out the history of later deleted files corrupts the whole history for most repos. And if some file was renamed, you will also loose the history before the renaming.

If you anyway really want to do this, something like the following should do:

git filter-branch --prune-empty --tag-filter cat --tree-filter 'files="$(git diff master --no-renames --diff-filter ACMRTUXB --name-only)" && if [ -n "$files" ]; then rm -f $files; fi' master


问:
How to read a string backwards in SQL ? (not REVERSE)
So I have these two strings.

```<code>@a =  SALE:1:39
@b =  SALE:12
</code>```

I have to compare both the string.
Comparison on:

```<code>LEFT part of @a = SALE:1
RIGHT Part of @a = 39

LEFT part of @b = SALE
RIGHT Part of @b = 12
</code>```

What I have done so far is

```<code>RIGHT(@a, CHARINDEX(':', REVERSE(@a))-1)<br>
RIGHT(@b, CHARINDEX(':', REVERSE(@b))-1)<br>
LEFT(@a, CHARINDEX(':', @a)-1)<br>
LEFT(@b, CHARINDEX(':',@b)-1).<br>
</code>```

RESULT

39 <-- LEFT @a

12 <-- LEFT @b

SALE <-- RIGHT @a, which should be SALE:1

SALE <-- RIGHT @b

SALE:1:39

SALE:12

I want to split the string on the last occurrence of :

How to achieve that in MS SQL Server?

So basically what I am trying to achieve here is, I want to compare these two strings.

```<code>IF @a AND @b are non-numeric<br> THEN IF @a AND @b LIKE '%:%'
IF So Then is the left part of @a = left part of @b
IF YES Then is the Right part of @b = Right part of @a + 1
</code>```

答:
```<code>declare @a varchar (100) = 'SALE:1:39'
, @b varchar(100) = 'SALE:12'

select
LEFT(@a, len(@a) - charindex(':', REVERSE(@a))) LeftFromA
, RIGHT(@a, case when charindex(':', REVERSE(@a)) - 1 < 0 then 0 else charindex(':', REVERSE(@a)) - 1 end) RightFromA
, LEFT(@b, len(@b) - charindex(':', REVERSE(@b))) LeftFromB
, RIGHT(@b, case when charindex(':', REVERSE(@b)) - 1 < 0 then 0 else charindex(':', REVERSE(@b)) - 1 end) RightFromB
</code>```

Body:
So I have these two strings.

@a =  SALE:1:39
@b =  SALE:12

I have to compare both the string.
Comparison on:

LEFT part of @a = SALE:1
RIGHT Part of @a = 39

LEFT part of @b = SALE
RIGHT Part of @b = 12

What I have done so far is

RIGHT(@a, CHARINDEX(':', REVERSE(@a))-1)

RIGHT(@b, CHARINDEX(':', REVERSE(@b))-1)

LEFT(@a, CHARINDEX(':', @a)-1)

LEFT(@b, CHARINDEX(':',@b)-1).

RESULT

39 <-- LEFT @a

12 <-- LEFT @b

SALE <-- RIGHT @a, which should be SALE:1

SALE <-- RIGHT @b

SALE:1:39

SALE:12

I want to split the string on the last occurrence of :

How to achieve that in MS SQL Server?

So basically what I am trying to achieve here is, I want to compare these two strings.

IF @a AND @b are non-numeric
 THEN IF @a AND @b LIKE '%:%'
IF So Then is the left part of @a = left part of @b
IF YES Then is the Right part of @b = Right part of @a + 1


问:
google analytics embed API without google login to google analytics account
I am trying to implement 'Google Analytics' where the resulted data should be imported into my site as a separate page.

When I use embed API, it asks for google analytics login before displaying the analytics data in the form of charts.. etc.

How to bypass the external google login for google analytics embed api.

We're using Angular JS to consume embed api.

答:
You can't do that. The embed API requires that you have access to the data in order to view it.

If you want to have a dashboard publicly available of your data the best course of action is to:

Query your data server side and store it in a database

Query the database and query your database on page load and draw the charts.

This way you protect your google credentials doing the query server-side and also cache the data for faster retrieval when serving your pages and also to avoid hitting api limits.

Another option is to take a look at SuperProxy. Which is an AppEngine Application you can deploy and does exactly the same job I described above.


问:
Using custom Model in Umbraco - error?
I am getting the following error, when using my Custom model in Umbraco:

```<code>Cannot bind source type Umbraco.Web.Models.RenderModel to model type MyParser.Model.MyModel.
</code>```

The code, which contains this model, is an old project i am 'importing' into a Umbraco site - it used to be just a vanilla MVC app.

For my use, it does not need to interact with Umbraco or the database - it just needs to live in the same project.

The layout, calling the model, looks like this;

```<code>@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyParser.Model.MyModel>
@{
    Layout = null;
}
</code>```

The Model looks like this

```<code>namespace MyParser.Model
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}
</code>```

The code works fine in the vanilla MVC app, but needs to be modified to run inside an Umbraco-app it would seem - but how?
It is Umbraco 7.6

答:
If it is a document type template, you need to hijack the route to inject the view model. You create the controller that inherits from RenderMvcController and override Index method.

```<code>namespace Controllers
{
    public class [YourDocTypeAlias]Controller : RenderMvcController
    {
        public override ActionResult Index(RenderModel model)
        {
            var vm = new ViewModel<MyModel>(model);
            return View(vm);
        }
    }

    public class ViewModel<TModel> : RenderModel
    {
        public ViewModel(RenderModel model) : base(model.Content, model.CurrentCulture) { }

        public TModel CustomModel { get; set; }
    }

    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}
</code>```

and your template now becomes.

```<code>@inherits Umbraco.Web.Mvc.UmbracoViewPage<ViewModel<MyModel>>
@{
    Layout = "Master.cshtml";
    //you can now access properties from MyModel like Model.CustomModel.IsValid...
}
</code>```

More info can be found on this link.

Title: Using custom Model in Umbraco - error?

Body:
I am getting the following error, when using my Custom model in Umbraco:

Cannot bind source type Umbraco.Web.Models.RenderModel to model type MyParser.Model.MyModel.

The code, which contains this model, is an old project i am 'importing' into a Umbraco site - it used to be just a vanilla MVC app.

For my use, it does not need to interact with Umbraco or the database - it just needs to live in the same project.

The layout, calling the model, looks like this;

@inherits Umbraco.Web.Mvc.UmbracoViewPage<MyParser.Model.MyModel>
@{
    Layout = null;
}

The Model looks like this

namespace MyParser.Model
{
    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}

The code works fine in the vanilla MVC app, but needs to be modified to run inside an Umbraco-app it would seem - but how?
It is Umbraco 7.6

Body:
If it is a document type template, you need to hijack the route to inject the view model. You create the controller that inherits from RenderMvcController and override Index method.

namespace Controllers
{
    public class [YourDocTypeAlias]Controller : RenderMvcController
    {
        public override ActionResult Index(RenderModel model)
        {
            var vm = new ViewModel<MyModel>(model);
            return View(vm);
        }
    }

    public class ViewModel<TModel> : RenderModel
    {
        public ViewModel(RenderModel model) : base(model.Content, model.CurrentCulture) { }

        public TModel CustomModel { get; set; }
    }

    public class MyModel
    {
        public string Name { get; set; }
        public string Value1 { get; set; }
        public bool IsValid { get; set; }
    }
}

and your template now becomes.

@inherits Umbraco.Web.Mvc.UmbracoViewPage<ViewModel<MyModel>>
@{
    Layout = "Master.cshtml";
    //you can now access properties from MyModel like Model.CustomModel.IsValid...
}

More info can be found on this link.


问:
Pandas pivot_table group column by values
I am trying to use numeric values as columns on a Pandas pivot_table. The problem is that since each number is mostly unique, the resulting pivot_table isn't very useful as a way to aggregate my data.

Here is what I have so far (fake data example):

```<code>import pandas as pd

df = pd.DataFrame({'Country': ['US', 'Brazil', 'France', 'Germany'],
                       'Continent': ['Americas', 'Americas', 'Europe', 'Europe'],
                       'Population': [321, 207, 80, 66]})

pd.pivot_table(df, index='Continent', columns='Population', aggfunc='count')
</code>```

Here is an image of the resulting
.

How could I group my values into ranges based on my columns?

In other words, how can I count all countries with Population... <100, 100-200, >300?

答:
Use pd.cut:

```<code>df = df.assign(PopGroup=pd.cut(df.Population,bins=[0,100,200,300,np.inf],labels=['<100','100-200','200-300','>300']))
</code>```

Output:

```<code>  Continent  Country  Population PopGroup
0  Americas       US         321     >300
1  Americas   Brazil         207  200-300
2    Europe   France          80     <100
3    Europe  Germany          66     <100

pd.pivot_table(df, index='Continent', columns='PopGroup',values=['Country'], aggfunc='count')
</code>```

Output:

```<code>        Country
PopGroup  200-300 <100 >300
Continent
Americas      1.0  NaN  1.0
Europe        NaN  2.0  NaN
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to use numeric values as columns on a Pandas pivot_table. The problem is that since each number is mostly unique, the resulting pivot_table isn't very useful as a way to aggregate my data.

Here is what I have so far (fake data example):

import pandas as pd

df = pd.DataFrame({'Country': ['US', 'Brazil', 'France', 'Germany'],
                       'Continent': ['Americas', 'Americas', 'Europe', 'Europe'],
                       'Population': [321, 207, 80, 66]})

pd.pivot_table(df, index='Continent', columns='Population', aggfunc='count')

Here is an image of the resulting
.

How could I group my values into ranges based on my columns?

In other words, how can I count all countries with Population... <100, 100-200, >300?

Body:
Use pd.cut:

df = df.assign(PopGroup=pd.cut(df.Population,bins=[0,100,200,300,np.inf],labels=['<100','100-200','200-300','>300']))

Output:

  Continent  Country  Population PopGroup
0  Americas       US         321     >300
1  Americas   Brazil         207  200-300
2    Europe   France          80     <100
3    Europe  Germany          66     <100

pd.pivot_table(df, index='Continent', columns='PopGroup',values=['Country'], aggfunc='count')

Output:

        Country
PopGroup  200-300 <100 >300
Continent
Americas      1.0  NaN  1.0
Europe        NaN  2.0  NaN


问:
Synchronizing a Block of Code - Exercise 13-2
In this exercise, we will attempt to synchronize a block of code. Within that block of code, we will get the lock on an object so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 A’s, 100 B’s, and 100 C’s, all in unbroken lines.

Create a class and extend the Thread class.

Override the run() method of Thread. This is where the synchronized block of code will go.

For our three thread objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.

The synchronized block of code will obtain a lock on the StringBuffer object from step 3.

Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer. You can check Chapter 5 for StringBuffer (StringBuilder) methods that will help with this.

Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.

Solution:

public class OCJPThread extends Thread{

```<code>StringBuffer sb;
public OCJPThread(StringBuffer sb) {
    this.sb =sb;
}

public void run(){
    synchronized (sb) {
        System.out.println(Thread.currentThread().getName());
        for(int i=1;i<=100;i++)
            System.out.print(sb);

        System.out.println();
        sb.setCharAt(0, (char)(sb.charAt(0)+1));

    }
}

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("A");
    OCJPThread t1 =new OCJPThread(sb);
    OCJPThread t2 =new OCJPThread(sb);
    OCJPThread t3 =new OCJPThread(sb);

    t1.start();
    t2.start();
    t3.start();
}
</code>```

}
output
Thread-0
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Thread-2
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Thread-1
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

Question : If I am using Stringbuilder or StringBuffer, it doesn't matter as I am using syncronized block.

But if I use synchronized(this) instead of stringbuffer object. Output is unpredicatable. As string buffer is already syncronized, why do we need to do it ourselves?

答:
StringBuffer is synchronized, but only on each individual method call. This means that when you are not using synchronization, the part that prints the value of the string buffer is not done within a synchronized block. One of the other threads can update the buffer during that time. When this happens, the print will show the new value. You can't really know which thread will update the buffer first.

Also, a thread may change the value between the call to sb.charAt() and the call to sb.setCharAt(). So the result of the increment itself may be unpredictable.

Note: synchronizing on this means each thread is synchronizing on a different lock, so it's like not synchronizing at all.

Body:
In this exercise, we will attempt to synchronize a block of code. Within that block of code, we will get the lock on an object so that other threads cannot modify it while the block of code is executing. We will be creating three threads that will all attempt to manipulate the same object. Each thread will output a single letter 100 times and then increment that letter by one. The object we will be using is StringBuffer. We could synchronize on a String object, but strings cannot be modified once they are created, so we would not be able to increment the letter without generating a new String object. The final output should have 100 A’s, 100 B’s, and 100 C’s, all in unbroken lines.

Create a class and extend the Thread class.

Override the run() method of Thread. This is where the synchronized block of code will go.

For our three thread objects to share the same object, we will need to create a constructor that accepts a StringBuffer object in the argument.

The synchronized block of code will obtain a lock on the StringBuffer object from step 3.

Within the block, output the StringBuffer 100 times and then increment the letter in the StringBuffer. You can check Chapter 5 for StringBuffer (StringBuilder) methods that will help with this.

Finally, in the main() method, create a single StringBuffer object using the letter A, then create three instances of our class and start all three of them.

Solution:

public class OCJPThread extends Thread{

StringBuffer sb;
public OCJPThread(StringBuffer sb) {
    this.sb =sb;
}

public void run(){
    synchronized (sb) {
        System.out.println(Thread.currentThread().getName());
        for(int i=1;i<=100;i++)
            System.out.print(sb);

        System.out.println();
        sb.setCharAt(0, (char)(sb.charAt(0)+1));

    }
}

public static void main(String[] args) {
    StringBuffer sb = new StringBuffer("A");
    OCJPThread t1 =new OCJPThread(sb);
    OCJPThread t2 =new OCJPThread(sb);
    OCJPThread t3 =new OCJPThread(sb);

    t1.start();
    t2.start();
    t3.start();
}

}
output
Thread-0
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Thread-2
BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
Thread-1
CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

Question : If I am using Stringbuilder or StringBuffer, it doesn't matter as I am using syncronized block.

But if I use synchronized(this) instead of stringbuffer object. Output is unpredicatable. As string buffer is already syncronized, why do we need to do it ourselves?


问:
Protractor Get Errors Only From Console, Ignore Warnings
I have a test which is navigating to a certain area of our application and then checking to see if there are any errors in the console when this area of the application is load.

The problem is that it is failing on a warning. Is there anyway from within my test that I can make it look just for errors and not warnings?

```<code>    it('Area of Application Loads With No Errors - Smoke', () => {
    console.log('\n ### Area of Applications Loads With No Errors ### \n')
    // Clear the Console before Navigating
    browser.manage().logs().get('browser')
    // Navigate
    common.navigationOpenByClick()
    navPage.navigateToApp(params.apps.areaOfApp.navLink)
    // Check the console for errors
    browser.manage().logs().get('browser').then(function(browserLog) {
        expect(browserLog.length).toEqual(0)
    })
})
</code>```

答:
Do you use multiCapabilities in your protractor.config file?

You can try this config below the browserName:
"loggingPrefs": {"browser": "SEVERE", "INFO", "DEBUG"},   //OFF, SEVERE, WARNING, INFO, DEBUG, ALL

Body:
I have a test which is navigating to a certain area of our application and then checking to see if there are any errors in the console when this area of the application is load.

The problem is that it is failing on a warning. Is there anyway from within my test that I can make it look just for errors and not warnings?

    it('Area of Application Loads With No Errors - Smoke', () => {
    console.log('\n ### Area of Applications Loads With No Errors ### \n')
    // Clear the Console before Navigating
    browser.manage().logs().get('browser')
    // Navigate
    common.navigationOpenByClick()
    navPage.navigateToApp(params.apps.areaOfApp.navLink)
    // Check the console for errors
    browser.manage().logs().get('browser').then(function(browserLog) {
        expect(browserLog.length).toEqual(0)
    })
})


问:
Pay for Access Areas in Wordpress
I want to build a wordpress site that shows some content to all, and then only shows the rest of the content to people who have paid either via paypal or credit card. Moreover, I want this access to happen automatically upon payment (if possible), i.e. I don't have to manually give that person access after I check to make sure they have paid.

Is there a way to do this in wordpress or would something like rails/django be more appropriate?

答: The s2member plugin will take care of this for you.</p>

ContentLicense: CC BY-SA 2.5

Title: Pay for Access Areas in Wordpress


问:
AJAX request, redirect with params
```<code> $.ajax({
               url: baseUrl,
               type: "post",
               contentType: "application/json",
               dataType: "json",
               success: function (data) {
                window.location = ('http://localhost:9000/#/home.html?' +  (data.search))
               },
               data: JSON.stringify(body),
             });
             return false;
           }
         };
</code>```

this is my ajax request, it sends as JSON and it returns an object

ie. search = {firstName: km, lastname: b}

However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?

JSON.stringify just decodes the object into

```<code>%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D
</code>```

答:
This is probably because it trying to send an object to your window.location part.
 What you probably need is this:</p>

```<code> window.location = ('http://localhost:9000/#/home.html?firstName=' +  data.search.firstName + "&lastname=" + data.search.lastname)
</code>```

Title: AJAX request, redirect with params

Body:
 $.ajax({
               url: baseUrl,
               type: "post",
               contentType: "application/json",
               dataType: "json",
               success: function (data) {
                window.location = ('http://localhost:9000/#/home.html?' +  (data.search))
               },
               data: JSON.stringify(body),
             });
             return false;
           }
         };

this is my ajax request, it sends as JSON and it returns an object

ie. search = {firstName: km, lastname: b}

However, ajax isnt setting the content type to JSON for the params in the redirect. It is still sending as an object. JSON stringify does not work. Is there a way to set the content type to JSON inside the success/redirect function?

JSON.stringify just decodes the object into

%7B%22clientName%22:%blah%22,%22em%22:%22mLigDACsBihAL2RETse06351MuCNehZQ%22,%22partnercode%22:%blah%22%7D

Body:
This is probably because it trying to send an object to your window.location part.
 What you probably need is this:

 window.location = ('http://localhost:9000/#/home.html?firstName=' +  data.search.firstName + "&lastname=" + data.search.lastname)


问:
How to make a bar chart, with x-labels and legend, directly from a table of listed data
I have a data table tb that looks something like this, which I want to turn into a bar chart.

```<code>N         X       P
________  ______  ______

0          5      15.314
0         10      36.288
0         13      7.1785
1          5      18.182
1         10      40.997
1         13      8.9741
2          5       17.65
2         10      40.095
2         13       9.276
</code>```

I want the bar chart to look something like this, but without needing to rearrange the table. What is the simplest way to do this?

Currently, my code to do it looks like this, but I expect there should be an easier way to manipulate it:

```<code>y = [tb.P(tb.X==5)' ; tb.P(tb.X==10)' ; tb.P(tb.X==13)'];
b = bar(y);
xlab = arrayfun(@num2str, Xlist, 'uniformoutput', false);
set(gca,'xticklabel',xlab);
leg = arrayfun(@num2str, Nlist, 'uniformoutput', false);;
legend(b,leg)
</code>```

What would be the proper method for doing this?

答:
I don't know if it's more simple for you, but you can also do this:

```<code>dat = sortrows(tb,[2 1]);
y = reshape(dat.P,numel(unique(dat.X)),[]).';
b = bar(y);
set(gca,'xticklabel',unique(dat.X));
legend(b,num2str(unique(dat.N)))
</code>```

And if you have Matlab 2017a you can also use this example with categorical data, to set x-axis values from the call to bar.

Body:
I have a data table tb that looks something like this, which I want to turn into a bar chart.

N         X       P
________  ______  ______

0          5      15.314
0         10      36.288
0         13      7.1785
1          5      18.182
1         10      40.997
1         13      8.9741
2          5       17.65
2         10      40.095
2         13       9.276

I want the bar chart to look something like this, but without needing to rearrange the table. What is the simplest way to do this?

Currently, my code to do it looks like this, but I expect there should be an easier way to manipulate it:

y = [tb.P(tb.X==5)' ; tb.P(tb.X==10)' ; tb.P(tb.X==13)'];
b = bar(y);
xlab = arrayfun(@num2str, Xlist, 'uniformoutput', false);
set(gca,'xticklabel',xlab);
leg = arrayfun(@num2str, Nlist, 'uniformoutput', false);;
legend(b,leg)

What would be the proper method for doing this?

Body:
I don't know if it's more simple for you, but you can also do this:

dat = sortrows(tb,[2 1]);
y = reshape(dat.P,numel(unique(dat.X)),[]).';
b = bar(y);
set(gca,'xticklabel',unique(dat.X));
legend(b,num2str(unique(dat.N)))

And if you have Matlab 2017a you can also use this example with categorical data, to set x-axis values from the call to bar.


问:
R put all possible combinations of 2 sets of variables in for loop
I have 2 strings of variables that I would like to combine to get every possible combination in R. My ultimate goals is to take all these combinations that refer to data in different data frame variables and include them in a for statement for writing pdfs for each combination. For example,

```<code>A <- c(a, b, c)
B <- c(1, 2, 3)
</code>```

I would like to end up being able to write,
for all combinations of A = x and B = y...

How do I do this? Can I instruct this within a for statement? Or, do I need to make some sort of string combining A*B first? Either way, I need help with the syntax. Thank you!

Body:
I have 2 strings of variables that I would like to combine to get every possible combination in R. My ultimate goals is to take all these combinations that refer to data in different data frame variables and include them in a for statement for writing pdfs for each combination. For example,

A <- c(a, b, c)
B <- c(1, 2, 3)

I would like to end up being able to write,
for all combinations of A = x and B = y...

How do I do this? Can I instruct this within a for statement? Or, do I need to make some sort of string combining A*B first? Either way, I need help with the syntax. Thank you!

Body:
A <- c("a", "b", "c")
B <- c(1, 2, 3)

AB <- merge(A,B)

for(i in 1:nrow(AB)){
  print(c("This is A:", AB[i,1]))
  print(c("This is B:", AB[i,2]))
}


问:
firemonkey tmapview custom tile server
I have my own tile server and like to use tmapview component

Is it possible to use tmapview with my own tile server ??

like tileoverlay

thanks

答:
TMapView is specifically for maps via the Google Maps API, which means it is tied specifically to Google. From the TMapView documentation (emphasis added):

To run an application on Android with TMapView, you need to acquire an API-Key for Google Maps API.

So no, you cannot use it with your own server.

Title: firemonkey tmapview custom tile server


问:
SDL2 Get the coordinates of a pixel
I have a window with an image as my user interface and I'm trying to see between what coordinates the buttons that I drew on that image are defined. I need those for the following condition:

```<code>if (mouseX0>a && mouseX0<b && mouseY0>c && mouseY0<d
  && event.window.windowID == user_interface)
</code>```

I do not know at the moment between which coordinates are the buttons. I found out there is a function that could get the coordinates of a pixel I would click in my window and I could print that then use it in my code. I want to click on each corners of the buttons so I could have the a, b, c, d values.

答:
The information you need is stored in SDL_MouseButtonEvent event structure (the x and y values obviously) . Just check the mouse events in your event loop as you click. See SDL_Event for example code on event processing and filtering.

Also if you have a static image for your UI, you just can measure that info in any graphics editor, just lookup coordinates under your cursor, which is basic functionality in most apps.

Title: SDL2 Get the coordinates of a pixel

Body:
I have a window with an image as my user interface and I'm trying to see between what coordinates the buttons that I drew on that image are defined. I need those for the following condition:

if (mouseX0>a && mouseX0c && mouseY0<d
  && event.window.windowID == user_interface)

I do not know at the moment between which coordinates are the buttons. I found out there is a function that could get the coordinates of a pixel I would click in my window and I could print that then use it in my code. I want to click on each corners of the buttons so I could have the a, b, c, d values.


问:
Prepend dynamic elements with pure javascript
I have the following HTML

```<code><div id="form">
        <div id="test">
            <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
        </div>
    </div>
</code>```

and I am trying to build an form based on JSON data

```<code>for (i in response[key].request_fields) {
var values = ( () => {
    var out = "";
    for(var e in response[key].request_fields[i].values){
        out += "<li class='item_check'>" +
                    "<input type='checkbox' id='" + response[key].request_fields[i].values[e] + "'>" +
                    "<label for='" + response[key].request_fields[i].values[e] + "'>"
                        + response[key].request_fields[i].values[e] +
                    "</label>" +
                "</li>";
    }
    return out;
})();

document.getElementById("test").innerHTML += "<div class='form_section'>" +
                                                "<label>" + response[key].request_fields[i].label + "</label>" +
                                                "<ul>" + values + "</ul>" +
                                             "</div>";
}
</code>```

It's working properly, except that I need this result to be printed before my textarea.
How can I prepend it ?

答:
Here's how you can do this using proper DOM manipulation. Though it's a lot more verbose than your original code, it is a lot more resilient to arbitrary values containing special characters (like &, <, etc.) and doesn't rely on fragile string concatenation.

The main points are:

document.createElement to create elements

appendChild to append child elements

insertBefore to insert elements before another element

var response = getResponse();
var key = '_embedded';

function liItemForValue(value) {
  var li = document.createElement('li');
  li.classList.add('item_check');

  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.id = value;

  var label = document.createElement('label');
  label.for = value;
  label.textContent = value;

  li.appendChild(checkbox);
  li.appendChild(label);

  return li;
}

function makeFormSection(rf) {
  var liItems = Object.keys(rf.values).map(function(key) {
    return liItemForValue(rf.values[key]);
  });

  var formSection = document.createElement('div');
  formSection.classList.add('form_section');

  var label = document.createElement('label');
  label.innerText = rf.label;

  var ul = document.createElement('ul');

  liItems.forEach(function(liItem) {
    ul.appendChild(liItem);
  });

  formSection.appendChild(label);
  formSection.appendChild(ul);

  return formSection;
}

var formSections = response[key].request_fields.map(makeFormSection);

var test = document.getElementById('test');
var textarea = test.querySelector('textarea');

formSections.forEach(function(formSection) {
  test.insertBefore(formSection, textarea);
});

function getResponse() {
  return {
    "_embedded": {
      "request_fields": [{
        "reference": null,
        "name": "Qual será o serviço?",
        "label": "Qual será o serviço?",
        "placeholder": "Qual será o serviço?",
        "values": {
          "Coloração": "Coloração",
          "Corte": "Corte",
          "Escova ": "Escova ",
          "Escova progressiva/definitiva": "Escova progressiva/definitiva",
          "Luzes": "Luzes"
        }
      }, {
        "reference": null,
        "name": "Para quem será o serviço?",
        "label": "Para quem será o serviço?",
        "placeholder": "Para quem será o serviço?",
        "values": {
          "Criança": "Criança",
          "Homem": "Homem",
          "Mulher": "Mulher"
        }
      }]
    }
  };
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="form">
  <div id="test">
    <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
  </div>
</div></code>```

Body:
I have the following HTML

            <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>

and I am trying to build an form based on JSON data

for (i in response[key].request_fields) {
var values = ( () => {
    var out = "";
    for(var e in response[key].request_fields[i].values){
        out += "
" +
                    "<input type='checkbox' id='" + response[key].request_fields[i].values[e] + "'>" +
                    ""
                        + response[key].request_fields[i].values[e] +
                    "" +
                "
";
    }
    return out;
})();

document.getElementById("test").innerHTML += "
" +
                                                "" + response[key].request_fields[i].label + "" +
                                                "
" + values + "
" +
                                             "
";
}

It's working properly, except that I need this result to be printed before my textarea.
How can I prepend it ?

Body:
Here's how you can do this using proper DOM manipulation. Though it's a lot more verbose than your original code, it is a lot more resilient to arbitrary values containing special characters (like &, <, etc.) and doesn't rely on fragile string concatenation.

The main points are:

document.createElement to create elements

appendChild to append child elements

insertBefore to insert elements before another element

var response = getResponse();
var key = '_embedded';

function liItemForValue(value) {
  var li = document.createElement('li');
  li.classList.add('item_check');

  var checkbox = document.createElement('input');
  checkbox.type = 'checkbox';
  checkbox.id = value;

  var label = document.createElement('label');
  label.for = value;
  label.textContent = value;

  li.appendChild(checkbox);
  li.appendChild(label);

  return li;
}

function makeFormSection(rf) {
  var liItems = Object.keys(rf.values).map(function(key) {
    return liItemForValue(rf.values[key]);
  });

  var formSection = document.createElement('div');
  formSection.classList.add('form_section');

  var label = document.createElement('label');
  label.innerText = rf.label;

  var ul = document.createElement('ul');

  liItems.forEach(function(liItem) {
    ul.appendChild(liItem);
  });

  formSection.appendChild(label);
  formSection.appendChild(ul);

  return formSection;
}

var formSections = response[key].request_fields.map(makeFormSection);

var test = document.getElementById('test');
var textarea = test.querySelector('textarea');

formSections.forEach(function(formSection) {
  test.insertBefore(formSection, textarea);
});

function getResponse() {
  return {
    "_embedded": {
      "request_fields": [{
        "reference": null,
        "name": "Qual será o serviço?",
        "label": "Qual será o serviço?",
        "placeholder": "Qual será o serviço?",
        "values": {
          "Coloração": "Coloração",
          "Corte": "Corte",
          "Escova ": "Escova ",
          "Escova progressiva/definitiva": "Escova progressiva/definitiva",
          "Luzes": "Luzes"
        }
      }, {
        "reference": null,
        "name": "Para quem será o serviço?",
        "label": "Para quem será o serviço?",
        "placeholder": "Para quem será o serviço?",
        "values": {
          "Criança": "Criança",
          "Homem": "Homem",
          "Mulher": "Mulher"
        }
      }]
    }
  };
}

<div id="form">
  <div id="test">
    <textarea name="" placeholder="input_form" id="" cols="30" rows="10"></textarea>
  </div>
</div>


问:
Javascript setTimeout is sometimes not triggered in WebView
We have a small Android app which mainly consists of a WebView. In this WebView, we load an Angular 2 App (Angular 2.4) which regularily polls an API. To trigger the polling regularily, we use a recursive call:

```<code>private xxx() {
  console.log("Beginning of xxx");
  ...
  http.get(url).then( => {
    console.log("Before setTimeout");
    setTimeout(() => xxx(), 300);
  });
}
</code>```

Polling usually works well, however, after some time (~ 1-2 min), polling stops. From our logging, we can see that the timeout is set (second log line above), but the callback is not called.

Things we have tried/learned so far:

Viewing the app in Chrome on the same device does not reproduce the issue

Remote debugging via Chrome development tools prevents the issue

A touch event makes the app recommence the polling

Android version 6.0

API level: 23

答: This issue was solved by updating  system.android.WebView from version 46.0.2490.76 to 58.0.3029.83.</p>

Body:
We have a small Android app which mainly consists of a WebView. In this WebView, we load an Angular 2 App (Angular 2.4) which regularily polls an API. To trigger the polling regularily, we use a recursive call:

private xxx() {
  console.log("Beginning of xxx");
  ...
  http.get(url).then( => {
    console.log("Before setTimeout");
    setTimeout(() => xxx(), 300);
  });
}

Polling usually works well, however, after some time (~ 1-2 min), polling stops. From our logging, we can see that the timeout is set (second log line above), but the callback is not called.

Things we have tried/learned so far:

Viewing the app in Chrome on the same device does not reproduce the issue

Remote debugging via Chrome development tools prevents the issue

A touch event makes the app recommence the polling

Android version 6.0

API level: 23


问:
Core Data Relationship Not Persisting
I am attempting to add an entity to a set but it is not persisting after the application is closed. My relationship looks like this:

I create a new Task like this:

```<code> guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Task",
                                   in: managedContext)!

    let task = NSManagedObject(entity: entity,
                                insertInto: managedContext)

    // 3
    task.setValue(cell.taskTextField.text, forKeyPath: "name")

    // 4
    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }
</code>```

I add the task to a group entity like this:

```<code> groups[0].mutableSetValue(forKey: "tasks").add(task)
</code>```

Where groups is a NSManagedObject array whose value is loaded in viewDidLoad: like so:

```<code>   //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Group")

    //3
    do {
        groups = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }
</code>```

The groups populate properly, I have all the groups I created. But no relationships are present. This prints nothing:

```<code>  let set = groups[0].mutableSetValue(forKey: "tasks")
    for tasks in set{
        print(tasks)
    }
</code>```

This code prints the tasks provided I don't open and close the app. For some reason the data is not persisting when the app is closed. Any Ideas? Thanks

答: Make sure you're saving your context all the way back to up the persistent store (not just the parent context). </p>

Title: Core Data Relationship Not Persisting

Body:
I am attempting to add an entity to a set but it is not persisting after the application is closed. My relationship looks like this:

I create a new Task like this:

 guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    // 1
    let managedContext =
        appDelegate.persistentContainer.viewContext

    // 2
    let entity =
        NSEntityDescription.entity(forEntityName: "Task",
                                   in: managedContext)!

    let task = NSManagedObject(entity: entity,
                                insertInto: managedContext)

    // 3
    task.setValue(cell.taskTextField.text, forKeyPath: "name")

    // 4
    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save. \(error), \(error.userInfo)")
    }

I add the task to a group entity like this:

 groups[0].mutableSetValue(forKey: "tasks").add(task)

Where groups is a NSManagedObject array whose value is loaded in viewDidLoad: like so:

   //1
    guard let appDelegate =
        UIApplication.shared.delegate as? AppDelegate else {
            return
    }

    let managedContext =
        appDelegate.persistentContainer.viewContext

    //2
    let fetchRequest =
        NSFetchRequest<NSManagedObject>(entityName: "Group")

    //3
    do {
        groups = try managedContext.fetch(fetchRequest)
    } catch let error as NSError {
        print("Could not fetch. \(error), \(error.userInfo)")
    }

The groups populate properly, I have all the groups I created. But no relationships are present. This prints nothing:

  let set = groups[0].mutableSetValue(forKey: "tasks")
    for tasks in set{
        print(tasks)
    }

This code prints the tasks provided I don't open and close the app. For some reason the data is not persisting when the app is closed. Any Ideas? Thanks


问:
How to detect if a point intersect body in libgdx
I am adding bodies with fixtures to a box2d world in libgdx.
I want to detect if the user has touched (clicked) an object.
How do I do this? thanks</p>

答:
User touches the body only if he touches some of Fixture's contained into this body. This mean, you can check every Fixture of Body using testPoit() method:

```<code>public class Player {
    private Body _body;

    public boolean isPointOnPlayer(float x, float y){
        for(Fixture fixture : _body.getFixtureList())
            if(fixture.testPoint(x, y)) return true;
        return false;
    }
}
</code>```

Next, you need to create InputAdapter like this:

```<code>public class PlayerControl extends InputAdapter {
    private final Camera _camera;
    private final Player _player;
    private final Vector3 _touchPosition;

    public PlayerControl(Camera camera, Player player) {
        _camera = camera;
        _player = player;
        // create buffer vector to make garbage collector happy
        _touchPosition = new Vector3();
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        // don't forget to unproject screen coordinates to game world
        _camera.unproject(_touchPosition.set(screenX, screenY, 0F));
        if (_player.isPointOnPlayer(_touchPosition.x, _touchPosition.y)) {
            // touch on the player body. Do some stuff like player jumping
            _player.jump();
            return true;
        } else
            return super.touchDown(screenX, screenY, pointer, button);
    }
}
</code>```

And the last one - setup this processor to listen user input:

```<code>public class MyGame extends ApplicationAdapter {

    @Override
    public void create () {
    // prepare player and game camera
    Gdx.input.setInputProcessor(new PlayerControl(cam, player));
}
</code>```

Read more about touch handling here

Body:
User touches the body only if he touches some of Fixture's contained into this body. This mean, you can check every Fixture of Body using testPoit() method:

public class Player {
    private Body _body;

    public boolean isPointOnPlayer(float x, float y){
        for(Fixture fixture : _body.getFixtureList())
            if(fixture.testPoint(x, y)) return true;
        return false;
    }
}

Next, you need to create InputAdapter like this:

public class PlayerControl extends InputAdapter {
    private final Camera _camera;
    private final Player _player;
    private final Vector3 _touchPosition;

    public PlayerControl(Camera camera, Player player) {
        _camera = camera;
        _player = player;
        // create buffer vector to make garbage collector happy
        _touchPosition = new Vector3();
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        // don't forget to unproject screen coordinates to game world
        _camera.unproject(_touchPosition.set(screenX, screenY, 0F));
        if (_player.isPointOnPlayer(_touchPosition.x, _touchPosition.y)) {
            // touch on the player body. Do some stuff like player jumping
            _player.jump();
            return true;
        } else
            return super.touchDown(screenX, screenY, pointer, button);
    }
}

And the last one - setup this processor to listen user input:

public class MyGame extends ApplicationAdapter {

    @Override
    public void create () {
    // prepare player and game camera
    Gdx.input.setInputProcessor(new PlayerControl(cam, player));
}

Read more about touch handling here


问:
How to deploy Angular 2 application developed in Typescript to production?
I am new to Angular 2.  I am confused with how Angular 2 works in production environment.

What are the prerequisites for running Angular 2 application in production   server?

Is it possible to  deploy the application in IIS server or is node server required?

After compiling the file in development machine using node, do we need to deploy both .js and  .ts to production?

答:
An application server (for my answer, I used Tomcat), node.js, and angular-cli (by running "npm install -g angular-cli")

You can deploy to other servers

Just .html, .js and .map files (at least for my solution)

This works better if you had created the application using angular-cli instructions shown here. In your application root directory, run the following command ng build --env=prod and that will bundle, via webpack, the deployable items in the \dist directory.

Copy the \dist directory and paste it into {CATALINA_HOME}\webapps. Rename \dist to a folder name such as \foo. Open \foo\index.html and edit the base-href line to represent your new directory name:

```<code><base href="/foo/">
</code>```

Start Tomcat via startup.bat or your chosen preference and navigate to http://localhost:8080/foo/ and you should be able to view your Angular 2 application.

Note: If you had not created the project with ng new command, I had read where executing ng init before build will allow you to still follow the steps. I have not tested this myself though.

Body:
An application server (for my answer, I used Tomcat), node.js, and angular-cli (by running "npm install -g angular-cli")

You can deploy to other servers

Just .html, .js and .map files (at least for my solution)

This works better if you had created the application using angular-cli instructions shown here. In your application root directory, run the following command ng build --env=prod and that will bundle, via webpack, the deployable items in the \dist directory.

Copy the \dist directory and paste it into {CATALINA_HOME}\webapps. Rename \dist to a folder name such as \foo. Open \foo\index.html and edit the base-href line to represent your new directory name:

<base href="/foo/">

Start Tomcat via startup.bat or your chosen preference and navigate to http://localhost:8080/foo/ and you should be able to view your Angular 2 application.

Note: If you had not created the project with ng new command, I had read where executing ng init before build will allow you to still follow the steps. I have not tested this myself though.


问:
Extending data class from a sealed class in Kotlin
I have a set of data classes that share some common fields, So ideally I'd like to declare those in a supertype (Message in this example), and be able to write functions that operate on the supertype if they need access to these common fields (messageId in this example).

```<code>fun operate(m: Message) {
  use(m.messageId)
}
</code>```

I tried to accomplish this by extending my data classes from a sealed class.

Data classes may extend sealed classes, but not I'm not sure how/if they can accept arguments required by the "supertype" sealed class.

Extending a regular class from a sealed class compiles just fine.

```<code>sealed class Message(val messageId: String)

class Track(val event: String, messageId: String): Message(messageId)
</code>```

However, changing it to a data class doesn't compile ("Data class primary constructor must have only property (val/var) parameters.").

```<code>sealed class Message(val messageId: String)

data class Track(val event: String, messageId: String): Message(messageId)
</code>```

Declaring the parameter as a property also doesn't compile ("'messageId' hides member of supertype 'Message' and needs 'override' modifier'").

```<code>sealed class Message(val messageId: String)

data class Track(val event: String, val messageId: String): Message(messageId)
</code>```

Opening the supertype property and overriding it in each of the base classes compiles fine:

```<code>sealed class Message(open val messageId: String)

data class Track(val event: String, override val messageId: String): Message(messageId)
</code>```

Ideally I would like something close to Option 2 - it allows me to combine the best of both worlds.

Otherwise, it seems my options are either handrolling my own data class functionality (copy, hashcode, equals etc) with option 1, or live with a compromise by opening up up the supertype properties with option 4.

答:
Options 3 and 4 would result in the class holding messageId twice. Once in the new class and once in its superclass.

The solution is to declare but not define the variable in the superclass:

```<code>sealed class Message {
    abstract val messageId: String
}

data class Track(val event: String, override val messageId: String): Message()
</code>```

This will make the messageId available on Message, but delegates the storage to whatever implements it.

Body:
I have a set of data classes that share some common fields, So ideally I'd like to declare those in a supertype (Message in this example), and be able to write functions that operate on the supertype if they need access to these common fields (messageId in this example).

fun operate(m: Message) {
  use(m.messageId)
}

I tried to accomplish this by extending my data classes from a sealed class.

Data classes may extend sealed classes, but not I'm not sure how/if they can accept arguments required by the "supertype" sealed class.

Extending a regular class from a sealed class compiles just fine.

sealed class Message(val messageId: String)

class Track(val event: String, messageId: String): Message(messageId)

However, changing it to a data class doesn't compile ("Data class primary constructor must have only property (val/var) parameters.").

sealed class Message(val messageId: String)

data class Track(val event: String, messageId: String): Message(messageId)

Declaring the parameter as a property also doesn't compile ("'messageId' hides member of supertype 'Message' and needs 'override' modifier'").

sealed class Message(val messageId: String)

data class Track(val event: String, val messageId: String): Message(messageId)

Opening the supertype property and overriding it in each of the base classes compiles fine:

sealed class Message(open val messageId: String)

data class Track(val event: String, override val messageId: String): Message(messageId)

Ideally I would like something close to Option 2 - it allows me to combine the best of both worlds.

Otherwise, it seems my options are either handrolling my own data class functionality (copy, hashcode, equals etc) with option 1, or live with a compromise by opening up up the supertype properties with option 4.

Body:
Options 3 and 4 would result in the class holding messageId twice. Once in the new class and once in its superclass.

The solution is to declare but not define the variable in the superclass:

sealed class Message {
    abstract val messageId: String
}

data class Track(val event: String, override val messageId: String): Message()

This will make the messageId available on Message, but delegates the storage to whatever implements it.


问:
Print more than one result in SQL Data Reader
I have a Stored Procedure that will return more than 1 value from a table. However, I'm only able to print 1 result, can someone please tell me what am I doing wrong

vb.net Code

```<code>reader = cmd_loadMacro.ExecuteReader()
        reader.Read()
        MacroKey = reader.GetString(0)
        MacroValue = reader.GetString(1)
</code>```

My query does return results when i execute it SSMS, I should have 5 rows back, but only 1 row is returned

Latest attempt  (This brings 0 results back)

`reader.Read()

```<code>        If reader.HasRows Then
            While reader.Read()
                MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
            End While
        End If`
</code>```

答:
I got this to working using a for loop in my main class, and passing it on to the function. This works perfectly.</p>

```<code>MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
                writer.WriteStartElement("djmacros") ' Root.
                writer.WriteStartElement("macro")
                writer.WriteAttributeString("name", MacroKey)
                writer.WriteAttributeString("type", "1000")
                writer.WriteAttributeString("value", MacroValue)
                writer.WriteEndElement()

                While reader.Read
                    MacroKey = reader.GetString(0)
                    MacroValue = reader.GetString(1)
                    writer.WriteStartElement("macro")
                    writer.WriteAttributeString("name", MacroKey)
                    writer.WriteAttributeString("type", "1000")
                    writer.WriteAttributeString("value", MacroValue)
                    writer.WriteEndElement()
</code>```

Body:
I have a Stored Procedure that will return more than 1 value from a table. However, I'm only able to print 1 result, can someone please tell me what am I doing wrong

vb.net Code

reader = cmd_loadMacro.ExecuteReader()
        reader.Read()
        MacroKey = reader.GetString(0)
        MacroValue = reader.GetString(1)

My query does return results when i execute it SSMS, I should have 5 rows back, but only 1 row is returned

Latest attempt  (This brings 0 results back)

`reader.Read()

        If reader.HasRows Then
            While reader.Read()
                MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
            End While
        End If`

Body:
I got this to working using a for loop in my main class, and passing it on to the function. This works perfectly.

MacroKey = reader.GetString(0)
                MacroValue = reader.GetString(1)
                writer.WriteStartElement("djmacros") ' Root.
                writer.WriteStartElement("macro")
                writer.WriteAttributeString("name", MacroKey)
                writer.WriteAttributeString("type", "1000")
                writer.WriteAttributeString("value", MacroValue)
                writer.WriteEndElement()

                While reader.Read
                    MacroKey = reader.GetString(0)
                    MacroValue = reader.GetString(1)
                    writer.WriteStartElement("macro")
                    writer.WriteAttributeString("name", MacroKey)
                    writer.WriteAttributeString("type", "1000")
                    writer.WriteAttributeString("value", MacroValue)
                    writer.WriteEndElement()


问:
Curious behaviour of std::string::operator[] in MSVC
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

```<code>t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);
</code>```

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?

答:
operator[](size_type pos) const doesn't return one-past-the-end is pos == size(); it returns charT(), which is a temporary.  In the non-const version of operator[], the behavior is undefined.

21.3.4/1

const_reference operator[](size_type pos) const;
  reference operator[](size_type pos);
  1 Returns: If pos < size(), returns data()[pos]. Otherwise, if pos == size(), the const
  version returns charT(). Otherwise, the behavior is undefined.

Body:
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?


问:
Creating a pdf file in android programmatically and writing in it
I'm trying to create a pdf file inside my app, save it on the external storage the open it. Saving a file isn't an issue for me, nor is opening one, my issue is with creating one and writing in it. So after some research online I found the following way of doing it:

```<code>File file = new File(directoryName, fileName);

// Creating output stream to write in the newly created file
FileOutputStream fOut = null;

try {
    fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

// Creating a new document
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

try {
    PdfWriter.getInstance(document, fOut);

    // Open the document for writing
    document.open();

    // Write in the document
    document.add(new Paragraph("Hello world"));
    document.close();

} catch (DocumentException de) {
    System.err.println(de.getMessage());
}
</code>```

Upon running my app and executing the code above, I get the following error:

```<code>java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;
</code>```

Would someone know what's the issue with my code, or of another way that is sure to work for creating and writing a pdf file ?

Thanks !

答:
Download source code from here (Create pdf file in android programmatically)

activity_main.xml:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_generate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Generate PDF" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:id="@+id/ll_pdflayout"
        android:background="#ffffff"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/iv_image"
            android:src="@drawable/image"
            android:layout_width="300dp"
            android:scaleType="fitXY"
            android:layout_marginTop="10dp"
            android:layout_gravity="center"
            android:layout_height="250dp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:textColor="#000000"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_link"
            android:textSize="10dp"
            android:textColor="#000000"/>

    </LinearLayout>

</LinearLayout>
</code>```

MainActivity.java

```<code>package com.deepshikha.generatepdf;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.pdf.PdfDocument;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btn_generate;
    TextView tv_link;
    ImageView iv_image;
    LinearLayout ll_pdflayout;
    public static int REQUEST_PERMISSIONS = 1;
    boolean boolean_permission;
    boolean boolean_save;
    Bitmap bitmap;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        fn_permission();
        listener();
    }

    private void init(){
        btn_generate = (Button)findViewById(R.id.btn_generate);
        tv_link = (TextView)findViewById(R.id.tv_link);
        iv_image = (ImageView) findViewById(R.id.iv_image);
        ll_pdflayout = (LinearLayout) findViewById(R.id.ll_pdflayout);

    }

    private void listener(){
        btn_generate.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_generate:

                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("Please wait");
                         bitmap = loadBitmapFromView(ll_pdflayout, ll_pdflayout.getWidth(), ll_pdflayout.getHeight());
                        createPdf();
//                        saveBitmap(bitmap);
                    } else {

                    }

                    createPdf();
                    break;
                }
        }
    }

    private void createPdf(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

//        Resources mResources = getResources();
//        Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot);

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);

       String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/PdfTett/";
    File dir = new File(path);
    if (!dir.exists())
        dir.mkdirs();

    File filePath = new File(dir,"Testtt.pdf");

        try {
            document.writeTo(new FileOutputStream(filePath));
            btn_generate.setText("Check PDF");
            boolean_save=true;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        // close the document
        document.close();
    }

    public static Bitmap loadBitmapFromView(View v, int width, int height) {
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);

        return b;
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)||
                (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }
        } else {
            boolean_permission = true;

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                boolean_permission = true;

            } else {
                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

            }
        }
    }

}
</code>```

Thanks!

Body:
I'm trying to create a pdf file inside my app, save it on the external storage the open it. Saving a file isn't an issue for me, nor is opening one, my issue is with creating one and writing in it. So after some research online I found the following way of doing it:

File file = new File(directoryName, fileName);

// Creating output stream to write in the newly created file
FileOutputStream fOut = null;

try {
    fOut = new FileOutputStream(file);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

// Creating a new document
Document document = new Document(PageSize.A4, 50, 50, 50, 50);

try {
    PdfWriter.getInstance(document, fOut);

    // Open the document for writing
    document.open();

    // Write in the document
    document.add(new Paragraph("Hello world"));
    document.close();

} catch (DocumentException de) {
    System.err.println(de.getMessage());
}

Upon running my app and executing the code above, I get the following error:

java.lang.NoClassDefFoundError: Failed resolution of: Ljava/awt/Color;

Would someone know what's the issue with my code, or of another way that is sure to work for creating and writing a pdf file ?

Thanks !

Body:
Download source code from here (Create pdf file in android programmatically)

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_generate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Generate PDF" />

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:id="@+id/ll_pdflayout"
        android:background="#ffffff"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/iv_image"
            android:src="@drawable/image"
            android:layout_width="300dp"
            android:scaleType="fitXY"
            android:layout_marginTop="10dp"
            android:layout_gravity="center"
            android:layout_height="250dp" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="14dp"
            android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
            android:layout_marginTop="10dp"
            android:gravity="center"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:textColor="#000000"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/tv_link"
            android:textSize="10dp"
            android:textColor="#000000"/>

    </LinearLayout>

</LinearLayout>

MainActivity.java

package com.deepshikha.generatepdf;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.pdf.PdfDocument;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    Button btn_generate;
    TextView tv_link;
    ImageView iv_image;
    LinearLayout ll_pdflayout;
    public static int REQUEST_PERMISSIONS = 1;
    boolean boolean_permission;
    boolean boolean_save;
    Bitmap bitmap;
    ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        fn_permission();
        listener();
    }

    private void init(){
        btn_generate = (Button)findViewById(R.id.btn_generate);
        tv_link = (TextView)findViewById(R.id.tv_link);
        iv_image = (ImageView) findViewById(R.id.iv_image);
        ll_pdflayout = (LinearLayout) findViewById(R.id.ll_pdflayout);

    }

    private void listener(){
        btn_generate.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_generate:

                if (boolean_save) {
                    Intent intent = new Intent(getApplicationContext(), PDFViewActivity.class);
                    startActivity(intent);

                } else {
                    if (boolean_permission) {
                        progressDialog = new ProgressDialog(MainActivity.this);
                        progressDialog.setMessage("Please wait");
                         bitmap = loadBitmapFromView(ll_pdflayout, ll_pdflayout.getWidth(), ll_pdflayout.getHeight());
                        createPdf();
//                        saveBitmap(bitmap);
                    } else {

                    }

                    createPdf();
                    break;
                }
        }
    }

    private void createPdf(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

//        Resources mResources = getResources();
//        Bitmap bitmap = BitmapFactory.decodeResource(mResources, R.drawable.screenshot);

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);

       String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString() + "/PdfTett/";
    File dir = new File(path);
    if (!dir.exists())
        dir.mkdirs();

    File filePath = new File(dir,"Testtt.pdf");

        try {
            document.writeTo(new FileOutputStream(filePath));
            btn_generate.setText("Check PDF");
            boolean_save=true;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        // close the document
        document.close();
    }

    public static Bitmap loadBitmapFromView(View v, int width, int height) {
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);

        return b;
    }

    private void fn_permission() {
        if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)||
                (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)) {

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.READ_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }

            if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE))) {
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_PERMISSIONS);

            }
        } else {
            boolean_permission = true;

        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSIONS) {

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                boolean_permission = true;

            } else {
                Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();

            }
        }
    }

}

Thanks!


问:
Pandas: how to convert a list into a matrix grouped by a column?
I have a pandas dataframe where the first column (CUSTOMER) is the name of the customer and the customer's name is repeated once for every product the customer has purchased (PRODUCT):

```<code>Customer  Product  Count
John      A        1
John      B        1
John      C        1
Mary      A        1
Mary      B        1
Charles   A        1
</code>```

I want to pivot this data to create a new dataframe where both rows and columns are the category of product (PRODUCT) and the values are the count of the customer name, as follows:

```<code>Product
       A     B     C
A      0     2     1
B      2     0     1
C      1     1     0
</code>```

So if John bought A and also bought B, +1 will be added to the A:B cell, he also bought A in combination with C, so there is a +1 on the A:C cell, and so on. Note that Charles does not appear in this dataframe because he only bought one product.

I tried to use pandas.pivot_table but this is what I got:

```<code>df = pd.pivot_table(df, index=['Product'], columns=['Product'], values=['Customer'])

>> KeyError: 'Level Product not found'
</code>```

What method and parameters should I use?

答:
Self merge with crosstab

```<code>d1 = df.merge(df, on='Customer').query('Product_x != Product_y')
pd.crosstab(d1.Product_x, d1.Product_y)

Product_y  A  B  C
Product_x
A          0  2  1
B          2  0  1
C          1  1  0
</code>```

You can see this answer to get a better idea how to speed the crosstab up.  The key insight for this problem was the self merging.

Body:
I have a pandas dataframe where the first column (CUSTOMER) is the name of the customer and the customer's name is repeated once for every product the customer has purchased (PRODUCT):

Customer  Product  Count
John      A        1
John      B        1
John      C        1
Mary      A        1
Mary      B        1
Charles   A        1

I want to pivot this data to create a new dataframe where both rows and columns are the category of product (PRODUCT) and the values are the count of the customer name, as follows:

Product
       A     B     C
A      0     2     1
B      2     0     1
C      1     1     0

So if John bought A and also bought B, +1 will be added to the A:B cell, he also bought A in combination with C, so there is a +1 on the A:C cell, and so on. Note that Charles does not appear in this dataframe because he only bought one product.

I tried to use pandas.pivot_table but this is what I got:

df = pd.pivot_table(df, index=['Product'], columns=['Product'], values=['Customer'])

>> KeyError: 'Level Product not found'

What method and parameters should I use?

Body:
Self merge with crosstab

d1 = df.merge(df, on='Customer').query('Product_x != Product_y')
pd.crosstab(d1.Product_x, d1.Product_y)

Product_y  A  B  C
Product_x
A          0  2  1
B          2  0  1
C          1  1  0

You can see this answer to get a better idea how to speed the crosstab up.  The key insight for this problem was the self merging.


问:
Does catching and rethrowing the exact same exception mean anything?
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}
</code>```

Contrast this to:

```<code>public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}
</code>```

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.

答:
It makes no sense for sure assuming code you provided.
Rethrowing exceptions makes sense when you want to handle this exception somehow (e.g. log it) but want it to be handled further in a stack trace.

Regarding commercial code, maybe the reason you saw it was that there was some handling logic initially that was removed but exceptions rethrowing wasn't removed. I saw such situations several times.

Body:
Lately, I have been seeing a lot of (commercial) code that throws and catches the exact same exception, similar to the code below:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        try {
            // do something (2) -- able to throw AnException
        } catch (AnException ex) {
            throw ex;
        }
        // do something (3)
    }
}

Contrast this to:

public class Foo {
    public void bar() throws AnException {
        // do something (1)
        // do something (2) -- able to throw AnException
        // do something (3)
    }
}

Does the former actually accomplish anything, in either behavior or semantics or else? Will it have any effect on code performance (time and space) or does it help readability?

P.S. this question is very different from this question.

EDIT: The catch block in the former doesn't do anything else other than rethrowing the caught exception.


问:
C# WPF Application Hiding button on click
I have been asked to create a C# WPF application in VS 2013 and scenario is as under.
At the start of the application, a form must appear with two buttons on it. On the top button, the text “Button 1” must be written and on the bottom button the text “Button 2” must be written. For the first time, when any of the button 1 or button 2 is clicked then it will disappear and the other button will stay unchanged. For example, user clicks button 1 for the first time then button 1 will disappear. Button 2 will be unchanged. Now there is only one button on the window that is button 2. On clicking button 2 it will disappear and button 1 will reappear on the window. Now if the user clicks button 1 then it will disappear again and button 2 will reappear. This process may go on indefinitely until the application is terminated by clicking the close button.

I have created all the things but button1.Visible=true; cannot be entered VS is generating warnings that" sytem.windows.control.button does not contains a defination for Visible.

I need help please

答:
Under the Button Click Method you want this:

```<code>private void button1_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button1.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 2
    if (button2.Visibility == Visibility.Collapsed)
    {
        button2.Visibility = Visibility.Visible;
    }
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button2.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 1
    if (button1.Visibility == Visibility.Collapsed)
    {
        button1.Visibility = Visibility.Visible;
    }
}
</code>```

In order to obtain these methods you should declare a Click="" Method in XAML

```<code><Button Name="button1" Click="button1_Click"><Button>
<Button Name="button2" Click="button2_Click"><Button>
</code>```

Body:
Under the Button Click Method you want this:

private void button1_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button1.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 2
    if (button2.Visibility == Visibility.Collapsed)
    {
        button2.Visibility = Visibility.Visible;
    }
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    //Hides Current Button
    button2.Visibility = Visibility.Collapsed;

    //Checks and Shows Button 1
    if (button1.Visibility == Visibility.Collapsed)
    {
        button1.Visibility = Visibility.Visible;
    }
}

In order to obtain these methods you should declare a Click="" Method in XAML

<Button Name="button1" Click="button1_Click"><Button>
<Button Name="button2" Click="button2_Click"><Button>