问:
Geofire and Mapbox in Android realtime location with Firebase
Let's say I have some data as follow:

```<code>{
  "rallye" : {
    "positions" : {
      "ATYFOP8lNRThzrEC83" : {
        ".priority" : "u1q04dmvuq",
        "g" : "u1q04dmvuq",
        "l" : [ -116.04463242, 19.55545101 ]
      },
      "AZYF2P8lNSThzrEC63" : {
        ".priority" : "u1q04dtcbk",
        "g" : "u1q04dtcbk",
        "l" : [ 116.045306, 17.555276 ]
      }
</code>```

in my firebase Realtime Database,

and this Android Class:

```<code>package com.sherdle.universal.rallye;

import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.os.*;

import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;

import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;

import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;

import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.SupportMapFragment;

import com.sherdle.universal.R;

import java.util.HashMap;
import java.util.Map;

public class rallye_activity extends FragmentActivity implements GeoQueryEventListener, MapboxMap.OnCameraChangeListener {

    // in welchem Suchradius sollen andere Teams auf der Karte angezeigt werden?
    private static final int TEAMSIMRADIUS = 100;
    private static final GeoLocation INITIAL_CENTER = new GeoLocation(52.543535, 8.55123);
    private static final int INITIAL_ZOOM_LEVEL = 14;
    private static final String GEO_FIRE_REF = "/rallye/positions";

    private MapboxMap map;
    private GeoFire geoFire;
    private GeoQuery geoQuery;

    private Map<String,Marker> markers;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_rallye_activity);

        Mapbox.getInstance(this, getString(R.string.mapbox_access_token));

        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.container);
        this.map = mapFragment.getMap();

        LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude, INITIAL_CENTER.longitude);
        this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, INITIAL_ZOOM_LEVEL));
        this.map.setOnCameraChangeListener(this);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/rallye/positions");
        final GeoFire geoFire = new GeoFire(ref);

        // radius in km
        this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);

        // setup markers
        this.markers = new HashMap<String, Marker>();

    }

    @Override
    protected void onStart() {
        super.onStart();
        // add an event listener to start updating locations again
        this.geoQuery.addGeoQueryEventListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // remove all event listeners to stop updating in the background
        this.geoQuery.removeAllListeners();
        for (Marker marker: this.markers.values()) {
            marker.remove();
        }
        this.markers.clear();
    }

    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        // Add a new marker to the map
        Marker marker = this.map.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
        this.markers.put(key, marker);
    }

    @Override
    public void onKeyExited(String key) {
        // Remove any old marker
        Marker marker = this.markers.get(key);
        if (marker != null) {
            marker.remove();
            this.markers.remove(key);
        }
    }

    @Override
    public void onKeyMoved(String key, GeoLocation location) {
        // Move the marker
        Marker marker = this.markers.get(key);
        if (marker != null) {
            this.animateMarkerTo(marker, location.latitude, location.longitude);
        }
    }

    @Override
    public void onGeoQueryReady() {
    }

    @Override
    public void onGeoQueryError(DatabaseError error) {
        new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage("There was an unexpected error querying GeoFire: " + error.getMessage())
                .setPositiveButton(android.R.string.ok, null)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    // Animation handler for old APIs without animation support
    private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final long DURATION_MS = 3000;
        final Interpolator interpolator = new AccelerateDecelerateInterpolator();
        final LatLng startPosition = marker.getPosition();
        handler.post(new Runnable() {
            @Override
            public void run() {
                float elapsed = SystemClock.uptimeMillis() - start;
                float t = elapsed/DURATION_MS;
                float v = interpolator.getInterpolation(t);

                double currentLat = (lat - startPosition.getLatitude()) * v + startPosition.getLatitude();
                double currentLng = (lng - startPosition.getLongitude()) * v + startPosition.getLongitude();
                marker.setPosition(new LatLng(currentLat, currentLng));

                // if animation is not finished yet, repeat
                if (t < 1) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    private double zoomLevelToRadius(double zoomLevel) {
        // Approximation to fit circle into view
        return 16384000/Math.pow(2, zoomLevel);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        // Update the search criteria for this geoQuery and the circle on the map
        LatLng center = cameraPosition.target;
        double radius = zoomLevelToRadius(cameraPosition.zoom);
        this.geoQuery.setCenter(new GeoLocation(center.getLatitude(), center.getLongitude()));
        // radius in km
        this.geoQuery.setRadius(radius/1000);
    }
}
</code>```

And this is my Layout XML

```<code><?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.mapbox.mapboxsdk.maps.SupportMapFragment"/>
</code>```

In fact: I want to show my geofire Data with multiple Markers in Realtime on this Mapbox Map.

But I get this Error

```<code>this.map = mapFragment.getMap();
</code>```

Then i use the "new" Function: getMapAsync()

```<code>this.map = mapFragment.getMapAsync(this);
</code>```

And without one of these function i get this Error:

```<code>FATAL EXCEPTION: main
Process: com.foo.bar, PID: 12380
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.foo.bar/com.sherdle.universal.rallye.rallye_activity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.transition.Scene.enter(Scene.java:175)
at com.android.internal.policy.impl.PhoneWindow.transitionTo(PhoneWindow.java:483)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:426)
at android.app.Activity.setContentView(Activity.java:2267)
at com.sherdle.universal.rallye.rallye_activity.onCreate(rallye_activity.java:54)
</code>```

答:
You are using the wrong ID to find the fragment.  The ID defined in the XML is map.  You are searching for container.

Change:

```<code>SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
    .findFragmentById(R.id.container);
</code>```

to:

```<code>SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
    .findFragmentById(R.id.map);
</code>```

Body:
Let's say I have some data as follow:

{
  "rallye" : {
    "positions" : {
      "ATYFOP8lNRThzrEC83" : {
        ".priority" : "u1q04dmvuq",
        "g" : "u1q04dmvuq",
        "l" : [ -116.04463242, 19.55545101 ]
      },
      "AZYF2P8lNSThzrEC63" : {
        ".priority" : "u1q04dtcbk",
        "g" : "u1q04dtcbk",
        "l" : [ 116.045306, 17.555276 ]
      }

in my firebase Realtime Database,

and this Android Class:

package com.sherdle.universal.rallye;

import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.os.*;

import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;

import com.firebase.geofire.GeoFire;
import com.firebase.geofire.GeoLocation;
import com.firebase.geofire.GeoQuery;
import com.firebase.geofire.GeoQueryEventListener;

import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;

import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.maps.SupportMapFragment;

import com.sherdle.universal.R;

import java.util.HashMap;
import java.util.Map;

public class rallye_activity extends FragmentActivity implements GeoQueryEventListener, MapboxMap.OnCameraChangeListener {

    // in welchem Suchradius sollen andere Teams auf der Karte angezeigt werden?
    private static final int TEAMSIMRADIUS = 100;
    private static final GeoLocation INITIAL_CENTER = new GeoLocation(52.543535, 8.55123);
    private static final int INITIAL_ZOOM_LEVEL = 14;
    private static final String GEO_FIRE_REF = "/rallye/positions";

    private MapboxMap map;
    private GeoFire geoFire;
    private GeoQuery geoQuery;

    private Map<String,Marker> markers;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_rallye_activity);

        Mapbox.getInstance(this, getString(R.string.mapbox_access_token));

        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.container);
        this.map = mapFragment.getMap();

        LatLng latLngCenter = new LatLng(INITIAL_CENTER.latitude, INITIAL_CENTER.longitude);
        this.map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLngCenter, INITIAL_ZOOM_LEVEL));
        this.map.setOnCameraChangeListener(this);

        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("/rallye/positions");
        final GeoFire geoFire = new GeoFire(ref);

        // radius in km
        this.geoQuery = this.geoFire.queryAtLocation(INITIAL_CENTER, 1);

        // setup markers
        this.markers = new HashMap<String, Marker>();

    }

    @Override
    protected void onStart() {
        super.onStart();
        // add an event listener to start updating locations again
        this.geoQuery.addGeoQueryEventListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // remove all event listeners to stop updating in the background
        this.geoQuery.removeAllListeners();
        for (Marker marker: this.markers.values()) {
            marker.remove();
        }
        this.markers.clear();
    }

    @Override
    public void onKeyEntered(String key, GeoLocation location) {
        // Add a new marker to the map
        Marker marker = this.map.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude)));
        this.markers.put(key, marker);
    }

    @Override
    public void onKeyExited(String key) {
        // Remove any old marker
        Marker marker = this.markers.get(key);
        if (marker != null) {
            marker.remove();
            this.markers.remove(key);
        }
    }

    @Override
    public void onKeyMoved(String key, GeoLocation location) {
        // Move the marker
        Marker marker = this.markers.get(key);
        if (marker != null) {
            this.animateMarkerTo(marker, location.latitude, location.longitude);
        }
    }

    @Override
    public void onGeoQueryReady() {
    }

    @Override
    public void onGeoQueryError(DatabaseError error) {
        new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage("There was an unexpected error querying GeoFire: " + error.getMessage())
                .setPositiveButton(android.R.string.ok, null)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    // Animation handler for old APIs without animation support
    private void animateMarkerTo(final Marker marker, final double lat, final double lng) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        final long DURATION_MS = 3000;
        final Interpolator interpolator = new AccelerateDecelerateInterpolator();
        final LatLng startPosition = marker.getPosition();
        handler.post(new Runnable() {
            @Override
            public void run() {
                float elapsed = SystemClock.uptimeMillis() - start;
                float t = elapsed/DURATION_MS;
                float v = interpolator.getInterpolation(t);

                double currentLat = (lat - startPosition.getLatitude()) * v + startPosition.getLatitude();
                double currentLng = (lng - startPosition.getLongitude()) * v + startPosition.getLongitude();
                marker.setPosition(new LatLng(currentLat, currentLng));

                // if animation is not finished yet, repeat
                if (t < 1) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    private double zoomLevelToRadius(double zoomLevel) {
        // Approximation to fit circle into view
        return 16384000/Math.pow(2, zoomLevel);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        // Update the search criteria for this geoQuery and the circle on the map
        LatLng center = cameraPosition.target;
        double radius = zoomLevelToRadius(cameraPosition.zoom);
        this.geoQuery.setCenter(new GeoLocation(center.getLatitude(), center.getLongitude()));
        // radius in km
        this.geoQuery.setRadius(radius/1000);
    }
}

And this is my Layout XML

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.mapbox.mapboxsdk.maps.SupportMapFragment"/>

In fact: I want to show my geofire Data with multiple Markers in Realtime on this Mapbox Map.

But I get this Error

this.map = mapFragment.getMap();

Then i use the "new" Function: getMapAsync()

this.map = mapFragment.getMapAsync(this);

And without one of these function i get this Error:

FATAL EXCEPTION: main
Process: com.foo.bar, PID: 12380
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.foo.bar/com.sherdle.universal.rallye.rallye_activity}: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2689)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2754)
at android.app.ActivityThread.access$900(ActivityThread.java:177)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1448)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
at android.view.LayoutInflater.inflate(LayoutInflater.java:483)
at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.transition.Scene.enter(Scene.java:175)
at com.android.internal.policy.impl.PhoneWindow.transitionTo(PhoneWindow.java:483)
at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:426)
at android.app.Activity.setContentView(Activity.java:2267)
at com.sherdle.universal.rallye.rallye_activity.onCreate(rallye_activity.java:54)

Body:
You are using the wrong ID to find the fragment.  The ID defined in the XML is map.  You are searching for container.

Change:

SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
    .findFragmentById(R.id.container);

to:

SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager()
    .findFragmentById(R.id.map);


来源: stackexchange

问:
Remote Debugging .NET Core Linux Docker Container - "the current source is different from the version built into .dll"

Docker

.NET Core 1.1

Visual Studio 2017

.NET Core Debugger (clrdbg)

I am receiving the following error:

```<code>"The breakpoint will not currently be hit. A copy of TokenController.cs was found in TSL.Security.Service.dll, but the current source code is different from the version built into the TSL.Security.Service.dll."
</code>```

I will got step by step how I build my .NET Core Docker image and run a Container instance from this image, and then connect remote with Visual Studio 2017, my Dockerfile.debug is at the bottom of my question:

on my docker host cd ~/repos/api.security //a git repository

git pull //pull latest code from git for .NET Core project

dotnet restore

dotnet publish //with no other args publishes with .pdbs

docker build -t tsl.api.security.image.debug -f Docker.debug .

docker run -d -p 8080:5000 -p 10222:22 --name=tsl.api.security.container.debug -t tsl.api.security.image.debug //run and map my .NET Core Webapi in Container on port 5000 to host port 8080 and map ssh in the Container, port 22, to port 10222 on the host

docker exec -it tsl.api.security.container.debug bash //terminal into running container from host

/usr/sbin/sshd //start sshd

Ok great, now that container is ready for remoting debugging, using ssh with Visual Studio 2017, on my machine with Visual Studio 2017:

pull latest code from git

open .sln with Visual Studio 2016

Build in Debug

Go to Tools -> Options -> Cross Platform and my SSH Remote:

CTRL + ALT + P //attach to process

Select Connection Type -> SSH

Select Managed (.NET Core for Unix)

And viola! We have my issue:

If we look at /app in my Docker Container we can see pdbs:

And the source code is the same, as the git pull steps in my workflow explanation demonstrates.

Not sure where to go from here...

Here is my Dockerfile.debug:

```<code># Use the standard Microsoft ASP.NET Core container
FROM microsoft/aspnetcore

# File Author / Maintainer
MAINTAINER Brian Ogden

WORKDIR /
RUN apt-get update && apt-get install -y unzip
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

#install CLRDBG, Microsoft's new cross-platform command line debugger used for debugging code running on .NET Core
RUN curl -sSL https://aka.ms/getclrdbgsh | bash /dev/stdin vs2015u2 ~/clrdbg

# Copy our code from the "/src/MyWebApi/bin/Debug/netcoreapp1.1/publish" folder to the "/app" folder in our container
WORKDIR /app
COPY ./src/TSL.Security.Service/bin/Debug/netcoreapp1.1/publish .

# Expose port 80 for the Web API traffic
ENV ASPNETCORE_URLS http://+:5000
EXPOSE 5000 22

ENTRYPOINT ["dotnet", "TSL.Security.Service.dll"]
</code>```

答:
Tools->Options->Debugging->General, turn off "Require source files to exactly match the original version". Not ideal, but at least it hits the breakpoint set in the source code in VS2017.

Please let me know once you find out how to properly fix this.

ContentLicense: CC BY-SA 3.0

Body:
Docker

.NET Core 1.1

Visual Studio 2017

.NET Core Debugger (clrdbg)

I am receiving the following error:

"The breakpoint will not currently be hit. A copy of TokenController.cs was found in TSL.Security.Service.dll, but the current source code is different from the version built into the TSL.Security.Service.dll."

I will got step by step how I build my .NET Core Docker image and run a Container instance from this image, and then connect remote with Visual Studio 2017, my Dockerfile.debug is at the bottom of my question:

on my docker host cd ~/repos/api.security //a git repository

git pull //pull latest code from git for .NET Core project

dotnet restore

dotnet publish //with no other args publishes with .pdbs

docker build -t tsl.api.security.image.debug -f Docker.debug .

docker run -d -p 8080:5000 -p 10222:22 --name=tsl.api.security.container.debug -t tsl.api.security.image.debug //run and map my .NET Core Webapi in Container on port 5000 to host port 8080 and map ssh in the Container, port 22, to port 10222 on the host

docker exec -it tsl.api.security.container.debug bash //terminal into running container from host

/usr/sbin/sshd //start sshd

Ok great, now that container is ready for remoting debugging, using ssh with Visual Studio 2017, on my machine with Visual Studio 2017:

pull latest code from git

open .sln with Visual Studio 2016

Build in Debug

Go to Tools -> Options -> Cross Platform and my SSH Remote:

CTRL + ALT + P //attach to process

Select Connection Type -> SSH

Select Managed (.NET Core for Unix)

And viola! We have my issue:

If we look at /app in my Docker Container we can see pdbs:

And the source code is the same, as the git pull steps in my workflow explanation demonstrates.

Not sure where to go from here...

Here is my Dockerfile.debug:

# Use the standard Microsoft ASP.NET Core container
FROM microsoft/aspnetcore

# File Author / Maintainer
MAINTAINER Brian Ogden

WORKDIR /
RUN apt-get update && apt-get install -y unzip
RUN apt-get install -y openssh-server
RUN mkdir /var/run/sshd
RUN echo 'root:password' | chpasswd
RUN sed -i 's/PermitRootLogin without-password/PermitRootLogin yes/' /etc/ssh/sshd_config
RUN sed 's@session\s*required\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd

ENV NOTVISIBLE "in users profile"
RUN echo "export VISIBLE=now" >> /etc/profile

#install CLRDBG, Microsoft's new cross-platform command line debugger used for debugging code running on .NET Core
RUN curl -sSL https://aka.ms/getclrdbgsh | bash /dev/stdin vs2015u2 ~/clrdbg

# Copy our code from the "/src/MyWebApi/bin/Debug/netcoreapp1.1/publish" folder to the "/app" folder in our container
WORKDIR /app
COPY ./src/TSL.Security.Service/bin/Debug/netcoreapp1.1/publish .

# Expose port 80 for the Web API traffic
ENV ASPNETCORE_URLS http://+:5000
EXPOSE 5000 22

ENTRYPOINT ["dotnet", "TSL.Security.Service.dll"]


问:
R - Apply a function based on logical vector
I have the following code, but it throws the following error:

```<code>the condition has length > 1 and only the first element will be used
</code>```

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

```<code>if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}
</code>```

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

答:
You could do this in one step using e.g. stringr::str_extract. It will return <NA> if there is no match.

```<code>library(dplyr)
library(stringr)

data <- data.frame(Survey = sample(c("it's Spring yay",
                                     "it's Summer yay",
                                     "it's Fall yay"),
                            20, replace = TRUE))

data <- data %>%
  mutate(Season = str_extract(Survey, "(Spring|Summer|Fall)"))
</code>```

Body:
I have the following code, but it throws the following error:

the condition has length > 1 and only the first element will be used

Obviously this means that I am misusing the if (condition) {action} construction, so I'm looking for a more elegant way to do this:

if (grepl("Spring", data$Survey)) {data["Season"] <- "Spring"}
if (grepl("Summer", data$Survey)) {data["Season"] <- "Summer"}
if (grepl("Fall", data$Survey)) {data["Season"] <- "Fall"}

Basically, I would like to input a logical vector, and for every TRUE, apply a function to a data set of the same length (in this case, assigning a string value to that row of a dataframe).

Body:
You could do this in one step using e.g. stringr::str_extract. It will return <NA> if there is no match.

library(dplyr)
library(stringr)

data <- data.frame(Survey = sample(c("it's Spring yay",
                                     "it's Summer yay",
                                     "it's Fall yay"),
                            20, replace = TRUE))

data <- data %>%
  mutate(Season = str_extract(Survey, "(Spring|Summer|Fall)"))


问:
VS2010 How to include files in project, to copy them to build output directory automatically during build or publish
Task is to form Visual Studio 2010 project so, that during any build or publish some foo.exe utility should be copied to output (bin) directory.

Early I have made PostBuildEvent task in .csproj (MSBuild-file):

```<code><PropertyGroup>
  <PostBuildEvent>
    Copy "$(SolutionDir)Tools\foo.exe" "$(ProjectDir)$(OutDir)foo.exe"
  </PostBuildEvent>
</PropertyGroup>
</code>```

But this is not universal. During publishing (Visual Studio 2010) foo.exe appears in bin directory, but is not copied to output publish directory. Maybe I do everything completely wrong and there is standard mechanism to include files in projects to be later, during build or publish, copied to bin?

答:
Just so my fellow neuronically impaired comrades might chance upon it here, I had assumed that, for web projects, if the linked file was an external .config file that the "output directory" would be the same directory that web.config lives in, i.e. your web project's root. In retrospect, it is entirely unsurprising that it copies the linked file into the root/bin folder.

So, if it's an appSettings include file, your web.config's open tag would be

<appSettings file=".\bin\includedAppSettingsFile.config">

Duh.

ContentLicense: CC BY-SA 2.5

Body:
Task is to form Visual Studio 2010 project so, that during any build or publish some foo.exe utility should be copied to output (bin) directory.

Early I have made PostBuildEvent task in .csproj (MSBuild-file):

<PropertyGroup>
  <PostBuildEvent>
    Copy "$(SolutionDir)Tools\foo.exe" "$(ProjectDir)$(OutDir)foo.exe"
  </PostBuildEvent>
</PropertyGroup>

But this is not universal. During publishing (Visual Studio 2010) foo.exe appears in bin directory, but is not copied to output publish directory. Maybe I do everything completely wrong and there is standard mechanism to include files in projects to be later, during build or publish, copied to bin?


问:
Java Socket read from socket in real time
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

```<code>/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}
</code>```

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush

答:
You probably need to flush the Output on the socket. Have a look at Java Flush Socket.
In your code you can call flush() on your output to force it to read the data.

Body:
I'm writing a java applet to simulate a ssh connection to ubuntu machine, I set up the connection, excute the command, and get back response, everything looks fine.
However, I had a small issue here, I want to receive server socket response in real time, so I can simulate on Applet in real time, but it seems I receive the response while the command excution is finished.
 For example, I have a test tcl file, I let the excution sleep 5 seconds between each statement, I should whoe the response on applet in every 5 seconds, instead of I get all of the response in the end.
Any thoughts?

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ssh_applet.java
 *
 * Created on 9-Dec-2010, 11:10:06 AM
 */

/**
 *
 * @author xzhang
 */
//import javax.swing.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import javax.swing.*;

public class ssh_applet extends javax.swing.JApplet{
    private String host_name = null;
    private String user_name = null;
    private String pass_word = null;
    private Connection app_conn;
    private Session app_session;
    /** Initializes the applet ssh_applet */
    public void init() {
        try {
            java.awt.EventQueue.invokeAndWait(new Runnable() {
                public void run() {
                    initComponents();
                }
            });
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    /** This method is called from within the init() method to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        ssh_input = new javax.swing.JPanel();
        connect = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        hostname = new javax.swing.JTextField();
        username = new javax.swing.JTextField();
        password = new javax.swing.JPasswordField();
        ssh_command = new javax.swing.JTextField();
        ssh_output_pannel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        ssh_output = new javax.swing.JTextArea();
        clear_text = new javax.swing.JButton();

        connect.setText("Connect");
        connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectActionPerformed(evt);
            }
        });

        jLabel1.setText("Host Name");

        jLabel2.setText("User Name");

        jLabel3.setText("Password");

        hostname.setText("10.4.0.135");

        username.setText("xzhang");

        password.setText("Samboapple0827!");

        ssh_command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ssh_commandActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_inputLayout = new javax.swing.GroupLayout(ssh_input);
        ssh_input.setLayout(ssh_inputLayout);
        ssh_inputLayout.setHorizontalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(username, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(password)
                            .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connect))
                    .addGroup(ssh_inputLayout.createSequentialGroup()
                        .addGap(49, 49, 49)
                        .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(60, Short.MAX_VALUE))
        );
        ssh_inputLayout.setVerticalGroup(
            ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_inputLayout.createSequentialGroup()
                .addGap(14, 14, 14)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(hostname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(connect))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(ssh_inputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ssh_command, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(18, Short.MAX_VALUE))
        );

        ssh_output.setColumns(20);
        ssh_output.setEditable(false);
        ssh_output.setLineWrap(true);
        ssh_output.setRows(5);
        jScrollPane1.setViewportView(ssh_output);

        clear_text.setText("Clear");
        clear_text.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clear_textActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ssh_output_pannelLayout = new javax.swing.GroupLayout(ssh_output_pannel);
        ssh_output_pannel.setLayout(ssh_output_pannelLayout);
        ssh_output_pannelLayout.setHorizontalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE)
                    .addComponent(clear_text, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        ssh_output_pannelLayout.setVerticalGroup(
            ssh_output_pannelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(ssh_output_pannelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(clear_text)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(ssh_input, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(ssh_output_pannel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(ssh_input, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(ssh_output_pannel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

    private void connectActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
                        /*get host_name*/
                    host_name=hostname.getText();
                    user_name=username.getText();
                    pass_word=password.getText();
            /* Create a connection instance */
                      app_conn=new Connection(host_name);
                      try
            {
                              app_conn.connect();
            /* Authenticate.
             * If you get an IOException saying something like
             * "Authentication method password not supported by the server at this stage."
             * then please check the FAQ.
             */
            boolean isAuthenticated = app_conn.authenticateWithPassword(user_name, pass_word);

            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");

                         JOptionPane.showMessageDialog(null, "You are connected to host "+host_name, "Connection",
                                        JOptionPane.INFORMATION_MESSAGE);
            /* Create a session */
                        }
                        catch(IOException e)
                        {}

    }

    private void ssh_commandActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        String command=ssh_command.getText();
         try
        {

        app_session=app_conn.openSession();
        app_session.execCommand( command );
            InputStream stdout = new StreamGobbler( app_session.getStdout() );
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            String line ;
            while( (line= br.readLine()) != null )
            {
                ssh_output.append( line + "\n" );
                //line = br.readLine();
            }
            // DEBUG: dump the exit code
            System.out.println( "ExitCode: " + app_session.getExitStatus() );

            // Close the session
            app_session.close();
        }
         catch(Exception e)
         {}
    }

    private void clear_textActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        ssh_output.setText("");
    }

    // Variables declaration - do not modify
    private javax.swing.JButton clear_text;
    private javax.swing.JButton connect;
    private javax.swing.JTextField hostname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPasswordField password;
    private javax.swing.JTextField ssh_command;
    private javax.swing.JPanel ssh_input;
    private javax.swing.JTextArea ssh_output;
    private javax.swing.JPanel ssh_output_pannel;
    private javax.swing.JTextField username;
    // End of variables declaration

}

Here is my code,I'm using ganymed-ssh2 library, can't get where to flush


问:
How to make a drawable Shape programmatically (Android)
i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

```<code>android:background="@drawable/myDrawableShape"
</code>```

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />
</code>```

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

```<code>void colorSet(String color)
</code>```

Thanks in advance!

答:
You can then create your Shape Drawable in Java itself using below code.</p>

```<code>public Drawable getRoundRect() {
    RoundRectShape rectShape = new RoundRectShape(new float[]{
            10, 10, 10, 10,
            10, 10, 10, 10
    }, null, null);

    ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
    shapeDrawable.getPaint().setColor(Color.parseColor("#FF0000"));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
    return shapeDrawable;
}
</code>```

Body:
i'm making a custom TextView (Java class) and i'm having trouble "to translate" the line (on "original TextView" xml)

android:background="@drawable/myDrawableShape"

to a java void to change the color of the "myDrawableShape"

myDrawableShape.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ffafafaf" />
<corners android:radius="15dp" />

I'll get the color to set from a String, the void to change the color programmatically could be (for example)

void colorSet(String color)

Thanks in advance!

Body:
You can then create your Shape Drawable in Java itself using below code.

public Drawable getRoundRect() {
    RoundRectShape rectShape = new RoundRectShape(new float[]{
            10, 10, 10, 10,
            10, 10, 10, 10
    }, null, null);

    ShapeDrawable shapeDrawable = new ShapeDrawable(rectShape);
    shapeDrawable.getPaint().setColor(Color.parseColor("#FF0000"));
    shapeDrawable.getPaint().setStyle(Paint.Style.FILL);
    shapeDrawable.getPaint().setAntiAlias(true);
    shapeDrawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
    return shapeDrawable;
}


问:
Use a variable created in a loop in other files - Ruby on Rails
I was wondering how I could use a variable that was created in a loop in other files. For example, I have this loop in my views :

```<code><% for @p in @posts %>
    <%= @p.content %>
<% end %>
</code>```

How could I use @p in a method that I created in my controller? Thank you in advance!

答:
Variable that are created in loops, are technically created inside a block. The variables that are created in a block, are accessible to that block. Please read this https://www.sitepoint.com/understanding-scope-in-ruby/

I am not sure why would anyone wants to use a variable that is created in a view in a controller, it's the reverse, YOU SHOULD use the variable that is created in the controller in views

Since you have tagged global variables in the question, if you want to use them anyways, use $p instead of @p

Body:
I was wondering how I could use a variable that was created in a loop in other files. For example, I have this loop in my views :

<% for @p in @posts %>
    <%= @p.content %>
<% end %>

How could I use @p in a method that I created in my controller? Thank you in advance!


问:
Trying to use filter function on strings
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"</p>

```<code>tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))
</code>```

答:
If you really insist to do it without explicit loops, list comprehensions or anything of that sort, you can map each element of your list to a searching function, and then filter out empty results. Something like:

```<code>def search_tweets(tweets, author):

    def search_tweet(tweet):
        tweet_fields = tweet.split('::', 2)
        return tweet_fields[0][1:] if tweet_fields[1][1:] == author else None

    return list(filter(None, map(search_tweet, tweets)))
</code>```

Then if you provide it your data and call it with the intended author, you'll get the expected result:

```<code>tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets = [tweet1, tweet19, tweet50, tweet14, tweet15]

print(search_tweets(tweets, "DanClark"))
# prints: ['1', '14']
</code>```

Btw. (opinion time) this is a bone-headed way to do it, but whatever... I've heard idiot teachers and interviewers ask for even more ridiculous things.

Body:
i have the following function and I am trying to make a list containing the 'tweet numbers' of tweets done by DanClark . I am splitting the strings and trying to use the filter function to produce it. I am trying to avoid explicit recursion. i keep getting the following error " 'str' object is not callable" when i try to run "search_tweets(tweets, "DanClark")"

tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets =   [tweet1, tweet19, tweet50, tweet14, tweet15]

def separator(tweets, item1, item2, tweeter):

part1 = (tweets[item1].split('::'))
part2 = part1[item2]
part3 = part2[1:]

  if part3 == tweeter:
      return (part1[0])[1:]
  else:
      return []

def search_tweets(tweets, tweeter):
  return list(filter((separator(tweets, 0, 1, tweeter)), tweets))

Body:
If you really insist to do it without explicit loops, list comprehensions or anything of that sort, you can map each element of your list to a searching function, and then filter out empty results. Something like:

def search_tweets(tweets, author):

    def search_tweet(tweet):
        tweet_fields = tweet.split('::', 2)
        return tweet_fields[0][1:] if tweet_fields[1][1:] == author else None

    return list(filter(None, map(search_tweet, tweets)))

Then if you provide it your data and call it with the intended author, you'll get the expected result:

tweet1 = "#1::@DanClark::The party was amazing"
tweet19 = "#19::@NatalyS::Avoid 401 Toronto area at this time"
tweet50 = "#50::@CBCNews::How Canadian captain gave her team a speech"
tweet14 = "#14::@DanClark::The food was good"
tweet15 = "#15::@DaveLin::Lucky you DanClark"
tweets = [tweet1, tweet19, tweet50, tweet14, tweet15]

print(search_tweets(tweets, "DanClark"))
# prints: ['1', '14']

Btw. (opinion time) this is a bone-headed way to do it, but whatever... I've heard idiot teachers and interviewers ask for even more ridiculous things.