问:
error while running ionic ios build --prod --release
After installing Themeable browser plugin I am getting this error when I run :

```<code>ionic cordova build ios --prod --release
</code>```

I was able to build ios --prod --release without any error. Thanks :D

```<code>    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s
</code>```

答:
It's all about libraries mismatching versions.

make sure you have "typescript": "2.4.0"and not newer.

And regarding all packages that start with "@ionic-native/..." their version should be 4.3.0 WITHOUT the ^ at the beginning.

and please don't upgrade to rxjs 5.5, use "rxjs": "5.4.3" since they changed the operators export/import.

note: if you still run into the problem of found version 4, expected 3 remove the hat ^ from the version of the library that caused the problem.

Best of luck!

Body:
After installing Themeable browser plugin I am getting this error when I run :

ionic cordova build ios --prod --release

I was able to build ios --prod --release without any error. Thanks :D

    Mac-Pro-de-chaker-2:cleantoufoulakids chakerkalai$ ionic cordova build ios --prod --realise
Running app-scripts build: --prod --platform ios --target cordova
[18:22:05]  build prod started ...
[18:22:07]  clean started ...
[18:22:07]  clean finished in 2 ms
[18:22:07]  copy started ...
[18:22:07]  ngc started ...
Error: Metadata version mismatch for module /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic-native/core/decorators.d.ts, found version 4, expected 3
    at StaticSymbolResolver.getModuleMetadata (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24474:34)
    at StaticSymbolResolver._createSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24260:46)
    at StaticSymbolResolver.getSymbolsOf (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:24241:14)
    at /Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23023:30
    at Array.forEach (native)
    at extractProgramSymbols (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:23022:79)
    at AotCompiler.compileAll (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler/bundles/compiler.umd.js:22720:47)
    at CodeGenerator.codegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/codegen.js:30:14)
    at Function.NgTools_InternalApi_NG_2.codeGen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@angular/compiler-cli/src/ngtools_api.js:61:30)
    at Object.doCodegen (/Users/chakerkalai/Desktop/cleantoufoulakids/node_modules/@ionic/app-scripts/dist/aot/codegen.js:6:51)
[18:22:47]  copy finished in 40.10 s


来源: stackexchange

问:
iPhone X keyboard appear showing extra space
I have created a chat UI in which I have added a constraint for the tableView to the bottom of the screen. I am changing the constraint value by adding the height of the keyboard which is working fine in all the devices except iPhone X.

UI when key board is not visible:

Which is fine.

Problem is when keyboard appears blank space is visible in between the textView and the keyboard:

Do I have to try for a different approach for this or it can be resolved using constraints ?

答:
Try subtracting the height of the safe area's bottom inset when calculating the value for your constraint.

Here is a sample implementation which handles a UIKeyboardWillChangeFrame notification.

```<code>@objc private func keyboardWillChange(_ notification: Notification) {
    guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
    let newHeight: CGFloat
    if #available(iOS 11.0, *) {
        newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
    } else {
        newHeight = value.cgRectValue.height
    }
    myConstraint.value = newHeight
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Try subtracting the height of the safe area's bottom inset when calculating the value for your constraint.

Here is a sample implementation which handles a UIKeyboardWillChangeFrame notification.

@objc private func keyboardWillChange(_ notification: Notification) {
    guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
    let newHeight: CGFloat
    if #available(iOS 11.0, *) {
        newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
    } else {
        newHeight = value.cgRectValue.height
    }
    myConstraint.value = newHeight
}


问:
XAML/Silverlight 4.0 complex form field binding
I have a datagrid in Silverlight, with the following field bound to lastPrice:

```<code><data:DataGridTextColumn Header="Last Price" SortMemberPath="lastPrice" Binding="{Binding lastPrice}" IsReadOnly="True"/>
</code>```

The problem is, occasionally lastPrice is less than 0, and in those cases I want to display something else (TBD) in the field instead of what lastPrice actually is. Is there an easy way for me to do this inside the XAML?

Thanks!

答: Yes, there is an easy way to do this. You can achieve this by using a Converter.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a datagrid in Silverlight, with the following field bound to lastPrice:

<data:DataGridTextColumn Header="Last Price" SortMemberPath="lastPrice" Binding="{Binding lastPrice}" IsReadOnly="True"/>

The problem is, occasionally lastPrice is less than 0, and in those cases I want to display something else (TBD) in the field instead of what lastPrice actually is. Is there an easy way for me to do this inside the XAML?

Thanks!


问:
My App is crashing when trying to replace fragments
I'm working with the preset navigation bar in the android studio activity creation, when I try and replace two fragments the app crashes. I have tried to use both the

import android.app.FragmentManager;

as well as the

import android.support.v4.app.FragmentManager;

I was having trouble defining the fragment to be swapped out with the seconds import so I was not able to test it using that import.

MainActivity Java Script

```<code>package acook.mobileassignment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity{

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                setTitle("Music Main");
                FragmentManager fragManager = getFragmentManager();
                MusicMain fragment = new MusicMain();
                FragmentTransaction fragTransaction = fragManager.beginTransaction();
                fragTransaction.replace(R.id.mainContent, fragment);
                fragTransaction.commit();

                Context context = getApplicationContext();
                CharSequence text = "MusicPageCheck!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                return true;
            case R.id.navigation_dashboard:
                setTitle("Timer Set");
                FragmentManager fragManager2 = getFragmentManager();
                FragmentTransaction fragTransaction2 = fragManager2.beginTransaction();
                fragTransaction2.replace(R.id.mainContent, new TimerSet()).commit();
                return true;
            case R.id.navigation_notifications:
                setTitle("Favourites");
                FragmentManager fragManager3 = getFragmentManager();
                FragmentTransaction fragTransaction3 = fragManager3.beginTransaction();
                fragTransaction3.replace(R.id.mainContent, new Favourites()).commit();
                return true;
        }
        return false;
    }

};

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

    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}

}
</code>```

答:
have you tried using getSupportFragmentManager() with the
android.support.v4.app.FragmentManager, instead the getFragmentManager() ?</p>

Body:
I'm working with the preset navigation bar in the android studio activity creation, when I try and replace two fragments the app crashes. I have tried to use both the

import android.app.FragmentManager;

as well as the

import android.support.v4.app.FragmentManager;

I was having trouble defining the fragment to be swapped out with the seconds import so I was not able to test it using that import.

MainActivity Java Script

package acook.mobileassignment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity{

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                setTitle("Music Main");
                FragmentManager fragManager = getFragmentManager();
                MusicMain fragment = new MusicMain();
                FragmentTransaction fragTransaction = fragManager.beginTransaction();
                fragTransaction.replace(R.id.mainContent, fragment);
                fragTransaction.commit();

                Context context = getApplicationContext();
                CharSequence text = "MusicPageCheck!";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                return true;
            case R.id.navigation_dashboard:
                setTitle("Timer Set");
                FragmentManager fragManager2 = getFragmentManager();
                FragmentTransaction fragTransaction2 = fragManager2.beginTransaction();
                fragTransaction2.replace(R.id.mainContent, new TimerSet()).commit();
                return true;
            case R.id.navigation_notifications:
                setTitle("Favourites");
                FragmentManager fragManager3 = getFragmentManager();
                FragmentTransaction fragTransaction3 = fragManager3.beginTransaction();
                fragTransaction3.replace(R.id.mainContent, new Favourites()).commit();
                return true;
        }
        return false;
    }

};

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

    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
}

}


问:
Retrieve child data from firebase realtime database
I have restructured my firebase database to a flat model in which object are referenced from one object to another. Like in the example below I reference related users from the customer object based on on their id's.

Now for some reason I expect the the data of the user objects to be returned when I list the 'customer/1510925e-0541-474f-93c1-10890934fda9' path.

What is the logic to access the user data when listing the customer record? What am I missing here?

```<code>  "customer" : {
    "1510925e-0541-474f-93c1-10890934fda9" : {
      "users" : {
        "LlMNVWXvzLhmP24AKVciM2PvPVy2" : true,
        "Q4sM188BgwRGYhJUiLDqgAzGGX72" : true
      },
      "name" : "NiceCustomer"
    },
    "634f6b10-1def-496d-af44-834ae3c69c27" : {..customer2.},
    "a7ca5d01-757c-4534-a9e1-154c53d160a7" : {..customer 2 etc.}
  }
</code>```

答:
I'm assuming that you also have a path for your user data, such as "/users/". The data for the user record would therefore be returned by looking at  "users/LlMNVWXvzLhmP24AKVciM2PvPVy2", for example.

The point of indexing your records as you've done by indicating which users are associated with a customer is just to make it easier to fetch data later on, particularly as your database scales.

Imagine that your user data looked like this:

```<code>"users":{
  "LlMNVWXvzLhmP24AKVciM2PvPVy2":{
    "customer" : "1510925e-0541-474f-93c1-10890934fda9"
  }
  "Q4sM188BgwRGYhJUiLDqgAzGGX72":{
    "customer" : "634f6b10-1def-496d-af44-834ae3c69c27"
  }
  ...for many, many records...
}
</code>```

...and you need to find which user(s) belong(s) to a particular customer record. If your list of users is large, it's going to take a lot of processing to find all the relevant records. You have to check each user.

If, on the other hand, you've done some indexing as you've indicated in your question, finding which users go with a customer record is easy. Just pull up the customer record, get the user ids, then get their data from the /users path.

See the Firebase docs for a great description: https://firebase.google.com/docs/database/android/structure-data#fanout

Body:
I have restructured my firebase database to a flat model in which object are referenced from one object to another. Like in the example below I reference related users from the customer object based on on their id's.

Now for some reason I expect the the data of the user objects to be returned when I list the 'customer/1510925e-0541-474f-93c1-10890934fda9' path.

What is the logic to access the user data when listing the customer record? What am I missing here?

  "customer" : {
    "1510925e-0541-474f-93c1-10890934fda9" : {
      "users" : {
        "LlMNVWXvzLhmP24AKVciM2PvPVy2" : true,
        "Q4sM188BgwRGYhJUiLDqgAzGGX72" : true
      },
      "name" : "NiceCustomer"
    },
    "634f6b10-1def-496d-af44-834ae3c69c27" : {..customer2.},
    "a7ca5d01-757c-4534-a9e1-154c53d160a7" : {..customer 2 etc.}
  }

Body:
I'm assuming that you also have a path for your user data, such as "/users/". The data for the user record would therefore be returned by looking at  "users/LlMNVWXvzLhmP24AKVciM2PvPVy2", for example.

The point of indexing your records as you've done by indicating which users are associated with a customer is just to make it easier to fetch data later on, particularly as your database scales.

Imagine that your user data looked like this:

"users":{
  "LlMNVWXvzLhmP24AKVciM2PvPVy2":{
    "customer" : "1510925e-0541-474f-93c1-10890934fda9"
  }
  "Q4sM188BgwRGYhJUiLDqgAzGGX72":{
    "customer" : "634f6b10-1def-496d-af44-834ae3c69c27"
  }
  ...for many, many records...
}

...and you need to find which user(s) belong(s) to a particular customer record. If your list of users is large, it's going to take a lot of processing to find all the relevant records. You have to check each user.

If, on the other hand, you've done some indexing as you've indicated in your question, finding which users go with a customer record is easy. Just pull up the customer record, get the user ids, then get their data from the /users path.

See the Firebase docs for a great description: https://firebase.google.com/docs/database/android/structure-data#fanout


问:
Kendo UI PDF Export multiple margin settings
I have only a footer on an Kendo UI PDF Export template so I want a different margin on the bottom as opposed to the rest of the PDF page.  I see in the documentation for the PDFMarginComponenet there is top, bottom, right and left but I do not see anywhere on how to implement multiple options.

```<code><kendo-pdf-export #pdf paperSize="A4" margin="'{top: 27, right: 27, left: 27, bottom: 50}'">
....
</kendo-pdf-export>
</code>```

Here is a plunker  http://plnkr.co/edit/jMaJfIdyn1wCoKrTeZ1v?p=preview

答:
Got answer on Github with the Kendo team.  Needed to bind the property and submit them in order.

```<code><kendo-pdf-export #pdf paperSize="A4" [margin]="{top: 27, bottom: 50, right: 27, left: 27}">
....
</kendo-pdf-export>
</code>```

Attached is plunker  http://plnkr.co/edit/HvL1kdiULjhfQPOcwqbe?p=preview

Here is the Github ticket.  https://github.com/telerik/kendo-angular/issues/1078

Body:
I have only a footer on an Kendo UI PDF Export template so I want a different margin on the bottom as opposed to the rest of the PDF page.  I see in the documentation for the PDFMarginComponenet there is top, bottom, right and left but I do not see anywhere on how to implement multiple options.

<kendo-pdf-export #pdf paperSize="A4" margin="'{top: 27, right: 27, left: 27, bottom: 50}'">
....
</kendo-pdf-export>

Here is a plunker  http://plnkr.co/edit/jMaJfIdyn1wCoKrTeZ1v?p=preview

Body:
Got answer on Github with the Kendo team.  Needed to bind the property and submit them in order.

<kendo-pdf-export #pdf paperSize="A4" [margin]="{top: 27, bottom: 50, right: 27, left: 27}">
....
</kendo-pdf-export>

Attached is plunker  http://plnkr.co/edit/HvL1kdiULjhfQPOcwqbe?p=preview

Here is the Github ticket.  https://github.com/telerik/kendo-angular/issues/1078


问:
spring security keycloak adapter
I'm trying to use Keycloak with my spring boot application.

I want to restrict access to a particular URL based on the REST method and user's role.

In the example below, users with any of the roles view-all or calendar can perform a GET, while those with manage-all or calendar_manage can do a POST, PUT, or DELETE.

Unfortunately, this configuration is allowing any authenticated user access to the /api/calendar URL.  What am I doing wrong?

```<code>@Configuration
@EnableWebSecurity
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
...
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .csrf().disable()
                .antMatcher("/api/**")
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/calendar/*").hasAnyRole("view-all", "calendar")
                .antMatchers(HttpMethod.POST, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
                .antMatchers(HttpMethod.PUT, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
                .antMatchers(HttpMethod.DELETE, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage");
    }
}
</code>```

答:
the trick is - you need a /** at the end of the path in the ant matchers!

(I had to step thru the spring code to figure it out - see method doMatch() in Spring Core's AntPathMatcher class)

```<code>.antMatchers(HttpMethod.GET, "/calendar/**")
    .hasAnyRole("view-all", "calendar", "calendar_manage")
.antMatchers(HttpMethod.POST, "/calendar/**")
    .hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.PUT, "/calendar/**")
     .hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.DELETE, "/calendar/**")
    .hasAnyRole("manage-all", "calendar_manage")
</code>```

Title: spring security keycloak adapter

Body:
I'm trying to use Keycloak with my spring boot application.

I want to restrict access to a particular URL based on the REST method and user's role.

In the example below, users with any of the roles view-all or calendar can perform a GET, while those with manage-all or calendar_manage can do a POST, PUT, or DELETE.

Unfortunately, this configuration is allowing any authenticated user access to the /api/calendar URL.  What am I doing wrong?

@Configuration
@EnableWebSecurity
class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
...
    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        super.configure(http);
        http
                .csrf().disable()
                .antMatcher("/api/**")
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/calendar/*").hasAnyRole("view-all", "calendar")
                .antMatchers(HttpMethod.POST, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
                .antMatchers(HttpMethod.PUT, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage")
                .antMatchers(HttpMethod.DELETE, "/api/calendar/*").hasAnyRole("manage-all", "calendar_manage");
    }
}

Body:
the trick is - you need a /** at the end of the path in the ant matchers!

(I had to step thru the spring code to figure it out - see method doMatch() in Spring Core's AntPathMatcher class)

.antMatchers(HttpMethod.GET, "/calendar/**")
    .hasAnyRole("view-all", "calendar", "calendar_manage")
.antMatchers(HttpMethod.POST, "/calendar/**")
    .hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.PUT, "/calendar/**")
     .hasAnyRole("manage-all", "calendar_manage")
.antMatchers(HttpMethod.DELETE, "/calendar/**")
    .hasAnyRole("manage-all", "calendar_manage")


问:
Remove a shape from Canvas
I am drawing simple shapes such as triangle, circles and rectangles onto an Android Canvas backed by a Bitmap.

My question is simple : is it possible to draw a circle (or any other shape) in a way that its surface will be removed from the draw surface ?

答:
The simple answer to your simple question is, "No"  A bit map has no memory so you can't ask it to go back to the previous state, and a Canvas doesn't remember the operations that got it to it's current state, so you can't say "Replay all of those operations except this one."

The more complex answer is you will have to develop the code to "remember" or "replay" as described in the preceding paragraph, or you may want to switch to another way to build your image -- for example Scalable Vector Graphics (SVG)

Title: Remove a shape from Canvas


问:
Angular 4 apply attributes upon declaration to component template (do not render wrapping element)
Let's say I want to make a custom button.
So I create a component

import { Component, Input } from '@angular/core';
@Component({
  selector: '[extended-button]',
  template: `<button (click)="onClick($event)"></button>`,
  styles: []
})
export class ExtendedButtonComponent {
  @Input() disabled: boolean;
}
```

<p>And when I use an instance of this button I want the attibutes I type when declaring it in the HTML to apply to the button inside the template:</p>

<pre class="lang-html prettyprint-override"><code><div extended-button class="some-nice-button"></div>
</code>```

So the results of this would be:

<button class="some-nice-button" (click)="onClick($event)"></button>
```

I really don't want the
 tag to be rendered. Any ideas how to achieve that?

答:
I am not sure if this is what you want to achieve but see the code snippets below:

```<code>import { Component, Input } from '@angular/core';
@Component({
  selector: 'custom-button',
  template: `<button [class]="className" (click)="onClick($event)>Custom Button</button>`
})
export class CustomButtonComponent {
   @Input() className: string;
}
</code>```

Then when you want to use this custom-button, you can attach it to another component like so:

```<code><custom-button [className]="someClassName"></custom-button>
</code>```

Then in the component ts file, you need to specify someClassName:

```<code>someClassName: string = 'someRandomClassName';
</code>```

I hope this will help you.

EDIT:

Body:
Let's say I want to make a custom button.
So I create a component

import { Component, Input } from '@angular/core';
@Component({
  selector: '[extended-button]',
  template: `<button (click)="onClick($event)"></button>`,
  styles: []
})
export class ExtendedButtonComponent {
  @Input() disabled: boolean;
}

And when I use an instance of this button I want the attibutes I type when declaring it in the HTML to apply to the button inside the template:

So the results of this would be:

<button class="some-nice-button" (click)="onClick($event)"></button>

I really don't want the
 tag to be rendered. Any ideas how to achieve that?

Body:
I am not sure if this is what you want to achieve but see the code snippets below:

import { Component, Input } from '@angular/core';
@Component({
  selector: 'custom-button',
  template: `<button [class]="className" (click)="onClick($event)>Custom Button</button>`
})
export class CustomButtonComponent {
   @Input() className: string;
}

Then when you want to use this custom-button, you can attach it to another component like so:

<custom-button [className]="someClassName"></custom-button>

Then in the component ts file, you need to specify someClassName:

someClassName: string = 'someRandomClassName';

I hope this will help you.

EDIT:


问:
Firestore - Cloud Functions - Get uid
I'm trying to get the UID of the user authenticated by firebase web sdk, in the cloud function. The cloud function is triggered by onWrite event of cloud firestore.

This function is triggered when the logged in user is creating/updating items to the cafe. The authentication is handled by Firebase Auth. The security rules enable write only for logged in users. So this event could be tied to a user.

```<code>export const cfun = functions.firestore.document('cafes/{cafeId}/items/{itemId}').onWrite(async event => {
  // trying to get the uid here
})
</code>```

There are examples in the docs that deals with the userId, but in all those cases the userId is part of the document path. But in this model the user is not part of the path, as a cafe could have multiple owners and so could be manipulated by many users. So adding userId to the path is not an option.

It looks like a common case for serverless architecture.

#

Update: Functions triggered by firestore doesn't have event.auth populated. Looking for suggestions on modelling the following requirement.

In the data-model, I've got cafes and owners. Each cafe could be owned by many owners and a cafe could be transferred to some-other owner at a later stage. So the cafes are modelled as /cafes/{cafeId} and everything that belongs to the cafe as /cafes/{cafeId}/items/{itemId} etc.
We also need to query cafes based on different params, if modelled below users it becomes difficult. For these reasons the cafe cannot be modelled as /users/{userId}/cafes/{cafeId}.

As far as security rules are concerned, I could control write access using get(<>) to determine who gets write access to cafes. There is no problem with the security.

I feel that the execution context should provide all available information and let the developers handle it appropriate for their use case. And for serverless apps userId is a must.

If event.auth is not provided in the function, then this restriction will force items that does not belong to users to be modelled /users/{userId}/<item_name>/{itemId} just for the sake of accessing the userId in the cloud functions. This doesn't feel natural.

Also right now there is no way to figure if the cloud function is triggered because of the changes performed in the console. The event.auth info that is available for firebase database triggered functions will be perfect to handle all cases.

Any suggestions regarding how to remodel this case is appreciated as well.

#

Thanks in advance,

答:
I have been facing a similar issue. In Firebase, it was easy - you simply took the data from event.auth. I would assume this is simply a feature not implemented yet while we are in the beta phase of Firestore. Adding the user id to the path does not work as you previously mentioned as it will constantly be changing depending on the user making the update.

My scenario is that I want to create a "lastUpdatedBy" field in the object being updated. If we were to allow the client to send in a lastUpdatedBy field in the payload, this could be abused by a rogue client (i.e. someone with a authenticated account) trying to impersonate someone else. Therefore in Firebase we relied on a cloud function to populate this field on data change events.

My workaround is to allow the client to insert the "lastUpdatedBy" field but additionally use the Firestore rules to validate that the userId in the payload matches that of the logged in user - otherwise deny the write request.

Something like:

```<code>match /collectionA/{docId} {
  allow update: if request.resource.data.lastUpdatedBy == request.auth.uid;
}
</code>```

Until Google/Firestore guys add the "auth" object to the cloud function I don't see any other workaround but would love to hear differently.

Title: Firestore - Cloud Functions - Get uid

Body:
I'm trying to get the UID of the user authenticated by firebase web sdk, in the cloud function. The cloud function is triggered by onWrite event of cloud firestore.

This function is triggered when the logged in user is creating/updating items to the cafe. The authentication is handled by Firebase Auth. The security rules enable write only for logged in users. So this event could be tied to a user.

export const cfun = functions.firestore.document('cafes/{cafeId}/items/{itemId}').onWrite(async event => {
  // trying to get the uid here
})

There are examples in the docs that deals with the userId, but in all those cases the userId is part of the document path. But in this model the user is not part of the path, as a cafe could have multiple owners and so could be manipulated by many users. So adding userId to the path is not an option.

It looks like a common case for serverless architecture.

#

Update: Functions triggered by firestore doesn't have event.auth populated. Looking for suggestions on modelling the following requirement.

In the data-model, I've got cafes and owners. Each cafe could be owned by many owners and a cafe could be transferred to some-other owner at a later stage. So the cafes are modelled as /cafes/{cafeId} and everything that belongs to the cafe as /cafes/{cafeId}/items/{itemId} etc.
We also need to query cafes based on different params, if modelled below users it becomes difficult. For these reasons the cafe cannot be modelled as /users/{userId}/cafes/{cafeId}.

As far as security rules are concerned, I could control write access using get(<>) to determine who gets write access to cafes. There is no problem with the security.

I feel that the execution context should provide all available information and let the developers handle it appropriate for their use case. And for serverless apps userId is a must.

If event.auth is not provided in the function, then this restriction will force items that does not belong to users to be modelled /users/{userId}/<item_name>/{itemId} just for the sake of accessing the userId in the cloud functions. This doesn't feel natural.

Also right now there is no way to figure if the cloud function is triggered because of the changes performed in the console. The event.auth info that is available for firebase database triggered functions will be perfect to handle all cases.

Any suggestions regarding how to remodel this case is appreciated as well.

#

Thanks in advance,

Body:
I have been facing a similar issue. In Firebase, it was easy - you simply took the data from event.auth. I would assume this is simply a feature not implemented yet while we are in the beta phase of Firestore. Adding the user id to the path does not work as you previously mentioned as it will constantly be changing depending on the user making the update.

My scenario is that I want to create a "lastUpdatedBy" field in the object being updated. If we were to allow the client to send in a lastUpdatedBy field in the payload, this could be abused by a rogue client (i.e. someone with a authenticated account) trying to impersonate someone else. Therefore in Firebase we relied on a cloud function to populate this field on data change events.

My workaround is to allow the client to insert the "lastUpdatedBy" field but additionally use the Firestore rules to validate that the userId in the payload matches that of the logged in user - otherwise deny the write request.

Something like:

match /collectionA/{docId} {
  allow update: if request.resource.data.lastUpdatedBy == request.auth.uid;
}

Until Google/Firestore guys add the "auth" object to the cloud function I don't see any other workaround but would love to hear differently.


问:
How to develop a wordpress site in the root while a static site exists?
Can I have an index2.php file and redirect the htacess file for the meantime?  If so how do I redirect the page for the time being so I can change it later?</p>

答:
There are two ways to do this:

Put WordPress somewhere else

This is, by far, the easiest way to create a WordPress site while keeping an existing site active.

Install WordPress in a different location than your existing, static site

Edit your Windows .hosts file so that your computer points to the new location when you try browsing to the existing site

Set up WordPress and get your site up-and-running

When you're ready to go, tell your server to redirect requests from the old location to the new location

This is similar to the process I use when setting up a new site or working on a client system.  If my static site is http://mysite.com/ and lives on /public_html/mysite.com/ on the server, I'll park WordPress in /public_html/wordpress/ and create a subdomain that points there (http://beta.mysite.com/).  When everything is ready, I just change my DNS settings and everything moves automatically.

Set up your default documents in .htaccess

If your existing site is static, it's probably got an index.html file in the root.  You can tell your .htaccess file to use this as the default document.  Then, regular requests to your site will go to the static site, but you can manually go to WordPress by placing index.php at the end of your URL.

The big lesson to learn here, though, is that you should never develop on a production site.  You should develop your WordPress site somewhere else (locally on your computer, on a subdomain, in a subfolder, etc) and only move it to the root of your live site when you're ready for it to go public.


问:
How to define a function in Laravel 5.5 before the app starts
In Laravel 5.5, the bootstrap/autoload.php file has been removed. This is where I would have defined a function that overwrites the typical Laravel helpers as in this thread.

How can I achieve the same in the 5.5 release? I tried a require at the top of the bootstrap/app.php file with no luck.

答: There is a package that can help https://github.com/funkjedi/composer-include-files</p>


问:
How to load images dynamically (or lazily) when users scrolls them into view
I've noticed this in numerous "modern" websites (e.g. facebook and google image search) where the images below the fold load only when user scrolls down the page enough to bring them inside the visible viewport region (upon view source, the page shows X number of  tags but they are not fetched from the server straight away). What is this technique called, how does it work and in how many browsers does it work. And is there a jQuery plugin that can achieve this behavior with minimum coding.

Edit

Bonus: can someone explain if there is a "onScrolledIntoView" or similar event for HTML elements. If not, how do these plugins work?

答: Im using jQuery Lazy. It took me about 10 minutes to test out and an hour or two to add to most of the image links on one of my websites (CollegeCarePackages.com). I have NO (none/zero) relationship of any kind to the dev, but it saved me a lot of time and basically helped improve our bounce rate for mobile users and I appreciate it.

ContentLicense: CC BY-SA 4.0


问:
Creating a worksheet from Apache POI deprecated methods
I am trying to create a worksheet using HSSFSheet from org.apache.poi.hssf.usermodel.*, but when I use some of the methods my Eclipse IDE is yelling that it is deprecated. For example, it is yelling that the setColumnWidth method is deprecated:

```<code>HSSFSheet workSheet = workBook.createSheet("CPNI");
workSheet.setColumnWidth((short) 0, (short) (230 * ABOUT_ONE_PIXEL_WIDE));
</code>```

However, when I look at the HSSFSheet API documentation, it doesn't list it as deprecated nor the other methods that my IDE is yelling at so I am not sure why my IDE is yelling that the methods are deprecated.

I am using the poi-3.13.jar.

答:
If I extract the javadoc for poi 3.13 it says the following

void    setColumnWidth(short columnIndex, short width)

Deprecated. (Sep 2008) use setColumnWidth(int, int)

You're probably reading an online documentation for the latest version where this function has been removed (after being deprecated for a long while)

https://poi.apache.org/apidocs/index.html?org/apache/poi/hssf/usermodel/HSSFSheet.html

So to fix this particular error you shouldn't cast it to short

It's always a good idea to read the documentation for the version you are using. The IDE should be ale to pull this from the maven repository automatically.

If it doesn't do this you can always extract the javadocs yourself.

Download poi-3.13-javadoc.jar from https://repo1.maven.org/maven2/org/apache/poi/poi/3.13/
and unzip it

Body:
I am trying to create a worksheet using HSSFSheet from org.apache.poi.hssf.usermodel.*, but when I use some of the methods my Eclipse IDE is yelling that it is deprecated. For example, it is yelling that the setColumnWidth method is deprecated:

HSSFSheet workSheet = workBook.createSheet("CPNI");
workSheet.setColumnWidth((short) 0, (short) (230 * ABOUT_ONE_PIXEL_WIDE));

However, when I look at the HSSFSheet API documentation, it doesn't list it as deprecated nor the other methods that my IDE is yelling at so I am not sure why my IDE is yelling that the methods are deprecated.

I am using the poi-3.13.jar.


问:
Best-case running time: upper and lower bound?
In my assignment I was given some information about an algorithm in form of statements. One of these statements was: "the best-case running time of Algorithm B is Ω(n^2);".

I was under the impression that best-case running time of algorithms is always either lower-bound, upper-bound or tight-bound. I am wondering if an algorithm such as this can also have an upper-bound of its best-case running time. If so, what are some examples of algorithms where this occurs?

答:
A case is a class of inputs for which you consider your algorithm's performance. The best case is the class of inputs for which your algorithm's runtime has the most desirable asymptotic bounds. Typically this might mean there is no other class which gives a lower Omega bound. The worst case is the class of inputs for which your algorithm's runtime has the least desirable asymptotic bounds. Typically this might mean there is no other class which gives a higher O bound. The average case has nothing to do with desirability of bounds but looks at the expected value of the runtime given some stated distribution of inputs. Etc. You can define whatever cases you want.

Imagine the following algorithm:

```<code>Weird(a[1...n])
    if n is even then
        flip a coin
        if heads then bogosort(a[1...n])
        else if tails then bubble_sort(a[1...n])
    else if n is odd then
        flip a coin
        if heads then merge_sort(a[1...n])
        else if tails then counting_sort(a[1...n])
</code>```

Given a list of n integers each between 1 and 10, inclusive, this algorithm sorts the list.

In the best case, n is odd. A lower bound on the best case is Omega(n) and an upper bound on the best case is O(n log n).

In the worst case, n is even. A lower bound on the worst case is O(n^2) and there is no upper bound on the worst case (since bogosort may never finish, despite that being terribly unlikely).

To define an average case, we would need to define probabilities. Assuming even/odd are equally likely for all n, then there is no upper bound on the average case and a lower bound on the average case is Omega(n^2), same as for the worst case. To get a different bound for the average case, we'd need to define the distribution so that n being even gets increasingly unlikely for larger lists. Maybe the only even-length list you typically pass into this algorithm has length 2, for example.

Body:
A case is a class of inputs for which you consider your algorithm's performance. The best case is the class of inputs for which your algorithm's runtime has the most desirable asymptotic bounds. Typically this might mean there is no other class which gives a lower Omega bound. The worst case is the class of inputs for which your algorithm's runtime has the least desirable asymptotic bounds. Typically this might mean there is no other class which gives a higher O bound. The average case has nothing to do with desirability of bounds but looks at the expected value of the runtime given some stated distribution of inputs. Etc. You can define whatever cases you want.

Imagine the following algorithm:

Weird(a[1...n])
    if n is even then
        flip a coin
        if heads then bogosort(a[1...n])
        else if tails then bubble_sort(a[1...n])
    else if n is odd then
        flip a coin
        if heads then merge_sort(a[1...n])
        else if tails then counting_sort(a[1...n])

Given a list of n integers each between 1 and 10, inclusive, this algorithm sorts the list.

In the best case, n is odd. A lower bound on the best case is Omega(n) and an upper bound on the best case is O(n log n).

In the worst case, n is even. A lower bound on the worst case is O(n^2) and there is no upper bound on the worst case (since bogosort may never finish, despite that being terribly unlikely).

To define an average case, we would need to define probabilities. Assuming even/odd are equally likely for all n, then there is no upper bound on the average case and a lower bound on the average case is Omega(n^2), same as for the worst case. To get a different bound for the average case, we'd need to define the distribution so that n being even gets increasingly unlikely for larger lists. Maybe the only even-length list you typically pass into this algorithm has length 2, for example.


问:
Jedis: Broken Pipe
So, I have 2 applications using jedis. They both connect to the same server, and one listens for a Publish in order to check if something certain is writen. Well, after about 10 hours of conisistent use and load, setting/getting/pub/sub ect, the jedis returns Broken Pipe. I don't know why because I have the timeout to 0 in jedis. Any ideas?</p>

答:
From what I've discovered Jedis keeps open connections to Redis and does not check for the state of these connections. If a connection has been interrupted during idle time (network got reset or momentarily disconnected, or connection timed out), Jedis connection pool will basically become invalid, but Jedis client won't report that until you try to send a command down the pipe.
Here's the discussion on github: https://github.com/xetorthio/jedis/issues/185

The way I worked around this is by sending a "ping" before sending any data:

```<code>private Jedis getResource() {
    Jedis jedis;
    try{
        jedis = pool.getResource();
        jedis.ping();
    } catch (JedisException e) {
        pool.destroy();
        pool = getPool(this.url);
        jedis = pool.getResource();
    }
    return jedis;
}

public String get(EphemeralKey key, EphemeralLocation location) throws Exception {
    String encodedKey = encodeKey(key, location);
    try (Jedis jedis = getResource()) {
        return jedis.get(encodedKey);
    } catch (JedisException e) {
        throw wrapJedisException(e);
    }
    return null;
}
</code>```

Title: Jedis: Broken Pipe

Body:
From what I've discovered Jedis keeps open connections to Redis and does not check for the state of these connections. If a connection has been interrupted during idle time (network got reset or momentarily disconnected, or connection timed out), Jedis connection pool will basically become invalid, but Jedis client won't report that until you try to send a command down the pipe.
Here's the discussion on github: https://github.com/xetorthio/jedis/issues/185

The way I worked around this is by sending a "ping" before sending any data:

private Jedis getResource() {
    Jedis jedis;
    try{
        jedis = pool.getResource();
        jedis.ping();
    } catch (JedisException e) {
        pool.destroy();
        pool = getPool(this.url);
        jedis = pool.getResource();
    }
    return jedis;
}

public String get(EphemeralKey key, EphemeralLocation location) throws Exception {
    String encodedKey = encodeKey(key, location);
    try (Jedis jedis = getResource()) {
        return jedis.get(encodedKey);
    } catch (JedisException e) {
        throw wrapJedisException(e);
    }
    return null;
}


问:
Single Quote Params vs No Quote Params?
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

```<code>{
    'name': 'Teddy',
    'last': 'Monster'
}
</code>```

But then I also see the more common, no quote params:

```<code>{
    name: 'Teddy',
    last: 'Monster'
}
</code>```

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

答:
You can't define this hash:

```<code>{
   function: 'foo'
}
</code>```

But you can define

```<code>{
   'function': 'foo'
}
</code>```

Personally, I use the former way, if there's no reserved keywords as keys (as to not clutter the code, like you've pointed out).

Title: Single Quote Params vs No Quote Params?

Body:
This is something that's been mind boggling to me for a while, some times I see people writing javascript objects like so with single quote params:

{
    'name': 'Teddy',
    'last': 'Monster'
}

But then I also see the more common, no quote params:

{
    name: 'Teddy',
    last: 'Monster'
}

Is there a reason one would use single quote params?
Is it faster to parse?

From what I can see, there is no speed difference, rather just cluttering the file with unnecessary quotes and increasing file size.

I'll change my mind if I can get a straight answer :)

Body:
You can't define this hash:

{
   function: 'foo'
}

But you can define

{
   'function': 'foo'
}

Personally, I use the former way, if there's no reserved keywords as keys (as to not clutter the code, like you've pointed out).


问:
7-dimensional vector Java
I am very new to java and I have this assignment which I have been working on very intensivly for the last 14 days.

The assignement is to build a class vector with max. 7 dimensions:
what I came with to make the vector multi-dimensional is that I declared 7 variables

```<code>private double x, y,z,i,j,k,f;
</code>```

which then I will initialize in constructors etc..
Well, my first question: did I build a 7 dimensional vector in this way?

OR,

should I somehow work with arrays for this problem
like declaring an array;

```<code>double [][] = data; // which generates a 2D-Vector.
</code>```

AND,

```<code>double [][][][][][][] = data1; //which declare a 7D-Vector??!!!
</code>```

for any helpful information I will be very thankful

thanks all and
Best regards to you  :)

答:
did I build a 7 dimensional vector in this way?

Yes you have.  A vector is a way of storing a magnitude and direction, which is done by correctly assigning the value and sign of each double.  A vector in 2-space would require two values, and a vector in 7-space would require 7 values, which you have.

should I somehow work with arrays for this problem like declaring an array;

You can, but you don't need a multi-dimensional array.  To store a single vector in a 7-space, you just need an array of length 7:

```<code>double[] data = new double[7]; // store a 7D vector
</code>```

You could then modify your existing code, replacing x with data[0], y with data[1] and so on.

Title: 7-dimensional vector Java

Body:
I am very new to java and I have this assignment which I have been working on very intensivly for the last 14 days.

The assignement is to build a class vector with max. 7 dimensions:
what I came with to make the vector multi-dimensional is that I declared 7 variables

private double x, y,z,i,j,k,f;

which then I will initialize in constructors etc..
Well, my first question: did I build a 7 dimensional vector in this way?

OR,

should I somehow work with arrays for this problem
like declaring an array;

double [][] = data; // which generates a 2D-Vector.

AND,

double [][][][][][][] = data1; //which declare a 7D-Vector??!!!

for any helpful information I will be very thankful

thanks all and
Best regards to you  :)

Body:
did I build a 7 dimensional vector in this way?

Yes you have.  A vector is a way of storing a magnitude and direction, which is done by correctly assigning the value and sign of each double.  A vector in 2-space would require two values, and a vector in 7-space would require 7 values, which you have.

should I somehow work with arrays for this problem like declaring an array;

You can, but you don't need a multi-dimensional array.  To store a single vector in a 7-space, you just need an array of length 7:

double[] data = new double[7]; // store a 7D vector

You could then modify your existing code, replacing x with data[0], y with data[1] and so on.


问:
tf.data.Dataset append element
Given a TFRecord with the following structure:

```<code>context_features = {
    "labels_length": tf.FixedLenFeature(shape=[], dtype=tf.int64),
    "filename": tf.FixedLenFeature(shape=[], dtype=tf.string)
}
sequence_features = {
    "labels": tf.FixedLenSequenceFeature(shape=[], dtype=tf.int64)
}
</code>```

I would like to append one element to the labels field at run time, when parsing the record file. The iterator written for this dataset also creates batches and pads them with zeros, so it is important to add the element at the end of the list before the padded values are added. For example, if we have three entries: [1.2], [3,4,5], [6,7,8,9] and the element to be added is 10, the padded batch should look like this:

[1, 2, 10, 0, 0],
[3, 4, 5, 10, 0],
[6, 7, 8, 9, 10]

Could you recommend me a way to do it ?
Thank you

答:
To do this, you can simply use tf.concat() to add an element to the labels tensor that you get from tf.parse_single_sequence_example(). For example, to append 10 to each label:

```<code>def _parse_labels_function(example):
    context_features = {
        "labels_length": tf.FixedLenFeature(shape=[], dtype=tf.int64),
        "filename": tf.FixedLenFeature(shape=[], dtype=tf.string)
    }
    sequence_features = {
        "labels": tf.FixedLenSequenceFeature(shape=[], dtype=tf.int64)
    }

    context_parsed, sequence_parsed = tf.parse_single_sequence_example(
        serialized=example,
        context_features=context_features,
        sequence_features=sequence_features
    )

    # Append `10` to each label sequence.
    labels = tf.concat([sequence_parsed["labels"], [10]], 0)

    return labels, context_parsed["labels_length"], context_parsed["filename"]

dataset = tf.data.TFRecordDataset(label_record)
dataset = dataset.map(_parse_labels_function)
</code>```

Note that I'm not sure how you use the "labels_length" feature in your program, but you may also want to add one to it before returning.

Title: tf.data.Dataset append element

Body:
Given a TFRecord with the following structure:

context_features = {
    "labels_length": tf.FixedLenFeature(shape=[], dtype=tf.int64),
    "filename": tf.FixedLenFeature(shape=[], dtype=tf.string)
}
sequence_features = {
    "labels": tf.FixedLenSequenceFeature(shape=[], dtype=tf.int64)
}

I would like to append one element to the labels field at run time, when parsing the record file. The iterator written for this dataset also creates batches and pads them with zeros, so it is important to add the element at the end of the list before the padded values are added. For example, if we have three entries: [1.2], [3,4,5], [6,7,8,9] and the element to be added is 10, the padded batch should look like this:

[1, 2, 10, 0, 0],
[3, 4, 5, 10, 0],
[6, 7, 8, 9, 10]

Could you recommend me a way to do it ?
Thank you

Body:
To do this, you can simply use tf.concat() to add an element to the labels tensor that you get from tf.parse_single_sequence_example(). For example, to append 10 to each label:

def _parse_labels_function(example):
    context_features = {
        "labels_length": tf.FixedLenFeature(shape=[], dtype=tf.int64),
        "filename": tf.FixedLenFeature(shape=[], dtype=tf.string)
    }
    sequence_features = {
        "labels": tf.FixedLenSequenceFeature(shape=[], dtype=tf.int64)
    }

    context_parsed, sequence_parsed = tf.parse_single_sequence_example(
        serialized=example,
        context_features=context_features,
        sequence_features=sequence_features
    )

    # Append `10` to each label sequence.
    labels = tf.concat([sequence_parsed["labels"], [10]], 0)

    return labels, context_parsed["labels_length"], context_parsed["filename"]

dataset = tf.data.TFRecordDataset(label_record)
dataset = dataset.map(_parse_labels_function)

Note that I'm not sure how you use the "labels_length" feature in your program, but you may also want to add one to it before returning.


问:
How to retrieve SQL result column value using column name in Python?
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:

```<code>Object id = rs.get("CUSTOMER_ID");
</code>```

I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.

Thanks!

答:
This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Here is the example on the mysql site:

```<code>cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))
</code>```

Body:
Is there a way to retrieve SQL result column value using column name instead of column index in Python? I'm using Python 3 with mySQL. The syntax I'm looking for is pretty much like the Java construct:

Object id = rs.get("CUSTOMER_ID");

I've a table with quite a number of columns and it is a real pain to constantly work out the index for each column I need to access. Furthermore the index is making my code hard to read.

Thanks!

Body:
This post is old but may come up via searching.

Now you can use mysql.connector to retrive a dictionary as shown here:
https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursordict.html

Here is the example on the mysql site:

cnx = mysql.connector.connect(database='world')
cursor = cnx.cursor(dictionary=True)
cursor.execute("SELECT * FROM country WHERE Continent = 'Europe'")

print("Countries in Europe:")
for row in cursor:
    print("* {Name}".format(Name=row['Name']))


问:
Load view from an external xib file in storyboard
I want to use a view throughout multiple viewcontrollers in a storyboard. Thus, I thought about designing the view in an external xib so changes are reflected in every viewcontroller. But how can one load a view from a external xib in a storyboard and is it even possible? If thats not the case, what other alternatives are availble to suit the situation abouve?</p>

答:
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift

Create a .xib file and style it as you want. i.e. MyCustomClass.xib

Set the File's Owner of the .xib file to be your custom class (MyCustomClass)

GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.

Hook up your outlets as you normally would using the Assistant Editor.

NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.

Make sure your custom class has @IBDesignable before the class statement.

Make your custom class conform to the NibLoadable protocol referenced below.

NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.

Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.

Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).

Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

```<code>public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}
</code>```

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

```<code>@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}
</code>```

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.

Body:
For a while Christopher Swasey's approach was the best approach I had found. I asked a couple of the senior devs on my team about it and one of them had the perfect solution! It satisfies every one of the concerns that Christopher Swasey so eloquently addressed and it doesn't require boilerplate subclass code(my main concern with his approach). There is one gotcha, but other than that it is fairly intuitive and easy to implement.

Create a custom UIView class in a .swift file to control your xib. i.e. MyCustomClass.swift

Create a .xib file and style it as you want. i.e. MyCustomClass.xib

Set the File's Owner of the .xib file to be your custom class (MyCustomClass)

GOTCHA: leave the class value (under the identity Inspector) for your custom view in the .xib file blank. So your custom view will have no specified class, but it will have a specified File's Owner.

Hook up your outlets as you normally would using the Assistant Editor.

NOTE: If you look at the Connections Inspector you will notice that your Referencing Outlets do not reference your custom class (i.e. MyCustomClass), but rather reference File's Owner. Since File's Owner is specified to be your custom class, the outlets will hook up and work propery.

Make sure your custom class has @IBDesignable before the class statement.

Make your custom class conform to the NibLoadable protocol referenced below.

NOTE: If your custom class .swift file name is different from your .xib file name, then set the nibName property to be the name of your .xib file.

Implement required init?(coder aDecoder: NSCoder) and override init(frame: CGRect) to call setupFromNib() like the example below.

Add a UIView to your desired storyboard and set the class to be your custom class name (i.e. MyCustomClass).

Watch IBDesignable in action as it draws your .xib in the storyboard with all of it's awe and wonder.

Here is the protocol you will want to reference:

public protocol NibLoadable {
    static var nibName: String { get }
}

public extension NibLoadable where Self: UIView {

    public static var nibName: String {
        return String(describing: Self.self) // defaults to the name of the class implementing this protocol.
    }

    public static var nib: UINib {
        let bundle = Bundle(for: Self.self)
        return UINib(nibName: Self.nibName, bundle: bundle)
    }

    func setupFromNib() {
        guard let view = Self.nib.instantiate(withOwner: self, options: nil).first as? UIView else { fatalError("Error loading \(self) from nib") }
        addSubview(view)
        view.translatesAutoresizingMaskIntoConstraints = false
        view.leadingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.leadingAnchor, constant: 0).isActive = true
        view.topAnchor.constraint(equalTo: self.safeAreaLayoutGuide.topAnchor, constant: 0).isActive = true
        view.trailingAnchor.constraint(equalTo: self.safeAreaLayoutGuide.trailingAnchor, constant: 0).isActive = true
        view.bottomAnchor.constraint(equalTo: self.safeAreaLayoutGuide.bottomAnchor, constant: 0).isActive = true
    }
}

And here is an example of MyCustomClass that implements the protocol (with the .xib file being named MyCustomClass.xib):

@IBDesignable
class MyCustomClass: UIView, NibLoadable {

    @IBOutlet weak var myLabel: UILabel!

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupFromNib()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupFromNib()
    }

}

NOTE: If you miss the Gotcha and set the class value inside your .xib file to be your custom class, then it will not draw in the storyboard and you will get a EXC_BAD_ACCESS error when you run the app because it gets stuck in an infinite loop of trying to initialize the class from the nib using the init?(coder aDecoder: NSCoder) method which then calls Self.nib.instantiate and calls the init again.


问:
DownloadManager does not start the download
im using downloadManager but it doesnt download nothing. When i start to download the file, it is placed in queue list and never start the download. This is my code:

```<code>webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);
                //------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                //------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) activity.getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(activity.getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }
        });
</code>```

If i debbug, all values seem correct. This exact code work with Android 6.0, but when i try it with Android 7.0 doesnt work.

Any help?

Thank you very much!!

答: Are you asking for the WRITE_EXTERNAL_STORAGE permission?</p>

Body:
im using downloadManager but it doesnt download nothing. When i start to download the file, it is placed in queue list and never start the download. This is my code:

webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, final String contentDisposition, final String mimeType, long contentLength) {
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                request.setMimeType(mimeType);
                //------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                //------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription("Downloading file...");
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimeType));
                DownloadManager dm = (DownloadManager) activity.getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);
                Toast.makeText(activity.getApplicationContext(), "Downloading File", Toast.LENGTH_LONG).show();
            }
        });

If i debbug, all values seem correct. This exact code work with Android 6.0, but when i try it with Android 7.0 doesnt work.

Any help?

Thank you very much!!


问:
Caching Google API calls for unit tests
I've got a Google App Engine project that uses the Google Cloud Language API, and I'm using the Google API Client Library (Python) to make the API calls.

When running my unit tests, I make quite a few calls to the API.  This slows down my testing and also incurs costs.

I'd like to cache the calls to the Google API to speed up my tests and avoid the API charges, and I'd rather not roll my own if another solution is available.

I found this Google API page, which suggests doing this:

```<code>import httplib2
http = httplib2.Http(cache=".cache")
</code>```

And I've added these lines to my code (there is another option to use GAE memcache but won't be persisted between test code invocations) and right after these lines, I create my API call connection:

```<code>NLP = discovery.build("language", "v1", API_KEY)
</code>```

The caching isn't working and the above solution seems too simple so I suspect I am missing something.

UPDATE:

I updated my tests so that App Engine is not used (just a regular unit test) and I also figured out that I can pass the http I created to the Google API client like this:

```<code>NLP = discovery.build("language", "v1", http, API_KEY)
</code>```

Now, the initial discovery call is cached but the actual API calls are not cached,e.g., this call is not cached:

```<code>result = NLP.documents().annotateText(body=data).execute()
</code>```

答:
If you're trying to make a test run faster by caching an API call result, stop and consider whether you may have taken a wrong turn.

If can you restructure your code such that you can replace the API call with a unittest.mock, your tests will run much, much faster.

Title: Caching Google API calls for unit tests

Body:
I've got a Google App Engine project that uses the Google Cloud Language API, and I'm using the Google API Client Library (Python) to make the API calls.

When running my unit tests, I make quite a few calls to the API.  This slows down my testing and also incurs costs.

I'd like to cache the calls to the Google API to speed up my tests and avoid the API charges, and I'd rather not roll my own if another solution is available.

I found this Google API page, which suggests doing this:

import httplib2
http = httplib2.Http(cache=".cache")

And I've added these lines to my code (there is another option to use GAE memcache but won't be persisted between test code invocations) and right after these lines, I create my API call connection:

NLP = discovery.build("language", "v1", API_KEY)

The caching isn't working and the above solution seems too simple so I suspect I am missing something.

UPDATE:

I updated my tests so that App Engine is not used (just a regular unit test) and I also figured out that I can pass the http I created to the Google API client like this:

NLP = discovery.build("language", "v1", http, API_KEY)

Now, the initial discovery call is cached but the actual API calls are not cached,e.g., this call is not cached:

result = NLP.documents().annotateText(body=data).execute()


问:
How to add +/- functionality to a butting in kotlin android
I need to add new button with functionality of +/-. If user clicks the button for the first time the value should return -> "-" (ex => -123), if the user clicks again value "-" should be removed (ex => 123). The functionality is similar as +/- button in the calculator.

Here is my code

Activity.kt file

```<code> package com.tripbegins.calculator
 import android.support.v7.app.AppCompatActivity
 import android.os.Bundle
 import android.view.View
 import android.widget.Button
 import com.tripbegins.calculator.R.id.*
 import kotlinx.android.synthetic.main.activity_main.*

 class MainActivity : AppCompatActivity() {

 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

var emptyText = true
fun numberEvents(view: View) {
var checkButton:Boolean = false
if(emptyText){
    viewResult.setText("")
}
emptyText = false

var button = view as Button
var isClicked = viewResult.text.toString()
when (button.id) {
    buttonOne.id -> isClicked += "1"
    buttonTwo.id -> isClicked += "2"
    buttonThree.id -> isClicked += "3"
    dotButton.id-> isClicked+="."
}

viewResult.setText(isClicked)
 }

var operation ="+"
var oldValues:String? = null

fun mathOperation(view: View){
var mathButton = view as Button
var isClicked = viewResult.text.toString()

when(mathButton.id){
    plusButton.id-> {
        operation = "+"
    }
    minusButton.id->{
        operation="-"
    }
    mulButton.id->{
        operation="*"
    }

}
oldValues = viewResult.text.toString()
emptyText = true
 }

 fun Calculate(view: View){

var newValues = viewResult.text.toString()
var calulateButton:Double? = null
when(operation){
    "+"-> { calulateButton = oldValues!!.toDouble() +
newValues.toDouble() }
    "-"-> { calulateButton = oldValues!!.toDouble() -
newValues.toDouble() }
    "*"-> { calulateButton = oldValues!!.toDouble() *
newValues.toDouble() }

}
viewResult.setText(calulateButton.toString())
emptyText=true
 }
 fun clearFunction(view: View){
viewResult.setText("")
 }
 }
</code>```

activity.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tripbegins.calculator.MainActivity">

<EditText
android:id="@+id/viewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="42dp"
android:ems="10"
android:gravity="bottom|right"
android:inputType="textPersonName"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="76dp"
android:onClick="numberEvents"
android:text="2"
app:layout_constraintStart_toEndOf="@+id/buttonOne"
app:layout_constraintTop_toBottomOf="@+id/viewResult" />

<Button
android:id="@+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="38dp"
android:onClick="mathOperation"
android:text="+"
app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="33dp"
android:onClick="mathOperation"
android:text="-"
app:layout_constraintStart_toEndOf="@+id/plusButton"
app:layout_constraintTop_toBottomOf="@+id/buttonTwo" />

<Button
android:id="@+id/mulButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="26dp"
android:onClick="mathOperation"
android:text="*"
app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
app:layout_constraintStart_toEndOf="@+id/minusButton" />

<Button
android:id="@+id/calButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:onClick="Calculate"
android:text="Calculate"
app:layout_constraintStart_toStartOf="@+id/minusButton"
app:layout_constraintTop_toBottomOf="@+id/minusButton" />

<Button
android:id="@+id/buttonThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="26dp"
android:onClick="numberEvents"
android:text="3"
app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
app:layout_constraintStart_toEndOf="@+id/buttonTwo" />

<Button
android:id="@+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="34dp"
android:onClick="numberEvents"
android:text="1"
app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/dotButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="22dp"
android:onClick="numberEvents"
android:text="."
app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
app:layout_constraintEnd_toStartOf="@+id/calButton" />

<Button
android:id="@+id/clearButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="11dp"
android:onClick="clearFunction"
android:text="Clear"
app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
app:layout_constraintStart_toEndOf="@+id/calButton" />
</android.support.constraint.ConstraintLayout>
</code>```

Updated Activity.kt file
I have updated the code for the =/-. Added the var outside the function

```<code>  var emptyText = true
  var isMinusPrinted=false
  fun numberEvents(view: View)

**Current result**

If button clicked for the first time value => -123
If button clicked for the second time value => -123
If button clicked for the third time value => --123

**Expected Result**
If button clicked for the first time value => -123
If button clicked for the second time value => 123
If button clicked for the third time value => -123
</code>```

Updated activity.kt file

```<code>package com.tripbegins.calculator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import com.tripbegins.calculator.R.id.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    var emptyText = true
    var isMinusPrinted=false
    fun numberEvents(view: View) {
        if(emptyText){
            viewResult.setText("")
        }
        emptyText = false
        var button = view as Button
        var plusMinusCheck =""
        var isClicked = viewResult.text.toString()

        when (button.id) {

            buttonOne.id -> isClicked += "1"
            buttonTwo.id -> isClicked += "2"
            buttonThree.id -> isClicked += "3"

            dotButton.id -> {
                isClicked += "."
                dotButton.isClickable = false //**add this line here**
            }
            plusMinusBtn.id->{

                var resultWithoutMinus=isClicked//ex: 123
                if(!isMinusPrinted){

                    isClicked = "-" + resultWithoutMinus//this line for
    example give result like: -123
                    isMinusPrinted=true
                }
                else{
                    isClicked=resultWithoutMinus //result became : 123
                    isMinusPrinted=false
                }

            }

        }

            viewResult.setText(isClicked)
    }

    var operation ="+"
    var oldValues:String? = null

    fun mathOperation(view: View){
        var mathButton = view as Button
        var isClicked = viewResult.text.toString()

        when(mathButton.id){
            plusButton.id-> {
                operation = "+"
            }
            minusButton.id->{
                operation="-"
            }
            mulButton.id->{
                operation="*"
            }

        }
        oldValues = viewResult.text.toString()
        emptyText = true
        dotButton.isClickable=true//**add this line here**

    }

    fun Calculate(view: View){

        var newValues = viewResult.text.toString()
        var calulateButton:Double? = null

        when(operation){
            "+"-> { calulateButton = oldValues!!.toDouble() +
newValues.toDouble() }
            "-"-> { calulateButton = oldValues!!.toDouble() -
newValues.toDouble() }
            "*"-> { calulateButton = oldValues!!.toDouble() *
newValues.toDouble() }

        }
        viewResult.setText(calulateButton.toString())
        emptyText=true
        dotButton.isClickable=true //**add this line here**
    }
    fun clearFunction(view: View){
        viewResult.setText("")
        dotButton.isClickable=true //**add this line here**
    }
}
</code>```

Updated the xml file for the button -> +/-

```<code><Button
android:id="@+id/plusMinusBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="52dp"
android:layout_marginStart="38dp"
android:onClick="numberEvents"
android:text="+/-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</code>```

答:
Edit:

```<code>    var emptyText = true
    var isMinusPrinted=false//add this line here
    fun numberEvents(view: View) {
    var checkButton:Boolean = false
    if(emptyText){
        viewResult.setText("")
    }
    emptyText = false

    var button = view as Button
    var isClicked = viewResult.text.toString()
    when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> isClicked+="."
        plusMinusBtn.id->{//add this block of code from here

        var resultWithoutMinus=Math.abs(isClicked.toInt()) //ex: 123

        if(!isMinusPrinted){

            isClicked = "-" + resultWithoutMinus//this line for example give result like: -123
            isMinusPrinted=true
        }
        else{
            isClicked=resultWithoutMinus //result became : 123
            isMinusPrinted=false
        }

}//to here

    }

    viewResult.setText(isClicked)
     }
</code>```

Body:
I need to add new button with functionality of +/-. If user clicks the button for the first time the value should return -> "-" (ex => -123), if the user clicks again value "-" should be removed (ex => 123). The functionality is similar as +/- button in the calculator.

Here is my code

Activity.kt file

 package com.tripbegins.calculator
 import android.support.v7.app.AppCompatActivity
 import android.os.Bundle
 import android.view.View
 import android.widget.Button
 import com.tripbegins.calculator.R.id.*
 import kotlinx.android.synthetic.main.activity_main.*

 class MainActivity : AppCompatActivity() {

 override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

var emptyText = true
fun numberEvents(view: View) {
var checkButton:Boolean = false
if(emptyText){
    viewResult.setText("")
}
emptyText = false

var button = view as Button
var isClicked = viewResult.text.toString()
when (button.id) {
    buttonOne.id -> isClicked += "1"
    buttonTwo.id -> isClicked += "2"
    buttonThree.id -> isClicked += "3"
    dotButton.id-> isClicked+="."
}

viewResult.setText(isClicked)
 }

var operation ="+"
var oldValues:String? = null

fun mathOperation(view: View){
var mathButton = view as Button
var isClicked = viewResult.text.toString()

when(mathButton.id){
    plusButton.id-> {
        operation = "+"
    }
    minusButton.id->{
        operation="-"
    }
    mulButton.id->{
        operation="*"
    }

}
oldValues = viewResult.text.toString()
emptyText = true
 }

 fun Calculate(view: View){

var newValues = viewResult.text.toString()
var calulateButton:Double? = null
when(operation){
    "+"-> { calulateButton = oldValues!!.toDouble() +
newValues.toDouble() }
    "-"-> { calulateButton = oldValues!!.toDouble() -
newValues.toDouble() }
    "*"-> { calulateButton = oldValues!!.toDouble() *
newValues.toDouble() }

}
viewResult.setText(calulateButton.toString())
emptyText=true
 }
 fun clearFunction(view: View){
viewResult.setText("")
 }
 }

activity.xml file

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.tripbegins.calculator.MainActivity">

<EditText
android:id="@+id/viewResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="42dp"
android:ems="10"
android:gravity="bottom|right"
android:inputType="textPersonName"
android:text="0"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="76dp"
android:onClick="numberEvents"
android:text="2"
app:layout_constraintStart_toEndOf="@+id/buttonOne"
app:layout_constraintTop_toBottomOf="@+id/viewResult" />

<Button
android:id="@+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="38dp"
android:onClick="mathOperation"
android:text="+"
app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="12dp"
android:layout_marginTop="33dp"
android:onClick="mathOperation"
android:text="-"
app:layout_constraintStart_toEndOf="@+id/plusButton"
app:layout_constraintTop_toBottomOf="@+id/buttonTwo" />

<Button
android:id="@+id/mulButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="26dp"
android:onClick="mathOperation"
android:text="*"
app:layout_constraintBaseline_toBaselineOf="@+id/minusButton"
app:layout_constraintStart_toEndOf="@+id/minusButton" />

<Button
android:id="@+id/calButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:onClick="Calculate"
android:text="Calculate"
app:layout_constraintStart_toStartOf="@+id/minusButton"
app:layout_constraintTop_toBottomOf="@+id/minusButton" />

<Button
android:id="@+id/buttonThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="26dp"
android:onClick="numberEvents"
android:text="3"
app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
app:layout_constraintStart_toEndOf="@+id/buttonTwo" />

<Button
android:id="@+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="34dp"
android:onClick="numberEvents"
android:text="1"
app:layout_constraintBaseline_toBaselineOf="@+id/buttonTwo"
app:layout_constraintStart_toStartOf="parent" />

<Button
android:id="@+id/dotButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="22dp"
android:onClick="numberEvents"
android:text="."
app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
app:layout_constraintEnd_toStartOf="@+id/calButton" />

<Button
android:id="@+id/clearButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="11dp"
android:onClick="clearFunction"
android:text="Clear"
app:layout_constraintBaseline_toBaselineOf="@+id/calButton"
app:layout_constraintStart_toEndOf="@+id/calButton" />
</android.support.constraint.ConstraintLayout>

Updated Activity.kt file
I have updated the code for the =/-. Added the var outside the function

  var emptyText = true
  var isMinusPrinted=false
  fun numberEvents(view: View)

**Current result**

If button clicked for the first time value => -123
If button clicked for the second time value => -123
If button clicked for the third time value => --123

**Expected Result**
If button clicked for the first time value => -123
If button clicked for the second time value => 123
If button clicked for the third time value => -123

Updated activity.kt file

package com.tripbegins.calculator
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import com.tripbegins.calculator.R.id.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    var emptyText = true
    var isMinusPrinted=false
    fun numberEvents(view: View) {
        if(emptyText){
            viewResult.setText("")
        }
        emptyText = false
        var button = view as Button
        var plusMinusCheck =""
        var isClicked = viewResult.text.toString()

        when (button.id) {

            buttonOne.id -> isClicked += "1"
            buttonTwo.id -> isClicked += "2"
            buttonThree.id -> isClicked += "3"

            dotButton.id -> {
                isClicked += "."
                dotButton.isClickable = false //**add this line here**
            }
            plusMinusBtn.id->{

                var resultWithoutMinus=isClicked//ex: 123
                if(!isMinusPrinted){

                    isClicked = "-" + resultWithoutMinus//this line for
    example give result like: -123
                    isMinusPrinted=true
                }
                else{
                    isClicked=resultWithoutMinus //result became : 123
                    isMinusPrinted=false
                }

            }

        }

            viewResult.setText(isClicked)
    }

    var operation ="+"
    var oldValues:String? = null

    fun mathOperation(view: View){
        var mathButton = view as Button
        var isClicked = viewResult.text.toString()

        when(mathButton.id){
            plusButton.id-> {
                operation = "+"
            }
            minusButton.id->{
                operation="-"
            }
            mulButton.id->{
                operation="*"
            }

        }
        oldValues = viewResult.text.toString()
        emptyText = true
        dotButton.isClickable=true//**add this line here**

    }

    fun Calculate(view: View){

        var newValues = viewResult.text.toString()
        var calulateButton:Double? = null

        when(operation){
            "+"-> { calulateButton = oldValues!!.toDouble() +
newValues.toDouble() }
            "-"-> { calulateButton = oldValues!!.toDouble() -
newValues.toDouble() }
            "*"-> { calulateButton = oldValues!!.toDouble() *
newValues.toDouble() }

        }
        viewResult.setText(calulateButton.toString())
        emptyText=true
        dotButton.isClickable=true //**add this line here**
    }
    fun clearFunction(view: View){
        viewResult.setText("")
        dotButton.isClickable=true //**add this line here**
    }
}

Updated the xml file for the button -> +/-

<Button
android:id="@+id/plusMinusBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="52dp"
android:layout_marginStart="38dp"
android:onClick="numberEvents"
android:text="+/-"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />

Body:
Edit:

    var emptyText = true
    var isMinusPrinted=false//add this line here
    fun numberEvents(view: View) {
    var checkButton:Boolean = false
    if(emptyText){
        viewResult.setText("")
    }
    emptyText = false

    var button = view as Button
    var isClicked = viewResult.text.toString()
    when (button.id) {
        buttonOne.id -> isClicked += "1"
        buttonTwo.id -> isClicked += "2"
        buttonThree.id -> isClicked += "3"
        dotButton.id-> isClicked+="."
        plusMinusBtn.id->{//add this block of code from here

        var resultWithoutMinus=Math.abs(isClicked.toInt()) //ex: 123

        if(!isMinusPrinted){

            isClicked = "-" + resultWithoutMinus//this line for example give result like: -123
            isMinusPrinted=true
        }
        else{
            isClicked=resultWithoutMinus //result became : 123
            isMinusPrinted=false
        }

}//to here

    }

    viewResult.setText(isClicked)
     }


问:
Drop down menu with input box
How can I make a drop down option with a input box using css and html like the picture below?

答:
I guess then you need a combo box. A simple way to implement it is with the datalist like this:

    <!DOCTYPE html>

    <input type="text" name="example" list="exampleList">
    <datalist id="exampleList">
        <option value="017">
        <option value="018">
        <option value="019">
    </datalist>

    ```

Title: Drop down menu with input box

Body:
I guess then you need a combo box. A simple way to implement it is with the datalist like this:

    <!DOCTYPE html>
    <html>
    <body>

    <input type="text" name="example" list="exampleList">
    <datalist id="exampleList">
        <option value="017">
        <option value="018">
        <option value="019">
    </datalist>

    </body>
    </html>


问:
How to retrieve the most recent photo from Camera Roll on iOS?
I'm having a hard figuring out how to programmatically retrieve the most recent photo in the camera roll without user intervention. To be clear, I do not want to use an Image Picker, I want the app to automatically grab the newest photo when the app opens.

I know this is possible because Ive seen a similar app do it, but I cant seem to find any info on it.

答:
Using Photos Library ( Objective-C )</p>

```<code>    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];

PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
if (assetsFetchResult.count>0) {
    PHAsset *asset = [assetsFetchResult objectAtIndex:0];

    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat dimension = 55.0f; // set your required size
    CGSize size = CGSizeMake(dimension*scale, dimension*scale);

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:size
                                              contentMode:PHImageContentModeAspectFit
                                                  options:nil
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                // do your thing with the image
                                            }
     ];
}
</code>```

Body:
Using Photos Library ( Objective-C )

    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];

PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:fetchOptions];
if (assetsFetchResult.count>0) {
    PHAsset *asset = [assetsFetchResult objectAtIndex:0];

    CGFloat scale = [UIScreen mainScreen].scale;
    CGFloat dimension = 55.0f; // set your required size
    CGSize size = CGSizeMake(dimension*scale, dimension*scale);

    [[PHImageManager defaultManager] requestImageForAsset:asset
                                               targetSize:size
                                              contentMode:PHImageContentModeAspectFit
                                                  options:nil
                                            resultHandler:^(UIImage *result, NSDictionary *info) {
                                                // do your thing with the image
                                            }
     ];
}