问:
Android EditText click event triggering on second time
I have an EditText inside a RelativeLayout which is child of a ScrollView. RelativeLayout has a list of EditText. My problem is EditText is triggering Click Event on second time click.

I have used android:focusable="true"  android:focusableInTouchMode="true" attributes but no luck.

I have added code. Actually, I am opening a DatePickerDialog on EditText Click event. That's why I had disabled editable attribute. But click event is triggering on second click and DatePickerDialog is showed.

```<code>            <RelativeLayout android:layout_width="wrap_content"
                android:padding="8dp"
                android:layout_below="@+id/eight"
                android:layout_marginTop="10dp"
                android:background="@drawable/white_bg"
                android:id="@+id/nine"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/lossDate"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:textSize="14sp"
                    android:layout_marginEnd="30dp"
                    android:layout_marginTop="5dp"
                    android:clickable="true"
                    android:editable="false"
                    android:inputType="none"
                    android:background="@drawable/transparent"
                    android:drawableStart="@drawable/ic_calendar"
                    android:drawablePadding="10dp"
                    android:hint=" Date Of Loss (Required)" />

                <ImageButton
                    android:id="@+id/lossDateCancel"
                    android:layout_height="23dp"
                    android:visibility="invisible"
                    android:layout_centerVertical="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ic_cancel"
                    android:layout_width="23dp"/>

            </RelativeLayout>
</code>```

答:
Change clickable=false and focusable=false

```<code> <EditText
                android:id="@+id/lossDate"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:textSize="14sp"
                android:layout_marginEnd="30dp"
                android:layout_marginTop="5dp"
                android:clickable="false"
                android:editable="false"
                android:focusable="false"
                android:inputType="none"
                android:background="@drawable/transparent"
                android:drawableStart="@drawable/ic_calendar"
                android:drawablePadding="10dp"
                android:hint=" Date Of Loss (Required)" />
</code>```

Body:
I have an EditText inside a RelativeLayout which is child of a ScrollView. RelativeLayout has a list of EditText. My problem is EditText is triggering Click Event on second time click.

I have used android:focusable="true"  android:focusableInTouchMode="true" attributes but no luck.

I have added code. Actually, I am opening a DatePickerDialog on EditText Click event. That's why I had disabled editable attribute. But click event is triggering on second click and DatePickerDialog is showed.

            <RelativeLayout android:layout_width="wrap_content"
                android:padding="8dp"
                android:layout_below="@+id/eight"
                android:layout_marginTop="10dp"
                android:background="@drawable/white_bg"
                android:id="@+id/nine"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/lossDate"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:textSize="14sp"
                    android:layout_marginEnd="30dp"
                    android:layout_marginTop="5dp"
                    android:clickable="true"
                    android:editable="false"
                    android:inputType="none"
                    android:background="@drawable/transparent"
                    android:drawableStart="@drawable/ic_calendar"
                    android:drawablePadding="10dp"
                    android:hint=" Date Of Loss (Required)" />

                <ImageButton
                    android:id="@+id/lossDateCancel"
                    android:layout_height="23dp"
                    android:visibility="invisible"
                    android:layout_centerVertical="true"
                    android:layout_alignParentEnd="true"
                    android:layout_alignParentRight="true"
                    android:background="@drawable/ic_cancel"
                    android:layout_width="23dp"/>

            </RelativeLayout>

Body:
Change clickable=false and focusable=false

 <EditText
                android:id="@+id/lossDate"
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:textSize="14sp"
                android:layout_marginEnd="30dp"
                android:layout_marginTop="5dp"
                android:clickable="false"
                android:editable="false"
                android:focusable="false"
                android:inputType="none"
                android:background="@drawable/transparent"
                android:drawableStart="@drawable/ic_calendar"
                android:drawablePadding="10dp"
                android:hint=" Date Of Loss (Required)" />


来源: stackexchange

问:
Deploying Node + MongoDB API on AWS or GCP
I am working on a Node + MongoDB API and the API is deployed on a VM on Google Cloud Platform. Currently, the data is stored in a MongoDB instance running on the VM.

Is running a local MongoDB instance for production a good practice? And how does various cloud services providing MongoDB compare with each other? And what are some good practices to ensure the API is scalable? Also can deploying API to Kubernetes as a container offer better results as compared to VMs?

答:
Having both server and database running in the same VM instance would always be a bad idea for a service that you want to scale. Let's think what happen if your instance could not handle the number of traffic being sent into anymore?

At first you might just do the vertical scale adding more CPU and RAM to the currently running instance and yes, that would be fine for some period of time. But it is actually more like a temporary life-extending plan since at some point, your instance will not be able to do the vertical scale anymore. And here come the horizontal scale...

New instance has to be created to handle the increasing number of traffic and how would you design the new instance for that?

The best practice is to have an instance that looks exactly the same as the first one. So the server is needed to be designed as a stateless one. In this case, your instance will be able to scale for at any number of machine.

That's why you should not have the API front end and database running in the same instance. It could not be scaled.

So how's about the database? It is quite straightforward. Just simply place it in the another VM instance! If database is still be able to handle the request, you can just share the database server among the server instances. But if there is a bottleneck on the database side, you can scale your mongoDB separately with cluster or so.

If you don't have time, you can consider using the ready-to-use service like Heroku Add-On, for example, mongolab, to managing the MongoDB instance for you.

Cheers.

ContentLicense: CC BY-SA 4.0


问:
Facebook share through my website and get likes and shares count only?
I want to create a website where it would be crucial to be able to view the likes and shares of a specific post a user shares from the website.. Is this possible anymore? The flow would be similar to this:

User logs in through Facebook and grants user_posts permission
User then clicks a share button for a specific url with quote content and a hashtag

What I need after those steps are:
ID of the post from sharing
Count of likes, reactions and shares on that post

even better would be a webhook notice of likes/reactions/shares count.

Any ideas? I don't need any private data... just counts of likes/reactions/shares but it's not looking possible anymore.

答:
https://developers.facebook.com/docs/apps/examples-platform-policy-4.4

Don't incentivize people to post content on Facebook, or give the
  impression that posting to Facebook will be rewarded

Incentivizing users for posting/sharing something on their personal wall is not allowed, you would not get the user_posts permission approved for that, and that makes it impossible.


问:
Android - onLoadFinished not called
I am facing an issue with Loader.

I have an Activity, which displays list of records retrieved from local DB. When the activity starts, records are automatically loaded via LoaderManager.initLoader() method.

There is also possibility to manually refresh the list via refresh button in ActionBarSherlock. However, after finishing another activity which adds a record to DB, onLoadFinished is not called.

I am using SimpleCursorLoader and here is code snippet from the activity:

```<code>@Override
public void onStart() {
   ...
   getSupportLoaderManager().initLoader(0, null, this);
}

@Override
public void onPause() {
   ...
   getSupportLoaderManager().destroyLoader(0);
}

public void refreshRecords() {
   getSupportLoaderManager().restartLoader(0, null, this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle args) {
Loader<Cursor> l = new SimpleCursorLoader(this) {
    @Override
    public Cursor loadInBackground() {
        return recordDAO.getCursor();
    }
};
l.forceLoad();
return l;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
   // updateUI
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
</code>```

The issue is that after finishing the other activity, onLoaderCreate is called, but onLoaderFinished is not called.

after some debugging, I've found that SimpleCursorAdapter.deliverResults() is also called, bud ends up on .. if (isReset()) { ..

Am I missing something? How to force the reload of data?

Thank you in advance

答:
Check the support library.Use this import android.support.v4.app. Don't use android.app.loadermanager.

```<code>import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
</code>```

Initialize part

```<code>    LoaderManager mLoaderManager=getSupportLoaderManager();

      LoaderManager.LoaderCallbacks<Cursor> mCursorLoaderCallbacks=new LoaderManager.LoaderCallbacks<Cursor>() {
                @Override
                public Loader<Cursor> onCreateLoader(int id, Bundle cursor) {
                      return new CursorLoader(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, COLUMNS_OF_INTEREST, null, null,
                            MediaStore.Video.Media.DATE_ADDED + " DESC");
                }
                @Override
                public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
                }

                @Override
                public void onLoaderReset(Loader<Cursor> loader) {
               }
            };

  mLoaderManager.initLoader(URL_LOADER_EXTERNAL, null, mCursorLoaderCallbacks);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Android - onLoadFinished not called

Body:
I am facing an issue with Loader.

I have an Activity, which displays list of records retrieved from local DB. When the activity starts, records are automatically loaded via LoaderManager.initLoader() method.

There is also possibility to manually refresh the list via refresh button in ActionBarSherlock. However, after finishing another activity which adds a record to DB, onLoadFinished is not called.

I am using SimpleCursorLoader and here is code snippet from the activity:

@Override
public void onStart() {
   ...
   getSupportLoaderManager().initLoader(0, null, this);
}

@Override
public void onPause() {
   ...
   getSupportLoaderManager().destroyLoader(0);
}

public void refreshRecords() {
   getSupportLoaderManager().restartLoader(0, null, this);
}

@Override
public Loader<Cursor> onCreateLoader(int id, final Bundle args) {
Loader<Cursor> l = new SimpleCursorLoader(this) {
    @Override
    public Cursor loadInBackground() {
        return recordDAO.getCursor();
    }
};
l.forceLoad();
return l;
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor c) {
   // updateUI
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
}

The issue is that after finishing the other activity, onLoaderCreate is called, but onLoaderFinished is not called.

after some debugging, I've found that SimpleCursorAdapter.deliverResults() is also called, bud ends up on .. if (isReset()) { ..

Am I missing something? How to force the reload of data?

Thank you in advance

Body:
Check the support library.Use this import android.support.v4.app. Don't use android.app.loadermanager.

import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

Initialize part

    LoaderManager mLoaderManager=getSupportLoaderManager();

      LoaderManager.LoaderCallbacks<Cursor> mCursorLoaderCallbacks=new LoaderManager.LoaderCallbacks<Cursor>() {
                @Override
                public Loader<Cursor> onCreateLoader(int id, Bundle cursor) {
                      return new CursorLoader(getActivity(), MediaStore.Video.Media.EXTERNAL_CONTENT_URI, COLUMNS_OF_INTEREST, null, null,
                            MediaStore.Video.Media.DATE_ADDED + " DESC");
                }
                @Override
                public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
                }

                @Override
                public void onLoaderReset(Loader<Cursor> loader) {
               }
            };

  mLoaderManager.initLoader(URL_LOADER_EXTERNAL, null, mCursorLoaderCallbacks);


问:
How to tar gzip with the same folder name
All, I need to tar gzip the folder and the name should be same as the original folder name.

Example Directory : /user/abc/documents/20190101
I need to tar the 20190101 folder to 20190101.tar.gz by not explicitly specifying the name of the folder.

tar -czvf /user/abc/documents/20190101.tar.gz /user/abc/documents/20190101/testing/20190506-081500000

答:
Use a shell command to detect the directory name and capture it in a variable. Then use this variable to create the tar file.

For e.g.

Create some files and directories:

```<code>shell$ mkdir -p foo/001
shell$ mkdir -p foo/002
shell$ mkdir -p foo/003
shell$ touch foo/bar.txt
shell$ tree foo
foo
├── 001
├── 002
├── 003
└── bar.txt

3 directories, 1 file
shell$
</code>```

Check the directory structure

```<code>shell$ cd foo
shell$ find . -type d
.
./001
./003
./002
shell$ find . -type d | grep -v "\.$"
./001
./003
./002
shell$
</code>```

Use find to detect the directories. Iterate in a loop and create tar files with same name as the directories.

```<code>shell$ for x in `find . -type d | grep -v "\.$"`; do
> echo "Tarring $x..."
> tar cvzf $x.tar.gz $x
> done
Tarring ./001...
a ./001
Tarring ./003...
a ./003
Tarring ./002...
a ./002
shell$
</code>```

Verify

```<code>shell$ tree .
.
├── 001
├── 001.tar.gz
├── 002
├── 002.tar.gz
├── 003
├── 003.tar.gz
└── bar.txt

3 directories, 4 files
shell$
</code>```

Body:
Use a shell command to detect the directory name and capture it in a variable. Then use this variable to create the tar file.

For e.g.

Create some files and directories:

shell$ mkdir -p foo/001
shell$ mkdir -p foo/002
shell$ mkdir -p foo/003
shell$ touch foo/bar.txt
shell$ tree foo
foo
├── 001
├── 002
├── 003
└── bar.txt

3 directories, 1 file
shell$

Check the directory structure

shell$ cd foo
shell$ find . -type d
.
./001
./003
./002
shell$ find . -type d | grep -v "\.$"
./001
./003
./002
shell$

Use find to detect the directories. Iterate in a loop and create tar files with same name as the directories.

shell$ for x in `find . -type d | grep -v "\.$"`; do
> echo "Tarring $x..."
> tar cvzf $x.tar.gz $x
> done
Tarring ./001...
a ./001
Tarring ./003...
a ./003
Tarring ./002...
a ./002
shell$

Verify

shell$ tree .
.
├── 001
├── 001.tar.gz
├── 002
├── 002.tar.gz
├── 003
├── 003.tar.gz
└── bar.txt

3 directories, 4 files
shell$


问:
Align Paragraph at the center of the page
I am using itext to generate pdf file. I want to align my title in the middle of the page. Presently i am using like this

```<code>Paragraph preface = new Paragraph();
for (int i = 0; i < 10; i++) {
    preface.add(new Paragraph(" "));
}
</code>```

Is it correct or is there any another best way to do this.

答:
If you are looking for a solution to Itext7 then you can use the method setTextAlignment(...).

Example:

```<code>Paragraph preface = new Paragraph();
// add text
preface.setTextAlignment(TextAlignment.CENTER);
</code>```

Body:
I am using itext to generate pdf file. I want to align my title in the middle of the page. Presently i am using like this

Paragraph preface = new Paragraph();
for (int i = 0; i < 10; i++) {
    preface.add(new Paragraph(" "));
}

Is it correct or is there any another best way to do this.

Body:
If you are looking for a solution to Itext7 then you can use the method setTextAlignment(...).

Example:

Paragraph preface = new Paragraph();
// add text
preface.setTextAlignment(TextAlignment.CENTER);


问:
How can I join the last X entries in a string array?
I've got an array like this:

```<code>string[] parts = line.Split(',');

string store = parts[0];
string sku = parts[1];
string subcatcode = parts[2];
string price = parts[3];
string date = parts[4];
string desc = parts[5];
</code>```

I want description to equal the joined value of all the parts with an index of 5 or higher. Will this work or is there a better way to do it?

```<code>string desc = string.Join(",", parts.Skip(5).ToArray());
</code>```

The issue is that the last part of the CSV I'm parsing can contain commas (parts 0-4 are guaranteed not to).

答:
Why not just specify a maximum count when you call Split?

```<code>string[] parts = line.Split(','.ToCharArray(), 6);
</code>```

The last element (which you will assign to description) will include everything else, including the commas.

For data like "1,2,3,4,5,6,7,8" this will give you { "1", "2", "3", "4", "5", "6,7,8" }

OwnerDisplayName: John Sheehan

ContentLicense: CC BY-SA 2.5

Body:
I've got an array like this:

string[] parts = line.Split(',');

string store = parts[0];
string sku = parts[1];
string subcatcode = parts[2];
string price = parts[3];
string date = parts[4];
string desc = parts[5];

I want description to equal the joined value of all the parts with an index of 5 or higher. Will this work or is there a better way to do it?

string desc = string.Join(",", parts.Skip(5).ToArray());

The issue is that the last part of the CSV I'm parsing can contain commas (parts 0-4 are guaranteed not to).

Body:
Why not just specify a maximum count when you call Split?

string[] parts = line.Split(','.ToCharArray(), 6);

The last element (which you will assign to description) will include everything else, including the commas.

For data like "1,2,3,4,5,6,7,8" this will give you { "1", "2", "3", "4", "5", "6,7,8" }

OwnerDisplayName: Daniel L

LastEditorDisplayName: Daniel L


问:
c# file move (file is already used by another process)
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

```<code>  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

this works fine

```<code> if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }
</code>```

答: I guess the sourcepath will be in use (copying of files) and since the destination path is a subfolder of source path it might give you "Currently used by another process error".</p>

Body:
I am moving files from one folder to another. If I try to move the entire folder to the folder within that particular folder I cannot do that. But if I move it outside it works fine. How can I move my folder to the folder within that folder?

this gives error

  if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\copypath\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }

this works fine

 if (System.IO.Directory.Exists(PhysicalPath))
 {
      string sourcePath = "c:\\copypath\\";
      string targetPath = "c:\\abc\\";
      System.IO.Directory.Move(sourcePath, targetPath);
 }


问:
How to update single property of multiple entities in specific kind of datastore?
I want to update one property of each entity present in one particular kind of my datastore. In traditional sql, we do something like this as -

```<code>update <tablename> set <property> = <value>; {where clause is optional}
</code>```

Now, how can I do same thing for datastore using golang code?

答:
In Datastore you can't perform an update like that without retrieving the entities. You have to pull all entities in that kind, update the property on each, and re-upsert the now updated entities (preferably in a batch).

Go Datastore Queries: https://cloud.google.com/datastore/docs/concepts/queries#datastore-datastore-basic-query-go

Go Update Entities: https://cloud.google.com/datastore/docs/concepts/entities#datastore-datastore-update-go

Go Batch Upsert: https://cloud.google.com/datastore/docs/concepts/entities#datastore-datastore-batch-upsert-go

Body:
I want to update one property of each entity present in one particular kind of my datastore. In traditional sql, we do something like this as -

update <tablename> set <property> = <value>; {where clause is optional}

Now, how can I do same thing for datastore using golang code?


问:
Google Cloud ML using Python 2.7
I have a ML python script that I have submitted as a job to Google Cloud ML, but kept getting a syntax error when using * to unpack a list. Then I realised that my code was getting executed in Python V2.7. Why would this be the case, can Google Cloud ML be set to use Python V3.?

Thanks

答:
As mentioned in Google document,

AI Platform runs Python 2.7 by default.
Python 3.5 is available when you use AI Platform runtime version 1.4 or greater.

ex:

```<code>training_inputs = {'scaleTier': 'BASIC',
    'packageUris': ['gs://my/trainer/path/package-0.0.0.tar.gz'],
    'pythonModule': 'trainer.task'
    'args': ['--arg1', 'value1', '--arg2', 'value2'],
    'region': 'us-central1',
    'jobDir': 'gs://my/training/job/directory',
    'runtimeVersion': '1.13',
    'pythonVersion': '3.5'}
</code>```

for more info, please refer :

https://cloud.google.com/ml-engine/docs/tensorflow/environment-overview

https://cloud.google.com/ml-engine/docs/tensorflow/versioning#set-python-version-training

Title: Google Cloud ML using Python 2.7

Body:
As mentioned in Google document,

AI Platform runs Python 2.7 by default.
Python 3.5 is available when you use AI Platform runtime version 1.4 or greater.

ex:

training_inputs = {'scaleTier': 'BASIC',
    'packageUris': ['gs://my/trainer/path/package-0.0.0.tar.gz'],
    'pythonModule': 'trainer.task'
    'args': ['--arg1', 'value1', '--arg2', 'value2'],
    'region': 'us-central1',
    'jobDir': 'gs://my/training/job/directory',
    'runtimeVersion': '1.13',
    'pythonVersion': '3.5'}

for more info, please refer :

https://cloud.google.com/ml-engine/docs/tensorflow/environment-overview

https://cloud.google.com/ml-engine/docs/tensorflow/versioning#set-python-version-training


问:
New data frame after function is empty
I prepare a function to have a temporary dataframe, but whent i apply this function on my old dataframe , the temporary dataframe is empty. How can i solve this ?

I tried this code :

data_a <- as.data.frame(cbind(pop=c("a1","b2","c3","d4","d5"),
                         PA1=c(1,40,430,4330,43330),
                        PA2=c(2,50,530,5330,53330)))

perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat["vname"]
 locci_1 <- sample(dat["loc1"], replace = F)
 locci_2 <- sample(dat["loc2"], replace = F)
 data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
 }

data_3 <- perm_all(dat= "data_a",vname="pop",loc1="PA1",loc2="PA2")
```

<p>I've tried to convert the data_a with </p>

<pre class="lang-r prettyprint-override"><code>data_a <- as.matrix(data_a)
</code>```

and

 popu <- sample(dat[,1], replace = F)
```

but they didn't work too

Thank's :)

答:
There are maybe multiple issues. First, when you have created your data frame, be aware that data.frame function family treat string as a factor by default. It may be not what you want.

Then @NURAIMIAZIMAH is right, your function needs a data frame to work properly, so :

```<code>data_3 <- perm_all(dat= data_a,vname="pop",loc1="PA1",loc2="PA2")
</code>```

is a good start.

Moreover, you give value to vector like vname, loc1 and loc2. But you only use the name of these objects in your function, because you forgot to remove quotation mark.

```<code>perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat[vname]
  locci_1 <- sample(dat[loc1], replace = F)
  locci_2 <- sample(dat[loc2], replace = F)
  data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
}
</code>```

Now your function should work, but maybe not in the way you would like to. Because there won't be any permutations in your data_3 table. If you look carefully, the type of return of this part of the code dat[loc1] is a data frame. You certainly want a vector to permute your data, so you have to subset your data frame like this : dat[,loc1].

This code below should do what you expect.

```<code>data_a <- as.data.frame(cbind(pop=c("a1","b2","c3","d4","d5"),
                              PA1=c(1,40,430,4330,43330),
                              PA2=c(2,50,530,5330,53330)))

perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat[vname]
  locci_1 <- sample(dat[,loc1], replace = F)
  locci_2 <- sample(dat[,loc2], replace = F)
  data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
}

data_3 <- perm_all(dat= data_a,vname="pop",loc1="PA1",loc2="PA2")
</code>```

See you.

Title: New data frame after function is empty

Body:
I prepare a function to have a temporary dataframe, but whent i apply this function on my old dataframe , the temporary dataframe is empty. How can i solve this ?

I tried this code :

data_a <- as.data.frame(cbind(pop=c("a1","b2","c3","d4","d5"),
                         PA1=c(1,40,430,4330,43330),
                        PA2=c(2,50,530,5330,53330)))

perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat["vname"]
 locci_1 <- sample(dat["loc1"], replace = F)
 locci_2 <- sample(dat["loc2"], replace = F)
 data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
 }

data_3 <- perm_all(dat= "data_a",vname="pop",loc1="PA1",loc2="PA2")

I've tried to convert the data_a with

data_a <- as.matrix(data_a)

and

 popu <- sample(dat[,1], replace = F)

but they didn't work too

Thank's :)

Body:
There are maybe multiple issues. First, when you have created your data frame, be aware that data.frame function family treat string as a factor by default. It may be not what you want.

Then @NURAIMIAZIMAH is right, your function needs a data frame to work properly, so :

data_3 <- perm_all(dat= data_a,vname="pop",loc1="PA1",loc2="PA2")

is a good start.

Moreover, you give value to vector like vname, loc1 and loc2. But you only use the name of these objects in your function, because you forgot to remove quotation mark.

perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat[vname]
  locci_1 <- sample(dat[loc1], replace = F)
  locci_2 <- sample(dat[loc2], replace = F)
  data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
}

Now your function should work, but maybe not in the way you would like to. Because there won't be any permutations in your data_3 table. If you look carefully, the type of return of this part of the code dat[loc1] is a data frame. You certainly want a vector to permute your data, so you have to subset your data frame like this : dat[,loc1].

This code below should do what you expect.

data_a <- as.data.frame(cbind(pop=c("a1","b2","c3","d4","d5"),
                              PA1=c(1,40,430,4330,43330),
                              PA2=c(2,50,530,5330,53330)))

perm_all <- function(dat,vname,loc1, loc2){
  popu <- dat[vname]
  locci_1 <- sample(dat[,loc1], replace = F)
  locci_2 <- sample(dat[,loc2], replace = F)
  data_a_1 <- as.data.frame(cbind(popu, locci_1, locci_2))
  return(data_a_1)
}

data_3 <- perm_all(dat= data_a,vname="pop",loc1="PA1",loc2="PA2")

See you.


问:
How to remove extra line at the bottom of bar chart using ios charts?
Using Charts library I would like to get a specific look on the second photo. What I'm able to accomplish as of now was the one at the top image. I know I'm still too far from accomplishing the right one.

This is the implementation that I have for https://github.com/danielgindi/Charts as of this moment. I'm still exploring the Charts features though.

```<code>    var dataEntries: [BarChartDataEntry] = []

    let dataEntry1 = BarChartDataEntry(x: Double(0), y: Double(26))
    dataEntries.append(dataEntry1)
    let dataEntry2 = BarChartDataEntry(x: Double(1), y: Double(0))
    dataEntries.append(dataEntry2)
    let dataEntry3 = BarChartDataEntry(x: Double(2), y: Double(2))
    dataEntries.append(dataEntry3)

    let chartDataSet = BarChartDataSet(values: dataEntries, label: nil)// BarChartDataSet(values: dataEntries, label: "A")
    chartDataSet.setColor(.red)

    let chartData = BarChartData(dataSet: chartDataSet)
    chartData.barWidth = Double(0.3)

    barChart.data = chartData
    barChart.fitBars = true
    barChart.zoomOut()

    barChart.xAxis.drawGridLinesEnabled = false // disable horizontal grid lines

    barChart.scaleYEnabled = true
    barChart.scaleXEnabled = true

    let description = Description()
    description.text = ""
    barChart.chartDescription = description

    let labels = ["1-30 days", "31-60 days", "61+ days"]
    barChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: labels)
    barChart.xAxis.granularity = 1.0
    barChart.xAxis.granularityEnabled = true
    barChart.xAxis.labelPosition = .bottom

    barChart.drawValueAboveBarEnabled = false
</code>```

Specifically what I still lack as of now is a way to remove the extra line at the bottom and at the right bounds of the bar chart.

Current look:

Target Look:

UPDATE:
barChart.rightAxis.enabled = false // removes the right labels

I still have to find a way to remove the one marked blue at the image, and have the bottom labels go near the box.

UPDATE: I was able to make the xAxis labels just right where I want them to be by positioning them with .bottomInside

```<code>barChart.xAxis.labelPosition = .bottomInside
</code>```

updated look:

What's left is getting rid of that last bottom square but keeping the label.

This: removes the whole bottom square including the labels.
barChart.xAxis.labelPosition = .bottomInside

答:
if your left axis enabled </p>

```<code>barChartView.leftAxis.spaceBottom = 0.0
</code>```

<p>if your right axis enabled </p>

```<code>barChartView.rightAxis.spaceBottom = 0.0
</code>```

Body:
Using Charts library I would like to get a specific look on the second photo. What I'm able to accomplish as of now was the one at the top image. I know I'm still too far from accomplishing the right one.

This is the implementation that I have for https://github.com/danielgindi/Charts as of this moment. I'm still exploring the Charts features though.

    var dataEntries: [BarChartDataEntry] = []

    let dataEntry1 = BarChartDataEntry(x: Double(0), y: Double(26))
    dataEntries.append(dataEntry1)
    let dataEntry2 = BarChartDataEntry(x: Double(1), y: Double(0))
    dataEntries.append(dataEntry2)
    let dataEntry3 = BarChartDataEntry(x: Double(2), y: Double(2))
    dataEntries.append(dataEntry3)

    let chartDataSet = BarChartDataSet(values: dataEntries, label: nil)// BarChartDataSet(values: dataEntries, label: "A")
    chartDataSet.setColor(.red)

    let chartData = BarChartData(dataSet: chartDataSet)
    chartData.barWidth = Double(0.3)

    barChart.data = chartData
    barChart.fitBars = true
    barChart.zoomOut()

    barChart.xAxis.drawGridLinesEnabled = false // disable horizontal grid lines

    barChart.scaleYEnabled = true
    barChart.scaleXEnabled = true

    let description = Description()
    description.text = ""
    barChart.chartDescription = description

    let labels = ["1-30 days", "31-60 days", "61+ days"]
    barChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: labels)
    barChart.xAxis.granularity = 1.0
    barChart.xAxis.granularityEnabled = true
    barChart.xAxis.labelPosition = .bottom

    barChart.drawValueAboveBarEnabled = false

Specifically what I still lack as of now is a way to remove the extra line at the bottom and at the right bounds of the bar chart.

Current look:

Target Look:

UPDATE:
barChart.rightAxis.enabled = false // removes the right labels

I still have to find a way to remove the one marked blue at the image, and have the bottom labels go near the box.

UPDATE: I was able to make the xAxis labels just right where I want them to be by positioning them with .bottomInside

barChart.xAxis.labelPosition = .bottomInside

updated look:

What's left is getting rid of that last bottom square but keeping the label.

This: removes the whole bottom square including the labels.
barChart.xAxis.labelPosition = .bottomInside

Body:
if your left axis enabled

barChartView.leftAxis.spaceBottom = 0.0

if your right axis enabled

barChartView.rightAxis.spaceBottom = 0.0


答:
Trying to  "c:\copypath\" into "c:\copypath\abc\" won't work because it doesn't make sense.

If you move the copypath folder then it won't exist anymore, so how will the target folder (which is a subfolder) of it exist?

You could move all of the child files of "c:\copypath\" into "c:\copypath\abc\" instead, which wouldn't cause a problem (again assuming you don't try to copy abc into itself).

Title: c# file move (file is already used by another process)


问:
Kubernetes Java Client API Exception
I am using Kubernetes Java client API https://github.com/kubernetes-client/java for fetching all namespaces present. I am Getting Error-

```<code>io.kubernetes.client.ApiException: java.net.ConnectException: Failed to connect to localhost/127.0.0.1:443
    at io.kubernetes.client.ApiClient.execute(ApiClient.java:801)
    at io.kubernetes.client.apis.CoreV1Api.listNamespaceWithHttpInfo(CoreV1Api.java:15939)
    at io.kubernetes.client.apis.CoreV1Api.listNamespace(CoreV1Api.java:15917)
    at com.cloud.kubernetes.KubernetesNamespacesAPI.fetchAllNamespaces(KubernetesNamespacesAPI.java:25)
    at com.cloud.spark.sharedvariable.ClouzerConfigurations.setKubernetesEnvironment(ClouzerConfigurations.java:45)
</code>```

I tried creating cluster role binding and giving permission to the user.

Here is my code snippet:

```<code>public static List<String> fetchAllNamespaces(){
        try {
            return COREV1_API.listNamespace(null, "true", null, null, null, 0, null, Integer.MAX_VALUE, Boolean.FALSE)
                    .getItems().stream().map(v1Namespace -> v1Namespace.getMetadata().getName())
                    .collect(Collectors.toList());
        }catch(Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
</code>```

Please let me know if I am missing anything. Thanks in advance.

答:
I'm facing the same exception too.
After several survey to the client lib's source code, I think you need to make sure of two things.

first of all, can you access your api-server?

secondly, you need to check your ApiClient bootstrap order.

Which way do you use to config your connection

The first thing here may not correlated to your case or the lib.
The api client lib supports three ways of configuration, to communicate with K8S apiserver from both inside of pod or out of cluster.

read env KUBECONFIG

read ${home}/.kube/config

read the service account resides under /var/run/secrets/kubernetes.io/serviceaccount/ca.crt

If you are using the lib inside a Pod, normally it will try to using the third way.

How you bootstrap your client.

You must keep in mind to invoke

Configuration.setDefaultApiClient(apiClient);
```

<p>before you init a CoreV1Api or your CRD api.
The reason is quite simply, because under all of the Api class, for example under
the class of io.kubernetes.client.api.CoreV1Api</p>

<pre class="lang-java prettyprint-override"><code>
public class CoreV1Api {
    private ApiClient apiClient;

    public CoreV1Api() {
        this(Configuration.getDefaultApiClient());
    }
...
}
</code>```

If you haven't set the Configuration's defaultApiClient, it will use all default config, which the basePath will be localhost:443, then you will face the error.

Under the example package, The client has already created lots of examples and use case.
The full configuration logic may be as below:

public class Example {
  public static void main(String[] args) throws IOException, ApiException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    // now you are safe to construct a CoreV1Api.
    CoreV1Api api = new CoreV1Api();
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
}
```

Just keeps in mind, order is important if you are using default constructor to init a XXXApi.

Title: Kubernetes Java Client API Exception

Body:
I am using Kubernetes Java client API https://github.com/kubernetes-client/java for fetching all namespaces present. I am Getting Error-

io.kubernetes.client.ApiException: java.net.ConnectException: Failed to connect to localhost/127.0.0.1:443
    at io.kubernetes.client.ApiClient.execute(ApiClient.java:801)
    at io.kubernetes.client.apis.CoreV1Api.listNamespaceWithHttpInfo(CoreV1Api.java:15939)
    at io.kubernetes.client.apis.CoreV1Api.listNamespace(CoreV1Api.java:15917)
    at com.cloud.kubernetes.KubernetesNamespacesAPI.fetchAllNamespaces(KubernetesNamespacesAPI.java:25)
    at com.cloud.spark.sharedvariable.ClouzerConfigurations.setKubernetesEnvironment(ClouzerConfigurations.java:45)

I tried creating cluster role binding and giving permission to the user.

Here is my code snippet:

public static List<String> fetchAllNamespaces(){
        try {
            return COREV1_API.listNamespace(null, "true", null, null, null, 0, null, Integer.MAX_VALUE, Boolean.FALSE)
                    .getItems().stream().map(v1Namespace -> v1Namespace.getMetadata().getName())
                    .collect(Collectors.toList());
        }catch(Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

Please let me know if I am missing anything. Thanks in advance.

Body:
I'm facing the same exception too.
After several survey to the client lib's source code, I think you need to make sure of two things.

first of all, can you access your api-server?

secondly, you need to check your ApiClient bootstrap order.

Which way do you use to config your connection

The first thing here may not correlated to your case or the lib.
The api client lib supports three ways of configuration, to communicate with K8S apiserver from both inside of pod or out of cluster.

read env KUBECONFIG

read ${home}/.kube/config

read the service account resides under /var/run/secrets/kubernetes.io/serviceaccount/ca.crt

If you are using the lib inside a Pod, normally it will try to using the third way.

How you bootstrap your client.

You must keep in mind to invoke

Configuration.setDefaultApiClient(apiClient);

before you init a CoreV1Api or your CRD api.
The reason is quite simply, because under all of the Api class, for example under
the class of io.kubernetes.client.api.CoreV1Api

public class CoreV1Api {
    private ApiClient apiClient;

    public CoreV1Api() {
        this(Configuration.getDefaultApiClient());
    }
...
}

If you haven't set the Configuration's defaultApiClient, it will use all default config, which the basePath will be localhost:443, then you will face the error.

Under the example package, The client has already created lots of examples and use case.
The full configuration logic may be as below:

public class Example {
  public static void main(String[] args) throws IOException, ApiException {
    ApiClient client = Config.defaultClient();
    Configuration.setDefaultApiClient(client);
    // now you are safe to construct a CoreV1Api.
    CoreV1Api api = new CoreV1Api();
    V1PodList list =
        api.listPodForAllNamespaces(null, null, null, null, null, null, null, null, null);
    for (V1Pod item : list.getItems()) {
      System.out.println(item.getMetadata().getName());
    }
  }
}

Just keeps in mind, order is important if you are using default constructor to init a XXXApi.


问:
Diff between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated
Can some one explain what's the difference between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated in angular2.

I tried to google it and read some articles, but I'm not able to understand the difference.

Below I have two components Home (home.ts) i.e. parent component and MyComp (my-comp.ts). I want to define styles in the parent that are being used in the child component.

Should I use ViewEncapsulation.Native or ViewEncapsulation.None

home.ts

```<code>import {Component, ViewEncapsulation} from 'angular2/core';
import {MyComp} from './my-comp';
@Component({
  selector: 'home',  // <home></home>
  providers: [
  ],
  directives: [
    MyComp
  ],
  styles: [`
    .parent-comp-width {
       height: 300px;
       width: 300px;
       border: 1px solid black;
     }
    `],
  template:`
    <my-comp></my-comp>
    <div class="parent-comp-width"></div>
  `,
  encapsulation: ViewEncapsulation.Native
})
export class Home {
}
</code>```

my-comp.ts

```<code>import {Component} from 'angular2/core';

@Component({
  selector: 'my-comp',  // <home></home>
  template: `
  <div class="parent-comp-width">my-comp</div>
  `
})
export class MyComp {
}
</code>```

答:
from pro-angular book:

The ViewEncapsulation Values:

Emulated: When this value is specified, Angular emulates the Shadow DOM by writting content and styles to add atrributes.This is default behaviour if no encapsulation value is specified.

If you inspect the DOM using the browser’s F12 developer tools, you will see that the contents of the external CSS file.

```<code>    ...
    <style>
    div[_ngcontent-c0] {
      background-color: lightcoral;
    }
    </style>
    ...
</code>```

The selector has been modified so that it matches div elements with      an
attribute called _ngcontent-c0 although you may see a different       name in
your browser since the name of the attribute is generated        dynamically by Angular.

To ensure that the CSS in the style element affects only the HTML elements managed by the component, the elements in the template are modified so they have the same dynamically generated attribute, like this:

```<code>...
<div _ngcontent-c0="" class="form-group">
   <label _ngcontent-c0="">Name</label>
   <input _ngcontent-c0="" class="form-control ng-untouched ng-pristineng-invalid"
        ng-reflect-name="name" name="name">
</div>
...
</code>```

Native: When this value is specified, Angular uses the browser’s shadow DOM feature. This will work only if the browser implements the shadow DOM or if you are using a polyfill.

None: When this value is specified, Angular simply adds the unmodified CSS styles to the head section of the HTML document and lets the browser figure out how to apply the styles using the normal CSS precedence rules.

The Native and None values should be used with caution. Browser support for the shadow DOM feature is so limited that using the Native option is sensible only if you are using a polyfill library that provides compatibility for other browsers.

The None option adds all the styles defined by components to the head section of the HTML document and lets the browser figure out how to apply them. This has the benefit of working in all browsers, but the results are unpredictable, and there is no isolation between the styles defined by different components.

Body:
Can some one explain what's the difference between ViewEncapsulation.Native, ViewEncapsulation.None and ViewEncapsulation.Emulated in angular2.

I tried to google it and read some articles, but I'm not able to understand the difference.

Below I have two components Home (home.ts) i.e. parent component and MyComp (my-comp.ts). I want to define styles in the parent that are being used in the child component.

Should I use ViewEncapsulation.Native or ViewEncapsulation.None

home.ts

import {Component, ViewEncapsulation} from 'angular2/core';
import {MyComp} from './my-comp';
@Component({
  selector: 'home',  // <home></home>
  providers: [
  ],
  directives: [
    MyComp
  ],
  styles: [`
    .parent-comp-width {
       height: 300px;
       width: 300px;
       border: 1px solid black;
     }
    `],
  template:`
    <my-comp></my-comp>

  `,
  encapsulation: ViewEncapsulation.Native
})
export class Home {
}

my-comp.ts

import {Component} from 'angular2/core';

@Component({
  selector: 'my-comp',  // <home></home>
  template: `

my-comp

  `
})
export class MyComp {
}

Body:
from pro-angular book:

The ViewEncapsulation Values:

Emulated: When this value is specified, Angular emulates the Shadow DOM by writting content and styles to add atrributes.This is default behaviour if no encapsulation value is specified.

If you inspect the DOM using the browser’s F12 developer tools, you will see that the contents of the external CSS file.

    ...
    <style>
    div[_ngcontent-c0] {
      background-color: lightcoral;
    }
    </style>
    ...

The selector has been modified so that it matches div elements with      an
attribute called _ngcontent-c0 although you may see a different       name in
your browser since the name of the attribute is generated        dynamically by Angular.

To ensure that the CSS in the style element affects only the HTML elements managed by the component, the elements in the template are modified so they have the same dynamically generated attribute, like this:

...
<div _ngcontent-c0="" class="form-group">
   <label _ngcontent-c0="">Name</label>
   <input _ngcontent-c0="" class="form-control ng-untouched ng-pristineng-invalid"
        ng-reflect-name="name" name="name">
</div>
...

Native: When this value is specified, Angular uses the browser’s shadow DOM feature. This will work only if the browser implements the shadow DOM or if you are using a polyfill.

None: When this value is specified, Angular simply adds the unmodified CSS styles to the head section of the HTML document and lets the browser figure out how to apply the styles using the normal CSS precedence rules.

The Native and None values should be used with caution. Browser support for the shadow DOM feature is so limited that using the Native option is sensible only if you are using a polyfill library that provides compatibility for other browsers.

The None option adds all the styles defined by components to the head section of the HTML document and lets the browser figure out how to apply them. This has the benefit of working in all browsers, but the results are unpredictable, and there is no isolation between the styles defined by different components.


问:
How to "auto-login" user in Alfresco-ADF angular 6
I'm setting up a web application, where user click on some link will take them  ADF angular 6 project which allows user to use Alfresco as shared drive . Everything is working fine except that, user has to specifically login into Alfresco ADF. As i have the credentials and do trust on all users having all permissions, can additional login page of alfresco be removed ?

I tried to customize class LoginComponent, so that i can submit form by js.

```<code>import { Component, AfterViewInit } from '@angular/core';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements AfterViewInit {
  ngAfterViewInit() {
  (<HTMLInputElement>document.getElementById('username')).value = 'admin';
  (<HTMLInputElement>document.getElementById('password')).value = 'xxxx';
  (<HTMLFormElement>document.getElementById('adf-login-form')).submit;
 }
</code>```

}

As stated before I trust all users of my application to use alfresco as shared drive. Thus no login page is required.

答: Did some R&D and found that ADF alfresco requires "ticket-ECM" in local storage of browser for login. Fetched ticket_ID from alfresco authentication rest api and passed it to frontend to store it in local session. On doing so, user no more sees login page and works as charm !!</p>

Body:
I'm setting up a web application, where user click on some link will take them  ADF angular 6 project which allows user to use Alfresco as shared drive . Everything is working fine except that, user has to specifically login into Alfresco ADF. As i have the credentials and do trust on all users having all permissions, can additional login page of alfresco be removed ?

I tried to customize class LoginComponent, so that i can submit form by js.

import { Component, AfterViewInit } from '@angular/core';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements AfterViewInit {
  ngAfterViewInit() {
  (<HTMLInputElement>document.getElementById('username')).value = 'admin';
  (<HTMLInputElement>document.getElementById('password')).value = 'xxxx';
  (<HTMLFormElement>document.getElementById('adf-login-form')).submit;
 }

}

As stated before I trust all users of my application to use alfresco as shared drive. Thus no login page is required.


问:
How to insert two docs to solr as one document
I have two documents. One document contains the name of the person, corresponding rank and the doc id, this document is in csv format. Screenshot for the same is below.

The other set of documents contains paragraphs. Here is the screenshot of an ohter set of documents, these documents are named as doc id and is in text format.

I need to insert these two as one doc in solr such that in solr I have a doc of format :

```<code>Person: arthur w cabot
KDE Rank: 5.98+108
Text: Text from the other set of documents
</code>```

How can I achieve this. Also, I would like to know if there is other approach that I can follow?

答:
In your case you can build the solr document and commit it to solr.
Something like below :

```<code>SolrInputDocument document = new SolrInputDocument();
document.addField("id", "123456");
document.addField("title", fileName);
document.addField("text", contentBuilder.toString());
solr.add(document);
solr.commit();
</code>```

In your case the fields are personName and personRank and the documentContent.
I assume that the reading of the csv file would be done from your end and you will retrieve the document name and you already know where the document is located.

As mentioned you can read the csv file, you will the data for the personName an PersonRank directly.

The third is about the field document content. As you only get the document file name, you can read the content of the document and pass it to the solr document as the third field.

I have done one option for you. Something like below :

```<code>String urlString = "http://localhost:8983/solr/TestCore";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();

StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get("D:/LogFolder/IB4_buildViewSchema.txt"),
StandardCharsets.UTF_8)) {
  stream.forEach(s -> contentBuilder.append(s).append("\n"));
  } catch (IOException e) {
    e.printStackTrace();
  }

try {
    File file = new File("D:/LogFolder/IB4_buildViewSchema.txt");
    String fileName = file.getName();
    SolrInputDocument document = new SolrInputDocument();
    document.addField("id", "123456");
    document.addField("title", fileName);
    document.addField("text", contentBuilder.toString());
    solr.add(document);
    solr.commit();
} catch (SolrServerException | IOException e) {
    e.printStackTrace();
}
</code>```

This will go in iterative mode for all the data of the csv.

Check if you can do it batches and you need to look for the optimizing the code as well.
This code is not a full proof solution for your problem.

I verified if the data is indexed in solr by querying it to solr by solr admin page.
Please refer the image below :

Note : I build a maven project and written the above piece of code. If you want you can use the below pom.xml for your reference.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>solr</groupId>
    <artifactId>TestSolr2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>TestSolr2</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>7.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-cell</artifactId>
            <version>7.6.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>
</code>```

Body:
I have two documents. One document contains the name of the person, corresponding rank and the doc id, this document is in csv format. Screenshot for the same is below.

The other set of documents contains paragraphs. Here is the screenshot of an ohter set of documents, these documents are named as doc id and is in text format.

I need to insert these two as one doc in solr such that in solr I have a doc of format :

Person: arthur w cabot
KDE Rank: 5.98+108
Text: Text from the other set of documents

How can I achieve this. Also, I would like to know if there is other approach that I can follow?

Body:
In your case you can build the solr document and commit it to solr.
Something like below :

SolrInputDocument document = new SolrInputDocument();
document.addField("id", "123456");
document.addField("title", fileName);
document.addField("text", contentBuilder.toString());
solr.add(document);
solr.commit();

In your case the fields are personName and personRank and the documentContent.
I assume that the reading of the csv file would be done from your end and you will retrieve the document name and you already know where the document is located.

As mentioned you can read the csv file, you will the data for the personName an PersonRank directly.

The third is about the field document content. As you only get the document file name, you can read the content of the document and pass it to the solr document as the third field.

I have done one option for you. Something like below :

String urlString = "http://localhost:8983/solr/TestCore";
SolrClient solr = new HttpSolrClient.Builder(urlString).build();

StringBuilder contentBuilder = new StringBuilder();
try (Stream<String> stream = Files.lines(Paths.get("D:/LogFolder/IB4_buildViewSchema.txt"),
StandardCharsets.UTF_8)) {
  stream.forEach(s -> contentBuilder.append(s).append("\n"));
  } catch (IOException e) {
    e.printStackTrace();
  }

try {
    File file = new File("D:/LogFolder/IB4_buildViewSchema.txt");
    String fileName = file.getName();
    SolrInputDocument document = new SolrInputDocument();
    document.addField("id", "123456");
    document.addField("title", fileName);
    document.addField("text", contentBuilder.toString());
    solr.add(document);
    solr.commit();
} catch (SolrServerException | IOException e) {
    e.printStackTrace();
}

This will go in iterative mode for all the data of the csv.

Check if you can do it batches and you need to look for the optimizing the code as well.
This code is not a full proof solution for your problem.

I verified if the data is indexed in solr by querying it to solr by solr admin page.
Please refer the image below :

Note : I build a maven project and written the above piece of code. If you want you can use the below pom.xml for your reference.

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>solr</groupId>
    <artifactId>TestSolr2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>TestSolr2</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.source>1.8</maven.compiler.source>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-solrj</artifactId>
            <version>7.6.0</version>
        </dependency>

        <dependency>
            <groupId>org.apache.solr</groupId>
            <artifactId>solr-cell</artifactId>
            <version>7.6.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>


问:
permission_classes doesn't work . where is problem?
I'm trying to found how Restframework's permission work , so i try write some code that response a simple Json. But the existence or absence of a permission_classes does not affect the execution of the code and endpoint will response all request without checking any permission.

here is my code:

```<code>class TeacherStatisticPost(generics.RetrieveAPIView):
    permission_classes = (ClassOwnerPermission)
    queryset = ClassRoom.objects.all()
    lookup_field = "id"
    lookup_url_kwarg = 'classRoom_id'

    def get_klass(self):
        class_id = self.kwargs['classRoom_id']
        return ClassRoom.objects.get(id=classRoom_id)

    def get(self, request, *arg, **kwargs):
        klass = self.get_klass()
        response ={
             'class_room_grade' : klass.grade,
              'class_room_name' : klass.name,
             }
        return JsonResponse(response, safe=False)
</code>```

and here is my permission.py:

```<code>class ClassOwnerPermission(permissions.BasePermission):

    def has_perm(self, user, klass):
        print("now in class perm") # never print out any thing!
        return klass.owner == user

    def has_object_permission(self, request, view, obj): # where is come from 'obj' ?
        return self.has_perm(request.user, obj)
</code>```

im try to set permission that just owner of ClassRoom can access to this endpoint.

答:
Firstly, DRF expects permission_classes to be list or tuple. permission_classes at the line permission_classes = (ClassOwnerPermission)  is not neither tuple not list. Put comma after the ClassOwnerPermission.

The line permission_classes = (ClassOwnerPermission, )  should work.

Secondly, you do not use get_object method which checks the permissions. Remove def get_klass(self): method and use get_object

Your view should look like following:

class TeacherStatisticPost(generics.RetrieveAPIView):
    permission_classes = (ClassOwnerPermission, )
    queryset = ClassRoom.objects.all()
    lookup_field = "id"
    lookup_url_kwarg = 'classRoom_id'

    def get(self, request, *arg, **kwargs):
        klass = self.get_object()
        response ={
             'class_room_grade' : klass.grade,
              'class_room_name' : klass.name,
             }
        return JsonResponse(response, safe=False)
```

Body:
I'm trying to found how Restframework's permission work , so i try write some code that response a simple Json. But the existence or absence of a permission_classes does not affect the execution of the code and endpoint will response all request without checking any permission.

here is my code:

class TeacherStatisticPost(generics.RetrieveAPIView):
    permission_classes = (ClassOwnerPermission)
    queryset = ClassRoom.objects.all()
    lookup_field = "id"
    lookup_url_kwarg = 'classRoom_id'

    def get_klass(self):
        class_id = self.kwargs['classRoom_id']
        return ClassRoom.objects.get(id=classRoom_id)

    def get(self, request, *arg, **kwargs):
        klass = self.get_klass()
        response ={
             'class_room_grade' : klass.grade,
              'class_room_name' : klass.name,
             }
        return JsonResponse(response, safe=False)

and here is my permission.py:

class ClassOwnerPermission(permissions.BasePermission):

    def has_perm(self, user, klass):
        print("now in class perm") # never print out any thing!
        return klass.owner == user

    def has_object_permission(self, request, view, obj): # where is come from 'obj' ?
        return self.has_perm(request.user, obj)

im try to set permission that just owner of ClassRoom can access to this endpoint.


问:
Adding draggable support to annotation method
I have an app that deals with mapkit and annotation and it's working fine, now I'd like to add DRAGGABLE annotation. What do I have to do to add this function? This is my annotation.m class:</p>

```<code>//
// MapDemoAnnotation.m
// MapDemo
//
// Created by Riccardo Queri on 12/01/11.
// Copyright 2011 Unipg. All rights reserved.
//

#import "MapAppAnnotation.h"

@implementation MapAppAnnotation

@synthesize coordinate=_coordinate;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate{
self = [super init];
if (self != nil) {
_coordinate = coordinate;
}
return self;
}
- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate{

}
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID{
self = [super init];
if (self != nil) {
_coordinate = coordinate;
_pinID = pinID;
}
return self;
}

- (NSString *)title {
return [NSString stringWithFormat:@"Boa %u", _pinID];
}

- (NSString *)subtitle {
return [NSString stringWithFormat:@"%.4f, %.4f", _coordinate.latitude, _coordinate.longitude];
}

@end
</code>```

答:
MKAnnotationView has draggable property..... you can use it. you can set it as per your needs.

thanks

Body:
I have an app that deals with mapkit and annotation and it's working fine, now I'd like to add DRAGGABLE annotation. What do I have to do to add this function? This is my annotation.m class:

//
// MapDemoAnnotation.m
// MapDemo
//
// Created by Riccardo Queri on 12/01/11.
// Copyright 2011 Unipg. All rights reserved.
//

#import "MapAppAnnotation.h"

@implementation MapAppAnnotation

@synthesize coordinate=_coordinate;
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate{
self = [super init];
if (self != nil) {
_coordinate = coordinate;
}
return self;
}
- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate{

}
- (id)initWithCoordinate:(CLLocationCoordinate2D)coordinate andID:(NSUInteger)pinID{
self = [super init];
if (self != nil) {
_coordinate = coordinate;
_pinID = pinID;
}
return self;
}

- (NSString *)title {
return [NSString stringWithFormat:@"Boa %u", _pinID];
}

- (NSString *)subtitle {
return [NSString stringWithFormat:@"%.4f, %.4f", _coordinate.latitude, _coordinate.longitude];
}

@end


问:
How to send FCM notification to single device from multiple devices
If application install in 10 devices then how can FCM notification will send to one of the device.</p>

答:
The easiest way to do that is to send a notification with a topic.

Subscribe the one device to a topic like that:
FirebaseMessaging.getInstance().subscribeToTopic("weather");

More information here.


问:
How to get Git Tag in Azure Pipelines
In Azure Pipelines, I have enabled git tags to trigger pipelines like so:

```<code>trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'
</code>```

Now I want to know if there is a way to determine programmatically:

Was the pipeline started from a git commit or git tag?

If the pipeline was started from a git tag, what is the tag name?

答:
When you configure the pipeline to be triggers with tag the meaning that when new tag is pushed the pipeline start to run. so:

1) The pipeline will start from the git tag.

2) I don't understand the question, if you pushed tag test so the tag name will be test.

If you want to know programmatically if the build trigger was a tag and what is the tag name you can check the environment variable Build.SourceBranch if the build is from a tag the value will be: refs/tags/tagName.

So just add a PowerShell task and print the value:

```<code>Write-Host $env:Build_SourceBranch
</code>```

Title: How to get Git Tag in Azure Pipelines

Body:
In Azure Pipelines, I have enabled git tags to trigger pipelines like so:

trigger:
  branches:
    include:
    - '*'
  tags:
    include:
    - '*'

Now I want to know if there is a way to determine programmatically:

Was the pipeline started from a git commit or git tag?

If the pipeline was started from a git tag, what is the tag name?

Body:
When you configure the pipeline to be triggers with tag the meaning that when new tag is pushed the pipeline start to run. so:

1) The pipeline will start from the git tag.

2) I don't understand the question, if you pushed tag test so the tag name will be test.

If you want to know programmatically if the build trigger was a tag and what is the tag name you can check the environment variable Build.SourceBranch if the build is from a tag the value will be: refs/tags/tagName.

So just add a PowerShell task and print the value:

Write-Host $env:Build_SourceBranch


问:
How do I make an alphabetized list of all distinct words in a file with the number of times each word was used?
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

```<code>// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.
</code>```

```<code>string lines;
getline(input, lines);      // Stores what is in file into the string
</code>```

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.

答:
It's rather simple, std::map automatically sorts based on key in the key/value pair you get. The key/value pair represents word/count which is what you need. You need to do some filtering for special characters and such.

EDIT: std::stringstream is a nice way of splitting std::string using whitespace delimiter as it's the default delimiter. Therefore, using stream >> word you will get whitespace-separated words. However, this might not be enough due to punctuation. For example: Often, has comma which we need to filter out. Therefore, I used std::replaceif which replaces puncts and digits with whitespaces.

Now a new problem arises. In your example, you have: "must.Few" which will be returned as one word. After replacing . with  we have "must Few". So I'm using another stringstream on the filtered "word" to make sure I have only words in the final result.

In the second loop you will notice if(word == "") continue;, this can happen if the string is not trimmed. If you look at the code you will find out that we aren't trimming after replacing puncts and digits. That is, "Often," will be "Often " with trailing whitespace. The trailing whitespace causes the second loop to extract an empty word. This is why I added the condition to ignore it. You can trim the filtered result and then you wouldn't need this check.

Finally, I have added ignorecase boolean to check if you wish to ignore the case of the word or not. If you wish to do so, the program will simply convert the word to lowercase and then add it to the map. Otherwise, it will add the word the same way it found it. By default, ignorecase = true, if you wish to consider case, just call the function differently: count_words(input, false);.

Edit 2: In case you're wondering, the statement counts[word] will automatically create key/value pair in the std::map IF there isn't any key matching word. So when we call ++: if the word isn't in the map, it will create the pair, and increment value by 1 so you will have newly added word. If it exists already in the map, this will increment the existing value by 1 and hence it acts as a counter.

The program:

```<code>#include <iostream>
#include <map>
#include <sstream>
#include <cstring>
#include <cctype>
#include <string>
#include <iomanip>
#include <algorithm>

std::string to_lower(const std::string& str) {
  std::string ret;
  for (char c : str)
    ret.push_back(tolower(c));
  return ret;
}

std::map<std::string, size_t> count_words(const std::string& str, bool ignorecase = true) {
  std::map<std::string, size_t> counts;

  std::stringstream stream(str);
  while (stream.good()) {
    // wordW may have multiple words connected by special chars/digits
    std::string wordW;
    stream >> wordW;
    // filter special chars and digits
    std::replace_if(wordW.begin(), wordW.end(),
      [](const char& c) { return std::ispunct(c) || std::isdigit(c); }, ' ');

    // now wordW may have multiple words seperated by whitespaces, extract them
    std::stringstream word_stream(wordW);
    while (word_stream.good()) {
      std::string word;
      word_stream >> word;
      // ignore empty words
      if (word == "") continue;
      // add to count.
      ignorecase ? counts[to_lower(word)]++ : counts[word]++;
    }
  }
  return counts;
}

void print_counts(const std::map<std::string, size_t>& counts) {
  for (auto pair : counts)
    std::cout << std::setw(15) << pair.first << " : " << pair.second << std::endl;
}

int main() {
  std::string input = "Any experienced programmer engaged in writing programs for use by others knows \
    that, once his program is working correctly, good output is a must.Few people \
    really care how much time and trouble a programmer has spent in designing and \
    debugging a program.Most people see only the results.Often, by the time a \
    programmer has finished tackling a difficult problem, any output may look \
    great.The programmer knows what it means and how to interpret it.However, \
    the same cannot be said for others, or even for the programmer himself six \
    months hence.";

  auto counts = count_words(input);
  print_counts(counts);
  return 0;
}
</code>```

I have tested this with Visual Studio 2017 and here is the part of the output:

```<code>          a : 5
        and : 3
        any : 2
         be : 1
         by : 2
     cannot : 1
       care : 1
  correctly : 1
  debugging : 1
  designing : 1
</code>```

Body:
I am writing a program using Microsoft Visual C++. In the program I must read in a text file and print out an alphabetized list of all distinct words in that file with the number of times each word was used.

I have looked up different ways to alphabetize a string but they do not work with the way I have my string initialized.

// What is inside my text file
Any experienced programmer engaged in writing programs for use by others knows
that, once his program is working correctly, good output is a must. Few people
really care how much time and trouble a programmer has spent in designing and
debugging a program. Most people see only the results. Often, by the time a
programmer has finished tackling a difficult problem, any output may look
great. The programmer knows what it means and how to interpret it. However,
the same cannot be said for others, or even for the programmer himself six
months hence.

string lines;
getline(input, lines);      // Stores what is in file into the string

I expect an alphabetized list of words with the number of times each word was used. So far, I do not know how to begin this process.

Body:
It's rather simple, std::map automatically sorts based on key in the key/value pair you get. The key/value pair represents word/count which is what you need. You need to do some filtering for special characters and such.

EDIT: std::stringstream is a nice way of splitting std::string using whitespace delimiter as it's the default delimiter. Therefore, using stream >> word you will get whitespace-separated words. However, this might not be enough due to punctuation. For example: Often, has comma which we need to filter out. Therefore, I used std::replaceif which replaces puncts and digits with whitespaces.

Now a new problem arises. In your example, you have: "must.Few" which will be returned as one word. After replacing . with  we have "must Few". So I'm using another stringstream on the filtered "word" to make sure I have only words in the final result.

In the second loop you will notice if(word == "") continue;, this can happen if the string is not trimmed. If you look at the code you will find out that we aren't trimming after replacing puncts and digits. That is, "Often," will be "Often " with trailing whitespace. The trailing whitespace causes the second loop to extract an empty word. This is why I added the condition to ignore it. You can trim the filtered result and then you wouldn't need this check.

Finally, I have added ignorecase boolean to check if you wish to ignore the case of the word or not. If you wish to do so, the program will simply convert the word to lowercase and then add it to the map. Otherwise, it will add the word the same way it found it. By default, ignorecase = true, if you wish to consider case, just call the function differently: count_words(input, false);.

Edit 2: In case you're wondering, the statement counts[word] will automatically create key/value pair in the std::map IF there isn't any key matching word. So when we call ++: if the word isn't in the map, it will create the pair, and increment value by 1 so you will have newly added word. If it exists already in the map, this will increment the existing value by 1 and hence it acts as a counter.

The program:

#include <iostream>
#include <map>
#include <sstream>
#include <cstring>
#include <cctype>
#include <string>
#include <iomanip>
#include <algorithm>

std::string to_lower(const std::string& str) {
  std::string ret;
  for (char c : str)
    ret.push_back(tolower(c));
  return ret;
}

std::map<std::string, size_t> count_words(const std::string& str, bool ignorecase = true) {
  std::map<std::string, size_t> counts;

  std::stringstream stream(str);
  while (stream.good()) {
    // wordW may have multiple words connected by special chars/digits
    std::string wordW;
    stream >> wordW;
    // filter special chars and digits
    std::replace_if(wordW.begin(), wordW.end(),
      [](const char& c) { return std::ispunct(c) || std::isdigit(c); }, ' ');

    // now wordW may have multiple words seperated by whitespaces, extract them
    std::stringstream word_stream(wordW);
    while (word_stream.good()) {
      std::string word;
      word_stream >> word;
      // ignore empty words
      if (word == "") continue;
      // add to count.
      ignorecase ? counts[to_lower(word)]++ : counts[word]++;
    }
  }
  return counts;
}

void print_counts(const std::map<std::string, size_t>& counts) {
  for (auto pair : counts)
    std::cout << std::setw(15) << pair.first << " : " << pair.second << std::endl;
}

int main() {
  std::string input = "Any experienced programmer engaged in writing programs for use by others knows \
    that, once his program is working correctly, good output is a must.Few people \
    really care how much time and trouble a programmer has spent in designing and \
    debugging a program.Most people see only the results.Often, by the time a \
    programmer has finished tackling a difficult problem, any output may look \
    great.The programmer knows what it means and how to interpret it.However, \
    the same cannot be said for others, or even for the programmer himself six \
    months hence.";

  auto counts = count_words(input);
  print_counts(counts);
  return 0;
}

I have tested this with Visual Studio 2017 and here is the part of the output:

          a : 5
        and : 3
        any : 2
         be : 1
         by : 2
     cannot : 1
       care : 1
  correctly : 1
  debugging : 1
  designing : 1


问:
Advice/ on how to plot side by side histograms with line graph going through in ggplot2
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

```<code>ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")
</code>```

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

```<code>opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))
</code>```

答:
Try the following. It uses a pre-computed data frame of the medians.

```<code>library(ggplot2)

df <- iris[c(1, 5)]
names(df) <- c("val", "rho")

med <- plyr::ddply(df, "rho", summarise, m = median(val))

ggplot(data = df, aes(x = val, fill = factor(rho))) +
  geom_histogram() +
  coord_flip() +
  geom_vline(data = med, aes(xintercept = m), colour = 'black') +
  facet_wrap(~ factor(rho))
</code>```

Body:
I'm currently finishing off my Masters project and need to include some graphics for the write-up. Without boring you too much, I have some data which is associated with AR(1) parameters ranging from 0.1 to 0.9 by 0.1 increments. As such I thought of doing a faceted histogram like the one below (worry not about the hideous fruit salad of colours, it will not be used).

I used this code.

ggplot(opt_lens_geom,aes(x=l_1024,fill=factor(rho))) + geom_histogram()+coord_flip()+facet_grid(.~rho,scales = "free_x")

I also would like to draw a trend line for the median values since the AR(1) parameter is continuous. In a later iteration I deleted the padding and made it "look" like it was one graph, but I have had issues with the endpoints matching up since each facet is a separate graphical device. Can anyone give me some advice on how to do this? I am not particularly partial to the faceting so if it is not needed I do away with it.

I will try and upload sample data, but all simulating 100 values for each of the 9 rhos would work just to get it started like:

opt_lens_geom <- data.frame(rho= rep(seq(0.1,0.9,by=0.1),each=100),l_1024=rnorm(900))

Body:
Try the following. It uses a pre-computed data frame of the medians.

library(ggplot2)

df <- iris[c(1, 5)]
names(df) <- c("val", "rho")

med <- plyr::ddply(df, "rho", summarise, m = median(val))

ggplot(data = df, aes(x = val, fill = factor(rho))) +
  geom_histogram() +
  coord_flip() +
  geom_vline(data = med, aes(xintercept = m), colour = 'black') +
  facet_wrap(~ factor(rho))


问:
How to change image size in amp-image-lightbox? (not maximizing up to window's edge)
I want to edit amp-image-lightbox's style.
I want to give padding around image.
How can I do this?
Please help me.
(I'm sorry for my poor English..)

答:
You can try adding padding to the
 tags

An example would be:

```<code><div style="padding: 10px">
    <amp-img on="tap:lightbox1"
             role="button"
             tabindex="0"
             src="/static/samples/img/Border_Collie.jpg"
             alt="Picture of a dog"
             title="Picture of a dog, view in lightbox"
             layout="responsive"
             width="300" height="246"></amp-img>
    <amp-image-lightbox id="lightbox1" layout="nodisplay"></amp-image-lightbox>
</div>
</code>```

Body:
You can try adding padding to the <div> tags

An example would be:

<div style="padding: 10px">
    <amp-img on="tap:lightbox1"
             role="button"
             tabindex="0"
             src="/static/samples/img/Border_Collie.jpg"
             alt="Picture of a dog"
             title="Picture of a dog, view in lightbox"
             layout="responsive"
             width="300" height="246"></amp-img>
    <amp-image-lightbox id="lightbox1" layout="nodisplay"></amp-image-lightbox>
</div>


问:
How to specify the folder on remote machine for backup usinf thinBackup plugin of jenkins?
I want to take the backup of jenkins confuguration in case if I lode my machine. I am using the thinBackup plugin provided by jenkins. It has an  option where I provide the path to folder where I want to take the backup.
Now the problem is I want to specify the folder on another machine, as it makes sense to have backup on different machine, how do I specifythe path to that folder? Do I have to specify as if

abc@12.34.567.890:path/to/folder?

I am new to jenkins so any help would be appreciated.

答: Thin backup performs just copies of jenkins configuration files in a specific folder for convenience. Is up to you to store it to scm or other machines, but it can be done with some simple script that upload your backup zip if exists</p>


问:
X has 67 features per sample, expected 207
I'm trying to apply a transformation to customers data without using .fit() or .fit_transform() method to re-fit the old objects, and I face this error in my code:

ValueError: X has 67 features per sample, expected 207

feat_customers = clean_data(customers)
scaler = StandardScaler()
imputer = Imputer(missing_values='NaN', strategy='most_frequent', axis=0)
# code that causes the error
customer_reduced = pca.transform(scaler.transform(imputer.transform(feat_customers)))
```

答:
It seems that 'clean_data' function is doing data-preprocessing for you. Please use this function to train your model and then apply transform after using same 'clean_data' function on the new data.

I'm trying to apply a transformation to customers data without using .fit()

The above sentence is not okay. Please check this link to exactly understand the difference between fit, fit_trnsform and transform. You may have an idea of these terminologies but as you have come up with this question it will be a good idea to revisit them once again.


问:
Which @NotNull Java annotation should I use?
I'm looking to make my code more readable as well as use tooling like IDE code inspection and/or static code analysis (FindBugs and Sonar) to avoid NullPointerExceptions.  Many of the tools seem incompatible with each others' @NotNull/@NonNull/@Nonnull annotation and listing all of them in my code would be terrible to read.  Any suggestions of which one is the 'best'?  Here is the list of equivalent annotations I've found:

javax.validation.constraints.NotNull

Created for runtime validation, not static analysis.

documentation

edu.umd.cs.findbugs.annotations.NonNull

Used by FindBugs (dead project) and its successor SpotBugs static analysis and therefore Sonar (now Sonarqube)

FindBugs documentation, SpotBugs documentation

javax.annotation.Nonnull

This might work with FindBugs too, but JSR-305 is inactive. (See also: What is the status of JSR 305?)
source

org.jetbrains.annotations.NotNull

Used by IntelliJ IDEA IDE for static analysis.

documentation

lombok.NonNull

Used to control code generation in Project Lombok.

Placeholder annotation since there is no standard.

source,
documentation

androidx.annotation.NonNull

Marker annotation available in Android, provided by annotation package

documentation

org.eclipse.jdt.annotation.NonNull

Used by Eclipse for static code analysis

documentation

答:
There are already too many answers here, but (a) it's 2019, and there's still no "standard" Nullable and (b) no other answer references Kotlin.

The reference to Kotlin is important, because Kotlin is 100% interoperable with Java and it has a core Null Safety feature. When calling Java libraries, it can take advantage of those annotations to let Kotlin tools know if a Java API can accept or return null.

As far as I know, the only Nullable packages compatible with Kotlin are org.jetbrains.annotations and android.support.annotation (now androidx.annotation). The latter is only compatible with Android so it can't be used in non-Android JVM/Java/Kotlin projects. However, the JetBrains package works everywhere.

So if you develop Java packages that should also work in Android and Kotlin (and be supported by Android Studio and IntelliJ), your best choice is probably the JetBrains package.

Maven:

```<code><dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations-java5</artifactId>
    <version>15.0</version>
</dependency>
</code>```

Gradle:

```<code>implementation 'org.jetbrains:annotations-java5:15.0'
</code>```

Body:
There are already too many answers here, but (a) it's 2019, and there's still no "standard" Nullable and (b) no other answer references Kotlin.

The reference to Kotlin is important, because Kotlin is 100% interoperable with Java and it has a core Null Safety feature. When calling Java libraries, it can take advantage of those annotations to let Kotlin tools know if a Java API can accept or return null.

As far as I know, the only Nullable packages compatible with Kotlin are org.jetbrains.annotations and android.support.annotation (now androidx.annotation). The latter is only compatible with Android so it can't be used in non-Android JVM/Java/Kotlin projects. However, the JetBrains package works everywhere.

So if you develop Java packages that should also work in Android and Kotlin (and be supported by Android Studio and IntelliJ), your best choice is probably the JetBrains package.

Maven:

<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations-java5</artifactId>
    <version>15.0</version>
</dependency>

Gradle:

implementation 'org.jetbrains:annotations-java5:15.0'


问:
extjs form post rails
i am newbie to Ext JS...I want to post Ext JS form data to server...
How am i supposed to proceed? i am using Ext JS with rails...
I have followed link : Ext JS With rails but no luck..</p>

答:
The link you provided discuss about Restful Ext JS store operations. Have a look at this simple example from the same site.

You can also make use of Netzke as mentioned by Nomad. But, I am not sure of the framework's compatibility with new version of Ext Js. If you plan to use Ext Js I would suggest you start working with Ext JS 4 straight away.

Title: extjs form post rails


问:
what is the Command To uninstall all that i have installed in react js using Node js command prompt
I just installed react, babel, web pack and redux in nodeJS command prompt and now I want to uninstall all these and wanna begin from starting. how can I do this? and what is the command to run after installing all</p>

答:
Removing a local package from your node_modules directory.

To remove a package from your node_modules directory, on the command line, use the uninstall command. Include the scope if the package is scoped.

Unscoped package

npm uninstall package_name

Scoped package

npm uninstall @scope/package_name

To remove a package from the dependencies in package.json, use the --save flag. Include the scope if the package is scoped.

npm uninstall --save package_name

if it is scoped then

npm uninstall --save @scope/package_name

hope this helps...:)


问:
Why my app opens wrong folder in filemanager dialog?
In my app I have made smth like file manager. It is based on custom dialog which has recyclerview with custom adapter. I send files list and then open folder/file.

I have two problems:

I send all folders and also folders which names start from . like .archivetemp. I don't know how to send only ordinary names without dot based. Here I send data to adapter:

```<code>fileList.clear()
fileList.addAll(root.list())
fileList.sort()

val files = root.listFiles()
Arrays.sort(files) { f1, f2 ->
    if (f1.isDirectory && !f2.isDirectory) {
        -1
    } else if (!f1.isDirectory && f2.isDirectory) {
        1
    } else {
        f1.compareTo(f2)
    }
}

fileManagerAdapter = FileManagerA(this, fileList, files)
fileManagerAdapter.notifyDataSetChanged()
fileManager.adapter = fileManagerAdapter
</code>```

at emulator I receive ordinary list without dot based folders.

Second problem - when I click an item on my phone I open the wrong folder. For example folder is placed on 10 position but I open folder which is placed on 12 position. I think that this problem is caused by sending wrong folders list but I can be wrong.

So, how I can solve this problem and where I did the mistake?

答:
You can list directory without . or hidden directory like:

For Java

```<code>//if the number of files is greater than 0, add the files and their names
for (int i = 0; i < files.length; i++) {
    if(!files[i].isHidden())
       fileList.add(files[i].getName()); // Add non hidden files
}
</code>```

For Kotlin

```<code>for (i in 0 until files.size) {
   if (!files[i].isHidden)
       fileList.add(files[i].name) // Add non hidden files
}
</code>```

Body:
In my app I have made smth like file manager. It is based on custom dialog which has recyclerview with custom adapter. I send files list and then open folder/file.

I have two problems:

I send all folders and also folders which names start from . like .archivetemp. I don't know how to send only ordinary names without dot based. Here I send data to adapter:

fileList.clear()
fileList.addAll(root.list())
fileList.sort()

val files = root.listFiles()
Arrays.sort(files) { f1, f2 ->
    if (f1.isDirectory && !f2.isDirectory) {
        -1
    } else if (!f1.isDirectory && f2.isDirectory) {
        1
    } else {
        f1.compareTo(f2)
    }
}

fileManagerAdapter = FileManagerA(this, fileList, files)
fileManagerAdapter.notifyDataSetChanged()
fileManager.adapter = fileManagerAdapter

at emulator I receive ordinary list without dot based folders.

Second problem - when I click an item on my phone I open the wrong folder. For example folder is placed on 10 position but I open folder which is placed on 12 position. I think that this problem is caused by sending wrong folders list but I can be wrong.

So, how I can solve this problem and where I did the mistake?

Body:
You can list directory without . or hidden directory like:

For Java

//if the number of files is greater than 0, add the files and their names
for (int i = 0; i < files.length; i++) {
    if(!files[i].isHidden())
       fileList.add(files[i].getName()); // Add non hidden files
}

For Kotlin

for (i in 0 until files.size) {
   if (!files[i].isHidden)
       fileList.add(files[i].name) // Add non hidden files
}


问:
module flask will not launch
project interpreter and local env IMAGEI'm having a real problem with using the module flask , I've tried a lot of the solutions here on the forum but none has worked.

I can see flask is installed
pip list - showing flask
in the setting the module flask is installed in project interpreter
when I type the code I can see the module comes up

However when I launch the code I get an error

No module named 'flask'

I've tried to re-install pycharm
I've tried to uninstall and install flask again
still the same problem. Any advice ?

The file name vsearch.py

Here is the code:

```<code>from flask import Flask, render_template, request, escape

app = Flask(__name__)

def search4words(phrase: str, letters: str) -> set:
    return set(letters).intersection(set(phrase))

def log_request(req: 'flask_request', res: str) -> None:
    with open('vsearch.log', 'a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log,
        sep='|')

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4words(phrase, letters))
    log_request(request, results)
    return render_template('results.html', the_phrase=phrase,
                           the_letters=letters, the_title=title,
                           the_results=results,)

@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html', the_title='Welcome back
    AGAIN!!!!!')

@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('vsearch.log') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                 contents[-1].append(escape(item))
    titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html',
                           the_title = 'View log',
                           the_row_titles = titles,
                           the_data = contents,)

if __name__ == '__main__' :
    app.run(debug=True)
</code>```

答:
Your issue was attempting to run vsearch.py through terminal, rather than through PyCharm's interpreter (which was correctly installed). In order to utilize the virtual environment, you should configure it to be used correctly when running your code.

There are multiple ways of activating your virtual environment, so please find that which is applicable to your project. A good source for this would be https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/26/python-virtual-env/.

Title: module flask will not launch

Body:
project interpreter and local env IMAGEI'm having a real problem with using the module flask , I've tried a lot of the solutions here on the forum but none has worked.

I can see flask is installed
pip list - showing flask
in the setting the module flask is installed in project interpreter
when I type the code I can see the module comes up

However when I launch the code I get an error

No module named 'flask'

I've tried to re-install pycharm
I've tried to uninstall and install flask again
still the same problem. Any advice ?

The file name vsearch.py

Here is the code:

from flask import Flask, render_template, request, escape

app = Flask(__name__)

def search4words(phrase: str, letters: str) -> set:
    return set(letters).intersection(set(phrase))

def log_request(req: 'flask_request', res: str) -> None:
    with open('vsearch.log', 'a') as log:
        print(req.form, req.remote_addr, req.user_agent, res, file=log,
        sep='|')

@app.route('/search4', methods=['POST'])
def do_search() -> 'html':
    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your results:'
    results = str(search4words(phrase, letters))
    log_request(request, results)
    return render_template('results.html', the_phrase=phrase,
                           the_letters=letters, the_title=title,
                           the_results=results,)

@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html', the_title='Welcome back
    AGAIN!!!!!')

@app.route('/viewlog')
def view_the_log() -> 'html':
    contents = []
    with open('vsearch.log') as log:
        for line in log:
            contents.append([])
            for item in line.split('|'):
                 contents[-1].append(escape(item))
    titles = ('Form Data', 'Remote_addr', 'User_agent', 'Results')
    return render_template('viewlog.html',
                           the_title = 'View log',
                           the_row_titles = titles,
                           the_data = contents,)

if __name__ == '__main__' :
    app.run(debug=True)