问:
Why is datekey in fact tables always INT?
I'm looking at the datekey column from the fact tables in AdventureWorksDW and they're all of type int.

Is there a reason for this and not of type date?

I understand that creating a clustered index composed of an INT would optimize query speed. But let's say I want to get data from this past week. I can subtract 6 from date 20170704 and I'll get 20170698 which is not a valid date. So I have to cast everything to date, subtract, and then cast as int.

Right now I have a foreign key constraint to make sure that something besides 'YYYYMMDD' isn't inserted. It wouldn't be necessary with a Date type. Just now, I wanted to get some data between 6/28 and 7/4. I can't just subtract six from `20170703'; I have to cast from int to date.

It seems like a lot of hassle and not many benefits.

Thanks.

答:
It's a good question, but the answer depends on what kind of datawarehouse you're aiming for.  SSAS, for instance, covers tabular and multi-dimensional.

In multi-dimensional, you would never be querying the fact table itself through SQL, so the problem you note with e.g. subtracting 6 days from 20170704 would actually never arise.  Because in MD SSAS you'd use MDX on the dimension itself to implement date logic (as suggested in @S4V1N's answer above).  Calendar.Date.PrevMember(6).  And for more complicated stuff, you can build all kinds of date hierarchies and get into MDX ParallelPeriod and FirstChild and that kind of thing.

For a datawarehouse that you're intending to use with SQL, your question has more urgency.  I think that in that case @S4V1N's answer still applies: restrict your date logic to the dimension side

because that's where it's already implemented (possibly with pre-built calendar and fiscal hierarchies).

Because your logic will operate on an order of magnitude less rows.

I'm perfectly happy to have fact tables keyed on an INT-style date: but that's because I use MD SSAS.  It could be that AdventureWorksDW was originally built with MD SSAS in mind (where whether the key used in fact tables is amenable to SQL is irrelevant), even though MS's emphasis seems to have switched to Tabular SSAS recently.  Or the use of INTs for date keys could have been a "developer-nudging" design decision, meant to discourage date operations on the fact tables themselves, as opposed to on the Date dimension.


来源: stackexchange

问:
Textfield size is not increase in storyboard ios
I have a textfield of 100 width but i want the size of this textfield change on different size screens in same manner. i do not want to give % constraint of screen to increase size. for example in 6s textfield size is 100 but on 7 size should be change on the basis of screen size.</p>

答:
If you want to use constraints, you have to manually change its value accordingly to screen size. You can drag and drop your constraint properties as outlet

And you can change the constraint by accessing its constant property

```<code>self.viewWidthConstraint.constant = 20 //Or desired value
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to use constraints, you have to manually change its value accordingly to screen size. You can drag and drop your constraint properties as outlet

And you can change the constraint by accessing its constant property

self.viewWidthConstraint.constant = 20 //Or desired value


问:
" MethodNotAllowedHttpException" while buiding an api for my andorid app using laravel 5.4
AuthController.php code

```<code><?php

 namespace App\Http\Controllers\Api;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 use JWTAuth;
 use App\User;
 use JWTAuthException;

 class AuthController extends Controller
{
 private $user;

 public function __construct(User $user)
{
    $this->user = $user;
}
public function register(Request $request)
{
    $this->validate($request, [
            'email'=> 'required|email|unique:users',
            'first_name'=> 'required|max:120',
            'password' => 'required|min:4'
            ]);

    $user = $this->user->create([
    'name' => $request->get('name'),
    'email' => $request->get('email'),
    'password' => bcrypt($request->get('password'))
        ]);

    $user->save();
    if(!$user){
            return response()->json(['status'=>false,'message'=>'User not created']);
    }
    else {
        return response()->json(['status'=>true,'message'=>'User created successfully','data'=>$user]);
    }

}

public function login(Request $request)
{
    $this->validate($request, [
            'email'=> 'required',
            'password'=> 'required'
            ]);

    $credentials = $request->only('email','password');
    $token = null;

    try {
        $token = $this->jwtauth->attepmt($credentials);
        if(!$token)
        {
            return response()->json(['invalid email or password'], 422);
        }
    }
    catch (JWTAuthException $ex)
    {
         return response()->json(['failed to create token'], 500);
    }

     return response()->json(compact('token'));
}

public function getAuthUser(Request $request){
    $user = JWTAuth::toUser($request->token);
    return response()->json(['result' => $user]);
}
}
</code>```

api.php routes

```<code>Route::post('register', 'api\AuthController@register');
Route::post('login', 'api\AuthController@login');
Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'api\AuthController@getAuthUser');

});
</code>```

*Im sure that there is something little  wrong im my code because the "getAuthUser" method is working and cheking if there is a token or no . I'll be thankful if anyone helped me *

答:
So, which one of the methods is giving you error?

Since you did specify that "getAuthUser" was working fine; And because of the kind of error you're getting I'm going to assume you're talking "register" and "login".

Anyway, that kind of error happens when you try to access a route with the incorrect kind of request. You must use a "POST" request, instead of a "GET" if you are trying to access /register and /login

Body:
AuthController.php code

<?php

 namespace App\Http\Controllers\Api;
 use Illuminate\Http\Request;
 use App\Http\Requests;
 use App\Http\Controllers\Controller;
 use JWTAuth;
 use App\User;
 use JWTAuthException;

 class AuthController extends Controller
{
 private $user;

 public function __construct(User $user)
{
    $this->user = $user;
}
public function register(Request $request)
{
    $this->validate($request, [
            'email'=> 'required|email|unique:users',
            'first_name'=> 'required|max:120',
            'password' => 'required|min:4'
            ]);

    $user = $this->user->create([
    'name' => $request->get('name'),
    'email' => $request->get('email'),
    'password' => bcrypt($request->get('password'))
        ]);

    $user->save();
    if(!$user){
            return response()->json(['status'=>false,'message'=>'User not created']);
    }
    else {
        return response()->json(['status'=>true,'message'=>'User created successfully','data'=>$user]);
    }

}

public function login(Request $request)
{
    $this->validate($request, [
            'email'=> 'required',
            'password'=> 'required'
            ]);

    $credentials = $request->only('email','password');
    $token = null;

    try {
        $token = $this->jwtauth->attepmt($credentials);
        if(!$token)
        {
            return response()->json(['invalid email or password'], 422);
        }
    }
    catch (JWTAuthException $ex)
    {
         return response()->json(['failed to create token'], 500);
    }

     return response()->json(compact('token'));
}

public function getAuthUser(Request $request){
    $user = JWTAuth::toUser($request->token);
    return response()->json(['result' => $user]);
}
}

api.php routes

Route::post('register', 'api\AuthController@register');
Route::post('login', 'api\AuthController@login');
Route::group(['middleware' => 'jwt.auth'], function () {
Route::get('user', 'api\AuthController@getAuthUser');

});

*Im sure that there is something little  wrong im my code because the "getAuthUser" method is working and cheking if there is a token or no . I'll be thankful if anyone helped me *


问:
Can't access method server on mobile side or via REST
I have already asked this question, but the previous method I used was created in 4D. This time I created a new class in Wakanda and a new datastore class method. I know how to use it in mobile side, but it won't works, so I try to call it via REST and I have this following message :

"{"__ERROR":[{"message":"The \"method1\" attribute cannot be found in The \"TEST\" datastore class","componentSignature":"dbmg","errCode":1500},{"message":"The \"method1\" attribute cannot be found in The \"TEST\" datastore class","componentSignature":"dbmg","errCode":1500},{"message":"Error code: 1804\nCannot completely build a list of attributes with \"method1\" for the \"TEST\" datastore class\ncomponent: 'dbmg'\ntask 7963, name: 'HTTP connection handler'\n","componentSignature":"dbmg","errCode":1804}]}"

My method is in public scope, and I can access to the datastore class TEST via REST.

Can someone tell me how I can use this method, or what to do to correct this error ? Thanks in advance.

答:
This error indicates the method1 is not publicly available under table TEST.

I tested and get the same exact error when the method scope is not set to public.

Please double check the code to change scope is correct, like following:

```<code>model.DataClass1.methods.method1.scope = 'public'
</code>```

And see if method1 is indeed published in table TEST by accessing http://127.0.0.1:8081/rest/$catalog/TEST/

The response JSON should have method1 in its methods property:

Body:
This error indicates the method1 is not publicly available under table TEST.

I tested and get the same exact error when the method scope is not set to public.

Please double check the code to change scope is correct, like following:

model.DataClass1.methods.method1.scope = 'public'

And see if method1 is indeed published in table TEST by accessing http://127.0.0.1:8081/rest/$catalog/TEST/

The response JSON should have method1 in its methods property:


问:
Convert formatted lines of delimited text into an associative array
I have a string of key->value pairs in the following colon-separated format:

```<code>MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!
</code>```

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

答:
You could always use regex :)

PHP

```<code>$str = 'MIME-Version: 1.0' . "\r\n" .
'From: "Tim Lincecum"' . "\r\n" .
'Reply-To: "Tim Lincecum"' . "\r\n" .
'Return-path: "Tim Lincecum"' . "\r\n" .
'Content-Type: text/html; charset=iso-8859-1' . "\r\n" .
'Subject: Giants Win World Series!';

preg_match_all('/(.*?):\s?(.*?)(\r\n|$)/', $str, $matches);

$headers = array_combine(array_map('trim', $matches[1]), $matches[2]);

var_dump($headers);
</code>```

Output

```<code>array(6) {
  ["MIME-Version"]=>
  string(3) "1.0"
  ["From"]=>
  string(14) ""Tim Lincecum""
  ["Reply-To"]=>
  string(14) ""Tim Lincecum""
  ["Return-path"]=>
  string(14) ""Tim Lincecum""
  ["Content-Type"]=>
  string(29) "text/html; charset=iso-8859-1"
  ["Subject"]=>
  string(24) "Giants Win World Series!"
}
</code>```

See it on IDEone.

ContentLicense: CC BY-SA 4.0

Body:
I have a string of key->value pairs in the following colon-separated format:

MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!

How do I get an associative array such that arr['From'] = "Tim Lincecum", etc.?

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?

Body:
You could always use regex :)

PHP

$str = 'MIME-Version: 1.0' . "\r\n" .
'From: "Tim Lincecum"' . "\r\n" .
'Reply-To: "Tim Lincecum"' . "\r\n" .
'Return-path: "Tim Lincecum"' . "\r\n" .
'Content-Type: text/html; charset=iso-8859-1' . "\r\n" .
'Subject: Giants Win World Series!';

preg_match_all('/(.*?):\s?(.*?)(\r\n|$)/', $str, $matches);

$headers = array_combine(array_map('trim', $matches[1]), $matches[2]);

var_dump($headers);

Output

array(6) {
  ["MIME-Version"]=>
  string(3) "1.0"
  ["From"]=>
  string(14) ""Tim Lincecum""
  ["Reply-To"]=>
  string(14) ""Tim Lincecum""
  ["Return-path"]=>
  string(14) ""Tim Lincecum""
  ["Content-Type"]=>
  string(29) "text/html; charset=iso-8859-1"
  ["Subject"]=>
  string(24) "Giants Win World Series!"
}

See it on IDEone.

ContentLicense: CC BY-SA 2.5


问:
iOS: Modal ViewController with transparent background
I'm trying to present a view controller modally, with a transparent background. My goal is to let both the presenting and presented view controllers's view to be displayed at the same time. The problem is, when the presenting animation finishes, the presenting view controller's view disappears.

```<code>- (IBAction)pushModalViewControllerButtonPressed:(id)sender
{
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    [self presentViewController:modalVC animated:YES completion:nil];
}
</code>```

I know I could just add the view as a subview, but I'd like to avoid this solution for some reason. How could I fix it?

答:
The solution to this answer using swift would be as follows.</p>

```<code>let vc = MyViewController()
vc.view.backgroundColor = UIColor.clear // or whatever color.
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)
</code>```

Body:
I'm trying to present a view controller modally, with a transparent background. My goal is to let both the presenting and presented view controllers's view to be displayed at the same time. The problem is, when the presenting animation finishes, the presenting view controller's view disappears.

- (IBAction)pushModalViewControllerButtonPressed:(id)sender
{
    ModalViewController *modalVC = [[ModalViewController alloc] init];
    [self presentViewController:modalVC animated:YES completion:nil];
}

I know I could just add the view as a subview, but I'd like to avoid this solution for some reason. How could I fix it?

Body:
The solution to this answer using swift would be as follows.

let vc = MyViewController()
vc.view.backgroundColor = UIColor.clear // or whatever color.
vc.modalPresentationStyle = .overCurrentContext
present(vc, animated: true, completion: nil)


问:
if else nested for loops using python list comprehension
Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

```<code>results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]
    }
]
</code>```

And I am looking for output in the form of list.
The code to get the output is:

```<code>output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])
</code>```

Thus the output using above code is -

```<code>['input', 'status', 'entity.value', 'entity.address']
</code>```

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

```<code>output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]
</code>```

答:
One way to transform your code into workable code would be to make the inner loop produce lists, and then flatten the result afterward.</p>

```<code>sum(([d['name'] + '.' + f['name'] for f in d['fields']]
    if d.get('fields') else [d['name']] for d in results), [])
</code>```

Body:
Can anyone help me figure the list comprehension way of producing following output -

Let given list be -

results = [
    {"id":  1, "name":  "input"},
    {"name": "status", "desc": "Status"},
    {"name": "entity", "fields": [
        {"id": 101, "name": "value"},
        {"id": 102, "name": "address"}]
    }
]

And I am looking for output in the form of list.
The code to get the output is:

output = []
for eachDict in results:
    if "fields" in eachDict:
        for field in eachDict["fields"]:
            output.append(eachDict["name"]+"."+field["name"])
    else:
        output.append(eachDict["name"])

Thus the output using above code is -

['input', 'status', 'entity.value', 'entity.address']

Is it possible to get similar output using if else nested for loops in list Comprehension?

I am having trouble trying to get access to that inner for loop in if condition of list Comprehension

My attempt -

output = [eachDict["name"]+"."+field["name"] for field in eachDict["fields"] if "fields" in eachDict else eachDict["name"] for eachDict in results]

Body:
One way to transform your code into workable code would be to make the inner loop produce lists, and then flatten the result afterward.

sum(([d['name'] + '.' + f['name'] for f in d['fields']]
    if d.get('fields') else [d['name']] for d in results), [])


问:
checkbox validation angularjs
I have multiple checkboxes for a question.Atleast one checkbox needs to be selected.If none of the checkboxes get selected form should through validation error.Did i miss anything. Any ideas on how I would be able to achieve this behaviour?
My .JS code:

```<code>$scope.onCheckBoxSelected=function(){

                            var flag=false;
                            for(var key in selectedOptions){
                                console.log('Key -' +key +' val- '+selectedOptions[key]);
                                if(selectedOptions[key]){
                                    flag=true;
                                }
                            }
                            if(!flag){
                                selectedOptions=undefined;
                            }
                        };
</code>```

below is my html code :

```<code><div class="grid">
    <div class="col flex-10  mandatoryField" ng-class="{error: (!selectedOptions && formMissingFields)}">Hello please select atleast one</div>
    <div class="col flex-2">
    </div>
    <div class="col flex-5">

        <div style="padding-top: 2px">
            <input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
            </input>
        </div>
        <div style="padding-top: 2px">
            <input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
            </input>
        </div>

    </div>

</div>
</code>```

答:
You can keep it simpler, without the need of the ngChange event.</p>

```<code><div ng-class="{error: !apple && !orange && !banana">Hello please select atleast one</div>
</code>```

Title: checkbox validation angularjs

Body:
I have multiple checkboxes for a question.Atleast one checkbox needs to be selected.If none of the checkboxes get selected form should through validation error.Did i miss anything. Any ideas on how I would be able to achieve this behaviour?
My .JS code:

$scope.onCheckBoxSelected=function(){

                            var flag=false;
                            for(var key in selectedOptions){
                                console.log('Key -' +key +' val- '+selectedOptions[key]);
                                if(selectedOptions[key]){
                                    flag=true;
                                }
                            }
                            if(!flag){
                                selectedOptions=undefined;
                            }
                        };

below is my html code :

Hello please select atleast one

            <input type="checkbox" name="apple" title="Select type" value="apple" ng-model="apple" ng-change="onCheckBoxSelected()">apple
            </input>

            <input type="checkbox" name="orange" title="Select type" value="orange" ng-model="orange" ng-change="onCheckBoxSelected()">orange
            </input>

            <input type="checkbox" name="banana" title="Select type" value="banana" ng-model="banana" ng-change="onCheckBoxSelected()">banana
            </input>

Body:
You can keep it simpler, without the need of the ngChange event.

<div ng-class="{error: !apple && !orange && !banana">Hello please select atleast one</div>


问:
What happens if the amount of characters that are entered into your character array is less than the amount of spaces you specified
```<code>char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );
</code>```

Will it fill the end of the array with null characters?

答:
You answered your own question.

the remaining 15 character will be assigned null value.

And you are declaring the array wrong... if you want ch_array = SALLY, you should use single inverted comma ('S' like this) with each of your character.

For output use printf("%s", ch_arry); instead of printf("%s", ch_arry[]);

Body:
char ch_arry[20] = { S, A, L, L, Y};
printf( "%s", ch_arry[] );

Will it fill the end of the array with null characters?


问:
CXF Web service client error
I am trying to invoke a web service  from java client using apache CXF. Following is my client code snippet.

```<code>Client client = new ClientImpl(new URL("http://localhost:8080/socialkast-web/services/skservice?wsdl"));
Object[] results = client.invoke("uploadVideoMetaData", new Object[] {metaData});
  String result = (String)results[0];
</code>```

I am getting parsing error although i am able to access the wsdl file from browser. Following is the exception stack.

```<code>INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14f5a31: defining beans [cxf,org.apache.cxf.bus.spring.BusApplicationListener,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,org.apache.cxf.resource.ResourceManager,org.apache.cxf.configuration.Configurer,org.apache.cxf.binding.BindingFactoryManager,org.apache.cxf.transport.DestinationFactoryManager,org.apache.cxf.transport.ConduitInitiatorManager,org.apache.cxf.wsdl.WSDLManager,org.apache.cxf.phase.PhaseManager,org.apache.cxf.workqueue.WorkQueueManager,org.apache.cxf.buslifecycle.BusLifeCycleManager,org.apache.cxf.endpoint.ServerRegistry,org.apache.cxf.endpoint.ServerLifeCycleManager,org.apache.cxf.endpoint.ClientLifeCycleManager,org.apache.cxf.transports.http.QueryHandlerRegistry,org.apache.cxf.endpoint.EndpointResolverRegistry,org.apache.cxf.headers.HeaderManager,org.apache.cxf.catalog.OASISCatalogManager,org.apache.cxf.endpoint.ServiceContractResolverRegistry,org.apache.cxf.binding.corba.CorbaBindingFactory,org.apache.cxf.binding.corba.wsdl.WSDLExtensionRegister#0,org.apache.cxf.jaxws.context.WebServiceContextResourceResolver,org.apache.cxf.jaxws.context.WebServiceContextImpl,org.apache.cxf.binding.soap.SoapBindingFactory,org.apache.cxf.binding.soap.SoapTransportFactory,org.apache.cxf.binding.soap.customEditorConfigurer,org.apache.cxf.binding.xml.XMLBindingFactory,org.apache.cxf.ws.addressing.policy.AddressingAssertionBuilder,org.apache.cxf.ws.addressing.policy.AddressingPolicyInterceptorProvider,org.apache.cxf.ws.addressing.policy.UsingAddressingAssertionBuilder,org.apache.cxf.javascript.JavascriptQueryHandlerRegistry,org.apache.cxf.transport.local.LocalTransportFactory,org.apache.cxf.transport.http.policy.HTTPClientAssertionBuilder,org.apache.cxf.transport.http.policy.HTTPServerAssertionBuilder,org.apache.cxf.transport.http.policy.NoOpPolicyInterceptorProvider,org.apache.cxf.transport.http.ClientOnlyHTTPTransportFactory,org.apache.cxf.management.InstrumentationManager,org.apache.cxf.transport.http_jetty.JettyHTTPTransportFactory,org.apache.cxf.transport.jms.JMSTransportFactory,org.apache.cxf.binding.object.ObjectBindingFactory,org.apache.cxf.binding.http.HttpBindingFactory,org.apache.cxf.ws.security.policy.WSSecurityPolicyLoader,org.apache.cxf.ws.policy.AssertionBuilderRegistry,org.apache.cxf.ws.policy.PolicyInterceptorProviderRegistry,org.apache.cxf.ws.policy.attachment.external.DomainExpressionBuilderRegistry,org.apache.cxf.ws.policy.attachment.external.EndpointReferenceDomainExpressionBuilder,org.apache.cxf.ws.policy.PolicyBuilder,org.apache.cxf.ws.policy.PolicyEngine,org.apache.cxf.ws.policy.attachment.wsdl11.Wsdl11AttachmentPolicyProvider,org.apache.cxf.ws.policy.attachment.ServiceModelPolicyProvider,org.apache.cxf.ws.policy.mtom.MTOMAssertionBuilder,org.apache.cxf.ws.policy.mtom.MTOMPolicyInterceptorProvider,org.apache.cxf.ws.rm.RMManager,org.apache.cxf.ws.rm.policy.RMPolicyInterceptorProvider,org.apache.cxf.ws.rm.RMAssertionBuilder,org.apache.cxf.binding.corba.wsdl.WSDLExtensionRegister#1]; root of factory hierarchy
org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service.
 at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:69)
 at org.apache.cxf.endpoint.ClientImpl.<init>(ClientImpl.java:152)
 at org.apache.cxf.endpoint.ClientImpl.<init>(ClientImpl.java:121)
 at tv.socialkast.client.ws.WSClient.<init>(WSClient.java:42)
 at tv.socialkast.upload.client.gui.UploadDirectoryChooser$DoneActionListener.actionPerformed(UploadDirectoryChooser.java:382)
 at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
 at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
 at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
 at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
 at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
 at java.awt.Component.processMouseEvent(Unknown Source)
 at javax.swing.JComponent.processMouseEvent(Unknown Source)
 at java.awt.Component.processEvent(Unknown Source)
 at java.awt.Container.processEvent(Unknown Source)
 at java.awt.Component.dispatchEventImpl(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Window.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)
**Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing 'http://localhost:8080/socialkast-web/services/skservice?wsdl'.: java.net.ConnectException: Connection refused: connect**
 at com.ibm.wsdl.xml.WSDLReaderImpl.getDocument(Unknown Source)
 at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source)
 at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source)
 at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:232)
 at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:161)
 at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:67)
 ... 29 more
</code>```

Please advice what am I missing here.

Thanks.

答:
Simple enough: Your server isn't responding.</p>

```<code>Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing 'http://localhost:8080/socialkast-web/services/skservice?wsdl'.: java.net.ConnectException: Connection refused: connect at com.ibm.wsdl.xml.WSDLReaderImpl.getDocument(Unknown Source
</code>```

Title: CXF Web service client error

Body:
I am trying to invoke a web service  from java client using apache CXF. Following is my client code snippet.

Client client = new ClientImpl(new URL("http://localhost:8080/socialkast-web/services/skservice?wsdl"));
Object[] results = client.invoke("uploadVideoMetaData", new Object[] {metaData});
  String result = (String)results[0];

I am getting parsing error although i am able to access the wsdl file from browser. Following is the exception stack.

INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14f5a31: defining beans [cxf,org.apache.cxf.bus.spring.BusApplicationListener,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,org.apache.cxf.resource.ResourceManager,org.apache.cxf.configuration.Configurer,org.apache.cxf.binding.BindingFactoryManager,org.apache.cxf.transport.DestinationFactoryManager,org.apache.cxf.transport.ConduitInitiatorManager,org.apache.cxf.wsdl.WSDLManager,org.apache.cxf.phase.PhaseManager,org.apache.cxf.workqueue.WorkQueueManager,org.apache.cxf.buslifecycle.BusLifeCycleManager,org.apache.cxf.endpoint.ServerRegistry,org.apache.cxf.endpoint.ServerLifeCycleManager,org.apache.cxf.endpoint.ClientLifeCycleManager,org.apache.cxf.transports.http.QueryHandlerRegistry,org.apache.cxf.endpoint.EndpointResolverRegistry,org.apache.cxf.headers.HeaderManager,org.apache.cxf.catalog.OASISCatalogManager,org.apache.cxf.endpoint.ServiceContractResolverRegistry,org.apache.cxf.binding.corba.CorbaBindingFactory,org.apache.cxf.binding.corba.wsdl.WSDLExtensionRegister#0,org.apache.cxf.jaxws.context.WebServiceContextResourceResolver,org.apache.cxf.jaxws.context.WebServiceContextImpl,org.apache.cxf.binding.soap.SoapBindingFactory,org.apache.cxf.binding.soap.SoapTransportFactory,org.apache.cxf.binding.soap.customEditorConfigurer,org.apache.cxf.binding.xml.XMLBindingFactory,org.apache.cxf.ws.addressing.policy.AddressingAssertionBuilder,org.apache.cxf.ws.addressing.policy.AddressingPolicyInterceptorProvider,org.apache.cxf.ws.addressing.policy.UsingAddressingAssertionBuilder,org.apache.cxf.javascript.JavascriptQueryHandlerRegistry,org.apache.cxf.transport.local.LocalTransportFactory,org.apache.cxf.transport.http.policy.HTTPClientAssertionBuilder,org.apache.cxf.transport.http.policy.HTTPServerAssertionBuilder,org.apache.cxf.transport.http.policy.NoOpPolicyInterceptorProvider,org.apache.cxf.transport.http.ClientOnlyHTTPTransportFactory,org.apache.cxf.management.InstrumentationManager,org.apache.cxf.transport.http_jetty.JettyHTTPTransportFactory,org.apache.cxf.transport.jms.JMSTransportFactory,org.apache.cxf.binding.object.ObjectBindingFactory,org.apache.cxf.binding.http.HttpBindingFactory,org.apache.cxf.ws.security.policy.WSSecurityPolicyLoader,org.apache.cxf.ws.policy.AssertionBuilderRegistry,org.apache.cxf.ws.policy.PolicyInterceptorProviderRegistry,org.apache.cxf.ws.policy.attachment.external.DomainExpressionBuilderRegistry,org.apache.cxf.ws.policy.attachment.external.EndpointReferenceDomainExpressionBuilder,org.apache.cxf.ws.policy.PolicyBuilder,org.apache.cxf.ws.policy.PolicyEngine,org.apache.cxf.ws.policy.attachment.wsdl11.Wsdl11AttachmentPolicyProvider,org.apache.cxf.ws.policy.attachment.ServiceModelPolicyProvider,org.apache.cxf.ws.policy.mtom.MTOMAssertionBuilder,org.apache.cxf.ws.policy.mtom.MTOMPolicyInterceptorProvider,org.apache.cxf.ws.rm.RMManager,org.apache.cxf.ws.rm.policy.RMPolicyInterceptorProvider,org.apache.cxf.ws.rm.RMAssertionBuilder,org.apache.cxf.binding.corba.wsdl.WSDLExtensionRegister#1]; root of factory hierarchy
org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service.
 at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:69)
 at org.apache.cxf.endpoint.ClientImpl.<init>(ClientImpl.java:152)
 at org.apache.cxf.endpoint.ClientImpl.<init>(ClientImpl.java:121)
 at tv.socialkast.client.ws.WSClient.<init>(WSClient.java:42)
 at tv.socialkast.upload.client.gui.UploadDirectoryChooser$DoneActionListener.actionPerformed(UploadDirectoryChooser.java:382)
 at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
 at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
 at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
 at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
 at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
 at java.awt.Component.processMouseEvent(Unknown Source)
 at javax.swing.JComponent.processMouseEvent(Unknown Source)
 at java.awt.Component.processEvent(Unknown Source)
 at java.awt.Container.processEvent(Unknown Source)
 at java.awt.Component.dispatchEventImpl(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
 at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
 at java.awt.Container.dispatchEventImpl(Unknown Source)
 at java.awt.Window.dispatchEventImpl(Unknown Source)
 at java.awt.Component.dispatchEvent(Unknown Source)
 at java.awt.EventQueue.dispatchEvent(Unknown Source)
 at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
 at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
 at java.awt.EventDispatchThread.run(Unknown Source)
**Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing 'http://localhost:8080/socialkast-web/services/skservice?wsdl'.: java.net.ConnectException: Connection refused: connect**
 at com.ibm.wsdl.xml.WSDLReaderImpl.getDocument(Unknown Source)
 at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source)
 at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(Unknown Source)
 at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:232)
 at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:161)
 at org.apache.cxf.wsdl11.WSDLServiceFactory.<init>(WSDLServiceFactory.java:67)
 ... 29 more

Please advice what am I missing here.

Thanks.

Body:
Simple enough: Your server isn't responding.

Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: Problem parsing 'http://localhost:8080/socialkast-web/services/skservice?wsdl'.: java.net.ConnectException: Connection refused: connect at com.ibm.wsdl.xml.WSDLReaderImpl.getDocument(Unknown Source


问:
Need to return cursor and not command_cursor with aggregate()
I need to iterate an aggregate() result twice. However it is impossible to rewind the command_cursor returned by aggregate(). I tried to turn to True the option UseCursor of aggregate() but it always returns a command_cursor. Is there a way to do what I want?

The main problem is that I can't store every documents returned by aggregate() in a list... It crashes my application and freeze my VM after ~127000 documents

答:
Simple execute the aggregate twice:

```<code>pipeline = [...]
for doc in collection.aggregate(pipeline):
    # do step 1 with your documents

for doc in collection.aggregate(pipeline):
    # do step 2 with your documents
</code>```

This is, in fact, what rewind on a normal Cursor actually does: it simply executes the same query twice.

Body:
Simple execute the aggregate twice:

pipeline = [...]
for doc in collection.aggregate(pipeline):
    # do step 1 with your documents

for doc in collection.aggregate(pipeline):
    # do step 2 with your documents

This is, in fact, what rewind on a normal Cursor actually does: it simply executes the same query twice.


问:
Python: How do you intercept a method call to change function parameters?
What I am trying to do is write a wrapper around another module so that I can transform the parameters that are being passed to the methods of the other module. That was fairly confusing, so here is an example:

```<code>import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    # This next function is the one I want to exist
    # Please understand the lines below will not compile and are not real code
    def __intercept__(self, item, *args, **kwargs):
        if "t" in args:
            args[args.index("t")] = self.transforms["t"]
        return somemodule.item(*args, **kwargs)
</code>```

The goal is to allow users of the wrapper class to make simplified calls to the underlying module without having to rewrite all of the functions in the module. So in this case if somemodule had a function called print_uppercase then the user could do

```<code>w = Wrapper()
w.print_uppercase("t")
</code>```

and get the output

```<code>TEST
</code>```

I believe the answer lies in __getattr__ but I'm not totally sure how to use it for this application.

答:
Since your Wrapper object doesn't have any mutable state, it'd be easier to implement without a class.  Example wrapper.py:

```<code>def func1(*args, **kwargs):
  # do your transformations
  return somemodule.func1(*args, **kwargs)
</code>```

Then call it like:

```<code>import wrapper as w
print w.func1('somearg')
</code>```

Body:
What I am trying to do is write a wrapper around another module so that I can transform the parameters that are being passed to the methods of the other module. That was fairly confusing, so here is an example:

import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    # This next function is the one I want to exist
    # Please understand the lines below will not compile and are not real code
    def __intercept__(self, item, *args, **kwargs):
        if "t" in args:
            args[args.index("t")] = self.transforms["t"]
        return somemodule.item(*args, **kwargs)

The goal is to allow users of the wrapper class to make simplified calls to the underlying module without having to rewrite all of the functions in the module. So in this case if somemodule had a function called print_uppercase then the user could do

w = Wrapper()
w.print_uppercase("t")

and get the output

TEST

I believe the answer lies in __getattr__ but I'm not totally sure how to use it for this application.

Body:
Since your Wrapper object doesn't have any mutable state, it'd be easier to implement without a class.  Example wrapper.py:

def func1(*args, **kwargs):
  # do your transformations
  return somemodule.func1(*args, **kwargs)

Then call it like:

import wrapper as w
print w.func1('somearg')


问:
Does Clojure have an efficient, idiomatic approach for decorators?
In Clojure(script) you define programming constructs with deftype and defrecord.  We want our constructs to each have a specific, well-defined purpose.  Rather than evolve any one construct into a monolithic full-featured thing, we choose to segregate responsibilities.  Decorators (e.g. data structures that wrap other data structures) are good for this.

For example, you have a logger construct.  You add timestamping as a feature with a decorator.  You later add alerting support staff beepers as another decorator.  We can, in theory, layer on any number of features this way.  Our config file cleanly determines which features get included.

If our logger implements a 3-method Logging protocol and each decorator only augments one, you still have to implement the other two methods on each decorator to uphold the contractual api.  These add-nothing implementations simply pass the message down the chain.  This is the awkward bit.

The richer a construct's api, the worse the problem.  Consider a construct that implements a few protocols and the work necessary to decorate something that handles 12 or so methods.

Is there a mechanism, macro, or technique that you've found to overcomes this?

答:
One option is to use extend to merge a mix of delegating-by-default functions and overriding implementations.

For example, with a logger protocol like:

```<code>(defprotocol Logger
  (info [logger s])
  (warn [logger s])
  (debug [logger s]))

(def println-logger
  (reify Logger
    (info [_ s]
      (println "Info:" s))
    (warn [_ s]
      (println "Warn:" s))
    (debug [_ s]
      (println "Debug:" s))))
</code>```

You could write a function that creates decorator implementations like so:

```<code>(defn decorate-fn
  "Creates a decorator function
   given the implementation accessor and the called function."
  [impl f]
  (fn [decorator & args]
    (apply f (impl decorator) args)))

(defn gen-decorators
  "Creates a map of decorator functions."
  [impl fs]
  (into {} (for [[k f] fs]
             [k (decorate-fn impl f)])))

(defn decorate-logger
  "Creates a logger decorator with functions
   passing through to the implementation by default."
  [impl overrides]
  (merge (gen-decorators impl
                         {:info info
                          :warn warn
                          :debug debug})
         overrides))
</code>```

And then use that to easily create decorators:

```<code>(defrecord CapslockWarningLogger [impl])

(extend CapslockWarningLogger
  Logger
  (decorate-logger :impl
                   {:warn (fn [{:keys [impl]} s]
                            (warn impl (clojure.string/upper-case s)))}))

(defrecord SelectiveDebugLogger [ignored impl])

(extend SelectiveDebugLogger
  Logger
  (decorate-logger :impl
                   {:debug (fn [{:keys [impl ignored]} s]
                             (when-not (ignored s)
                               (debug impl s)))}))

(def logger
  (->SelectiveDebugLogger #{"ignored"}
                          (->CapslockWarningLogger
                            println-logger)))

(info logger "something")
; Info: something
; => nil

(warn logger "something else")
; Warn: SOMETHING ELSE
; => nil

(debug logger "ignored")
; => nil
</code>```

Body:
One option is to use extend to merge a mix of delegating-by-default functions and overriding implementations.

For example, with a logger protocol like:

(defprotocol Logger
  (info [logger s])
  (warn [logger s])
  (debug [logger s]))

(def println-logger
  (reify Logger
    (info [_ s]
      (println "Info:" s))
    (warn [_ s]
      (println "Warn:" s))
    (debug [_ s]
      (println "Debug:" s))))

You could write a function that creates decorator implementations like so:

(defn decorate-fn
  "Creates a decorator function
   given the implementation accessor and the called function."
  [impl f]
  (fn [decorator & args]
    (apply f (impl decorator) args)))

(defn gen-decorators
  "Creates a map of decorator functions."
  [impl fs]
  (into {} (for [[k f] fs]
             [k (decorate-fn impl f)])))

(defn decorate-logger
  "Creates a logger decorator with functions
   passing through to the implementation by default."
  [impl overrides]
  (merge (gen-decorators impl
                         {:info info
                          :warn warn
                          :debug debug})
         overrides))

And then use that to easily create decorators:

(defrecord CapslockWarningLogger [impl])

(extend CapslockWarningLogger
  Logger
  (decorate-logger :impl
                   {:warn (fn [{:keys [impl]} s]
                            (warn impl (clojure.string/upper-case s)))}))

(defrecord SelectiveDebugLogger [ignored impl])

(extend SelectiveDebugLogger
  Logger
  (decorate-logger :impl
                   {:debug (fn [{:keys [impl ignored]} s]
                             (when-not (ignored s)
                               (debug impl s)))}))

(def logger
  (->SelectiveDebugLogger #{"ignored"}
                          (->CapslockWarningLogger
                            println-logger)))

(info logger "something")
; Info: something
; => nil

(warn logger "something else")
; Warn: SOMETHING ELSE
; => nil

(debug logger "ignored")
; => nil


答:
__getattr__ combined with defining a function on the fly should work:

```<code># somemodule

def print_uppercase(x):
    print(x.upper())
</code>```

Now:

```<code>from functools import wraps

import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    def __getattr__(self, attr):
        func = getattr(somemodule, attr)
        @wraps(func)
        def _wrapped(*args, **kwargs):
            if "t" in args:
                args = list(args)
                args[args.index("t")] = self.transforms["t"]
            return func(*args, **kwargs)
        return _wrapped

w = Wrapper()
w.print_uppercase('Hello')
w.print_uppercase('t')
</code>```

Output:

```<code>HELLO
TEST
</code>```

Title: Python: How do you intercept a method call to change function parameters?

Body:
__getattr__ combined with defining a function on the fly should work:

# somemodule

def print_uppercase(x):
    print(x.upper())

Now:

from functools import wraps

import somemodule

class Wrapper:
    def __init__(self):
        self.transforms = {}
        self.transforms["t"] = "test"

    def __getattr__(self, attr):
        func = getattr(somemodule, attr)
        @wraps(func)
        def _wrapped(*args, **kwargs):
            if "t" in args:
                args = list(args)
                args[args.index("t")] = self.transforms["t"]
            return func(*args, **kwargs)
        return _wrapped

w = Wrapper()
w.print_uppercase('Hello')
w.print_uppercase('t')

Output:

HELLO
TEST


问:
nth word in a text
how can I find the nth word in a text.

example:

```<code>my_txt("hello to you all" , 3)

all
</code>```

I don't wanna use any built in function ...and this is not a homework :D

答:
First let me say that I absolutely agree with the comments and the other answer, not using built in functions is stupid.  That being said, I found that attempting to write this code using as few built in function calls to be an interesting challenge, so I'll post what I came up with anyways.

```<code>def my_txt(txt, n, i=0):
    if n == 1:
        r = ""
        s = 0
        for c in txt:
            if s >= i:
                if c == " ":
                    return r
                r += c
            s += 1
    while txt[i] != " ":
        i += 1
    return my_txt(txt, n - 1, i + 1)

my_txt("hello to you all", 3) # returns 'you'
</code>```

My self inflicted rules: no slices, comprehensions, generators, or built in function calls.

This code will horribly fail when attempting to get the last word (unless there is a trailing space) or for any n out of the range of words.

Title: nth word in a text

Body:
how can I find the nth word in a text.

example:

my_txt("hello to you all" , 3)

all

I don't wanna use any built in function ...and this is not a homework :D

Body:
First let me say that I absolutely agree with the comments and the other answer, not using built in functions is stupid.  That being said, I found that attempting to write this code using as few built in function calls to be an interesting challenge, so I'll post what I came up with anyways.

def my_txt(txt, n, i=0):
    if n == 1:
        r = ""
        s = 0
        for c in txt:
            if s >= i:
                if c == " ":
                    return r
                r += c
            s += 1
    while txt[i] != " ":
        i += 1
    return my_txt(txt, n - 1, i + 1)

my_txt("hello to you all", 3) # returns 'you'

My self inflicted rules: no slices, comprehensions, generators, or built in function calls.

This code will horribly fail when attempting to get the last word (unless there is a trailing space) or for any n out of the range of words.


问:
Change Height and Width of TextArea in codemirror
I am developing website which having xml, java programs. So i chose CodeMirror for displaying programs in TextArea. I had successfully displayed. It's default height is 300px in codemirror.css. How to change Height and Width of TextArea programmatically in codemirror?

答:
```<code>myCodeMirror.setSize(null, 500);
</code>```

You can pass null for either of them to indicate that that dimension should not be changed.

Documentation:

```<code>cm.setSize(width: number|string, height: number|string)
</code>```

Programmatically set the size of the editor (overriding the applicable
  CSS rules). width and height can be either numbers (interpreted as
  pixels) or CSS units ("100%", for example). You can pass null for
  either of them to indicate that that dimension should not be changed.

Body:
myCodeMirror.setSize(null, 500);

You can pass null for either of them to indicate that that dimension should not be changed.

Documentation:

cm.setSize(width: number|string, height: number|string)

Programmatically set the size of the editor (overriding the applicable
  CSS rules). width and height can be either numbers (interpreted as
  pixels) or CSS units ("100%", for example). You can pass null for
  either of them to indicate that that dimension should not be changed.


问:
Rotate animation android from top right,Bottom left, Bottom right in android?
The below code helps me to rotate through left top edge of screen when swipe. can any one helps me how to rotate through remaining edges of the screen like top right edge, bottom right and left edges.
To be simple i need Rotate Page Transform as an animation for image view</p>

```<code>RotateAnimation r=new RotateAnimation(130,0,90,180);
</code>```

答:
If you need coordinates of imageview to rotate on particular edge you can get by using

```<code>     Rect rect = new Rect();
     imageview.getLocalVisibleRect(rect);
     int bottomimagevalue = rect.bottom;
     int rightimagevalue = rect.right;
</code>```

Using this coordinated you can rotate image

```<code> RotateAnimation r=new RotateAnimation(130,0,bottomimagevalue,rightimagevalue);
</code>```

the above is example for rotating image from bottom right corner

Body:
The below code helps me to rotate through left top edge of screen when swipe. can any one helps me how to rotate through remaining edges of the screen like top right edge, bottom right and left edges.
To be simple i need Rotate Page Transform as an animation for image view

RotateAnimation r=new RotateAnimation(130,0,90,180);

Body:
If you need coordinates of imageview to rotate on particular edge you can get by using

     Rect rect = new Rect();
     imageview.getLocalVisibleRect(rect);
     int bottomimagevalue = rect.bottom;
     int rightimagevalue = rect.right;

Using this coordinated you can rotate image

 RotateAnimation r=new RotateAnimation(130,0,bottomimagevalue,rightimagevalue);

the above is example for rotating image from bottom right corner


问:
Force Logout all devices in mvc 4 application?
I have mvc 4 project with default Account Controller and UsersContext as DbContext. When a user, Suppose User1 logged in with REMEMBER ME checked on mobile. And next day User1 login in Laptop and changed its password, now User1 opened his mobile it is already logged in even when password is changed.

Is there any way by which i can force that User1 to Logout all the Devices,
without storing any session id in database?

答:
I know this is an old topic but I ran across this today.  The cause was slightly different, but I needed to do the same thing - log off a user if 'remember me' had been chosen.

The cause in my case was a change of database.  I changed the database name in my connection string (from a 'test' DB to a 'dev' DB), and I will still logged in after running the project, which caused a problem because the user did not actually exist in this new DB.

So in Global.asax I did the following:

```<code>    private ApplicationUserManager _userManager;

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    protected void Session_Start()
    {
        if (User.Identity.IsAuthenticated)
        {
            var user = UserManager.FindByName(User.Identity.Name);
            if (user == null)
            {
                HttpContext.Current.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                Response.Redirect("/", true);
            }
        }
    }
</code>```

You need to redirect and terminate execution of the current page (by passing true) because (as I understand it) the sign out does not affect the current request, so the page that was loading will still load as if the user is logged in.  Anyone feel free to correct, clarify or expand upon this.

Body:
I know this is an old topic but I ran across this today.  The cause was slightly different, but I needed to do the same thing - log off a user if 'remember me' had been chosen.

The cause in my case was a change of database.  I changed the database name in my connection string (from a 'test' DB to a 'dev' DB), and I will still logged in after running the project, which caused a problem because the user did not actually exist in this new DB.

So in Global.asax I did the following:

    private ApplicationUserManager _userManager;

    public ApplicationUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    protected void Session_Start()
    {
        if (User.Identity.IsAuthenticated)
        {
            var user = UserManager.FindByName(User.Identity.Name);
            if (user == null)
            {
                HttpContext.Current.GetOwinContext().Authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                Response.Redirect("/", true);
            }
        }
    }

You need to redirect and terminate execution of the current page (by passing true) because (as I understand it) the sign out does not affect the current request, so the page that was loading will still load as if the user is logged in.  Anyone feel free to correct, clarify or expand upon this.


问:
WPF MainWindow to display other pages
I am trying to create a Main Window that will have a Header for navigation/buttons, and a footer for displaying information.
(similar to the top and bottom bars on StackOverflow.com)

What is the best way to make the Main Window function as a container that could display any page in between the header/footer?

答: create a page with 3 rows.  The top row being a height of 'auto' the middle row being of height '*' and the bottom row being height 'auto' as well.  The top and bottom row will take up as much room needed for the header and footer and the middle row will take up the rest of the room.</p>

Title: WPF MainWindow to display other pages


问:
Setting RootViewController in Appdelegate
I have storyboard in my application, but i don't want to set the Main storyboard file base name in info.plist, as well as I don't want to set the entry point i.e Is Initial View Controller in storyboard for any viewcontroller scene.

Though I want to launch the app with some scene from the storyboard, but all shows me a black screen.

When I tried

```<code>let testob:testClass = testClass()
self.window?.rootViewController = testob
</code>```

in AppDelegate, it didn't worked and got the same black screen.

But when I set the Main storyboard file base name in info.plist, and the entry point i.e Is Initial View Controller in storyboard every thing works.

Is there any solution to do so?

答:
You need to instantiate the window and make it key and visible.</p>

```<code>let bounds = UIScreen.main.bounds
self.window = UIWindow(frame: bounds)
self.window?.rootViewController = rootViewController
self.window?.makeKeyAndVisible()
</code>```

Body:
I have storyboard in my application, but i don't want to set the Main storyboard file base name in info.plist, as well as I don't want to set the entry point i.e Is Initial View Controller in storyboard for any viewcontroller scene.

Though I want to launch the app with some scene from the storyboard, but all shows me a black screen.

When I tried

let testob:testClass = testClass()
self.window?.rootViewController = testob

in AppDelegate, it didn't worked and got the same black screen.

But when I set the Main storyboard file base name in info.plist, and the entry point i.e Is Initial View Controller in storyboard every thing works.

Is there any solution to do so?

Body:
You need to instantiate the window and make it key and visible.

let bounds = UIScreen.main.bounds
self.window = UIWindow(frame: bounds)
self.window?.rootViewController = rootViewController
self.window?.makeKeyAndVisible()


问:
What is the idiomatic way to assoc several keys/values in a nested map in Clojure?
Imagine you have a map like this:

```<code>(def person {
  :name {
    :first-name "John"
    :middle-name "Michael"
    :last-name "Smith" }})
</code>```

What is the idiomatic way to change values associated with both :first-name and :last-name in one expression?

(Clarification: Let's say you want to set :first-name to "Bob" and :last-name to "Doe". Let's also say that this map has some other values in it that we want to preserve, so constructing it from scratch is not an option)

答:
Here are a couple of ways.

```<code>user> (update-in person [:name] assoc :first-name "Bob" :last-name "Doe")
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (update-in person [:name] merge {:first-name "Bob" :last-name "Doe"})
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (update-in person [:name] into {:first-name "Bob" :last-name "Doe"})
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (-> person
          (assoc-in [:name :first-name] "Bob")
          (assoc-in [:name :last-name]  "Doe"))
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}
</code>```

Edit

update-in does recursive assocs on your map.  In this case it's roughly equivalent to:

```<code>user> (assoc person :name
             (assoc (:name person)
                    :first-name "Bob"
                    :last-name "Doe"))
</code>```

The repetition of keys becomes more and more tedious as you go deeper into a series of nested maps.  update-in's recursion lets you avoid repeating keys (e.g. :name) over and over; intermediary results are stored on the stack between recursive calls.  Take a look at the source for update-in to see how it's done.

```<code>user> (def foo {:bar {:baz {:quux 123}}})
#'user/foo

user> (assoc foo :bar
             (assoc (:bar foo) :baz
                    (assoc (:baz (:bar foo)) :quux
                           (inc (:quux (:baz (:bar foo)))))))
{:bar {:baz {:quux 124}}}

user> (update-in foo [:bar :baz :quux] inc)
{:bar {:baz {:quux 124}}}
</code>```

assoc is dynamic (as are update-in, assoc-in, and most other Clojure functions that operate on Clojure data structures).  If assoc onto a map, it returns a map.  If you assoc onto a vector, it returns a vector.  Look at the source for assoc and take a look in in RT.java in the Clojure source for details.

Body:
Imagine you have a map like this:

(def person {
  :name {
    :first-name "John"
    :middle-name "Michael"
    :last-name "Smith" }})

What is the idiomatic way to change values associated with both :first-name and :last-name in one expression?

(Clarification: Let's say you want to set :first-name to "Bob" and :last-name to "Doe". Let's also say that this map has some other values in it that we want to preserve, so constructing it from scratch is not an option)

Body:
Here are a couple of ways.

user> (update-in person [:name] assoc :first-name "Bob" :last-name "Doe")
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (update-in person [:name] merge {:first-name "Bob" :last-name "Doe"})
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (update-in person [:name] into {:first-name "Bob" :last-name "Doe"})
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

user> (-> person
          (assoc-in [:name :first-name] "Bob")
          (assoc-in [:name :last-name]  "Doe"))
{:name {:middle-name "Michael", :last-name "Doe", :first-name "Bob"}}

Edit

update-in does recursive assocs on your map.  In this case it's roughly equivalent to:

user> (assoc person :name
             (assoc (:name person)
                    :first-name "Bob"
                    :last-name "Doe"))

The repetition of keys becomes more and more tedious as you go deeper into a series of nested maps.  update-in's recursion lets you avoid repeating keys (e.g. :name) over and over; intermediary results are stored on the stack between recursive calls.  Take a look at the source for update-in to see how it's done.

user> (def foo {:bar {:baz {:quux 123}}})
#'user/foo

user> (assoc foo :bar
             (assoc (:bar foo) :baz
                    (assoc (:baz (:bar foo)) :quux
                           (inc (:quux (:baz (:bar foo)))))))
{:bar {:baz {:quux 124}}}

user> (update-in foo [:bar :baz :quux] inc)
{:bar {:baz {:quux 124}}}

assoc is dynamic (as are update-in, assoc-in, and most other Clojure functions that operate on Clojure data structures).  If assoc onto a map, it returns a map.  If you assoc onto a vector, it returns a vector.  Look at the source for assoc and take a look in in RT.java in the Clojure source for details.


问:
Tensorflow: Merge two 2-D tensors according to even and odd indices
I want to perform a check for even and odd elements of the batch and swap them if needed. I managed to result with two tensors I want to interweave:

```<code>def tf_oplu(x, name=None):

    even = x[:,::2] #slicing into odd and even parts on the batch
    odd = x[:,1::2]

    even_flatten = tf.reshape(even, [-1]) # flatten tensors
    #in row-major order to apply function across them

    odd_flatten = tf.reshape(odd, [-1])

    compare = tf.to_float(even_flatten<odd_flatten)
    compare_not = tf.to_float(even_flatten>=odd_flatten)

    #def oplu(x,y): # trivial function
    #    if x<y : # (x<y)==1
    #       return y, x
    #    else:
    #       return x, y # (x<y)==0

    even_flatten_new = odd_flatten * compare + even_flatten * compare_not
    odd_flatten_new = odd_flatten * compare_not + even_flatten * compare

    # convolute back

    even_new = tf.reshape(even_flatten_new,[100,128])
    odd_new = tf.reshape(odd_flatten_new,[100,128])
</code>```

Now I want to get back $[100,256]$ tensor with even and odd places filled. In numpy I would of course do:

```<code>y = np.empty((even_new.size + odd_newsize,), dtype=even_new.dtype)
y[:,0::2] = even_new
y[:,1::2] = odd_new

return y
</code>```

But such thing is not possible for tensoflow, as tensor is not modifiable. I suppose it is possible with either sparse tensor or tf.gather_nd, but both require generating array of indices, which is again non-trivial task for me.
One more note: I don not want to use any python functions via tf.py_func, as I checked that they run on CPU only. Maybe lambda and tf.map_fn may help somehow? Thanks!

答:
You can use assign to assign into slices.

```<code>odd_new = tf.constant([1,3,5])
even_new = tf.constant([2,4,6])
y=tf.Variable(tf.zeros(6, dtype=tf.int32))

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
y[0::2].assign(odd_new).eval()
y[1::2].assign(even_new).eval()
</code>```

Body:
I want to perform a check for even and odd elements of the batch and swap them if needed. I managed to result with two tensors I want to interweave:

def tf_oplu(x, name=None):

    even = x[:,::2] #slicing into odd and even parts on the batch
    odd = x[:,1::2]

    even_flatten = tf.reshape(even, [-1]) # flatten tensors
    #in row-major order to apply function across them

    odd_flatten = tf.reshape(odd, [-1])

    compare = tf.to_float(even_flatten<odd_flatten)
    compare_not = tf.to_float(even_flatten>=odd_flatten)

    #def oplu(x,y): # trivial function
    #    if x<y : # (x<y)==1
    #       return y, x
    #    else:
    #       return x, y # (x<y)==0

    even_flatten_new = odd_flatten * compare + even_flatten * compare_not
    odd_flatten_new = odd_flatten * compare_not + even_flatten * compare

    # convolute back

    even_new = tf.reshape(even_flatten_new,[100,128])
    odd_new = tf.reshape(odd_flatten_new,[100,128])

Now I want to get back $[100,256]$ tensor with even and odd places filled. In numpy I would of course do:

y = np.empty((even_new.size + odd_newsize,), dtype=even_new.dtype)
y[:,0::2] = even_new
y[:,1::2] = odd_new

return y

But such thing is not possible for tensoflow, as tensor is not modifiable. I suppose it is possible with either sparse tensor or tf.gather_nd, but both require generating array of indices, which is again non-trivial task for me.
One more note: I don not want to use any python functions via tf.py_func, as I checked that they run on CPU only. Maybe lambda and tf.map_fn may help somehow? Thanks!

Body:
You can use assign to assign into slices.

odd_new = tf.constant([1,3,5])
even_new = tf.constant([2,4,6])
y=tf.Variable(tf.zeros(6, dtype=tf.int32))

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
y[0::2].assign(odd_new).eval()
y[1::2].assign(even_new).eval()


问:
Is there an idiomatic way to write the conditional operator when you want nothing to happen in one case?
Is there an idiomatic way to write the conditional operator when you want nothing to happen in one case?

For example, in the following I want to yield a value only if foo is truthy.

Syntactically I must include the second half of the conditional operator (the :), so is it idiomatic to put undefined here?

```<code>foo ? yield 'something' : undefined;
</code>```

答:
No. You can't.

If you do not want to happen nothing just go with simple if.

```<code>if(foo)
 yield 'something'
</code>```

Body:
Is there an idiomatic way to write the conditional operator when you want nothing to happen in one case?

For example, in the following I want to yield a value only if foo is truthy.

Syntactically I must include the second half of the conditional operator (the :), so is it idiomatic to put undefined here?

foo ? yield 'something' : undefined;

Body:
No. You can't.

If you do not want to happen nothing just go with simple if.

if(foo)
 yield 'something'


问:
TSQL puzzle, why is my update not random?
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

```<code>create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n
</code>```

It returns a very odd result set:

```<code>Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209
</code>```

And a second result set that makes complete sense:

```<code>n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339
</code>```

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?

答:
I have an idea:

maybe the value is being computed on every when statement, if it gets to the first one, computes a value other than 0 it goes to the second, it then computes a value other than 1, then the next and so on, if it makes it's way to 5 and then computes a number other than 5 it goes to else.

this would also explain why there are so many more "HOW IS THIS POSSIBLE" than the others, the others are incremented when the current position and the random number generated at that position match.

your thoughts?

edit: also i've tested in sql server express 2008 and it's the same outcome.

Body:
I was looking at postgres question and it called for updating a table with random values.

I only noticed it was targeted at postgres after answering it, but in answering it I hit a mystery.

Here is my sample code in question:

create table #Buildings([Use] varchar(50), n int)

insert #Buildings
select null,null from sysobjects

update #Buildings
set [Use] =
        case (ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6)
            when 0 then null
            when 1 then 'warehouse'
            when 2 then 'office'
            when 3 then 'market'
            when 4 then 'retail'
            when 5 then 'workshop'
            else 'HOW IS THIS POSSIBLE'
        end,
    n = ABS(CAST(CAST(NEWID() AS VARBINARY) AS int)) % 6

select [Use], count(*) from
#Buildings
group by [Use]

select n, count(*) from
#Buildings
group by n

It returns a very odd result set:

Use
-------------------------------------------------- -----------
workshop                                           128
HOW IS THIS POSSIBLE                               633
NULL                                               287
retail                                             140
warehouse                                          258
market                                             177
office                                             209

And a second result set that makes complete sense:

n
----------- -----------
0           292
3           300
1           313
4           277
5           311
2           339

The data for both result sets was generated in the same update statement.

So my question is why is a number out of the range of 0 - 5 hitting my case statement? What is that number? Why when I update the int directly is stuff distributed properly?

OwnerDisplayName: John Boker

LastEditorDisplayName: John Boker


问:
Script using the createCourses function using data from a sheet
I am creating a script using the createCourses function. The template code provided on google development support is where this began. Now I want to manipulate the template to pull data from a spreadsheet. Debuggin is giving me an error - "Invalid JSON payload received. Unknown name "name" at 'course': Proto field is not repeating, cannot start list." The data appears to be pulled but I can't figure out how to repeat the create function for all my courses.

Here is my code... I have replaced the sheets 'ID' on purpose!

```<code>function createCourses() {

  var course;
  course = Classroom.newCourse();

  var ss = SpreadsheetApp.openById('ID');

  course.name = ss.getRange("A2:A").getValues();
  course.ownerId = ss.getRange("H2:H").getValues();
  //course.id = "Bio10";

  course = Classroom.Courses.create(course);
  Logger.log('%s (%s)', course.name, course.id);

  var list = Classroom.Courses.create();
  Logger.log(create);

}
</code>```

答:
You don't say but I assume you are getting the error on the line var list = Classroom.Courses.create(); you're not passing any parameters to the .create() method.

To repeat the function you would just need to pull the range of data from the spreadsheet and use a for loop to iterate through the data and create your courses.

Body:
I am creating a script using the createCourses function. The template code provided on google development support is where this began. Now I want to manipulate the template to pull data from a spreadsheet. Debuggin is giving me an error - "Invalid JSON payload received. Unknown name "name" at 'course': Proto field is not repeating, cannot start list." The data appears to be pulled but I can't figure out how to repeat the create function for all my courses.

Here is my code... I have replaced the sheets 'ID' on purpose!

function createCourses() {

  var course;
  course = Classroom.newCourse();

  var ss = SpreadsheetApp.openById('ID');

  course.name = ss.getRange("A2:A").getValues();
  course.ownerId = ss.getRange("H2:H").getValues();
  //course.id = "Bio10";

  course = Classroom.Courses.create(course);
  Logger.log('%s (%s)', course.name, course.id);

  var list = Classroom.Courses.create();
  Logger.log(create);

}


问:
Pandas Shift Converts Ints to Float AND Rounds
When shifting column of integers, I know how to fix my column when Pandas automatically converts the integers to floats because of the presence of a NaN.
I basically use the method described here.

However, if the shift introduces a NaN thereby converting all integers to floats, there's some rounding that happens (e.g. on epoch timestamps) so even recasting it back to integer doesn't replicate what it was originally.

Any way to fix this?

Example Data:

```<code>pd.DataFrame({'epochee':[1495571400259317500,1495571400260585120,1495571400260757200, 1495571400260866800]})
Out[19]:
                 epoch
0  1495571790919317503
1  1495999999999999999
2  1495571400265555555
3  1495571400267777777
</code>```

Example Code:

```<code>df['prior_epochee'] = df['epochee'].shift(1)
df.dropna(axis=0, how='any', inplace=True)
df['prior_epochee'] = df['prior_epochee'].astype(int)
</code>```

Resulting output:

```<code>Out[22]:
                 epoch          prior_epoch
1  1444444444444444444  1400000000000000000
2  1433333333333333333  1490000000000000000
3  1777777777777777777  1499999999999999948
</code>```

答:
Because you know what happens when int is casted as float due to np.nan  and you know that you don't want the np.nan rows anyway, you can shift yourself with numpy

```<code>df[1:].assign(prior_epoch=df.epoch.values[:-1])

                 epoch          prior_epoch
1  1495571400260585120  1495571400259317500
2  1495571400260757200  1495571400260585120
3  1495571400260866800  1495571400260757200
</code>```

Body:
When shifting column of integers, I know how to fix my column when Pandas automatically converts the integers to floats because of the presence of a NaN.
I basically use the method described here.

However, if the shift introduces a NaN thereby converting all integers to floats, there's some rounding that happens (e.g. on epoch timestamps) so even recasting it back to integer doesn't replicate what it was originally.

Any way to fix this?

Example Data:

pd.DataFrame({'epochee':[1495571400259317500,1495571400260585120,1495571400260757200, 1495571400260866800]})
Out[19]:
                 epoch
0  1495571790919317503
1  1495999999999999999
2  1495571400265555555
3  1495571400267777777

Example Code:

df['prior_epochee'] = df['epochee'].shift(1)
df.dropna(axis=0, how='any', inplace=True)
df['prior_epochee'] = df['prior_epochee'].astype(int)

Resulting output:

Out[22]:
                 epoch          prior_epoch
1  1444444444444444444  1400000000000000000
2  1433333333333333333  1490000000000000000
3  1777777777777777777  1499999999999999948

Body:
Because you know what happens when int is casted as float due to np.nan  and you know that you don't want the np.nan rows anyway, you can shift yourself with numpy

df[1:].assign(prior_epoch=df.epoch.values[:-1])

                 epoch          prior_epoch
1  1495571400260585120  1495571400259317500
2  1495571400260757200  1495571400260585120
3  1495571400260866800  1495571400260757200


问:
IllegalStateException in main thread while implementing Hadoop Counters
I have used Counters in Hadoop to count different type of LIC customers. Below is my code -

Map

```<code>import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;

public class Map
            extends Mapper<LongWritable,Text,Text,IntWritable>
{

@Override
protected void map(LongWritable key,Text value,Context context)
                        throws IOException,InterruptedException
{
    String line = value.toString().trim();
    String[] part = line.split(" ");

    if(part.length > 1)
    {
        String str = part[0].toLowerCase();

        if(str.equals("LIC1"))
            context.getCounter("LIC1","lic1").increment(1);
        else if(str.equals("LIC2"))
            context.getCounter("LIC2", "lic2").increment(1);
        else
            context.getCounter("Others", "others").increment(1);

        context.write(new Text(str),new IntWritable(1));
    }
}
}
</code>```

Driver Class

```<code>import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MapReduceDriver
{
public static void main(String[] args) throws Exception
{
    Job job = new Job();

    job.setJarByClass(MapReduceDriver.class);
    job.setJobName("Counter Example");

    FileInputFormat.addInputPath(job,new Path(args[0]));
    FileOutputFormat.setOutputPath(job,new Path(args[1]));

    job.setMapperClass(Map.class);
    job.setNumReduceTasks(0);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    long lic1 = job.getCounters().findCounter("LIC1", "lic1").getValue();
    long lic2 = job.getCounters().findCounter("LIC2", "lic2").getValue();
    long others = job.getCounters().findCounter("Others",
         "others").getValue();

    System.out.println("LIC1= "+lic1);
    System.out.println("LIC2= "+lic2);
    System.out.println("Others= "+others);

    System.exit(job.waitForCompletion(true)?0:1);

}

}
</code>```

The following Exceptions are thrown for the Driver Class

```<code>Exception in thread "main" java.lang.IllegalStateException: Job in state
DEFINE instead of RUNNING
at org.apache.hadoop.mapreduce.Job.ensureState(Job.java:64)
at org.apache.hadoop.mapreduce.Job.getCounters(Job.java:425)
at MapReduceDriver.main(MapReduceDriver.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke
  (NativeMethodAccessorImpl.java:62)
  at
  sun.reflect.DelegatingMethodAccessorImpl.invoke
  (DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.apache.hadoop.util.RunJar.main(RunJar.java:156
</code>```

Can you please help me find out what is wrong with our code?

答: The job.getCounters() method works only for running jobs. And I do not see code to submit job for running in MapReduceDriver class. Add job.submit() to submit job to run into cluster and return immediately.

Body:
I have used Counters in Hadoop to count different type of LIC customers. Below is my code -

Map

import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Mapper;

public class Map
            extends Mapper<LongWritable,Text,Text,IntWritable>
{

@Override
protected void map(LongWritable key,Text value,Context context)
                        throws IOException,InterruptedException
{
    String line = value.toString().trim();
    String[] part = line.split(" ");

    if(part.length > 1)
    {
        String str = part[0].toLowerCase();

        if(str.equals("LIC1"))
            context.getCounter("LIC1","lic1").increment(1);
        else if(str.equals("LIC2"))
            context.getCounter("LIC2", "lic2").increment(1);
        else
            context.getCounter("Others", "others").increment(1);

        context.write(new Text(str),new IntWritable(1));
    }
}
}

Driver Class

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class MapReduceDriver
{
public static void main(String[] args) throws Exception
{
    Job job = new Job();

    job.setJarByClass(MapReduceDriver.class);
    job.setJobName("Counter Example");

    FileInputFormat.addInputPath(job,new Path(args[0]));
    FileOutputFormat.setOutputPath(job,new Path(args[1]));

    job.setMapperClass(Map.class);
    job.setNumReduceTasks(0);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    long lic1 = job.getCounters().findCounter("LIC1", "lic1").getValue();
    long lic2 = job.getCounters().findCounter("LIC2", "lic2").getValue();
    long others = job.getCounters().findCounter("Others",
         "others").getValue();

    System.out.println("LIC1= "+lic1);
    System.out.println("LIC2= "+lic2);
    System.out.println("Others= "+others);

    System.exit(job.waitForCompletion(true)?0:1);

}

}

The following Exceptions are thrown for the Driver Class

Exception in thread "main" java.lang.IllegalStateException: Job in state
DEFINE instead of RUNNING
at org.apache.hadoop.mapreduce.Job.ensureState(Job.java:64)
at org.apache.hadoop.mapreduce.Job.getCounters(Job.java:425)
at MapReduceDriver.main(MapReduceDriver.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke
  (NativeMethodAccessorImpl.java:62)
  at
  sun.reflect.DelegatingMethodAccessorImpl.invoke
  (DelegatingMethodAccessorImpl.java:43)
  at java.lang.reflect.Method.invoke(Method.java:498)
  at org.apache.hadoop.util.RunJar.main(RunJar.java:156

Can you please help me find out what is wrong with our code?


问:
AWS Lex receives Invalid Response from lambda function - Can not construct instance of IntentResponse
Using Java8 in eclipse AWS SDK, I've created and uploaded a lambda function that is hooked in upon fulfillment of my lex intent.
Lambda has not problem receiving JSON request and parsing.
Then, I format a simple "Close" dialogAction response and send back to lex and receive the following error from the Test Bot page in the lex console:

```<code>    An error has occurred: Received invalid response from Lambda:
    Can not construct instance of IntentResponse:
    no String-argument constructor/factory method to deserialize
    from String value
    ('{"dialogAction
    {"type":"Close","fulfillmentState":"Fulfilled","message":
    {"contentType":"PlainText","content":"Thanks I got your info"}}}')
    at [Source: "{\"dialogAction\":
    {\"type\":\"Close\",\"fulfillmentState\":\"Fulfilled\",\"message\":
   {\"contentType\":\"PlainText\",\"content\":\"Thanks I got your
   info\"}}}";line: 1, column: 1]
</code>```

It seems to have a problem right away with the format (line 1, column 1), but my JSON string looks ok to me. Before returning the output string in the handleRequest java function, I am writing the it to the Cloudwatch log and it writes as follows:

```<code>{
   "dialogAction": {
        "type": "Close",
        "fulfillmentState": "Fulfilled",
        "message": {
            "contentType": "PlainText",
            "content": "Thanks I got your info"
        }
    }
}
</code>```

Things I've tried:

Removing the message element as it's not required

Adding in non-required properties like sessionAttributes,
responseCard, etc

removing the double quotes

replacing double quotes with single quotes

hardcoding json from sample response format message in documentation

Is there something hidden at the http headers level or is java8 doing something to the JSON that is not visible?

答:
Not sure if this is because I'm using Java8 or not, but a return value of "String" from the RequestHandler class handleRequest method will not work.
Yes, String is an object, but the constructors on the Lex side are expecting an "Object".  I was converting my lex response POJO to a String before returning it in the handleRequest method.  That was my mistake.

I fixed it by changing the return type of the handleRequest method to be "Object" instead of "String".

```<code>public Object handleRequest(Object input, Context context)
</code>```

instead of

```<code>public String handleRequest(Object input, Context context)
</code>```

You also have to implement the

```<code> public class LambdaFunctionHandler implements RequestHandler<Object, Object>
</code>```

not

```<code>public class LambdaFunctionHandler implements RequestHandler<Object, String>
</code>```

This solved my issue.

Body:
Using Java8 in eclipse AWS SDK, I've created and uploaded a lambda function that is hooked in upon fulfillment of my lex intent.
Lambda has not problem receiving JSON request and parsing.
Then, I format a simple "Close" dialogAction response and send back to lex and receive the following error from the Test Bot page in the lex console:

    An error has occurred: Received invalid response from Lambda:
    Can not construct instance of IntentResponse:
    no String-argument constructor/factory method to deserialize
    from String value
    ('{"dialogAction
    {"type":"Close","fulfillmentState":"Fulfilled","message":
    {"contentType":"PlainText","content":"Thanks I got your info"}}}')
    at [Source: "{\"dialogAction\":
    {\"type\":\"Close\",\"fulfillmentState\":\"Fulfilled\",\"message\":
   {\"contentType\":\"PlainText\",\"content\":\"Thanks I got your
   info\"}}}";line: 1, column: 1]

It seems to have a problem right away with the format (line 1, column 1), but my JSON string looks ok to me. Before returning the output string in the handleRequest java function, I am writing the it to the Cloudwatch log and it writes as follows:

{
   "dialogAction": {
        "type": "Close",
        "fulfillmentState": "Fulfilled",
        "message": {
            "contentType": "PlainText",
            "content": "Thanks I got your info"
        }
    }
}

Things I've tried:

Removing the message element as it's not required

Adding in non-required properties like sessionAttributes,
responseCard, etc

removing the double quotes

replacing double quotes with single quotes

hardcoding json from sample response format message in documentation

Is there something hidden at the http headers level or is java8 doing something to the JSON that is not visible?

Body:
Not sure if this is because I'm using Java8 or not, but a return value of "String" from the RequestHandler class handleRequest method will not work.
Yes, String is an object, but the constructors on the Lex side are expecting an "Object".  I was converting my lex response POJO to a String before returning it in the handleRequest method.  That was my mistake.

I fixed it by changing the return type of the handleRequest method to be "Object" instead of "String".

public Object handleRequest(Object input, Context context)

instead of

public String handleRequest(Object input, Context context)

You also have to implement the

 public class LambdaFunctionHandler implements RequestHandler<Object, Object>

not

public class LambdaFunctionHandler implements RequestHandler<Object, String>

This solved my issue.


问:
version `GLIBC_2.7' not found when import pytorch
I have downloaded torch-0.1.12.post2-cp27-none-linux_x86_64.whl(from http://download.pytorch.org/whl/cu75/torch-0.1.12.post2-cp27-none-linux_x86_64.whl ) file and use the following command to install.

```<code>pip install torch-0.1.12.post2-cp27-none-linux_x86_64.whl
pip install pip install torchvision
</code>```

However, the error occurs when import torch

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/my/lib/python2.7/site-packages/torch/__init__.py", line 53, in <module>
    from torch._C import *
ImportError: /lib64/tls/libc.so.6: version `GLIBC_2.7' not found (required by /home/my/lib/python2.7/site-packages/torch/lib/libTH.so.1)
</code>```

My Linux kernel is 2.6.32_1-19-0-0 and GCC version is 4.8.3

How can I fix this problem?

答:
What's the output of running /lib64/tls/libc.so.6?

PyTorch requires glibc version 2.7 or newer. You may need to update your glibc version.

Body:
I have downloaded torch-0.1.12.post2-cp27-none-linux_x86_64.whl(from http://download.pytorch.org/whl/cu75/torch-0.1.12.post2-cp27-none-linux_x86_64.whl ) file and use the following command to install.

pip install torch-0.1.12.post2-cp27-none-linux_x86_64.whl
pip install pip install torchvision

However, the error occurs when import torch

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/my/lib/python2.7/site-packages/torch/__init__.py", line 53, in <module>
    from torch._C import *
ImportError: /lib64/tls/libc.so.6: version `GLIBC_2.7' not found (required by /home/my/lib/python2.7/site-packages/torch/lib/libTH.so.1)

My Linux kernel is 2.6.32_1-19-0-0 and GCC version is 4.8.3

How can I fix this problem?


问:
Vue components with partial reusability
I'm working on a large app with legacy code.  I've run into this issue twice now and am realizing there must be a better solution than what I've done to solve it.  The issue is as follows.

There are 3 separate pages where I need to add very similar Vue functionality.  However, these pages have significantly different HTML/Blade templates.  Therefore, it's like I have to pass in separate HTML/Blade templates to the component in addition to component props.

I can kind of accomplish this using Vue inline-templates, which takes care of the significantly different HTML/Blade template problem.

However, the remaining issue is that I have 3 .js Vue components, one for each page.  This would be fine, except the Vue code in each file is very similar.

It's also possible that at some point I will need to add more unique Vue code to each component, and would like to keep that possibility open.

What I would like to do is find a way to reuse the Vue code that is very similar in each component.

I have tried thinking of a way to nest the same child component within each of these 3 separate components, but I don't see how that would be possible due to the differences in the HTML/Blade in each file.

Any suggestions would be most appreciated, as I feel like I'm duplicating too much Vue code!

答:
Thanks to user thanksd for providing the solution in the comments above.  Mixins indeed were the way to go for me.  That way, instead of this:

```<code>Vue.component('first-component', {
    template: // something unique
    methods : {
        functionNumber1: function () {
            // do something
        },
});

Vue.component('second-component', {
    template: // something totally different
    methods : {
        functionNumber1: function () {
            // do same something
        },
    }

});
</code>```

I can essentially do this:

```<code>const myMixin = {
    methods : {
        functionNumber1: function () {
            // do same something
        },
}

Vue.component('first-component', {
    template: // something unique
    mixins: ['myMixin']
});

Vue.component('second-component', {
    template: // something totally different
    mixins: ['myMixin']
});
</code>```

Title: Vue components with partial reusability

Body:
Thanks to user thanksd for providing the solution in the comments above.  Mixins indeed were the way to go for me.  That way, instead of this:

Vue.component('first-component', {
    template: // something unique
    methods : {
        functionNumber1: function () {
            // do something
        },
});

Vue.component('second-component', {
    template: // something totally different
    methods : {
        functionNumber1: function () {
            // do same something
        },
    }

});

I can essentially do this:

const myMixin = {
    methods : {
        functionNumber1: function () {
            // do same something
        },
}

Vue.component('first-component', {
    template: // something unique
    mixins: ['myMixin']
});

Vue.component('second-component', {
    template: // something totally different
    mixins: ['myMixin']
});


问:
Move first row from a csv to another using php
What I need to do is to be able to move the first row from a testdata.csv every time I run the .php to another .csv with the name testdata_new.csv(appending data).

This is an example of data that includes Name, Age, Job

Example data testdata.csv:

John,32,Scientist

  Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

This is what the .php will do running it:
Cut the first row from testdata.csv(john,32,scientist) and paste it to the new testdata_new.csv under the first row(header) that will always be "Name Age Job".
Save testdata_new.csv and testdata.csv with the remaining rows.

I did some tests but I'm still far away from the solution.

```<code><?php

    $file = "testdata.csv";
    $f = fopen($file, "r");
    $i = 0;

    $file2 = str_replace(".csv", "_new.csv", $file);
    $f2 = fopen($file2,"a");

    while ($i<2) {
        $record = fgetcsv($f);
        foreach($record as $field) {
            echo $field . "<br>";
        }

        $i++;
    }

    fwrite($f2,fread($f, filesize($file)));

    fclose($f);
    fclose($f2);

?>
</code>```

Executing the script will display the first row of the template.csv file
and will produce another file with the name template_new.csv with the following rows:

Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

What I really need to have in the template_new.csv file is only the first row displayed:

John,32,Scientist

And save again the template.csv without the first row as the idea is to cut and paste the rows, as following:

Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

Thank you all in advance for your help!

答:
As easy as this ;-)</p>

```<code>$old_file = 'testdata.csv';
$new_file = 'testdata_new.csv';

$file_to_read = file_get_contents($old_file);  // Reading entire file
$lines_to_read = explode("\n", $file_to_read);  // Creating array of lines

if ( $lines_to_read == '' ) die('EOF'); // No data

$line_to_append = array_shift( $lines_to_read ); // Extracting first line

$file_to_append = file_get_contents($new_file);  // Reading entire file

if ( substr($file_to_append, -1, 1) != "\n" ) $file_to_append.="\n";  // If new file doesn't ends in new line I add it

// Writing files
file_put_contents($new_file, $file_to_append . $line_to_append . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));
</code>```

Body:
What I need to do is to be able to move the first row from a testdata.csv every time I run the .php to another .csv with the name testdata_new.csv(appending data).

This is an example of data that includes Name, Age, Job

Example data testdata.csv:

John,32,Scientist

  Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

This is what the .php will do running it:
Cut the first row from testdata.csv(john,32,scientist) and paste it to the new testdata_new.csv under the first row(header) that will always be "Name Age Job".
Save testdata_new.csv and testdata.csv with the remaining rows.

I did some tests but I'm still far away from the solution.

<?php

    $file = "testdata.csv";
    $f = fopen($file, "r");
    $i = 0;

    $file2 = str_replace(".csv", "_new.csv", $file);
    $f2 = fopen($file2,"a");

    while ($i<2) {
        $record = fgetcsv($f);
        foreach($record as $field) {
            echo $field . "
";
        }

        $i++;
    }

    fwrite($f2,fread($f, filesize($file)));

    fclose($f);
    fclose($f2);

?>

Executing the script will display the first row of the template.csv file
and will produce another file with the name template_new.csv with the following rows:

Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

What I really need to have in the template_new.csv file is only the first row displayed:

John,32,Scientist

And save again the template.csv without the first row as the idea is to cut and paste the rows, as following:

Mary,25,Employer

  Nick,36,Designer

  Miky,46,Sales

  Alex,29,Logistics

Thank you all in advance for your help!

Body:
As easy as this ;-)

$old_file = 'testdata.csv';
$new_file = 'testdata_new.csv';

$file_to_read = file_get_contents($old_file);  // Reading entire file
$lines_to_read = explode("\n", $file_to_read);  // Creating array of lines

if ( $lines_to_read == '' ) die('EOF'); // No data

$line_to_append = array_shift( $lines_to_read ); // Extracting first line

$file_to_append = file_get_contents($new_file);  // Reading entire file

if ( substr($file_to_append, -1, 1) != "\n" ) $file_to_append.="\n";  // If new file doesn't ends in new line I add it

// Writing files
file_put_contents($new_file, $file_to_append . $line_to_append . "\n");
file_put_contents($old_file, implode("\n", $lines_to_read));