The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:
new google.maps.Size(42,68)
I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(42, 68)
);
Try below solution to draw path with animation and also get time and distance between two points.
DirectionHelper.java
public class DirectionHelper {
public List<List<HashMap<String, String>>> parse(JSONObject jObject) {
List<List<HashMap<String, String>>> routes = new ArrayList<>();
JSONArray jRoutes;
JSONArray jLegs;
JSONArray jSteps;
JSONObject jDistance = null;
JSONObject jDuration = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for (int i = 0; i < jRoutes.length(); i++) {
jLegs = ((JSONObject) jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<>();
/** Traversing all legs */
for (int j = 0; j < jLegs.length(); j++) {
/** Getting distance from the json data */
jDistance = ((JSONObject) jLegs.get(j)).getJSONObject("distance");
HashMap<String, String> hmDistance = new HashMap<String, String>();
hmDistance.put("distance", jDistance.getString("text"));
/** Getting duration from the json data */
jDuration = ((JSONObject) jLegs.get(j)).getJSONObject("duration");
HashMap<String, String> hmDuration = new HashMap<String, String>();
hmDuration.put("duration", jDuration.getString("text"));
/** Adding distance object to the path */
path.add(hmDistance);
/** Adding duration object to the path */
path.add(hmDuration);
jSteps = ((JSONObject) jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for (int k = 0; k < jSteps.length(); k++) {
String polyline = "";
polyline = (String) ((JSONObject) ((JSONObject) jSteps.get(k)).get("polyline")).get("points");
List<LatLng> list = decodePoly(polyline);
/** Traversing all points */
for (int l = 0; l < list.size(); l++) {
HashMap<String, String> hm = new HashMap<>();
hm.put("lat", Double.toString((list.get(l)).latitude));
hm.put("lng", Double.toString((list.get(l)).longitude));
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
//Method to decode polyline points
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
GetPathFromLocation.java
public class GetPathFromLocation extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {
private Context context;
private String TAG = "GetPathFromLocation";
private LatLng source, destination;
private ArrayList<LatLng> wayPoint;
private GoogleMap mMap;
private boolean animatePath, repeatDrawingPath;
private DirectionPointListener resultCallback;
private ProgressDialog progressDialog;
//https://www.mytrendin.com/draw-route-two-locations-google-maps-android/
//https://www.androidtutorialpoint.com/intermediate/google-maps-draw-path-two-points-using-google-directions-google-map-android-api-v2/
public GetPathFromLocation(Context context, LatLng source, LatLng destination, ArrayList<LatLng> wayPoint, GoogleMap mMap, boolean animatePath, boolean repeatDrawingPath, DirectionPointListener resultCallback) {
this.context = context;
this.source = source;
this.destination = destination;
this.wayPoint = wayPoint;
this.mMap = mMap;
this.animatePath = animatePath;
this.repeatDrawingPath = repeatDrawingPath;
this.resultCallback = resultCallback;
}
synchronized public String getUrl(LatLng source, LatLng dest, ArrayList<LatLng> wayPoint) {
String url = "https://maps.googleapis.com/maps/api/directions/json?sensor=false&mode=driving&origin="
+ source.latitude + "," + source.longitude + "&destination=" + dest.latitude + "," + dest.longitude;
for (int centerPoint = 0; centerPoint < wayPoint.size(); centerPoint++) {
if (centerPoint == 0) {
url = url + "&waypoints=optimize:true|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
} else {
url = url + "|" + wayPoint.get(centerPoint).latitude + "," + wayPoint.get(centerPoint).longitude;
}
}
url = url + "&key=" + context.getResources().getString(R.string.google_api_key);
return url;
}
public int getRandomColor() {
Random rnd = new Random();
return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setMessage("Please wait...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
@Override
protected List<List<HashMap<String, String>>> doInBackground(String... url) {
String data;
try {
InputStream inputStream = null;
HttpURLConnection connection = null;
try {
URL directionUrl = new URL(getUrl(source, destination, wayPoint));
connection = (HttpURLConnection) directionUrl.openConnection();
connection.connect();
inputStream = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
data = stringBuffer.toString();
bufferedReader.close();
} catch (Exception e) {
Log.e(TAG, "Exception : " + e.toString());
return null;
} finally {
inputStream.close();
connection.disconnect();
}
Log.e(TAG, "Background Task data : " + data);
//Second AsyncTask
JSONObject jsonObject;
List<List<HashMap<String, String>>> routes = null;
try {
jsonObject = new JSONObject(data);
// Starts parsing data
DirectionHelper helper = new DirectionHelper();
routes = helper.parse(jsonObject);
Log.e(TAG, "Executing Routes : "/*, routes.toString()*/);
return routes;
} catch (Exception e) {
Log.e(TAG, "Exception in Executing Routes : " + e.toString());
return null;
}
} catch (Exception e) {
Log.e(TAG, "Background Task Exception : " + e.toString());
return null;
}
}
@Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
ArrayList<LatLng> points;
PolylineOptions lineOptions = null;
String distance = "";
String duration = "";
// Traversing through all the routes
for (int i = 0; i < result.size(); i++) {
points = new ArrayList<>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
if (j == 0) { // Get distance from the list
distance = (String) point.get("distance");
continue;
} else if (j == 1) { // Get duration from the list
duration = (String) point.get("duration");
continue;
}
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(8);
lineOptions.color(Color.RED);
//lineOptions.color(getRandomColor());
if (animatePath) {
final ArrayList<LatLng> finalPoints = points;
((AppCompatActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
PolylineOptions polylineOptions;
final Polyline greyPolyLine, blackPolyline;
final ValueAnimator polylineAnimator;
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : finalPoints) {
builder.include(latLng);
}
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.RED);
polylineOptions.width(8);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(ROUND);
polylineOptions.addAll(finalPoints);
greyPolyLine = mMap.addPolyline(polylineOptions);
polylineOptions = new PolylineOptions();
polylineOptions.width(8);
polylineOptions.color(Color.WHITE);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.zIndex(5f);
polylineOptions.jointType(ROUND);
blackPolyline = mMap.addPolyline(polylineOptions);
polylineAnimator = ValueAnimator.ofInt(0, 100);
polylineAnimator.setDuration(5000);
polylineAnimator.setInterpolator(new LinearInterpolator());
polylineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyLine.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polylineAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
if (repeatDrawingPath) {
List<LatLng> greyLatLng = greyPolyLine.getPoints();
if (greyLatLng != null) {
greyLatLng.clear();
}
polylineAnimator.start();
}
}
@Override
public void onAnimationCancel(Animator animation) {
polylineAnimator.cancel();
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
polylineAnimator.start();
}
});
}
Log.e(TAG, "PolylineOptions Decoded");
}
// Drawing polyline in the Google Map for the i-th route
if (resultCallback != null && lineOptions != null)
resultCallback.onPath(lineOptions, distance, duration);
}
}
DirectionPointListener
public interface DirectionPointListener {
public void onPath(PolylineOptions polyLine,String distance,String duration);
}
Now draw path using below code in your Activity
private GoogleMap mMap;
private ArrayList<LatLng> wayPoint = new ArrayList<>();
private SupportMapFragment mapFragment;
mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
@Override
public void onMapLoaded() {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
/*Add Source Marker*/
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(source);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mMap.addMarker(markerOptions);
builder.include(source);
/*Add Destination Marker*/
markerOptions = new MarkerOptions();
markerOptions.position(destination);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
mMap.addMarker(markerOptions);
builder.include(destination);
LatLngBounds bounds = builder.build();
int width = mapFragment.getView().getMeasuredWidth();
int height = mapFragment.getView().getMeasuredHeight();
int padding = (int) (width * 0.15); // offset from edges of the map 10% of screen
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
mMap.animateCamera(cu);
new GetPathFromLocation(context, source, destination, wayPoint, mMap, true, false, new DirectionPointListener() {
@Override
public void onPath(PolylineOptions polyLine, String distance, String duration) {
mMap.addPolyline(polyLine);
Log.e(TAG, "onPath :: Distance :: " + distance + " Duration :: " + duration);
binding.txtDistance.setText(String.format(" %s", distance));
binding.txtDuration.setText(String.format(" %s", duration));
}
}).execute();
}
});
}
OutPut
I hope this can help you!
Thank You.
function loadMarkers(){
{% for location in object_list %}
var point = new google.maps.LatLng({{location.latitude}},{{location.longitude}});
var marker = new google.maps.Marker({
position: point,
map: map,
url: {{location.id}},
});
google.maps.event.addDomListener(marker, 'click', function() {
window.location.href = this.url; });
{% endfor %}
You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.
we can change the icon of markers, i did it on right click event. Lets see if it works for you...
// Create a Marker
var marker = new google.maps.Marker({
position: location,
map: map,
title:'Sample Tool Tip'
});
// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
marker.setIcon('blank.png'); // set image path here...
});
function setMarkers(map,locations){
for (var i = 0; i < locations.length; i++)
{
var loan = locations[i][0];
var lat = locations[i][1];
var long = locations[i][2];
var add = locations[i][3];
latlngset = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
map: map, title: loan , position: latlngset
});
map.setCenter(marker.getPosition());
marker.content = "<h3>Loan Number: " + loan + '</h3>' + "Address: " + add;
google.maps.events.addListener(marker,'click', function(map,marker){
map.infowindow.setContent(marker.content);
map.infowindow.open(map,marker);
});
}
}
Then move var infowindow = new google.maps.InfoWindow()
to the initialize()
function:
function initialize() {
var myOptions = {
center: new google.maps.LatLng(33.890542, 151.274856),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("default"),
myOptions);
map.infowindow = new google.maps.InfoWindow();
setMarkers(map,locations)
}
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
The alternative and easier solution that i also use is to create custom marker layout and convert it into a bitmap.
view_custom_marker.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_marker_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/marker_mask">
<ImageView
android:id="@+id/profile_image"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:contentDescription="@null"
android:src="@drawable/avatar" />
</FrameLayout>
Convert this view into bitmap by using the code below
private Bitmap getMarkerBitmapFromView(@DrawableRes int resId) {
View customMarkerView = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.view_custom_marker, null);
ImageView markerImageView = (ImageView) customMarkerView.findViewById(R.id.profile_image);
markerImageView.setImageResource(resId);
customMarkerView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
customMarkerView.buildDrawingCache();
Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
canvas.drawColor(Color.WHITE, PorterDuff.Mode.SRC_IN);
Drawable drawable = customMarkerView.getBackground();
if (drawable != null)
drawable.draw(canvas);
customMarkerView.draw(canvas);
return returnedBitmap;
}
Add your custom marker in on Map ready callback.
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d(TAG, "onMapReady() called with");
mGoogleMap = googleMap;
MapsInitializer.initialize(this);
addCustomMarker();
}
private void addCustomMarker() {
Log.d(TAG, "addCustomMarker()");
if (mGoogleMap == null) {
return;
}
// adding a marker on map with image from drawable
mGoogleMap.addMarker(new MarkerOptions()
.position(mDummyLatLng)
.icon(BitmapDescriptorFactory.fromBitmap(getMarkerBitmapFromView(R.drawable.avatar))));
}
For more details please follow the link below
This format works, but it doesn't seem to be an official way of doing so
http://maps.google.com/maps?q=loc:36.26577,-92.54324
Also you may want to take a look at this. They have a few answers and seem to indicate that this is the new method:
http://maps.google.com/maps?&z=10&q=36.26577+-92.54324&ll=36.26577+-92.54324
i had a situation where i can't change old code, so added this javascript function to calculate center point and zoom level:
//input_x000D_
var tempdata = ["18.9400|72.8200-19.1717|72.9560-28.6139|77.2090"];_x000D_
_x000D_
function getCenterPosition(tempdata){_x000D_
var tempLat = tempdata[0].split("-");_x000D_
var latitudearray = [];_x000D_
var longitudearray = [];_x000D_
var i;_x000D_
for(i=0; i<tempLat.length;i++){_x000D_
var coordinates = tempLat[i].split("|");_x000D_
latitudearray.push(coordinates[0]);_x000D_
longitudearray.push(coordinates[1]);_x000D_
}_x000D_
latitudearray.sort(function (a, b) { return a-b; });_x000D_
longitudearray.sort(function (a, b) { return a-b; });_x000D_
var latdifferenece = latitudearray[latitudearray.length-1] - latitudearray[0];_x000D_
var temp = (latdifferenece / 2).toFixed(4) ;_x000D_
var latitudeMid = parseFloat(latitudearray[0]) + parseFloat(temp);_x000D_
var longidifferenece = longitudearray[longitudearray.length-1] - longitudearray[0];_x000D_
temp = (longidifferenece / 2).toFixed(4) ;_x000D_
var longitudeMid = parseFloat(longitudearray[0]) + parseFloat(temp);_x000D_
var maxdifference = (latdifferenece > longidifferenece)? latdifferenece : longidifferenece;_x000D_
var zoomvalue; _x000D_
if(maxdifference >= 0 && maxdifference <= 0.0037) //zoom 17_x000D_
zoomvalue='17';_x000D_
else if(maxdifference > 0.0037 && maxdifference <= 0.0070) //zoom 16_x000D_
zoomvalue='16';_x000D_
else if(maxdifference > 0.0070 && maxdifference <= 0.0130) //zoom 15_x000D_
zoomvalue='15';_x000D_
else if(maxdifference > 0.0130 && maxdifference <= 0.0290) //zoom 14_x000D_
zoomvalue='14';_x000D_
else if(maxdifference > 0.0290 && maxdifference <= 0.0550) //zoom 13_x000D_
zoomvalue='13';_x000D_
else if(maxdifference > 0.0550 && maxdifference <= 0.1200) //zoom 12_x000D_
zoomvalue='12';_x000D_
else if(maxdifference > 0.1200 && maxdifference <= 0.4640) //zoom 10_x000D_
zoomvalue='10';_x000D_
else if(maxdifference > 0.4640 && maxdifference <= 1.8580) //zoom 8_x000D_
zoomvalue='8';_x000D_
else if(maxdifference > 1.8580 && maxdifference <= 3.5310) //zoom 7_x000D_
zoomvalue='7';_x000D_
else if(maxdifference > 3.5310 && maxdifference <= 7.3367) //zoom 6_x000D_
zoomvalue='6';_x000D_
else if(maxdifference > 7.3367 && maxdifference <= 14.222) //zoom 5_x000D_
zoomvalue='5';_x000D_
else if(maxdifference > 14.222 && maxdifference <= 28.000) //zoom 4_x000D_
zoomvalue='4';_x000D_
else if(maxdifference > 28.000 && maxdifference <= 58.000) //zoom 3_x000D_
zoomvalue='3';_x000D_
else_x000D_
zoomvalue='1';_x000D_
return latitudeMid+'|'+longitudeMid+'|'+zoomvalue;_x000D_
}
_x000D_
You can use the strokeColor
property:
var marker = new google.maps.Marker({
id: "some-id",
icon: {
path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
strokeColor: "red",
scale: 3
},
map: map,
title: "some-title",
position: myLatlng
});
See this page for other possibilities.
Thanks to duncan answer, I end up with this:
marker.addListener('mouseover', () => infoWindow.open(map, marker))
marker.addListener('mouseout', () => infoWindow.close())
marker = new google.maps.Marker({
map:map,
// draggable:true,
// animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(59.32522, 18.07002),
icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
});
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.
What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.
Here is the JSFiddle Demo. In Google Maps API V3 it's pretty simple to track the lat and lng of a draggable marker. Let's start with the following HTML and CSS as our base.
<div id='map_canvas'></div>
<div id="current">Nothing yet...</div>
#map_canvas{
width: 400px;
height: 300px;
}
#current{
padding-top: 25px;
}
Here is our initial JavaScript initializing the google map. We create a marker that we want to drag and set it's draggable property to true. Of course keep in mind it should be attached to an onload event of your window for it to be loaded, but i'll skip to the code:
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 1,
center: new google.maps.LatLng(35.137879, -82.836914),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(47.651968, 9.478485),
draggable: true
});
Here we attach two events dragstart
to track the start of dragging and dragend
to drack when the marker stop getting dragged, and the way we attach it is to use google.maps.event.addListener
. What we are doing here is setting the div current
's content when marker is getting dragged and then set the marker's lat and lng when drag stops. Google mouse event has a property name 'latlng' that returns 'google.maps.LatLng' object when the event triggers. So, what we are doing here is basically using the identifier for this listener that gets returned by the google.maps.event.addListener
and get the property latLng
to extract the dragend's current position. Once we get that Lat Lng when the drag stops we'll display within your current
div:
google.maps.event.addListener(myMarker, 'dragend', function(evt){
document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});
google.maps.event.addListener(myMarker, 'dragstart', function(evt){
document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});
Lastly, we'll center our marker and display it on the map:
map.setCenter(myMarker.position);
myMarker.setMap(map);
Let me know if you have any questions regarding my answer.
<button class="btn" onClick="openDialog('New Type','Sample.html')">Middle</button>
<script type="text/javascript">
function openDialog(title,url) {
$('.opened-dialogs').dialog("close");
$('<div class="opened-dialogs">').html('loading...').dialog({
position: ['center',20],
open: function () {
$(this).load(url);
},
close: function(event, ui) {
$(this).remove();
},
title: title,
minWidth: 600
});
return false;
}
</script>
For JSON Post:
var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
Non-JSON:
var stringContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("field1", "value1"),
new KeyValuePair<string, string>("field2", "value2"),
});
var response = await httpClient.PostAsync("http://www.sample.com/write", stringContent);
https://blog.pedrofelix.org/2012/01/16/the-new-system-net-http-classes-message-content/
STL has a max_elements function. Here is an example: http://www.cplusplus.com/reference/algorithm/max_element/
When I open a "DOS" command prompt, I use a batch file which sets all of the options I need and adds my old-time dos utilities to the path too.
@set path=%path%;c:\utils
@doskey cd=cd/d $*
@cd \wip
@cmd.exe
The doskey line sets the CD command so that it will do both drive and folder simultaneously. If this doesn't work, it is possibly because of the version of windows that you're running.
Corrected as of 25.06.2019:
var newDate = new Date(date.setMonth(date.getMonth()+8));
Old From here:
var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009 = jan312009.setMonth(jan312009.getMonth()+8);
Your mistake is using the datetime
module instead of the date
module. You meant to do this:
from datetime import date
date = models.DateField(_("Date"), default=date.today)
If you only want to capture the current date the proper way to handle this is to use the auto_now_add
parameter:
date = models.DateField(_("Date"), auto_now_add=True)
However, the modelfield docs clearly state that auto_now_add
and auto_now
will always use the current date and are not a default value that you can override.
int is a primitive type, you can read what does mean a primitive type in java here, and a Map is an interface that has to objects as input:
public interface Map<K extends Object, V extends Object>
object means a class, and it means also that you can create an other class that exends from it, but you can not create a class that exends from int. So you can not use int variable as an object. I have tow solutions for your problem:
Map<String, Integer> map = new HashMap<>();
or
Map<String, int[]> map = new HashMap<>();
int x = 1;
//put x in map
int[] x_ = new int[]{x};
map.put("x", x_);
//get the value of x
int y = map.get("x")[0];
Starting with xdebug 3 you can use the following command line :
php -r "xdebug_info();"
And it will display useful information about your xdebug installation.
Wow, you have a huge misunderstanding how asp.net works.
This line of code
System.Diagnostics.Process.Start("help/AdminTutorial.html");
Will not redirect a admin user to a new site, but start a new process on the server (usually a browser, IE) and load the site. That is for sure not what you want.
A very easy solution would be to change the href attribute of the link in you page_load method.
Your aspx code:
<a href="#" runat="server" id="myLink">Tutorial</a>
Your codebehind / cs code of page_load:
...
if (userinfo.user == "Admin")
{
myLink.Attributes["href"] = "help/AdminTutorial.html";
}
else
{
myLink.Attributes["href"] = "help/otherSite.html";
}
...
Don't forget to check the Admin rights again on "AdminTutorial.html" to "prevent" hacking.
I feel only very few approaches here doesn't risk the prospect OP the most worry (Marc Gravell, Stevo3000, Richard Szalay, Neil, Darren Koppand) and most are unnecessarily complex. Being fully aware this is useless micro-optimization, let me say you should basically employ these:
1) Don't read the value from DataReader/DataRow twice - so either cache it before null checks and casts/conversions or even better directly pass your record[X]
object to a custom extension method with appropriate signature.
2) To obey the above, do not use built in IsDBNull
function on your DataReader/DataRow since that calls the record[X]
internally, so in effect you will be doing it twice.
3) Type comparison will be always slower than value comparison as a general rule. Just do record[X] == DBNull.Value
better.
4) Direct casting will be faster than calling Convert
class for converting, though I fear the latter will falter less.
5) Lastly, accessing record by index rather than column name will be faster again.
I feel going by the approaches of Szalay, Neil and Darren Koppand will be better. I particularly like Darren Koppand's extension method approach which takes in IDataRecord
(though I would like to narrow it down further to IDataReader
) and index/column name.
Take care to call it:
record.GetColumnValue<int?>("field");
and not
record.GetColumnValue<int>("field");
in case you need to differentiate between 0
and DBNull
. For example, if you have null values in enum fields, otherwise default(MyEnum)
risks first enum value being returned. So better call record.GetColumnValue<MyEnum?>("Field")
.
Since you're reading from a DataRow
, I would create extension method for both DataRow
and IDataReader
by DRYing common code.
public static T Get<T>(this DataRow dr, int index, T defaultValue = default(T))
{
return dr[index].Get<T>(defaultValue);
}
static T Get<T>(this object obj, T defaultValue) //Private method on object.. just to use internally.
{
if (obj.IsNull())
return defaultValue;
return (T)obj;
}
public static bool IsNull<T>(this T obj) where T : class
{
return (object)obj == null || obj == DBNull.Value;
}
public static T Get<T>(this IDataReader dr, int index, T defaultValue = default(T))
{
return dr[index].Get<T>(defaultValue);
}
So now call it like:
record.Get<int>(1); //if DBNull should be treated as 0
record.Get<int?>(1); //if DBNull should be treated as null
record.Get<int>(1, -1); //if DBNull should be treated as a custom value, say -1
I believe this is how it should have been in the framework (instead of the record.GetInt32
, record.GetString
etc methods) in the first place - no run-time exceptions and gives us the flexibility to handle null values.
From my experience I had less luck with one generic method to read from the database. I always had to custom handle various types, so I had to write my own GetInt
, GetEnum
, GetGuid
, etc. methods in the long run. What if you wanted to trim white spaces when reading string from db by default, or treat DBNull
as empty string? Or if your decimal should be truncated of all trailing zeroes. I had most trouble with Guid
type where different connector drivers behaved differently that too when underlying databases can store them as string or binary. I have an overload like this:
static T Get<T>(this object obj, T defaultValue, Func<object, T> converter)
{
if (obj.IsNull())
return defaultValue;
return converter == null ? (T)obj : converter(obj);
}
With Stevo3000's approach, I find the calling a bit ugly and tedious, and it will be harder to make a generic function out of it.
If you value your time, buy a Mac! I don't know enough about Linux development options to offer a viable solution, but it seems the proposed methods involve some pretty roundabout work. If you plan on seriously writing and selling iPhone apps, I think you could easily recoup the cost of a Mac Mini or Macbook. :-)
In Python the passing by reference or by value has to do with what are the actual objects you are passing.So,if you are passing a list for example,then you actually make this pass by reference,since the list is a mutable object.Thus,you are passing a pointer to the function and you can modify the object (list) in the function body.
When you are passing a string,this passing is done by value,so a new string object is being created and when the function terminates it is destroyed. So it all has to do with mutable and immutable objects.
Pawel Sawicz .NET blog has a real good explanation and example code, explaining how to call the library;
GET:
var client = new RestClient("192.168.0.1");
var request = new RestRequest("api/item/", Method.GET);
var queryResult = client.Execute<List<Items>>(request).Data;
POST:
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/", Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddBody(new Item
{
ItemName = someName,
Price = 19.99
});
client.Execute(request);
DELETE:
var item = new Item(){//body};
var client = new RestClient("http://192.168.0.1");
var request = new RestRequest("api/item/{id}", Method.DELETE);
request.AddParameter("id", idItem);
client.Execute(request)
The RestSharp GitHub page has quite an exhaustive sample halfway down the page. To get started install the RestSharp NuGet package in your project, then include the necessary namespace references in your code, then above code should work (possibly negating your need for a full example application).
If you're using jq and trying to remove the quotes from the result, the other answers will work, but there's a better way. By using the -r
option, you can output the result with no quotes.
$ echo '{"foo": "bar"}' | jq '.foo'
"bar"
$ echo '{"foo": "bar"}' | jq -r '.foo'
bar
shouldn't the button be 100% width if it's "display: block"
No. That just means it's the only thing in the space vertically (assuming you aren't using another trick to force something else there as well). It doesn't mean it has to fill up the width of that space.
I think your problem in this instance is that the input
is not natively a block element. Try nesting it inside another div and set the margin on that. But I don't have an IE8 browser to test this with at the moment, so it's just a guess.
I solved this by looking at this comment on JBIDE-11655 : deleting all .project, .settings and .classpath in my projects folder.
Swift 3.0
i had the same problem, i found on the documentation Apple this solution.
let numbers = [1, 2, 3, 4]
let addTwo: (Int, Int) -> Int = { x, y in x + y }
let numberSum = numbers.reduce(0, addTwo)
// 'numberSum' == 10
But, in my case i had a list of object, then i needed transform my value of my list:
let numberSum = self.list.map({$0.number_here}).reduce(0, { x, y in x + y })
this work for me.
Rails 6 added an upsert
and upsert_all
methods that deliver this functionality.
Model.upsert(column_name: value)
[upsert] It does not instantiate any models nor does it trigger Active Record callbacks or validations.
Not if you are looking for an "upsert" (where the database executes an update or an insert statement in the same operation) type of statement. Out of the box, Rails and ActiveRecord have no such feature. You can use the upsert gem, however.
Otherwise, you can use: find_or_initialize_by
or find_or_create_by
, which offer similar functionality, albeit at the cost of an additional database hit, which, in most cases, is hardly an issue at all. So unless you have serious performance concerns, I would not use the gem.
For example, if no user is found with the name "Roger", a new user instance is instantiated with its name
set to "Roger".
user = User.where(name: "Roger").first_or_initialize
user.email = "[email protected]"
user.save
Alternatively, you can use find_or_initialize_by
.
user = User.find_or_initialize_by(name: "Roger")
In Rails 3.
user = User.find_or_initialize_by_name("Roger")
user.email = "[email protected]"
user.save
You can use a block, but the block only runs if the record is new.
User.where(name: "Roger").first_or_initialize do |user|
# this won't run if a user with name "Roger" is found
user.save
end
User.find_or_initialize_by(name: "Roger") do |user|
# this also won't run if a user with name "Roger" is found
user.save
end
If you want to use a block regardless of the record's persistence, use tap
on the result:
User.where(name: "Roger").first_or_initialize.tap do |user|
user.email = "[email protected]"
user.save
end
Use its value directly:
In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]:
array([[ 0.98836259, 0.82403141],
[ 0.337358 , 0.02054435],
[ 0.29271728, 0.37813099],
[ 0.70033513, 0.69919695]])
Its simple :)
<link rel="icon" href="{{ asset('favicon.ico')}}" type="image/x-icon" />
Try using the key
keyword with sorted()
.
sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)], key=lambda x: x[1])
key
should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1]
.
For optimization, see jamylak's response using itemgetter(1)
, which is essentially a faster version of lambda x: x[1]
.
In the following shell commands existing-dir
is a directory whose contents match the tracked files in the repo-to-clone
git repository.
# Clone just the repository's .git folder (excluding files as they are already in
# `existing-dir`) into an empty temporary directory
git clone --no-checkout repo-to-clone existing-dir/existing-dir.tmp # might want --no-hardlinks for cloning local repo
# Move the .git folder to the directory with the files.
# This makes `existing-dir` a git repo.
mv existing-dir/existing-dir.tmp/.git existing-dir/
# Delete the temporary directory
rmdir existing-dir/existing-dir.tmp
cd existing-dir
# git thinks all files are deleted, this reverts the state of the repo to HEAD.
# WARNING: any local changes to the files will be lost.
git reset --hard HEAD
I'd like to add my thoughts since I had exactly the same problem.
I was using UITextView
since it had nicer text alignment (justify, which at the time was not available in UILabel
), but in order to "simulate" non-interactive-non-scrollable UILabel
, I'd switch off completely scrolling, bouncing, and user interaction.
Of course, problem was that text was dynamic, and while width would be fixed, height should be recalculated every time I'd set new text value.
boundingRectWithSize
didn't work well for me at all, from what I could see, UITextView
was adding some margin on top which boundingRectWithSize
would not get into a count, hence, height retrieved from boundingRectWithSize
was smaller than it should be.
Since text was not to be updated rapidly, it's just used for some information that may update every 2-3 seconds the most, I've decided following approach:
/* This f is nested in a custom UIView-inherited class that is built using xib file */
-(void) setTextAndAutoSize:(NSString*)text inTextView:(UITextView*)tv
{
CGFloat msgWidth = tv.frame.size.width; // get target's width
// Make "test" UITextView to calculate correct size
UITextView *temp = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, msgWidth, 300)]; // we set some height, really doesn't matter, just put some value like this one.
// Set all font and text related parameters to be exact as the ones in targeted text view
[temp setFont:tv.font];
[temp setTextAlignment:tv.textAlignment];
[temp setTextColor:tv.textColor];
[temp setText:text];
// Ask for size that fits :P
CGSize tv_size = [temp sizeThatFits:CGSizeMake(msgWidth, 300)];
// kill this "test" UITextView, it's purpose is over
[temp release];
temp = nil;
// apply calculated size. if calcualted width differs, I choose to ignore it anyway and use only height because I want to have width absolutely fixed to designed value
tv.frame = CGRectMake(tv.frame.origin.x, tv.frame.origin.y, msgWidth, tv_size.height );
}
*Above code is not directly copied from my source, I had to adjust it / clear it from bunch of other stuff not needed for this article. Don't take it for copy-paste-and-it-will-work-code.
Obvious disadvantage is that it has alloc and release, for each call.
But, advantage is that you avoid depending on compatibility between how boundingRectWithSize draws text and calculates it's size and implementation of text drawing in UITextView
(or UILabel
which also you can use just replace UITextView
with UILabel
). Any "bugs" that Apple may have are this way avoided.
P.S. It would seem that you shouldn't need this "temp" UITextView
and can just ask sizeThatFits
directly from target, however that didn't work for me. Though logic would say it should work and alloc/release of temporary UITextView
are not needed, it did not. But this solution worked flawlessly for any text I would set in.
This is a highly inefficient way of doing it. You can use the merge
statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.
MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
UPDATE SET l.studName = s.studName
WHERE l.studName != s.studName
WHEN NOT MATCHED THEN
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)
Make sure you commit
, once completed, in order to be able to see this in the database.
To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.
It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.
However, as I say this will not be as efficient as merge
.
declare
cursor c_data is
select b.rowid as rid, a.studId, a.studName
from student a
left outer join studLoad b
on a.studId = b.studId
and a.studName <> b.studName
;
type t__data is table of c_data%rowtype index by binary_integer;
t_data t__data;
begin
open c_data;
loop
fetch c_data bulk collect into t_data limit 10000;
exit when t_data.count = 0;
for idx in t_data.first .. t_data.last loop
if t_data(idx).rid is null then
insert into studLoad (studId, studName)
values (t_data(idx).studId, t_data(idx).studName);
else
update studLoad
set studName = t_data(idx).studName
where rowid = t_data(idx).rid
;
end if;
end loop;
end loop;
close c_data;
end;
/
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Can't* believe this question has existed for 9 years without anyone suggesting a simple recursive function:
from datetime import datetime, timedelta
def walk_days(start_date, end_date):
if start_date <= end_date:
print(start_date.strftime("%Y-%m-%d"))
next_date = start_date + timedelta(days=1)
walk_days(next_date, end_date)
#demo
start_date = datetime(2009, 5, 30)
end_date = datetime(2009, 6, 9)
walk_days(start_date, end_date)
Output:
2009-05-30
2009-05-31
2009-06-01
2009-06-02
2009-06-03
2009-06-04
2009-06-05
2009-06-06
2009-06-07
2009-06-08
2009-06-09
Edit: *Now I can believe it -- see Does Python optimize tail recursion? . Thank you Tim.
You just try this, Its so easy
<script>
$("#YourDropDownId").change(function () {
alert($("#YourDropDownId").val());
});
</script>
What is X
? If it is a 2D-array, how can you then compare its row to a number: i < 3
?
EDIT after OP's comment:
A = array([[0, 1, 2], [0, 2, 0]])
X = array([[0, 1, 2], [1, 2, 0], [2, 1, 2], [3, 2, 0]])
add to A
all rows from X
where the first element < 3
:
import numpy as np
A = np.vstack((A, X[X[:,0] < 3]))
# returns:
array([[0, 1, 2],
[0, 2, 0],
[0, 1, 2],
[1, 2, 0],
[2, 1, 2]])
Some answers mentioned using 'splice', which did as Chance Smith said mutated the array. I would suggest you to use the Method call 'slice' (Document for 'slice' is here) which make a copy of the original array.
From Interface Builder (Storyboard/XIB):
Programmatically:
SWift 4
Using label extension
extension UILabel {
// Pass value for any one of both parameters and see result
func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {
guard let labelText = self.text else { return }
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineSpacing
paragraphStyle.lineHeightMultiple = lineHeightMultiple
let attributedString:NSMutableAttributedString
if let labelattributedText = self.attributedText {
attributedString = NSMutableAttributedString(attributedString: labelattributedText)
} else {
attributedString = NSMutableAttributedString(string: labelText)
}
// Line spacing attribute
attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
Now call extension function
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) . // try values 1.0 to 5.0
// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0
Or using label instance (Just copy & execute this code to see result)
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))
label.attributedText = attrString
Swift 3
let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString
font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")
Another way to look at it is to consider git rebase master
as:
Rebase the current branch on top of
master
Here , 'master
' is the upstream branch, and that explain why, during a rebase, ours
and theirs
are reversed.
I implemented dispatchTouchEvent in Activity to do this:
private EditText mEditText;
private Rect mRect = new Rect();
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
int[] location = new int[2];
mEditText.getLocationOnScreen(location);
mRect.left = location[0];
mRect.top = location[1];
mRect.right = location[0] + mEditText.getWidth();
mRect.bottom = location[1] + mEditText.getHeight();
int x = (int) ev.getX();
int y = (int) ev.getY();
if (action == MotionEvent.ACTION_DOWN && !mRect.contains(x, y)) {
InputMethodManager input = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
input.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
}
return super.dispatchTouchEvent(ev);
}
and I tested it, works perfect!
You're setting the global git options, but the local checkout possibly has overrides set. Try setting them again with git config --local <setting> <value>
. You can look at the .git/config
file in your local checkout to see what local settings the checkout has defined.
Is
is not the same as =
-- Is
compares the references, whilst =
will compare the values.
If you're using v2 of the .Net Framework (or later), there is the IsNot
operator which will do the right thing, and read more naturally.
In Laravel 5, there is a .env
file,
It looks like
APP_ENV=local
APP_DEBUG=true
APP_KEY=YOUR_API_KEY
DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync
MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
Edit that .env There is .env.sample is there , try to create from that if no such .env file found.
Fastest way to clone an Array of Objects will be using spread operator
var clonedArray=[...originalArray]
but the objects inside that cloned array will still pointing at the old memory location. hence change to clonedArray objects will also change the orignalArray.
var clonedArray = originalArray.map(({...ele}) => {return ele})
this will not only create new array but also the objects will be cloned to.
With version 2.0 Firebug introduced an Events panel, which lists all events for the element currently selected within the HTML panel.
It can also display event listeners wrapped into jQuery event bindings in case the option Show Wrapped Listeners is checked, which you can reach via the Events panel's options menu.
With that panel the workflow to debug an event handler is as follows:
=> The script execution will stop at the first line of the event handler function and you can step debug it.
Here is a simple example:
ThreadTest.java
public class ThreadTest
{
public static void main(String [] args)
{
MyThread t1 = new MyThread(0, 3, 300);
MyThread t2 = new MyThread(1, 3, 300);
MyThread t3 = new MyThread(2, 3, 300);
t1.start();
t2.start();
t3.start();
}
}
MyThread.java
public class MyThread extends Thread
{
private int startIdx, nThreads, maxIdx;
public MyThread(int s, int n, int m)
{
this.startIdx = s;
this.nThreads = n;
this.maxIdx = m;
}
@Override
public void run()
{
for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
{
System.out.println("[ID " + this.getId() + "] " + i);
}
}
}
And some output:
[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23
An explanation - Each MyThread
object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1
does index 0, 3, 6, 9, etc.
Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:
MyThread.java
System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();
And the output:
[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7
Now you can see each thread executing, giving up control early, and the next executing.
You do it through an IIFE (immediately invoked function expression):
var incr = (function () {
var i = 1;
return function () {
return i++;
}
})();
incr(); // returns 1
incr(); // returns 2
I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.
Swal.fire({
title: 'A cool title',
icon: 'info',
confirmButtonText: 'Log in'
}).then((result) => {
if (result['isConfirmed']){
// Put your function here
}
})
Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.
You can use this construct:
export class AppComponent {
title:string;
myHero:string;
heroes: any[];
constructor() {
this.title = 'Tour of Heros';
this.heroes=['Windstorm','Bombasto','Magneta','Tornado']
this.myHero = this.heroes[0];
}
}
I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering
Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date
'You said time1 doesn't change, so I left it in a singe cell.
'If that is not correct, you will have to play with this some more.
time1 = Range("A6").Value
'Looping through each of our output cells.
For Each t In Range("B7:E9") 'Change these to match your real ranges.
'Looping through each departure date/time.
'(Only one row in your example. This can be adjusted if needed.)
For Each x In Range("B2:E2") 'Change these to match your real ranges.
'Check to see if our dep time corresponds to
'the matching column in our output
If t.Column = x.Column Then
'If it does, then check to see what our time value is
If x > 0 Then
time2 = x.Value
'Apply the change to the output cell.
t.Value = time1 - time2
'Exit out of this loop and move to the next output cell.
Exit For
End If
End If
'If the columns don't match, or the x value is not a time
'then we'll move to the next dep time (x)
Next x
Next t
End Sub
EDIT
I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).
A B C D E
1 LOAD_NUMBER 1 2 3 4
2 DEPARTURE_TIME_DATE 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 19:30 11/12/2011 20:00
4 Dry_Refrig 7585.1 0 10099.8 16700
6 1/4/2012 19:30
Using the sub I got this output:
A B C D E
7 Friday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
8 Saturday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
9 Thursday 1272:00:00 1272:00:00 1272:00:00 1271:30:00
UPDATE: Take a look at @Joey's answer: Git now supports the **
syntax in patterns. Both approaches should work fine.
The gitignore(5) man page states:
Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.
What this means is that the patterns in a .gitignore
file in any given directory of your repo will affect that directory and all subdirectories.
The pattern you provided
/public/static/**/*.js
isn't quite right, firstly because (as you correctly noted) the **
syntax is not used by Git. Also, the leading /
anchors that pattern to the start of the pathname. (So, /public/static/*.js
will match /public/static/foo.js
but not /public/static/foo/bar.js
.) Removing the leading EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out)./
won't work either, matching paths like public/static/foo.js
and foo/public/static/bar.js
.
As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore
and include just this pattern:
*.js
There is no leading /
, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static
directory and its subdirectories.
For Sql Server 2017 and later you can use the new STRING_AGG
function
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql
The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.
SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv FROM Person.Person;
Here is the result set.
John,N/A,Mike,Peter,N/A,N/A,Alice,Bob
Perhaps a more common use case is to group together and then aggregate, just like you would with SUM
, COUNT
or AVG
.
SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags
FROM dbo.Article AS a
LEFT JOIN dbo.ArticleTag AS t
ON a.ArticleId = t.ArticleId
GROUP BY a.articleId, title;
p = Project{...}
fmt.Printf("%+v", p)
fmt.Printf("%#v", p) //with type
The following works as expected:
SELECT Diff = CASE DATEDIFF(HOUR, StartTime, EndTime)
WHEN 0 THEN CAST(DATEDIFF(MINUTE, StartTime, EndTime) AS VARCHAR(10))
ELSE CAST(60 - DATEPART(MINUTE, StartTime) AS VARCHAR(10)) +
REPLICATE(',60', DATEDIFF(HOUR, StartTime, EndTime) - 1) +
+ ',' + CAST(DATEPART(MINUTE, EndTime) AS VARCHAR(10))
END
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
To get 24 columns, you could use 24 case expressions, something like:
SELECT [0] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 0
THEN DATEDIFF(MINUTE, StartTime, EndTime)
ELSE 60 - DATEPART(MINUTE, StartTime)
END,
[1] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 1
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 1 THEN 60
END,
[2] = CASE WHEN DATEDIFF(HOUR, StartTime, EndTime) = 2
THEN DATEPART(MINUTE, EndTime)
WHEN DATEDIFF(HOUR, StartTime, EndTime) > 2 THEN 60
END -- ETC
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('10:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) t (StartTime, EndTime);
The following also works, and may end up shorter than repeating the same case expression over and over:
WITH Numbers (Number) AS
( SELECT ROW_NUMBER() OVER(ORDER BY t1.N) - 1
FROM (VALUES (1), (1), (1), (1), (1), (1)) AS t1 (N)
CROSS JOIN (VALUES (1), (1), (1), (1)) AS t2 (N)
), YourData AS
( SELECT StartTime, EndTime
FROM (VALUES
(CAST('11:15' AS TIME), CAST('13:15' AS TIME)),
(CAST('09:45' AS TIME), CAST('18:59' AS TIME)),
(CAST('10:45' AS TIME), CAST('11:59' AS TIME))
) AS t (StartTime, EndTime)
), PivotData AS
( SELECT t.StartTime,
t.EndTime,
n.Number,
MinuteDiff = CASE WHEN n.Number = 0 AND DATEDIFF(HOUR, StartTime, EndTime) = 0 THEN DATEDIFF(MINUTE, StartTime, EndTime)
WHEN n.Number = 0 THEN 60 - DATEPART(MINUTE, StartTime)
WHEN DATEDIFF(HOUR, t.StartTime, t.EndTime) <= n.Number THEN DATEPART(MINUTE, EndTime)
ELSE 60
END
FROM YourData AS t
INNER JOIN Numbers AS n
ON n.Number <= DATEDIFF(HOUR, StartTime, EndTime)
)
SELECT *
FROM PivotData AS d
PIVOT
( MAX(MinuteDiff)
FOR Number IN
( [0], [1], [2], [3], [4], [5],
[6], [7], [8], [9], [10], [11],
[12], [13], [14], [15], [16], [17],
[18], [19], [20], [21], [22], [23]
)
) AS pvt;
It works by joining to a table of 24 numbers, so the case expression doesn't need to be repeated, then rolling these 24 numbers back up into columns using PIVOT
I have been waiting to see if Google would open a Keep API. When I discovered Google Tasks, and saw that it had an Android app, web app, and API, I converted over to Tasks. This may not directly answer your question, but it is my solution to the Keep API problem.
Tasks doesn't have a reminder alarm exactly like Keep. I can live without that if I also connect with the Calendar API.
SELECT ID from bugs WHERE user=Me ORDER BY CREATED_STAMP DESC; BY CREATED_STAMP DESC fetches those data at index first which last created.
I hope it will resolve your problem
You'll find the answer by typing ?rm
rm(data_1, data_2, data_3)
Solution based on Ashish answer with Java
private void setUI(){
mainToolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(mainToolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_messaging, R.id.nav_me)
.setDrawerLayout(drawer)
.build();
navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.addOnDestinationChangedListener(navDestinationChange);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
private NavController.OnDestinationChangedListener navDestinationChange = new NavController.OnDestinationChangedListener(){
@Override
public void onDestinationChanged(@NonNull NavController controller, @NonNull NavDestination destination, @Nullable Bundle arguments) {
if(R.id.nav_home==destination.getId()){
destination.setLabel("News");
}
}
};
With hours, 0-padding minutes and seconds:
var ms = 298999;
var d = new Date(1000*Math.round(ms/1000)); // round to nearest second
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
console.log(str); // 0:04:59
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
Your original rewrite should almost work. I'm not sure why it would be redirecting, but I think what you really want is just
rewrite ^ /base.html break;
You should be able to put that in a location or directly in the server.
I had given permissions I shouldn't have to write in some folders (especially /usr/bin/), and that caused the problem. I fixed it by opening Disk Utility and running 'Repair Disk Permissions' on the Macintosh HD disk.
When working with 4 large Db2 tables I have not only found the limit but it caused me to look really bad to a boss who thought that I could append all four tables (each with over 900,000 rows) to one large table. the real life result was that regardless of how many times I tried the Table (which had exactly 34 columns - 30 text and 3 integer) would spit out some cryptic message "Cannot open database unrecognized format or the file may be corrupted". Bottom Line is Less than 1,500,000 records and just a bit more than 1,252,000 with 34 rows.
This should be fine:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string bool_cast(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
int main() {
cout << bool_cast(true) << "\n";
cout << bool_cast(false) << "\n";
}
You can also delete cookies without using jquery.cookie plugin:
document.cookie = 'NAMEOFYOURCOOKIE' + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
some problem, but I find the solution, this is :
2 February Feb 28 (29 in leap years)
this is my code
public string GetCountArchiveByMonth(int iii)
{
// iii: is number of months, use any number other than (**2**)
con.Open();
SqlCommand cmd10 = con.CreateCommand();
cmd10.CommandType = CommandType.Text;
cmd10.CommandText = "select count(id_post) from posts where dateadded between CONVERT(VARCHAR, @start, 103) and CONVERT(VARCHAR, @end, 103)";
cmd10.Parameters.AddWithValue("@start", "" + iii + "/01/2019");
cmd10.Parameters.AddWithValue("@end", "" + iii + "/30/2019");
string result = cmd10.ExecuteScalar().ToString();
con.Close();
return result;
}
now for test
lbl1.Text = GetCountArchiveByMonth(**7**).ToString(); // here use any number other than (**2**)
**
because of check
**February**
is maxed 28 days,
**
Binary releases contain computer readable version of the application, meaning it is compiled. Source releases contain human readable version of the application, meaning it has to be compiled before it can be used.
Parsing is about READING data in one format, so that you can use it to your needs.
I think you need to teach them to think like this. So, this is the simplest way I can think of to explain parsing for someone new to this concept.
Generally, we try to parse data one line at a time because generally it is easier for humans to think this way, dividing and conquering, and also easier to code.
We call field to every minimum undivisible data. Name is field, Age is another field, and Surname is another field. For example.
In a line, we can have various fields. In order to distinguish them, we can delimit fields by separators or by the maximum length assign to each field.
For example: By separating fields by comma
Paul,20,Jones
Or by space (Name can have 20 letters max, age up to 3 digits, Jones up to 20 letters)
Paul 020Jones
Any of the before set of fields is called a record.
To separate between a delimited field record we need to delimit record. A dot will be enough (though you know you can apply CR/LF).
A list could be:
Michael,39,Jordan.Shaquille,40,O'neal.Lebron,24,James.
or with CR/LF
Michael,39,Jordan
Shaquille,40,O'neal
Lebron,24,James
You can say them to list 10 nba (or nlf) players they like. Then, they should type them according to a format. Then make a program to parse it and display each record. One group, can make list in a comma-separated format and a program to parse a list in a fixed size format, and viceversa.
You could use
https://github.com/slightfoot/flutter_after_layout
which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)
Which is basically
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => yourFunction(context));
}
I have one same Warning caused to com.google.gms:google-services.
The solution is to upgrade classpath com.google.gms:google-services to classpath 'com.google.gms:google-services:3.2.0' in file in build.gradle Project:
buildscript {
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:3.2.0'
}
}
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
In Android Studio verion 3.1 dependencies complie word is replaced to implementation
dependencies with Warning in android studio 3.1
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:27.1.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
dependencies OK in android studio 3.1
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
Gradel generate by Android Studio 3.1 for new project.
Visit https://docs.gradle.org/current/userguide/dependency_management_for_java_projects.html
For details https://docs.gradle.org/current/userguide/declaring_dependencies.html
Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.
The error says that the parameter needed to the concerned breaking function is not in the required format i.e. string or Buffer
The solution is to change the parameter to string
breakingFunction(JSON.stringify(offendingParameter), ... other params...);
or buffer
breakingFunction(BSON.serialize(offendingParameter), ... other params...);
I solved this problem using @Kjuly's answer and the specific line:
"The reason failed to build might be that, the project does not support the architecture of the device you connected."
With Xcode loaded it automatically set my iPad app to iPad Air
This caused the dependancy analysis error.
Changing the device type immediately solved the issue:
I don't know why this works but this is a very quick answer which saved me a lot of fiddling around in the background and instantly got the app working to test. I would never have thought that this could be a thing and something so simple would fix it but in this case it did.
I was having this issue when trying to add a project reference, and after a lot of searching and trying many of the things above, my build configuration and outputs were correct.
I finally just deleted the \bin and \obj folders from the source and referencing project.
Honestly I believe it was the obj
folder not containing the correct metadata or corrupted metadata.
All is fixed now.
This was with Visual Studio 2015 - .NET 4.6 projects.
UPDATE:
The above worked on the first build, but on subsequent builds it failed, so I ended up recreating the solution file, and removing and reading the NuGet packages that were referenced incorrectly in my project files which pointed to the incorrect hint path.
That seemed to have fixed it thus far on subsequent builds.
<ItemGroup>
<Reference Include="Antlr3.Runtime, Version=3.5.0.2, Culture=neutral, PublicKeyToken=eb42632606e9261f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
</Reference>
</ItemGroup>
Take a look at the Java standard API doc. Right next to LinkedHashMap
, there is a LinkedHashSet
. But note that the order in those is the insertion order, not the natural order of the elements. And you can only iterate in that order, not do random access (except by counting iteration steps).
There is also an interface SortedSet
implemented by TreeSet
and ConcurrentSkipListSet
. Both allow iteration in the natural order of their elements or a Comparator
, but not random access or insertion order.
For a data structure that has both efficient access by index and can efficiently implement the set criterium, you'd need a skip list, but there is no implementation with that functionality in the Java Standard API, though I am certain it's easy to find one on the internet.
In JavaScript, there are truthy and falsy expressions. If you want to check if the property is undefined or not, there is a straight way of using an if condition as given,
if(!ob.someProp){
console.log('someProp is falsy')
}
However, there are several more approaches to check the object has property or not, but it seems long to me. Here are those.
=== undefined
check in if
conditionif(ob.someProp === undefined){
console.log('someProp is undefined')
}
typeof
typeof
acts as a combined check for the value undefined and for whether a variable exists.
if(typeof ob.someProp === 'undefined'){
console.log('someProp is undefined')
}
hasOwnProperty
methodThe JavaScript object has built in the hasOwnProperty
function in the object prototype.
if(!ob.hasOwnProperty('someProp')){
console.log('someProp is undefined')
}
Not going in deep, but the 1st way looks shortened and good to me. Here are the details on truthy/falsy values in JavaScript and undefined
is the falsy value listed in there. So the if
condition behaves normally without any glitch. Apart from the undefined
, values NaN
, false
(Obviously), ''
(empty string) and number 0
are also the falsy values.
Warning: Make sure the property value does not contain any falsy value, otherwise the
if
condition will return false. For such a case, you can use thehasOwnProperty
method
Depending on the situation you can check with isinstance
what kind of object you have, and then use the corresponding attributes. With the introduction of abstract base classes in Python 2.6/3.0 this approach has also become much more powerful (basically ABCs allow for a more sophisticated way of duck typing).
One situation were this is useful would be if two different objects have an attribute with the same name, but with different meaning. Using only hasattr
might then lead to strange errors.
One nice example is the distinction between iterators and iterables (see this question). The __iter__
methods in an iterator and an iterable have the same name but are semantically quite different! So hasattr
is useless, but isinstance
together with ABC's provides a clean solution.
However, I agree that in most situations the hasattr
approach (described in other answers) is the most appropriate solution.
If this folder is the first in the command then it won't work with a space in the folder name, so replace the space in the folder name with an underscore.
Try this command:
Dism.exe /online /enable-feature /featurename:NetFX3 /Source:I:\Sources\sxs /LimitAccess
I:
partition of your Windows DVD.
You can use text
method:
$(function(){
$(".pushme").click(function () {
$(this).text(function(i, text){
return text === "PUSH ME" ? "DON'T PUSH ME" : "PUSH ME";
})
});
})
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
Assuming your array is sorted (like the one you posted) you could simply iterate over the array and count the longest segment of elements, it's something like @narek.gevorgyan's post but without the awfully big array, and it uses the same amount of memory regardless of the array's size:
private static int getMostPopularElement(int[] a){
int counter = 0, curr, maxvalue, maxcounter = -1;
maxvalue = curr = a[0];
for (int e : a){
if (curr == e){
counter++;
} else {
if (counter > maxcounter){
maxcounter = counter;
maxvalue = curr;
}
counter = 0;
curr = e;
}
}
if (counter > maxcounter){
maxvalue = curr;
}
return maxvalue;
}
public static void main(String[] args) {
System.out.println(getMostPopularElement(new int[]{1,2,3,4,5,6,7,7,7,7}));
}
If the array is not sorted, sort it with Arrays.sort(a);
np.array()
is even more powerful than what unutbu said above.
You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:
aArray=np.array([1,1,1])
bArray=np.array([2,2,2])
aList=[aArray, bArray]
xArray=np.array(aList)
xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.
From the OP:
I finally reinstalled it from Java for OS X 2013-005. It solved this issue.
This is discouraged (if you want to create/distribute a clean Docker image), since the PATH
variable is set by /etc/profile
script, the value can be overridden.
head /etc/profile
:
if [ "`id -u`" -eq 0 ]; then
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH
At the end of the Dockerfile, you could add:
RUN echo "export PATH=$PATH" > /etc/environment
So PATH is set for all users.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
if(Context.Session!= null)
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = (Context.Session["culture"] ?? (Context.Session["culture"] = new CultureInfo("pt-BR"))) as CultureInfo;
}
It's used to add padding in UIScrollView
Without contentInset
, a table view is like this:
Then set contentInset
:
tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
The effect is as below:
Seems to be better, right?
And I write a blog to study the contentInset
, criticism is welcome.
At any channel page with "user" url for example http://www.youtube.com/user/klauskkpm
, without API call, from YouTube UI, click a video of the channel (in its "VIDEOS" tab) and click the channel name on the video. Then you can get to the page with its "channel" url for example https://www.youtube.com/channel/UCfjTOrCPnAblTngWAzpnlMA
.
You do not need to call d.keys()
, so
if key not in d:
d[key] = value
is enough. There is no clearer, more readable method.
You could update again with dict.get()
, which would return an existing value if the key is already present:
d[key] = d.get(key, value)
but I strongly recommend against this; this is code golfing, hindering maintenance and readability.
You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status and if it is from web server it returns the status)
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
For device file readuing use this:
readTextFile("file:///C:/your/path/to/file.txt");
For file reading from server use:
readTextFile("http://test/file.txt");
This is my UIImage extension and you can directly use changeTintColor function for an image.
extension UIImage {
func changeTintColor(color: UIColor) -> UIImage {
var newImage = self.withRenderingMode(.alwaysTemplate)
UIGraphicsBeginImageContextWithOptions(self.size, false, newImage.scale)
color.set()
newImage.draw(in: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height))
newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
func changeColor(color: UIColor) -> UIImage {
let backgroundSize = self.size
UIGraphicsBeginImageContext(backgroundSize)
guard let context = UIGraphicsGetCurrentContext() else {
return self
}
var backgroundRect = CGRect()
backgroundRect.size = backgroundSize
backgroundRect.origin.x = 0
backgroundRect.origin.y = 0
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
context.setFillColor(red: red, green: green, blue: blue, alpha: alpha)
context.translateBy(x: 0, y: backgroundSize.height)
context.scaleBy(x: 1.0, y: -1.0)
context.clip(to: CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height),
mask: self.cgImage!)
context.fill(backgroundRect)
var imageRect = CGRect()
imageRect.size = self.size
imageRect.origin.x = (backgroundSize.width - self.size.width) / 2
imageRect.origin.y = (backgroundSize.height - self.size.height) / 2
context.setBlendMode(.multiply)
context.draw(self.cgImage!, in: imageRect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
Example usage like this
let image = UIImage(named: "sample_image")
imageView.image = image.changeTintColor(color: UIColor.red)
And you can use change changeColor
function to change the image color
If you're:
One option is scripting the terminal itself if your use case is more app monitoring / management.
For example I recently did the following. Granted it's Mac specific, iTerm specific, and relies on a deprecated Apple Script API (iTerm has a newer Python option). It doesn't win any elegance awards but gets the job done.
#!/bin/sh
root_path="~/root-path"
auth_api_script="$root_path/auth-path/auth-script.sh"
admin_api_proj="$root_path/admin-path/admin.csproj"
agent_proj="$root_path/agent-path/agent.csproj"
dashboard_path="$root_path/dashboard-web"
osascript <<THEEND
tell application "iTerm"
set newWindow to (create window with default profile)
tell current session of newWindow
set name to "Auth API"
write text "pushd $root_path && $auth_api_script"
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Admin API"
write text "dotnet run --debug -p $admin_api_proj"
end tell
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Agent"
write text "dotnet run --debug -p $agent_proj"
end tell
end tell
tell newWindow
set newTab to (create tab with default profile)
tell current session of newTab
set name to "Dashboard"
write text "pushd $dashboard_path; ng serve -o"
end tell
end tell
end tell
THEEND
Here's an update for those looking for a tidyverse method to extract hh:mm::ss.sssss from a POSIXct object. Note that time zone is not included in the output.
library(hms)
as_hms(times)
You can have a look at Eclipse color theme, also which has a hell of a lot of options for customizing font, background color, etc.
A bit 'lazy' way to do this is to use startswith
- it is easier to understand this rather regexps. However regexps might work faster, I haven't measured.
>>> papa = "papa is a good man"
>>> app = "app is important"
>>> strip_word = 'papa'
>>> papa[len(strip_word):] if papa.startswith(strip_word) else papa
' is a good man'
>>> app[len(strip_word):] if app.startswith(strip_word) else app
'app is important'
You could try this:
$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
$scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)
This way you can save the data for later use and acces it by using an ng-repeat like this:
<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>
I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.
The abs() in the while condition is needed, since, well, it controls the number of iterations (how would you define a negative number of iterations?). You can correct it by inverting the sign of the result if numb
is negative.
So this is the modified version of your code. Note I replaced the while loop with a cleaner for loop.
#get user input of numbers as variables
numa, numb = input("please give 2 numbers to multiply seperated with a comma:")
#standing variables
total = 0
#output the total
for count in range(abs(numb)):
total += numa
if numb < 0:
total = -total
print total
Maybe you can use float:right;:
.one {_x000D_
padding-left: 1em;_x000D_
text-color: white;_x000D_
display:inline; _x000D_
}_x000D_
.two {_x000D_
background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="row">_x000D_
<h3 class="one">Text</h3>_x000D_
<button class="btn btn-secondary pull-right">Button</button>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The below code is correct answer for me.
$('#datetimepicker6').datetimepicker({
format : 'YYYY-MM-DD HH:mm'
});
You are really asking a couple of questions here:
1) Why does the price of SSL certificates vary so much
2) Where can I get good, cheap SSL certificates?
The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).
You can read more on this subject here
For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.
People run into this error when the Node.js process is still running and they are attempting to start the server again. Try this:
ps aux | grep node
This will print something along the lines of:
user 7668 4.3 1.0 42060 10708 pts/1 Sl+ 20:36 0:00 node server
user 7749 0.0 0.0 4384 832 pts/8 S+ 20:37 0:00 grep --color=auto node
In this case, the process will be the one with the pid 7668. To kill it and restart the server, run kill -9 7668
.
I just had this exact same problem. This will sound crazy but if someone sees this try this before drastic measures. delete method signature:
public static void main(String args[])
(Not the body of your main just method declaration)
Save your project then re-write the method's header back onto its respective body. Save again and re-run. That worked for me but if it doesn't work try again but clean project right before re-running.
I don't know how this fixed it but it did. Worth a shot before recreating your whole project right?
The XML document:
<Home>
<Addr>
<Street>ABC</Street>
<Number>5</Number>
<Comment>BLAH BLAH BLAH <br/><br/>ABC</Comment>
</Addr>
</Home>
The XPath expression:
//*[contains(text(), 'ABC')]
//*
matches any descendant element of the root node. That is, any element but the root node.
[...]
is a predicate, it filters the node-set. It returns nodes for which ...
is true
:
A predicate filters a node-set [...] to produce a new node-set. For each node in the node-set to be filtered, the PredicateExpr is evaluated [...]; if PredicateExpr evaluates to true for that node, the node is included in the new node-set; otherwise, it is not included.
contains('haystack', 'needle')
returns true
if haystack
contains needle
:
Function: boolean contains(string, string)
The contains function returns true if the first argument string contains the second argument string, and otherwise returns false.
But contains()
takes a string as its first parameter. And it's passed nodes. To deal with that every node or node-set passed as the first parameter is converted to a string by the string()
function:
An argument is converted to type string as if by calling the string function.
string()
function returns string-value
of the first node:
A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned.
string-value
of an element node:
The string-value of an element node is the concatenation of the string-values of all text node descendants of the element node in document order.
string-value
of a text node:
The string-value of a text node is the character data.
So, basically string-value
is all text that is contained in a node (concatenation of all descendant text nodes).
text()
is a node test that matches any text node:
The node test text() is true for any text node. For example, child::text() will select the text node children of the context node.
Having that said, //*[contains(text(), 'ABC')]
matches any element (but the root node), the first text node of which contains ABC
. Since text()
returns a node-set that contains all child text nodes of the context node (relative to which an expression is evaluated). But contains()
takes only the first one. So for the document above the path matches the Street
element.
The following expression //*[text()[contains(., 'ABC')]]
matches any element (but the root node), that has at least one child text node, that contains ABC
. .
represents the context node. In this case, it's a child text node of any element but the root node. So for the document above the path matches the Street
, and the Comment
elements.
Now then, //*[contains(., 'ABC')]
matches any element (but the root node) that contains ABC
(in the concatenation of the descendant text nodes). For the document above it matches the Home
, the Addr
, the Street
, and the Comment
elements. As such, //*[contains(., 'BLAH ABC')]
matches the Home
, the Addr
, and the Comment
elements.
inefficient solution:
As of version 0.8.6 of Android Studio generating an APK file (signed and I believe unsigned, too) will be placed inside ProjectName/device/build/outputs/apk
For example, I am making something for Google Glass and my signed APK gets dropped in /Users/MyName/AndroidStudioProjects/HelloGlass/glass/build/outputs/apk
Daemon threads are killed ungracefully so any finalizer instructions are not executed. A possible solution is to check is main thread is alive instead of infinite loop.
E.g. for Python 3:
while threading.main_thread().isAlive():
do.you.subthread.thing()
gracefully.close.the.thread()
See Check if the Main Thread is still alive from another thread.
I'm here in general only to find out that through dict it is necessary to work inside setattr XD
The JLS specifies a break is an abnormal termination of a loop. However, just because it is considered abnormal does not mean that it is not used in many different code examples, projects, products, space shuttles, etc. The JVM specification does not state either an existence or absence of a performance loss, though it is clear code execution will continue after the loop.
However, code readability can suffer with odd breaks. If you're sticking a break in a complex if statement surrounded by side effects and odd cleanup code, with possibly a multilevel break with a label(or worse, with a strange set of exit conditions one after the other), it's not going to be easy to read for anyone.
If you want to break your loop by forcing the iteration variable to be outside the iteration range, or by otherwise introducing a not-necessarily-direct way of exiting, it's less readable than break
.
However, looping extra times in an empty manner is almost always bad practice as it takes extra iterations and may be unclear.
Instead of any Array
you can load your data in DataTable
like:
using System.Data;
DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
using (var command = new SqlCommand("SELECT col1,col2" +
{
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
dt.Load(dr);
}
}
}
You can also use SqlDataAdapater
to fill your DataTable like
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
Later you can iterate each row and compare like:
foreach (DataRow dr in dt.Rows)
{
if (dr.Field<string>("col1") == "yourvalue") //your condition
{
}
}
$("#closeLink").click(closeIt);
Let's say you want to call your function passing some args to it i.e., closeIt(1, false)
. Then, you should build an anonymous function and call closeIt
from it.
$("#closeLink").click(function() {
closeIt(1, false);
});
2015 update with dplyr:
df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]
dive percentage
1 dive1 0.4777462
2 dive2 0.6726483
Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)
var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
// do something
}
Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.
You could use isnull
function to get both null
and empty values of a text field:
SELECT * FROM myTable
WHERE isnull(my_nullable_text_field,'') = ''
in Ubuntu system try to run below command:
sudo php artisan cache:clear
sudo php artisan view:clear
sudo php artisan config:cache
temperature = input("What's the current temperature in your city? (please use the format ??C or ???F) >>> ")
### warning... the result from input will <str> on Python 3.x only
### in the case of Python 2.x, the result from input is the variable type <int>
### for the <str> type as the result for Python 2.x it's neccessary to use the another: raw_input()
temp_int = int(temperature[:-1]) # 25 <int> (as example)
temp_str = temperature[-1:] # "C" <str> (as example)
if temp_str.lower() == 'c':
print("Your temperature in Fahrenheit is: {}".format( (9/5 * temp_int) + 32 ) )
elif temp_str.lower() == 'f':
print("Your temperature in Celsius is: {}".format( ((5/9) * (temp_int - 32)) ) )
I recall running a program that was creating a huge amount of files at the output. The files were sorted at 30000 per directory. I do not recall having any read problems when I had to reuse the produced output. It was on an 32-bit Ubuntu Linux laptop, and even Nautilus displayed the directory contents, albeit after a few seconds.
ext3 filesystem: Similar code on a 64-bit system dealt well with 64000 files per directory.
the return statement exits from the current function and exit() exits from the program
they are the same when used in main() function
also return is a statement while exit() is a function which requires stdlb.h header file
Yes you can use setValue to set value for edit/update purpose.
this.personalform.setValue({
name: items.name,
address: {
city: items.address.city,
country: items.address.country
}
});
You can refer http://musttoknow.com/use-angular-reactive-form-addinsert-update-data-using-setvalue-setpatch/ to understand how to use Reactive forms for add/edit feature by using setValue. It saved my time
If you don't care about the number of occurrences, I would approach it like this. Using hash sets will give you better performance than simple iteration.
var set1 = new HashSet<MyType>(list1);
var set2 = new HashSet<MyType>(list2);
return set1.SetEquals(set2);
This will require that you have overridden .GetHashCode()
and implemented IEquatable<MyType>
on MyType
.
As far as I understand, the question is NOT about recursion. We can easily call main
method of another class in your class. Following example illustrates static and calling by object. Note omission of word static
in Class2
class Class1{
public static void main(String[] args) {
System.out.println("this is class 1");
}
}
class Class2{
public void main(String[] args) {
System.out.println("this is class 2");
}
}
class MyInvokerClass{
public static void main(String[] args) {
System.out.println("this is MyInvokerClass");
Class2 myClass2 = new Class2();
Class1.main(args);
myClass2.main(args);
}
}
Output Should be:
this is wrapper class
this is class 1
this is class 2
I had a similar problem on OSX but tried to play around with double and single quotes. For your case, you could try something like this
$query = 'SELECT * FROM "sf_bands"'; // NOTE: double quotes on "sf_Bands"
For the parent: display: table;
For the child: display: table-cell;
Then add vertical-align: middle;
I can make a fiddle but home time now, yay!
OK here is the lovely fiddle: http://jsfiddle.net/lharby/AJAhR/
.parent {
display:table;
}
.child {
display:table-cell;
vertical-align:middle;
text-align:center;
}
If you're using MacPorts, the path is
/opt/local/share/java/gradle
While I agree with the results given, they didn't work for me. If your Table has a name this will work:
Public Sub GetCountOfResults(WorkSheetName As String, TableName As String)
Dim rnData As Range
Dim rngArea As Range
Dim lCount As Long
Set rnData = ThisWorkbook.Worksheets(WorkSheetName).ListObjects(TableName).Range
With rnData
For Each rngArea In .SpecialCells(xlCellTypeVisible).Areas
lCount = lCount + rngArea.Rows.Count
Next
MsgBox "Autofilter " & lCount - 1 & " records"
End With
Set rnData = Nothing
lCount = Empty
End Sub
This is modified to work with ListObjects from an original version I found here:
1) Underlying Data Structure
The first difference between ArrayList and LinkedList comes with the fact that ArrayList is backed by Array while LinkedList is backed by LinkedList. This will lead to further differences in performance.
2) LinkedList implements Deque
Another difference between ArrayList and LinkedList is that apart from the List interface, LinkedList also implements Deque interface, which provides first in first out operations for add()
and poll()
and several other Deque functions. 3) Adding elements in ArrayList Adding element in ArrayList is O(1) operation if it doesn't trigger re-size of Array, in which case it becomes O(log(n)), On the other hand, appending an element in LinkedList is O(1) operation, as it doesn't require any navigation.
4) Removing an element from a position
In order to remove an element from a particular index e.g. by calling remove(index)
, ArrayList performs a copy operation which makes it close to O(n) while LinkedList needs to traverse to that point which also makes it O(n/2), as it can traverse from either direction based upon proximity.
5) Iterating over ArrayList or LinkedList
Iteration is the O(n) operation for both LinkedList and ArrayList where n is a number of an element.
6) Retrieving element from a position
The get(index)
operation is O(1) in ArrayList while its O(n/2) in LinkedList, as it needs to traverse till that entry. Though, in Big O notation O(n/2) is just O(n) because we ignore constants there.
7) Memory
LinkedList uses a wrapper object, Entry, which is a static nested class for storing data and two nodes next and previous while ArrayList just stores data in Array.
So memory requirement seems less in the case of ArrayList than LinkedList except for the case where Array performs the re-size operation when it copies content from one Array to another.
If Array is large enough it may take a lot of memory at that point and trigger Garbage collection, which can slow response time.
From all the above differences between ArrayList vs LinkedList, It looks ArrayList is the better choice than LinkedList in almost all cases, except when you do a frequent add()
operation than remove()
, or get()
.
It's easier to modify a linked list than ArrayList, especially if you are adding or removing elements from start or end because linked list internally keeps references of those positions and they are accessible in O(1) time.
In other words, you don't need to traverse through the linked list to reach the position where you want to add elements, in that case, addition becomes O(n) operation. For example, inserting or deleting an element in the middle of a linked list.
In my opinion, use ArrayList over LinkedList for most of the practical purpose in Java.
This is possible in Python 2 using
execfile("test2.py")
See the documentation for the handling of namespaces, if important in your case.
In Python 3, this is possible using (thanks to @fantastory)
exec(open("test2.py").read())
However, you should consider using a different approach; your idea (from what I can see) doesn't look very clean.
if(is_array($EMailArr)){
foreach($EMailArr as $key => $value){
$R_ID = (int) $value['R_ID'];
$email = mysql_real_escape_string( $value['email'] );
$name = mysql_real_escape_string( $value['name'] );
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
mysql_query($sql) or exit(mysql_error());
}
}
A better example solution with PDO:
$q = $sql->prepare("INSERT INTO `email_list`
SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");
foreach($EMailArr as $value){
$q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
}
Use repr() and The difference between using repr and str
Using repr
:
>>> try:
... print(x)
... except Exception as e:
... print(repr(e))
...
NameError("name 'x' is not defined")
Using str
:
>>> try:
... print(x)
... except Exception as e:
... print(str(e))
...
name 'x' is not defined
no , there is nothing similar IndexOf for Dictionary although you can make use of ContainsKey method to get whether a key belongs to dictionary or not
Although already over a year old, I stumbled across this question a couple of times on other Google search and I believe I can improve on the previous answer for the benefit of others.
Short answer is you cannot combine both action in one line, but you can create a chain that does what you want and then call it in a one liner.
Let's create a chain to log and accept:
iptables -N LOG_ACCEPT
And let's populate its rules:
iptables -A LOG_ACCEPT -j LOG --log-prefix "INPUT:ACCEPT:" --log-level 6
iptables -A LOG_ACCEPT -j ACCEPT
Now let's create a chain to log and drop:
iptables -N LOG_DROP
And let's populate its rules:
iptables -A LOG_DROP -j LOG --log-prefix "INPUT:DROP: " --log-level 6
iptables -A LOG_DROP -j DROP
Now you can do all actions in one go by jumping (-j) to you custom chains instead of the default LOG / ACCEPT / REJECT / DROP:
iptables -A <your_chain_here> <your_conditions_here> -j LOG_ACCEPT
iptables -A <your_chain_here> <your_conditions_here> -j LOG_DROP
A bit late in the game but just in case it helps anyone.
If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).
The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.
I got the url above from PayPal's tech support.
Tested using a simple Hosted button and IPN. Good luck.
A break
statement results in the termination of the statement to which it applies (switch
, for
, do
, or while
).
A continue
statement is used to end the current loop iteration and return control to the loop statement.
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
Here's my answer using glob without filter if you want to read files with a certain extension in date order (Python 3).
dataset_path='/mydir/'
files = glob.glob(dataset_path+"/morepath/*.extension")
files.sort(key=os.path.getmtime)
How about like this:
PriorityQueue<Integer> queue = new PriorityQueue<>(10, Collections.reverseOrder());
queue.offer(1);
queue.offer(2);
queue.offer(3);
//...
Integer val = null;
while( (val = queue.poll()) != null) {
System.out.println(val);
}
The Collections.reverseOrder()
provides a Comparator
that would sort the elements in the PriorityQueue
in a the oposite order to their natural order in this case.
I'm going to begin this answer with an illustration:
var colours = ['red', 'green', 'blue'];
document.getElementById('element').addEventListener('click', function() {
// this is a reference to the element clicked on
var that = this;
colours.forEach(function() {
// this is undefined
// that is a reference to the element clicked on
});
});
My answer originally demonstrated this with jQuery, which is only very slightly different:
$('#element').click(function(){
// this is a reference to the element clicked on
var that = this;
$('.elements').each(function(){
// this is a reference to the current element in the loop
// that is still a reference to the element clicked on
});
});
Because this
frequently changes when you change the scope by calling a new function, you can't access the original value by using it. Aliasing it to that
allows you still to access the original value of this
.
Personally, I dislike the use of that
as the alias. It is rarely obvious what it is referring to, especially if the functions are longer than a couple of lines. I always use a more descriptive alias. In my examples above, I'd probably use clickedEl
.
it depends on your php settings...
use phpinfo()
and take a look at the session chapter. There are values like session.gc_maxlifetime
and session.cache_expire
and session.cookie_lifetime
which affects the sessions lifetime
EDIT: it's like Martin write before
Assuming the type is CV_8UC3 you would do this:
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
Vec3b bgrPixel = foo.at<Vec3b>(i, j);
// do something with BGR values...
}
}
Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.
EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:
Here is how you might go about this:
uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R
// do something with BGR values...
}
}
Or alternatively:
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
uint8_t* rowPtr = foo.row(i);
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
bgrPixel.val[2] = rowPtr[j*cn + 2]; // R
// do something with BGR values...
}
}
According to the docs, you want to export of type del (the default delimiter looks like a comma, which is what you want). See the doc page for more information on the EXPORT command.
C# 7.0 now has binary literals, which is awesome.
[Flags]
enum Days
{
None = 0,
Sunday = 0b0000001,
Monday = 0b0000010, // 2
Tuesday = 0b0000100, // 4
Wednesday = 0b0001000, // 8
Thursday = 0b0010000, // 16
Friday = 0b0100000, // etc.
Saturday = 0b1000000,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
Since the topic seems to have turned to declaring bit-based flag values in enums, I thought it would be worth pointing out a handy trick for this sort of thing. The left-shift operator (<<
) will allow you to push a bit to a specific binary position. Combine that with the ability to declare enum values in terms of other values in the same class, and you have a very easy-to-read declarative syntax for bit flag enums.
[Flags]
enum Days
{
None = 0,
Sunday = 1,
Monday = 1 << 1, // 2
Tuesday = 1 << 2, // 4
Wednesday = 1 << 3, // 8
Thursday = 1 << 4, // 16
Friday = 1 << 5, // etc.
Saturday = 1 << 6,
Weekend = Saturday | Sunday,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday
}
If you only want to undo the last checkin, you can use the following
svn merge -r head:prev l3toks.dtx
That way, you don't have to hunt for the current and previous version numbers.
Increasing Permanent Generation size or tweaking GC parameters will NOT help if you have a real memory leak. If your application or some 3rd party library it uses, leaks class loaders the only real and permanent solution is to find this leak and fix it. There are number of tools that can help you, one of the recent is Plumbr, which has just released a new version with the required capabilities.
Here is what the standard (SI) says:
For me, Visual Studio on Mac doesn't support Node.js (editing and debugging) whereas Visual Studio Code does this very well.
I hope this will be more useful for future scope contain auto complete Google API feature with latitude and longitude
var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();
Complete View
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete With Latitude & Longitude </title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#pac-input {
background-color: #fff;
padding: 0 11px 0 13px;
width: 400px;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
text-overflow: ellipsis;
}
#pac-input:focus {
border-color: #4d90fe;
margin-left: -1px;
padding-left: 14px; /* Regular padding-left + 1. */
width: 401px;
}
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places"></script>
<script>
function initialize() {
var address = (document.getElementById('pac-input'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
/*********************************************************************/
/* var address contain your autocomplete address *********************/
/* place.geometry.location.lat() && place.geometry.location.lat() ****/
/* will be used for current address latitude and longitude************/
/*********************************************************************/
document.getElementById('lat').innerHTML = place.geometry.location.lat();
document.getElementById('long').innerHTML = place.geometry.location.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="pac-input" class="controls" type="text"
placeholder="Enter a location">
<div id="lat"></div>
<div id="long"></div>
</body>
</html>
It's Ctrl+Shift+O / Cmd+Shift+O on mac. You can see it if you close all tabs
I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection
, which the QueryString
property actually is, unfortunately it is internal in the .NET framework.
You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.
HttpValueCollection
extends NameValueCollection
, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString()
method to later rebuild the query string from the underlying collection.
A little old but this works in L5:
<li class="{{ Request::is('mycategory/', '*') ? 'active' : ''}}">
This captures both /mycategory and /mycategory/slug
Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.
Void pointers can point to any memory chunk. Hence the compiler does not know how many bytes to increment/decrement when we attempt pointer arithmetic on a void pointer. Therefore void pointers must be first typecast to a known type before they can be involved in any pointer arithmetic.
void *p = malloc(sizeof(char)*10);
p++; //compiler does how many where to pint the pointer after this increment operation
char * c = (char *)p;
c++; // compiler will increment the c by 1, since size of char is 1 byte.
Using np.percentile
.
q75, q25 = np.percentile(DataFrame, [75,25])
iqr = q75 - q25
Answer from How do you find the IQR in Numpy?
Because if none of the if statements evaluate to true then the local variable will be unassigned. Throw an else statement in there and assign some values to those variables in case the if statements don't evaluate to true. Post back here if that doesn't make the error go away.
Your other option is to initialize the variables to some default value when you declare them at the beginning of your code.
Use HttpClientBuilder to build the HttpClient instead of using DefaultHttpClient
ex:
MinimalHttpClient httpclient = new HttpClientBuilder().build();
// Prepare a request object
HttpGet httpget = new HttpGet("http://www.apache.org/");
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Go to the Preferences tab (menu File → Settings), and then search as “word wrap”. The following animated image is helpful too.
Inside pom.xml
<project>
.....
<profiles>
<profile>
<id>linux64</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<build_os>linux</build_os>
<build_ws>gtk</build_ws>
<build_arch>x86_64</build_arch>
</properties>
</profile>
<profile>
<id>win64</id>
<activation>
<property>
<name>env</name>
<value>win64</value>
</property>
</activation>
<properties>
<build_os>win32</build_os>
<build_ws>win32</build_ws>
<build_arch>x86_64</build_arch>
</properties>
</profile>
</profiles>
.....
<plugin>
<groupId>org.eclipse.tycho</groupId>
<artifactId>target-platform-configuration</artifactId>
<version>${tycho.version}</version>
<configuration>
<environments>
<environment>
<os>${build_os}</os>
<ws>${build_ws}</ws>
<arch>${build_arch}</arch>
</environment>
</environments>
</configuration>
</plugin>
.....
In this example when you run the pom without any argument mvn clean install
default profile will execute.
When executed with mvn -Denv=win64 clean install
win64 profile will executed.
Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html
Check out the split function of String Here, and use it something like this String[] results = input.split("\\s+");
. The regular expresion bit spilts on whitespaces, it should do the trick
Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0
) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE
).
Since your integer array cannot contain a value larger than Integer.MAX_VALUE
and smaller than Integer.MIN_VALUE
your code works across all edge cases.
I think this answer needs an update and the solution would go better this way.
from datetime import datetime
datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")
or you may use datetime object and format the time using %s to convert it into epoch time.
The node-mysql
library automatically performs escaping when used as you are already doing. See https://github.com/felixge/node-mysql#escaping-query-values
Consider:
Sub SheetKiller()
Dim s As Worksheet, t As String
Dim i As Long, K As Long
K = Sheets.Count
For i = K To 1 Step -1
t = Sheets(i).Name
If t = "ID Sheet" Or t = "Summary" Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
Next i
End Sub
NOTE:
Because we are deleting, we run the loop backwards.
You must create a new anonymous type:
select new { op, pg }
Refer to the official guide.
This is one of the other method to solve the Error: "Cannot get a text value from a numeric cell “Poi”"
Go to the Excel Sheet. Drag and Select the Numerics which you are importing Data from the Excel sheet. Go to Format > Number > Then Select "Plain Text" Then Export as .xlsx. Now Try to Run the Script
Hope works Fine...!
openjdk-6
is a Java runtime, not a JDK (development kit which contains javac
, for example). Install openjdk-6-jdk
.
Maven also needs the JDK.
[EDIT] When the JDK is installed, use /usr/lib/jvm/java-6-openjdk
for JAVA_HOME
(i.e. without the jre
part).
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
Set IIS to forward your mail to the remote server. The specifics vary greatly depending on the version of IIS. For IIS 7.5:
The answer by @T.J.Crowder is Java 6 - in java 7 the valid answer is the one by @McIntosh - though its use of Charset for name for UTF -8 is discouraged:
List<String> lines = Files.readAllLines(Paths.get("/tmp/test.csv"),
StandardCharsets.UTF_8);
for(String line: lines){ /* DO */ }
Reminds a lot of the Guava way posted by Skeet above - and of course same caveats apply. That is, for big files (Java 7):
BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8);
for (String line = reader.readLine(); line != null; line = reader.readLine()) {}
You can implement a middleware which handles Basic authentication.
public async Task Invoke(HttpContext context)
{
var authHeader = context.Request.Headers.Get("Authorization");
if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
{
var token = authHeader.Substring("Basic ".Length).Trim();
System.Console.WriteLine(token);
var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
var credentials = credentialstring.Split(':');
if(credentials[0] == "admin" && credentials[1] == "admin")
{
var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
var identity = new ClaimsIdentity(claims, "Basic");
context.User = new ClaimsPrincipal(identity);
}
}
else
{
context.Response.StatusCode = 401;
context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
}
await _next(context);
}
This code is written in a beta version of asp.net core. Hope it helps.
it would be great if somebody told to put gif into any folder instead of assets folder
This worked for me, based on your code, generating a 93Mb png image with color noise and the desired dimensions:
import matplotlib.pyplot as plt
import numpy
w = 7195
h = 3841
im_np = numpy.random.rand(h, w)
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig('figure.png', dpi=1)
I am using the last PIP versions of the Python 2.7 libraries in Linux Mint 13.
Hope that helps!
Here's another solution using a div container for img while using :hover::after
to achieve the effect.
The HTML as follows:
<div id=img_container><img src='' style='height:300px; width:300px;'></img></div>
The CSS as follows:
#img_container {
margin:0;
position:relative;
}
#img_container:hover::after {
content:'';
display:block;
position:absolute;
width:300px;
height:300px;
background:url('');
z-index:1;
top:0;
}
To see it in action, check out the fiddle I've created. Just so you know this is cross browser friendly and there's no need to trick the code with 'fake content'.
ndarray.tofile()
should also work
e.g. if your array is called a
:
a.tofile('yourfile.txt',sep=" ",format="%s")
Not sure how to get newline formatting though.
Edit (credit Kevin J. Black's comment here):
Since version 1.5.0,
np.tofile()
takes an optional parameternewline='\n'
to allow multi-line output. https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.savetxt.html
Instruction is base on the "icemelon" post. Link to the post:
how-do-i-compile-and-run-a-c-program-in-sublime-text-2
Use the link below to find out how to setup enviroment variable on your OS:
The instruction below was tested on the Windows 8.1 system and Sublime Text 3 - build 3065.
1) Install MinGW. 2) Add path to the "MinGW\bin" in the "PATH environment variable".
"System Properties -> Advanced -> Environment" variables and there update "PATH' variable.
3) Then check your PATH environment variable by the command below in the "Command Prompt":
echo %path%
4) Add new Build System to the Sublime Text.
My version of the code below ("C.sublime-build").
link to the code:
// Put this file here:
// "C:\Users\[User Name]\AppData\Roaming\Sublime Text 3\Packages\User"
// Use "Ctrl+B" to Build and "Crtl+Shift+B" to Run the project.
// OR use "Tools -> Build System -> New Build System..." and put the code there.
{
"cmd" : ["gcc", "$file_name", "-o", "${file_base_name}.exe"],
// Doesn't work, sublime text 3, Windows 8.1
// "cmd" : ["gcc $file_name -o ${file_base_name}"],
"selector" : "source.c",
"shell": true,
"working_dir" : "$file_path",
// You could add path to your gcc compiler this and don't add path to your "PATH environment variable"
// "path" : "C:\\MinGW\\bin"
"variants" : [
{ "name": "Run",
"cmd" : ["${file_base_name}.exe"]
}
]
}
You can pass in any CMake variable on the command line, or edit cached variables using ccmake/cmake-gui. On the command line,
cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr . && make all install
Would configure the project, build all targets and install to the /usr prefix. The type (PATH) is not strictly necessary, but would cause the Qt based cmake-gui to present the directory chooser dialog.
Some minor additions as comments make it clear that providing a simple equivalence is not enough for some. Best practice would be to use an external build directory, i.e. not the source directly. Also to use more generic CMake syntax abstracting the generator.
mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr .. && cmake --build . --target install --config Release
You can see it gets quite a bit longer, and isn't directly equivalent anymore, but is closer to best practices in a fairly concise form... The --config is only used by multi-configuration generators (i.e. MSVC), ignored by others.
If you used Create React App, you can set an environment variable using a .env file. The documentation is here:
https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables
Basically do something like this in the .env file at the project root.
REACT_APP_NOT_SECRET_CODE=abcdef
Note that the variable name must start with REACT_APP_
You can access it from your component with
process.env.REACT_APP_NOT_SECRET_CODE
When in an iframe on the same origin as the parent, the window.frameElement
method returns the element (e.g. iframe
or object
) in which the window is embedded. Otherwise, if browsing in a top-level context, or if the parent and the child frame have different origins, it will evaluate to null
.
window.frameElement
? 'embedded in iframe or object'
: 'not embedded or cross-origin'
This is an HTML Standard with basic support in all modern browsers.
I had this problem when trying to connect to my SQL Server 2017 instance via L2TP VPN on a domain-joined Windows 10 machine.
The problem ended up being in my VPN settings. In the security settings, in Authentication, using EAP-MSCHAPv2 and in the Properties dialog, I had selected Automatically use my Windows logon name and password (and domain if any).
I turned this off and then re-connected my VPN and then I was able to connect to SQL Server successfully.
I believe this was causing my SQL login (with Windows account security) to use Kerberos instead of NTLM, causing the SSPI error.
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen()
after 'dynamic library').
They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.
Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.
Here's another simple solution. The following code will return everything before the '|' character:
if (path.Contains('|'))
path = path.Split('|')[0];
In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':
if (path.Contains('|'))
path = path.Split('|')[1];
(All I changed in the second piece of code was the index of the array.)
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
The children of a row-flexbox container automatically fill the container's vertical space.
Specify flex: 1;
for a child if you want it to fill the remaining horizontal space:
.wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
flex: 1;
for both children if you want them to fill equal amounts of the horizontal space: .wrapper {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: stretch;_x000D_
width: 100%;_x000D_
height: 5em;_x000D_
background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="left">Left</div>_x000D_
<div class="right">Right</div>_x000D_
</div>
_x000D_
If you use the standard scripts to launch Tomcat (i.e. you haven't installed Tomcat as a windows service), you can use the setenv.bat file, to set your JRE_HOME version.
On Windows, create the file
%CATALINA_BASE%\bin\setenv.bat
, with content:
set "JRE_HOME=%ProgramFiles%\Java\jre1.6.0_20"
exit /b 0
And that should be it.
You can test this using %CATALINA_BASE%\bin\configtest.bat (Disclaimer: I've only checked this with a Tomcat7 installation).
Further Reading:
Maven needs the dependencies in your local repository. The easiest way to get them is with internet access (or harder using other solutions provided here).
So assumed that you can get temporarily internet access you can prepare to go offline using the maven-dependency-plugin with its dependency:go-offline goal. This will download all your project dependencies to your local repository (of course changes in the dependencies / plugins will require new internet / central repository access).
@Daniel H (concerning your comment on andcoz' answer, although long time ago): deleting trailing zeros works with
s,([[:digit:]]\.[[:digit:]]*[1-9])[0]*$,\1,g
it's about clearly defining the matching conditions ...
You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const
.
So, in this case, it should be:
const val MY_CONST = "something"
and then you can import the constant using:
import package_name.MY_CONST
You can refer to this link
For Mac Users
I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.
You need to remove those credentials from Keychain Access and then try to push.
Hope it help to Mac users.
Try to use UICollectionViewDelegateFlowLayout method. In Xcode 11 or later, you need to set Estimate Size to none from storyboard.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout:
UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let padding: CGFloat = 170
let collectionViewSize = advertCollectionView.frame.size.width - padding
return CGSize(width: collectionViewSize/2, height: collectionViewSize/2)
}
library(dplyr)
library(tidyr)
#supposing you want to arrange column 'c' in descending order and 'd' in ascending order. name of data frame is df
## first doing descending
df<-arrange(df,desc(c))
## then the ascending order of col 'd;
df <-arrange(df,d)
Google Chrome now supports the W3C standard for push notifications.
HTML/JSP Markup:
<form:option
data-libelle="${compte.libelleCompte}"
data-raison="${compte.libelleSociale}" data-rib="${compte.numeroCompte}" <c:out value="${compte.libelleCompte} *MAD*"/>
</form:option>
JQUERY CODE: Event: change
var $this = $(this);
var $selectedOption = $this.find('option:selected');
var libelle = $selectedOption.data('libelle');
To have a element libelle.val() or libelle.text()
Encryption has not only cpu, but also some network overhead.
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
I was running into this error message because of <></>
being returned for some items in the array when instead null
needs to be returned.
public static void main(String[] args) {
String test = "something hear - to - find some to or tows";
System.out.println("1.result: " + contains("- to -( \\w+) som", test, null));
System.out.println("2.result: " + contains("- to -( \\w+) som", test, 5));
}
static boolean contains(String pattern, String text, Integer fromIndex){
if(fromIndex != null && fromIndex < text.length())
return Pattern.compile(pattern).matcher(text).find();
return Pattern.compile(pattern).matcher(text).find();
}
1.result: true
2.result: true
The command build
in pipeline is there to trigger other jobs in jenkins.
The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git
self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];
more info with example project
I believe this is what you're looking for:
char[] characters = "this is a test".ToCharArray();
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
There's the %
sign. It's not just for the remainder, it is the modulo operation.
It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==
, the following should work:
byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);
This will output: YWJjZGVmPT0=
which is abcdef==
encoded in Base64.
Edit:
To decode a Base64 string, simply use Convert.FromBase64String()
. E.g.
string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);
At this point, bytes
will be a byte[]
(not a string
). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);
This will output the original input string, abcdef==
in this case.
You can't directly control this, because it's an option controlled by Internet Explorer users.
Opening pages using Window.open with a different window name will open in a new browser window like a popup, OR open in a new tab, if the user configured the browser to do so.
if path.exists(Score_file):
try :
with open(Score_file , "rb") as prev_Scr:
return Unpickler(prev_Scr).load()
except EOFError :
return dict()
Try to connect to the repository using command line SVN to see if you get a similar error.
$ svn checkout http://svn.python.org/projects/peps/trunk
If you keep getting the error, it is probably an issue with your proxy server. I have found that I can't check out internet based SVN projects at work because the firewall blocks most HTTP commands. It only allows GET, POST and others necessary for browsing.
String.regionMatches()
Using regexp can be relatively slow. It (being slow) doesn't matter if you just want to check in one case. But if you have an array or a collection of thousands or hundreds of thousands of strings, things can get pretty slow.
The presented solution below doesn't use regular expressions nor toLowerCase()
(which is also slow because it creates another strings and just throws them away after the check).
The solution builds on the String.regionMatches() method which seems to be unknown. It checks if 2 String
regions match, but what's important is that it also has an overload with a handy ignoreCase
parameter.
public static boolean containsIgnoreCase(String src, String what) {
final int length = what.length();
if (length == 0)
return true; // Empty string is contained
final char firstLo = Character.toLowerCase(what.charAt(0));
final char firstUp = Character.toUpperCase(what.charAt(0));
for (int i = src.length() - length; i >= 0; i--) {
// Quick check before calling the more expensive regionMatches() method:
final char ch = src.charAt(i);
if (ch != firstLo && ch != firstUp)
continue;
if (src.regionMatches(true, i, what, 0, length))
return true;
}
return false;
}
This speed analysis does not mean to be rocket science, just a rough picture of how fast the different methods are.
I compare 5 methods.
String.contains()
.String.contains()
with the pre-cached, lower-cased substring. This solution is already not as flexible because it tests a predefiend substring.Pattern.compile().matcher().find()
...)Pattern
. This solution is already not as flexible because it tests a predefined substring.Results (by calling the method 10 million times):
Pattern
: 1845 msResults in a table:
RELATIVE SPEED 1/RELATIVE SPEED
METHOD EXEC TIME TO SLOWEST TO FASTEST (#1)
------------------------------------------------------------------------------
1. Using regionMatches() 670 ms 10.7x 1.0x
2. 2x lowercase+contains 2829 ms 2.5x 4.2x
3. 1x lowercase+contains cache 2446 ms 2.9x 3.7x
4. Regexp 7180 ms 1.0x 10.7x
5. Regexp+cached pattern 1845 ms 3.9x 2.8x
Our method is 4x faster compared to lowercasing and using contains()
, 10x faster compared to using regular expressions and also 3x faster even if the Pattern
is pre-cached (and losing flexibility of checking for an arbitrary substring).
If you're interested how the analysis was performed, here is the complete runnable application:
import java.util.regex.Pattern;
public class ContainsAnalysis {
// Case 1 utilizing String.regionMatches()
public static boolean containsIgnoreCase(String src, String what) {
final int length = what.length();
if (length == 0)
return true; // Empty string is contained
final char firstLo = Character.toLowerCase(what.charAt(0));
final char firstUp = Character.toUpperCase(what.charAt(0));
for (int i = src.length() - length; i >= 0; i--) {
// Quick check before calling the more expensive regionMatches()
// method:
final char ch = src.charAt(i);
if (ch != firstLo && ch != firstUp)
continue;
if (src.regionMatches(true, i, what, 0, length))
return true;
}
return false;
}
// Case 2 with 2x toLowerCase() and contains()
public static boolean containsConverting(String src, String what) {
return src.toLowerCase().contains(what.toLowerCase());
}
// The cached substring for case 3
private static final String S = "i am".toLowerCase();
// Case 3 with pre-cached substring and 1x toLowerCase() and contains()
public static boolean containsConverting(String src) {
return src.toLowerCase().contains(S);
}
// Case 4 with regexp
public static boolean containsIgnoreCaseRegexp(String src, String what) {
return Pattern.compile(Pattern.quote(what), Pattern.CASE_INSENSITIVE)
.matcher(src).find();
}
// The cached pattern for case 5
private static final Pattern P = Pattern.compile(
Pattern.quote("i am"), Pattern.CASE_INSENSITIVE);
// Case 5 with pre-cached Pattern
public static boolean containsIgnoreCaseRegexp(String src) {
return P.matcher(src).find();
}
// Main method: perfroms speed analysis on different contains methods
// (case ignored)
public static void main(String[] args) throws Exception {
final String src = "Hi, I am Adam";
final String what = "i am";
long start, end;
final int N = 10_000_000;
start = System.nanoTime();
for (int i = 0; i < N; i++)
containsIgnoreCase(src, what);
end = System.nanoTime();
System.out.println("Case 1 took " + ((end - start) / 1000000) + "ms");
start = System.nanoTime();
for (int i = 0; i < N; i++)
containsConverting(src, what);
end = System.nanoTime();
System.out.println("Case 2 took " + ((end - start) / 1000000) + "ms");
start = System.nanoTime();
for (int i = 0; i < N; i++)
containsConverting(src);
end = System.nanoTime();
System.out.println("Case 3 took " + ((end - start) / 1000000) + "ms");
start = System.nanoTime();
for (int i = 0; i < N; i++)
containsIgnoreCaseRegexp(src, what);
end = System.nanoTime();
System.out.println("Case 4 took " + ((end - start) / 1000000) + "ms");
start = System.nanoTime();
for (int i = 0; i < N; i++)
containsIgnoreCaseRegexp(src);
end = System.nanoTime();
System.out.println("Case 5 took " + ((end - start) / 1000000) + "ms");
}
}