问:
Centered square chessboard using GridView
It seems like this has been asked a lot of times and I've read so many questions and their answers but none of them would fit to my problem:

My situation:

In my Activity, below a bunch of other stuff, you should see a chessboard. For small/short smartphones it's possible that the remaining space for the chessboard (which is a square) is not too much. Therefore I cannot simply say that the size of the chessboard is determined by the remaining width. If the remaining height is lower then the height determines the size.

The number of squares varies within the game. The chessboard will always be a square but it's dimension varies from 3x3 to 8x8.

I want my chessboard, which is implemented by using a GridView, to have a black border (circa 2pd).

It would be nice if the squares of the chessboard could be real squares. But I want the size of the chessboard to be fix even if the number of columns varies. Therefore I cannot have a constant border thickness and squares that are real squares since the size of the chessboard (minus the border thickness) is not guaranteed to be divisible by the number of columns.

I see two possible solutions to handle this but I can't get them working:

To have a nice square chessboard, I use the follwing xml:

<GridView
    android:id="@+id/chessboard_gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="2dp"
    android:layout_margin="10dp"
    android:background="@color/black"
    android:layout_gravity="center"
    android:gravity="center" >
</GridView>

and in onCreate() the following code in my activity:

```<code>gridView.setNumColumns(board.getColumns());
gridView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){

    @Override
    public void onGlobalLayout() {

        int size = Math.min(gridView.getWidth(), gridView.getHeight());

        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.width = size;
        params.height = size;
        gridView.setLayoutParams(params);

        gridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }});
</code>```

And in order to have perfect squares as squares I found the following solution for ImageViews which are used by my custom Adapter:

```<code>public class SquareView extends ImageView{

    public SquareView(Context context){
        super(context);
    }

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }
}
</code>```

But if I have a look at the result I can see that the border line thickness varies because the chessboard with is not divisible by the number of columns:

I'm OK with that IF I somehow manage to have all squares centered in the GridView. Then the border is thicker than 2dp and it's possible that one side is one pixel thicker than the other, but I don't care.

QUESTION: How can I center the squares such that the border thickness does not vary to that extend?

Another approach would be to have a nice border of exactly 2 dp but the squares wouldn't really be squares. The remaining space that makes the border thicker on the right and at the bottom could be more or less equally distributed over the squares. For example: if there are 3 remaining pixels, make the 2., 4. and 6. column each one pixel wider and the 2., 4. and 6. row higher.

QUESTION: How can I use all the GridView space perfectly for my squares even if that means that my squares aren't real squares anymore but some are slightly wider or higher?

I had thought that the GridView does stretch them automatically but if I use a simple ImageView and not my SquareView for the squares I have a black chessboard if I do not set the size of each square on my own. If I do set a square size for the squares manually I get different wrong results for all the stretchModes.

答:
I asked this question quite a while ago and decided to finally write how I solved my problem then. In the end I didn't care that the chessboard size might vary when changing the number of rows and columns. Please note that there might be a more up-to-date answer. This is a solution that worked for me in 2015.

My GridView:

```<code><GridView
    android:id="@+id/chessboard_gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@color/black"
    android:gravity="center"
    android:padding="2dp">
</GridView>
</code>```

initialized in an Activity's onCreate:

```<code>this.gridView = (GridView) findViewById(R.id.chessboard_gridview);
</code>```

The same Activity uses a custom Adapter for the chessboard:

```<code>ChessboardViewAdapter adapter = new ChessboardViewAdapter(numRows, numCols, ...);
gridView.setAdapter(adapter);
</code>```

The ChessboardViewAdapter then (among other things) determines the proper size for the squares. Note that the SquareView is a custom class that does not override onMeasure anymore like in the code from my original question.

```<code>public class ChessboardViewAdapter extends BaseAdapter{
    ...
    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        View view = convertView;
        if(view == null){
            view = new SquareView(context);
        }

        // Adjust each square's size to look like a square
        int parentPadding = 2 * parent.getPaddingTop(); // equal paddings
        int newSize = (parent.getWidth() - parentPadding) / this.columns;
        view.setLayoutParams(new GridView.LayoutParams(newSize, newSize));
        view.setPadding(10, 10, 10, 10); // hard coded offsets for the black border
        ...
    }
}
</code>```

Body:
It seems like this has been asked a lot of times and I've read so many questions and their answers but none of them would fit to my problem:

My situation:

In my Activity, below a bunch of other stuff, you should see a chessboard. For small/short smartphones it's possible that the remaining space for the chessboard (which is a square) is not too much. Therefore I cannot simply say that the size of the chessboard is determined by the remaining width. If the remaining height is lower then the height determines the size.

The number of squares varies within the game. The chessboard will always be a square but it's dimension varies from 3x3 to 8x8.

I want my chessboard, which is implemented by using a GridView, to have a black border (circa 2pd).

It would be nice if the squares of the chessboard could be real squares. But I want the size of the chessboard to be fix even if the number of columns varies. Therefore I cannot have a constant border thickness and squares that are real squares since the size of the chessboard (minus the border thickness) is not guaranteed to be divisible by the number of columns.

I see two possible solutions to handle this but I can't get them working:

To have a nice square chessboard, I use the follwing xml:

<GridView
    android:id="@+id/chessboard_gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="2dp"
    android:layout_margin="10dp"
    android:background="@color/black"
    android:layout_gravity="center"
    android:gravity="center" >
</GridView>

and in onCreate() the following code in my activity:

gridView.setNumColumns(board.getColumns());
gridView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){

    @Override
    public void onGlobalLayout() {

        int size = Math.min(gridView.getWidth(), gridView.getHeight());

        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.width = size;
        params.height = size;
        gridView.setLayoutParams(params);

        gridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }});

And in order to have perfect squares as squares I found the following solution for ImageViews which are used by my custom Adapter:

public class SquareView extends ImageView{

    public SquareView(Context context){
        super(context);
    }

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

But if I have a look at the result I can see that the border line thickness varies because the chessboard with is not divisible by the number of columns:

I'm OK with that IF I somehow manage to have all squares centered in the GridView. Then the border is thicker than 2dp and it's possible that one side is one pixel thicker than the other, but I don't care.

QUESTION: How can I center the squares such that the border thickness does not vary to that extend?

Another approach would be to have a nice border of exactly 2 dp but the squares wouldn't really be squares. The remaining space that makes the border thicker on the right and at the bottom could be more or less equally distributed over the squares. For example: if there are 3 remaining pixels, make the 2., 4. and 6. column each one pixel wider and the 2., 4. and 6. row higher.

QUESTION: How can I use all the GridView space perfectly for my squares even if that means that my squares aren't real squares anymore but some are slightly wider or higher?

I had thought that the GridView does stretch them automatically but if I use a simple ImageView and not my SquareView for the squares I have a black chessboard if I do not set the size of each square on my own. If I do set a square size for the squares manually I get different wrong results for all the stretchModes.

Body:
I asked this question quite a while ago and decided to finally write how I solved my problem then. In the end I didn't care that the chessboard size might vary when changing the number of rows and columns. Please note that there might be a more up-to-date answer. This is a solution that worked for me in 2015.

My GridView:

<GridView
    android:id="@+id/chessboard_gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:background="@color/black"
    android:gravity="center"
    android:padding="2dp">
</GridView>

initialized in an Activity's onCreate:

this.gridView = (GridView) findViewById(R.id.chessboard_gridview);

The same Activity uses a custom Adapter for the chessboard:

ChessboardViewAdapter adapter = new ChessboardViewAdapter(numRows, numCols, ...);
gridView.setAdapter(adapter);

The ChessboardViewAdapter then (among other things) determines the proper size for the squares. Note that the SquareView is a custom class that does not override onMeasure anymore like in the code from my original question.

public class ChessboardViewAdapter extends BaseAdapter{
    ...
    @Override
    public View getView(int position, View convertView, ViewGroup parent){

        View view = convertView;
        if(view == null){
            view = new SquareView(context);
        }

        // Adjust each square's size to look like a square
        int parentPadding = 2 * parent.getPaddingTop(); // equal paddings
        int newSize = (parent.getWidth() - parentPadding) / this.columns;
        view.setLayoutParams(new GridView.LayoutParams(newSize, newSize));
        view.setPadding(10, 10, 10, 10); // hard coded offsets for the black border
        ...
    }
}


来源: stackexchange

问:
Disable selecting text in a TextBox
I have a textbox with the following (important) properties:

```<code>this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.license.ShortcutsEnabled = false;
</code>```

It looks like this:

How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?

答:
If you are using XAML / WPF you should use a TextBlock instead of a TextBox.

ONLY IF YOU USE A TEXTBOX AS A DISPLAY AND NOT FOR INPUT
- as TextBlock makes it seem as if the text is "engraved" onto the form itself, and not within a textbox. To get a Border around the TextBlock (if you wish), you can either do it :

In XAML such as :

```<code><Border BorderThickness="1" BorderBrush="Gray">
    <TextBlock Background="White" Text="Your Own TextBlock"/>
</Border>
</code>```

Or dynamically in C# Code:

```<code>//Create a Border object
Border border = new Border();
border.BorderThickness = new Thickness(1);
border.BorderBrush = Brushes.Black;

//Create the TextBlock object
TextBlock tb = new TextBlock();
tb.Background = Brushes.White;
tb.Text = "Your Own TextBlock";

//Make the text block a child to the border
border.Child = tb;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Disable selecting text in a TextBox

Body:
I have a textbox with the following (important) properties:

this.license.Multiline = true;
this.license.ReadOnly = true;
this.license.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.license.ShortcutsEnabled = false;

It looks like this:

How can I disable the user to highlight text in this textbox (I do not want to disable the textbox completely)?

Body:
If you are using XAML / WPF you should use a TextBlock instead of a TextBox.

ONLY IF YOU USE A TEXTBOX AS A DISPLAY AND NOT FOR INPUT
- as TextBlock makes it seem as if the text is "engraved" onto the form itself, and not within a textbox. To get a Border around the TextBlock (if you wish), you can either do it :

In XAML such as :

<Border BorderThickness="1" BorderBrush="Gray">
    <TextBlock Background="White" Text="Your Own TextBlock"/>
</Border>

Or dynamically in C# Code:

//Create a Border object
Border border = new Border();
border.BorderThickness = new Thickness(1);
border.BorderBrush = Brushes.Black;

//Create the TextBlock object
TextBlock tb = new TextBlock();
tb.Background = Brushes.White;
tb.Text = "Your Own TextBlock";

//Make the text block a child to the border
border.Child = tb;


问:
How can I speed up or slow down a background music track with iPhone SDK?
Is there an easy way to control the playback speed/tempo of a sound file loop played using Audio Queue Services?  For example, if a game is playing background music, I want to make the BGM speed up as time runs out, but without changing the pitch of the music.  Thx!</p>

答:
There's no trivial way to do this that I know of. On the Mac, you'd presumably use Audio Units to do this, but I think the support for those is limited on the iPhone SDK.

You can do some processing during your AudioQueue playback callback, between AudioFileReadPackets() and AudioQueueEnqueueBuffer() but I think speed-shifting without changing the tone will require rather a lot of CPU time.

It'd probably be easier to have more than one recording of the music, and switch files during a silent passage of the music.

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Bessey


问:
How do I update records in sql using other records as values?
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2
</code>```

After:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2
</code>```

Self-taught, relatively new to SQL.  Patience is appreciated.

答:
You could use an update with inner join on min(TxID)  group by RecordID</p>

```<code>  update my_table t1
  inner join
  (
      select RecordID, ColumnA, ColumnX, ColumnY
      from my_table
      where (TxID, RecordID ) in (
        select min(TxID), RecordID
      from my_table
      group by RecordID)
  ) ttt on ttt.RecordID = t1.RecordID
  set  t1.ColumnX = ttt.ColumnX
</code>```

Body:
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2

After:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2

Self-taught, relatively new to SQL.  Patience is appreciated.

Body:
You could use an update with inner join on min(TxID)  group by RecordID

  update my_table t1
  inner join
  (
      select RecordID, ColumnA, ColumnX, ColumnY
      from my_table
      where (TxID, RecordID ) in (
        select min(TxID), RecordID
      from my_table
      group by RecordID)
  ) ttt on ttt.RecordID = t1.RecordID
  set  t1.ColumnX = ttt.ColumnX


问:
ValueError: Input 0 is incompatible with layer conv_1: expected ndim=3, found ndim=4
I am trying to make a variational auto encoder to learn to encode DNA sequences, but am getting an unexpected error.

My data is an array of one-hot arrays.

The issue I'm getting is a Value Error. It's telling me that I have a four dimensional input, when my input is clearly three-dimensional (100, 4008, 4).

In fact, when I print out the seq layer, it says that it's shape is (?, 100, 4008, 4).

When I take out a dimension, it then gives me an error for being two dimensional.

Any help will be highly appreciated!

Code is:

from keras.layers import Input
from keras.layers.convolutional import Conv1D
from keras.layers.core import Dense, Activation, Flatten, RepeatVector, Lambda
from keras import backend as K
from keras.layers.wrappers import TimeDistributed
from keras.layers.recurrent import GRU
from keras.models import Model
from keras import objectives

from one_hot import dna_sequence_to_one_hot

from random import shuffle
import numpy as np

# take FASTA file and convert into array of vectors
seqs = [line.rstrip() for line in open("/home/ubuntu/sequences.fa", "r").readlines() if line[0] != ">"]
seqs = [dna_sequence_to_one_hot(s) for s in seqs]
seqs = np.array(seqs)

# first random thousand are training, next thousand are validation
test_data = seqs[:1000]
validation_data = seqs[1000:2000]

latent_rep_size = 292
batch_size = 100
epsilon_std = 0.01
max_length = len(seqs[0])
charset_length = 4
epochs = 100

def sampling(args):
    z_mean_, z_log_var_ = args
    # batch_size = K.shape(z_mean_)[0]
    epsilon = K.random_normal_variable((batch_size, latent_rep_size), 0., epsilon_std)
    return z_mean_ + K.exp(z_log_var_ / 2) * epsilon

# loss function
def vae_loss(x, x_decoded_mean):
    x = K.flatten(x)
    x_decoded_mean = K.flatten(x_decoded_mean)
    xent_loss = max_length * objectives.categorical_crossentropy(x, x_decoded_mean)
    kl_loss = - 0.5 * K.mean(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis = -1)
    return xent_loss + kl_loss

# Encoder
seq = Input(shape=(100, 4008, 4), name='one_hot_sequence')
e = Conv1D(9, 9, activation = 'relu', name='conv_1')(seq)
e = Conv1D(9, 9, activation = 'relu', name='conv_2')(e)
e = Conv1D(9, 9, activation = 'relu', name='conv_3')(e)
e = Conv1D(10, 11, activation = 'relu', name='conv_4')(e)
e = Flatten(name='flatten_1')(e)
e = Dense(435, activation = 'relu', name='dense_1')(e)
z_mean = Dense(latent_rep_size, name='z_mean', activation = 'linear')(e)
z_log_var = Dense(latent_rep_size, name='z_log_var', activation = 'linear')(e)
z = Lambda(sampling, output_shape=(latent_rep_size,), name='lambda')([z_mean, z_log_var])

encoder = Model(seq, z)

# Decoder
d = Dense(latent_rep_size, name='latent_input', activation = 'relu')(z)
d = RepeatVector(max_length, name='repeat_vector')(d)
d = GRU(501, return_sequences = True, name='gru_1')(d)
d = GRU(501, return_sequences = True, name='gru_2')(d)
d = GRU(501, return_sequences = True, name='gru_3')(d)
d = TimeDistributed(Dense(charset_length, activation='softmax'), name='decoded_mean')(d)

# create the model, compile it, and fit it
vae = Model(seq, d)
vae.compile(optimizer='Adam', loss=vae_loss, metrics=['accuracy'])
vae.fit(x=test_data, y=test_data, epochs=epochs, batch_size=batch_size, validation_data=validation_data)
```

答:
Try to put the input to the network like this:
 Input(shape=(None, 4)

Generally, it's for the case you don't know the length of your sequence, but I had the same problem and for some reason, it was solved when I did it

Hope it works!

ContentLicense: CC BY-SA 4.0


问:
Error:Execution failed for task ':app:packageDebug'. > !zip.isFile()
@UPDATE

Thank you very much. Now at least there are no errors. But it's still a far cry from how it worked before - how it should work. Now, the database looks ... strange. I think that something is still wrong with this gradle.

It should not look like. According to the java code in the database will be user and its data (name, email, date of account creation, id avatar)

In the application at the site next to the avatar you should display the name. Unfortunately, as you can see nothing happens. There is nothing wrong with the code because it previously worked. :(

I ruined my project! I tried to fix it but now it's worse than it was.

The project is chat client through Firebase.

It started when I deleted my base. I had too many test users, messages I wanted to clear it. Since then, it gets a million error notifications - trying to fix one thing leads to even worse errors.

I tried to connect to the application completely different base, I tried to re-arrange a few things. Nothing helps.

At first I thought that the problem is with wrong compile 'com.google.firebase:firebase-database:9.8.0' number. Then I received

E/FirebaseApp: Firebase API initialization failure.

I try to fix it. Application was started and in the database was very strange things.

Now i get

Error:Execution failed for task ':app:packageDebug'.> !zip.isFile()

build.gradle (project)

```<code>buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'

    }
}
</code>```

build.gradle (module:app)

```<code>apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.rachel.komunikator"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.google.firebase:firebase-database:9.8.0'
    compile 'com.google.firebase:firebase-auth:9.8.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    testCompile 'junit:junit:4.12'
}
</code>```

Google Play Services
on my emulator

Im using: Android Studio 2.2.3 and Nexus 5X Emulator

@UPDATE

W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. E/FirebaseApp: Firebase API

initialization failure. D/FirebaseApp:

com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.

all logs:

```<code>W/System: ClassLoader referenced unknown path: /data/app/com.example.rachel.komunikator-2/lib/x86

          [ 02-02 20:56:04.988  1566: 1589 D/         ]
          HostConnection::get() New Host Connection established 0x8cf20100, tid 1589
I/InstantRun: Instant Run Runtime started. Android package is com.example.rachel.komunikator, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.rachel.komunikator-2/lib/x86
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/x86
E/FirebaseApp: Firebase API initialization failure.
               java.lang.reflect.InvocationTargetException
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                Caused by: java.lang.IllegalAccessError: Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg' (declaration of 'com.google.firebase.iid.zzg' appears in /data/data/com.example.rachel.komunikator/files/instant-run/dex/slice-com.google.firebase-firebase-iid-9.0.0_8eee9db5e99a0da2dcdc7b52647c81db3aed29e6-classes.dex)
                   at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                   at com.google.firebase.iid.zzg.<init>(Unknown Source)
                   at com.google.firebase.iid.zzg.<init>(Unknown Source)
                   at com.google.firebase.iid.zzd.zzb(Unknown Source)
                   at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
E/FirebaseApp: Firebase API initialization failure.
               java.lang.reflect.InvocationTargetException
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                Caused by: java.lang.NoSuchMethodError: No static method zzz(Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzaa; or its super classes (declaration of 'com.google.android.gms.common.internal.zzaa' appears in /data/data/com.example.rachel.komunikator/files/instant-run/dex/slice-com.google.android.gms-play-services-basement-9.8.0_b60271da061b8a83af31355011409573bfa72cef-classes.dex)
                   at com.google.android.gms.measurement.internal.zzx.zzbd(Unknown Source)
                   at com.google.android.gms.measurement.AppMeasurement.getInstance(Unknown Source)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
Regarding this:

Error:Execution failed for task ':app:packageDebug'.> !zip.isFile()

I solved it by deleting the build project and running again.

Hope this helps.

Body:
@UPDATE

Thank you very much. Now at least there are no errors. But it's still a far cry from how it worked before - how it should work. Now, the database looks ... strange. I think that something is still wrong with this gradle.

It should not look like. According to the java code in the database will be user and its data (name, email, date of account creation, id avatar)

In the application at the site next to the avatar you should display the name. Unfortunately, as you can see nothing happens. There is nothing wrong with the code because it previously worked. :(

I ruined my project! I tried to fix it but now it's worse than it was.

The project is chat client through Firebase.

It started when I deleted my base. I had too many test users, messages I wanted to clear it. Since then, it gets a million error notifications - trying to fix one thing leads to even worse errors.

I tried to connect to the application completely different base, I tried to re-arrange a few things. Nothing helps.

At first I thought that the problem is with wrong compile 'com.google.firebase:firebase-database:9.8.0' number. Then I received

E/FirebaseApp: Firebase API initialization failure.

I try to fix it. Application was started and in the database was very strange things.

Now i get

Error:Execution failed for task ':app:packageDebug'.> !zip.isFile()

build.gradle (project)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.0.0'

    }
}

build.gradle (module:app)

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.rachel.komunikator"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })

    compile 'com.android.support:appcompat-v7:25.1.0'
    compile 'com.google.firebase:firebase-database:9.8.0'
    compile 'com.google.firebase:firebase-auth:9.8.0'
    compile 'com.android.support:recyclerview-v7:25.1.0'
    testCompile 'junit:junit:4.12'
}

Google Play Services
on my emulator

Im using: Android Studio 2.2.3 and Nexus 5X Emulator

@UPDATE

W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found. E/FirebaseApp: Firebase API

initialization failure. D/FirebaseApp:

com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.

all logs:

W/System: ClassLoader referenced unknown path: /data/app/com.example.rachel.komunikator-2/lib/x86

          [ 02-02 20:56:04.988  1566: 1589 D/         ]
          HostConnection::get() New Host Connection established 0x8cf20100, tid 1589
I/InstantRun: Instant Run Runtime started. Android package is com.example.rachel.komunikator, real application class is null.
W/System: ClassLoader referenced unknown path: /data/app/com.example.rachel.komunikator-2/lib/x86
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
W/System: ClassLoader referenced unknown path: /system/priv-app/PrebuiltGmsCore/lib/x86
E/FirebaseApp: Firebase API initialization failure.
               java.lang.reflect.InvocationTargetException
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                Caused by: java.lang.IllegalAccessError: Method 'void android.support.v4.content.ContextCompat.<init>()' is inaccessible to class 'com.google.firebase.iid.zzg' (declaration of 'com.google.firebase.iid.zzg' appears in /data/data/com.example.rachel.komunikator/files/instant-run/dex/slice-com.google.firebase-firebase-iid-9.0.0_8eee9db5e99a0da2dcdc7b52647c81db3aed29e6-classes.dex)
                   at com.google.firebase.iid.zzg.zzeC(Unknown Source)
                   at com.google.firebase.iid.zzg.<init>(Unknown Source)
                   at com.google.firebase.iid.zzg.<init>(Unknown Source)
                   at com.google.firebase.iid.zzd.zzb(Unknown Source)
                   at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
D/FirebaseApp: com.google.firebase.crash.FirebaseCrash is not linked. Skipping initialization.
E/FirebaseApp: Firebase API initialization failure.
               java.lang.reflect.InvocationTargetException
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                Caused by: java.lang.NoSuchMethodError: No static method zzz(Ljava/lang/Object;)Ljava/lang/Object; in class Lcom/google/android/gms/common/internal/zzaa; or its super classes (declaration of 'com.google.android.gms.common.internal.zzaa' appears in /data/data/com.example.rachel.komunikator/files/instant-run/dex/slice-com.google.android.gms-play-services-basement-9.8.0_b60271da061b8a83af31355011409573bfa72cef-classes.dex)
                   at com.google.android.gms.measurement.internal.zzx.zzbd(Unknown Source)
                   at com.google.android.gms.measurement.AppMeasurement.getInstance(Unknown Source)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.google.firebase.FirebaseApp.zza(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.FirebaseApp.initializeApp(Unknown Source)
                   at com.google.firebase.provider.FirebaseInitProvider.onCreate(Unknown Source)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
                   at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
                   at com.google.firebase.provider.FirebaseInitProvider.attachInfo(Unknown Source)
                   at android.app.ActivityThread.installProvider(ActivityThread.java:5853)
                   at android.app.ActivityThread.installContentProviders(ActivityThread.java:5445)
                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5384)
                   at android.app.ActivityThread.-wrap2(ActivityThread.java)
                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
                   at android.os.Handler.dispatchMessage(Handler.java:102)
                   at android.os.Looper.loop(Looper.java:154)
                   at android.app.ActivityThread.main(ActivityThread.java:6119)
                   at java.lang.reflect.Method.invoke(Native Method)
                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


问:
Cannot animate UIImageview
My issue is that when I press the button that runs the dealToPlayer function(), everything acts as if a card has been dealt, updates total value of cards dealt, but it does not show any animation of the card being dealt or placed. Why might this be? I am not using auto layout for this scene at all.</p>

```<code>  func dealToPlayer() {

    let index = Int(arc4random_uniform(UInt32(deckCards.count)))
    let drawnCard = deckCards.remove(at: index)
    randomCards.append(drawnCard)

    randomCard = randomCards[3 + cardSelect]

    image = UIImageView(frame: CGRect(x: self.deckLocation.x, y: self.deckLocation.y, width: self.width, height: self.height))
    image.image = mapping[randomCard]

    cardsOut = cardsOut + 1
    print("cards out is currently: \(cardsOut)")
    cardSelect = cardSelect + 1

    UIView.animate(withDuration: 0.5, delay: 1.5, options: [], animations: {
        self.image.frame = CGRect(x: self.cardTwoLocation.x - (self.cardsOut * self.thirdWidth), y: self.cardTwoLocation.y, width: self.width, height: self.height)
        }, completion: nil)

    checkPlayerValue()

}
</code>```

答:
First, make sure your image view is added to your view controller.

Second, make sure your animation is called by putting a break point.

Third, print out the location and make sure the new x and y are valid, and they are different than the previous x and y.

Here is a sample duplicate of your code an it works fine

```<code>image = UIImageView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
image.backgroundColor = .red

self.view.addSubview(image)

UIView.animate(withDuration: 0.5, delay: 1.5, options: [], animations: {
    self.image.frame = CGRect(x: 200, y: 200, width: 100, height: 100)
}, completion: nil)
</code>```

Title: Cannot animate UIImageview

Body:
My issue is that when I press the button that runs the dealToPlayer function(), everything acts as if a card has been dealt, updates total value of cards dealt, but it does not show any animation of the card being dealt or placed. Why might this be? I am not using auto layout for this scene at all.

  func dealToPlayer() {

    let index = Int(arc4random_uniform(UInt32(deckCards.count)))
    let drawnCard = deckCards.remove(at: index)
    randomCards.append(drawnCard)

    randomCard = randomCards[3 + cardSelect]

    image = UIImageView(frame: CGRect(x: self.deckLocation.x, y: self.deckLocation.y, width: self.width, height: self.height))
    image.image = mapping[randomCard]

    cardsOut = cardsOut + 1
    print("cards out is currently: \(cardsOut)")
    cardSelect = cardSelect + 1

    UIView.animate(withDuration: 0.5, delay: 1.5, options: [], animations: {
        self.image.frame = CGRect(x: self.cardTwoLocation.x - (self.cardsOut * self.thirdWidth), y: self.cardTwoLocation.y, width: self.width, height: self.height)
        }, completion: nil)

    checkPlayerValue()

}

Body:
First, make sure your image view is added to your view controller.

Second, make sure your animation is called by putting a break point.

Third, print out the location and make sure the new x and y are valid, and they are different than the previous x and y.

Here is a sample duplicate of your code an it works fine

image = UIImageView(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
image.backgroundColor = .red

self.view.addSubview(image)

UIView.animate(withDuration: 0.5, delay: 1.5, options: [], animations: {
    self.image.frame = CGRect(x: 200, y: 200, width: 100, height: 100)
}, completion: nil)


问:
How to resend dropped emails in mailgun
How to resend dropped emails in mailgun?

I am using mailgun to send mails in my application,but some mails are dropped. Is there any method to resend the dropped mails?

答:
You can resend a message with Mailgun via their control panel and through their API. But it's only available for messages that have an associated event-type of "delivered" or "permanent fail" and are also not more than your domain's message retention period (3 days for most, I think).

API:

See their docs:

```<code>curl -s --user 'api:YOUR_API_KEY' \
    https://se.api.mailgun.net/v3/domains/YOUR_DOMAIN_NAME/messages/STORAGE_URL \
    -F to='bob@example.com'
</code>```

Control Panel:

The Logs page allows for the resending of individual messages directly within the UI. Simply login to your Mailgun account and go to the Logs tab. Click the dropdown menu cog of any qualifying message and you'll see an option in the menu called "Resend Message"

Clicking that will cause a little popup to appear where you can enter a single recipient address.

Title: How to resend dropped emails in mailgun

Body:
You can resend a message with Mailgun via their control panel and through their API. But it's only available for messages that have an associated event-type of "delivered" or "permanent fail" and are also not more than your domain's message retention period (3 days for most, I think).

API:

See their docs:

curl -s --user 'api:YOUR_API_KEY' \
    https://se.api.mailgun.net/v3/domains/YOUR_DOMAIN_NAME/messages/STORAGE_URL \
    -F to='bob@example.com'

Control Panel:

The Logs page allows for the resending of individual messages directly within the UI. Simply login to your Mailgun account and go to the Logs tab. Click the dropdown menu cog of any qualifying message and you'll see an option in the menu called "Resend Message"

Clicking that will cause a little popup to appear where you can enter a single recipient address.


问:
c# syntax help, about generic programming
```<code> TEntity Single(Expression<Func<TEntity, bool>> predicate);
</code>```

Please explain the parameter.

答:
This is a expression used to specify any delegate function taking any "TEntity" (as defined in this instance by the collection you are calling it on) and returning a bool. In practice, the delegate is specified using a lambda function:

```<code>items.Single(i => i.Id == 1);
</code>```

In your example, the Single function is an extension method that is applied to a generic collection of TEntity (which I believe don't have any limitations - i.e. must just be objects). Therefore, the type of TEntity is inferred based on the collection that you are calling it on.

Body:
 TEntity Single(Expression<Func<TEntity, bool>> predicate);

Please explain the parameter.

Body:
This is a expression used to specify any delegate function taking any "TEntity" (as defined in this instance by the collection you are calling it on) and returning a bool. In practice, the delegate is specified using a lambda function:

items.Single(i => i.Id == 1);

In your example, the Single function is an extension method that is applied to a generic collection of TEntity (which I believe don't have any limitations - i.e. must just be objects). Therefore, the type of TEntity is inferred based on the collection that you are calling it on.


问:
An app which has complete control of the device
I would like to create an app which is preinstalled on a device and has complete control of it (no way to exit it), this is for devices handed out for a specific purpose. It will have some pages/navigation as well as the ability to run certain whitelisted apps.

Is there anything out there helping with this, or would this kind of an app have to be a custom build of Android? Thanks.

答: To have complete control over the device you would need a custom operating system. I don't think it is possible to do what you are asking for with an app</p>


问:
How to render woff fonts in PhantomJS 2.1+ or headless Chrome?
I'm using PhantomJS 2.1.1 on CentOS with the example script rasterize.js just to reproduce the screenshot problem, which is to take a screenshot of a simple web-font demo site:

http://castellsonclaret.com/public/external/georgiapro/demo.htm

It should render like so (as taken using the SaaS PhantomJSCloud service):

However, with PhantomJS 2.1.1 locally I get

First I increased the script timeout to 10s just to be sure that isn't the issue.

Next I thought the css or fonts were blocked somehow from downloading. When I use tcpflow (it's like wireshark) before running phantomjs scripts I can see that the above web page is downloading the .woff fonts. However, they are not being rendered in the screenshot I'm taking.

When I run the following before the phantomjs script

```<code>tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]'
</code>```

I can see the fonts are being downloaded. Real console output:

```<code>GET /public/external/georgiapro/demo.htm HTTP/1.1

GET /t/1.css?apiType=css&projectid=4a82c0c9-a48a-4ef5-97ae-de0d7e62c8d0 HTTP/1.1

GET /public/external/georgiapro/Fonts/a5d15255-f5b4-4cca-808f-211ec0f25ac8.woff HTTP/1.1

GET /public/external/georgiapro/Fonts/3859825b-bdc4-47f3-af3d-a2ef42d58cfb.woff HTTP/1.1

... [snip] ...

GET /public/external/georgiapro/Fonts/ab79a7ac-4aaf-4393-896b-feb6610c9528.woff HTTP/1.1
</code>```

I then thought that PhantomJS 2.x still doesn't support woff, but 1) it is supposed to be supported (see here), and 2) the SaaS PhantomJSCloud service can render them fine. Is there something more that is needed to be done to render web fonts?

Update: I've confirmed zlib is installed, and compiled PhantomJS 2.1.1 from source, but the results are still the same as above.

Update: Chrome has headless support, and that is the reason why on April 13 the maintainer of PhrantomJS has announced he is stepping down. Eventually we will switch to headless Chrome. Can headless Chrome handle web fonts?

答:
You should try and use an abstraction so you don't have to deal with the noise that comes from CDP.

I've started a project that just does that (and a few other things as well) https://github.com/joelgriffith/navalia. I'd be more than happy to fix anything you see missing (just throw up an issue!)

Body:
I'm using PhantomJS 2.1.1 on CentOS with the example script rasterize.js just to reproduce the screenshot problem, which is to take a screenshot of a simple web-font demo site:

http://castellsonclaret.com/public/external/georgiapro/demo.htm

It should render like so (as taken using the SaaS PhantomJSCloud service):

However, with PhantomJS 2.1.1 locally I get

First I increased the script timeout to 10s just to be sure that isn't the issue.

Next I thought the css or fonts were blocked somehow from downloading. When I use tcpflow (it's like wireshark) before running phantomjs scripts I can see that the above web page is downloading the .woff fonts. However, they are not being rendered in the screenshot I'm taking.

When I run the following before the phantomjs script

tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]'

I can see the fonts are being downloaded. Real console output:

GET /public/external/georgiapro/demo.htm HTTP/1.1

GET /t/1.css?apiType=css&projectid=4a82c0c9-a48a-4ef5-97ae-de0d7e62c8d0 HTTP/1.1

GET /public/external/georgiapro/Fonts/a5d15255-f5b4-4cca-808f-211ec0f25ac8.woff HTTP/1.1

GET /public/external/georgiapro/Fonts/3859825b-bdc4-47f3-af3d-a2ef42d58cfb.woff HTTP/1.1

... [snip] ...

GET /public/external/georgiapro/Fonts/ab79a7ac-4aaf-4393-896b-feb6610c9528.woff HTTP/1.1

I then thought that PhantomJS 2.x still doesn't support woff, but 1) it is supposed to be supported (see here), and 2) the SaaS PhantomJSCloud service can render them fine. Is there something more that is needed to be done to render web fonts?

Update: I've confirmed zlib is installed, and compiled PhantomJS 2.1.1 from source, but the results are still the same as above.

Update: Chrome has headless support, and that is the reason why on April 13 the maintainer of PhrantomJS has announced he is stepping down. Eventually we will switch to headless Chrome. Can headless Chrome handle web fonts?


问:
iOS 10+ using NSPersistentContainer - What's the best method to "clear all"
We want to have a settings bundle property that can be set to delete all the information stored using core data.  I see some examples that loop over all the entities and calls delete.  I see some that manipulate the files storing the stores.  This last way sounds better but I'm not sure how that fits into the magic of NSPersistentContainer.

On iOS 10, what's the best way to delete all the content in Core Data and continue on in the app saving new fetched data to Core Data?

答:
I haven't tried it, but here's what I think I'd do:

Create a new directory where you'll keep your persistent store and anything else that NSPersistentContainer wants to save. Make sure to create this directory when the app launches, using FileManager. You'll use this with Core Data by...

Subclassing NSPersistentContainer and overriding defaultDirectoryURL(). Use the directory from step 1.

Now you'll be sure that everything the persistent container writes goes in a known location that doesn't contain anything else.

When you want to delete everything, just delete every file in the directory that you're using (again, using FileManager). Make sure to do this before loading any data.


问:
Realm Object is not part of the schema for this Realm
I'm using realm as database for my app and i have model SessionModel:

```<code>public class SessionModel extends RealmObject {

    private long id;

    private int currentPomod;

    private int state;

    ...getters\setters
}
</code>```

When i'm trying to create new document in database:

```<code>Realm.init(this);

realm = Realm.getDefaultInstance();

realm.beginTransaction();
realm.copyToRealm(defSession);
</code>```

I got this error: java.lang.IllegalArgumentException: SessionModel is not part of the schema for this Realm

My top level gradle file contains this dependencies:

```<code>...
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

    classpath "io.realm:realm-gradle-plugin:2.3.0"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
...
</code>```

and app gradle module applying this plugins (ont top of build.gradle module app file):

```<code>apply plugin: 'com.android.application'
apply plugin: 'realm-android'

...
</code>```

Instant Run disabled.

答:
Found some solution from git issues. Its looking like same problem you have.

Solution:
apply apply plugin: 'com.neenbedankt.android-apt' before apply plugin: 'realm-android'

Hope it will help you!!

Body:
I'm using realm as database for my app and i have model SessionModel:

public class SessionModel extends RealmObject {

    private long id;

    private int currentPomod;

    private int state;

    ...getters\setters
}

When i'm trying to create new document in database:

Realm.init(this);

realm = Realm.getDefaultInstance();

realm.beginTransaction();
realm.copyToRealm(defSession);

I got this error: java.lang.IllegalArgumentException: SessionModel is not part of the schema for this Realm

My top level gradle file contains this dependencies:

...
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

    classpath "io.realm:realm-gradle-plugin:2.3.0"

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
...

and app gradle module applying this plugins (ont top of build.gradle module app file):

apply plugin: 'com.android.application'
apply plugin: 'realm-android'

...

Instant Run disabled.


问:
Getting a list of words from a Trie
I'm looking to use the following code to not check whether there is a word matching in the Trie but to return a list all words beginning with the prefix inputted by the user. Can someone point me in the right direction? I can't get it working at all.....</p>

```<code>public boolean search(String s)
{
    Node current = root;
    System.out.println("\nSearching for string: "+s);

    while(current != null)
    {
        for(int i=0;i<s.length();i++)
        {
            if(current.child[(int)(s.charAt(i)-'a')] == null)
            {
                System.out.println("Cannot find string: "+s);
                return false;
            }
            else
            {
                current = current.child[(int)(s.charAt(i)-'a')];
                System.out.println("Found character: "+ current.content);
            }
        }
        // If we are here, the string exists.
        // But to ensure unwanted substrings are not found:

        if (current.marker == true)
        {
            System.out.println("Found string: "+s);
            return true;
        }
        else
        {
            System.out.println("Cannot find string: "+s +"(only present as a substring)");
            return false;
        }
    }

    return false;
}

}
</code>```

答:
The below recursive code can be used where your TrieNode is like this:
This code works fine.</p>

```<code>TrieNode(char c)
{

        this.con=c;
        this.isEnd=false;
        list=new ArrayList<TrieNode>();
        count=0;

}

//--------------------------------------------------

public void Print(TrieNode root1, ArrayList<Character> path)
{

      if(root1==null)
          return;

      if(root1.isEnd==true)
      {
          //print the entire path
          ListIterator<Character> itr1=path.listIterator();
          while(itr1.hasNext())
          {
              System.out.print(itr1.next());
          }
          System.out.println();
          return;
      }
      else{
          ListIterator<TrieNode> itr=root1.list.listIterator();
          while(itr.hasNext())
          {
              TrieNode child=itr.next();
              path.add(child.con);
              Print(child,path);
              path.remove(path.size()-1);

            }
      }
</code>```

Title: Getting a list of words from a Trie

Body:
I'm looking to use the following code to not check whether there is a word matching in the Trie but to return a list all words beginning with the prefix inputted by the user. Can someone point me in the right direction? I can't get it working at all.....

public boolean search(String s)
{
    Node current = root;
    System.out.println("\nSearching for string: "+s);

    while(current != null)
    {
        for(int i=0;i<s.length();i++)
        {
            if(current.child[(int)(s.charAt(i)-'a')] == null)
            {
                System.out.println("Cannot find string: "+s);
                return false;
            }
            else
            {
                current = current.child[(int)(s.charAt(i)-'a')];
                System.out.println("Found character: "+ current.content);
            }
        }
        // If we are here, the string exists.
        // But to ensure unwanted substrings are not found:

        if (current.marker == true)
        {
            System.out.println("Found string: "+s);
            return true;
        }
        else
        {
            System.out.println("Cannot find string: "+s +"(only present as a substring)");
            return false;
        }
    }

    return false;
}

}

Body:
The below recursive code can be used where your TrieNode is like this:
This code works fine.

TrieNode(char c)
{

        this.con=c;
        this.isEnd=false;
        list=new ArrayList<TrieNode>();
        count=0;

}

//--------------------------------------------------

public void Print(TrieNode root1, ArrayList<Character> path)
{

      if(root1==null)
          return;

      if(root1.isEnd==true)
      {
          //print the entire path
          ListIterator<Character> itr1=path.listIterator();
          while(itr1.hasNext())
          {
              System.out.print(itr1.next());
          }
          System.out.println();
          return;
      }
      else{
          ListIterator<TrieNode> itr=root1.list.listIterator();
          while(itr.hasNext())
          {
              TrieNode child=itr.next();
              path.add(child.con);
              Print(child,path);
              path.remove(path.size()-1);

            }
      }


问:
how to pass variable with require() in PHP
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

```<code><?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."<br>".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>
</code>```

b.php

```<code><?php
echo "<h1>".$msg."</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Password: <input type='text' name='password'><br>
<input type='submit' name='submit'>
</form>
"

?>
</code>```

答:
"which means that if a.php includes b.php, it can read its variables."

I think the concept is slightly different. When you call the language construct require, it will read and include the specified file as if it were written in the calling file itself.

So this:

<?php

// File a.php
$somevar = 6;
require "b.php";

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

// File b.php
echo $somevar;

?>
</code>```

Is effectively the same as

<?php

// File a.php
$somevar = 6;

// File b.php
echo $somevar;

?>
```

Body:
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

<?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."
".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>

b.php

<?php
echo "
".$msg."

<form action='' method='post'>
Username: <input type='text' name='username'>

Password: <input type='text' name='password'>

<input type='submit' name='submit'>
</form>
"

?>

Body:
"which means that if a.php includes b.php, it can read its variables."

I think the concept is slightly different. When you call the language construct require, it will read and include the specified file as if it were written in the calling file itself.

So this:

<?php

// File a.php
$somevar = 6;
require "b.php";

?>

<?php

// File b.php
echo $somevar;

?>

Is effectively the same as

<?php

// File a.php
$somevar = 6;

// File b.php
echo $somevar;

?>


问:
Can't Pull Docker Image From Google Container Registry on Compute Engine
I am running CoreOS on a Google Compute Instance. I am trying to start a service to run a custom image I have in my private Google Container Registry.  Based on documentation, I need to run gcloud docker -- pull <image>.  When I do that, I get the error Cannot connect to the Docker daemon. Is the docker daemon running on this host?

I have resolved similar issues setting the Docker environment variables using docker-machine.  Unfortunately, that command is not available.

I have checked the ensure the Computer instance has read access to Storage.

How do I get my Docker image from my Google Container Registry to my machine running CoreOS in Goolge Compute?

答:
The gcloud CLI runs in a container on CoreOS, which has the unfortunate effect of breaking gcloud docker.

Please take a look at our advanced authentication options, e.g. for an image hosted on gcr.io (as opposed to us.gcr.io, eu.gcr.io ...)

docker login -u oauth2accesstoken -p "$(gcloud auth print-access-token)" https://gcr.io


问:
Expanding use of Javascript array.reduce helper method
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

```<code>function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));
</code>```

Question

How would I return the max depth of the parenthesis using the reduce helper method.

答:
You could maintain current depth and max depth while reducing.

function maxDepth(string) {
    return string.split("").reduce(({current, max}, char) => {
        // Handle if parens open and close out of order
        if (current < 0) return {current, max}
        // Add 1 for each open in order
        if (char === "(") return { current: current + 1, max: Math.max(max, current + 1)}
        // subtract 1 for each close in order
        if (char === ")") return { current: current - 1, max}
        return {current, max}
    }, {current: 0, max: 0}).max;
}
console.log(maxDepth("(((()))(((())))()(((((()))))))"));```

Body:
Background

I am following a course on Udemy which goes over all of the ES6 features. In one of the lessons the instructor talks about using the reduce helper method to solve the popular balance parenthesis interview question.

I can solve this without the reduce method. Although with the reduce method it does get the job done in less code. I have been asked to find the depth of the parenthesis in an interview before and was wondering if this could all be done in the same method using reduce.

I do not know why this addition to the question confuses me so much but I would like to learn.

Problem

I have been trying to figure it out for a while and it might be my lack of understanding how reduce works.

Example

This uses reduce to return true of false regarding if the parenthesis or open and closed evenly.

function balanceParens(string) {
    return !string.split("").reduce((counter, char) => {
        // Handle if parens open and close out of order
        if (counter < 0) { return counter; }
        // Add 1 for each open in order
        if (char === "(") { return ++counter; }
        // subtract 1 for each close in order
        if (char === ")") { return --counter; }
        // handle use case if char is not a paren
        return counter;
    }, 0);
}
console.log(balanceParens("((()))"));

Question

How would I return the max depth of the parenthesis using the reduce helper method.


问:
How to run a convolutional neural network on new data
I was looking at this tutorial for creating a Convolutional Neural Network with Tensorflow.

After the neural network is built and trained, in the tutorial, it is tested like this:

```<code>eval_results = mnist_classifier.evaluate(
    x=eval_data, y=eval_labels, metrics=metrics)
print(eval_results)
</code>```

However, I don't have a labels for the test set, so I want to run it just with the training examples, like this:

```<code>eval_results = mnist_classifier.evaluate(x=test_data, metrics=metrics)
</code>```

If I do that however, I get this warning and then the execution stops:

```<code>WARNING:tensorflow:From ../src/script.py:169: calling BaseEstimator.evaluate (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
Traceback (most recent call last):
  File "../src/script.py", line 172, in <module>
    main()
  File "../src/script.py", line 169, in main
    eval_results = mnist_classifier.evaluate(x=test_data, metrics=metrics)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 530, in evaluate
102.5s
7
    return SKCompat(self).score(x, y, batch_size, steps, metrics)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1365, in score
    name='score')
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 816, in _evaluate_model
    % self._model_dir)
tensorflow.contrib.learn.python.learn.estimators._sklearn.NotFittedError: Couldn't find trained model at /tmp/mnist_convnet_model.
</code>```

答:
You can not use mnist_classifier.evaluate without a y paramater, because you have nothing to evaluate.

Instead, use y = mnist_classifier.predict(x=x) to get results, and have a look at them yourself to know if they are correct or not.

However, it's a very bad idea to do this with data that the network already trained on, because it could lead to good results that do not reflect how the network is handling new information.

Other than that, the warning you get is pretty normal, because the x and y arguments are deprecated anyway, but you can still use them. If you want to make the warning itself go away you should add tf.logging.set_verbosity(tf.logging.ERROR) after you import tf

EDIT: Also, when I think about it, how come you have the labels for the training set and not for the test set? You should always split the training data and labels so that most of it is trained on, but some of it is kept exactly so you can use it in evaluate

Body:
I was looking at this tutorial for creating a Convolutional Neural Network with Tensorflow.

After the neural network is built and trained, in the tutorial, it is tested like this:

eval_results = mnist_classifier.evaluate(
    x=eval_data, y=eval_labels, metrics=metrics)
print(eval_results)

However, I don't have a labels for the test set, so I want to run it just with the training examples, like this:

eval_results = mnist_classifier.evaluate(x=test_data, metrics=metrics)

If I do that however, I get this warning and then the execution stops:

WARNING:tensorflow:From ../src/script.py:169: calling BaseEstimator.evaluate (from tensorflow.contrib.learn.python.learn.estimators.estimator) with x is deprecated and will be removed after 2016-12-01.
Instructions for updating:
Estimator is decoupled from Scikit Learn interface by moving into
separate class SKCompat. Arguments x, y and batch_size are only
available in the SKCompat class, Estimator will only accept input_fn.
Example conversion:
  est = Estimator(...) -> est = SKCompat(Estimator(...))
Traceback (most recent call last):
  File "../src/script.py", line 172, in <module>
    main()
  File "../src/script.py", line 169, in main
    eval_results = mnist_classifier.evaluate(x=test_data, metrics=metrics)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 530, in evaluate
102.5s
7
    return SKCompat(self).score(x, y, batch_size, steps, metrics)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 1365, in score
    name='score')
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/contrib/learn/python/learn/estimators/estimator.py", line 816, in _evaluate_model
    % self._model_dir)
tensorflow.contrib.learn.python.learn.estimators._sklearn.NotFittedError: Couldn't find trained model at /tmp/mnist_convnet_model.


问:
How to get intersection of two slice in golang?
Is there any efficient way to get intersection of two slices in Go?</p>

I want to avoid nested for loop like solution

```<code>slice1 := []string{"foo", "bar","hello"}
slice2 := []string{"foo", "bar"}

intersection(slice1, slice2)
=> ["foo", "bar"]
</code>```

order of string does not matter

答:
How do I get the intersection between two arrays as a new array?

Simple Intersection: Compare each element in A to each in B (O(n^2))

Hash Intersection: Put them into a hash table (O(n))

Sorted Intersection: Sort A and do an optimized intersection (O(n*log(n)))

All of which are implemented here

https://github.com/juliangruber/go-intersect

Body:
Is there any efficient way to get intersection of two slices in Go?

I want to avoid nested for loop like solution

slice1 := []string{"foo", "bar","hello"}
slice2 := []string{"foo", "bar"}

intersection(slice1, slice2)
=> ["foo", "bar"]

order of string does not matter


答:
So, there is a lot going on here, but lets start with the inside:

Func<TEntity, bool> is a delegate that takes an input, which type is generic, so we just call it TEntity.  Without any contraints, this can be anything, but a strongly-typed anything.

Out one level is Expression<Func<TEntity, bool>>.  This is the expression tree, which is strongly typed to be a delegate that takes an input and return a bool.  In other words, it is an expression tree (think back to your compilers course) that represents the function.

Finally, the outermost level: TEntity Single(Expression<Func<TEntity, bool>> predicate) is a method called Single which takes a predicate function in the form of an expression.  What is returned is the same type that is passed into that function.

Essentially, Single will take your expression, compile it and execute it against a set of data, returning the first entity in the collection that matches the predicate expression.

Hope this helps?

Title: c# syntax help, about generic programming