问:
Pushsharp support of Apple Push Notification Authentication Key
Does pushsharp supports a new Apple approach for sending APN using Apple Push Notification Authentication Key (which never expires) instead of using Certificates? Is any way to use it with pushsharp? If not, is there any other C# library to support it?

答:
here you are:

```<code>private string GetToken()
{
    var algorithm = "ES256";
    var teamID = "teamID";
    var apnsKeyID = "apnsKeyID";
    var apnsAuthKeyPath = @"apnsAuthKeyPath";
    var epochNow = DateTimeOffset.Now.ToUnixTimeSeconds();

    var header = new Dictionary<string, object>()
    {
        { "alg", algorithm },
        { "kid" , apnsKeyID }
    };
    var payload = new Dictionary<string, object>()
    {
        { "iss", teamID },
        { "iat", epochNow }
    };

    var privateKey = GetPrivateKey(apnsAuthKeyPath);
    var token = Jose.JWT.Encode(payload, privateKey, algorithm: Jose.JwsAlgorithm.ES256, extraHeaders: header);
    return token;
}
private CngKey GetPrivateKey(string apnsAuthKey)
{
    using (var reader = File.OpenText(apnsAuthKey))
    {
        var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
        var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
        var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
        return EccKey.New(x, y, d);
    }
}
</code>```

then you can simply call send method in apns.

Body:
here you are:

private string GetToken()
{
    var algorithm = "ES256";
    var teamID = "teamID";
    var apnsKeyID = "apnsKeyID";
    var apnsAuthKeyPath = @"apnsAuthKeyPath";
    var epochNow = DateTimeOffset.Now.ToUnixTimeSeconds();

    var header = new Dictionary<string, object>()
    {
        { "alg", algorithm },
        { "kid" , apnsKeyID }
    };
    var payload = new Dictionary<string, object>()
    {
        { "iss", teamID },
        { "iat", epochNow }
    };

    var privateKey = GetPrivateKey(apnsAuthKeyPath);
    var token = Jose.JWT.Encode(payload, privateKey, algorithm: Jose.JwsAlgorithm.ES256, extraHeaders: header);
    return token;
}
private CngKey GetPrivateKey(string apnsAuthKey)
{
    using (var reader = File.OpenText(apnsAuthKey))
    {
        var ecPrivateKeyParameters = (ECPrivateKeyParameters)new PemReader(reader).ReadObject();
        var x = ecPrivateKeyParameters.Parameters.G.AffineXCoord.GetEncoded();
        var y = ecPrivateKeyParameters.Parameters.G.AffineYCoord.GetEncoded();
        var d = ecPrivateKeyParameters.D.ToByteArrayUnsigned();
        return EccKey.New(x, y, d);
    }
}

then you can simply call send method in apns.


来源: stackexchange

问:
Best practices in unit-test writing
I have a "best practices" question. I'm writing a test for a certain method, but there are multiple entry values. Should I write one test for each entry value or should I change the entryValues variable value, and call the .assert() method (doing it for all range of possible values)?

Thank you for your help.
Best regards,

Pedro Magueija

edited: I'm using .NET. Visual Studio 2010 with VB.

答:
Should I write one test for each entry
  value or should I change the
  entryValues variable value, and call
  the .assert() method (doing it for all
  range of possible values)?

If you have one code path typically you do not test all possible inputs.  What you usually want to test are "interesting" inputs that make good exemplars of the data you will get.

For example if I have a function

```<code>define add_one(num) {
  return num+1;
}
</code>```

I can't write a test for all possible values so I may use MAX_NEGATIVE_INT, -1, 0, 1, MAX_POSITIVE_INT as my test set because they are a good representatives of interesting values I might get.

You should have at least one input for every code path.  If you have a function where every value corresponds to a unique code path then I would consider writing a tests for the complete range of possible values.  And example of this would be a command parser.

```<code>define execute(directive) {
  if (directive == 'quit') { exit; }
  elsif (directive == 'help') { print help; }
  elsif (directive == 'connect') { intialize_connection(); }
  else { warn("unknown directive"); }
}
</code>```

For the purpose of clarity I used elifs rather than a dispatch table.  I think this make it's clear that each unique value that comes in has a different behavior and therefore you would need to test every possible value.

ContentLicense: CC BY-SA 2.5

Title: Best practices in unit-test writing

Body:
Should I write one test for each entry
  value or should I change the
  entryValues variable value, and call
  the .assert() method (doing it for all
  range of possible values)?

If you have one code path typically you do not test all possible inputs.  What you usually want to test are "interesting" inputs that make good exemplars of the data you will get.

For example if I have a function

define add_one(num) {
  return num+1;
}

I can't write a test for all possible values so I may use MAX_NEGATIVE_INT, -1, 0, 1, MAX_POSITIVE_INT as my test set because they are a good representatives of interesting values I might get.

You should have at least one input for every code path.  If you have a function where every value corresponds to a unique code path then I would consider writing a tests for the complete range of possible values.  And example of this would be a command parser.

define execute(directive) {
  if (directive == 'quit') { exit; }
  elsif (directive == 'help') { print help; }
  elsif (directive == 'connect') { intialize_connection(); }
  else { warn("unknown directive"); }
}

For the purpose of clarity I used elifs rather than a dispatch table.  I think this make it's clear that each unique value that comes in has a different behavior and therefore you would need to test every possible value.


问:
Is it possible to dynamically load a library at runtime from an Android application?
Is there any way to make an Android application to download and use a Java library at runtime?

Here is an example:

Imagine that the application needs to make some calculations depending on the input values. The application asks for these input values and then checks if the required Classes or Methods are available.

If not, it connects to a server, downloads the needed library, and loads it at runtime to calls the required methods using reflection techniques. The implementation could change depending on various criteria such as the user who is downloading the library.

答:
Technically should work but what about Google rules?
From: play.google.com/intl/en-GB/about/developer-content-policy-print

An app distributed via Google Play may not modify, replace or update
  itself using any method other than Google Play’s update mechanism.
  Likewise, an app may not download executable code (e.g. dex, JAR, .so
  files) from a source other than Google Play. This restriction does not
  apply to code that runs in a virtual machine and has limited access to
  Android APIs (such as JavaScript in a WebView or browser).

ContentLicense: CC BY-SA 3.0


问:
Converting .exe to VS solution file / project
I've recently had an issue at work where I have lost my solution files to my projects, but I still have the executables that have been produced by the projects / solution.  It has been collection of 50+ webforms.

I have tried some de-compiler tools like ILSpy, JustComplie and .Net Reflector but everything gives source code in different format (not originally written by me) and also not designs of forms.

Is there any possibility to decompiling the executable back into a solution/project file?

答:
There is a Decompiler that works very well for .Net applications called DNSpy.
Here is link to the Project :
https://github.com/0xd4d/dnSpy

After you have decompiled you can start debugging and such from this application.

Hope this help.

ContentLicense: CC BY-SA 4.0


问:
Using @ViewChild { read: ElementRef } of component causes unit test to fail
In my component I have a child component that looks like this:

```<code><child-component #childComponent></childComponent>
</code>```

In my parent component I then access this child component using @ViewChild and the read parameter to get the ElementRef, and not the component reference. I need the ElementRef to ensure I can get some properties from nativeElement that I need. So it's like this:

```<code>export class ParentComponent {
  @ViewChild('childComponent', { read: ElementRef }) public childComponent: ElementRef;
  public position: string;

  // some way down the code
  private someMethod() {
    if (this.childComponent.nativeElement.offsetLeft > 500) {
      this.position = 'left';
    } else {
      this.position = 'right';
    }
  }
}
</code>```

So this works for the application, however I am writing the tests and mocking the child component, like this:

```<code>@Component({
  selector: 'child-component',
  template: ''
})
class ChildComponentMockComponent {
  private nativeElement = {
    get offsetLeft() {
      return 600
    }
  };
}

beforeEach(async(() => TestBed.configureTestingModule({
  imports: [ ... ],
  declarations: [ ParentComponent, ChildComponentMockComponent ],
  providers: [ ... ],
  schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents()));

it('should have the correct position, based on position of child-component', () => {
  spyOn(component, 'someMethod');
  expect(component.someMethod).toHaveBeenCalled();
  expect(component.position).toBe('left');
});
</code>```

So the test will compile the component, and use the mocked child component values as the proper value and compute the value of this.position, which is then asserted in the test.

However, when the { read: ElementRef } parameter is set, the mock gets completely ignored by the TestBed, even though it's being added in the declarations array. If I remove { read: ElementRef }, the mock is used in the test and it passes. But then my application doesn't work, as it is now getting the component reference, where the nativeElement property doesn't exist, rather than the element reference.

So how do I get the ElementRef in my application and then in my test use the mock component?

答:
I have fixed this by changing the architecture of the app. The child component now finds it's own offsetLeft property, and then puts it into an output EventEmitter to be picked up the parent component.

```<code>export class ChildComponent implements AfterViewInit {
  @Output() offsetPosition: EventEmitter<number> = new EventEmitter<number>();

  constructor(private el: ElementRef) {}

  public ngAfterViewInit() {
    this.offsetPosition.emit(this.el.nativeElement.offsetLeft);
  }
}

export class ParentComponent implements AfterViewInit {
  public childComponentOffset: number;

  public ngAfterViewInit() {
    setTimeout(() => {
      // this.childComponentOffset is available
      // needs to be in setTimeout to prevent ExpressionChangedAfterItHasBeenCheckedError
      // more info: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
    }
  }

  public getChildComponentOffset(position: number): void {
    this.childComponentOffset = position;
  }
}
</code>```

And then in the HTML, you just define the child component with output variable and method:

```<code><child-component (offsetPosition)="getChildComponentOffset($event)"></child-component>
</code>```

In the test, I then mock ElementRef for the child component and use it as a provider.

```<code>const mockElementRef: any = {
  get offsetLeft() {
    return position;
  }
};

beforeEach(async(() => TestBed.configureTestingModule({
  imports: [ ... ],
  declarations: [ ParentComponent ],
  providers: [
    { provide: ElementRef, useValue: mockElementRef }
  ],
  schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents()));

it('should have the correct position, based on position of child-component', (done) => {
  component.getChildComponentOffset(600);
  setTimeout(() => expect(component.position).toBe('left'));
  done();
});
</code>```

Body:
In my component I have a child component that looks like this:

<child-component #childComponent></childComponent>

In my parent component I then access this child component using @ViewChild and the read parameter to get the ElementRef, and not the component reference. I need the ElementRef to ensure I can get some properties from nativeElement that I need. So it's like this:

export class ParentComponent {
  @ViewChild('childComponent', { read: ElementRef }) public childComponent: ElementRef;
  public position: string;

  // some way down the code
  private someMethod() {
    if (this.childComponent.nativeElement.offsetLeft > 500) {
      this.position = 'left';
    } else {
      this.position = 'right';
    }
  }
}

So this works for the application, however I am writing the tests and mocking the child component, like this:

@Component({
  selector: 'child-component',
  template: ''
})
class ChildComponentMockComponent {
  private nativeElement = {
    get offsetLeft() {
      return 600
    }
  };
}

beforeEach(async(() => TestBed.configureTestingModule({
  imports: [ ... ],
  declarations: [ ParentComponent, ChildComponentMockComponent ],
  providers: [ ... ],
  schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents()));

it('should have the correct position, based on position of child-component', () => {
  spyOn(component, 'someMethod');
  expect(component.someMethod).toHaveBeenCalled();
  expect(component.position).toBe('left');
});

So the test will compile the component, and use the mocked child component values as the proper value and compute the value of this.position, which is then asserted in the test.

However, when the { read: ElementRef } parameter is set, the mock gets completely ignored by the TestBed, even though it's being added in the declarations array. If I remove { read: ElementRef }, the mock is used in the test and it passes. But then my application doesn't work, as it is now getting the component reference, where the nativeElement property doesn't exist, rather than the element reference.

So how do I get the ElementRef in my application and then in my test use the mock component?

Body:
I have fixed this by changing the architecture of the app. The child component now finds it's own offsetLeft property, and then puts it into an output EventEmitter to be picked up the parent component.

export class ChildComponent implements AfterViewInit {
  @Output() offsetPosition: EventEmitter<number> = new EventEmitter<number>();

  constructor(private el: ElementRef) {}

  public ngAfterViewInit() {
    this.offsetPosition.emit(this.el.nativeElement.offsetLeft);
  }
}

export class ParentComponent implements AfterViewInit {
  public childComponentOffset: number;

  public ngAfterViewInit() {
    setTimeout(() => {
      // this.childComponentOffset is available
      // needs to be in setTimeout to prevent ExpressionChangedAfterItHasBeenCheckedError
      // more info: https://blog.angularindepth.com/everything-you-need-to-know-about-the-expressionchangedafterithasbeencheckederror-error-e3fd9ce7dbb4
    }
  }

  public getChildComponentOffset(position: number): void {
    this.childComponentOffset = position;
  }
}

And then in the HTML, you just define the child component with output variable and method:

<child-component (offsetPosition)="getChildComponentOffset($event)"></child-component>

In the test, I then mock ElementRef for the child component and use it as a provider.

const mockElementRef: any = {
  get offsetLeft() {
    return position;
  }
};

beforeEach(async(() => TestBed.configureTestingModule({
  imports: [ ... ],
  declarations: [ ParentComponent ],
  providers: [
    { provide: ElementRef, useValue: mockElementRef }
  ],
  schemas: [ NO_ERRORS_SCHEMA ]
}).compileComponents()));

it('should have the correct position, based on position of child-component', (done) => {
  component.getChildComponentOffset(600);
  setTimeout(() => expect(component.position).toBe('left'));
  done();
});


问:
in angular2 while import ngx-store in appmodule.ts
Failed to load resource: the server responded with a status of 404 (Not Found)
index.html:54 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:56455/src/ngx-store
    Error: XHR error (404 Not Found) loading http://localhost:56455/src/ngx-store
        at XMLHttpRequest.wrapFn
    Error loading http://localhost:56455/src/ngx-store as "ngx-store" from http://localhost:56455/src/app/app.module.js</p>

答:
Most likely you haven't configured systemjs correctly to setup ngrx-store with systemjs use a config that has the following:</p>

```<code>System.config({
    packages: {

        '@ngrx/store': {
            main: 'dist/index.js',
            format: 'cjs'
        },
        '@ngrx/devtools': {
            main: 'dist/index.js',
            format: 'cjs'
        }
    },
    map: {
        '@ngrx': 'node_modules/@ngrx'
    }
});
</code>```

Body:
Most likely you haven't configured systemjs correctly to setup ngrx-store with systemjs use a config that has the following:

System.config({
    packages: {

        '@ngrx/store': {
            main: 'dist/index.js',
            format: 'cjs'
        },
        '@ngrx/devtools': {
            main: 'dist/index.js',
            format: 'cjs'
        }
    },
    map: {
        '@ngrx': 'node_modules/@ngrx'
    }
});


问:
Qt Creator: different behavior of class template in Debug and Release modes
I'm trying to specialize template member function. The problem is that in Debug mode calls specialization of method, but in Release calls non-specialized function.

For example, I have class template and specialized method

```<code>template <typename T>
class SimpleClass
{
public:
    void doSomething(const T& arg)
    {
        std::cout << "doSomething(const T& arg)" << std::endl;
    }
};
template <>
void SimpleClass<double>::doSomething(const double& arg)
{
    std::cout << "doSomething(const double& arg)" << std::endl;
}

int main(int argc, char **argv)
{
    SimpleClass<double> obj;
    obj.doSomething(1);
    return 0;
}
</code>```

I'm expecting, that output will "doSomething(const double& arg)".

So in Debug mode I got it, but in Release I got this: "doSomething(const T& arg)"

My question is why that code behave this way and how can I fix it?
Just in case, my .pro file

```<code>TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
SOURCES += main.cpp \
    mathop.cpp
HEADERS += \
    mathop.h
</code>```

edit: I'm using Qt 5.9.1

edit: forgot #include <iostream> before using cout

答:
As you're calling doSomething() with an integer as parameter, I guess the compiler is just trying to find an arbitrary match here. I can't say why debug and release builds behave differently, but I would expect it to work as expected when explicitely using a float value in the call:

```<code>obj.doSomething(1.0);
</code>```

Body:
I'm trying to specialize template member function. The problem is that in Debug mode calls specialization of method, but in Release calls non-specialized function.

For example, I have class template and specialized method

template <typename T>
class SimpleClass
{
public:
    void doSomething(const T& arg)
    {
        std::cout << "doSomething(const T& arg)" << std::endl;
    }
};
template <>
void SimpleClass<double>::doSomething(const double& arg)
{
    std::cout << "doSomething(const double& arg)" << std::endl;
}

int main(int argc, char **argv)
{
    SimpleClass<double> obj;
    obj.doSomething(1);
    return 0;
}

I'm expecting, that output will "doSomething(const double& arg)".

So in Debug mode I got it, but in Release I got this: "doSomething(const T& arg)"

My question is why that code behave this way and how can I fix it?
Just in case, my .pro file

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
SOURCES += main.cpp \
    mathop.cpp
HEADERS += \
    mathop.h

edit: I'm using Qt 5.9.1

edit: forgot #include <iostream> before using cout

Body:
As you're calling doSomething() with an integer as parameter, I guess the compiler is just trying to find an arbitrary match here. I can't say why debug and release builds behave differently, but I would expect it to work as expected when explicitely using a float value in the call:

obj.doSomething(1.0);


问:
WPF -Child datacontext set from the parent ViewModel doesnot contains the modified values in the parent ViewModel
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

```<code><Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>
</code>```

MainWindowVM.cs

```<code> ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);
</code>```

ProfileIdentitySettings.xaml

```<code>DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">
</code>```

答:
Set the datacontext of each of your usercontrol in the xaml

```<code><UserControl.DataContext>
    <VMPath:ChildVM/>
</UserControl.DataContext>
</code>```

then add a loaded event for your user controls defined in your MainWindow

```<code><ViewPath:MyUserControl x:Name="uc1" Loaded="UserControlLoaded"/>
</code>```

in your code behind you'll have

```<code>    private void UserControlLoaded(object sender, RoutedEventArgs e)
    {
        ParentVM vm = this.DataContext as VM;
        ChildVM cvm = uc1.DataContext as ChildVM;
        // do your stuff
    }
</code>```

if the operation you need to do are always the same you can use 1 method to all of your UserControl.

Basically what you are going to do are the following operation.

set statically the dantacontext for your user controls to an instance of an "empty" ChildVM

load your controls

after the loading do the operation you need to do on your ChildVM (like set some properties)

All of this before you can actually use your app

Body:
In my WPF application I have a MainWindow.xaml which has many User Controls embedded into it. I have separate viewmodel for both the main window as well as the user controls. In the Main Window ViewModel I create an instance of the child ViewModel and set it as the child's datacontext.

Parent VM
ChildUserControlVM ChildVM = new ChildUserControlVM (ParentModel.ChildModel);

MainWindow.xaml

But this approach is not working as I am not getting the values set in the parent viewmodel in the child one and vice versa.

On the contrary, if I set the Child model object as the datacontext from the parent that is working both way.

I need some solution so that I can use MVVM in the user controls also ensuring data gets passed from parent to child and vice versa.
In the usercontrol I am going to have some buttons whose action I want to handle in the child Viewmodel through ICommand.
Adding the code snippets for reference
MainWindow.xaml

<Grid Grid.Row="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0">
    <local:ProfileIdentitySettings Visibility="{Binding ProfileIdentitySettingsVisibility,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" DataContext="{Binding ChildProfileIdentityVM}"/>
</Grid>

MainWindowVM.cs

 ProfileIdentitySettingsVM ChildProfileIdentityVM = new ProfileIdentitySettingsVM(DeviceEditorModel.ProfileIdentitySettings);

ProfileIdentitySettings.xaml

DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.MainWindowVM}">

Body:
Set the datacontext of each of your usercontrol in the xaml

<UserControl.DataContext>
    <VMPath:ChildVM/>
</UserControl.DataContext>

then add a loaded event for your user controls defined in your MainWindow

<ViewPath:MyUserControl x:Name="uc1" Loaded="UserControlLoaded"/>

in your code behind you'll have

    private void UserControlLoaded(object sender, RoutedEventArgs e)
    {
        ParentVM vm = this.DataContext as VM;
        ChildVM cvm = uc1.DataContext as ChildVM;
        // do your stuff
    }

if the operation you need to do are always the same you can use 1 method to all of your UserControl.

Basically what you are going to do are the following operation.

set statically the dantacontext for your user controls to an instance of an "empty" ChildVM

load your controls

after the loading do the operation you need to do on your ChildVM (like set some properties)

All of this before you can actually use your app


问:
PHP and Apache Ignite - very slow query
Firstly, sorry for my English.

I start to use Apache Ignite with PHP (PDO, UnixODBC, Ignite ODBC driver). I successfully installed it and configured Ignite, DSN and ODBC on my linux server (Debian). I installed php-odbc extension and everything looks well.

I start Apache Ignite by: ./bin/ignite.sh php-ignite.xml where php-ignite.xml is my config(default config + odbc enable):

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">
   <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

   <property name="odbcConfiguration">
       <bean class="org.apache.ignite.configuration.OdbcConfiguration"></bean>
   </property>
</bean>
```

<p></p>

<p>I wrote a simple PHP script to connect with Ignite by PDO and put some custom data in it:</p>

<pre class="lang-php prettyprint-override"><code><?php

try {

    $db = new PDO('odbc:Apache Ignite');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = 'CREATE TABLE IF NOT EXISTS test_md5 (id int PRIMARY KEY, md5_1 VARCHAR, md5_2 VARCHAR, md5_3 VARCHAR, md5_4 VARCHAR, md5_5 VARCHAR, md5_6 VARCHAR, md5_7 VARCHAR, md5_8 VARCHAR, md5_9 VARCHAR) WITH "atomicity=transactional,cachegroup=somegroup"';

    $db->exec($sql);

    for($i=0; $i<=1000000; $i++){
        $md5 = md5($i);
        $sql = "INSERT INTO test_md5 (id, md5_1, md5_2, md5_3, md5_4, md5_5, md5_6, md5_7, md5_8, md5_9) VALUES ($i, '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5');";
        $db->exec($sql);
    }

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "\n";
    die();
}
</code>```

On this point everythink looks nice. Data is set to the cluster. Now I wont to do some tests, to check if Apache Ignite is faster solution for big data then MySQL. This is my test (simple select only):

<?php

error_reporting(E_ALL);
$startTime = microtime(true);

try {

    $ignite = new PDO('odbc:Apache Ignite');
    $ignite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $nRows = $ignite->query('select count(*) from test_md5')->fetchColumn();
    echo 'Rows count: '.$nRows.'

';

    $stmt = $ignite->prepare("select * from test_md5 limit 60500,10");
    $stmt->execute();
    $rows = $stmt->fetchAll();

    foreach($rows as $item){
        echo 'id: '.$item['ID'].' - md5: '.$item['MD5_1'].'
';
    }

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "\n";
    die();
}

echo "

Speed test:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";
```

Results: Speed test: 1.3717 seconds
My question is: Why does Apache Ignite work so slow?

When I do the same with MySQL, results are much faster: Speed test: 0.0019 seconds

Of course this is a simple test but I wan't to use Apache Ignite to work with big data.

How can I configure Ignite corectly?

what am I doing wrong?

EDIT:

So, problem was with offset and single machine comparison scenario. This article can be helped: http://apache-ignite-users.70518.x6.nabble.com/PHP-and-Apache-Ignite-very-slow-query-td18857.html

答:
First of all, you should use exactly the same code if you are going to compare performance. You use ODBC driver for Ignite, but you say that you use default MySQL driver. Do you even use PHP for MySQL test? In your benchmark it is unclear if you are benchmarking Ignite, PDO or PHP I/O itself. Try using exactly the same code for MySQL - it may make things more clear.

Second, Ignite is written in Java and run on JVM. This means that you need to "warm up" it to get real numbers, which you are going to see in production. Observed performance may be MUCH lower on a "cold" JVM, which you just started and have not run a single query on it.

Title: PHP and Apache Ignite - very slow query

Body:
Firstly, sorry for my English.

I start to use Apache Ignite with PHP (PDO, UnixODBC, Ignite ODBC driver). I successfully installed it and configured Ignite, DSN and ODBC on my linux server (Debian). I installed php-odbc extension and everything looks well.

I start Apache Ignite by: ./bin/ignite.sh php-ignite.xml where php-ignite.xml is my config(default config + odbc enable):

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/util
    http://www.springframework.org/schema/util/spring-util.xsd">
   <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">

   <property name="odbcConfiguration">
       <bean class="org.apache.ignite.configuration.OdbcConfiguration"></bean>
   </property>
</bean>

I wrote a simple PHP script to connect with Ignite by PDO and put some custom data in it:

<?php

try {

    $db = new PDO('odbc:Apache Ignite');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql = 'CREATE TABLE IF NOT EXISTS test_md5 (id int PRIMARY KEY, md5_1 VARCHAR, md5_2 VARCHAR, md5_3 VARCHAR, md5_4 VARCHAR, md5_5 VARCHAR, md5_6 VARCHAR, md5_7 VARCHAR, md5_8 VARCHAR, md5_9 VARCHAR) WITH "atomicity=transactional,cachegroup=somegroup"';

    $db->exec($sql);

    for($i=0; $i<=1000000; $i++){
        $md5 = md5($i);
        $sql = "INSERT INTO test_md5 (id, md5_1, md5_2, md5_3, md5_4, md5_5, md5_6, md5_7, md5_8, md5_9) VALUES ($i, '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5', '$md5');";
        $db->exec($sql);
    }

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "\n";
    die();
}

On this point everythink looks nice. Data is set to the cluster. Now I wont to do some tests, to check if Apache Ignite is faster solution for big data then MySQL. This is my test (simple select only):

<?php

error_reporting(E_ALL);
$startTime = microtime(true);

try {

    $ignite = new PDO('odbc:Apache Ignite');
    $ignite->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $nRows = $ignite->query('select count(*) from test_md5')->fetchColumn();
    echo 'Rows count: '.$nRows.'

';

    $stmt = $ignite->prepare("select * from test_md5 limit 60500,10");
    $stmt->execute();
    $rows = $stmt->fetchAll();

    foreach($rows as $item){
        echo 'id: '.$item['ID'].' - md5: '.$item['MD5_1'].'
';
    }

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "\n";
    die();
}

echo "

Speed test:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

Results: Speed test: 1.3717 seconds
My question is: Why does Apache Ignite work so slow?

When I do the same with MySQL, results are much faster: Speed test: 0.0019 seconds

Of course this is a simple test but I wan't to use Apache Ignite to work with big data.

How can I configure Ignite corectly?

what am I doing wrong?

EDIT:

So, problem was with offset and single machine comparison scenario. This article can be helped: http://apache-ignite-users.70518.x6.nabble.com/PHP-and-Apache-Ignite-very-slow-query-td18857.html


问:
Which Thread Hold Lock in wait() and notify() multithreading
I have a confusion in multithreading in below code ...

```<code>public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?

答:
From the Javadocs (bolding mine):

```<code>public final void wait(long timeout)
            throws InterruptedException
</code>```

...

This method causes the current thread (call it T) to place itself in
  the wait set for this object and then to relinquish any and all
  synchronization claims on this object. Thread T becomes disabled for
  thread scheduling purposes and lies dormant until one of four things
  happens:

Some other thread invokes the notify method for this object and thread
  T happens to be arbitrarily chosen as the thread to be awakened.

Some other thread invokes the notifyAll method for this object.

Some other thread interrupts thread T.

The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into
  consideration and the thread simply waits until notified.

The thread T is then removed from the wait set for this object and
  re-enabled for thread scheduling. It then competes in the usual manner
  with other threads for the right to synchronize on the object; once it
  has gained control of the object, all its synchronization claims on
  the object are restored to the status quo ante - that is, to the
  situation as of the time that the wait method was invoked. Thread T
  then returns from the invocation of the wait method. Thus, on return
  from the wait method, the synchronization state of the object and of
  thread T is exactly as it was when the wait method was invoked.

So, in your example:

A thread enters your run() method, then waits to get a lock on obj.

Once it gets that lock, it enters obj.wait() and releases its lock on obj().

When it wakes up (for one of the four reasons above), it waits to get a lock on obj before returning from obj.wait().

The answer to "Which thread holds the lock?" depends entirely on when you examine the object.  If all your threads are blocking in obj.wait() waiting to wake up, then no thread holds the lock.

Body:
I have a confusion in multithreading in below code ...

public class ThreadTest implements Runnable {
        private int num;
        private static SecondThread obj = new SecondThread();

        public void run() {
            synchronized (obj) { //which thread holding lock here
                try {

                    obj.wait();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

which thread is owner while synchronize method is called.

which thread holding lock ThreadTest or SecondThread

what is mean by releasing lock here obj.wait(); means ? Once lock is released can same object come inside synchronized block and access code until previous thread get notified ?

Body:
From the Javadocs (bolding mine):

public final void wait(long timeout)
            throws InterruptedException

...

This method causes the current thread (call it T) to place itself in
  the wait set for this object and then to relinquish any and all
  synchronization claims on this object. Thread T becomes disabled for
  thread scheduling purposes and lies dormant until one of four things
  happens:

Some other thread invokes the notify method for this object and thread
  T happens to be arbitrarily chosen as the thread to be awakened.

Some other thread invokes the notifyAll method for this object.

Some other thread interrupts thread T.

The specified amount of real time has elapsed, more or less. If timeout is zero, however, then real time is not taken into
  consideration and the thread simply waits until notified.

The thread T is then removed from the wait set for this object and
  re-enabled for thread scheduling. It then competes in the usual manner
  with other threads for the right to synchronize on the object; once it
  has gained control of the object, all its synchronization claims on
  the object are restored to the status quo ante - that is, to the
  situation as of the time that the wait method was invoked. Thread T
  then returns from the invocation of the wait method. Thus, on return
  from the wait method, the synchronization state of the object and of
  thread T is exactly as it was when the wait method was invoked.

So, in your example:

A thread enters your run() method, then waits to get a lock on obj.

Once it gets that lock, it enters obj.wait() and releases its lock on obj().

When it wakes up (for one of the four reasons above), it waits to get a lock on obj before returning from obj.wait().

The answer to "Which thread holds the lock?" depends entirely on when you examine the object.  If all your threads are blocking in obj.wait() waiting to wake up, then no thread holds the lock.


问:
Update javascript variable in html
I have a html template.

```<code><html>
<head>
<script>
        var chart;
        var chartData = [
            {
                "label": 2005,
                "data": 23.5
            },
        ];
</script>
</head>

<body>
    <div id="chartdiv" style="width: 500px; height: 600px;"></div>
</body>
</code>```

How can i update chartData using php before actually  loading that (i am getting this template from db).

答:
You can simply echo the variable into the script.

```<code><?PHP
$var = "Hello world";
?>

<html>
<script>
var welcome = "<?php echo $var; ?>";
console.log(welcome);
</script>
</html>
</code>```

Title: Update javascript variable in html

Body:
I have a html template.

How can i update chartData using php before actually  loading that (i am getting this template from db).

Body:
You can simply echo the variable into the script.

<?PHP
$var = "Hello world";
?>

<html>
<script>
var welcome = "<?php echo $var; ?>";
console.log(welcome);
</script>
</html>


问:
intellij idea failed to create JVM error code -1
I have intellij-idea installed. Although I have set JAVA_HOME environment variable referring to "C:\Program Files\Java\jdk1.8.0_45" but when I try to run it, I end up with the following error:

```<code>failed to create JVM: error code -1. JVM path: "C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.2\jre64\" if you have a 64-bit jdk installed, define a JAVA_HOME variable in Computer> system variables> system settings> environment variables.
</code>```

Windows 7_ 64-bit

答:
Please check your phpstorm64.exe.vmoptions file located at bin folder and remove option

-XX:+UseG1GC

Body:
I have intellij-idea installed. Although I have set JAVA_HOME environment variable referring to "C:\Program Files\Java\jdk1.8.0_45" but when I try to run it, I end up with the following error:

failed to create JVM: error code -1. JVM path: "C:\Program Files\JetBrains\IntelliJ IDEA 2017.2.2\jre64\" if you have a 64-bit jdk installed, define a JAVA_HOME variable in Computer> system variables> system settings> environment variables.

Windows 7_ 64-bit


问:
I am trying to read Excel data using Apache POI

```<code>import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public void getDataFromExcel()
    {
        File src = new File("C:\\Users\\kunalku\\Desktop\\Selenium\\Excel\\TestData.xlsx");
        FileInputStream fis = new FileInputStream(src);
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet Sheet2 = wb.getSheetAt(0);

    }
</code>```

I am getting error like (The package org.apache.poi.hssf.usermodel is accessible from more than one module: poi, poi.examples, poi.scratchpad)
I am rookie in selenium, so kindly help me regarding this.

答:
It seems you added all the JARS available in POI zip archive. I will suggest please use only below JARS in your project build path configurations:

```<code>poi-<version>***.jar
poi-ooxml-<version>***.jar
</code>```

Body:
import java.io.File;
import java.io.FileInputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;

public void getDataFromExcel()
    {
        File src = new File("C:\\Users\\kunalku\\Desktop\\Selenium\\Excel\\TestData.xlsx");
        FileInputStream fis = new FileInputStream(src);
        XSSFWorkbook wb = new XSSFWorkbook(fis);
        XSSFSheet Sheet2 = wb.getSheetAt(0);

    }

I am getting error like (The package org.apache.poi.hssf.usermodel is accessible from more than one module: poi, poi.examples, poi.scratchpad)
I am rookie in selenium, so kindly help me regarding this.

Body:
It seems you added all the JARS available in POI zip archive. I will suggest please use only below JARS in your project build path configurations:

poi-<version>***.jar
poi-ooxml-<version>***.jar


问:
UICollectionView + FetchResultsController sometimes crashes when i flush CoreData entity
I have an issue with UICollectionView that linked to CoreData Entity via FetchResultsController. I have a screen with search results, so i need to get records from API, flush Core Data Entity and add new records.

It works fine, but sometimes when i click search button too fast UICollection becomes broken and does not updates anymore. It's a fact that error occurred when i am trying to work with elements that does not exists anymore.

I've added some checks, but it not helps in 100% of situations.

```<code>func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        blockOperations.append(BlockOperation(block: {
            if type == .insert {
                 self.ChatsCollectionView?.insertItems(at: [newIndexPath!])
            }

            if type == .delete {
                if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
                    self.ChatsCollectionView?.deleteItems(at: [indexPath!])
                }
            }

            if type == .update {
                if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
                    self.ChatsCollectionView?.reloadItems(at: [indexPath!])
                }
            }

            if type == .move {
                if let indexPath = indexPath {
                    self.ChatsCollectionView.deleteItems(at: [indexPath])
                }

                if let newIndexPath = newIndexPath {
                    self.ChatsCollectionView.insertItems(at: [newIndexPath])
                }
            }

        }))
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    ChatsCollectionView?.performBatchUpdates({

        for operation in self.blockOperations {
            operation.start()
        }

    }, completion: { (completed) in
        //self.ChatsCollectionView.reloadItems(at: self.ChatsCollectionView.indexPathsForSelectedItems!)
        // I comment this, because it cause crash

    })
}
</code>```

So i have no crashes now, but sometimes i get errors and Collection looks damaged (some rows are emty etc...):

I don't use reloadData() because it works async and crash when i flush data in Entity.

答:
With collectionView and tableView if you ever mess up and your datasource does match what is expected (ie you inserted a row but the number of row did not increase) the view will stop doing any updates and can appear with empty rows.

Updating from a fetchedResultsController is more difficult than the Apple documentation states.  The code that you are sharing will cause this kinds of a bug when there is a move and an insert or a move and delete at the same time.

indexPath  is the index BEFORE the deletes and inserts are applied;  newIndexPath is the index AFTER the deletes and inserts are applied.

For updates you don't care where it was BEFORE the inserts and delete - only after - so use newIndexPath not indexPath. This will fix crashes that can happen when you an update and insert (or update and delete) at the same time and the cell doesn't update as you expect.

For move the delegate is saying where it moved from BEFORE the inserts and where it should be inserted AFTER the inserts and deletes. This can be challenging when you have a move and insert (or move and delete). You can fix this by saving all the changes from controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: into three different arrays, insert, delete and update (you can use a custom object or dictionary - whatever works for you). When you get a move add an entry for it in both the insert array and in the delete array. In controllerDidChangeContent: sort the delete array descending and the insert array ascending.  Then apply the changes  - first delete, then insert, then update.  This will fix crashes that can happens when you have a move and insert (or move and delete) at the same time.

If you have section then also save the sections changes in arrays, and then apply the changes in order: deletes (descending), sectionDelete (descending), sectionInserts (ascending), inserts(ascending), updates (any order). Sections can't move or be updated.

Summary:

Have 5 arrays : sectionInserts, sectionDeletes, rowDeletes, rowInserts, and rowUpdates

in controllerWillChangeContent clear all the arrays

in controller:didChangeObject: add the indexPaths into the arrays (move is a delete and an insert)

in controller:didChangeSection add the section into the sectionInserts or rowDeletes array

in controllerDidChangeContent: process them as follows:

sort rowDeletes descending

sort sectionDelete descending

sort sectionInserts ascending

sort rowInserts ascending

then in one performBatchUpdates block apply the changes to the collectionView: rowDeletes, sectionDelete, sectionInserts, rowInserts and rowUpdates in that order.

Body:
I have an issue with UICollectionView that linked to CoreData Entity via FetchResultsController. I have a screen with search results, so i need to get records from API, flush Core Data Entity and add new records.

It works fine, but sometimes when i click search button too fast UICollection becomes broken and does not updates anymore. It's a fact that error occurred when i am trying to work with elements that does not exists anymore.

I've added some checks, but it not helps in 100% of situations.

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        blockOperations.append(BlockOperation(block: {
            if type == .insert {
                 self.ChatsCollectionView?.insertItems(at: [newIndexPath!])
            }

            if type == .delete {
                if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
                    self.ChatsCollectionView?.deleteItems(at: [indexPath!])
                }
            }

            if type == .update {
                if ((indexPath?.row)! <= self.ChatsCollectionView.numberOfItems(inSection: 0) && self.ChatsCollectionView.numberOfItems(inSection: 0) != 0) {
                    self.ChatsCollectionView?.reloadItems(at: [indexPath!])
                }
            }

            if type == .move {
                if let indexPath = indexPath {
                    self.ChatsCollectionView.deleteItems(at: [indexPath])
                }

                if let newIndexPath = newIndexPath {
                    self.ChatsCollectionView.insertItems(at: [newIndexPath])
                }
            }

        }))
}

func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {

    ChatsCollectionView?.performBatchUpdates({

        for operation in self.blockOperations {
            operation.start()
        }

    }, completion: { (completed) in
        //self.ChatsCollectionView.reloadItems(at: self.ChatsCollectionView.indexPathsForSelectedItems!)
        // I comment this, because it cause crash

    })
}

So i have no crashes now, but sometimes i get errors and Collection looks damaged (some rows are emty etc...):

I don't use reloadData() because it works async and crash when i flush data in Entity.


问:
How to responsively place links in a navbar
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

```

Keeping the dropdown open while in hamburger-mode is a problem for another day.

答:
check the bootstrap 4 official documentation. I used it yesterday for a navbar and it works great with the responsive.
https://v4-alpha.getbootstrap.com/components/navbar/
if you want to include bootstrap 4 in your code, add this to the head tag

```<code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
</code>```

Body:
I'm having some issues with CSS at the moment. I'm working on a navbar with some horizontal links and a dropdown menu at the end.

The links collapse into a hamburger menu when on a small screen. What I'm trying to do is, when the links collapse, I want the last link that is next to the dropdown button to be placed after the dropdown button.

Here is what it looks like when uncollapsed and with the dropdown open:

This is what it looks like collapsed at the moment:

And this is how I would like it to look:

I'm not sure how to accomplish this. I have tried floating the "Profile name" to the right and it kinda works as it place itself to the right of the "IMG" but then all the way to the right. I would like it placed snug to the "IMG". Padding it to the right place screws up the responsiveness.

I'm using bootstrap for the responsiveness and dropdown menu. I assume that I will have to use media queries for this.

If anyone has any idea of how to do this I am more than grateful for any tip!

here is a code

Link 1

Link 2

Profile name

Link 3

Link 4

Link 5

Keeping the dropdown open while in hamburger-mode is a problem for another day.

Body:
check the bootstrap 4 official documentation. I used it yesterday for a navbar and it works great with the responsive.
https://v4-alpha.getbootstrap.com/components/navbar/
if you want to include bootstrap 4 in your code, add this to the head tag

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>


问:
IllegalArgumentException in Shared Element Transition
Implemented activity to activity shared element transition. It works fine but receiving crashes on very few devices that are running >=LOLLIPOP.

Report:

```<code>Fatal Exception: java.lang.IllegalArgumentException
       at android.os.Parcel.readException(Parcel.java:1550)
       at android.os.Parcel.readException(Parcel.java:1499)
       at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:4654)
       at android.app.Activity.isTopOfTask(Activity.java:5557)
       at android.app.Activity.startActivityForResult(Activity.java:3903)
       at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:65)
       at android.app.Activity.startActivity(Activity.java:4146)
       at com.mypackage.Activity1.method1(Activity1.java:414).
</code>```

tried this:

```<code>Intent intent = new Intent(Activity1.this, Activity2.class);
     ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation(Activity1.this,
                            logoImageView,
                            ViewCompat.getTransitionName(logoImageView));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                startActivity(intent, options.toBundle());
            } else {
                startActivity(intent);
            }
            overridePendingTransition(R.anim.stay, R.anim.stay);
</code>```

then this from this sof IllegalArgumentException in ActivityManagerProxy:

```<code>Intent intent = new Intent(Activity1.this, Activity2.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    ActivityOptions options = ActivityOptions
            .makeSceneTransitionAnimation(Activity1.this,
                    logoImageView,
                    getString(R.string.splashLogoSharedTransition));
    startActivity(intent, options.toBundle());
} else {
    ActivityOptionsCompat options = ActivityOptionsCompat.
            makeSceneTransitionAnimation(SplashActivity.this,
                    logoImageView,
                    getString(R.string.splashLogoSharedTransition));
    ActivityCompat.startActivity(SplashActivity.this, intent, options.toBundle());
}
overridePendingTransition(R.anim.stay, R.anim.stay);
</code>```

Crash happens with the both the codes at:

```<code>startActivity(intent, options.toBundle());
</code>```

Ever faced ? Any hints ?

答:
According to this post you shouldn't use ActivityOptionsCompat above API 21:
https://stackoverflow.com/a/42455484/1067763

I don't use it, but I still have this crash:

Crashes after startActivityForResult in API 27

I think it's still using the wrong version somehow.

Still, knowing this you might be able to solve your issue.

Body:
Implemented activity to activity shared element transition. It works fine but receiving crashes on very few devices that are running >=LOLLIPOP.

Report:

Fatal Exception: java.lang.IllegalArgumentException
       at android.os.Parcel.readException(Parcel.java:1550)
       at android.os.Parcel.readException(Parcel.java:1499)
       at android.app.ActivityManagerProxy.isTopOfTask(ActivityManagerNative.java:4654)
       at android.app.Activity.isTopOfTask(Activity.java:5557)
       at android.app.Activity.startActivityForResult(Activity.java:3903)
       at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
       at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:65)
       at android.app.Activity.startActivity(Activity.java:4146)
       at com.mypackage.Activity1.method1(Activity1.java:414).

tried this:

Intent intent = new Intent(Activity1.this, Activity2.class);
     ActivityOptionsCompat options = ActivityOptionsCompat.
                    makeSceneTransitionAnimation(Activity1.this,
                            logoImageView,
                            ViewCompat.getTransitionName(logoImageView));
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                startActivity(intent, options.toBundle());
            } else {
                startActivity(intent);
            }
            overridePendingTransition(R.anim.stay, R.anim.stay);

then this from this sof IllegalArgumentException in ActivityManagerProxy:

Intent intent = new Intent(Activity1.this, Activity2.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    ActivityOptions options = ActivityOptions
            .makeSceneTransitionAnimation(Activity1.this,
                    logoImageView,
                    getString(R.string.splashLogoSharedTransition));
    startActivity(intent, options.toBundle());
} else {
    ActivityOptionsCompat options = ActivityOptionsCompat.
            makeSceneTransitionAnimation(SplashActivity.this,
                    logoImageView,
                    getString(R.string.splashLogoSharedTransition));
    ActivityCompat.startActivity(SplashActivity.this, intent, options.toBundle());
}
overridePendingTransition(R.anim.stay, R.anim.stay);

Crash happens with the both the codes at:

startActivity(intent, options.toBundle());

Ever faced ? Any hints ?


问:
PHPMyAdmin File Import Error
I can't seem to get PHPMYADMIN to import an SQL file properly as it is giving my the error:

No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP
  configuration. See FAQ 1.16.

The documentation says:

The first things to check (or ask your host provider to check) are the
  values of upload_max_filesize, memory_limit and post_max_size in the
  php.ini configuration file. All of these three settings limit the
  maximum size of data that can be submitted and handled by PHP. One
  user also said that post_max_size and memory_limit need to be larger
  than upload_max_filesize.

Here's what I've done...

Changed PHP.INI params

upload_max_filesize = 1000M

memory_limit = 1500M

post_max_size = 1500M

restarted Apache

I also tried different limit variables in hopes that maybe I was setting them too high... but that didn't matter. PHPMYADMIN confirms (on the import page) that the upload variable is set to "(Max: 1,000MiB)" but still no good. I am only trying to upload a file that is 5MB in size.

Any help would be much appreciated!

答:
I faced this problem on Ubuntu 17, maybe because of the upgrade I've done. The problem was a not writable /var/lib/phpmyadmin/tmp so just run this code:

sudo chmod 777 /var/lib/phpmyadmin/tmp/

and then its works again.

Title: PHPMyAdmin File Import Error


问:
CreateTimerQueueTimer callback and race condition
I'm using timer queues in my application, and pass a pointer to one of my own C++ Timer objects as the 'parameter' to the callback (in CreateTimerQueueTimer). I then call a virtual method on the object in the callback.

The destructor of the Timer object will make sure to cancel the timer using DeleteTimerQueueTimer().

```<code>static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    Timer* timer = reinterpret_cast< Timer* >( param );
    timer->TimedOut();
}

class Timer
{
public:
   Timer();

   virtual ~Timer()
   {
       ::DeleteTimerQueueTimer( handle );
   }

   void Start( double period )
   {
      ::CreateTimerQueueTimer( &handle, ..., &callback, this, ... );
   }

   virtual void TimedOut() = 0;

   ...
};
</code>```

However, there is a subtle race condition that if the callback has already been called, but the timer object is destroyed before the call to TimedOut(), the app crashes because the callback calls the virtual method on a non-existent object. Or even worse, while it's being deleted.

I do have mutexes in place to control multi-threaded calls, but I still get the problem.

Is using an object pointer as the callback parameter really a good idea? With no guarantees of synchronisation between the threads, it just smells bad to me.

Is there a better solution? What do other people do?

One thing that occurs is to keep a set of pointers to every single Timer instance (add in constructor, remove in destructor). But I don't think this would work because if Timer is derived from, we'd only remove the pointer from the set in the base class destructor; the damage is already done if we've started destroying the derived object.

Cheers.

答:
You almost certainly can't do this with an inheritance model. The principal problem is that by the time the base class constructor has been entered, the derived object is already invalid but the timer might fire and nothing stops it attempting the virtual function call which will now result in undefined behaviour.

I think the way to do it is a wrapper like this. The point is to ensure that there is no race condition with trying to dispatch the 'timed out' event.

This implementation still has one flaw. There is a chance the a timer event is waiting when the timer object starts to be deleted. It is possible for the destructor to release the mutex and then destroy the mutex while the timer thread is waiting on the mutex. We've prevented the race in the dispatch of the 'timed out' event, but the behaviour of a thread waiting on a mutex that is destroyed depends on the implementation of mutex.

```<code>static void callback( PVOID param, BOOLEAN timerOrWaitFired );

class TimerWrapper
{
    public:

        /* Take reference to std::auto_ptr to ensure ownership transfer is explicit */
        TimerWrapper( std::auto_ptr<Timer>& timer ) : timer_(timer)
        {
            ::CreateTimerQueueTimer( &htimer_, ..., callback, this, ... );
        }

        void TimedOut()
        {
            ScopedGuard guard( mutex_ );
            if( timer_.get() )
                timer_->TimedOut();
        }

        ~TimerWrapper()
        {
            ::DeleteTimerQueueTimer( htimer_, ... );
            ScopedGuard guard( mutex_ );
            timer_.reset();
        }

    private:

        Mutex mutex_;
        std::auto_ptr<Timer> timer_;
        HANDLE htimer_;
};

static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    TimerWrapper* timer = reinterpret_cast< TimerWrapper* >( param );
    timer->TimedOut();
}
</code>```

OwnerDisplayName: Steve Folly

Body:
I'm using timer queues in my application, and pass a pointer to one of my own C++ Timer objects as the 'parameter' to the callback (in CreateTimerQueueTimer). I then call a virtual method on the object in the callback.

The destructor of the Timer object will make sure to cancel the timer using DeleteTimerQueueTimer().

static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    Timer* timer = reinterpret_cast< Timer* >( param );
    timer->TimedOut();
}

class Timer
{
public:
   Timer();

   virtual ~Timer()
   {
       ::DeleteTimerQueueTimer( handle );
   }

   void Start( double period )
   {
      ::CreateTimerQueueTimer( &handle, ..., &callback, this, ... );
   }

   virtual void TimedOut() = 0;

   ...
};

However, there is a subtle race condition that if the callback has already been called, but the timer object is destroyed before the call to TimedOut(), the app crashes because the callback calls the virtual method on a non-existent object. Or even worse, while it's being deleted.

I do have mutexes in place to control multi-threaded calls, but I still get the problem.

Is using an object pointer as the callback parameter really a good idea? With no guarantees of synchronisation between the threads, it just smells bad to me.

Is there a better solution? What do other people do?

One thing that occurs is to keep a set of pointers to every single Timer instance (add in constructor, remove in destructor). But I don't think this would work because if Timer is derived from, we'd only remove the pointer from the set in the base class destructor; the damage is already done if we've started destroying the derived object.

Cheers.

Body:
You almost certainly can't do this with an inheritance model. The principal problem is that by the time the base class constructor has been entered, the derived object is already invalid but the timer might fire and nothing stops it attempting the virtual function call which will now result in undefined behaviour.

I think the way to do it is a wrapper like this. The point is to ensure that there is no race condition with trying to dispatch the 'timed out' event.

This implementation still has one flaw. There is a chance the a timer event is waiting when the timer object starts to be deleted. It is possible for the destructor to release the mutex and then destroy the mutex while the timer thread is waiting on the mutex. We've prevented the race in the dispatch of the 'timed out' event, but the behaviour of a thread waiting on a mutex that is destroyed depends on the implementation of mutex.

static void callback( PVOID param, BOOLEAN timerOrWaitFired );

class TimerWrapper
{
    public:

        /* Take reference to std::auto_ptr to ensure ownership transfer is explicit */
        TimerWrapper( std::auto_ptr<Timer>& timer ) : timer_(timer)
        {
            ::CreateTimerQueueTimer( &htimer_, ..., callback, this, ... );
        }

        void TimedOut()
        {
            ScopedGuard guard( mutex_ );
            if( timer_.get() )
                timer_->TimedOut();
        }

        ~TimerWrapper()
        {
            ::DeleteTimerQueueTimer( htimer_, ... );
            ScopedGuard guard( mutex_ );
            timer_.reset();
        }

    private:

        Mutex mutex_;
        std::auto_ptr<Timer> timer_;
        HANDLE htimer_;
};

static void callback( PVOID param, BOOLEAN timerOrWaitFired )
{
    TimerWrapper* timer = reinterpret_cast< TimerWrapper* >( param );
    timer->TimedOut();
}

OwnerDisplayName: Charles Bailey

LastEditorDisplayName: Charles Bailey


问:
Android application must not run on rooted devices
I'm writing an application that must not run on rooted devices. I want to store some secure data and which is possible only on non-rooted devices as nobody can access files in /data/data/package-name.

Does anyone know:

1) Is it possible to prevent the installation of an application on rooted devices? I read something about the "copy-protection mechanism" of Android Market. This feature seems to be outdated and replaced by the licensing feature. However, licensing is only possible for paid application and mine is free...

2) Is it possible to check programmatically whether a device is rooted or not? If it would be possible to do so I could simply stop the application if the device is rooted.

Any help regarding this topic is appreciated!

答:
Execute

```<code>Runtime.getRuntime().exec("su");
</code>```

and check the result code.

In other words, if you can exec su, then you have root access. it doesn't matter if the user allows or denies it, you have your answer.

Body:
Execute

Runtime.getRuntime().exec("su");

and check the result code.

In other words, if you can exec su, then you have root access. it doesn't matter if the user allows or denies it, you have your answer.


问:
Can you set clang-format's line length?
clang-format is breaking up my lines at 80 columns. Is there a way to make stop breaking lines?  The documentation doesn't seem to address this.</p>

答:
The configuration option responsible for it is called ColumnLimit. You can remove the column limit by setting it to 0.

```<code>ColumnLimit: 0
</code>```

Title: Can you set clang-format's line length?

Body:
The configuration option responsible for it is called ColumnLimit. You can remove the column limit by setting it to 0.

ColumnLimit: 0


问:
How does constant integer assignment in c++
could any please explain the below code

```<code>const uInt32 eVal = 8ul;
const uInt32 fVal = 5ul;
const uInt32 zVal = 0ul;
</code>```

what does ul and numbers 8,5,0 are stand for

答:
It's the programmer being unnecessarily verbose. ul is the prefix for an unsigned long literal, so 8ul has an unsigned long type.

Most likely, that isn't the same type as the uInt32, so really the code you present is an exercise in obfuscation. Really they should rely on the automatic implicit conversion rules and write

```<code>const uInt32 eVal = 8;
const uInt32 fVal = 5;
const uInt32 zVal = 0;
</code>```

perhaps even preferring constexpr in place of const.

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

Body:
could any please explain the below code

const uInt32 eVal = 8ul;
const uInt32 fVal = 5ul;
const uInt32 zVal = 0ul;

what does ul and numbers 8,5,0 are stand for

Body:
It's the programmer being unnecessarily verbose. ul is the prefix for an unsigned long literal, so 8ul has an unsigned long type.

Most likely, that isn't the same type as the uInt32, so really the code you present is an exercise in obfuscation. Really they should rely on the automatic implicit conversion rules and write

const uInt32 eVal = 8;
const uInt32 fVal = 5;
const uInt32 zVal = 0;

perhaps even preferring constexpr in place of const.

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


问:
Can I run a custom action in a Windows Installer Project before the files are installed?
I have a Windows Installer Project that installs files to C:\Program Files\MyInstalledFiles. When I run the MSI, I want it to check if there is already a folder called MyInstalledFiles in the install destination and, if so, rename it to MyInstalledFiles-OLD. This way I can back up any files that already exist.

The catch is that I want this to be done BEFORE the files are installed by the MSI. Otherwise, it will overwrite the existing files and I will lose them. Is there any way for me to rename the folder before the installation using custom actions?

答:
I had similar issue for a project before, and achived by calling an executable on Install.

Create a custom action for Installer Project.

Point a vbs or executable according your needs.

After that, you'll see your custom action under Custom Actions>Install tree.

Edit: And, unfortunately, there is no way to make any control in early stages. If this doesn't help, you need to find another Installer extension.


问:
laravel Undefined variable when i post multiple value to view
In controller when i try to send multiple value to view such as this codes:

```<code>$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));
</code>```

i get error for this variables into view:

```<code>$categories
$selected_categories
$content
</code>```

result of dd(['content' => $content], $content_categories, $selected_categories); is:

```<code>array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]
</code>```

whats problem of my code to parse them on view or send them with correct way

my view:

```<code>1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"
</code>```

Errors:

```<code>"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"
</code>```

答:
You need to change your code something like this to pass value.

```<code>return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories','content'));
</code>```

Second point you getting undefined $categories because you are not passing categories into compact function. you need to pass categories variable into compact function.

I think you need to change select tag code like this:

```<code>{{ Form::select('categories[]', $selected_categories['categories'], NULL , array('class' => 'multiselect-success','multiple'=>'multiple')) }}
</code>```

Hope can help you. Good Luck!

Body:
In controller when i try to send multiple value to view such as this codes:

$content = Contents::find($contents);
$content_categories['categories'] = ContentCategories::all()->pluck('title', 'id');
$selected_categories['selected_categories'] = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, ['content' => $content]));

i get error for this variables into view:

$categories
$selected_categories
$content

result of dd(['content' => $content], $content_categories, $selected_categories); is:

array:1 [▼
  "content" => Contents {#220 ▶}
]

array:1 [▼
  "categories" => Collection {#214 ▶}
]

array:1 [▼
  "selected_categories" => Collection {#227 ▶}
]

whats problem of my code to parse them on view or send them with correct way

my view:

1) {{ Form::select('categories[]', $categories, $selected_categories, array('class' => 'multiselect-success','multiple'=>'multiple')) }}

2) action="{{ route('manage_contents.update' , ['id' => $content->id ]) }}"

Errors:

"Undefined variable: categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: selected_categories (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

"Undefined variable: content (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/layouts/backend/pages/manage_contents/edit.blade.php)"

Body:
You need to change your code something like this to pass value.

return view('layouts.backend.pages.manage_contents.edit', compact('selected_categories', 'content_categories','content'));

Second point you getting undefined $categories because you are not passing categories into compact function. you need to pass categories variable into compact function.

I think you need to change select tag code like this:

{{ Form::select('categories[]', $selected_categories['categories'], NULL , array('class' => 'multiselect-success','multiple'=>'multiple')) }}

Hope can help you. Good Luck!


问:
What does 'Refused to get unsafe header "X-Bandwidth-Est 3"' error mean?
I have a problem with every website that I am working on currently. And the error is this:

Refused to get unsafe header "X-Bandwidth-Est 3" in base.js.
Base.js is youtube file. I searched a lot and I couldn't find this error. Anyone have idea what this error is?

And this is image of this error:

答:
I see the same problem. It is quite irritating when you try to debug since you get a lot of them.

Are you using Google Chrome? There was an update to it today.

I am also using the YouTube player (which I think you do to).

Unfortunately I don't think I can test in another browser right now, since there are bugs in the other browsers.

EDIT: I ruled out that this is a problem with Firebase/Firestore (since you do not mention them and we got this problem at the same time). So I see two possibilities now, Chrome and YouTube.


问:
How to use surf and sift detector in OpenCV for Python
I was trying a code for feature matching which uses the function SURF(). Upon execution it gives an error saying "AttributeError: 'module' object has no attribute 'SURF'".

How can I download this module for Python (Windows) and fix this error?

答:
At first

```<code>pip install opencv-contrib-python
</code>```

and then use this hack to create sift object

```<code>sift = cv2.xfeatures2d.SIFT_create()
</code>```

Body:
At first

pip install opencv-contrib-python

and then use this hack to create sift object

sift = cv2.xfeatures2d.SIFT_create()


答:
Try this way</p>

```<code>$content = Contents::find($contents);
$categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, $content));
</code>```

Title: laravel Undefined variable when i post multiple value to view

Body:
Try this way

$content = Contents::find($contents);
$categories = ContentCategories::all()->pluck('title', 'id');
$selected_categories = $content->categories()->pluck('title', 'id');

return view('layouts.backend.pages.manage_contents.edit', compact($selected_categories, $content_categories, $content));


问:
Where are files uploaded by Valums?! (i have to store them in mysql database with PHP)
when i upload several files using Valmus Uploader, how can i "work with them", ie. store in mysql database, crop or resize, etc...

but, where are those files, and how can i access them?

tnx in adv!!!

答:
PHP puts a list of uploaded files in the $_FILES global variable (see doc here : http://www.php.net/manual/en/features.file-upload.post-method.php ).

You can iterate over uploaded files like this:

```<code>foreach($_FILES as $file) {
    // $file['tmp_name'] is where the file resides on the disk
    // use move_uploaded_file() to move it elsewhere
    // $file['name'] is the name of the file on the sender's computer
}
</code>```

Body:
PHP puts a list of uploaded files in the $_FILES global variable (see doc here : http://www.php.net/manual/en/features.file-upload.post-method.php ).

You can iterate over uploaded files like this:

foreach($_FILES as $file) {
    // $file['tmp_name'] is where the file resides on the disk
    // use move_uploaded_file() to move it elsewhere
    // $file['name'] is the name of the file on the sender's computer
}


问:
Android simple spinner item
this question relates to this one: android.R.simple_spinner_item

Since I can't comment because of low reputation, I have an additional question:

If I copy&paste the android.R.simple_spinner_item layout, I get an error on

```<code>android:layout_height="?android:attr/dropdownListPreferredItemHeight"
</code>```

saying "error: Error: Attribute is not public. (at 'layout_height' with value '?android:attr/dropdownListPreferredItemHeight')."

I just added android:gravity="right" to get the spinner_item alignment to the right side.

How can I solve this error?

答:
This resource is private, so only the library which that attribute comes from can use it. So you need to get the size of this attribute and create it within your app. From the source code: https://android.googlesource.com/platform/frameworks/support/+/50fe5ec/appcompat/res/values/themes.xml

we can see at lines 50 and/or 84 the attribute there.
So in your dimens.xml file you can write:

<dimen name="dropdownListPreferredItemHeight">64dip</dimen>

and then reference it like you would a normal resource:

android:layout_height="@dimen/dropdownListPreferredItemHeight"

Title: Android simple spinner item

Body:
this question relates to this one: android.R.simple_spinner_item

Since I can't comment because of low reputation, I have an additional question:

If I copy&paste the android.R.simple_spinner_item layout, I get an error on

android:layout_height="?android:attr/dropdownListPreferredItemHeight"

saying "error: Error: Attribute is not public. (at 'layout_height' with value '?android:attr/dropdownListPreferredItemHeight')."

I just added android:gravity="right" to get the spinner_item alignment to the right side.

How can I solve this error?


问:
Extract list keys and list of values for each row from json in python
I'm trying to extract a list of keys and a list of all values for each entry from json. Consider the following json:

```<code>[{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]
</code>```

And I want the output to be:

```<code>['height','width','weight']

[[1.2,2.5,5],[1.7,4.5,2],[3.2,4.5,7]]
</code>```

Basically I need to load it to pandas Dataframe. I believe it will be easier to load the rows and cols directly. I can't load the json directly to DataFrame and I can't find an efficient way to extract rows and cols as described above.

答:
Assuming you have the json loaded in a variable, like text, you can simply do:</p>

```<code>In [13]: import json, pandas

In [14]: text = json.dumps([{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }])
    ...:

In [15]: df = pandas.read_json(text)

In [16]: df
Out[16]:
   height  weight  width
0     1.2       5    2.5
1     1.7       2    4.5
2     3.2       7    4.5

In [17]: df.columns.values
Out[17]: array([u'height', u'weight', u'width'], dtype=object)

In [18]: df.as_matrix()
Out[18]:
array([[ 1.2,  5. ,  2.5],
       [ 1.7,  2. ,  4.5],
       [ 3.2,  7. ,  4.5]])
</code>```

Body:
I'm trying to extract a list of keys and a list of all values for each entry from json. Consider the following json:

[{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]

And I want the output to be:

['height','width','weight']

[[1.2,2.5,5],[1.7,4.5,2],[3.2,4.5,7]]

Basically I need to load it to pandas Dataframe. I believe it will be easier to load the rows and cols directly. I can't load the json directly to DataFrame and I can't find an efficient way to extract rows and cols as described above.

Body:
Assuming you have the json loaded in a variable, like text, you can simply do:

In [13]: import json, pandas

In [14]: text = json.dumps([{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }])
    ...:

In [15]: df = pandas.read_json(text)

In [16]: df
Out[16]:
   height  weight  width
0     1.2       5    2.5
1     1.7       2    4.5
2     3.2       7    4.5

In [17]: df.columns.values
Out[17]: array([u'height', u'weight', u'width'], dtype=object)

In [18]: df.as_matrix()
Out[18]:
array([[ 1.2,  5. ,  2.5],
       [ 1.7,  2. ,  4.5],
       [ 3.2,  7. ,  4.5]])


问:
How to know an OWIN cookie/User Session is about to expire in mvc 5
I'n my MVC 5 application I need to prevent users to login if they are already logged in on another system. For this I have a flag column in the database and set its value to true when user logs in and false when the user logs out. But the issue occurs when the user is inactive for a certain period of time or closes the browser, which invalidates the authentication cookie but does not update the flag in the database, which in turn keeps the user logged in in the database and therefore the user will never be able to login again.
I wanted to know if there is any functionality that identity framework provides where I can check that when the authentication cookie if about to expire, I can set the flag in the database to false.</p>

答: Since I didn't get any answer here I found a work around for this and hope that will be of help to others too. What I'm doing now is storing the SessionId of the current user in the database along with setting its isLoggedIn flag to true when user logs in. And when the user logs out I set the isLoggedIn flag to false and also remove the SessionId from the database. The same functionality of logout function is also present in the Session_End() event in the Global.asax, which handles the inactivity issue. For now this is working fine for me but I'm open to other ideas if anyone has a different and better approach .


答:
As the comments have mentioned, you can just pass dictionaries straight to the DataFrame constructor. However, if you really want the format you described for some reason, you can use:</p>

```<code>>>> x = [{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]

>>> list(map(lambda l:list(l.keys()), x))
[['height', 'width', 'weight'], ['height', 'width', 'weight'], ['height', 'width', 'weight']]

>>> list(map(lambda l:list(l.values()), x))
[[1.2, 2.5, 5], [1.7, 4.5, 2], [3.2, 4.5, 7]]
</code>```

Title: Extract list keys and list of values for each row from json in python

Body:
As the comments have mentioned, you can just pass dictionaries straight to the DataFrame constructor. However, if you really want the format you described for some reason, you can use:

>>> x = [{'height': 1.2 , 'width':2.5, 'weight':5 },{'height': 1.7 , 'width':4.5, 'weight':2 },{'height': 3.2 , 'width':4.5, 'weight':7 }]

>>> list(map(lambda l:list(l.keys()), x))
[['height', 'width', 'weight'], ['height', 'width', 'weight'], ['height', 'width', 'weight']]

>>> list(map(lambda l:list(l.values()), x))
[[1.2, 2.5, 5], [1.7, 4.5, 2], [3.2, 4.5, 7]]