In PCRE \R
matches \n
, \r
and \r\n
.
Here is how to do it in Unity:
(Modified answer from @markmuetz so be sure to upvote his answer)
int[,] rawNodes = new int[,]
{
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0 }
};
private void Start()
{
int rowLength = rawNodes.GetLength(0);
int colLength = rawNodes.GetLength(1);
string arrayString = "";
for (int i = 0; i < rowLength; i++)
{
for (int j = 0; j < colLength; j++)
{
arrayString += string.Format("{0} ", rawNodes[i, j]);
}
arrayString += System.Environment.NewLine + System.Environment.NewLine;
}
Debug.Log(arrayString);
}
Use this:
void double_to_char(double f,char * buffer){
gcvt(f,10,buffer);
}
another important point is that Random.nextInt(n) is repeatable since you can create two Random object with the same seed. This is not possible with Math.random().
Using the class:
import android.provider.MediaStore.Video.Thumbnails;
We can get two preview thumbnail sizes from the video:
Thumbnails.MICRO_KIND
for 96 x 96Thumbnails.MINI_KIND
for 512 x 384 pxThis is a code example:
String filePath = "/sdcard/DCIM/Camera/my_video.mp4"; //change the location of your file!
ImageView imageview_mini = (ImageView)findViewById(R.id.thumbnail_mini);
ImageView imageview_micro = (ImageView)findViewById(R.id.thumbnail_micro);
Bitmap bmThumbnail;
//MICRO_KIND, size: 96 x 96 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MICRO_KIND);
imageview_micro.setImageBitmap(bmThumbnail);
// MINI_KIND, size: 512 x 384 thumbnail
bmThumbnail = ThumbnailUtils.createVideoThumbnail(filePath, Thumbnails.MINI_KIND);
imageview_mini.setImageBitmap(bmThumbnail);
This works in SQL 2008 and 2012 to produce datetime2:
declare @date date = current_timestamp;
declare @time time = current_timestamp;
select
@date as date
,@time as time
,cast(@date as datetime) + cast(@time as datetime) as datetime
,cast(@time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,@date) - 1,dateadd(year,datepart(year,@date) - 1900,cast(@time as datetime2))) as datetime2;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
I answered this already, but some reason the answer was converted to a comment. Nevertheless, this is the most efficient solution:
Not being able to include (and propagate) NaNs in groups is quite aggravating. Citing R is not convincing, as this behavior is not consistent with a lot of other things. Anyway, the dummy hack is also pretty bad. However, the size (includes NaNs) and the count (ignores NaNs) of a group will differ if there are NaNs.
dfgrouped = df.groupby(['b']).a.agg(['sum','size','count'])
dfgrouped['sum'][dfgrouped['size']!=dfgrouped['count']] = None
When these differ, you can set the value back to None for the result of the aggregation function for that group.
If you haven't already created the project in Github, do so on that site. If memory serves, they display a page that tells you exactly how to get your existing code into your new repository. At the risk of oversimplification, though, you'd follow Veeti's instructions, then:
git remote add [name to use for remote] [private URI] # associate your local repository to the remote
git push [name of remote] master # push your repository to the remote
If all else fails (or perhaps before then) you may want to check and see if NuGet is a package source. I installed VS2017, and it was NOT there by default. I thought it was kind of odd.
Have you read about the nohup command?
How about this:
function array_keys_exist($searchForKeys = array(), $searchableArray) {
$searchableArrayKeys = array_keys($searchableArray);
return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys);
}
Based on the answer of @AlokThakur (thanks!):
def run_system_command(command):
return_value = os.system(command)
# Calculate the return value code
return_value = int(bin(return_value).replace("0b", "").rjust(16, '0')[:8], 2)
if return_value != 0:
raise RuntimeError(f'The system command\n{command}\nexited with return code {return_value}')
It's very simple. You are getting the result into an Object
which is a primitive one.
Your code:
Object result = (Object)envelope.getResponse();
Correct code:
SoapObject result=(SoapObject)envelope.getResponse();
//To get the data.
String resultData=result.getProperty(0).toString();
// 0 is the first object of data.
I think this should definitely work.
You can use CSS to do the trick:
$("#yourElement").css({ top: '100px' });
If you want to find all commits where commit message contains given word, use
$ git log --grep=word
If you want to find all commits where "word" was added or removed in the file contents (to be more exact: where number of occurences of "word" changed), i.e. search the commit contents, use so called 'pickaxe' search with
$ git log -Sword
In modern git there is also
$ git log -Gword
to look for differences whose added or removed line matches "word" (also commit contents).
Note that -G
by default accepts a regex, while -S
accepts a string, but can be modified to accept regexes using the --pickaxe-regex
.
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return !regexec(regexp, two->ptr, 1, ®match, 0); ... - hit = !regexec(regexp, mf2.ptr, 1, ®match, 0);
While
git log -G"regexec\(regexp"
will show this commit,git log -S"regexec\(regexp" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
With Git 2.25.1 (Feb. 2020), the documentation is clarified around those regexes.
See commit 9299f84 (06 Feb 2020) by Martin Ågren (``).
(Merged by Junio C Hamano -- gitster
-- in commit 0d11410, 12 Feb 2020)
diff-options.txt
: avoid "regex" overload in exampleReported-by: Adam Dinwoodie
Signed-off-by: Martin Ågren
Reviewed-by: Taylor BlauWhen we exemplify the difference between
-G
and-S
(using--pickaxe-regex
), we do so using an example diff andgit diff
invocation involving "regexec", "regexp", "regmatch", ...The example is correct, but we can make it easier to untangle by avoiding writing "regex.*" unless it's really needed to make our point.
Use some made-up, non-regexy words instead.
The git diff
documentation now includes:
To illustrate the difference between
-S<regex> --pickaxe-regex
and-G<regex>
, consider a commit with the following diff in the same file:+ return frotz(nitfol, two->ptr, 1, 0); ... - hit = frotz(nitfol, mf2.ptr, 1, 0);
While
git log -G"frotz\(nitfol"
will show this commit,git log -S"frotz\(nitfol" --pickaxe-regex
will not (because the number of occurrences of that string did not change).
I hope below solution will work for you all as I was having the same problem with my websites...
For : $json = json_decode(file_get_contents('http://...'));
Replace with below query
$Details= unserialize(file_get_contents('http://......'));
The way to dynamically add elements to DOM, as explained on Angular 2 doc, is by using ViewContainerRef class from @Angular/core.
What you have to do is to declare a directive that will implement ViewContainerRef and act like a placeholder on your DOM.
Directive
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appInject]'
})
export class InjectDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
Then, in the template where you want to inject the component:
HTML
<div class="where_you_want_to_inject">
<ng-template appInject></ng-template>
</div>
Then, from the injected component code, you will inject the component containing the HTML you want:
import { Component, OnInit, ViewChild, ComponentFactoryResolver } from '@angular/core';
import { InjectDirective } from '../inject.directive';
import { InjectedComponent } from '../injected/injected.component';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
@ViewChild(InjectDirective) injectComp: InjectDirective;
constructor(private _componentFactoryResolver: ComponentFactoryResolver) {
}
ngOnInit() {
}
public addComp() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
const componentRef = viewContainerRef.createComponent(componentFactory);
}
public removeComp() {
const componentFactory = this._componentFactoryResolver.resolveComponentFactory(InjectedComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
const componentRef = viewContainerRef.remove();
}
}
I added a fully working demo app on Angular 2 dynamically add component to DOM demo
This is partly based on this earlier answer above by @A Boschman. In that solution, I found that the input size of the image greatly affected the ability of makeImageSpan()
to properly center-align the image. Additionally, I found that the solution affected text spacing by creating unnecessary line spacing.
I found BaseImageSpan (from Facebook's Fresco library) to do the job particularly well:
/**
* Create an ImageSpan for the given icon drawable. This also sets the image size. Works best
* with a square icon because of the sizing
*
* @param context The Android Context.
* @param drawableResId A drawable resource Id.
* @param size The desired size (i.e. width and height) of the image icon in pixels.
* Use the lineHeight of the TextView to make the image inline with the
* surrounding text.
* @return An ImageSpan, aligned with the bottom of the text.
*/
private static BetterImageSpan makeImageSpan(Context context, int drawableResId, int size) {
final Drawable drawable = context.getResources().getDrawable(drawableResId);
drawable.mutate();
drawable.setBounds(0, 0, size, size);
return new BetterImageSpan(drawable, BetterImageSpan.ALIGN_CENTER);
}
Then supply your betterImageSpan instance to spannable.setSpan()
as usual
I tried researching that too but instead ended up using jsconsole.com by Remy Sharp (he also created jsbin.com). I'm running on Ubuntu 12.10 so I had to create a special icon but if you're on Windows and use Chrome simply go to Tools>Create Application Shortcuts (note this doesn't work very well, or at all in my case, on Ubuntu). This site works very like the Mac jsc
console: actually it has some cool features too (like loading libraries/code from a URL) that I guess jsc
does not.
Hope this helps.
Just in case someone is looking to do the same using Reactive Forms:
<form [formGroup]="form">
<select formControlName="country">
<option *ngFor="let country of countries" [ngValue]="country">{{country.name}}</option>
</select>
<p>Selected Country: {{country?.name}}</p>
</form>
Check the working example here
<?php
session_start();
session_destroy();
header("Location: home.php");
?>
This worked for me. Thank you Rody!
y="HELLO"
val=$(echo $y | tr '[:upper:]' '[:lower:]')
string="$val world"
one small modification, if you are using underscore next to the variable You need to encapsulate the variable name in {}.
string="${val}_world"
To read all files in a folder:
import glob
from google.colab import drive
drive.mount('/gdrive', force_remount=True)
#!ls "/gdrive/My Drive/folder"
files = glob.glob(f"/gdrive/My Drive/folder/*.txt")
for file in files:
do_something(file)
The correct CSS for setting font-size is "font-size: 35px". I.e.:
<td style="padding-left: 5px; padding-bottom:3px; font size: 35px;">
Note that this sets the font size in pixels. You can also set it in *em*s or percentage. Learn more about fonts in CSS here: http://www.w3schools.com/css/css_font.asp
I'd suggest creating a directory junction named C:\Android
pointing to the actual C:\Program Files (x86)\Android\android-sdk-windows\
:
MKLINK /J C:\Android "C:\Program Files (x86)\Android\android-sdk-windows\"
and then setting the newly created junction as SDK Location for your Eclipse ADT Plugin (Eclipse menu\ Window\ Preference\ Android). This might help for a number of tools/ plugin too that have problems with spaces in paths.
In any case, checking for type of device must be called just ONE TIME: your phone can't surprisingly stay a desktop in a moment :)
So, code for checking by userAgent, suggested here sometime ago, have to be look like that:
(function(a){window.isMobile = (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4)))})(navigator.userAgent||navigator.vendor||window.opera);_x000D_
_x000D_
console.info('This is %s device', window.isMoblie ? 'mobile' : 'desktop');
_x000D_
Functionally no difference, Google just changed the name from fill_parent to match_parent, from API level 8 (Android 2.2). FILL_PARENT is still available for compatibility reason.
LayoutParams.FILL_PARENT
and LayoutParams.MATCH_PARENT
both have value -1. Not sure what tempted google to change from Fill Parent to Match Parent :)
Since most of the phones are >= Android 2.2
.. you should use Match Parent for future compatibility... not sure when they will discontinue the older Fill Parent constant!
If you want to run inside a background service and take the data in foreground use the below one, it is tested and verified.
public class MyService extends Service
implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener {
private static final int ASHIS = 1234;
Intent intentForPendingIntent;
HandlerThread handlerThread;
Looper looper;
GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRrequest;
private static final int UPDATE_INTERVAL = 1000;
private static final int FASTEST_INTERVAL = 100;
private static final int DSIPLACEMENT_UPDATES = 1;
;
private Handler handler1;
private Runnable runable1;
private Location mLastLocation;
private float waitingTime;
private int waiting2min;
private Location locationOld;
private double distance;
private float totalWaiting;
private float speed;
private long timeGpsUpdate;
private long timeOld;
private NotificationManager mNotificationManager;
Notification notification;
PendingIntent resultPendingIntent;
NotificationCompat.Builder mBuilder;
// Sets an ID for the notification
int mNotificationId = 001;
private static final String TAG = "BroadcastService";
public static final String BROADCAST_ACTION = "speedExceeded";
private final Handler handler = new Handler();
Intent intentforBroadcast;
int counter = 0;
private Runnable sendUpdatesToUI;
@Nullable
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(MyService.this, "binder", Toast.LENGTH_SHORT).show();
return null;
}
@Override
public void onCreate() {
showNotification();
intentforBroadcast = new Intent(BROADCAST_ACTION);
Toast.makeText(MyService.this, "created", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
createLocationRequest();
mGoogleApiClient.connect();
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void showNotification() {
mBuilder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_media_play)
.setContentTitle("Total Waiting Time")
.setContentText(totalWaiting+"");
Intent resultIntent = new Intent(this, trackingFusion.class);
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
startForeground(001, mBuilder.getNotification());
}
@Override
public void onLocationChanged(Location location) {
//handler.removeCallbacks(runable);
Toast.makeText(MyService.this, "speed" + speed, Toast.LENGTH_SHORT).show();
timeGpsUpdate = location.getTime();
float delta = (timeGpsUpdate - timeOld) / 1000;
if (location.getAccuracy() < 100) {
speed = location.getSpeed();
distance += mLastLocation.distanceTo(location);
Log.e("distance", "onLocationChanged: " + distance);
//mLastLocation = location;
//newLocation = mLastLocation;
Log.e("location:", location + "");
//speed = (long) (distance / delta);
locationOld = location;
mLastLocation = location;
diaplayViews();
}
diaplayViews();
/*if (map != null) {
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}*/
}
private void createLocationRequest() {
mLocationRrequest = new LocationRequest();
mLocationRrequest.setInterval(UPDATE_INTERVAL);
mLocationRrequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRrequest.setSmallestDisplacement(DSIPLACEMENT_UPDATES);
}
private void methodToCalculateWaitingTime() {
if (handler1 != null) {
handler1.removeCallbacks(runable1);
}
Log.e("Here", "here1");
handler1 = new Handler(Looper.getMainLooper());
runable1 = new Runnable() {
public void run() {
Log.e("Here", "here2:" + mLastLocation.getSpeed());
if (mLastLocation != null) {
diaplayViews();
if ((mLastLocation.getSpeed() == 0.0)) {
increaseTime();
} else {
if (waitingTime <= 120) {
waiting2min = 0;
}
}
handler1.postDelayed(this, 10000);
} else {
if (ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MyService.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastLocation = locationOld;
}
}
};
handler1.postDelayed(runable1, 10000);
}
private void diaplayViews() {
float price = (float) (14 + distance * 0.5);
//textDistance.setText(waitingTime);a
}
private void increaseTime() {
waiting2min = waiting2min + 10;
if (waiting2min >= 120)
{
if (waiting2min == 120) {
waitingTime = waitingTime + 2 * 60;
} else {
waitingTime = waitingTime + 10;
}
totalWaiting = waitingTime / 60;
showNotification();
Log.e("waiting Time", "increaseTime: " + totalWaiting);
}
}
@Override
public void onDestroy() {
Toast.makeText(MyService.this, "distroyed", Toast.LENGTH_SHORT).show();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
Log.e("Connection_fusion", "connected");
startLocationUpdates();
}
@Override
public void onConnectionSuspended(int i) {
}
private void startLocationUpdates() {
Location location = plotTheInitialMarkerAndGetInitialGps();
if (location == null) {
plotTheInitialMarkerAndGetInitialGps();
} else {
mLastLocation = location;
methodToCalculateWaitingTime();
}
}
private Location plotTheInitialMarkerAndGetInitialGps() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return null;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRrequest, this);
locationOld = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if ((locationOld != null)) {
mLastLocation = locationOld;
timeOld = locationOld.getTime();
} else {
startLocationUpdates();
}
return mLastLocation;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onStart(intent, startId);
Toast.makeText(MyService.this, "start command", Toast.LENGTH_SHORT).show();
sendUpdatesToUI = new Runnable() {
public void run() {
DisplayLoggingInfo();
handler.postDelayed(this, 10000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 10000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
return START_NOT_STICKY;
}
@Override
public void onStart(Intent intent, int startId) {
sendUpdatesToUI = new Runnable() {
public void run() {
Log.e("sent", "sent");
DisplayLoggingInfo();
handler.postDelayed(this, 5000); // 5 seconds
}
};
handler.postDelayed(sendUpdatesToUI, 1000); // 1 second
Log.i("LocalService", "Received start id " + startId + ": " + intent);
super.onStart(intent, startId);
}
private void DisplayLoggingInfo() {
Log.d(TAG, "entered DisplayLoggingInfo");
intentforBroadcast.putExtra("distance", distance);
LocalBroadcastManager.getInstance(this).sendBroadcast(intentforBroadcast);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onMapReady(GoogleMap googleMap) {
}
}
I use the following vba code where filename is a string containing the filename I want, and Function RemoveSpecialCharactersAndTruncate is defined below:
worksheet1.Name = RemoveSpecialCharactersAndTruncate(filename)
'Function to remove special characters from file before saving
Private Function RemoveSpecialCharactersAndTruncate$(ByVal FormattedString$)
Dim IllegalCharacterSet$
Dim i As Integer
'Set of illegal characters
IllegalCharacterSet$ = "*." & Chr(34) & "//\[]:;|=,"
'Iterate through illegal characters and replace any instances
For i = 1 To Len(IllegalCharacterSet) - 1
FormattedString$ = Replace(FormattedString$, Mid(IllegalCharacterSet, i, 1), "")
Next
'Return the value capped at 31 characters (Excel limit)
RemoveSpecialCharactersAndTruncate$ = Left(FormattedString$, _
Application.WorksheetFunction.Min(Len(FormattedString), 31))
End Function
For no errors.
error_reporting(0);
or for just not strict
error_reporting(E_ALL ^ E_STRICT);
and if you ever want to display all errors again, use
error_reporting(-1);
Another option to transform the static method into a static Func or Action. For instance.
Original code:
class Math
{
public static int Add(int x, int y)
{
return x + y;
}
You want to "mock" the Add method, but you can't. Change the above code to this:
public static Func<int, int, int> Add = (x, y) =>
{
return x + y;
};
Existing client code doesn't have to change (maybe recompile), but source stays the same.
Now, from the unit-test, to change the behavior of the method, just reassign an in-line function to it:
[TestMethod]
public static void MyTest()
{
Math.Add = (x, y) =>
{
return 11;
};
Put whatever logic you want in the method, or just return some hard-coded value, depending on what you're trying to do.
This may not necessarily be something you can do each time, but in practice, I found this technique works just fine.
[edit] I suggest that you add the following Cleanup code to your Unit Test class:
[TestCleanup]
public void Cleanup()
{
typeof(Math).TypeInitializer.Invoke(null, null);
}
Add a separate line for each static class. What this does is, after the unit test is done running, it resets all the static fields back to their original value. That way other unit tests in the same project will start out with the correct defaults as opposed your mocked version.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
String.prototype.replaceAll=function(obj,keydata='key'){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(new RegExp(`${keys[0]}${key}${keys[1]}`,'g'),val),this)
}
const data='hids dv sdc sd {yathin} {ok}'
console.log(data.replaceAll({yathin:12,ok:'hi'},'{key}'))
_x000D_
String.prototype.replaceAll=function(keydata,obj){
const keys=keydata.split('key');
return Object.entries(obj).reduce((a,[key,val])=> a.replace(${keys[0]}${key}${keys[1]}
,val),this)
}
const data='hids dv sdc sd ${yathin} ${ok}' console.log(data.replaceAll('${key}',{yathin:12,ok:'hi'}))
Use CURRENT_TIMESTAMP (or GETDATE() on archaic versions of SQL Server).
on Rails 6 you can now do something like
rake db:seed:replant
This Truncates tables of each database for current environment and loads the seeds
https://blog.saeloun.com/2019/09/30/rails-6-adds-db-seed-replant-task-and-db-truncate_all.html
$ rails db:seed:replant --trace
** Invoke db:seed:replant (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Invoke db:truncate_all (first_time)
** Invoke db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:truncate_all
** Invoke db:seed (first_time)
** Invoke db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config
** Execute db:abort_if_pending_migrations
** Execute db:seed:replant
After placing the jar file in desired location, you need to add the jar file by right click on
Project --> properties --> Java Build Path --> Libraries --> Add Jar.
Here's a method I'm using.
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
throw new
NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
You'll probably want the following.
List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);
Although I don't know about asp.net mvc, but this is what we should do in a normal .net website. It should work for asp.net mvc also.
YourSessionClass obj=Session["key"] as YourSessionClass;
if(obj==null){
obj=new YourSessionClass();
Session["key"]=obj;
}
You would put this inside a method for easy access. HTH
I am surprised that in almost ten years, no one has posted this approach yet:
If using older versions of bash where &>>
isn't available, you also can do:
(cmd 2>&1) >> file.txt
This spawns a subshell, so it's less efficient than the traditional approach of cmd >> file.txt 2>&1
, and it consequently won't work for commands that need to modify the current shell (e.g. cd
, pushd
), but this approach feels more natural and understandable to me:
Also, the parentheses remove any ambiguity of order, especially if you want to pipe stdout and stderr to another command instead.
Edit: To avoid starting a subshell, you instead could use curly braces instead of parentheses to create a group command:
{ cmd 2>&1; } >> file.txt
(Note that a semicolon (or newline) is required to terminate the group command.)
To find the sessions, as a DBA use
select sid,serial# from v$session where username = '<your_schema>'
If you want to be sure only to get the sessions that use SQL Developer, you can add and program = 'SQL Developer'
. If you only want to kill sessions belonging to a specific developer, you can add a restriction on os_user
Then kill them with
alter system kill session '<sid>,<serial#>'
(e.g.
alter system kill session '39,1232'
)
A query that produces ready-built kill-statements could be
select 'alter system kill session ''' || sid || ',' || serial# || ''';' from v$session where username = '<your_schema>'
This will return one kill statement per session for that user - something like:
alter system kill session '375,64855';
alter system kill session '346,53146';
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
Private Sub DownloadFile(relativeUrl As String, destinationPath As String, name As String)
Try
destinationPath = Replace(destinationPath + "\" + name, "\\", "\")
Dim fi As FileInformation = Microsoft.SharePoint.Client.File.OpenBinaryDirect(Me.context, relativeUrl)
Dim down As Stream = System.IO.File.Create(destinationPath)
Dim a As Integer = fi.Stream.ReadByte()
While a <> -1
down.WriteByte(CType(a, Byte))
a = fi.Stream.ReadByte()
End While
Catch ex As Exception
ToLog(Type.ERROR, ex.Message)
End Try
End Sub
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
I had the exact same error, Installing zlib-devel solved my problem, Type the command and install zlib package.
On linux:
sudo apt-get install zlib*
On Centos:
sudo yum install zlib*
Using Reflections
Get everything on the classpath:
Reflections reflections = new Reflections(null, new ResourcesScanner());
Set<String> resourceList = reflections.getResources(x -> true);
Another example - get all files with extension .csv from some.package:
Reflections reflections = new Reflections("some.package", new ResourcesScanner());
Set<String> fileNames = reflections.getResources(Pattern.compile(".*\\.csv"));
Easy solution for .Net Core WinForms / WPF / .Net Standard Class Library projects
step 1: Install System.Configuration.ConfigurationManager
by Nuget Manager
step 2: Add a new App.Config
file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Bodrum" value="Yalikavak" />
</appSettings>
</configuration>
step3: Get the value
string value = ConfigurationManager.AppSettings.Get("Bodrum");
// value is Yalikavak
If you are calling it from a Class Library
then add the App.Config
file on your Main Project.
Check out these:
You're gonna need something like:
<h:link outcome="success">
<f:param name="foo" value="bar"/>
</h:link>
...and...
<f:metadata>
<f:viewParam name="foo" value="#{bean.foo}"/>
</f:metadata>
Judging from this page, something like this might be easier:
<managed-bean>
<managed-bean-name>blog</managed-bean-name>
<managed-bean-class>com.acme.Blog</managed-bean-class>
<managed-property>
<property-name>entryId</property-name>
<value>#{param['id']}</value>
</managed-property>
</managed-bean>
I wanted a way to output the contents of an intent to the log, and to be able to read it easily, so here's what I came up with. I've created a LogUtil
class, and then took the dumpIntent()
method @Pratik created, and modified it a bit. Here's what it all looks like:
public class LogUtil {
private static final String TAG = "IntentDump";
public static void dumpIntent(Intent i){
Bundle bundle = i.getExtras();
if (bundle != null) {
Set<String> keys = bundle.keySet();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("IntentDump \n\r");
stringBuilder.append("-------------------------------------------------------------\n\r");
for (String key : keys) {
stringBuilder.append(key).append("=").append(bundle.get(key)).append("\n\r");
}
stringBuilder.append("-------------------------------------------------------------\n\r");
Log.i(TAG, stringBuilder.toString());
}
}
}
Hope this helps someone!
The way to do this in bash is
zsh <<< '> test <<< "Hello World!"'
This is one of the interesting differences between zsh and bash: given an unchained >
or >>
, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard.
I tried to use this to send & append my ssh key over ssh to a remote authorized_keys
file, but the remote host was bash, of course, and quietly did nothing.
And that's why you should just use cat
.
You can do two different container one with mobile order and hide on desktop screen, another with desktop order and hide on mobile screen
According to OpenCV cheat-sheet this can be done as follows:
IplImage* oldC0 = cvCreateImage(cvSize(320,240),16,1);
Mat newC = cvarrToMat(oldC0);
The cv::cvarrToMat function takes care of the conversion issues.
Application.Exit()
kills your application but there are some instances that it won't close the application.
End
is better than Application.Exit()
.
I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.
Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.
If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.
How to discover the line which causes the problem?
You have three ways to do that.
1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.
2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.
3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.
In my case I followed the third option and fortunately I pinpoint the line which causes the problem.
This is a long answer but it actually does not solve the exception. How I overcome this exception?
I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t
. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n
) and then it deals each line as a separate json string.
In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.
To declare a variable as a Decimal
, first declare it as a Variant
and then convert to Decimal
with CDec
. The type would be Variant/Decimal
in the watch window:
Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.
In the example below, we see that the expression:
0.1 + 0.11 = 0.21
is either True
or False
, depending on whether the collectibles (0.1,0.11) are declared as Double
or as Decimal
:
Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub
If you really want to use ls
, then format its output using awk:
ls -R /path | awk '
/:$/&&f{s=$0;f=0}
/:$/&&!f{sub(/:$/,"");s=$0;f=1;next}
NF&&f{ print s"/"$0 }'
>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…
http://www.lfd.uci.edu/~gohlke/pythonlibs/
press contrl F type Pillow-2.4.0.win-amd64-py3.3.exe
then click and downloadd the 64 bit version
Pillow is a replacement for PIL, the Python Image Library, which provides image processing functionality and supports many file formats.
Note: use from PIL import Image
instead of import Image
.
PIL-1.1.7.win-amd64-py2.5.exe
PIL-1.1.7.win32-py2.5.exe
Pillow-2.4.0.win-amd64-py2.6.exe
Pillow-2.4.0.win-amd64-py2.7.exe
Pillow-2.4.0.win-amd64-py3.2.exe
Pillow-2.4.0.win-amd64-py3.3.exe
Pillow-2.4.0.win-amd64-py3.4.exe
Pillow-2.4.0.win32-py2.6.exe
Pillow-2.4.0.win32-py2.7.exe
Pillow-2.4.0.win32-py3.2.exe
Pillow-2.4.0.win32-py3.3.exe
Pillow-2.4.0.win32-py3.4.exe
Your
<img src="/home/tony/london.jpg" />
will work for a HTML file read from disk, as it will assume the URL is file:///home/...
. For a file served from a webserver though, the URL will become something like: http://www.yourdomain.com/home/tony/london.jpg
, which can be an invalid URL and not what you really mean.
For about how to serve and where to place your static files, check out this document. Basicly, if you're using django's development server, you want to show him the place where your media files live, then make your urls.py
serve those files (for example, by using some /static/
url prefix).
Will require you to put something like this in your urls.py
:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
In production environment you want to skip this and make your http server (apache, lighttpd, etc) serve static files.
If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.
The error message says your DbContext
(LogManagerContext
) needs a constructor which accepts a DbContextOptions
. But i couldn't find such a constructor in your DbContext
. So adding below constructor probably solves your problem.
public LogManagerContext(DbContextOptions options) : base(options)
{
}
Edit for comment
If you don't register IHttpContextAccessor
explicitly, use below code:
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
The easiest way to do what the original poster wants is to change the delimiter from any whitespace to just the end-of-line character like this:
find whatever ... | xargs -d "\n" cp -t /var/tmp
The local names for a function are decided when the function is defined:
>>> x = 1
>>> def inc():
... x += 5
...
>>> inc.__code__.co_varnames
('x',)
In this case, x
exists in the local namespace. Execution of x += 5
requires a pre-existing value for x
(for integers, it's like x = x + 5
), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError
is named as such.
Compare the other version, where x
is not a local variable, so it can be resolved at the global scope instead:
>>> def incg():
... print(x)
...
>>> incg.__code__.co_varnames
()
Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
Here's a light weight way to use require and exports in your web client. It's a simple wrapper that creates a "namespace" global variable, and you wrap your CommonJS compatible code in a "define" function like this:
namespace.lookup('org.mydomain.mymodule').define(function (exports, require) {
var extern = require('org.other.module');
exports.foo = function foo() { ... };
});
More docs here:
Edit 2017:
use ggplot and theme(legend.position = ""):
library(ggplot2)
library(reshape2)
set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)
df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")
Original answer 2012: Put the legend on the bottom:
set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)
dev.off()
layout(rbind(1,2), heights=c(7,1)) # put legend on bottom 1/8th of the chart
plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')
# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
col=c('black','black','blue'),ncol=3,bty ="n")
Here's a google chrome extension that'll allow you to download your reviews: https://chrome.google.com/webstore/detail/my-play-store-reviews/ldggikfajgoedghjnflfafiiheagngoa?hl=en
date('Y-m-d H:i:s')
Look here for more details: http://pl.php.net/manual/en/function.date.php
You just need to wrap object in ()
var arr = [{_x000D_
id: 1,_x000D_
name: 'bill'_x000D_
}, {_x000D_
id: 2,_x000D_
name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
This happens when you add a framework to your project and unintentionally copy the framework into your project directory.
The fix is to check your project directory (where you store your project on disk) for any iphone SDK *.Framework files and delete them.
Project will build fine afterwards.
In Android the visual design is stored in XML files and each Activity is associated to a design.
setContentView(R.layout.main)
R
means Resource
layout
means design
main
is the xml you have created under res->layout->main.xml
Whenever you want to change the current look of an Activity or when you move from one Activity to another, the new Activity must have a design to show. We call setContentView
in onCreate with the desired design as argument.
You can use
call script.bat
or just
script.bat
setBounds
is used to define the bounding rectangle of a component. This includes it's position and size.
The is used in a number of places within the framework.
For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.
You can use ajax and jquery to solve this problem:
<script>
function getData() {
$.ajax({
url : "/urlpattern",
type : "post",
success : function(data) {
alert("success");
}
});
}
</script>
<form method="POST">
<button name="data" type="button" onclick="getData()">Click</button>
</form>
If you want to create two table's columns into a relationship by using a query try the following:
Alter table Foreign_Key_Table_name add constraint
Foreign_Key_Table_name_Columnname_FK
Foreign Key (Column_name) references
Another_Table_name(Another_Table_Column_name)
You can also do this:
static ArrayList<String> reverseReturn(ArrayList<String> alist)
{
if(alist==null || alist.isEmpty())
{
return null;
}
ArrayList<String> rlist = new ArrayList<>(alist);
Collections.reverse(rlist);
return rlist;
}
Answer to Question 1
Here's what I did on a Ubuntu EC2
:
A) Login as root using the keypairs
B) Setup the necessary users and their passwords with
# sudo adduser USERNAME
# sudo passwd USERNAME
C) Edit /etc/ssh/sshd_config
setting
PasswordAuthentication yes
PermitRootLogin yes
D) Restart the ssh
daemon with
# sudo service ssh restart
just change ssh to sshd if you are using centOS
Now you can login into your ec2
instance without key pairs.
self.materials
is a dict
and by default you are iterating over just the keys (which are strings).
Since self.materials
has more than two keys*, they can't be unpacked into the tuple
"k, m
", hence the ValueError
exception is raised.
In Python 2.x, to iterate over the keys and the values (the tuple
"k, m
"), we use self.materials.iteritems()
.
However, since you're throwing the key away anyway, you may as well simply iterate over the dictionary's values:
for m in self.materials.itervalues():
In Python 3.x, prefer dict.values()
(which returns a dictionary view object):
for m in self.materials.values():
Your issue here is that you're not understanding the scope that you're setting.
You are passing the ready
function a function itself. Within this function, you're creating another function called codeAddress
. This one exists within the scope that created it and not within the window object (where everything and its uncle could call it).
For example:
var myfunction = function(){
var myVar = 12345;
};
console.log(myVar); // 'undefined' - since it is within
// the scope of the function only.
Have a look here for a bit more on anonymous functions: http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
Another thing is that I notice you're using jQuery on that page. This makes setting click handlers much easier and you don't need to go into the hassle of setting the 'onclick' attribute in the HTML. You also don't need to make the codeAddress
method available to all:
$(function(){
$("#imgid").click(function(){
var address = $("#formatedAddress").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
}
});
});
});
(You should remove the existing onclick
and add an ID to the image element that you want to handle)
Note that I've replaced $(document).ready()
with its shortcut of just $()
(http://api.jquery.com/ready/). Then the click method is used to assign a click handler to the element. I've also replaced your document.getElementById
with the jQuery object.
My resolution was kind of stupid.
I installed a copy of .net 3.5
Created another app pool and selected .net 3.5 (it says 2.0.5077 in the drop down)
Added my website to that app pool
Recycled the old and new pools and the site started working.
It came down to me not having 3.5 installed even though the turn on windows features said I did and creating another app pool to use. I hope this helps others.
In my case, set the cpp file to "C/C++ compiler" in "property"->"general", resolve the LNK2019 error.
Yes, fork is a clone. It emerged because, you cannot push to others' copies without their permission. They make a copy of it for you (fork), where you will have write permission as well.
In the future if the actual owner or others users with a fork like your changes they can pull it back to their own repository. Alternatively you can send them a "pull-request".
timedelta to string, use for print running time info.
def strfdelta_round(tdelta, round_period='second'):
"""timedelta to string, use for measure running time
attend period from days downto smaller period, round to minimum period
omit zero value period
"""
period_names = ('day', 'hour', 'minute', 'second', 'millisecond')
if round_period not in period_names:
raise Exception(f'round_period "{round_period}" invalid, should be one of {",".join(period_names)}')
period_seconds = (86400, 3600, 60, 1, 1/pow(10,3))
period_desc = ('days', 'hours', 'mins', 'secs', 'msecs')
round_i = period_names.index(round_period)
s = ''
remainder = tdelta.total_seconds()
for i in range(len(period_names)):
q, remainder = divmod(remainder, period_seconds[i])
if int(q)>0:
if not len(s)==0:
s += ' '
s += f'{q:.0f} {period_desc[i]}'
if i==round_i:
break
if i==round_i+1:
s += f'{remainder} {period_desc[round_i]}'
break
return s
e.g. auto omit zero leading period:
>>> td = timedelta(days=0, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'second')
'2 hours 5 mins 8 secs'
or omit middle zero period:
>>> td = timedelta(days=2, hours=0, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'millisecond')
'2 days 5 mins 8 secs 3 msecs'
or round to minutes, omit below minutes:
>>> td = timedelta(days=1, hours=2, minutes=5, seconds=8, microseconds=3549)
>>> strfdelta_round(td, 'minute')
'1 days 2 hours 5 mins'
You can check out the CXF. You can visit the JAX-RS Article here
Calling is as simple as this (quote):
BookStore store = JAXRSClientFactory.create("http://bookstore.com", BookStore.class);
// (1) remote GET call to http://bookstore.com/bookstore
Books books = store.getAllBooks();
// (2) no remote call
BookResource subresource = store.getBookSubresource(1);
// {3} remote GET call to http://bookstore.com/bookstore/1
Book b = subresource.getDescription();
Taking care of whether the array starts at zero or one. Also, when position 0 or 1 is returned by the function, making sure that the same is not confused as True or False returned by the function.
Function array_return_index(arr As Variant, val As Variant, Optional array_start_at_zero As Boolean = True) As Variant
Dim pos
pos = Application.Match(val, arr, False)
If Not IsError(pos) Then
If array_start_at_zero = True Then
pos = pos - 1
'initializing array at 0
End If
array_return_index = pos
Else
array_return_index = False
End If
End Function
Sub array_return_index_test()
Dim pos, arr, val
arr = Array(1, 2, 4, 5)
val = 1
'When array starts at zero
pos = array_return_index(arr, val)
If IsNumeric(pos) Then
MsgBox "Array starting at 0; Value found at : " & pos
Else
MsgBox "Not found"
End If
'When array starts at one
pos = array_return_index(arr, val, False)
If IsNumeric(pos) Then
MsgBox "Array starting at 1; Value found at : " & pos
Else
MsgBox "Not found"
End If
End Sub
You enter the
if (!(cin >> input_var))
statement if an error occurs when taking the input from cin. If an error occurs then an error flag is set and future attempts to get input will fail. That's why you need
cin.clear();
to get rid of the error flag. Also, the input which failed will be sitting in what I assume is some sort of buffer. When you try to get input again, it will read the same input in the buffer and it will fail again. That's why you need
cin.ignore(10000,'\n');
It takes out 10000 characters from the buffer but stops if it encounters a newline (\n). The 10000 is just a generic large value.
You can read files in raw/res using getResources().openRawResource(R.raw.myfilename)
.
BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt
or my_data.bin
will not be listed in R.
Please follow the following steps
Adding libxml2
libxml2.dylib can be found on your mac machin at /usr/lib/libxml2.dylib
Change "Header Search Paths"
Click on [Project Name] (in left panel) -> Project -> Build Settings -> Select All (default is Basic)
Type Header Search Paths in search box
Double click on Header Search Paths -> + -> "$(SDKROOT)/usr/include/libxml2"
Add -lxml2 to "Other linker flag"
Search for "Other Linker Flags" as search in step 2
click on the "Other Linker Flags" row. Click the "+" and add "-lxml2" to the list.
Change your project type to ARC -> No i.e Automatic Reference Counting to No You can search ARC as per in step 2
I'm didn't totally follow, but to add an action listener, you just call addActionListener (from Abstract Button). If this doesn't totally answer your question, can you provide some more details?
set -o noclobber
option and attempt to overwrite a common file.if ! (set -o noclobber ; echo > /tmp/global.lock) ; then
exit 1 # the global.lock already exists
fi
# ... remainder of script ...
This example will wait for the global.lock
file but timeout after too long.
function lockfile_waithold()
{
declare -ir time_beg=$(date '+%s')
declare -ir time_max=7140 # 7140 s = 1 hour 59 min.
# poll for lock file up to ${time_max}s
# put debugging info in lock file in case of issues ...
while ! \
(set -o noclobber ; \
echo -e "DATE:$(date)\nUSER:$(whoami)\nPID:$$" > /tmp/global.lock \
) 2>/dev/null
do
if [ $(($(date '+%s') - ${time_beg})) -gt ${time_max} ] ; then
echo "Error: waited too long for lock file /tmp/global.lock" 1>&2
return 1
fi
sleep 1
done
return 0
}
function lockfile_release()
{
rm -f /tmp/global.lock
}
if ! lockfile_waithold ; then
exit 1
fi
trap lockfile_release EXIT
# ... remainder of script ...
This has reliably worked for me on an Ubuntu 16 host with multiple instances of a bash script that used the same system-wide "lock" file.
(This is similar to this post by @Barry Kelly which was noticed afterward.)
This code worked great for me .. I hope it will also work great for you .. All you have to do is just inject $anchorScroll to your run block and apply listener function to the rootScope like I have done in the below example ..
angular.module('myAngularApp')
.run(function($rootScope, Auth, $state, $anchorScroll){
$rootScope.$on("$locationChangeSuccess", function(){
$anchorScroll();
});
Here's the calling order of Angularjs Module:
app.config()
app.run()
directive's compile functions (if they are found in the dom)
app.controller()
directive's link functions (again, if found)
RUN BLOCK get executed after the injector is created and are used to kickstart the application.. it means when you redirected to the new route view ,the listener in the run block calls the
$anchorScroll()
and you can now see the scroll starts to the top with the new routed view :)
In Python 2.7 this might have worked fine:
>>> a = b = c = range(20)
>>> zip(a, b, c)
But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>
):
>>> a = b = c = range(20)
>>> list(zip(a, b, c))
request.getContextPath()-
returns root path of your application, while
../
- returns parent directory of a file.
You use request.getContextPath(), as it will always points to root of your application. If you were to move your jsp file from one directory to another, nothing needs to be changed. Now, consider the second approach. If you were to move your jsp files from one folder to another, you'd have to make changes at every location where you are referring your files.
Also, better approach of using request.getContextPath() will be to set 'request.getContextPath()' in a variable and use that variable for referring your path.
<c:set var="context" value="${pageContext.request.contextPath}" />
<script src="${context}/themes/js/jquery.js"></script>
PS- This is the one reason I can figure out. Don't know if there is any more significance to it.
Considering you want to check for ASCII Alphanumeric characters, Try this:
"^[a-zA-Z0-9]*$"
. Use this RegEx in String.matches(Regex)
, it will return true if the string is alphanumeric, else it will return false.
public boolean isAlphaNumeric(String s){
String pattern= "^[a-zA-Z0-9]*$";
return s.matches(pattern);
}
If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html
If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.
You can do it with PhantomJSDriver.
PhantomJSDriver pd = ((PhantomJSDriver) ((WebDriverFacade) getDriver()).getProxiedDriver());
pd.executePhantomJS(
"this.onResourceRequested = function(request, net) {" +
" net.setHeader('header-name', 'header-value')" +
"};");
Using the request object, you can filter also so the header won't be set for every request.
always year for bootstrap 3 datetimepicker https://eonasdan.github.io/bootstrap-datetimepicker/
$('#year').datetimepicker({
format: 'YYYY',
viewMode: "years",
});
$("#year").on("dp.hide", function (e) {
$('#year').datetimepicker('destroy');
$('#year').datetimepicker({
format: 'YYYY',
viewMode: "years",
});
});
In Swift 4 and 5. I created a closure variable containing two parameter dictionary and bool.
var completionHandler:([String:Any], Bool)->Void = { dict, success in
if success {
print(dict)
}
}
Calling the closure variable
self.completionHandler(["name":"Gurjinder singh"],true)
try this...
public class Student
{
public int Grade { get; set; }
public string Name { get; set; }
public override string ToString()
{
return string.Format("Name{0} : Grade{1}", Name, Grade);
}
}
class Program
{
static void Main(string[] args)
{
List<Student> listStudents = new List<Student>();
listStudents.Add(new Student() { Grade = 10, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 10, Name = "Maria" });
listStudents.Add(new Student() { Grade = 11, Name = "Mario" });
listStudents.Add(new Student() { Grade = 15, Name = "Mario" });
listStudents.Add(new Student() { Grade = 10, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 10, Name = "Luana" });
listStudents.Add(new Student() { Grade = 11, Name = "Luana" });
listStudents.Add(new Student() { Grade = 22, Name = "Maria" });
listStudents.Add(new Student() { Grade = 55, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 77, Name = "Maria" });
listStudents.Add(new Student() { Grade = 66, Name = "Maria" });
listStudents.Add(new Student() { Grade = 88, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 42, Name = "Pedro" });
listStudents.Add(new Student() { Grade = 33, Name = "Bruno" });
listStudents.Add(new Student() { Grade = 33, Name = "Luciana" });
listStudents.Add(new Student() { Grade = 17, Name = "Maria" });
listStudents.Add(new Student() { Grade = 25, Name = "Luana" });
listStudents.Add(new Student() { Grade = 25, Name = "Pedro" });
listStudents.GroupBy(g => g.Name).OrderBy(g => g.Key).SelectMany(g => g.OrderByDescending(x => x.Grade)).ToList().ForEach(x => Console.WriteLine(x.ToString()));
}
}
If an object's property may refer to some other object then you can test that for undefined before trying to use its properties:
if (thing && thing.foo)
alert(thing.foo.bar);
I could update my answer to better reflect your situation if you show some actual code, but possibly something like this:
function someFunc(parameterName) {
if (parameterName && parameterName.foo)
alert(parameterName.foo.bar);
}
Here in my sample I find out the solution of this, because I had the same problem with updates and subquerys:
UPDATE
A
SET
A.ValueToChange = B.NewValue
FROM
(
Select * From C
) B
Where
A.Id = B.Id
I would recommend you to use background-image instead of default list.
.listStyle {
list-style: none;
background: url(image_path.jpg) no-repeat left center;
padding-left: 30px;
width: 20px;
height: 20px;
}
Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:
.liststyle{
list-style: none;
margin: 0;
padding: 0;
}
.liststyle:before {
content: "• ";
color: red; /* or whatever color you prefer */
font-size: 20px;/* or whatever the bullet size you prefer */
}
I had the same exact isuue with the latest Android Studio 2.3.2 and Instant Run.
here what I did : (I'll give you two ways to achive that one disable for specefic project, and second for whole android studio):
on root of your projct open gradle-->gradle-wrapper.properties then change the value
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
and on your project build.gradle change the value
classpath 'com.android.tools.build:gradle:2.2.3'
in older version of AS settings for instant run is
File -> Other Settings -> Default Settings ->Build,Execution,Deployment
However In most recent version of Android Studio i.e 2.3.2 , instant run settings is:
Edited: If for any reason the Instant-run settings is greyed out do this :
Help-> Find Action...
and then type 'enable isntant run' and click (now you should be able to change the value in Preferences... or file->Settings... , if that was the case then this is an Android Studio bug :-)
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
My solution is in T-SQL without any pivots:
SELECT
CompanyName,
SUM(CASE WHEN (action='EMAIL') THEN 1 ELSE 0 END) AS Email,
SUM(CASE WHEN (action='PRINT' AND pagecount=1) THEN 1 ELSE 0 END) AS Print1Pages,
SUM(CASE WHEN (action='PRINT' AND pagecount=2) THEN 1 ELSE 0 END) AS Print2Pages,
SUM(CASE WHEN (action='PRINT' AND pagecount=3) THEN 1 ELSE 0 END) AS Print3Pages
FROM
Company
GROUP BY
CompanyName
When you include Underscore, it attaches itself to the window
object, and so is available globally.
So you can use it from Angular code as-is.
You can also wrap it up in a service or a factory, if you'd like it to be injected:
var underscore = angular.module('underscore', []);
underscore.factory('_', ['$window', function($window) {
return $window._; // assumes underscore has already been loaded on the page
}]);
And then you can ask for the _
in your app's module:
// Declare it as a dependency of your module
var app = angular.module('app', ['underscore']);
// And then inject it where you need it
app.controller('Ctrl', function($scope, _) {
// do stuff
});
Use DATEDIFF
Select I.Fee
From Item I
WHERE DATEDIFF(day, GETDATE(), I.DateCreated) < 365
I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.
https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886
@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo Zeichenfolge die zu suchende Zeichenfolge wird mit FIND bestimmt
echo ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^
^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1
:Eingabe temporär speichern
>"%intemp%" find /n /v ""
:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr
:end
del "%intemp%"
exit /b %xcode%
:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^
^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
setlocal enabledelayedexpansion
for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
set "Lineout=!LineStr:~0,%%n!!string!"
echo(!Lineout:*]=!
exit /b
)
) )
exit /b
:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout% exit /b
set "Line=%%i"
setlocal enabledelayedexpansion
echo(!Line:*]=!
endlocal
)
exit /b
@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo Zeichenfolge String zum Durchsuchen
echo B Zeichen Wonach am Anfang gesucht wird
echo n Auszulassende Zeichenanzahl
echo E Zeichen was das Ende der Zeichen Bestimmt
echo /i Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set "Original=%~1"
set "Begin=%~2"
set /a Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set "CaseInt=%~5"
:: end Setting Input Param
set "out="
set "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
if defined out exit /b 0
for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
set "out=1"
setlocal enabledelayedexpansion
set "In= !Original!"
set "In=!In:~,%%a!"
echo !In:^~2!
endlocal
) )
if not defined out exit /b 1
exit /b
::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)
You can use .filter()
method of the Array
object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
Some old browsers like IE8 doesn't support .filter()
method of the Array
object, if you are using jQuery you can use .filter()
method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
For me the problem was that on my Podfile I didn't put use_frameworks!
. I just uncomment that line, run pod install
on the terminal again. And it got fixed.
It was commented since the app was entirely made on Objective-C. Since the app now uses Swift I had to make that change on the Podfile
There is also bind_rows(x, ...)
in dplyr
.
> system.time({ df.Base <- do.call("rbind", listOfDataFrames) })
user system elapsed
0.08 0.00 0.07
>
> system.time({ df.dplyr <- as.data.frame(bind_rows(listOfDataFrames)) })
user system elapsed
0.01 0.00 0.02
>
> identical(df.Base, df.dplyr)
[1] TRUE
Check documentation for model.fit here.
By setting verbose 0, 1 or 2 you just say how do you want to 'see' the training progress for each epoch.
verbose=0
will show you nothing (silent)
verbose=1
will show you an animated progress bar like this:
verbose=2
will just mention the number of epoch like this:
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
I always use this in jQuery for disabling links
$("form a").attr("disabled", "disabled");
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
To change color of hint and edit text underline color : colorControlActivated
To change character counter color : textColorSecondary
To change error message color : colorControlNormal
To change password visibility button tint : colorForeground
For more info on TextInputLayout read http://www.zoftino.com/android-textinputlayout-tutorial
<style name="MyAppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorControlActivated">#e91e63</item>
<item name="android:colorForeground">#33691e</item>
<item name="colorControlNormal">#f57f17</item>
<item name="android:textColorSecondary">#673ab7</item>
</style>
The 'frame' command will give you what you are looking for. (This can be abbreviated just 'f'). Here is an example:
(gdb) frame
\#0 zmq::xsub_t::xrecv (this=0x617180, msg_=0x7ffff00008e0) at xsub.cpp:139
139 int rc = fq.recv (msg_);
(gdb)
Without an argument, 'frame' just tells you where you are at (with an argument it changes the frame). More information on the frame command can be found here.
I prefer using Hamcrest because it gives much better output in case of a failure
Assert.assertThat(listUnderTest,
IsIterableContainingInOrder.contains(expectedList.toArray()));
Instead of reporting
expected true, got false
it will report
expected List containing "1, 2, 3, ..." got list containing "4, 6, 2, ..."
IsIterableContainingInOrder.contain
According to the Javadoc:
Creates a matcher for Iterables that matches when a single pass over the examined Iterable yields a series of items, each logically equal to the corresponding item in the specified items. For a positive match, the examined iterable must be of the same length as the number of specified items
So the listUnderTest
must have the same number of elements and each element must match the expected values in order.
This works on Windows with Cygwin installed:
System.getenv("NUMBER_OF_PROCESSORS")
Type the command mvn -version
directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).
If you want to the batch program to exit back to the prompt and not close the prompt (A.K.A cmd.exe) you can use "exit /b".
This may help.
set /p _sure="Are you sure?"
::The underscore is used to ensure that "sure" is not an enviroment
::varible
if /I NOT "_sure"=="y" (
::the /I makes it so you can
exit /b
) else (
::Any other modifications...
)
Or if you don't want to use as many lines...
Set /p _sure="Are you sure?"
if /I NOT "_sure"=="y" exit /b
::Any other modifications and commands.
Hope this helps...
I have been in similar situation before. In Command prompt, you type 'start-ssh-agent' and voila! The ssh-agent will be started. Input the passphrase if it asked you.
To get the current Date in Kotlin do this:
val dateNow = Calendar.getInstance().time
That's correct, initially the ResultSet
's cursor is pointing to before the first row, if the first call to next()
returns false
then there was no data in the ResultSet
.
If you use this method, you may have to call beforeFirst()
immediately after to reset it, since it has positioned itself past the first row now.
It should be noted however, that Seifer's answer below is a more elegant solution to this question.
Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);
As the title suggests that we want to adjust the size of the labels and not the tick marks I figured that I actually might add something to the question, you need to use the mtext() if you want to specify one of the label sizes, or you can just use par(cex.lab=2)
as a simple alternative. Here's a more advanced mtext() example:
set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data=foo,
yaxt="n", ylab="",
xlab="Regular boring x",
pch=16,
col="darkblue")
axis(2,cex.axis=1.2)
mtext("Awesome Y variable", side=2, line=2.2, cex=2)
You may need to adjust the line=
option to get the optimal positioning of the text but apart from that it's really easy to use.
try this
document.getElementById("datapicker").addEventListener("submit", function())
This might not work if the localhost has been changed from 127.0.0.1
Try
import socket
ipaddress=socket.gethostbyname(socket.gethostname())
if ipaddress=="127.0.0.1":
print("You are not connected to the internet!")
else:
print("You are connected to the internet with the IP address of "+ ipaddress )
Unless edited , your computers IP will be 127.0.0.1 when not connected to the internet. This code basically gets the IP address and then asks if it is the localhost IP address . Hope that helps
If you are in an interactive environment like Jupyter
or ipython
you might be interested in clearing unwanted var's if they are getting heavy.
The magic-commands reset
and reset_selective
is vailable on interactive python sessions like ipython
and Jupyter
1) reset
reset
Resets the namespace by removing all names defined by the user, if called without arguments.
in
and the out
parameters specify whether you want to flush the in/out caches. The directory history is flushed with the dhist
parameter.
reset in out
Another interesting one is array
that only removes numpy Arrays:
reset array
2) reset_selective
Resets the namespace by removing names defined by the user. Input/Output history are left around in case you need them.
Clean Array Example:
In [1]: import numpy as np
In [2]: littleArray = np.array([1,2,3,4,5])
In [3]: who_ls
Out[3]: ['littleArray', 'np']
In [4]: reset_selective -f littleArray
In [5]: who_ls
Out[5]: ['np']
Source: http://ipython.readthedocs.io/en/stable/interactive/magics.html
I was able to solve the same problem with different solution.
The solution that worked for me was to Right click project "pom.xml" in eclipse and select "Maven Install".
If you have Multiple Insert Statements then Toad has a simple Way to execute all the Insert Statements.
Right Click On the Highlighted Insert Statements --> Select Execute Menu --> Execute Script
This will automatically start running the Insert Statements
This is how you link a JS file in HTML
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
- tag is used to define a client-side script, such as a JavaScript.
type
- specify the type of the script
src
- script file name and path
The below worked really good for me. I patched together all the above answers plus read about displaying object properties in the following link and came up with the below short read about printing objects
add the following text to a file named print_object.ps1:
$date = New-Object System.DateTime
Write-Output $date | Get-Member
Write-Output $date | Select-Object -Property *
open powershell command prompt, go to the directory where that file exists and type the following:
powershell -ExecutionPolicy ByPass -File is_port_in_use.ps1 -Elevated
Just substitute 'System.DateTime' with whatever object you wanted to print. If the object is null, nothing will print out.
Yes. Here's the way using pipe( | ) separator,
try
{
.......
}
catch
{
catch(IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e)
}
Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.
cin.get();
Yes, there's a way to do this without the plugin! But it is not as clean and elegant as using the mentioned plugin. Here it is.
Assuming it's Rails 3 (I don't know if it's different in previous versions),
keep this in your model:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
and in the view, instead of leaving
@instance.errors.full_messages
as it would be when we use the scaffold generator, put:
@instance.errors.first[1]
And you will get just the message you specified in the model, without the attribute name.
Explanation:
#returns an hash of messages, one element foreach field error, in this particular case would be just one element in the hash:
@instance.errors # => {:song_rep_xyz=>"can't be empty"}
#this returns the first element of the hash as an array like [:key,"value"]
@instance.errors.first # => [:song_rep_xyz, "can't be empty"]
#by doing the following, you are telling ruby to take just the second element of that array, which is the message.
@instance.errors.first[1]
So far we are just displaying only one message, always for the first error. If you wanna display all errors you can loop in the hash and show the values.
Hope that helped.
try
block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
And as suggested above by Siu Ching Pong -Asuka Kenji with the function which in my opinion makes more sense and leaves you with the convenience of the map type without the function wrapper around:
// romanNumeralDict returns map[int]string dictionary, since the return
// value is always the same it gives the pseudo-constant output, which
// can be referred to in the same map-alike fashion.
var romanNumeralDict = func() map[int]string { return map[int]string {
1000: "M",
900: "CM",
500: "D",
400: "CD",
100: "C",
90: "XC",
50: "L",
40: "XL",
10: "X",
9: "IX",
5: "V",
4: "IV",
1: "I",
}
}
func printRoman(key int) {
fmt.Println(romanNumeralDict()[key])
}
func printKeyN(key, n int) {
fmt.Println(strings.Repeat(romanNumeralDict()[key], n))
}
func main() {
printRoman(1000)
printRoman(50)
printKeyN(10, 3)
}
Another possibility I came up with, inspired by using grep, is:
tasklist /FI "IMAGENAME eq myapp.exe" 2>NUL | find /I /N "myapp.exe">NUL
if "%ERRORLEVEL%"=="0" echo Program is running
It doesn't need to save an extra file, so I prefer this method.
You can use even "MouseExited" to control. example:
private void jtSoMauMouseExited(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
try {
if (Integer.parseInt(jtSoMau.getText()) > 1) {
//auto update field
SoMau = Integer.parseInt(jtSoMau.getText());
int result = SoMau / 5;
jtSoBlockQuan.setText(String.valueOf(result));
}
} catch (Exception e) {
}
}
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
Maybe you only need a shallow copy, in that case use Object.MemberWiseClone()
.
There are good recommendations in the documentation for MemberWiseClone()
for strategies to deep copy: -
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx
Alternatively,
1) Without touching System.Reflection
namespace,
GETNAME(new { myInput });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}
2) The below one can be faster though (from my tests)
GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
You can also extend this for properties of objects (may be with extension methods):
new { myClass.MyProperty1 }.GETNAME();
You can cache property values to improve performance further as property names don't change during runtime.
The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine
As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:
and
, or
and not
have much lower precedence than &&
, ||
and !
and
and or
have the same precedence, while &&
has higher precedence than ||
In general, it is good style to avoid the use of and
, or
and not
and use &&
, ||
and !
instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)
The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that
idiom, where do_this
returns false
or nil
if there is an error and only then is do_that
executed instead. (Analogous, there is also the do_this and then_do_that
idiom.)
Examples:
download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache
Sometimes, this can make control flow a little bit more fluent than using if
or unless
.
It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.
private String convertFrom(String lines, String from, String to) {
ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
CharBuffer cb = Charset.forName(to).decode(bb);
return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};
Use:
using System.IO;
string oldFilePath = @"C:\OldFile.txt"; // Full path of old file
string newFilePath = @"C:\NewFile.txt"; // Full path of new file
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.Move(oldFilePath, newFilePath);
Your request should be to the server, NOT the server.js file which instantiates it. So, the request should look something like this: xmlhttp.open("GET","http://localhost:8001/", true);
Also, you are trying to serve the front-end (index.html) AND serve AJAX requests at the same URI. To accomplish this, you are going to have to introduce logic to your server.js that will differentiate between your AJAX requests and a normal http access request. To do this, you'll want to either introduce GET/POST data (i.e. call http://localhost:8001/?getstring=true
) or use a different path for your AJAX requests (i.e. call http://localhost:8001/getstring
). On the server end then, you'll need to examine the request object to determine what to write on the response. For the latter option, you need to use the 'url' module to parse the request.
You are correctly calling listen()
but incorrectly writing the response. First of all, if you wish to serve index.html when navigating to http://localhost:8001/, you need to write the contents of the file to the response using response.write()
or response.end()
. First, you need to include fs=require('fs')
to get access to the filesystem. Then, you need to actually serve the file.
XMLHttpRequest needs a callback function specified if you use it asynchronously (third parameter = true, as you have done) AND want to do something with the response. The way you have it now, string
will be undefined
(or perhaps null
), because that line will execute before the AJAX request is complete (i.e. the responseText is still empty). If you use it synchronously (third parameter = false), you can write inline code as you have done. This is not recommended as it locks the browser during the request. Asynchronous operation is usually used with the onreadystatechange function, which can handle the response once it is complete. You need to learn the basics of XMLHttpRequest. Start here.
Here is a simple implementation that incorporates all of the above:
server.js:
var http = require('http'),
fs = require('fs'),
url = require('url'),
choices = ["hello world", "goodbye world"];
http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
if(path=="/getstring"){
console.log("request recieved");
var string = choices[Math.floor(Math.random()*choices.length)];
console.log("string '" + string + "' chosen");
response.writeHead(200, {"Content-Type": "text/plain"});
response.end(string);
console.log("string sent");
}else{
fs.readFile('./index.html', function(err, file) {
if(err) {
// write an error response or nothing here
return;
}
response.writeHead(200, { 'Content-Type': 'text/html' });
response.end(file, "utf-8");
});
}
}).listen(8001);
console.log("server initialized");
frontend (part of index.html):
function newGame()
{
guessCnt=0;
guess="";
server();
displayHash();
displayGuessStr();
displayGuessCnt();
}
function server()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/getstring", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}
You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.
UPDATE: I have changed response.sendHeader()
to the new response.writeHead()
in the code above !!!
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
I just had to update legacy Weblogic 8 app to use a data-source instead of hard-coded JDBC string. Datasource JNDI name on the configuration tab in the Weblogic admin showed: "weblogic.jdbc.ESdatasource", below are two ways that worked:
Context ctx = new InitialContext();
DataSource dataSource;
try {
dataSource = (DataSource) ctx.lookup("weblogic.jdbc.ESdatasource");
response.getWriter().println("A " +dataSource);
}catch(Exception e) {
response.getWriter().println("A " + e.getMessage() + e.getCause());
}
//or
try {
dataSource = (DataSource) ctx.lookup("weblogic/jdbc/ESdatasource");
response.getWriter().println("F "+dataSource);
}catch(Exception e) {
response.getWriter().println("F " + e.getMessage() + e.getCause());
}
//use your datasource
conn = datasource.getConnection();
That's all folks. No passwords and initial context factory needed from the inside of Weblogic app.
As of June 14th 2013 (HTML5), there is a significant difference
Browser : Chrome 27.X.X
References: document.location, window.location (MDN)
type: Object
The object when called by itself document.location
return its origin
+ pathname
properties concatenated.
To retrieve just the URL as a string, the read-only document.URL
property can be used.
ancestorOrigins: DOMStringList
assign: function () { [native code] }
hash: ""
host: "stackoverflow.com"
hostname: "stackoverflow.com"
href: "http://stackoverflow.com/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location?rq=1"
origin: "http://stackoverflow.com"
pathname: "/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location"
port: ""
protocol: "http:"
reload: function () { [native code] }
replace: function () { [native code] }
search: "?rq=1"
toString: function toString() { [native code] }
valueOf: function valueOf() { [native code] }
type: string
http://stackoverflow.com/questions/2652816/what-is-the-difference-between-document-location-href-and-document-location?rq=1
Have you tried using double tabs? To make a box:
Start on a fresh line
Hit tab twice, type up the content
Your content should appear in a box
It works for me in a regular Rmarkdown document with html output. The double-tabbed portion should appear in a rounded rectangular light grey box.
In my case, I wanted to check out
a new branch
that has cut recently
but it's it big in size and I want to save time and internet bandwidth, as I'm in a slow metered network
so I copped the previous branch
that I already checked in
I went to the working directory, and from svn info, I can see it's on the previous branch I did the following command (you can find this command from svn switch --help
)
svn switch ^/branches/newBranchName
go check svn info
again you can see it is becoming the newBranchName go ahead and svn up
and this how I got the new branch easily, quickly with minimum data transmitting over the internet
hope sharing my case helps and speeds up your work
The !
should be around the outside of the statement:
data[!(data$v1 %in% c("b", "d", "e")), ]
v1 v2 v3 v4
1 a v d c
2 a v d d
5 c k d c
6 c r p g
Thank you for planting a seed, Cel! I've been struggling with this for hours, finally got it. I was counting a text field, oops, calculation failed.
Created 2 helper columns in my raw data, each resulting in 1 if condition met, 0 if not. Then pulled each into a pivot column, mine are called, "Inbd" (for Inbound), "Back", where "Back" is a return to sending facility, so in reality the total is one trip, not 2 trips, i.e., back is a subset of inbound and not every inbd has a back (obviously). Trying to calculate in the pivot table so I can sort on the field the rate of back to inbound for each sending facility.
For my calculated field I used: =IFERROR(IF(Pvt_Back>0,Pvt_Back/Pvt_Inbd,0),0)
So: if we sent back to sending some number of times greater than 0, divide Back/Inbd to give me a rate; if equal to 0, then 0; if Inbd = 0, then 0 to avoid Div/0 error.
Thanks again!! :)
You can also check like struct_var == (struct{})
. This does not allow you to compare to nil but it does check if it is initialized or not. Be careful while using this method. If your struct can have zero values for all of its fields you won't have great time.
package main
import "fmt"
type A struct {
Name string
}
func main() {
a := A{"Hello"}
var b A
if a == (A{}) {
fmt.Println("A is empty") // Does not print
}
if b == (A{}) {
fmt.Println("B is empty") // Prints
}
}
function remove_prefix($text, $prefix) {
if(0 === strpos($text, $prefix))
$text = substr($text, strlen($prefix)).'';
return $text;
}
Here is the most simple way.
import tkinter as tk
root = tk.Tk()
root.geometry('200x200')
root.resizable(width=0, height=0)
root.mainloop()
I don't think there is anything to specify. It's pretty straight forward.
For me it was a issue with react-native dependency on next version of react package, while in my package.json the old one was specified. Upgrading my react version solved this problem.
Yes it can. A private constructor would exist to prevent the class from being instantiated, or because construction happens only internally, e.g. a Factory pattern. See here for more information.
As noted, you could use a target attribute, but it was technically deprecated in XHTML. That leaves you with using javascript, usually something like parent.window.location
.
It's Never late. This error shows that you have After Installation of OS in Virtual Box you Remove the ISO file from Virtual Box Setting or you change your OS ISO file location. Thus you can Solve your Problem bY following given steps or you can watch video at Link
To watch Video click on Below link: Link
If this doesn't work I'm out of ideas. This way you get the 4 columns in both tables (as Bar
owns them and Foo
uses them to reference Bar
) and the generated IDs in both entities. The set of 4 columns has to be unique in Bar
so the many-to-one relation doesn't become a many-to-many.
@Embeddable
public class AnEmbeddedObject
{
@Column(name = "column_1")
private Long column1;
@Column(name = "column_2")
private Long column2;
@Column(name = "column_3")
private Long column3;
@Column(name = "column_4")
private Long column4;
}
@Entity
public class Foo
{
@Id
@Column(name = "id")
@GeneratedValue(generator = "seqGen")
@SequenceGenerator(name = "seqGen", sequenceName = "FOO_ID_SEQ", allocationSize = 1)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({
@JoinColumn(name = "column_1", referencedColumnName = "column_1"),
@JoinColumn(name = "column_2", referencedColumnName = "column_2"),
@JoinColumn(name = "column_3", referencedColumnName = "column_3"),
@JoinColumn(name = "column_4", referencedColumnName = "column_4")
})
private Bar bar;
}
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = {
"column_1",
"column_2",
"column_3",
"column_4"
}))
public class Bar
{
@Id
@Column(name = "id")
@GeneratedValue(generator = "seqGen")
@SequenceGenerator(name = "seqGen", sequenceName = "BAR_ID_SEQ", allocationSize = 1)
private Long id;
@Embedded
private AnEmbeddedObject anEmbeddedObject;
}
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
Just to demonstrate the flexibility of javascript: you can use a oneliner for this
function padLeft(nr, n, str){
return Array(n-String(nr).length+1).join(str||'0')+nr;
}
//or as a Number prototype method:
Number.prototype.padLeft = function (n,str){
return Array(n-String(this).length+1).join(str||'0')+this;
}
//examples
console.log(padLeft(23,5)); //=> '00023'
console.log((23).padLeft(5)); //=> '00023'
console.log((23).padLeft(5,' ')); //=> ' 23'
console.log(padLeft(23,5,'>>')); //=> '>>>>>>23'
If you want to use this for negative numbers also:
Number.prototype.padLeft = function (n,str) {
return (this < 0 ? '-' : '') +
Array(n-String(Math.abs(this)).length+1)
.join(str||'0') +
(Math.abs(this));
}
console.log((-23).padLeft(5)); //=> '-00023'
Alternative if you don't want to use Array
:
number.prototype.padLeft = function (len,chr) {
var self = Math.abs(this)+'';
return (this<0 && '-' || '')+
(String(Math.pow( 10, (len || 2)-self.length))
.slice(1).replace(/0/g,chr||'0') + self);
}
One extremely important notice:
NEVER use a direct package names as in something similar to passing a string value containing the package name. Use the method getPackageName(). This will make the renaming dynamic. Do whatever to reach the method getPackageName().
In Eclipse Juno, the correct way of renaming is:
function insSubstr($str, $sub, $posStart, $posEnd){
return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
It's not as easy as it seems to implement a control like that. Explorer works with shell items, not filesystem items (ex: the control panel, the printers folder, and so on). If you need to implement it i suggest to have a look at the Windows shell functions at http://msdn.microsoft.com/en-us/library/bb776426(VS.85).aspx.
The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning
.
Here chained indexing is something like dfc['A'][0] = 111
The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:
In [1]: import pandas as pd
In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})
In [3]: dfc
Out[3]:
A B
0 aaa 1
1 bbb 2
2 ccc 3
In [4]: aColumn = dfc['A']
In [5]: aColumn[0] = 111
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [6]: dfc
Out[6]:
A B
0 111 1
1 bbb 2
2 ccc 3
Here the aColumn
is a view and not a copy from the original DataFrame, so modifying aColumn
will cause the original dfc
be modified too. Next, if we index the row first:
In [7]: zero_row = dfc.loc[0]
In [8]: zero_row['A'] = 222
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [9]: dfc
Out[9]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time zero_row
is a copy, so the original dfc
is not modified.
From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:
In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
In [11]: dfc
Out[11]:
A B
0 111 1
1 bbb 2
2 ccc 3
This time it didn't work at all. Here we wanted to change dfc
, but we actually modified an intermediate value dfc.loc[0]
that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0]
or dfc['A']
is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning
for this kind of chained indexing update.
Now is the use of .copy()
. To eliminate the warning, make a copy to express your intention explicitly:
In [12]: zero_row_copy = dfc.loc[0].copy()
In [13]: zero_row_copy['A'] = 444 # This time no warning
Since you are modifying a copy, you know the original dfc
will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning
disappears.
Note, If you do want to modify the original DataFrame, the document suggests you use loc
:
In [14]: dfc.loc[0,'A'] = 555
In [15]: dfc
Out[15]:
A B
0 555 1
1 bbb 2
2 ccc 3
for me the only thing that works is:
CREATE FUNCTION IsNumeric (SIN VARCHAR(1024)) RETURNS TINYINT
RETURN SIN REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';
from kevinclark all other return useless stuff for me in case of 234jk456
or 12 inches
I faced the same issue with a Foundation menu. align-self: center;
didn't work for me.
My solution was to wrap the image with a <div style="display: inline-table;">...</div>
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
For those looking for a one-liner:
grep xyz abc.txt | while read -r line; do echo "Processing $line"; done
Here are two one-line macros that I use:
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])
Use it like this:
TICK;
/* ... Do Some Work Here ... */
TOCK;
Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.
Here is one already implemented: https://github.com/jacwright/date.format
You can use the following the get the difference between parent and the view you interested in:
private int getRelativeTop(View view) {
final View parent = (View) view.getParent();
int[] parentLocation = new int[2];
int[] viewLocation = new int[2];
view.getLocationOnScreen(viewLocation);
parent.getLocationOnScreen(parentLocation);
return viewLocation[1] - parentLocation[1];
}
Dont forget to call it after the view is drawn:
timeIndicator.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
final int relativeTop = getRelativeTop(timeIndicator);
});
To build on JJC's helpful answer that builds on Louis's helpful answer...
With PhantomJS 2.1.1-windows this line works:
driver.execute_script("return navigator.userAgent")
If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):
from selenium import webdriver
import json
from fake_useragent import UserAgent
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])
I feel your frustration.
Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.
That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.
(Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)
protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
{
@Override
protected JSONObject doInBackground(Void... params)
{
String str="http://your.domain.here/yourSubMethod";
URLConnection urlConn = null;
BufferedReader bufferedReader = null;
try
{
URL url = new URL(str);
urlConn = url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
}
return new JSONObject(stringBuffer.toString());
}
catch(Exception ex)
{
Log.e("App", "yourDataTask", ex);
return null;
}
finally
{
if(bufferedReader != null)
{
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Override
protected void onPostExecute(JSONObject response)
{
if(response != null)
{
try {
Log.e("App", "Success: " + response.getString("yourJsonElement") );
} catch (JSONException ex) {
Log.e("App", "Failure", ex);
}
}
}
}
This would be the json object it is targeted towards.
{
"yourJsonElement":"Hi, I'm a string",
"anotherElement":"Ohh, why didn't you pick me"
}
It is working on my end, hope this is helpful to someone else out there.
I'll answer for horizontal stretching of text, since the vertical is the easy part - just use "transform: scaleY()"
.stretched-text {
letter-spacing: 2px;
display: inline-block;
font-size: 32px;
transform: scaleY(0.5);
transform-origin: 0 0;
margin-bottom: -50%;
}
span {
font-size: 16px;
vertical-align: top;
}
_x000D_
<span class="stretched-text">this is some stretched text</span>
<span>and this is some random<br />triple line <br />not stretched text</span>
_x000D_
letter-spacing just adds space between letters, stretches nothing, but it's kinda relative
inline-block because inline elements are too restrictive and the code below wouldn't work otherwise
font-size to get to the size we want - that way the text will really be of the length it's supposed to be and the text before and after it will appear next to it (scaleX is just for show, the browser still sees the element at its original size when positioning other elements).
scaleY to reduce the height of the text, so that it's the same as the text beside it.
transform-origin to make the text scale from the top of the line.
margin-bottom set to a negative value, so that the next line will not be far below - preferably percentage, so that we won't change the line-height property. vertical-align set to top, to prevent the text before or after from floating to other heights (since the stretched text has a real size of 32px)
-- The simple span element has a font-size, only as a reference.
The question asked for a way to prevent the boldness of the text caused by the stretch and I still haven't given one, BUT the font-weight property has more values than just normal and bold.
I know, you just can't see that, but if you search for the appropriate fonts, you can use the more values.
For route controller method we have to define only one route. In get or post method we have to define the route separately.
And the resources method is used to creates multiple routes to handle a variety of Restful actions.
Here the Laravel documentation about this.
BLOB :
BLOB
(Binary Large Object) is a large object data type in the database system. BLOB
could store a large chunk of data, document types and even media files like audio or video files. BLOB
fields allocate space only whenever the content in the field is utilized. BLOB
allocates spaces in Giga Bytes.
USAGE OF BLOB :
You can write a binary large object (BLOB
) to a database as either binary or character data, depending on the type of field at your data source. To write a BLOB
value to your database, issue the appropriate INSERT or UPDATE
statement and pass the BLOB
value as an input parameter. If your BLOB
is stored as text, such as a SQL Server text field, you can pass the BLOB
as a string parameter. If the BLOB
is stored in binary format, such as a SQL Server image field, you can pass an array of type byte as a binary parameter.
A useful link : Storing documents as BLOB in Database - Any disadvantages ?
This is a simple example of a configuration with headers and responseType:
var config = {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
responseType: 'blob'
};
axios.post('http://YOUR_URL', this.data, config)
.then((response) => {
console.log(response.data);
});
Content-Type can be 'application/x-www-form-urlencoded' or 'application/json' and it may work also 'application/json;charset=utf-8'
responseType can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
In this example, this.data is the data you want to send. It can be a value or an Array. (If you want to send an object you'll probably have to serialize it)
It is just a name change. before_action
is more specific, because it gets executed before an action.
All the other answer accounts only for http
URLs. If the URL is https
, then do as follows,
Open launchsettings.json
under Properties of the API project.
Change the sslPort
under iisSettings -> iisExpress
A sample launchsettings.json
will look as follows
{
"iisSettings": {
"iisExpress": {
"applicationUrl": "http://localhost:12345",
"sslPort": 98765 <== Change_This
}
},
For basic autocompletion, have a look at the files in %ProgramFiles%\Notepad++\plugins\APIs
. It's basically just an XML file with keywords in. If you want calltips ("function parameters hint"), check out these instructions.
I've never found any more documentation, but cpp.xml
has a calltip for fopen
, while php.xml
is quite complete.
You can use the query parameter ll
for your lat and long, and you can use the query parameter q
for what you want to search.
http://maps.google.com/?ll=39.774769,-74.86084
Or you can
Actually I used my script in html directly. But in javascript when you add oninput event listener for this event it gives the data automatically.You just need to assign the value as per your requirement.
[slider] {_x000D_
width: 300px;_x000D_
position: relative;_x000D_
height: 5px;_x000D_
margin: 45px 0 10px 0;_x000D_
}_x000D_
_x000D_
[slider] > div {_x000D_
position: absolute;_x000D_
left: 13px;_x000D_
right: 15px;_x000D_
height: 5px;_x000D_
}_x000D_
[slider] > div > [inverse-left] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
[slider] > div > [inverse-right] {_x000D_
position: absolute;_x000D_
right: 0;_x000D_
height: 5px;_x000D_
border-radius: 10px;_x000D_
background-color: #CCC;_x000D_
margin: 0 7px;_x000D_
}_x000D_
_x000D_
_x000D_
[slider] > div > [range] {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
height: 5px;_x000D_
border-radius: 14px;_x000D_
background-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [thumb] {_x000D_
position: absolute;_x000D_
top: -7px;_x000D_
z-index: 2;_x000D_
height: 20px;_x000D_
width: 20px;_x000D_
text-align: left;_x000D_
margin-left: -11px;_x000D_
cursor: pointer;_x000D_
box-shadow: 0 3px 8px rgba(0, 0, 0, 0.4);_x000D_
background-color: #FFF;_x000D_
border-radius: 50%;_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
[slider] > input[type=range] {_x000D_
position: absolute;_x000D_
pointer-events: none;_x000D_
-webkit-appearance: none;_x000D_
z-index: 3;_x000D_
height: 14px;_x000D_
top: -2px;_x000D_
width: 100%;_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus::-webkit-slider-runnable-track {_x000D_
background: transparent;_x000D_
border: transparent;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]:focus {_x000D_
outline: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-webkit-slider-thumb {_x000D_
pointer-events: all;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 0px;_x000D_
border: 0 none;_x000D_
background: red;_x000D_
-webkit-appearance: none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-lower {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-fill-upper {_x000D_
background: transparent;_x000D_
border: 0 none;_x000D_
}_x000D_
_x000D_
div[slider] > input[type=range]::-ms-tooltip {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
margin-left: -11px;_x000D_
top: -39px;_x000D_
z-index:3;_x000D_
background-color: #d02128;_x000D_
color: #fff;_x000D_
width: 28px;_x000D_
height: 28px;_x000D_
border-radius: 28px;_x000D_
-webkit-border-radius: 28px;_x000D_
align-items: center;_x000D_
-webkit-justify-content: center;_x000D_
justify-content: center;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign]:after {_x000D_
position: absolute;_x000D_
content: '';_x000D_
left: 0;_x000D_
border-radius: 16px;_x000D_
top: 19px;_x000D_
border-left: 14px solid transparent;_x000D_
border-right: 14px solid transparent;_x000D_
border-top-width: 16px;_x000D_
border-top-style: solid;_x000D_
border-top-color: #d02128;_x000D_
}_x000D_
_x000D_
[slider] > div > [sign] > span {_x000D_
font-size: 12px;_x000D_
font-weight: 700;_x000D_
line-height: 28px;_x000D_
}_x000D_
_x000D_
[slider]:hover > div > [sign] {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div slider id="slider-distance">_x000D_
<div>_x000D_
<div inverse-left style="width:70%;"></div>_x000D_
<div inverse-right style="width:70%;"></div>_x000D_
<div range style="left:0%;right:0%;"></div>_x000D_
<span thumb style="left:0%;"></span>_x000D_
<span thumb style="left:100%;"></span>_x000D_
<div sign style="left:0%;">_x000D_
<span id="value">0</span>_x000D_
</div>_x000D_
<div sign style="left:100%;">_x000D_
<span id="value">100</span>_x000D_
</div>_x000D_
</div>_x000D_
<input type="range" value="0" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.min(this.value,this.parentNode.childNodes[5].value-1);_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[1].style.width=value+'%';_x000D_
children[5].style.left=value+'%';_x000D_
children[7].style.left=value+'%';children[11].style.left=value+'%';_x000D_
children[11].childNodes[1].innerHTML=this.value;" />_x000D_
_x000D_
<input type="range" value="100" max="100" min="0" step="1" oninput="_x000D_
this.value=Math.max(this.value,this.parentNode.childNodes[3].value-(-1));_x000D_
let value = (this.value/parseInt(this.max))*100_x000D_
var children = this.parentNode.childNodes[1].childNodes;_x000D_
children[3].style.width=(100-value)+'%';_x000D_
children[5].style.right=(100-value)+'%';_x000D_
children[9].style.left=value+'%';children[13].style.left=value+'%';_x000D_
children[13].childNodes[1].innerHTML=this.value;" />_x000D_
</div>
_x000D_
Technically it's undefined, but in reality most (all?) compilers treat it exactly the same as using a reinterpret_cast
from one type to the other, the result of which is implementation defined. I wouldn't lose sleep over your current code.
<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>
More esoteric ways:
Rails.cache.delete_matched("*")
For Redis:
Redis.new.keys.each{ |key| Rails.cache.delete(key) }
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You can do it using write() :
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
I think the original question can easily be answered with something being overlooked so far: a simple string split. The time being returned is a text string, just split it on the ":" delimiter and reassemble the string the way you want. No plug ins, no complicated scripting. and here ya go:
var myVar=setInterval(function(){myTimer()},1000);
function myTimer() {
var d = new Date();
currentNow = d.toLocaleTimeString();
nowArray = currentNow.split(':');
filteredNow = nowArray[0]+':'+nowArray[1];
document.getElementById("demo").innerHTML = filteredNow;
}
Or try this
const https = require('https');
const fs = require('fs');
const DOMAIN = 'raw.githubusercontent.com';
function writeFile(data, fileName) {
fs.appendFile(fileName, data.toString(), err => {
if (err) {
console.log('error in writing file', err);
}
});
}
function EOF(data) {
console.log('EOF');
}
function getFileName(pathToFile) {
var result = pathToFile.split('/');
var splitLength = result.length;
return result[splitLength - 1];
}
function getFile(branchName, username, repoName, ...pathToFile) {
pathToFile.forEach(item => {
const path = `/${username}/${repoName}/${branchName}/${item}`;
const URL = `${DOMAIN}${path}`;
const options = {
hostname: DOMAIN,
path: path
};
var fileName = getFileName(item);
https
.get(options, function(res) {
console.log(res.statusCode);
/* if file not found */
if (res.statusCode === 404) {
console.log('FILE NOT FOUND');
} else {
/* if file found */
res.on('data', data => writeFile(data, fileName));
res.on('end', data => EOF(data));
}
})
.on('error', function(res) {
console.log('error in reading URL');
});
});
}
getFile('master', 'bansalAyush', 'InstagramClone', '.babelrc', 'README.md');
I suggest a LinkedHashMap
or a TreeMap
. A LinkedHashMap
keeps the keys in the order they were inserted, while a TreeMap
is kept sorted via a Comparator
or the natural Comparable
ordering of the elements.
Since it doesn't have to keep the elements sorted, LinkedHashMap
should be faster for most cases; TreeMap
has O(log n)
performance for containsKey
, get
, put
, and remove
, according to the Javadocs, while LinkedHashMap
is O(1)
for each.
If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap
or SortedMap
. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.
Try this code
SELECT REPLACE([Column], char(9), '') From [dbo.Table]
char(9) is the TAB character
This not the best way to manage session in react you can use web tokens to encrypt your data that you want save,you can use various number of services available a popular one is JSON web tokens(JWT) with web-tokens you can logout after some time if there no action from the client And after creating the token you can store it in your local storage for ease of access.
jwt.sign({user}, 'secretkey', { expiresIn: '30s' }, (err, token) => {
res.json({
token
});
user object in here is the user data which you want to keep in the session
localStorage.setItem('session',JSON.stringify(token));
To this case, I have a hexadecimal data format into an int array and I want to convert them on String.
int[] encodeHex = new int[] { 0x48, 0x65, 0x6c, 0x6c, 0x6f }; // Hello encode
for (int i = 0; i < encodeHex.length; i++) {
System.out.print((char) (encodeHex[i]));
}
If anyone is using GoDaddy Shared Hosting, you can try for following solution, worked for me.
When starting DB connection, set the time_zone command in my PDO object e.g.:
$pdo = new PDO($dsn, $user, $pass, $opt);
$pdo->exec("SET time_zone='+05:30';");
Where "+05:30" is the TimeZone of India. You can change it as per your need.
After that; all the MySQL processes related to Date and Time are set with required timezone.
Source : https://in.godaddy.com/community/cPanel-Hosting/How-to-change-TimeZone-for-MySqL/td-p/31861
you should return Scaffold widget and add your widget inside Scaffold
suck as this code :
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(child: new Text("Hello, World!"));
);
}
}