问:
How do i draw anywhere in a graphics object after it is transformed
I'm trying to create a canvas for drawing different objects. I've created zoom and pan functions using graphics.scaleTransform and graphics.translateTransform, but i wan't the canvas background (a grid) to allways fill out the entire window, however it does not, using the following code:

EDIT: I've tried using the coordinates in the transformed graphics object, but it seems it won't accept negative numbers?!?

EDIT: This picture explains my problem:

```<code> public partial class Form1 : Form
        {

            PointF mouseDown;

            float newX;
            float newY;
            float zoomFactor = 1F;

            Region _rgn;
            Graphics _dc;
            PointF zoomPoint = new PointF(150, 150);

            public Form1()
            {
                InitializeComponent();

                mouseDown = new PointF(0F, 0F);

                this.panel1.Paint += new PaintEventHandler(panel1_Paint);
                this.panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown);
                this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove);

            }

            private void panel1_Paint(object sender, PaintEventArgs e)
            {

                base.OnPaint(e);

                //Graphics bg =

                Graphics dc = e.Graphics;
                _dc = dc;

                dc.SmoothingMode = SmoothingMode.AntiAlias;

Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            for (float i = 0; i < this.Height * (zoomFactor); i = i + 30*zoomFactor)
            {
                dc.DrawLine(gridPen, 0, i, this.Width * (zoomFactor), i);
            }
            for (float i = 0; i < this.Width * (zoomFactor); i = i + 30*zoomFactor)
            {
                dc.DrawLine(gridPen, i, 0, i, this.Height * (zoomFactor));
            }

                dc.TranslateTransform(newX, newY);
                dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

                float XPosition = 10;
                float YPosition = 10;
                float CornerRadius = 5;
                float Width = 50;
                float Height = 50;

                Color BoxColor = Color.FromArgb(0, 0, 0);
                Pen BoxPen = new Pen(BoxColor, 2);

                GraphicsPath Path = new GraphicsPath();

                Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
                Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
                Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
                Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
                Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
                Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
                Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
                Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

                Path.CloseFigure();

                LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition+(Width/2),YPosition), new PointF(XPosition+(Width/2),YPosition + Height), Color.RosyBrown, Color.Red);

                dc.FillPath(lgb, Path);

                dc.DrawPath(BoxPen, Path);

                Matrix transformMatrix = new Matrix();
                transformMatrix.Translate(newX, newY);
                transformMatrix.Scale(zoomFactor, zoomFactor);

                _rgn = new Region(Path);

                _rgn.Transform(transformMatrix);

            }

            private void panel1_MouseDown(object sender, EventArgs e)
            {
                MouseEventArgs mouse = e as MouseEventArgs;

                if (mouse.Button == MouseButtons.Right)
                {

                    mouseDown = mouse.Location;

                    mouseDown.X = mouseDown.X - newX;
                    mouseDown.Y = mouseDown.Y - newY;

                }

                else if (mouse.Button == MouseButtons.Left)
                {

                    if (_rgn.IsVisible(mouse.Location, _dc))
                    {
                        MessageBox.Show("tada");
                    }

                }

            }

            private void panel1_MouseMove(object sender, EventArgs e)
            {
                MouseEventArgs mouse = e as MouseEventArgs;

                if (mouse.Button == MouseButtons.Right)
                {
                    PointF mousePosNow = mouse.Location;

                    float deltaX = mousePosNow.X - mouseDown.X;
                    float deltaY = mousePosNow.Y - mouseDown.Y;

                    newX = deltaX;
                    newY = deltaY;

                    panel1.Invalidate();

                }

            }

            protected override void OnMouseWheel(MouseEventArgs e)
            {

                MouseEventArgs mouse = e as MouseEventArgs;

                PointF mP = mouse.Location;

                if (e.Delta > 0)
                {
                    if (zoomFactor >= 1 && zoomFactor <= 10)
                    {
                        zoomFactor += 1F;

                        newX = newX - ((mP.X - newX) / (zoomFactor - 1));
                        newY = newY - ((mP.Y - newY) / (zoomFactor - 1));
                    }
                    else if (zoomFactor == 0.5)
                    {
                        zoomFactor = zoomFactor * 2;
                        newX = 2 * newX - mP.X ;
                        newY = 2 * newY - mP.Y ;
                    }
                    else if (zoomFactor < 0.5)
                    {
                        zoomFactor = zoomFactor * 2;
                        newX = 2 * newX - mP.X;
                        newY = 2 * newY - mP.Y;
                    }
                }

                else if (e.Delta < 0)
                {
                    if (zoomFactor >2)
                    {
                        zoomFactor -= 1F;
                        newX = newX + (((mP.X - newX)) / (zoomFactor+1 ));
                        newY = newY + (((mP.Y - newY)) / (zoomFactor+1));
                    }
                    else if (zoomFactor == 2) {
                        zoomFactor -= 1F;

                        newX = newX + ((mP.X - newX)/2);
                        newY = newY + ((mP.Y - newY)/2);
                    }else if(zoomFactor <= 1 && zoomFactor > 0.2)
                    {
                        zoomFactor = zoomFactor / 2;

                        newX = newX + ((mP.X - newX) / 2);
                        newY = newY + ((mP.Y - newY) / 2);

                    }

                }

                panel1.Invalidate();

            }
        }
</code>```

答:
Draw your GRID BEFORE transforming the coordinate system.

If you can't, use GetTransform() and ResetTransform(), then draw grid, then SetTransform back (the one got in the first step).

IMHO: It would be much better if you scale you image 'manually' instead of using coordinate transformation.  You'll have much greater control this way, and won't hit the wall with anything.

EDIT:

Also: you have a bug in your grid drawing routine:

```<code>for (float i = 0; i < this.Height * (zoomFactor); i = i + 30*zoomFactor)
</code>```

try replacing with

```<code>for (float i = 0; i < this.Height; i = i + 30*zoomFactor)
</code>```

Body:
I'm trying to create a canvas for drawing different objects. I've created zoom and pan functions using graphics.scaleTransform and graphics.translateTransform, but i wan't the canvas background (a grid) to allways fill out the entire window, however it does not, using the following code:

EDIT: I've tried using the coordinates in the transformed graphics object, but it seems it won't accept negative numbers?!?

EDIT: This picture explains my problem:

 public partial class Form1 : Form
        {

            PointF mouseDown;

            float newX;
            float newY;
            float zoomFactor = 1F;

            Region _rgn;
            Graphics _dc;
            PointF zoomPoint = new PointF(150, 150);

            public Form1()
            {
                InitializeComponent();

                mouseDown = new PointF(0F, 0F);

                this.panel1.Paint += new PaintEventHandler(panel1_Paint);
                this.panel1.MouseDown += new System.Windows.Forms.MouseEventHandler(panel1_MouseDown);
                this.panel1.MouseMove += new System.Windows.Forms.MouseEventHandler(panel1_MouseMove);

            }

            private void panel1_Paint(object sender, PaintEventArgs e)
            {

                base.OnPaint(e);

                //Graphics bg =

                Graphics dc = e.Graphics;
                _dc = dc;

                dc.SmoothingMode = SmoothingMode.AntiAlias;

Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            for (float i = 0; i < this.Height * (zoomFactor); i = i + 30*zoomFactor)
            {
                dc.DrawLine(gridPen, 0, i, this.Width * (zoomFactor), i);
            }
            for (float i = 0; i < this.Width * (zoomFactor); i = i + 30*zoomFactor)
            {
                dc.DrawLine(gridPen, i, 0, i, this.Height * (zoomFactor));
            }

                dc.TranslateTransform(newX, newY);
                dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

                float XPosition = 10;
                float YPosition = 10;
                float CornerRadius = 5;
                float Width = 50;
                float Height = 50;

                Color BoxColor = Color.FromArgb(0, 0, 0);
                Pen BoxPen = new Pen(BoxColor, 2);

                GraphicsPath Path = new GraphicsPath();

                Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
                Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
                Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
                Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
                Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
                Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
                Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
                Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

                Path.CloseFigure();

                LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition+(Width/2),YPosition), new PointF(XPosition+(Width/2),YPosition + Height), Color.RosyBrown, Color.Red);

                dc.FillPath(lgb, Path);

                dc.DrawPath(BoxPen, Path);

                Matrix transformMatrix = new Matrix();
                transformMatrix.Translate(newX, newY);
                transformMatrix.Scale(zoomFactor, zoomFactor);

                _rgn = new Region(Path);

                _rgn.Transform(transformMatrix);

            }

            private void panel1_MouseDown(object sender, EventArgs e)
            {
                MouseEventArgs mouse = e as MouseEventArgs;

                if (mouse.Button == MouseButtons.Right)
                {

                    mouseDown = mouse.Location;

                    mouseDown.X = mouseDown.X - newX;
                    mouseDown.Y = mouseDown.Y - newY;

                }

                else if (mouse.Button == MouseButtons.Left)
                {

                    if (_rgn.IsVisible(mouse.Location, _dc))
                    {
                        MessageBox.Show("tada");
                    }

                }

            }

            private void panel1_MouseMove(object sender, EventArgs e)
            {
                MouseEventArgs mouse = e as MouseEventArgs;

                if (mouse.Button == MouseButtons.Right)
                {
                    PointF mousePosNow = mouse.Location;

                    float deltaX = mousePosNow.X - mouseDown.X;
                    float deltaY = mousePosNow.Y - mouseDown.Y;

                    newX = deltaX;
                    newY = deltaY;

                    panel1.Invalidate();

                }

            }

            protected override void OnMouseWheel(MouseEventArgs e)
            {

                MouseEventArgs mouse = e as MouseEventArgs;

                PointF mP = mouse.Location;

                if (e.Delta > 0)
                {
                    if (zoomFactor >= 1 && zoomFactor <= 10)
                    {
                        zoomFactor += 1F;

                        newX = newX - ((mP.X - newX) / (zoomFactor - 1));
                        newY = newY - ((mP.Y - newY) / (zoomFactor - 1));
                    }
                    else if (zoomFactor == 0.5)
                    {
                        zoomFactor = zoomFactor * 2;
                        newX = 2 * newX - mP.X ;
                        newY = 2 * newY - mP.Y ;
                    }
                    else if (zoomFactor < 0.5)
                    {
                        zoomFactor = zoomFactor * 2;
                        newX = 2 * newX - mP.X;
                        newY = 2 * newY - mP.Y;
                    }
                }

                else if (e.Delta < 0)
                {
                    if (zoomFactor >2)
                    {
                        zoomFactor -= 1F;
                        newX = newX + (((mP.X - newX)) / (zoomFactor+1 ));
                        newY = newY + (((mP.Y - newY)) / (zoomFactor+1));
                    }
                    else if (zoomFactor == 2) {
                        zoomFactor -= 1F;

                        newX = newX + ((mP.X - newX)/2);
                        newY = newY + ((mP.Y - newY)/2);
                    }else if(zoomFactor <= 1 && zoomFactor > 0.2)
                    {
                        zoomFactor = zoomFactor / 2;

                        newX = newX + ((mP.X - newX) / 2);
                        newY = newY + ((mP.Y - newY) / 2);

                    }

                }

                panel1.Invalidate();

            }
        }

Body:
Draw your GRID BEFORE transforming the coordinate system.

If you can't, use GetTransform() and ResetTransform(), then draw grid, then SetTransform back (the one got in the first step).

IMHO: It would be much better if you scale you image 'manually' instead of using coordinate transformation.  You'll have much greater control this way, and won't hit the wall with anything.

EDIT:

Also: you have a bug in your grid drawing routine:

for (float i = 0; i < this.Height * (zoomFactor); i = i + 30*zoomFactor)

try replacing with

for (float i = 0; i < this.Height; i = i + 30*zoomFactor)


来源: stackexchange

问:
Spliting line to array of words
I'm finding the longest and shortest word in the txt.file.
But I always take result

```<code>File Path: there it's ok.
The longest word: *empty*
The shortest word: *empty*
Task complete...
</code>```

Code:

```<code>        List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        String max = "", min = "BlaBlaBlaBlaBlaBlaBla";
        // We take a single line
        for(String line: lines){
            // Break the next line through the regular to an array of words
            List<String> words = Arrays.asList(line.split("\\P{Punct}\\P{Space}"));
            String tempMax = Collections.max(words);
            max = max.length() < tempMax.length() ? tempMax : max;
            String tempMin = Collections.min(words);
            min = min.length() > tempMin.length() ? tempMin : min;
        }

        textArea.setText(String.format(
                "File Path: %s\n" +
                        "The longest word: %s\n" +
                        "The shortest word: %s\n" +
                        "Task complete...", fileName, max, min));
</code>```

Give a hint)

答:
Problem seems to be here:

```<code>String tempMax = Collections.max(words);
</code>```

Collections.max returns the maximum element of the given collection.

For a List<String> maximum element will give you word that is alphabetically last in the list.

So for example in this list:

```<code>new String[] {"food", "zz", "abcdef", "zoo"}
</code>```

It will find "zz" as maximum element.

Moreover your regex for splitting the wors \\P{Punct}\\P{Space} is incorrect.

\\P{Punct}\\P{Space} means a non-punctuation word followed by a white-space.

There are some very helpful comments below your question that suggest right way to split.

At the minimum use: [\\p{P}\\P{ZS}]+ for splitting.

ContentLicense: CC BY-SA 3.0

Title: Spliting line to array of words

Body:
I'm finding the longest and shortest word in the txt.file.
But I always take result

File Path: there it's ok.
The longest word: *empty*
The shortest word: *empty*
Task complete...

Code:

        List<String> lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        String max = "", min = "BlaBlaBlaBlaBlaBlaBla";
        // We take a single line
        for(String line: lines){
            // Break the next line through the regular to an array of words
            List<String> words = Arrays.asList(line.split("\\P{Punct}\\P{Space}"));
            String tempMax = Collections.max(words);
            max = max.length() < tempMax.length() ? tempMax : max;
            String tempMin = Collections.min(words);
            min = min.length() > tempMin.length() ? tempMin : min;
        }

        textArea.setText(String.format(
                "File Path: %s\n" +
                        "The longest word: %s\n" +
                        "The shortest word: %s\n" +
                        "Task complete...", fileName, max, min));

Give a hint)

Body:
Problem seems to be here:

String tempMax = Collections.max(words);

Collections.max returns the maximum element of the given collection.

For a List<String> maximum element will give you word that is alphabetically last in the list.

So for example in this list:

new String[] {"food", "zz", "abcdef", "zoo"}

It will find "zz" as maximum element.

Moreover your regex for splitting the wors \\P{Punct}\\P{Space} is incorrect.

\\P{Punct}\\P{Space} means a non-punctuation word followed by a white-space.

There are some very helpful comments below your question that suggest right way to split.

At the minimum use: [\\p{P}\\P{ZS}]+ for splitting.


问:
How to change the text " Material ActionBar"
How to change the text " Material ActionBar"?
I can't find the code to change it..help.

A Material ActionBar

答:
Hi in your AndroidManifest.xml inside application tag declare your activity if not declared and inside the declared activity tag you need to set label like below:

```<code> <activity
            android:name=".main.MainActivity"
            android:label="Your Custom Name"
         />
</code>```

Thanks

Body:
Hi in your AndroidManifest.xml inside application tag declare your activity if not declared and inside the declared activity tag you need to set label like below:

 <activity
            android:name=".main.MainActivity"
            android:label="Your Custom Name"
         />

Thanks


问:
How to play flv video in android?
I want to display my FLV video in emulator. Anybody who have already work on this?
Basically I need to play video from particular URL and assets folder. So just help on this topic.

答: I used flv.js in the webpage to make the html support flv video file without flash. Then use XWalkView something like webview in android studio to load the webpage. Use WWalkView..</p>

Title: How to play flv video in android?


问:
Execute dynamically created array of observables in series
I am working on a project (Angular2) where I am creating Observables dynamically and putting them in an array

```<code>var ObservableArray : Observable<any>[] = [];
//filling up Observable array dynamically
for (var i = 0; i < this.mainPerson.children.length; i++) {
ObservableArray.push(Observable.fromPromise(this.determineFate(this.mainPerson.children[i])));
  }
}

var finalObservable: Observable<any> = Observable.concat(ObservableArray);

finalObservable
  .subscribe( data => {
    //here  I expected to execute determineFate() for all observables inside array
    console.log("determine fate resolved data returned [" + data + "]");
  }, error => {
    console.error("error on Age Year for Characters")
  },() => {
    //Here I expect this gets executed only when all Observables inside my array finishes
    console.log("determine fate resolved data returned COMPLETED");
    //DB call
  });

  determineFate(..): Promise<boolean> {
       ...
       return either true / false if success or error;

 }
</code>```

I want to execute all observables in a series (forkJoin seems to run in parallel - so used concat). Once all observables are executed, want to execute some DB related code. But it seems my code inside 'Completed' block does not wait for all Observables to finish. How can I achieve this?

Thanks in advance

答:
Using Observable.concat(ObservableArray) will just flatten the array and emit each Observable from ObservableArray one by one. Btw, using the static version of concat makes sense only with two or more parameters (see http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-concat).

Instead you can iterate the array of Observables and wait until they complete one by one with the concatAll() operator.

This example simulates your use-case:

```<code>var observableArray = [];
// filling up Observable array dynamically
for (var i = 0; i < 10; i++) {
  observableArray.push(Observable.of('Value ' + i));
}

Observable.from(observableArray)
  .concatAll()
  .subscribe(console.log, null, () => console.log('completed'));
</code>```

The Observable.from() emits each Observable separately and concatAll() subscribes to each one of them in the order they were emitted.

This demo prints to console the following output:

```<code>Value 0
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
completed
</code>```

Body:
I am working on a project (Angular2) where I am creating Observables dynamically and putting them in an array

var ObservableArray : Observable<any>[] = [];
//filling up Observable array dynamically
for (var i = 0; i < this.mainPerson.children.length; i++) {
ObservableArray.push(Observable.fromPromise(this.determineFate(this.mainPerson.children[i])));
  }
}

var finalObservable: Observable<any> = Observable.concat(ObservableArray);

finalObservable
  .subscribe( data => {
    //here  I expected to execute determineFate() for all observables inside array
    console.log("determine fate resolved data returned [" + data + "]");
  }, error => {
    console.error("error on Age Year for Characters")
  },() => {
    //Here I expect this gets executed only when all Observables inside my array finishes
    console.log("determine fate resolved data returned COMPLETED");
    //DB call
  });

  determineFate(..): Promise<boolean> {
       ...
       return either true / false if success or error;

 }

I want to execute all observables in a series (forkJoin seems to run in parallel - so used concat). Once all observables are executed, want to execute some DB related code. But it seems my code inside 'Completed' block does not wait for all Observables to finish. How can I achieve this?

Thanks in advance

Body:
Using Observable.concat(ObservableArray) will just flatten the array and emit each Observable from ObservableArray one by one. Btw, using the static version of concat makes sense only with two or more parameters (see http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-concat).

Instead you can iterate the array of Observables and wait until they complete one by one with the concatAll() operator.

This example simulates your use-case:

var observableArray = [];
// filling up Observable array dynamically
for (var i = 0; i < 10; i++) {
  observableArray.push(Observable.of('Value ' + i));
}

Observable.from(observableArray)
  .concatAll()
  .subscribe(console.log, null, () => console.log('completed'));

The Observable.from() emits each Observable separately and concatAll() subscribes to each one of them in the order they were emitted.

This demo prints to console the following output:

Value 0
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
completed


问:
How can you return status code 404 from angular PageNotFoundComponent?
My understanding is that you can customize the not found page by setting { path: '**', component: PageNotFoundComponent } to RouterMoudle.forRoot(routes).

However it returns http status code 200.
How can you return status code 404?

答:
Actually it does not return any status, that page should be bundled with your app, so you won't get any status because there is no request.

There is no point in sending a 404 status as there is no real request when you are changing page in an angular application (as it is a single page application).

Even if your 404 page is located in a lazy-loaded module, you must get the 200 status because the bundle is correctly loaded. Plus, you cannot change the status of a request on client side.

If you use server-side rendering (using angular universal), then your server might be able to send a 404 status on page load, but that would not be while the user browser from one page to another one which does not exist.


问:
SoapFault Exception: [Client] SOAP-ERROR: Encoding: object has no 'user_name' property
I am having some trouble issuing a SoapClient call using PHP, and I'm getting the error you're seeing in the title.

I am pretty sure it's something "small" I'm missing, but I checked similar questions and no answer found for my problem.

Let's get straight to the code:

```<code>    $client = new SoapClient("path_to_wsdl");
    var_dump($client->__getFunctions()[1]);
    var_dump($client->__getTypes()[73]);

   //I need to call function in position [1], which is login, and I need to declare struct in position [73], user_auth

    class user_auth {
        function user_auth($username, $password) {
            $this->user_name = $username;
            $this->password = md5($password);
            $this->version = 1;
        }
    }
    $user = new user_auth("username", "password");
    $params = array("user_auth" => $user);
    print_r($params);
    $response =$client->login(array($params)); //This is where I get the exception!
</code>```

What I get from running this PHP is:

string(70) "set_entry_result login(user_auth $user_auth, string $application_name)"

string(74) "struct user_auth { string user_name; string password; string version; }"

Array ( [user_auth] => user_auth Object ( [user_name] => username [password] => md5(password) [version] => 1 ) )

So the error is that in Object, I don't have "user_name" field, but it looks like I have it!

Hope you guys can give me some help about this.

Sincerely,

Andrea

答:
Here's how it's solved, look at the differences in code:</p>

```<code>$client = new SoapClient("path_to_wsdl");

class user_auth {
    function user_auth($username, $password) {
        $this->user_name = $username;
        $this->password = md5($password);
        $this->version = 1;
    }
}
$user = new user_auth("username", "password");
$params = array($user);
$response =$client->__soapCall("login",$params); //Now working!
</code>```

Body:
I am having some trouble issuing a SoapClient call using PHP, and I'm getting the error you're seeing in the title.

I am pretty sure it's something "small" I'm missing, but I checked similar questions and no answer found for my problem.

Let's get straight to the code:

    $client = new SoapClient("path_to_wsdl");
    var_dump($client->__getFunctions()[1]);
    var_dump($client->__getTypes()[73]);

   //I need to call function in position [1], which is login, and I need to declare struct in position [73], user_auth

    class user_auth {
        function user_auth($username, $password) {
            $this->user_name = $username;
            $this->password = md5($password);
            $this->version = 1;
        }
    }
    $user = new user_auth("username", "password");
    $params = array("user_auth" => $user);
    print_r($params);
    $response =$client->login(array($params)); //This is where I get the exception!

What I get from running this PHP is:

string(70) "set_entry_result login(user_auth $user_auth, string $application_name)"

string(74) "struct user_auth { string user_name; string password; string version; }"

Array ( [user_auth] => user_auth Object ( [user_name] => username [password] => md5(password) [version] => 1 ) )

So the error is that in Object, I don't have "user_name" field, but it looks like I have it!

Hope you guys can give me some help about this.

Sincerely,

Andrea

Body:
Here's how it's solved, look at the differences in code:

$client = new SoapClient("path_to_wsdl");

class user_auth {
    function user_auth($username, $password) {
        $this->user_name = $username;
        $this->password = md5($password);
        $this->version = 1;
    }
}
$user = new user_auth("username", "password");
$params = array($user);
$response =$client->__soapCall("login",$params); //Now working!


问:
How to set time to 24 hour format in Calendar
I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

```<code>  SimpleDateFormat df = new SimpleDateFormat("kk:mm");
  Date d1 = df.parse("10:30");
  Calendar c1 = Calendar.getInstance();
  c1.set(Calendar.HOUR, d1.getHours());
  c1.set(Calendar.MINUTE, d1.getMinutes());
</code>```

The date should be today's date and the time set to 10:30. Instead the time in c1 ends up being 22:30. How can I force the calendar control to recognize my time is 24 hour format?

EDIT:
If I just do this:

```<code>Calendar c1 = Calendar.getInstance();
c1.set(Calendar.HOUR, 10);
c1.set(Calendar.MINUTE, 30);
</code>```

This gives me the same result. Why?

答:
Here you will get all kinds of time related problems. I hope this will solve your problem.</p>

```<code>public class MyClass {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23)
            k Hour in day (1-24)
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}
</code>```

Body:
I need to set the time on the current date. The time string is always in 24 hour format but the result I get is wrong:

  SimpleDateFormat df = new SimpleDateFormat("kk:mm");
  Date d1 = df.parse("10:30");
  Calendar c1 = Calendar.getInstance();
  c1.set(Calendar.HOUR, d1.getHours());
  c1.set(Calendar.MINUTE, d1.getMinutes());

The date should be today's date and the time set to 10:30. Instead the time in c1 ends up being 22:30. How can I force the calendar control to recognize my time is 24 hour format?

EDIT:
If I just do this:

Calendar c1 = Calendar.getInstance();
c1.set(Calendar.HOUR, 10);
c1.set(Calendar.MINUTE, 30);

This gives me the same result. Why?

Body:
Here you will get all kinds of time related problems. I hope this will solve your problem.

public class MyClass {

    public static void main(String[] args) {

        Calendar cal = Calendar.getInstance();

        // To get the current hour
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        System.out.println("hour: " + hour);

        // To get the current time in 12 hours format
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a",Locale.US);
        String a = sdf.format(cal.getTime());
        System.out.println("Time: " + a);

        // To get the desired time in 12 hours format from 23 hours format
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a",Locale.ENGLISH);
        String a1 = sdf1.format(cal.getTime());
        System.out.println("Time: " + a1);

        /*  H Hour in day (0-23)
            k Hour in day (1-24)
        */

        //To get the desired time in 24 hours format as 0-23 or 1-24
        cal.set(Calendar.HOUR_OF_DAY, 24);
        SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm",Locale.ENGLISH);
        SimpleDateFormat sdf3 = new SimpleDateFormat("kk:mm",Locale.ENGLISH);
        String a2 = sdf2.format(cal.getTime());
        String a3 = sdf3.format(cal.getTime());
        System.out.println("Time: " + a2);
        System.out.println("Time: " + a3);

        //For example, time like 12:30 PM. How can i convert to 24 hours time in java?

        SimpleDateFormat bigFormat = new SimpleDateFormat("kk:mm");
        SimpleDateFormat smallFormat = new SimpleDateFormat("hh:mm a");

        Date date = null;
        try {
            date = smallFormat.parse("12:30 AM");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println(smallFormat.format(date) + " = " + bigFormat.format(date));

    }

}


问:
Entity Framework Code First and Identity
I have a three layer project(DAL, Domain, MVC). I need to bound AuthorEntity from the DAL with ApplicationUser, which is in the MVC project.

They have a different context(EfContext, ApplicationDbContext).

First, I created a UserEntity and tried to implement IUser, which has string field Id (sting Id{get;}), I got an error:

"EntityType 'UserEntity' has no key defined.Define the key for this
  EntityType"

I add attributes:

```<code>[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
</code>```

It's not working. How to do this?

答:
Primary Key property must be readable and writable.</p>

```<code>[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id{get;set;}
</code>```

Body:
I have a three layer project(DAL, Domain, MVC). I need to bound AuthorEntity from the DAL with ApplicationUser, which is in the MVC project.

They have a different context(EfContext, ApplicationDbContext).

First, I created a UserEntity and tried to implement IUser, which has string field Id (sting Id{get;}), I got an error:

"EntityType 'UserEntity' has no key defined.Define the key for this
  EntityType"

I add attributes:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]

It's not working. How to do this?

Body:
Primary Key property must be readable and writable.

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id{get;set;}


答:
Angular applications are just HTTP clients, not servers. So a component cannot return an HTTP code. To get to the PageNotFoundComponent, the application must be correctly loaded (HTTP 200).

From the perspective of the application, nothing wrong happened, just a user requested a route that falls back to the PageNotFoundComponent and it has nothing to do with HTTP.

Title: How can you return status code 404 from angular PageNotFoundComponent?

Body:
My understanding is that you can customize the not found page by setting { path: '**', component: PageNotFoundComponent } to RouterMoudle.forRoot(routes).

However it returns http status code 200.
How can you return status code 404?


问:
check if a lat long is within an extent using open layers 3
I have a UK county shape file (Multipolygon) using EPSG:4326 in my geoserver. I'm using open layers 3 to load this shape file in my application as below :

```<code>source = new ol.source.XYZ({url: '/gmaps?zoom={z}&x={x}&y={y}&Layers=UKCounties', crossOrigin: "anonymous"});
countiesLayer = new ol.layer.Tile({source: source});
map.addLayer(countiesLayer);
</code>```

This works well. I have a requirement to get users current location which is done as

```<code>var coordinate = geolocation.getPosition();
</code>```

I'm able to retrieve the correct lat & long here. Ex : Lat = 53.797534899999995, Lng = -1.5449. now I need to check which of the counties (polygon) these points are in using open layers 3 & Javascript.
Using Geoserver WFS, I'm able to get the bounding box of each of the counties as

```<code>$.each(features, function(index, eachFeature) {
            var bbox = eachFeature.properties.bbox;
            if (bbox != null) {
              var bottomLeft = ([bbox[0], bbox[1]]);
              var topRight = ([bbox[2], bbox[3]]);
              var extent = new ol.extent.boundingExtent([bottomLeft, topRight]);

            if (ol.extent.containsXY(extent1,lat,long)) {
                alert("got the feature");
            }
        }

});
</code>```

The issue is my code doesn't print the alert statement.I've also tried using

```<code>if (ol.extent.containsXY(extent,long,lat))
</code>```

and

```<code>var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
</code>```

if (ol.extent.containsXY(extent,XY[0],XY[1]))
if (ol.extent.containsXY(extent,XY[1],XY[0]))

But none of these print the alert. Is there anything wrong in this?

答:
Before answering your question, I did not know the method of "ol.extent.containsXY".
I used my poor logic! I detected a feature if in a polygon by follwing :

transform feature and container(polygon) to coordinate [lon, lat]

detect the container if contain the feature

extent array rule [minLon, minLat, maxLon, maxLat]

code snippet: (my destinationPro:'EPSG:3857', sourcePro:'EPSG:4326')

```<code>QyGIS.prototype.isInner = function(featureExtent, containerExtent) {
    var featureLonLat = ol.proj.transformExtent(featureExtent, destinationPro, sourcePro);
    var containerLonLat = ol.proj.transformExtent(containerExtent, destinationPro, sourcePro);
    // in my condition, the feature is a point, so featureLonLat[0] = featureLonLat[2], featureLonLat[1] = featureLonLat[3]. what's more extent have four value in a array so the loop length is 4
    for (var i = 0; i < featureLonLat.length; i++) {
    /* actually:
     featureLonLat[0] < containerLonLat[0] || featureLonLat[0] > containerLonLat[2]
     featureLonLat[1] < containerLonLat[1] || featureLonLat[1] > containerLonLat[3]
     featureLonLat[2] < containerLonLat[0] || featureLonLat[2] > containerLonLat[2]
     featureLonLat[3] < containerLonLat[1] || featureLonLat[3] > containerLonLat[3]
    */
        if (featureLonLat[i] < containerLonLat[i % 2] || featureLonLat[i] > containerLonLat[i % 2 + 2]) {
            return false;
        }
    }
    return true;
};

QyGIS.prototype.getInnerFeatures = function(layerName, extent) {
    var self = this;
    var layer = self.getLayer(layerName);
    if (layer) {
        var source = layer.getSource();
        var features = source.getFeatures();
        for (var i = 0; i < features.length; i++) {
            var curFeatureExtent = features[i].getGeometry().getExtent();
            if (self.isInner(curFeatureExtent, extent)) {
                console.log(features[i].get('name') + 'in area');
            }
        }
    }
};
</code>```

At last, sorry for my poor english if my answer confuse you .

Body:
I have a UK county shape file (Multipolygon) using EPSG:4326 in my geoserver. I'm using open layers 3 to load this shape file in my application as below :

source = new ol.source.XYZ({url: '/gmaps?zoom={z}&x={x}&y={y}&Layers=UKCounties', crossOrigin: "anonymous"});
countiesLayer = new ol.layer.Tile({source: source});
map.addLayer(countiesLayer);

This works well. I have a requirement to get users current location which is done as

var coordinate = geolocation.getPosition();

I'm able to retrieve the correct lat & long here. Ex : Lat = 53.797534899999995, Lng = -1.5449. now I need to check which of the counties (polygon) these points are in using open layers 3 & Javascript.
Using Geoserver WFS, I'm able to get the bounding box of each of the counties as

$.each(features, function(index, eachFeature) {
            var bbox = eachFeature.properties.bbox;
            if (bbox != null) {
              var bottomLeft = ([bbox[0], bbox[1]]);
              var topRight = ([bbox[2], bbox[3]]);
              var extent = new ol.extent.boundingExtent([bottomLeft, topRight]);

            if (ol.extent.containsXY(extent1,lat,long)) {
                alert("got the feature");
            }
        }

});

The issue is my code doesn't print the alert statement.I've also tried using

if (ol.extent.containsXY(extent,long,lat))

and

var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');

if (ol.extent.containsXY(extent,XY[0],XY[1]))
if (ol.extent.containsXY(extent,XY[1],XY[0]))

But none of these print the alert. Is there anything wrong in this?

Body:
Before answering your question, I did not know the method of "ol.extent.containsXY".
I used my poor logic! I detected a feature if in a polygon by follwing :

transform feature and container(polygon) to coordinate [lon, lat]

detect the container if contain the feature

extent array rule [minLon, minLat, maxLon, maxLat]

code snippet: (my destinationPro:'EPSG:3857', sourcePro:'EPSG:4326')

QyGIS.prototype.isInner = function(featureExtent, containerExtent) {
    var featureLonLat = ol.proj.transformExtent(featureExtent, destinationPro, sourcePro);
    var containerLonLat = ol.proj.transformExtent(containerExtent, destinationPro, sourcePro);
    // in my condition, the feature is a point, so featureLonLat[0] = featureLonLat[2], featureLonLat[1] = featureLonLat[3]. what's more extent have four value in a array so the loop length is 4
    for (var i = 0; i < featureLonLat.length; i++) {
    /* actually:
     featureLonLat[0] < containerLonLat[0] || featureLonLat[0] > containerLonLat[2]
     featureLonLat[1] < containerLonLat[1] || featureLonLat[1] > containerLonLat[3]
     featureLonLat[2] < containerLonLat[0] || featureLonLat[2] > containerLonLat[2]
     featureLonLat[3] < containerLonLat[1] || featureLonLat[3] > containerLonLat[3]
    */
        if (featureLonLat[i] < containerLonLat[i % 2] || featureLonLat[i] > containerLonLat[i % 2 + 2]) {
            return false;
        }
    }
    return true;
};

QyGIS.prototype.getInnerFeatures = function(layerName, extent) {
    var self = this;
    var layer = self.getLayer(layerName);
    if (layer) {
        var source = layer.getSource();
        var features = source.getFeatures();
        for (var i = 0; i < features.length; i++) {
            var curFeatureExtent = features[i].getGeometry().getExtent();
            if (self.isInner(curFeatureExtent, extent)) {
                console.log(features[i].get('name') + 'in area');
            }
        }
    }
};

At last, sorry for my poor english if my answer confuse you .


问:
How GoToMeeting validate desktop software installed in order to host session
Looking for a Technique where I can install my software on a windows PC and check using javascript that if the software is installed.

If installed launch it. If not installed download it.

The hint I got is to add custom font or mime type and then check it something like this - https://www.samclarke.com/javascript-is-font-available/

答:
That is a protocol handler.

How the check works,

It execute a custom schema url. For example.

executing the magnet:// will redirect you to torrent application if installed. Else, redirect you to google. Here, in the place of google, you can use the protocol handler to redirect to the setup file.

From mobile, executing whatsapp:// will Open whatsapp if installed.

Check the below snippet.

Running it will prompt to Open the torrent application.

function utorrent_test(){
  return window.location.href="magnet://";
}
var result=utorrent_test();
console.log(result);```

Read more about protocol handler in MDN

Also read in detail here https://html.spec.whatwg.org/multipage/webappapis.html#custom-handlers

Body:
That is a protocol handler.

How the check works,

It execute a custom schema url. For example.

executing the magnet:// will redirect you to torrent application if installed. Else, redirect you to google. Here, in the place of google, you can use the protocol handler to redirect to the setup file.

From mobile, executing whatsapp:// will Open whatsapp if installed.

Check the below snippet.

Running it will prompt to Open the torrent application.

function utorrent_test(){
  return window.location.href="magnet://";
}
var result=utorrent_test();
console.log(result);

Read more about protocol handler in MDN

Also read in detail here https://html.spec.whatwg.org/multipage/webappapis.html#custom-handlers


问:
Drawer not covering header in react-navigation
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

```<code>import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);
</code>```

Other problem is how should I add 2 drawers in my app at the same screen

答:
Here is a simplified example:

const FooStackNavigator = StackNavigator({
  Foo: {
    screen: FooScreen,
    navigationOptions: {
      title: 'Foo',
    }
  },
});
const BarStackNavigator = StackNavigator({...});

const MyDrawerNavigator = DrawerNavigator({
  FooStack: {
    screen: FooStackNavigator,
    navigationOptions: {
      drawer: () => ({
        label: 'Foo',
      })
    },
  },
  BarStack: {
    screen: BarStackNavigator,
    navigationOptions: {
      drawer: () => ({
        label: 'Bar',
      })
    },
  }
});

const AppNavigator = StackNavigator({
  Drawer: { screen: MyDrawerNavigator },
}, {
  headerMode: 'none',
});
```

Body:
Hi friends I am scratching my head with react-navigation from last 2 days, I tried many things(documentation doesn't seems that clear for a beginner), so right now I am facing few problem that seems little complex to me and hence I seek advice and help to proceed further.following are the cases/problem/scenario I seek help for -

react-navigation does not cover the header and statusbar, I wanted to achieve something like gmail but I ended up with like this

I used following code blocks to reach to this point

import React, {Component} from 'react';
import { AppRegistry, View, BackAndroid, StatusBar,} from 'react-native';
import {
  NavigationActions,
  addNavigationHelpers,
  StackNavigator,
  DrawerNavigator
} from 'react-navigation';

import LandingScreen from 'src/screens/landingScreen';
import Login from 'src/screens/login'
import SignUp from 'src/screens/signUp'
import ForgotPassword from 'src/screens/forgotPassword'
import Dashboard from 'src/screens/dashboard'
import UserProfile from 'src/screens/userProfile'

export const Drawer = DrawerNavigator({
  Dashboard:{
    path:'/',
    screen:Dashboard,
  },
  UserProfile:{
    path:'/'
    screen:UserProfile
  },
}, {
  initialRouteName: 'Dashboard',
  contentOptions: {
    activeTintColor: '#e91e63',
  },
  headerMode: 'screen',
});

const routesConfig = {
  Landing:{screen:LandingScreen},
  Login: { screen: Login },
  SignUp: { screen: SignUp },
  ForgotPassword: { screen: ForgotPassword },
  Drawer:{screen:Drawer}
};

export const AppNavigator = StackNavigator(routesConfig, {
  initialRouteName: 'Drawer'
});
AppRegistry.registerComponent('Riduk', () => AppNavigator);

Other problem is how should I add 2 drawers in my app at the same screen


问:
Why does Rails titlecase add a space to a name?
Why does the titlecase mess up the name? I have:

```<code>John Mark McMillan
</code>```

and it turns it into:

```<code>>> "john mark McMillan".titlecase
=> "John Mark Mc Millan"
</code>```

Why is there a space added to the last name?

Basically I have this in my model:

```<code>before_save :capitalize_name

def capitalize_name
  self.artist = self.artist.titlecase
end
</code>```

I am trying to make sure that all the names are titlecase in the DB, but in situtations with a camelcase name it fails. Any ideas how to fix this?

答:
If you want to handle the case where someone has entered JOHN CAPSLOCK JOE as well as the others, I combined this one:

```<code>class String
  def proper_titlecase
    if self.titleize.split.length == self.split.length
      self.titleize
    else
      self.split(" ").collect{|word| word[0] = word[0].upcase; word}.join(" ")
    end
  end
end
</code>```

Depends if you want that kinda logic on a String method ;)

Body:
Why does the titlecase mess up the name? I have:

John Mark McMillan

and it turns it into:

>> "john mark McMillan".titlecase
=> "John Mark Mc Millan"

Why is there a space added to the last name?

Basically I have this in my model:

before_save :capitalize_name

def capitalize_name
  self.artist = self.artist.titlecase
end

I am trying to make sure that all the names are titlecase in the DB, but in situtations with a camelcase name it fails. Any ideas how to fix this?

Body:
If you want to handle the case where someone has entered JOHN CAPSLOCK JOE as well as the others, I combined this one:

class String
  def proper_titlecase
    if self.titleize.split.length == self.split.length
      self.titleize
    else
      self.split(" ").collect{|word| word[0] = word[0].upcase; word}.join(" ")
    end
  end
end

Depends if you want that kinda logic on a String method ;)


问:
Apply Middleware to all routes except `setup/*` in Laravel 5.4
I'm experimenting with Middleware in my Laravel application. I currently have it set up to run on every route for an authenticated user, however, I want it to ignore any requests that begin with the setup URI.

Here is what my CheckOnboarding middleware method looks like:

```<code>public function handle($request, Closure $next)
{
    /**
    * Check to see if the user has completed the onboarding, if not redirect.
    * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
    */
    if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
        return redirect('setup');
    } else {
        return $next($request);
    }
}
</code>```

This is being used in my routes like this:

```<code>Route::group(['middleware' => ['auth','checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});
</code>```

Now, if I go to /home or /account I get redirected to /setup as you would expect. This originally caused a redirect loop error hence why & $request->path() != 'setup' is in the Middleware.

I feel like this is a really clunky way of doing it, and obviously doesn't match anything after setup like the setup/settings route I have created.

Is there a better way to have this Middleware run on all routes for a user, but also set certain routes that should be exempt from this check?

答:
Routes on which you dont want the middleware to run , simply put them outside of the function:</p>

```<code>//here register routes on which you dont want the middleware: checkOnboarding
Route::group(['middleware' => ['auth','checkOnboarding']], function () {
     //routes on which you want the middleware
});
</code>```

Body:
I'm experimenting with Middleware in my Laravel application. I currently have it set up to run on every route for an authenticated user, however, I want it to ignore any requests that begin with the setup URI.

Here is what my CheckOnboarding middleware method looks like:

public function handle($request, Closure $next)
{
    /**
    * Check to see if the user has completed the onboarding, if not redirect.
    * Also checks that the requested URI isn't the setup route to ensure there isn't a redirect loop.
    */
    if ($request->user()->onboarding_complete == false && $request->path() != 'setup') {
        return redirect('setup');
    } else {
        return $next($request);
    }
}

This is being used in my routes like this:

Route::group(['middleware' => ['auth','checkOnboarding']], function () {
    Route::get('/home', 'HomeController@index');
    Route::get('/account', 'AccountController@index');

    Route::group(['prefix' => 'setup'], function () {
        Route::get('/', 'OnboardingController@index')->name('setup');
        Route::post('/settings', 'SettingsController@store');
    });
});

Now, if I go to /home or /account I get redirected to /setup as you would expect. This originally caused a redirect loop error hence why & $request->path() != 'setup' is in the Middleware.

I feel like this is a really clunky way of doing it, and obviously doesn't match anything after setup like the setup/settings route I have created.

Is there a better way to have this Middleware run on all routes for a user, but also set certain routes that should be exempt from this check?

Body:
Routes on which you dont want the middleware to run , simply put them outside of the function:

//here register routes on which you dont want the middleware: checkOnboarding
Route::group(['middleware' => ['auth','checkOnboarding']], function () {
     //routes on which you want the middleware
});


问:
Is it possible to use the instanceof operator in a switch statement?
I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

```<code>if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():
</code>```

How would it be implemented using switch...case?

答:
If you need to "switch" thru the class type of "this" object, this answer is the best https://stackoverflow.com/a/5579385/2078368

But if you need to apply "switch" to any other variable. I would suggest another solution. Define following interface:

```<code>public interface ClassTypeInterface {
    public String getType();
}
</code>```

Implement this interface in every class you want to "switch". Example:

```<code>public class A extends Something implements ClassTypeInterface {

    public final static String TYPE = "A";

    @Override
    public String getType() {
        return TYPE;
    }
}
</code>```

After that you can use it in following way:

```<code>switch (var.getType()) {
    case A.TYPE: {
        break;
    }
    case B.TYPE: {
        break;
    }
    ...
}
</code>```

The only thing you should care about - keep the "types" unique across all the classes implementing the ClassTypeInterface. It's not a big problem, because in case of any intersection you receive a compile-time error for the "switch-case" statement.

ContentLicense: CC BY-SA 4.0

Body:
I have a question of using switch case for instanceof object:

For example: my problem can be reproduced in Java:

if(this instanceof A)
    doA();
else if(this instanceof B)
    doB();
else if(this instanceof C)
    doC():

How would it be implemented using switch...case?

Body:
If you need to "switch" thru the class type of "this" object, this answer is the best https://stackoverflow.com/a/5579385/2078368

But if you need to apply "switch" to any other variable. I would suggest another solution. Define following interface:

public interface ClassTypeInterface {
    public String getType();
}

Implement this interface in every class you want to "switch". Example:

public class A extends Something implements ClassTypeInterface {

    public final static String TYPE = "A";

    @Override
    public String getType() {
        return TYPE;
    }
}

After that you can use it in following way:

switch (var.getType()) {
    case A.TYPE: {
        break;
    }
    case B.TYPE: {
        break;
    }
    ...
}

The only thing you should care about - keep the "types" unique across all the classes implementing the ClassTypeInterface. It's not a big problem, because in case of any intersection you receive a compile-time error for the "switch-case" statement.


问:
Configure .bash_profile on linux (CENTOS) for multiple ORACLE HOMEs
I am using a server with CENTOS 5.11 and for different circumstances I need to use two versions of Oracle. I have already installed Oracle 10g successfully, however I want to install the 12c, in part to migrate my DB.

The problem is that I do not know how to configure the .bash_profile which is where the ORACLE_HOME is configured in the following way:

```<code>    ## Oracle Env Settings
    export TMP=/tmp
    export TMPDIR=$TMP
    export ORACLE_HOSTNAME=oracle.localdomain
    export ORACLE_UNQNAME=MYDB
    export ORACLE_BASE=/u01/app/oracle
    export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
    export ORACLE_SID=MYDB
    export PATH=/usr/sbin:$PATH
    export PATH=$ORACLE_HOME/bin:$PATH
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
    export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
</code>```

I have searched and in the documentation of Oracle only mention that to install another version just need to install it in another ORACLE_HOME. So, my question is, how to add the new ORACLE_HOME in .bash_profile? and likewise if I can use the same users and groups for the new installation.

答:
Write two functions to switch between the two installations.

```<code>export SYS_PATH=$PATH
export TMP=/tmp
export TMPDIR=$TMP

## First Oracle Env Settings
ora1 ()
{
  export ORACLE_HOSTNAME=oracle1.localdomain
  export ORACLE_UNQNAME=MYDB1
  export ORACLE_BASE=/u01/app/oracle
  export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
  export ORACLE_SID=MYDB1
  export PATH=/usr/sbin:$SYS_PATH
  export PATH=$ORACLE_HOME/bin:$PATH
  export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
  export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
}

## Second Oracle Env Settings
ora2 ()
{
  export ORACLE_HOSTNAME=oracle2.localdomain
  export ORACLE_UNQNAME=MYDB2
  export ORACLE_BASE=/u02/app/oracle
  export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_2
  export ORACLE_SID=MYDB2
  export PATH=/usr/sbin:$SYS_PATH
  export PATH=$ORACLE_HOME/bin:$PATH
  export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
  export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
}
</code>```

Use your default:

```<code>ora1
</code>```

And switch to another:

```<code>ora2
</code>```

And switch back:

```<code>ora1
</code>```

Body:
I am using a server with CENTOS 5.11 and for different circumstances I need to use two versions of Oracle. I have already installed Oracle 10g successfully, however I want to install the 12c, in part to migrate my DB.

The problem is that I do not know how to configure the .bash_profile which is where the ORACLE_HOME is configured in the following way:

    ## Oracle Env Settings
    export TMP=/tmp
    export TMPDIR=$TMP
    export ORACLE_HOSTNAME=oracle.localdomain
    export ORACLE_UNQNAME=MYDB
    export ORACLE_BASE=/u01/app/oracle
    export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
    export ORACLE_SID=MYDB
    export PATH=/usr/sbin:$PATH
    export PATH=$ORACLE_HOME/bin:$PATH
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
    export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib

I have searched and in the documentation of Oracle only mention that to install another version just need to install it in another ORACLE_HOME. So, my question is, how to add the new ORACLE_HOME in .bash_profile? and likewise if I can use the same users and groups for the new installation.

Body:
Write two functions to switch between the two installations.

export SYS_PATH=$PATH
export TMP=/tmp
export TMPDIR=$TMP

## First Oracle Env Settings
ora1 ()
{
  export ORACLE_HOSTNAME=oracle1.localdomain
  export ORACLE_UNQNAME=MYDB1
  export ORACLE_BASE=/u01/app/oracle
  export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_1
  export ORACLE_SID=MYDB1
  export PATH=/usr/sbin:$SYS_PATH
  export PATH=$ORACLE_HOME/bin:$PATH
  export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
  export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
}

## Second Oracle Env Settings
ora2 ()
{
  export ORACLE_HOSTNAME=oracle2.localdomain
  export ORACLE_UNQNAME=MYDB2
  export ORACLE_BASE=/u02/app/oracle
  export ORACLE_HOME=$ORACLE_BASE/product/VERSION/db_2
  export ORACLE_SID=MYDB2
  export PATH=/usr/sbin:$SYS_PATH
  export PATH=$ORACLE_HOME/bin:$PATH
  export LD_LIBRARY_PATH=$ORACLE_HOME/lib:/lib:/usr/lib
  export CLASSPATH=$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib
}

Use your default:

ora1

And switch to another:

ora2

And switch back:

ora1


问:
I need stop my services when I killed or from recent app in Android
I am in need of stop all the service which I used in my app when I killed or remove from my recent apps in android. Is there any possible to determine ? </p>

答:
The Service class has an onTaskRemoved() method which is triggered when the app is removed from the recent apps.

There the Service can call stopSelf() to shut itself down.

As in:

```<code>/**
 * This is called if the service is currently running and the user has
 * removed a task that comes from the service's application.  If you have
 * set {@link ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
 * then you will not receive this callback; instead, the service will simply
 * be stopped.
 *
 * @param rootIntent The original root Intent that was used to launch
 *                   the task that is being removed.
 */
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    stopSelf();
}
</code>```

And then there's the exception that if the FLAG_STOP_WITH_TASK flag is used this callback isn't triggered, but the Service is automatically stopped when the app is killed. You may want to use onTaskRemoved() if you need to do something in the Service before finally stopping it.

Body:
The Service class has an onTaskRemoved() method which is triggered when the app is removed from the recent apps.

There the Service can call stopSelf() to shut itself down.

As in:

/**
 * This is called if the service is currently running and the user has
 * removed a task that comes from the service's application.  If you have
 * set {@link ServiceInfo#FLAG_STOP_WITH_TASK ServiceInfo.FLAG_STOP_WITH_TASK}
 * then you will not receive this callback; instead, the service will simply
 * be stopped.
 *
 * @param rootIntent The original root Intent that was used to launch
 *                   the task that is being removed.
 */
@Override
public void onTaskRemoved(Intent rootIntent) {
    super.onTaskRemoved(rootIntent);
    stopSelf();
}

And then there's the exception that if the FLAG_STOP_WITH_TASK flag is used this callback isn't triggered, but the Service is automatically stopped when the app is killed. You may want to use onTaskRemoved() if you need to do something in the Service before finally stopping it.


问:
How to replace string in files recursively via sed or awk?
I would like to know how to search from the command line for a string in various files of type .rb.

And replace:

```<code>.delay([ANY OPTIONAL TEXT FOR DELETION]).
</code>```

with

```<code>.delay.
</code>```

Besides sed an awk are there any other command line tools included in the OS that are better for the task?

Status

So far I have the following regular expression:

```<code>.delay\(*.*\)\.
</code>```

I would like to know how to match only the expression ending on the first closing parenthesis? And avoid replacing:

```<code>.delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param)
</code>```

Thanks in advance!

答:
For the part of the question where you want to only match and replace until the first ) and not include a second pair of (), here is how to change your regex:

```<code>.delay\(*.*\)\.
</code>```

->

```<code>\.delay\([^\)]*\)
</code>```

I.e. match "actual dot, delay, brace open, everything but brace close and brace close".

E.g. using sed:

```<code>>echo .delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param) | sed -E "s/\.delay\([^\)]*\)/.delay/"
</code>```

.delay.sometext(param)

I recommend to use grep for finding the right files:

```<code>grep -rl --include "*.rb" '\.delay' .
</code>```

Then feed the list into xargs, as recommended by other answers.

Credits to the other answers for providing a solution for feeding multiple files into sed.

Body:
I would like to know how to search from the command line for a string in various files of type .rb.

And replace:

.delay([ANY OPTIONAL TEXT FOR DELETION]).

with

.delay.

Besides sed an awk are there any other command line tools included in the OS that are better for the task?

Status

So far I have the following regular expression:

.delay\(*.*\)\.

I would like to know how to match only the expression ending on the first closing parenthesis? And avoid replacing:

.delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param)

Thanks in advance!

Body:
For the part of the question where you want to only match and replace until the first ) and not include a second pair of (), here is how to change your regex:

.delay\(*.*\)\.

->

\.delay\([^\)]*\)

I.e. match "actual dot, delay, brace open, everything but brace close and brace close".

E.g. using sed:

>echo .delay([ANY OPTIONAL TEXT FOR DELETION]).sometext(param) | sed -E "s/\.delay\([^\)]*\)/.delay/"

.delay.sometext(param)

I recommend to use grep for finding the right files:

grep -rl --include "*.rb" '\.delay' .

Then feed the list into xargs, as recommended by other answers.

Credits to the other answers for providing a solution for feeding multiple files into sed.


问:
Is it possible to run C++ binded with SDL+OpenGL code on a web browser?
My client wants her website to have an application that renders 3D (light 3D stuff, we are drawing only flat squares in 3D world) but web programming is not my thing. So I am looking for something that can run a C++ program from a web browser. But I think, if this is the case, then the client side must download the program first, and that's not what I want. The client should only be able to use this application only on the website.

I came across Google Native Client, which claims that it can run x86 native code in web applications. I haven't decide whether it is worth it or not and I don't know whether this is what I want or not, so I decided to ask experienced people about this.

If I want to have something like this, is what I said above possible? Or I completely need other languages like Flex because it does not worth the trouble? Or is Google Native Client suitable for doing something like this?

答:
I never thought you could do this without Native Client or plugins either, but recently discovered emscripten, and my mind was blown.

http://kripken.github.io/emscripten-site/

Emscripten is an LLVM-based project that compiles C and C++ into highly-optimizable JavaScript in asm.js format. This lets you run C and C++ on the web at near-native speed, without plugins.

Emscripten converts OpenGL into WebGL, and lets you use familiar APIs like SDL, or HTML5 directly.

ContentLicense: CC BY-SA 2.5


问:
OperationContext is null after async method using .net 4.6.2
I have a problem with OperationContext getting null after an async operation is called (and my threadid changes).

I know this is a know issue and I've gone threw some StackOverflow questions regarding the issue.

In .net 4.6.2 there is a fix for the issue as you can read here.

OperationContext.Current Async Improvements

WCF now has the ability to
  include OperationContext.Current with ExecutionContext so that the
  OperationContext flows through asynchronous continuations. With this
  improvement, WCF allows CurrentContext to propagate from one thread to
  another thread. This means that even if there’s a context switch
  between calls to OperationContext.Current, it’s value will flow
  correctly throughout the execution of the method.

Is there anything special I need to do in order to get this supported on my end? I'm using VS 2013, updated the framework to 4.6.2 and installed the dev-pack.
I've changed my project to use Framework 4.6.2 and I still get a null OperationContext after an async call.

答: After installing KB4013429 operation context async flow is disabled by default. To enable it (and use functionality fixed in 4.6.2) you need to set wcf:disableOperationContextAsyncFlow flag to "false" in your app config. (I haven't found any information about this flag, discovered it while fixing issue with incorrect propagation of OperationContext).</p>


问:
Am I leaking memory in my UIScrollView implementation?
I am working on an app which uses a UIScrollView to scroll through a bunch of slides. When the app opens, it creates the slides and passes them to the scroll view. My app also has a timer which causes the UIScrollView to scroll through the slides.

I also have a settings button. When I press on that button, it opens the settings panel. The timer is invalidated and set to nil. When the settings panel opens, the user can change things like the application theme, the slides and the animation direction.

When the settings panel is closed, the settings are applied: The slides are removed from the UIScrollView and the UIScrollView is given a new NSArray of slides to work with. The UIScrollView then lays out the new slides in the proper order and direction. The timer is reset.

Once, approximately every 14-16 times, the app crashes while running dismissAndRestart (the "close" code). I'm not sure why. I thought I was leaking memory, and apparently I am, but I don't see where.

Here's my code:

This runs on startup:

```<code>    - (void)viewDidLoad {
        [scrollView setPagingEnabled:YES];
    }

    - (void) viewWillAppear:(BOOL)animated{
        [self prepareViews];
        [self applyTheme];
    }

    - (void) viewDidAppear:(BOOL)animated{
        [self createTimerWithInterval:kScrollInterval];
    }
</code>```

Workhorse method that loads the views into the scroller. (It also removes the older ones):

```<code>- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
    [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [scrollView setShowsHorizontalScrollIndicator: NO];
    [scrollView setShowsVerticalScrollIndicator:NO];
    scrollView.scrollsToTop = NO;

    if([direction isEqualToString:@"horizontal"]){
        scrollView.frame = CGRectMake(0, 0, 1024, 768);
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
    }else if([direction isEqualToString:@"vertical"]){
        scrollView.frame = CGRectMake(0, 0, 1024, 768);
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
    }

    for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {

        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];

        if([direction isEqualToString:@"horizontal"]){
            [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
        }else if([direction isEqualToString:@"vertical"]){
            [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
        }

        [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
    }
}
</code>```

Create the timer for automated scrolling:

```<code>#pragma mark -
#pragma mark Create the Timer to automate scrolling

- (void) createTimerWithInterval:(float)interval{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(scrollWrapperForTimer) userInfo:nil repeats:YES];
}
</code>```

Wrapper function for the timer function. (This was necessary before the direction was an NSUserDefault, now I shouldn't need this.)

```<code>#pragma mark -
#pragma mark Scroll Automatically Every N seconds

- (void) scrollWrapperForTimer{
    [self scrollToNewViewInDirection:kDirection];
}

- (void)scrollToNewViewInDirection:(NSString *)direction{
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"animated_scrolling"] == YES){
        if([direction isEqualToString:@"horizontal"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x + scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }
        }else if([direction isEqualToString:@"vertical"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(0, scrollView.contentOffset.y + scrollView.frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }
        }
    }else {
        if([direction isEqualToString:@"horizontal"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x + scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }
        }else if([direction isEqualToString:@"vertical"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(0, scrollView.contentOffset.y + scrollView.frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }
        }
    }

}
</code>```

This method gets called when the done button is pressed in the setting panel.

```<code>#pragma mark -
#pragma mark Restart the program

- (void) dismissAndRestart{
    [self prepareViews];
    [self applyTheme];
    [self dismissModalViewControllerAnimated:YES];
    [self createTimerWithInterval:kScrollInterval];
}
</code>```

This creates the proper image files and loads them into place:

```<code>#pragma mark -
#pragma mark Apply the theme to the main view

- (void) applyTheme{

    //Front panel
    UIImage *frontImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_front", kTheme]description] ofType:@"png"]];
    [self.overlayImage setImage:frontImage];
    [frontImage release];

    //Back Panel
    if([kTheme isEqualToString:@"walnut"]){
        [self.backgroundImage setHidden:NO];
        UIImage *backImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_back", kTheme]description] ofType:@"png"]];
        [self.backgroundImage setImage:backImage];
        [backImage release];
    }else if([kTheme isEqualToString:@"metal"]){
        [self.backgroundImage setHidden:YES];
        [self.view setBackgroundColor: [UIColor scrollViewTexturedBackgroundColor]];
    }

    //Gabbai Button
    UIImage *gabbaiImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_settings_button", kTheme]description] ofType:@"png"]];
    [self.gabbaiButton setImage:gabbaiImage forState:UIControlStateNormal];
    [gabbaiImage release];

}
</code>```

Another wrapper function that needs to be refactored:

```<code>#pragma mark -
#pragma mark Slide View related

- (void) prepareViews{
    [self loadViews:[self createandReturnViews] IntoScroller:scrollView withDirection:kDirection];
}
</code>```

Creates the Array of slides to pass to the scroller:

```<code>//recreation of the views causes a delay each time the admin panel is closed.
- (NSArray*) createandReturnViews{

    NSMutableArray *announcements = [NSMutableArray array];
    NSArray *announcementsArray = [NSArray arrayWithObjects: @"Welcome to\nGabbai HD!",
                                   @"First slide",
                                   @"Second Slide",
                                   @"Third Slide",
                                   @"etc.",
                                   nil];
    for (int i = 0; i<[[NSNumber numberWithUnsignedInteger:[announcementsArray count]] intValue]; i++) {
        MBAnnouncementViewController *announcement = [[MBAnnouncementViewController alloc] initWithNibName:@"MBAnnouncementViewController" bundle:nil];
        [announcement setAnnouncementText:[announcementsArray objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntegerValue]]];
        [announcements addObject:announcement];
        [announcement release];
    }

    return announcements;
}
</code>```

Why would my settings panel be crashing the app on close?

答: You can also use xcode analyser using window+shift+a to find out memory leakage.</p>

Body:
I am working on an app which uses a UIScrollView to scroll through a bunch of slides. When the app opens, it creates the slides and passes them to the scroll view. My app also has a timer which causes the UIScrollView to scroll through the slides.

I also have a settings button. When I press on that button, it opens the settings panel. The timer is invalidated and set to nil. When the settings panel opens, the user can change things like the application theme, the slides and the animation direction.

When the settings panel is closed, the settings are applied: The slides are removed from the UIScrollView and the UIScrollView is given a new NSArray of slides to work with. The UIScrollView then lays out the new slides in the proper order and direction. The timer is reset.

Once, approximately every 14-16 times, the app crashes while running dismissAndRestart (the "close" code). I'm not sure why. I thought I was leaking memory, and apparently I am, but I don't see where.

Here's my code:

This runs on startup:

    - (void)viewDidLoad {
        [scrollView setPagingEnabled:YES];
    }

    - (void) viewWillAppear:(BOOL)animated{
        [self prepareViews];
        [self applyTheme];
    }

    - (void) viewDidAppear:(BOOL)animated{
        [self createTimerWithInterval:kScrollInterval];
    }

Workhorse method that loads the views into the scroller. (It also removes the older ones):

- (void)loadViews:(NSArray *)views IntoScroller:(UIScrollView *)scroller withDirection:(NSString *)direction{
    [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [scrollView setShowsHorizontalScrollIndicator: NO];
    [scrollView setShowsVerticalScrollIndicator:NO];
    scrollView.scrollsToTop = NO;

    if([direction isEqualToString:@"horizontal"]){
        scrollView.frame = CGRectMake(0, 0, 1024, 768);
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width * [[NSNumber numberWithUnsignedInt:[views count]] floatValue], scrollView.frame.size.height);
    }else if([direction isEqualToString:@"vertical"]){
        scrollView.frame = CGRectMake(0, 0, 1024, 768);
        scrollView.contentSize = CGSizeMake(scrollView.frame.size.width, scrollView.frame.size.height * [[NSNumber numberWithUnsignedInt:[views count]] floatValue]);
    }

    for (int i=0; i<[[NSNumber numberWithUnsignedInt:[views count]] intValue]; i++) {

        [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:scrollView.frame];

        if([direction isEqualToString:@"horizontal"]){
            [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height)];//CGRectMake(i * announcementView.view.frame.size.width, -scrollView.frame.origin.x, scrollView.frame.size.width, scrollView.frame.size.height)];
        }else if([direction isEqualToString:@"vertical"]){
            [[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view] setFrame:CGRectMake(0, i * [[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view].frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height)];
        }

        [scrollView addSubview:[[views objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntValue]] view]];
    }
}

Create the timer for automated scrolling:

#pragma mark -
#pragma mark Create the Timer to automate scrolling

- (void) createTimerWithInterval:(float)interval{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(scrollWrapperForTimer) userInfo:nil repeats:YES];
}

Wrapper function for the timer function. (This was necessary before the direction was an NSUserDefault, now I shouldn't need this.)

#pragma mark -
#pragma mark Scroll Automatically Every N seconds

- (void) scrollWrapperForTimer{
    [self scrollToNewViewInDirection:kDirection];
}

- (void)scrollToNewViewInDirection:(NSString *)direction{
    if([[NSUserDefaults standardUserDefaults] boolForKey:@"animated_scrolling"] == YES){
        if([direction isEqualToString:@"horizontal"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x + scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }
        }else if([direction isEqualToString:@"vertical"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(0, scrollView.contentOffset.y + scrollView.frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:YES];
            }
        }
    }else {
        if([direction isEqualToString:@"horizontal"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(scrollView.contentOffset.x + scrollView.frame.size.width, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.x] compare:[NSNumber numberWithFloat:scrollView.contentSize.width - scrollView.frame.size.width]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }
        }else if([direction isEqualToString:@"vertical"]){
            if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedAscending)){
                [scrollView scrollRectToVisible:CGRectMake(0, scrollView.contentOffset.y + scrollView.frame.size.height, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }else if([[NSNumber numberWithFloat:scrollView.contentOffset.y] compare:[NSNumber numberWithFloat:scrollView.contentSize.height - scrollView.frame.size.height]] == (NSOrderedSame)){
                [scrollView scrollRectToVisible:CGRectMake(0, 0, scrollView.frame.size.width, scrollView.frame.size.height) animated:NO];
            }
        }
    }

}

This method gets called when the done button is pressed in the setting panel.

#pragma mark -
#pragma mark Restart the program

- (void) dismissAndRestart{
    [self prepareViews];
    [self applyTheme];
    [self dismissModalViewControllerAnimated:YES];
    [self createTimerWithInterval:kScrollInterval];
}

This creates the proper image files and loads them into place:

#pragma mark -
#pragma mark Apply the theme to the main view

- (void) applyTheme{

    //Front panel
    UIImage *frontImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_front", kTheme]description] ofType:@"png"]];
    [self.overlayImage setImage:frontImage];
    [frontImage release];

    //Back Panel
    if([kTheme isEqualToString:@"walnut"]){
        [self.backgroundImage setHidden:NO];
        UIImage *backImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_back", kTheme]description] ofType:@"png"]];
        [self.backgroundImage setImage:backImage];
        [backImage release];
    }else if([kTheme isEqualToString:@"metal"]){
        [self.backgroundImage setHidden:YES];
        [self.view setBackgroundColor: [UIColor scrollViewTexturedBackgroundColor]];
    }

    //Gabbai Button
    UIImage *gabbaiImage = [[UIImage alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[NSString stringWithFormat:@"%@_settings_button", kTheme]description] ofType:@"png"]];
    [self.gabbaiButton setImage:gabbaiImage forState:UIControlStateNormal];
    [gabbaiImage release];

}

Another wrapper function that needs to be refactored:

#pragma mark -
#pragma mark Slide View related

- (void) prepareViews{
    [self loadViews:[self createandReturnViews] IntoScroller:scrollView withDirection:kDirection];
}

Creates the Array of slides to pass to the scroller:

//recreation of the views causes a delay each time the admin panel is closed.
- (NSArray*) createandReturnViews{

    NSMutableArray *announcements = [NSMutableArray array];
    NSArray *announcementsArray = [NSArray arrayWithObjects: @"Welcome to\nGabbai HD!",
                                   @"First slide",
                                   @"Second Slide",
                                   @"Third Slide",
                                   @"etc.",
                                   nil];
    for (int i = 0; i<[[NSNumber numberWithUnsignedInteger:[announcementsArray count]] intValue]; i++) {
        MBAnnouncementViewController *announcement = [[MBAnnouncementViewController alloc] initWithNibName:@"MBAnnouncementViewController" bundle:nil];
        [announcement setAnnouncementText:[announcementsArray objectAtIndex:[[NSNumber numberWithInt:i] unsignedIntegerValue]]];
        [announcements addObject:announcement];
        [announcement release];
    }

    return announcements;
}

Why would my settings panel be crashing the app on close?


问:
JavaFx comboBox JFoenix css
I am currently using jfoenix's combobox but my problem is that I can't edit the prompt text color inside of it. It keeps using the default color grey. How can I change the font color of the combobox from grey to white? Is there any way to do this in css?

This is how it looks like:

I hope you can help me out with this.

Thank you in advance.

答:
I am answering my own question for other people's reference. For some reason the font color of the Jfoenix combobox wasn't editable in css. So what I did instead is used the standard combobox provided and simply changed the css to make it look like the Jfoenix combobox.

This is the css style I used for combo-box:

```<code>.combo-box,
.choice-box {
    -fx-font-size: 12px;
    -fx-prompt-text-fill: black;
    -fx-text-fill: black;
    -fx-background-color: none;
    -fx-border-width: 0 0 1 0;
    -fx-border-color: #bdbdbd;
    -fx-padding: 0 0 3 -8;
}

.combo-box .list-cell:filled:selected .text,
.choice-box .list-cell:filled:selected .text {
    -fx-fill: black;
}

.combo-box .arrow,
.choice-box .arrow {
    -fx-background-color: #4d4d4d;
}
</code>```

Title: JavaFx comboBox JFoenix css

Body:
I am answering my own question for other people's reference. For some reason the font color of the Jfoenix combobox wasn't editable in css. So what I did instead is used the standard combobox provided and simply changed the css to make it look like the Jfoenix combobox.

This is the css style I used for combo-box:

.combo-box,
.choice-box {
    -fx-font-size: 12px;
    -fx-prompt-text-fill: black;
    -fx-text-fill: black;
    -fx-background-color: none;
    -fx-border-width: 0 0 1 0;
    -fx-border-color: #bdbdbd;
    -fx-padding: 0 0 3 -8;
}

.combo-box .list-cell:filled:selected .text,
.choice-box .list-cell:filled:selected .text {
    -fx-fill: black;
}

.combo-box .arrow,
.choice-box .arrow {
    -fx-background-color: #4d4d4d;
}


问:
How to transitionTo multiple views using angular ui.router
I'm having some issues with the ui.router.
I've defined what i thought were 3 states that i could flip between

```<code>$stateProvider
        .state('rackOrShelf', {
            url: '/information',
            templateUrl: 'Scripts/html/rackOrShelfPartial.html'
        }).state('door', {
            url: '/information',
            templateUrl: 'Scripts/html/doorPartial.html'
        }).state('frame', {
            url: '/information',
            templateUrl: 'Scripts/html/framePartial.html'
        });
</code>```

I've an html page that defines a header to display common stuff at the top. further down within div i have the ui-view placeholder

the html page defines an ng-controller that does some work and returns a json model, one of the parameters being a

```<code>model.Transiton = 'frame';
</code>```

which i then use to call this.
    $state.transitionTo(model.Transiton);

Problem is if model.Transition = 'rackOrShelf' or 'door' ui.router seems to work fine. but if i do model.Transition = 'frame' i always appear to get the contents of the door templateUrl? Why is this?

this is an SPA too.
and i use $routeProvider

```<code>$routeProvider
      .when("/main", {
          templateUrl: "Scripts/html/main.html",
          controller: "mainController"
      }).when("/information", {
          templateUrl: "Scripts/html/information.html",
          controller: "informationController",
          reloadOnSearch: false
      })
      .otherwise({ redirectTo: "/main" });
</code>```

so here is an update, this seems to work.

```<code>$stateProvider
        .state('empty', {
            template: '<div></div>'
        })
        .state('rackOrShelf', {
            templateUrl: 'Scripts/html/rackOrShelfPartial.html'
        }).state('door', {
            templateUrl: 'Scripts/html/doorPartial.html'
        }).state('frame', {
            templateUrl: 'Scripts/html/framePartial.html'
        }).state('information', {
            url: '/information',
            params: {partial: 'empty'},
            controller: function ($state) {
               $state.go($state.params.partial);
            }
        });
</code>```

And in my angular controller i have something like this.

```<code> $state.transitionTo('information', { partial:<'door' || 'frame' || 'rackOrShelf'> });
</code>```

答:
Angular Router allows us to handle that pretty well

I think nested states the solution.

Kindly check here:

Different states for same URL #217

Re-use a URL for states #1096

Body:
I'm having some issues with the ui.router.
I've defined what i thought were 3 states that i could flip between

$stateProvider
        .state('rackOrShelf', {
            url: '/information',
            templateUrl: 'Scripts/html/rackOrShelfPartial.html'
        }).state('door', {
            url: '/information',
            templateUrl: 'Scripts/html/doorPartial.html'
        }).state('frame', {
            url: '/information',
            templateUrl: 'Scripts/html/framePartial.html'
        });

I've an html page that defines a header to display common stuff at the top. further down within div i have the ui-view placeholder

the html page defines an ng-controller that does some work and returns a json model, one of the parameters being a

model.Transiton = 'frame';

which i then use to call this.
    $state.transitionTo(model.Transiton);

Problem is if model.Transition = 'rackOrShelf' or 'door' ui.router seems to work fine. but if i do model.Transition = 'frame' i always appear to get the contents of the door templateUrl? Why is this?

this is an SPA too.
and i use $routeProvider

$routeProvider
      .when("/main", {
          templateUrl: "Scripts/html/main.html",
          controller: "mainController"
      }).when("/information", {
          templateUrl: "Scripts/html/information.html",
          controller: "informationController",
          reloadOnSearch: false
      })
      .otherwise({ redirectTo: "/main" });

so here is an update, this seems to work.

$stateProvider
        .state('empty', {
            template: '

'
        })
        .state('rackOrShelf', {
            templateUrl: 'Scripts/html/rackOrShelfPartial.html'
        }).state('door', {
            templateUrl: 'Scripts/html/doorPartial.html'
        }).state('frame', {
            templateUrl: 'Scripts/html/framePartial.html'
        }).state('information', {
            url: '/information',
            params: {partial: 'empty'},
            controller: function ($state) {
               $state.go($state.params.partial);
            }
        });

And in my angular controller i have something like this.

 $state.transitionTo('information', { partial:<'door' || 'frame' || 'rackOrShelf'> });