问:
Find the Max and Min element out of all the nested arrays in javascript
I have a array like so:

```<code>var arr = [[12,45,75], [54,45,2],[23,54,75,2]];
</code>```

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

```<code>    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }
</code>```

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.

答:
Assuming ES6

const arr = [[12,45,75], [54,45,2],[23,54,75,2]];

const max = Math.max(...[].concat(...arr));

const min = Math.min(...[].concat(...arr));

console.log(max);

console.log(min);```

Body:
I have a array like so:

var arr = [[12,45,75], [54,45,2],[23,54,75,2]];

I want to find out the largest element and the smallest element out of all the elements in the nested array:

The min should be: 2

and

Max should be 75

I tried the functions below but they do not work:

    function Max(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let max = Math.max.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.max.apply(window, arrs[i].filter(f)))>max) max=m;
        }
        return max;
    }
    function Min(arrs)
    {
        if (!arrs || !arrs.length) return undefined;
        let min = Math.min.apply(window, arrs[0]), m,
            f = function(v){ return !isNaN(v); };
        for (let i = 1, l = arrs.length; i<l; i++) {
            if ((m = Math.min.apply(window, arrs[i].filter(f)))>min) min=m;
        }
        return min;
    }

It gives out Max as 75 and min as 12.

Any guidance will be appreciated.

Also tried other answers in SO but none help.

The answer at Merge/flatten an array of arrays in JavaScript? resolves the problem of merging arrays.

Whereas my problem is to keep the array as is and perform operations.


来源: stackexchange

答:
You can flatten the array first (advantage - will work for nested arrays at multiple levels)

```<code>var flattenedArr = [[12,45,75], [54,45,2],[23,54,75,2] ].toString().split(",").map(Number);
</code>```

Then get the min and max from the flattened array

```<code>var max = Math.max.apply( null, flattenedArr );
var min = Math.min.apply( null, flattenedArr );
</code>```

Demo

var flattenedArr = [
  [12, 45, 75],
  [54, 45, 2],
  [23, 54, 75, 2]
].toString().split(",").map(Number);

var max = Math.max.apply(null, flattenedArr);
var min = Math.min.apply(null, flattenedArr);

console.log(max, min);```

ContentLicense: CC BY-SA 3.0

Title: Find the Max and Min element out of all the nested arrays in javascript

Body:
You can flatten the array first (advantage - will work for nested arrays at multiple levels)

var flattenedArr = [[12,45,75], [54,45,2],[23,54,75,2] ].toString().split(",").map(Number);

Then get the min and max from the flattened array

var max = Math.max.apply( null, flattenedArr );
var min = Math.min.apply( null, flattenedArr );

Demo

var flattenedArr = [
  [12, 45, 75],
  [54, 45, 2],
  [23, 54, 75, 2]
].toString().split(",").map(Number);

var max = Math.max.apply(null, flattenedArr);
var min = Math.min.apply(null, flattenedArr);

console.log(max, min);


问:
Riak Cs Long manifest history
I am using riak-cs (s3) to store application configuration, which gets regenerated and updated every 10min per application context. I am getting these warnings:

Dec 04 14:53:12 hostname01 docker[8947]: Dec  4 14:53:12 hostname01 riak-cs[39]: [warning] <0.14295.2911>@riak_cs_manifest:maybe_warn_bloated_manifests:153 Long manifest history (51 manifests) for bucket=<<"production">> key=<<"routing/8f39843e-9d0c-47e7-9d04-80b9846c028d/7c48f790-0d38-4400-a447-189f271ca1fd/navigation_configuration">>

I have no idea what they really mean, I couldn't find any reference to this error in documentation

答:
Riak CS manages object binaries and thier manifests (something like inode). The manifests are retained in histories instead of only latest one. The old manifest entries are reclaimed in garbage collections (along with binaries.)

Riak CS is (originally) designed for large and almost static objects, so some configuration settings and internal structures are optimized for that.
As an example of such configuration, garbage collections clean up objects with more than 24-hour old.

Your objects are "very frequently" overwritten (in Riak CS's view point ;) ) and its history becomes "very" long , then the warning log was emitted.
As a general rule, overwriting object in 10 minutes interval is out of sweet spot of Riak CS.

However, if you know such overwriting will happen only for small objects, it's not bad. You can suppress warning logs by setting manifest_warn_history under riak_cs application larger value in advanced.config.

Title: Riak Cs Long manifest history


问:
Recovering implicit information from existentials in Coq
Suppose we have something like this:

Suppose x is a real number. Show that if there is a real number y such that (y + 1) / (y - 2) = x, then x <> 1".

If one formulates it in an obvious way: forall x : R, (exists y, ((y + 1) * / (y - 2)) = x) -> x <> 1, one runs into an issue very soon.

We have an assumption of existence of y such that ((y + 1) * / (y - 2)) = x). Am I wrong to assume that this should also imply that y <> 2? Is there a way to recover this information in Coq?

Surely, if such y exists, then it is not 2. How does one recover this information in Coq - do I need to explicitly assume it (that is, there is no way to recover it by existential instantiation somehow?).

Of course, destruct H as [y] just gives us ((y + 1) * / (y - 2)) = x) for y : R, but now we don't know y <> 2.

答:
The real numbers in Coq are defined axiomatically, i.e. they are just names associated with types, there are no definitions attached to the names. There are basic numbers (R0, R1) and operations on reals (Rplus, Rmult, etc.) which do not get executed, i.e. operations are not functions. In a sense one just builds real numbers by constructing them out of those operations just like with data constructors (but we cannot pattern-match on reals).

The above means that, e.g. 1/0 is a valid real number. It's just the premises of the axioms for real numbers prohibit some simplifications involving expressions like that: we cannot rewrite expressions like 1/0 * 0 to 1 (though, we can rewrite it to 0).

Here is how we can show that we cannot derive y <> 2 from an expression like

```<code>(y + 1) / (y - 2) = x
</code>```

because we are allowed to use "strange" real numbers:

```<code>From Coq Require Import Reals.
Open Scope R.

Goal ~ (forall x y : R, (y + 1) / (y - 2) = x -> y <> 2).
  unfold "_ - _"; intros contra; specialize (contra ((2+1)/0) 2).
  rewrite Rplus_opp_r in contra.
  intuition.
Qed.
</code>```

Body:
The real numbers in Coq are defined axiomatically, i.e. they are just names associated with types, there are no definitions attached to the names. There are basic numbers (R0, R1) and operations on reals (Rplus, Rmult, etc.) which do not get executed, i.e. operations are not functions. In a sense one just builds real numbers by constructing them out of those operations just like with data constructors (but we cannot pattern-match on reals).

The above means that, e.g. 1/0 is a valid real number. It's just the premises of the axioms for real numbers prohibit some simplifications involving expressions like that: we cannot rewrite expressions like 1/0 * 0 to 1 (though, we can rewrite it to 0).

Here is how we can show that we cannot derive y <> 2 from an expression like

(y + 1) / (y - 2) = x

because we are allowed to use "strange" real numbers:

From Coq Require Import Reals.
Open Scope R.

Goal ~ (forall x y : R, (y + 1) / (y - 2) = x -> y <> 2).
  unfold "_ - _"; intros contra; specialize (contra ((2+1)/0) 2).
  rewrite Rplus_opp_r in contra.
  intuition.
Qed.


问:
Guarantee Multiple Instances of an Object
I really don't know how to proper name this question. I have a certain scenario where I have an object that should be disposed of whenever used. The reasons for this are twofold:

I must guarantee that every member variable (field) is initialized before any new use.

I must guarantee that there aren't two methods of this object being called at the same time, since it's not thread-safe.

Both reasons could be covered in the object, having every public method lock the same mutex and initializing every variable on a private method, which is also called on every public method.

This solution is error prone and has a side effect of serializing the access on a multi-thread scenario, since I'll be locking the object before use. Of course, the call site could then create a new instance before calling a method (removing the side effect), but it's also error prone.

So I came up with a solution that I find both clean and very weird:

My object expose static methods, that have as parameters the variables necessary to both create a new instance of the object and execute the method. This static method create a instance of the object and then call the necessary method.

Of course, the constructor is private.

The first thing that I noticed when looking at this solution is that my object is looking a lot like a procedural method, of course, since every new method call requires a new object. But the responsibilities of the object fits nicely this scheme.

My questions (finally!, I know) are:

Is there a pattern that would adhere to my requirements (always using a new instance of an object)?

Is there a pattern describing my approach? Or is it a anti-pattern?

Besides the fact that the object seems like a collection of procedural functions, is there any other reason for me not having this approach?

Thanks for any comments.

答:
You don't say what language you're using (it's good to use a tag for that). In C#, I'd do the following:

Make fields private and expose them only through properties.

Initialize fields at construction.

Since the class clearly needs to be thread-safe ("must guarantee that there aren't two methods of this object being called at the same time"), make it thread-safe. Protect mutable shared state with locks.

Implement the Dispose pattern, making the client responsible for disposing of instances.

Static methods inherently couple your concrete class to any client classes. Among other things, that makes client classes difficult to test in isolation.

ContentLicense: CC BY-SA 2.5


问:
"CASE WHEN" in WHERE clause with indexed columns
I have a function with CASE WHEN condition in WHERE clause. Simply (very simply) it looks like this:

```<code>SELECT *
FROM mytable t
WHERE (
   CASE aPARAM WHEN 'a' THEN t.a = aID
               WHEN 'b' THEN t.b = aID
               WHEN 'c' THEN t.c = aID
               ELSE TRUE END
)
</code>```

aPARAM and aID - function params

a, b and c - indexed columns of the table "mytable"

But in this case MySQL doesn't use indexes at all.

Yes, this query contains condition to select another condition, but it's not depends of result value and can be calculated (defined) before query execute.

What can use suggest to this function to use indexes?

答:
Case is an expression for which MySQL can't use indexes. Try converting the case to a bunch of or conditions like this:

```<code>SELECT *
FROM mytable t
WHERE (t.a = aID and aPARAM = 'a')
or (t.b = aID and aPARAM = 'b')
or (t.c = aID and aPARAM = 'c')
or (aPARAM not in ('a','b','c'))
</code>```

Body:
I have a function with CASE WHEN condition in WHERE clause. Simply (very simply) it looks like this:

SELECT *
FROM mytable t
WHERE (
   CASE aPARAM WHEN 'a' THEN t.a = aID
               WHEN 'b' THEN t.b = aID
               WHEN 'c' THEN t.c = aID
               ELSE TRUE END
)

aPARAM and aID - function params

a, b and c - indexed columns of the table "mytable"

But in this case MySQL doesn't use indexes at all.

Yes, this query contains condition to select another condition, but it's not depends of result value and can be calculated (defined) before query execute.

What can use suggest to this function to use indexes?

Body:
Case is an expression for which MySQL can't use indexes. Try converting the case to a bunch of or conditions like this:

SELECT *
FROM mytable t
WHERE (t.a = aID and aPARAM = 'a')
or (t.b = aID and aPARAM = 'b')
or (t.c = aID and aPARAM = 'c')
or (aPARAM not in ('a','b','c'))


问:
Ionic 3 - FirebaseInstanceID not found
I try to build an Ionic 3 app with push notification on iOS.

Refeer to this post :
Ionic 3 - xcode error with cocoapods

I had tree errors :

```<code>diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.
</code>```

I tried to solve it buy this modification in my [CP] Check Pods Manifest.lock to this :

```<code>diff "${SRCROOT}/Podfile.lock" "${SRCROOT}/Pods/Manifest.lock" > /dev/null
if [ $? != 0 ] ; then
    # print error to STDERR
    echo "error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation." >&2
    exit 1
fi
</code>```

I think it works. But now, I have a new error in xCode after try to run on my device :

```<code> Module 'FirebaseInstanceID' not found
</code>```

I tried to run pod install again but no difference. I tried to modify my podfile like this ...

```<code># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'MyProject' do
pod 'Firebase'
pod 'Firebase/Core'
pod 'Fi
</code>```

But I keep my error. Someone have a solution to solve this ?

答:
I surely faced this problem when running my ionic3 application on ios device, here is what you may need to do to get it working.
Run cd platforms/ios
         pod install
Or check out this link for additional help.
https://github.com/phonegap/phonegap-plugin-push/blob/master/docs/INSTALLATION.md

Title: Ionic 3 - FirebaseInstanceID not found

Body:
I try to build an Ionic 3 app with push notification on iOS.

Refeer to this post :
Ionic 3 - xcode error with cocoapods

I had tree errors :

diff: /Podfile.lock: No such file or directory
diff: /Manifest.lock: No such file or directory
error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.

I tried to solve it buy this modification in my [CP] Check Pods Manifest.lock to this :

diff "${SRCROOT}/Podfile.lock" "${SRCROOT}/Pods/Manifest.lock" > /dev/null
if [ $? != 0 ] ; then
    # print error to STDERR
    echo "error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation." >&2
    exit 1
fi

I think it works. But now, I have a new error in xCode after try to run on my device :

 Module 'FirebaseInstanceID' not found

I tried to run pod install again but no difference. I tried to modify my podfile like this ...

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'MyProject' do
pod 'Firebase'
pod 'Firebase/Core'
pod 'Fi

But I keep my error. Someone have a solution to solve this ?


问:
How can I do a self-join in Laravel?
Here is my code:

```<code>$role_id = Auth::user()->role_id;

$related = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->related;
$pages   = Page::where('related', $related)->get();

foreach ($pages as $page){
    $accessGiven = page_role::where('role_id', $role_id)->where('page_id', $page->id)->first();
    if ( sizeof($accessGiven) > 0 ) {
        return $next($request);
    }
}

return redirect('/');
</code>```

It works well logically, but it is a little slow for huge dataset. You know, it's actually a middleware and will be executed before most of requests.

Anyway, I guess I can combine line 2 and line 3 and make one query of them. Any idea how can I do that?

答:
Try this:

In your Page model:

```<code>public function relatedPages(){
    return $this->hasMany(self::class, 'related', 'related');
}
</code>```

then

```<code>$pages = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->relatedPages
</code>```

Title: How can I do a self-join in Laravel?

Body:
Here is my code:

$role_id = Auth::user()->role_id;

$related = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->related;
$pages   = Page::where('related', $related)->get();

foreach ($pages as $page){
    $accessGiven = page_role::where('role_id', $role_id)->where('page_id', $page->id)->first();
    if ( sizeof($accessGiven) > 0 ) {
        return $next($request);
    }
}

return redirect('/');

It works well logically, but it is a little slow for huge dataset. You know, it's actually a middleware and will be executed before most of requests.

Anyway, I guess I can combine line 2 and line 3 and make one query of them. Any idea how can I do that?

Body:
Try this:

In your Page model:

public function relatedPages(){
    return $this->hasMany(self::class, 'related', 'related');
}

then

$pages = Page::where('path', $request->path())->where('method', $_SERVER["REQUEST_METHOD"])->first()->relatedPages


问:
Failed at the grpc@1.7.2 install script
I am trying to deploy a build a Docker image containing a react app. I am trying to use node:8-alpine as my base image. However, I am running into this error during the npm install layer. I tried using the standard node base image and every thing works fine, but the file size is 1GB so I'd really like to use alpine.

I am running macOS 10.12.6 node 8.7.0

```<code>Failed to execute '/usr/local/bin/node /usr/src/app/node_modules/node-
gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --
module=/usr/src/app/node_modules/grpc/src/node/extension_binary/node-v57-
linux-
x64-musl/grpc_node.node --module_name=grpc_node --
module_path=/usr/src/app/node_modules/grpc/src/node/extension_binary/node-v57-
linux-x64-musl' (1)
npm info lifecycle grpc@1.7.2~install: Failed to exec install script
npm WARN sign-in-app@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3
(node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current:
{"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --
library=static_library`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the grpc@1.7.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-06T18_26_09_926Z-debug.log
</code>```

答:
Ran into the same issue this morning. Looks like the precompiled grpc1.7.2 hasn't been uploaded for musl based distributions (alpine is musl vs glibc)

For the short term, to get your build going again, and until they upload the precompiled versions, try adding this to your dockerfile

```<code>RUN apk update && apk upgrade && \
    apk add --no-cache python make g++
</code>```

python, make and g++ basically allow node-gyp to compile from source rather than relying on the precompiled versions

Title: Failed at the grpc@1.7.2 install script

Body:
I am trying to deploy a build a Docker image containing a react app. I am trying to use node:8-alpine as my base image. However, I am running into this error during the npm install layer. I tried using the standard node base image and every thing works fine, but the file size is 1GB so I'd really like to use alpine.

I am running macOS 10.12.6 node 8.7.0

Failed to execute '/usr/local/bin/node /usr/src/app/node_modules/node-
gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --
module=/usr/src/app/node_modules/grpc/src/node/extension_binary/node-v57-
linux-
x64-musl/grpc_node.node --module_name=grpc_node --
module_path=/usr/src/app/node_modules/grpc/src/node/extension_binary/node-v57-
linux-x64-musl' (1)
npm info lifecycle grpc@1.7.2~install: Failed to exec install script
npm WARN sign-in-app@1.0.0 No repository field.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3
(node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for
fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current:
{"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --
library=static_library`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the grpc@1.7.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional
logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2017-12-06T18_26_09_926Z-debug.log

Body:
Ran into the same issue this morning. Looks like the precompiled grpc1.7.2 hasn't been uploaded for musl based distributions (alpine is musl vs glibc)

For the short term, to get your build going again, and until they upload the precompiled versions, try adding this to your dockerfile

RUN apk update && apk upgrade && \
    apk add --no-cache python make g++

python, make and g++ basically allow node-gyp to compile from source rather than relying on the precompiled versions


问:
Is it correct to use self/current in a rest api url?
For example let's say I have a url like /projects/{projectId}/progress.

Now, lets say a user can only be in one project. if the server already knows which project the user belongs to based on the context, do we need to pass the projectId or can we put the url as /projects/current/progress since we wouldn't be using the projectId even if it is passed.

Just want to know if it is a good practice or not.

答:
A resource can have multiple identifiers and nothing stops you from using a static mapping such as /projects/{projectId}/progress and a mapping that depends on a context such as /projects/current/progress.

A similar topic has been discussed here, here and here.


问:
Radio button text to top of the button programmatically
Is there any way to align the text of radio button to the top like below programmatically.

i used the below code for creating radio group

```<code>  final RadioButton[] rb = new RadioButton[5];
            RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
            rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
            rg.setLayoutParams(radioparams);

            for (int i = 0; i < 5; i++) {
                rb[i] = new RadioButton(getActivity());
                rb[i].setText("Radiobtn " + i);
                rb[i].setId(i + 100);
                rg.addView(rb[i]);

            }
            layout.addView(rg);
</code>```

but i get the text to the right side of each button.

答:
```<code>    final RadioButton[] rb = new RadioButton[5];
    RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
    rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
    rg.setLayoutParams(radioparams);

    for (int i = 0; i < 5; i++) {
        rb[i] = new RadioButton(getActivity());
        rb[i].setText("Radiobtn " + i);
        rb[i].setId(i + 100);
        rb[i].setButtonDrawable(null);

        TypedArray a = getTheme().obtainStyledAttributes(R.style.AppTheme, new int[] {android.R.attr.listChoiceIndicatorSingle});
        int attributeResourceId = a.getResourceId(0, 0);
        Drawable drawable = getResources().getDrawable(attributeResourceId);

        rb[i].setCompoundDrawablesWithIntrinsicBounds(null, null, null, drawable);
        rb[i].setGravity(Gravity.CENTER | Gravity.BOTTOM);
        rg.addView(rb[i]);

    }
    layout.addView(rg);
</code>```

Body:
Is there any way to align the text of radio button to the top like below programmatically.

i used the below code for creating radio group

  final RadioButton[] rb = new RadioButton[5];
            RadioGroup rg = new RadioGroup(getActivity()); //create the RadioGroup
            rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL
            rg.setLayoutParams(radioparams);

            for (int i = 0; i < 5; i++) {
                rb[i] = new RadioButton(getActivity());
                rb[i].setText("Radiobtn " + i);
                rb[i].setId(i + 100);
                rg.addView(rb[i]);

            }
            layout.addView(rg);

but i get the text to the right side of each button.


问:
Opinions/headers for splitting an application into front-end/back-end (not user/admin, but ui/logic)
I am building a new web application and playing around with the architecture and would like some opinions about splitting UI and business logic and running them on separate servers.

This means that if someone requests a page, the front end will itself request the data from a back-end server and then not actually perform any calculations/logic but just use the data to populate a template and then respond with that.

Back-End: Java + JAX-WS

Front-End: Kohana 3.1 (PHP)

Data Interchange Format: JSON

Advantages:

clear separation of logic and UI

ability to choose language/framework best suited for either end

possibility to add logic/UI servers depending on which one is the bottleneck in case of performance issues

possibility to make the API publicly available without any extra work (pseudo-internal requests will go to the same API as requests from third-part applications)

ability to change (if need be) the framework/language of either side without having to edit the other

ability to specify different server hardware according to the needs of the logic/UI application

better security (if API private) (??)

Disadvantages:

latency (??)

more servers

So what do you think? Is this a good idea? I haven't been able to find much information so far but my guess is that many big sites do it this way, right? How will performance be affected (I am thinking of running it on EC2)? What are further advantages/disadvantages? Any thoughts on the  languages/frameworks choices?

答:
A similar architectural pattern is often employed, though generally the UI part is often moved to the client. So you have a backend that responds with JSON, a quick http server with full-blown caching (and that can use html5 app caching as well) and a rich javascript client which requests the JSON from the backend and builds the UI.

More on this pattern: http://www.metaskills.net/2008/05/24/the-ajax-head-design-pattern/

The main negative of the approach is that is generally more work in the beginning - if you don't need an external API then using a simpler architecture will be easier to program.


问:
How to generate an xml file in C of 1GB
I don't know who to generate 1GB of data within a tag of XML.
I want to generate a line of data within the data text of 1GB of size
How can I realise this in the most efficient (speed-wise) way.
The data should be readable (can be nonsense of course)</p>

```<code>#include <stdio.h>

int main() {

    printf(" --- Creating XML");

    FILE *fptr;

    /*  open for writing */
    fptr = fopen("/tmp/emp.xml", "w");

    if (fptr == NULL)
    {
            printf("File does not exists \n");
            return 1;
    }

    fprintf(fptr, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
    fprintf(fptr, "<customer id=\"100\">\n");
    fprintf(fptr, "    <age>25</age>\n");
    fprintf(fptr, "    <name>New Customer</name>\n");
    fprintf(fptr, "    <data>dhgdhgdkrjgndliutghdnkljtghdliuthgdithugdnk...1GB_LONG<data>\n");
    fprintf(fptr, "</customer>");

    fclose(fptr);
}
</code>```

答:
I solved it by creating three files.

One with the xml until the opening of the tag in which the data should reside.
The second with the generated junk data.
The third with the close tag of the bulk data en the rest of the xml.

Like so:

```<code>   // Open two files to be merged
   FILE *fp1 = fopen("person1.xml", "r");
   FILE *fp2 = fopen("randomdata.txt", "r");
   FILE *fp3 = fopen("person3.xml", "r");

   // Open file to store the result
   FILE *fp4 = fopen("personf.xml", "w");
   char c;

   if (fp1 == NULL || fp2 == NULL || fp3 == NULL || fp4 == NULL)
   {
         puts(" --- Could not open files");
         exit(0);
   }

   // Copy contents of first file1
   while ((c = fgetc(fp1)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 1\n");
   // Copy contents of first file2
   while ((c = fgetc(fp2)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 2\n");

   // Copy contents of first file3
   while ((c = fgetc(fp3)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 3\n");

   printf("Merged files\n");

   fclose(fp1);
   fclose(fp2);
   fclose(fp3);
   fclose(fp4);
   return 0;
</code>```

Title: How to generate an xml file in C of 1GB

Body:
I don't know who to generate 1GB of data within a tag of XML.
I want to generate a line of data within the data text of 1GB of size
How can I realise this in the most efficient (speed-wise) way.
The data should be readable (can be nonsense of course)

#include <stdio.h>

int main() {

    printf(" --- Creating XML");

    FILE *fptr;

    /*  open for writing */
    fptr = fopen("/tmp/emp.xml", "w");

    if (fptr == NULL)
    {
            printf("File does not exists \n");
            return 1;
    }

    fprintf(fptr, "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n");
    fprintf(fptr, "<customer id=\"100\">\n");
    fprintf(fptr, "    <age>25</age>\n");
    fprintf(fptr, "    <name>New Customer</name>\n");
    fprintf(fptr, "    <data>dhgdhgdkrjgndliutghdnkljtghdliuthgdithugdnk...1GB_LONG<data>\n");
    fprintf(fptr, "</customer>");

    fclose(fptr);
}

Body:
I solved it by creating three files.

One with the xml until the opening of the tag in which the data should reside.
The second with the generated junk data.
The third with the close tag of the bulk data en the rest of the xml.

Like so:

   // Open two files to be merged
   FILE *fp1 = fopen("person1.xml", "r");
   FILE *fp2 = fopen("randomdata.txt", "r");
   FILE *fp3 = fopen("person3.xml", "r");

   // Open file to store the result
   FILE *fp4 = fopen("personf.xml", "w");
   char c;

   if (fp1 == NULL || fp2 == NULL || fp3 == NULL || fp4 == NULL)
   {
         puts(" --- Could not open files");
         exit(0);
   }

   // Copy contents of first file1
   while ((c = fgetc(fp1)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 1\n");
   // Copy contents of first file2
   while ((c = fgetc(fp2)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 2\n");

   // Copy contents of first file3
   while ((c = fgetc(fp3)) != EOF)
      fputc(c, fp4);

   printf(" --- Done copying file 3\n");

   printf("Merged files\n");

   fclose(fp1);
   fclose(fp2);
   fclose(fp3);
   fclose(fp4);
   return 0;


问:
how to add prefix for multi lines string?
Some times, the source string contain  multi lines. I found no prefix since second line in log result. I don't want to split the source string to single line, have any idea?

```<code>int main()
{
    BOOST_LOG_TRIVIAL(info) << "hello\nworld";
    return 0;
}
</code>```

output:

```<code>[2017-12-05 09:49:34.957813] [0x000028d4] [info]    hello
world
</code>```

I want the following output:

```<code>[2017-12-05 10:01:35.033017] [0x00000af8] [info]    hello
[2017-12-05 10:01:35.033017] [0x00000af8] [info]    world
</code>```

答:
Unfortunately, this is not possible to do with Boost.Log. Whatever output you generate in the streaming expression, including newlines, is considered a single log record, which is formatted once, hence it only has one timestamp and other attributes in the output.

You should manually separate the lines into different log records. If the log message text is received from an external source (e.g. network or as a callback from some library), you will have to split the text by newlines yourself.

Body:
Some times, the source string contain  multi lines. I found no prefix since second line in log result. I don't want to split the source string to single line, have any idea?

int main()
{
    BOOST_LOG_TRIVIAL(info) << "hello\nworld";
    return 0;
}

output:

[2017-12-05 09:49:34.957813] [0x000028d4] [info]    hello
world

I want the following output:

[2017-12-05 10:01:35.033017] [0x00000af8] [info]    hello
[2017-12-05 10:01:35.033017] [0x00000af8] [info]    world


问:
Way to not use goto loops in vba msgbox
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

```<code>Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub
</code>```

Thanks for any help you are able to provide

答:
You could use Do >> Loop Until loop, to remove the GoTo.

Also, you can use UCase(TestVariable) to remove the Or from your Ifs.

```<code>Sub MsgBox_Test()

Dim TestVariable As String

Do
    TestVariable = InputBox(" Y or N")
    If UCase(TestVariable) = "Y" Then
        MsgBox ("Yeyy")
    ElseIf UCase(TestVariable) = "N" Then
        MsgBox ("Awww")
    End If
Loop Until UCase(TestVariable) Like "[YN]"

End Sub
</code>```

Title: Way to not use goto loops in vba msgbox

Body:
I am trying to find a way to avoid using GoTo loops in VBA as i understand they can lead to serious confusion and issues. I have a  user InputBox, where the user defines a variables, currently on the if statement there are 3 options, if = Y ElseIf = N and else GoTo Start.

However this works great for the case where the user mistypes the variable i.e Y# etc, but i currently run into issues when the user wants to close the input box i.e clicks cancel or the cross.

So i was wondering if there is a more elligent solution to this or am I stuck with this hicup?

My code is below, this is only a test set used to test this new feature i am adding to my main code.

Sub MsgBox_Test ()

Dim TestVariable As String

VariableEntrey: TestVariable = InputBox(" Y or N")
If TestVariable = "Y" Or TestVariable = "y" Then
    MsgBox ("Yeyy")
ElseIf TestVariable = "N" Or TestVariable = "n" Then
    MsgBox ("Awww")
Else: GoTo VariableEntrey
End If

End Sub

Thanks for any help you are able to provide

Body:
You could use Do >> Loop Until loop, to remove the GoTo.

Also, you can use UCase(TestVariable) to remove the Or from your Ifs.

Sub MsgBox_Test()

Dim TestVariable As String

Do
    TestVariable = InputBox(" Y or N")
    If UCase(TestVariable) = "Y" Then
        MsgBox ("Yeyy")
    ElseIf UCase(TestVariable) = "N" Then
        MsgBox ("Awww")
    End If
Loop Until UCase(TestVariable) Like "[YN]"

End Sub


问:
Chef node usage
I'm learning Chef and find it difficult to understand the usage of node, like the perspective of its usage.

I went thru the Chef documents but still unable to exactly get the concepts.

Example, below are the scenarios where 'node' is being used. Can anyone explain in a simple term about the usage of node for different scenarios. Thank you.

Scenario 1:

```<code>currentUser = node['myusers'][node['myenv'] - 1] #arrays start at 0, doing -1 for 2 pointing to second user
user currentUser do
  gid node['mygroup']
  home "/home/#{currentUser}"
end
execute "sudoers for #{currentUser}" do
  command "echo '#{currentUser} ALL=(ALL) ALL' >> /etc/sudoers"
  not_if "grep -F '#{currentUser} ALL=(ALL) ALL' /etc/sudoers"
end
</code>```

Scenario 2:

```<code>pkg_resource = case node['platform_family']
  when "debian"
    :dpkg_package
  when "fedora", "rhel", "amazon"
    :rpm_package
  end
</code>```

Scenario 3:
By using a node attribute:

```<code>source node['nginx']['foo123']['url']
</code>```

答: For understanding consider Node attributes as a dictionary data type and as in dictionary every key has its own value. same way node['platform_family'] will have value as debian or centos depending upon the value it attain from ohai. ohai generally assigns value to the node attribute. there are other ways such as node.run_state which can use to assign value to a node[key] dynamically during chef run. eg node.run_state[weather]=sunny will assign node[weather] value as sunny.</p>

Title: Chef node usage

Body:
I'm learning Chef and find it difficult to understand the usage of node, like the perspective of its usage.

I went thru the Chef documents but still unable to exactly get the concepts.

Example, below are the scenarios where 'node' is being used. Can anyone explain in a simple term about the usage of node for different scenarios. Thank you.

Scenario 1:

currentUser = node['myusers'][node['myenv'] - 1] #arrays start at 0, doing -1 for 2 pointing to second user
user currentUser do
  gid node['mygroup']
  home "/home/#{currentUser}"
end
execute "sudoers for #{currentUser}" do
  command "echo '#{currentUser} ALL=(ALL) ALL' >> /etc/sudoers"
  not_if "grep -F '#{currentUser} ALL=(ALL) ALL' /etc/sudoers"
end

Scenario 2:

pkg_resource = case node['platform_family']
  when "debian"
    :dpkg_package
  when "fedora", "rhel", "amazon"
    :rpm_package
  end

Scenario 3:
By using a node attribute:

source node['nginx']['foo123']['url']


问:
C# how to decode html character squared ($sup2)
I am getting a string "lb/in&sup2" (which I want to show as lb/in²) from server. I want to decode this and show it in my Xamarin.iOS app.

I tried:

```<code>System.Net.WebUtility.HtmlDecode("lb/in&sup2")
</code>```

but its not working, still shows as "lb/in&sup2".

答:
Html entity should end with ";" character. This should work fine:

```<code>System.Net.WebUtility.HtmlDecode("lb/in²");
</code>```

If you are getting string exactly as you posted - you should fix the side which you are getting this string from, because "&sup2" is not html entity, it's just a "&sup2" string.

Body:
I am getting a string "lb/in&sup2" (which I want to show as lb/in²) from server. I want to decode this and show it in my Xamarin.iOS app.

I tried:

System.Net.WebUtility.HtmlDecode("lb/in&sup2")

but its not working, still shows as "lb/in&sup2".

Body:
Html entity should end with ";" character. This should work fine:

System.Net.WebUtility.HtmlDecode("lb/in&sup2;");

If you are getting string exactly as you posted - you should fix the side which you are getting this string from, because "&sup2" is not html entity, it's just a "&sup2" string.


问:
how to use ForEach loop in nested format
I am a newbie in Node.js and still learning the basic syntax

I was wondering if we want to use two different JSON object and then compare their values before giving the output then how do we use forEach in a nested manner like normal for?

```<code>var count = 0;
app.locals.author.forEach(function(item)
{
    app.locals.post.forEach(function(item1){

        if(item.id == item1.userId)
        {
            count++;
        }
    });
    res.send('Author = ' + item.name + " No of Posts done = " + count+"\n");
    count = 0;
});
</code>```

答:
Looks like you're just after a filter</p>

```<code>item.posts = app.locals.post.filter(x => x.userId === item.id)
</code>```

Body:
I am a newbie in Node.js and still learning the basic syntax

I was wondering if we want to use two different JSON object and then compare their values before giving the output then how do we use forEach in a nested manner like normal for?

var count = 0;
app.locals.author.forEach(function(item)
{
    app.locals.post.forEach(function(item1){

        if(item.id == item1.userId)
        {
            count++;
        }
    });
    res.send('Author = ' + item.name + " No of Posts done = " + count+"\n");
    count = 0;
});

Body:
Looks like you're just after a filter

item.posts = app.locals.post.filter(x => x.userId === item.id)


问:
How can I increase the timeout for the temporary EC2 credentials?
I am using IAM roles to access S3 from my EC2 instance calling the following end point.

curl http://169.254.169.254/latest/meta-data/iam/security-credentials/s3access.

The response I get -

{
  "Code" : "Success",
  "LastUpdated" : "2017-12-07T06:29:59Z",
  "Type" : "AWS-HMAC",
  "AccessKeyId" : "AASDJCJNSDPLB5FZA",

"SecretAccessKey" : "/vKFYv4AFlarEspnSNSKD87SDNSDFx3EsJv",

"Token" : "FQoDYXdzEIj//////////wEaDBUN1g6SxPkVQ46UjyKcA0l0q7jpEphFkq1OR3TD3Zm180bKKfkUqYeG6Xr/537olhJWKT2GGdkl/kDXIg3WxxBBOafy+yl4jgn0XTrTT2DWOX+ETPLvjZ4vpfrMNfVP0kwZiWbOuk4GcruixVdiuuDM6cce3WxZprFMLIe5WI0jVkpdA/MQQkqVsIsVcsVMa5LdhUsgdLQ3Yo+82BXVMpccjo+jeYqKEvm3h9rk9XmVRlPxn0wHzHgyiUgIl9O3U6/Ocp+hai+L8JzH5EH8O9ystJvf/rPQyZi0tVmsadasdasdydZr4NPtGYiTEye0dWHOhNvUNg8ZzQ9iBSZzUH8YxgtuOsM8C4LESNubVUxj4d9D49Krzs+oc2lFzLvQaEsSosn+V2mLlGq/AtPHwvyVQvlEOD7Uo27+j0QU=",

"Expiration" : "2017-12-07T12:39:23Z"

============================

I want to increase the expiration time "2017-12-07T12:39:23Z" of the temporary credentials. Can someone please help?

答:
Temporary Security Credentials are short term and they are refreshed for some duration. From your question you have mentioned that the code block to access the S3 bucket is running inside the EC2 instance from where you are using the CURL command to get the credentials.

As per AWS best practices it's better to user the Instance profile credentials, so that you don't need to worry about the credentials expiry time. Read More Here Instance profile credentials

Also we can increase the duration of the credentials. For that you have to use the AWS Security Token Service (AWS STS) to get the credentials.

AWS Security Token Service (AWS STS) to create and provide trusted
  users with temporary security credentials that can control access to
  your AWS resources

Here the duration can be configured to last for anywhere from a few minutes to several hours. Here is the chart of various time configurations of AWS STS API's

For more about this you can AWS STS API Refer Here and about Temporary Credentials Refer Here


问:
iPhone popup menu like iPad popover?
How can i implement this popup menu in iphone app like a popover in ipad?

EDIT: This is the best at moment: https://github.com/runway20/PopoverView

答: On iPhone you would generally use a UIActionSheet for a stack of buttons like that.  It slides up from the bottom, rather than popping up next to the button, but that's the standard behavior on iPhone.</p>

Title: iPhone popup menu like iPad popover?


问:
Bootstrap, I created a dropdown menu, how can I highlight choices on hover?
I created a dropdown menu that opens when you click on a text box, and then when you chose a string for that dropdown list, it puts it in the text box.

I would like to make that when you hover your mouse on the strings in the dropdown, they get slightly highlighted!  how can I achieve this?

```<code><div class="row">
    <div class="col-xs-12 max300" uib-dropdown is-open="vm.descriptionDropdownOpen">
         <textarea name="remarks" class="form-control" ng-model="vm.presence.description" ng-click="vm.toggleDescriptionDropdown()" autofocus></textarea>
         <ul id="descriptionDropdown" uib-dropdown-menu>
             <li ng-repeat="descr in vm.loadedDescriptions" ng-click="vm.presence.description = descr.text; vm.descriptionDropdownOpen = false;">
                 {{descr.text}}
             </li>
         </ul>
</code>```

and the css to keep the dropdown aligned with the textbox:

```<code>#descriptionDropdown {
    width: 100%;
    line-height: 150%;
    padding-left: 8px;
    position: relative;
}
</code>```

thank you very much

答:
you can do something like this

```<code>#descriptionDropdown li:hover{
   background-color:#eaeaea;
}
</code>```

Change the color code to your desired color code.
And remove the padding from ul to avoid space around background when you hover. Instead, use padding on li

```<code>#descriptionDropdown li{
   padding-left:8px;
}
</code>```

Body:
I created a dropdown menu that opens when you click on a text box, and then when you chose a string for that dropdown list, it puts it in the text box.

I would like to make that when you hover your mouse on the strings in the dropdown, they get slightly highlighted!  how can I achieve this?

         <textarea name="remarks" class="form-control" ng-model="vm.presence.description" ng-click="vm.toggleDescriptionDropdown()" autofocus></textarea>

                 {{descr.text}}

and the css to keep the dropdown aligned with the textbox:

#descriptionDropdown {
    width: 100%;
    line-height: 150%;
    padding-left: 8px;
    position: relative;
}

thank you very much

Body:
you can do something like this

#descriptionDropdown li:hover{
   background-color:#eaeaea;
}

Change the color code to your desired color code.
And remove the padding from ul to avoid space around background when you hover. Instead, use padding on li

#descriptionDropdown li{
   padding-left:8px;
}


问:
Append objects to a json file
I have a task to implement a pseudo cart page and when I click on checkout i want to send a request to a json file "ordersTest.json" with a following structure:
 { "orders": [] }. So when a post request is sent i have to put the data in that orders array in the json. I am completely new to Nodejs and express. This is my first project on it and i came up with a very simple server.

```<code>const express = require('express')
const path = require('path')
const fs = require('fs')
const url = require('url')
const bodyParser = require('body-parser')
const app = express()
const ordersJson = require('./public/ordersTest.json');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));
app.post('/api/orders', (req, res) => {
    let body = req.body;
    console.log(body);
    fs.appendFile('./public/ordersTest.json', JSON.stringify(body), err => {
        if (err) console.log(err);
    })
})
</code>```

But this thing only appends it to the end of the file. I need to put it inside this orders array

This is my ajax passing an example object in the body of the post:

```<code>$(".btn-checkout").on('click', function() {
    let date = new Date();
    $.ajax({
        method : "POST",
        url: "/api/orders",
        data : {a: "abc"},//{ order: "order",date: date.toDateString(), order: JSON.stringify(cart)},
        success : function(success){
            console.log(success,'success');
        },
        error : function(err) {
            console.log(err);
        }
    });
    clearCart();
    displayClearedCart();
});
</code>```

答:
You need to parse the JSON file and then treat it like an object. Once you are done with it, convert it to JSON again and overwrite your file. like this

```<code>app.post('/api/orders', (req, res) => {
    let body = req.body;
    var ordersTest = require('./public/ordersTest.json');
    ordersTest.orders.push(body);
    fs.writeFile('./public/ordersTest.json', JSON.stringify(ordersTest), function(err) {
      if (err) res.sendStatus(500)
      res.sendStatus(200);
    });
})
</code>```

Not tested, please fix typo error if any.

Title: Append objects to a json file

Body:
I have a task to implement a pseudo cart page and when I click on checkout i want to send a request to a json file "ordersTest.json" with a following structure:
 { "orders": [] }. So when a post request is sent i have to put the data in that orders array in the json. I am completely new to Nodejs and express. This is my first project on it and i came up with a very simple server.

const express = require('express')
const path = require('path')
const fs = require('fs')
const url = require('url')
const bodyParser = require('body-parser')
const app = express()
const ordersJson = require('./public/ordersTest.json');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
   extended: true
}));
app.post('/api/orders', (req, res) => {
    let body = req.body;
    console.log(body);
    fs.appendFile('./public/ordersTest.json', JSON.stringify(body), err => {
        if (err) console.log(err);
    })
})

But this thing only appends it to the end of the file. I need to put it inside this orders array

This is my ajax passing an example object in the body of the post:

$(".btn-checkout").on('click', function() {
    let date = new Date();
    $.ajax({
        method : "POST",
        url: "/api/orders",
        data : {a: "abc"},//{ order: "order",date: date.toDateString(), order: JSON.stringify(cart)},
        success : function(success){
            console.log(success,'success');
        },
        error : function(err) {
            console.log(err);
        }
    });
    clearCart();
    displayClearedCart();
});

Body:
You need to parse the JSON file and then treat it like an object. Once you are done with it, convert it to JSON again and overwrite your file. like this

app.post('/api/orders', (req, res) => {
    let body = req.body;
    var ordersTest = require('./public/ordersTest.json');
    ordersTest.orders.push(body);
    fs.writeFile('./public/ordersTest.json', JSON.stringify(ordersTest), function(err) {
      if (err) res.sendStatus(500)
      res.sendStatus(200);
    });
})

Not tested, please fix typo error if any.


问:
C - Cannot iterate through second string onward
Can anyone tell what I am doing wrong here?

Problem statement:
https://practice.geeksforgeeks.org/problems/good-or-bad-string/0

My code:

```<code>#include <stdio.h>
#include<string.h>
int is_vowel(char a) {
    if(a==97||a==101||a==105||a==111||a==117){
        return(1);
    }
    return(0);
}
int main() {
    //code
    int t,i;
    scanf("%d",&t);
    for(i=0;i<t;i++){
        char str[100];
        scanf("%s",str);
        printf("%s",str);
        int c_cnsnt=0;
        int c_vwl=0;
        int g_b=1;//suppose good
        for(int j=0;j<strlen(str);j++){
            //("%c",str[j]);
            int num=is_vowel(str[j]);
            printf("Debug %c %d %d\n",str[j],num,strlen(str));
            if(is_vowel(str[j])) {
                c_vwl++;
            }
            else { c_cnsnt++;}
            if(c_vwl==c_cnsnt){
                c_cnsnt=0;
                c_vwl=0;
            }
            else {
                if(c_vwl>5||c_cnsnt>=3){
                    g_b=0;
                    break;
                }
            }

        }
        printf("%d\n",g_b);
    }

    return 0;
}
</code>```

Sample

Input:

```<code>2
aeioup??
bcdaeiou??
</code>```

Output:

```<code>1
0
</code>```

My solution link:

https://code.hackerearth.com/9bca55K

Why does the for loop not work for the 2nd string?

答:
Hint: You have to clear the the consonant and vowel counts after increment the other (e.g {c_vwl++;c_cnsnt=0;}), not when they are equal, and always tests your BAD condition.

I will not give you a sample code. Good luck

Body:
Can anyone tell what I am doing wrong here?

Problem statement:
https://practice.geeksforgeeks.org/problems/good-or-bad-string/0

My code:

#include <stdio.h>
#include<string.h>
int is_vowel(char a) {
    if(a==97||a==101||a==105||a==111||a==117){
        return(1);
    }
    return(0);
}
int main() {
    //code
    int t,i;
    scanf("%d",&t);
    for(i=0;i<t;i++){
        char str[100];
        scanf("%s",str);
        printf("%s",str);
        int c_cnsnt=0;
        int c_vwl=0;
        int g_b=1;//suppose good
        for(int j=0;j<strlen(str);j++){
            //("%c",str[j]);
            int num=is_vowel(str[j]);
            printf("Debug %c %d %d\n",str[j],num,strlen(str));
            if(is_vowel(str[j])) {
                c_vwl++;
            }
            else { c_cnsnt++;}
            if(c_vwl==c_cnsnt){
                c_cnsnt=0;
                c_vwl=0;
            }
            else {
                if(c_vwl>5||c_cnsnt>=3){
                    g_b=0;
                    break;
                }
            }

        }
        printf("%d\n",g_b);
    }

    return 0;
}

Sample

Input:

2
aeioup??
bcdaeiou??

Output:

1
0

My solution link:

https://code.hackerearth.com/9bca55K

Why does the for loop not work for the 2nd string?


问:
android:onClick method on Custom View
I have an example code from GitHub. Example works great, but when I take only a portion of the code, I can't get it work. It is question of android:onClick-method in XML-file using custom view. The code follows:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tapio.testingapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <com.example.tapio.testingapp.LVCircularCD
        android:id="@+id/lv_circularCD"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:onClick="startAnim"/>

</RelativeLayout>
</code>```

Java Code :

```<code>public class LVCircularCD extends View {

    private Paint mPaint;

    private float mWidth = 0f;
    private float mPadding = 0f;

    RotateAnimation mProgerssRotateAnim;
    RectF rectF = new RectF();
    RectF rectF2 = new RectF();
    public LVCircularCD(Context context) {
        this(context, null);
    }

    public LVCircularCD(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LVCircularCD(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (getMeasuredWidth() > getHeight())
            mWidth = getMeasuredHeight();
        else
            mWidth = getMeasuredWidth();
        mPadding = 5;

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        mPaint.setStrokeWidth(2);
        canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2 - mPadding, mPaint);
        mPaint.setStrokeWidth(3);
        canvas.drawCircle(mWidth / 2, mWidth / 2, mPadding, mPaint);

        mPaint.setStrokeWidth(2);
        rectF = new RectF(mWidth / 2 - mWidth / 3, mWidth / 2 - mWidth / 3,
                mWidth / 2 + mWidth / 3, mWidth / 2 + mWidth / 3);
        canvas.drawArc(rectF, 0, 80
                , false, mPaint);

        canvas.drawArc(rectF, 180, 80
                , false, mPaint);

        rectF2 = new RectF(mWidth / 2 - mWidth / 4, mWidth / 2 - mWidth / 4,
                mWidth / 2 + mWidth / 4, mWidth / 2 + mWidth / 4);
        canvas.drawArc(rectF2, 0, 80
                , false, mPaint);
        canvas.drawArc(rectF2, 180, 80
                , false, mPaint);
        canvas.restore();

    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.WHITE);
        mProgerssRotateAnim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mProgerssRotateAnim.setRepeatCount(-1);
        mProgerssRotateAnim.setInterpolator(new LinearInterpolator());//不停顿
        mProgerssRotateAnim.setFillAfter(true);//停在最后

    }

    public void setViewColor(int color)
    {
        mPaint.setColor(color);
        postInvalidate();
    }

    public void startAnim(View view) {
        stopAnim();
        mProgerssRotateAnim.setDuration(1500);
        startAnimation(mProgerssRotateAnim);
    }

    public void startAnim(int time) {
        stopAnim();
        mProgerssRotateAnim.setDuration(time);
        startAnimation(mProgerssRotateAnim);
    }

    public void stopAnim() {
        clearAnimation();
    }

}
</code>```

The problematic place is in XML-file:android:onclick  = startAnim. I will get the following error: "Corresponding method handler 'public void startAnim(android.view.View)' not found"

答: Yep. I added startAnim method to MainActivity-activity. Works fine. I still wonder why the original worked so well.</p>

Title: android:onClick method on Custom View

Body:
I have an example code from GitHub. Example works great, but when I take only a portion of the code, I can't get it work. It is question of android:onClick-method in XML-file using custom view. The code follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.tapio.testingapp.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <com.example.tapio.testingapp.LVCircularCD
        android:id="@+id/lv_circularCD"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:onClick="startAnim"/>

</RelativeLayout>

Java Code :

public class LVCircularCD extends View {

    private Paint mPaint;

    private float mWidth = 0f;
    private float mPadding = 0f;

    RotateAnimation mProgerssRotateAnim;
    RectF rectF = new RectF();
    RectF rectF2 = new RectF();
    public LVCircularCD(Context context) {
        this(context, null);
    }

    public LVCircularCD(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LVCircularCD(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        if (getMeasuredWidth() > getHeight())
            mWidth = getMeasuredHeight();
        else
            mWidth = getMeasuredWidth();
        mPadding = 5;

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.save();
        mPaint.setStrokeWidth(2);
        canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2 - mPadding, mPaint);
        mPaint.setStrokeWidth(3);
        canvas.drawCircle(mWidth / 2, mWidth / 2, mPadding, mPaint);

        mPaint.setStrokeWidth(2);
        rectF = new RectF(mWidth / 2 - mWidth / 3, mWidth / 2 - mWidth / 3,
                mWidth / 2 + mWidth / 3, mWidth / 2 + mWidth / 3);
        canvas.drawArc(rectF, 0, 80
                , false, mPaint);

        canvas.drawArc(rectF, 180, 80
                , false, mPaint);

        rectF2 = new RectF(mWidth / 2 - mWidth / 4, mWidth / 2 - mWidth / 4,
                mWidth / 2 + mWidth / 4, mWidth / 2 + mWidth / 4);
        canvas.drawArc(rectF2, 0, 80
                , false, mPaint);
        canvas.drawArc(rectF2, 180, 80
                , false, mPaint);
        canvas.restore();

    }

    private void initPaint() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.WHITE);
        mProgerssRotateAnim = new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        mProgerssRotateAnim.setRepeatCount(-1);
        mProgerssRotateAnim.setInterpolator(new LinearInterpolator());//不停顿
        mProgerssRotateAnim.setFillAfter(true);//停在最后

    }

    public void setViewColor(int color)
    {
        mPaint.setColor(color);
        postInvalidate();
    }

    public void startAnim(View view) {
        stopAnim();
        mProgerssRotateAnim.setDuration(1500);
        startAnimation(mProgerssRotateAnim);
    }

    public void startAnim(int time) {
        stopAnim();
        mProgerssRotateAnim.setDuration(time);
        startAnimation(mProgerssRotateAnim);
    }

    public void stopAnim() {
        clearAnimation();
    }

}

The problematic place is in XML-file:android:onclick  = startAnim. I will get the following error: "Corresponding method handler 'public void startAnim(android.view.View)' not found"


问:
The SOAP action specified on the message, '', does not match the HTTP SOAP Action,
I am trying to connect my script to the SOAP client. But when I try to do it throws the mentioned error. When I tried to get the function with
$client->__getFunctions(). It shows all the function. when I try to call them it ends in fatal error.

```<code>$client = new SoapClient("http://bsestarmfdemo.bseindia.com/MFOrderEntry/MFOrder.svc?singleWsdl",array(
    'soap_version' => SOAP_1_2, // !!!!!!!
));
var_dump($client->__getFunctions());
//var_dump($client->__getTypes());

$login_params = array(
    'UserId' => 123456,
    'Password' => 123456,
    'PassKey' => 1234569870,

  );

//$response = $client->getPassword($login_params);
$response = $client->__soapCall('getPassword', array($login_params));
dd($response);
</code>```

if i change the SOAP version to 1.1 i get another error Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. Would be great if i come to know what i am missing here.

答:
To address the reply made by @Naveen Kumar: this was my solution.

```<code>// Apply WSA headers
$action = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', self::ACTION_PREFIX.$this->action);
$to = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', $this->endpoint);
$this->client()->__setSoapHeaders([$action, $to]);
</code>```

In the end, $this->client simply returns an instance of \SoapClient and the action contains the full URL to the method. Naturally, the To portion is optional, but in my case it obviously points towards the endpoint specified in the .wsdl file.

Body:
I am trying to connect my script to the SOAP client. But when I try to do it throws the mentioned error. When I tried to get the function with
$client->__getFunctions(). It shows all the function. when I try to call them it ends in fatal error.

$client = new SoapClient("http://bsestarmfdemo.bseindia.com/MFOrderEntry/MFOrder.svc?singleWsdl",array(
    'soap_version' => SOAP_1_2, // !!!!!!!
));
var_dump($client->__getFunctions());
//var_dump($client->__getTypes());

$login_params = array(
    'UserId' => 123456,
    'Password' => 123456,
    'PassKey' => 1234569870,

  );

//$response = $client->getPassword($login_params);
$response = $client->__soapCall('getPassword', array($login_params));
dd($response);

if i change the SOAP version to 1.1 i get another error Cannot process the message because the content type 'text/xml; charset=utf-8' was not the expected type 'application/soap+xml; charset=utf-8'. Would be great if i come to know what i am missing here.

Body:
To address the reply made by @Naveen Kumar: this was my solution.

// Apply WSA headers
$action = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'Action', self::ACTION_PREFIX.$this->action);
$to = new \SoapHeader('http://www.w3.org/2005/08/addressing', 'To', $this->endpoint);
$this->client()->__setSoapHeaders([$action, $to]);

In the end, $this->client simply returns an instance of \SoapClient and the action contains the full URL to the method. Naturally, the To portion is optional, but in my case it obviously points towards the endpoint specified in the .wsdl file.


问:
How do I fill a rectangle with the exception of a area
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

```<code>  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);
</code>```

答: You could try to use regions.  Create a rectangle region, exclude an ellipse and then fill it.</p>

Body:
I am trying to fill a rectangle in a winforms application less a ellipse in the center that allows the image in the background to show through.

can anyone give me a hint on which way to go on this,

thanks.

this is what I have come up with so far:

  path.AddRectangle(new Rectangle(30, 30, 100, 100));
  path.AddEllipse(new Rectangle(50, 50, 60, 60));
  gfx.FillPath(new SolidBrush(Color.Black), path);


问:
Referencing a local relative file in a JSON Schema?
I am building a JSON for a REST web service. The schema however has grown to over 1300 lines and I want to split it up across multiple files. I am unit testing my schema against a folder of JSON sample responses using json-schema-validator version 2.1.8.

I know you have import types defined in your current file like { "$ref": "#/definitions/MyBool" }, however if I wanted to move the definition of MyBool to another file, like Common.schema.json, how would I reference it then?

I tried { "$ref": "Common.schema.json/definitions/MyBoolean" }, { "$ref": "./Common.schema.json/defintion/MyBoolean" }, and { "$ref": "file://./Common.schema.json/definitions/MyBoolean" } but none of them work.

The answer on "Does JSON Schema validation in common-js utils support references?" seems like it should work but I can't seem to get the syntax right.

I'm loading the schema with:

JsonNode mySchema = JsonLoader.fromReader(   new InputStreamReader(  JsonSchemaTest.class.getResourceAsStream( "/json/schema/MySchema.schema.json" )  )   );
```

<p>and then validating it with:</p>

<pre class="lang-java prettyprint-override"><code>JsonSchemaFactory.byDefault().getValidator().validate(   schema,   new InputStreamReader(  getClass().getResourceAsStream( "/json/sample/MyJsonSample.json" )  )   ).isSuccess();
</code>```

FWIW MyBool looks like:

```<code>"MyBool": {
    "type": "object",
    "properties": {
        "value" :{
            "type": "string",
            "enum": [ "true", "false", "file not found" ]
        }
    },
    "required": ["value"],
    "additionalProperties": false
}
</code>```

When I don't try to extract MyBool, the schema validates all my JSON samples correctly.

The exception I receive is:

com.github.fge.jsonschema.core.exceptions.ProcessingException: fatal: unable to dereference URI "file:/Common.schema.json/definitions/MyBool#"
    level: "fatal"
    uri: "file:/Common.schema.json/definitions/MyBool#"
    exceptionMessage: "\\Common.schema.json\\definitions\\MyBool (The system cannot find the path specified)"

    at com.github.fge.jsonschema.core.load.URIManager.getContent(URIManager.java:108)
    at com.github.fge.jsonschema.core.load.SchemaLoader$1.load(SchemaLoader.java:108)
    at com.github.fge.jsonschema.core.load.SchemaLoader$1.load(SchemaLoader.java:103)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.load.SchemaLoader.get(SchemaLoader.java:165)
    at com.github.fge.jsonschema.core.load.RefResolver.rawProcess(RefResolver.java:113)
    at com.github.fge.jsonschema.core.load.RefResolver.rawProcess(RefResolver.java:50)
    at com.github.fge.jsonschema.core.processing.RawProcessor.process(RawProcessor.java:76)
    at com.github.fge.jsonschema.core.processing.RawProcessor.process(RawProcessor.java:40)
    at com.github.fge.jsonschema.core.processing.ProcessorChain$ProcessorMerger.process(ProcessorChain.java:188)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:127)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:119)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.processing.CachingProcessor.process(CachingProcessor.java:108)
    at com.github.fge.jsonschema.processors.validation.ValidationChain.process(ValidationChain.java:106)
    at com.github.fge.jsonschema.processors.validation.ValidationChain.process(ValidationChain.java:55)
    at com.github.fge.jsonschema.core.processing.ProcessorMap$Mapper.process(ProcessorMap.java:165)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:127)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:119)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.processing.CachingProcessor.process(CachingProcessor.java:108)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:83)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processObject(ValidationProcessor.java:179)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:121)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processArray(ValidationProcessor.java:149)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:119)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processObject(ValidationProcessor.java:179)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:121)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:48)
    at com.github.fge.jsonschema.keyword.validator.draftv4.OneOfValidator.validate(OneOfValidator.java:67)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:100)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:48)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.main.JsonValidator.validate(JsonValidator.java:103)
    at com.github.fge.jsonschema.main.JsonValidator.validate(JsonValidator.java:123)
    at com.initech.ws.json.BaseJsonSchemaTest.jsonFileShouldValidate(BaseJsonSchemaTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
```

答:
The following solution worked for me. The path is relative to location where I run mvn goals.

```<code>"items": {
                "type": "object",
                "$ref": "file:src/xyz/abc/lmn/DeviceRecord.json"
         }
</code>```

Here file: is the path from where you are executing the maven goal.

Body:
I am building a JSON for a REST web service. The schema however has grown to over 1300 lines and I want to split it up across multiple files. I am unit testing my schema against a folder of JSON sample responses using json-schema-validator version 2.1.8.

I know you have import types defined in your current file like { "$ref": "#/definitions/MyBool" }, however if I wanted to move the definition of MyBool to another file, like Common.schema.json, how would I reference it then?

I tried { "$ref": "Common.schema.json/definitions/MyBoolean" }, { "$ref": "./Common.schema.json/defintion/MyBoolean" }, and { "$ref": "file://./Common.schema.json/definitions/MyBoolean" } but none of them work.

The answer on "Does JSON Schema validation in common-js utils support references?" seems like it should work but I can't seem to get the syntax right.

I'm loading the schema with:

JsonNode mySchema = JsonLoader.fromReader(   new InputStreamReader(  JsonSchemaTest.class.getResourceAsStream( "/json/schema/MySchema.schema.json" )  )   );

and then validating it with:

JsonSchemaFactory.byDefault().getValidator().validate(   schema,   new InputStreamReader(  getClass().getResourceAsStream( "/json/sample/MyJsonSample.json" )  )   ).isSuccess();

FWIW MyBool looks like:

"MyBool": {
    "type": "object",
    "properties": {
        "value" :{
            "type": "string",
            "enum": [ "true", "false", "file not found" ]
        }
    },
    "required": ["value"],
    "additionalProperties": false
}

When I don't try to extract MyBool, the schema validates all my JSON samples correctly.

The exception I receive is:

com.github.fge.jsonschema.core.exceptions.ProcessingException: fatal: unable to dereference URI "file:/Common.schema.json/definitions/MyBool#"
    level: "fatal"
    uri: "file:/Common.schema.json/definitions/MyBool#"
    exceptionMessage: "\\Common.schema.json\\definitions\\MyBool (The system cannot find the path specified)"

    at com.github.fge.jsonschema.core.load.URIManager.getContent(URIManager.java:108)
    at com.github.fge.jsonschema.core.load.SchemaLoader$1.load(SchemaLoader.java:108)
    at com.github.fge.jsonschema.core.load.SchemaLoader$1.load(SchemaLoader.java:103)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.load.SchemaLoader.get(SchemaLoader.java:165)
    at com.github.fge.jsonschema.core.load.RefResolver.rawProcess(RefResolver.java:113)
    at com.github.fge.jsonschema.core.load.RefResolver.rawProcess(RefResolver.java:50)
    at com.github.fge.jsonschema.core.processing.RawProcessor.process(RawProcessor.java:76)
    at com.github.fge.jsonschema.core.processing.RawProcessor.process(RawProcessor.java:40)
    at com.github.fge.jsonschema.core.processing.ProcessorChain$ProcessorMerger.process(ProcessorChain.java:188)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:127)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:119)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.processing.CachingProcessor.process(CachingProcessor.java:108)
    at com.github.fge.jsonschema.processors.validation.ValidationChain.process(ValidationChain.java:106)
    at com.github.fge.jsonschema.processors.validation.ValidationChain.process(ValidationChain.java:55)
    at com.github.fge.jsonschema.core.processing.ProcessorMap$Mapper.process(ProcessorMap.java:165)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:127)
    at com.github.fge.jsonschema.core.processing.CachingProcessor$1.load(CachingProcessor.java:119)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3524)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2317)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2280)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2195)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3934)
    at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3938)
    at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4821)
    at com.github.fge.jsonschema.core.processing.CachingProcessor.process(CachingProcessor.java:108)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:83)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processObject(ValidationProcessor.java:179)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:121)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processArray(ValidationProcessor.java:149)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:119)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.processObject(ValidationProcessor.java:179)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:121)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:48)
    at com.github.fge.jsonschema.keyword.validator.draftv4.OneOfValidator.validate(OneOfValidator.java:67)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:100)
    at com.github.fge.jsonschema.processors.validation.ValidationProcessor.process(ValidationProcessor.java:48)
    at com.github.fge.jsonschema.core.processing.ProcessingResult.of(ProcessingResult.java:78)
    at com.github.fge.jsonschema.main.JsonValidator.validate(JsonValidator.java:103)
    at com.github.fge.jsonschema.main.JsonValidator.validate(JsonValidator.java:123)
    at com.initech.ws.json.BaseJsonSchemaTest.jsonFileShouldValidate(BaseJsonSchemaTest.java:84)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runners.Suite.runChild(Suite.java:127)
    at org.junit.runners.Suite.runChild(Suite.java:26)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:74)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:211)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Body:
The following solution worked for me. The path is relative to location where I run mvn goals.

"items": {
                "type": "object",
                "$ref": "file:src/xyz/abc/lmn/DeviceRecord.json"
         }

Here file: is the path from where you are executing the maven goal.


问:
Operator Delete in an Abstract Class, how does it work
how this thing works.

```<code>class Car
{
 public:
 Car() = default;
 Car(const Car& other) = delete;
 Car& operator=(const Car& other) = delete;
 virtual void WhatsTheMake() = 0;
 virtual void WhatsTheSpeed() =0;
}
</code>```

Now what does this delete keyword mean here?

Also does using abstract class increase code size. I mean if I don't need an Abstract class, do I always have to create it ?

答:
If you mark a function as deleted ( = delete), any use of it will generate a compile error.

Regarding the code size, actually yes, defining an abstract class will generated more code for managing the pure virtual call (Declaring abstract class (pure virtual method) increase binary size substantially)

Personally I use an abstract class when I need to define a common base interface and I don't want to provide any common implementation and I want to delegate the implementation to the concrete classes which will inherit from (https://en.wikipedia.org/wiki/Polymorphism_(computer_science)#Subtyping)

Body:
how this thing works.

class Car
{
 public:
 Car() = default;
 Car(const Car& other) = delete;
 Car& operator=(const Car& other) = delete;
 virtual void WhatsTheMake() = 0;
 virtual void WhatsTheSpeed() =0;
}

Now what does this delete keyword mean here?

Also does using abstract class increase code size. I mean if I don't need an Abstract class, do I always have to create it ?


问:
Unable to deploy portlet in Liferay 7
I can not deploy portlet in my project in Liferay.

My gradle file looks like this:

```<code>#Thu Aug 18 11:52:36 CDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip
</code>```

Firstly, I had an error:

```<code>* What went wrong:
Execution failed for task ':compileJava'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jdk1.8.0_111 contains a valid JDK installation.
</code>```

I added this line to gradle file

```<code>org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_111
</code>```

Now, I have this error:

```<code>Gradle User Home: C:\Users\Piotr\.gradle
Gradle Distribution: Gradle wrapper from target build
Gradle Version: 3.0
Java Home: C:\Program Files\Java\jre1.8.0_131
JVM Arguments: None
Program Arguments: None
Build Scans Enabled: false
Offline Mode Enabled: false
Gradle Tasks: deploy

:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_131 contains a valid JDK installation.
</code>```

Any ideas what should I do to deploy this portlet correctly?

答:
From Error Its looks like your Java Home path is wrong.

It should be

```<code>Java Home: C:\Program Files\Java\jdk1.8.0_60
</code>```

If you are deploying from IDE than you can change it from
Window --> Preferences-->Java-->Installed JREs

```<code>Gradle Distribution: Gradle wrapper from target build
Gradle Version: 2.14.1
Java Home: C:\Program Files\Java\jdk1.8.0_60
JVM Arguments: None
Program Arguments: None
Gradle Tasks: deploy
</code>```

Title: Unable to deploy portlet in Liferay 7

Body:
I can not deploy portlet in my project in Liferay.

My gradle file looks like this:

#Thu Aug 18 11:52:36 CDT 2016
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-3.0-bin.zip

Firstly, I had an error:

* What went wrong:
Execution failed for task ':compileJava'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jdk1.8.0_111 contains a valid JDK installation.

I added this line to gradle file

org.gradle.java.home=C:\\Program Files\\Java\\jdk1.8.0_111

Now, I have this error:

Gradle User Home: C:\Users\Piotr\.gradle
Gradle Distribution: Gradle wrapper from target build
Gradle Version: 3.0
Java Home: C:\Program Files\Java\jre1.8.0_131
JVM Arguments: None
Program Arguments: None
Build Scans Enabled: false
Offline Mode Enabled: false
Gradle Tasks: deploy

:compileJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileJava'.
> Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_131 contains a valid JDK installation.

Any ideas what should I do to deploy this portlet correctly?

Body:
From Error Its looks like your Java Home path is wrong.

It should be

Java Home: C:\Program Files\Java\jdk1.8.0_60

If you are deploying from IDE than you can change it from
Window --> Preferences-->Java-->Installed JREs

Gradle Distribution: Gradle wrapper from target build
Gradle Version: 2.14.1
Java Home: C:\Program Files\Java\jdk1.8.0_60
JVM Arguments: None
Program Arguments: None
Gradle Tasks: deploy


问:
Hosting or deploy R rest Api's
We have created RestApi's in R. We are able to run the code by using Plumber. But the thing is we need to host or deploy the R code on web (like web api or web services)

```<code># myfile.R

#' @get /Sample
Sample <- function(samples=10){
 print(samples)
}
</code>```

Note : Please suggest other than Plumber and Shiny

答:
This is for those who wants to have a comparion of API development with R.

Basically concurrent requests are queued by httpuv in plumber so that it is not performant by itself. The author recommends multiple docker containers but it can be complicated as well as response-demanding.

There are other tech eg Rserve and rApache. Rserve forks prosesses and it is possible to configure rApache to pre-fork so as to handle concurrent requests.

See the following posts for comparison

https://www.linkedin.com/pulse/api-development-r-part-i-jaehyeon-kim/
https://www.linkedin.com/pulse/api-development-r-part-ii-jaehyeon-kim/

Title: Hosting or deploy R rest Api's

Body:
We have created RestApi's in R. We are able to run the code by using Plumber. But the thing is we need to host or deploy the R code on web (like web api or web services)

# myfile.R

#' @get /Sample
Sample <- function(samples=10){
 print(samples)
}

Note : Please suggest other than Plumber and Shiny


问:
How to get the range of string for attributed string?
I have string as 2/42. Here 2 & 42 is dynamic.Now I want to set /42 as superscript of string. I am not able to find out the range of /42. please tell me how do i find out the range in swift?

答:
Mutable string of attributed string has functionality to find of range of specific string.

Try this and see (Swift 4):

```<code>let stringValue = "2/42"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
let range: NSRange = attributedString.mutableString.range(of: "/42", options: .caseInsensitive)
print("range - \(range)")
</code>```

Result:

range - {1, 3}

Ref Snapshot:

Body:
Mutable string of attributed string has functionality to find of range of specific string.

Try this and see (Swift 4):

let stringValue = "2/42"
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
let range: NSRange = attributedString.mutableString.range(of: "/42", options: .caseInsensitive)
print("range - \(range)")

Result:

range - {1, 3}

Ref Snapshot:


问:
Why is following-sibling faster then preceding-sibling if matched data is located behind
If I have a list of value in XML:

```<code>1 2 1 2 1 2 1 2 8 9 6 8 7 9 8
</code>```

and I am using preceding-sibling or following-sibling to search the value that more than 5. I can clearly noticed that following-sibling only take 1/4 time of preceding-sibling, but in theory them both query all the element, so why not them take the same time? THX!

答:
Well, this is going to depend entirely on what XSLT/XPath processor you are using, and on the details of how its tree model is implemented. It may also depend on exactly what your XPath expression looks like, and on how you are measuring its performance. So you need to give us a lot more detail. (When asking a question on SO, ask yourself "have I given enough information that someone else could reproduce my problem"?)

It's entirely possible that the tree implementation you are using has forwards pointers and no backwards pointer, in which case finding preceding siblings might involve searching forwards from the start.

Saxon's TinyTree implementation doesn't have backwards pointers when a tree is first built, but the first time you use the preceding-sibling axis there is a one-time cost of creating backwards pointers for the whole tree, after which navigation in the forwards and backwards directions should be equally fast.

No doubt other implementations have other tricks designed to make performance faster but less predictable!

Body:
If I have a list of value in XML:

1 2 1 2 1 2 1 2 8 9 6 8 7 9 8

and I am using preceding-sibling or following-sibling to search the value that more than 5. I can clearly noticed that following-sibling only take 1/4 time of preceding-sibling, but in theory them both query all the element, so why not them take the same time? THX!


问:
How do I change TextView Value inside Java Code?
I am working on a android program. A user clicks on a button I do some math and I would like to change the values that I have on my view in some TextView objects.  Can someone please tell me how to do it in my code?</p>

答:
I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

```<code><TextView
android:id="@+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/rate"
/>
</code>```

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

```<code><string name="rate">Rate</string>
</code>```

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:

```<code>
final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");
</code>```

Body:
I presume that this question is a continuation of this one.

What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:

<TextView
android:id="@+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/rate"
/>

The string "@string/rate" refers to an entry in your strings.xml file that looks like this:

<string name="rate">Rate</string>

If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:

final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
    "The new text that I'd like to display now that the user has pushed a button.");