just add:
int main()
{
//you can leave it empty
return 0;
}
to your project and everything will work its causes because of visual studio try to find the main function to start the project and didn't found it
Your Button2Click
and Button3Click
functions pass klad.xls
and smimime.txt
. These files most likely aren't actual executables indeed.
In order to open arbitrary files using the application associated with them, use ShellExecute
rem This is the command line version
cscript "C:\Users\guest\Desktop\123\MyScript.vbs"
OR
rem This is the windowed version
wscript "C:\Users\guest\Desktop\123\MyScript.vbs"
You can also add the option //e:vbscript
to make sure the scripting engine will recognize your script as a vbscript.
Windows/DOS batch files doesn't require escaping \
like *nix.
You can still use "C:\Users\guest\Desktop\123\MyScript.vbs"
, but this requires the user has *.vbs
associated to wscript
.
This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates
which is more suitable than distinct
for certain queries.
Suppose you have this DataFrame:
+-------+-------------+
|country| continent|
+-------+-------------+
| china| asia|
| brazil|south america|
| france| europe|
| china| asia|
+-------+-------------+
Here's how to take all the distinct countries and run a transformation:
df
.select("country")
.distinct
.withColumn("country", concat(col("country"), lit(" is fun!")))
.show()
+--------------+
| country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+
You can use dropDuplicates
instead of distinct
if you don't want to lose the continent
information:
df
.dropDuplicates("country")
.withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
.show(false)
+-------+-------------+------------------------------------+
|country|continent |description |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe |france is a country in europe |
|china |asia |china is a country in asia |
+-------+-------------+------------------------------------+
See here for more information about filtering DataFrames and here for more information on dropping duplicates.
Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.
I encountered this issue in a NodeJS Lambda function that was triggered by a file upload to S3.
My mistake was that I was not decoding the object key, which contained a colon. Corrected my code as follows:
let key = decodeURIComponent(event.Records[0].s3.object.key);
Download "PuttyGEN" get publickey and privatekey use gcloud SSH edit and paste your publickey located in /home/USER/.ssh/authorized_keys
sudo vim ~/.ssh/authorized_keys
Tap the i key to paste publicKEY. To save, tap Esc, :, w, q, Enter. Edit the /etc/ssh/sshd_config file.
sudo vim /etc/ssh/sshd_config
Change
PasswordAuthentication no [...] ChallengeResponseAuthentication to no. [...] UsePAM no [...] Restart ssh
/etc/init.d/ssh restart.
the rest config your putty as tutorial NB:choose the pageant add keys and start session would be better
The problem was that I used ajax to post the message to the server, when I used a direct link to download the file everything worked fine.
I used this other Stackoverflow Q&A material instead, it worked great for me:
One solution: add isAdmin: 0/1 flag to your post collection document.
Other solution: use DBrefs
I have do something like this to get date in local device timezone from UTC time stamp.
private long UTC_TIMEZONE=1470960000;
private String OUTPUT_DATE_FORMATE="dd-MM-yyyy - hh:mm a"
getDateFromUTCTimestamp(UTC_TIMEZONE,OUTPUT_DATE_FORMATE);
Here is the function
public String getDateFromUTCTimestamp(long mTimestamp, String mDateFormate) {
String date = null;
try {
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(mTimestamp * 1000L);
date = DateFormat.format(mDateFormate, cal.getTimeInMillis()).toString();
SimpleDateFormat formatter = new SimpleDateFormat(mDateFormate);
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date value = formatter.parse(date);
SimpleDateFormat dateFormatter = new SimpleDateFormat(mDateFormate);
dateFormatter.setTimeZone(TimeZone.getDefault());
date = dateFormatter.format(value);
return date;
} catch (Exception e) {
e.printStackTrace();
}
return date;
}
Result :
12-08-2016 - 04:30 PM
Hope this will work for others.
try this method
$("your id or class name").css({ 'margin-top': '18px' });
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.
I was also stuck on the same kind of problem and I followed the simple steps below.
Just get the exact url of the file to which you want to copy, for example:
http://www.test.com/test.txt (file to copy)
Then pass the exact absolute folder path with filename where you do want to write that file.
If you are on a Windows machine then
d:/xampp/htdocs/upload/test.txt
If you are on a Linux machine then
/var/www/html/upload/test.txt
You can get the document root with the PHP function $_SERVER['DOCUMENT_ROOT']
.
From Twitter Bootstrap documentation:
.col-sm-*
,.col-md-*
,.col-lg-*
.You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
Instead of trying to manually align the text into columns with arbitrary strings of spaces, you should embed actual tabs (the \t
escape sequence) into each output string:
Console.WriteLine("Customer name" + "\t"
+ "sales" + "\t"
+ "fee to be paid" + "\t"
+ "70% value" + "\t"
+ "30% value");
for (int DisplayPos = 0; DisplayPos < LineNum; DisplayPos++)
{
seventy_percent_value = ((fee_payable[DisplayPos] / 10.0) * 7);
thirty_percent_value = ((fee_payable[DisplayPos] / 10.0) * 3);
Console.WriteLine(customer[DisplayPos] + "\t"
+ sales_figures[DisplayPos] + "\t"
+ fee_payable + "\t\t"
+ seventy_percent_value + "\t\t"
+ thirty_percent_value);
}
I just tested this extremely simple method and it works perfectly--but I use the built-in Administrator account, so I don't have to jump through hoops for elevated privileges.
The following batch file relieves the user of the need to move files in/out of system folders. It also leaves it up to Windows to apply the proper version of Regsvr32
.
INSTRUCTIONS:
In the folder that contains the library (-.dll
or -.ax
) file you wish to register, open a new text file and paste in ONE of the routines below :
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 64-BIT SYSTEMS
copy %1 C:\Windows\System32
regsvr32 "%nx1"
echo END BATCH FILE
pause
echo BEGIN DRAG-AND-DROP %n1 REGISTRAR FOR 32-BIT SYSTEMS
copy %1 C:\Windows\SysWOW64
regsvr32 "%nx1"
echo END BATCH FILE
pause
Save your new text file as a batch (-.bat
) file; then simply drag-and-drop your -.dll
or -.ax
file on top of the batch file.
If UAC doesn't give you the opportunity to run the batch file as an Administrator, you may need to manually elevate privileges (instructions are for Windows 7):
Create shortcut
;Properties
;Compatibility
tab;Run this program as administrator
;-.dll
or -.ax
file on top of the new shortcut instead of the batch file.That's it. I chose COPY
instead of MOVE
to prevent the failure of any UAC-related follow-up attempt(s). Successful registration should be followed by deletion of the original library (-.dll
or -.ax
) file.
Don't worry about copies made to the system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) by previous passes--they will be overwritten every time you run the batch file.
Unless you ran the wrong batch file, in which case you will probably want to delete the copy made to the wrong system folder (C:\Windows\System32
or C:\Windows\SysWOW64
) before running the proper batch file, ...or...
Help Windows choose the right library file to register by fully-qualifying its directory location.
C:\Windows\System32
C:\Windows\SysWOW64
%nx1
regsvr32 "C:\Windows\System32\%nx1"
regsvr32 "C:\Windows\SysWOW64\%nx1"
%nx1
from system folder pathRun this shotgun batch file, which will (in order):
C:\Windows\System32
;C:\Windows\System32
;C:\Windows\SystemWOW64
Can be used as follow:
d2j-dex2jar release.apk
Kotlin version of solution
private fun setLocale(activity: Activity, languageCode: String?) {
val locale = Locale(languageCode)
Locale.setDefault(locale)
val config: Configuration = resources.configuration
config.setLocale(locale)
resources.updateConfiguration(config, resources.displayMetrics)
See this answer for list of the language codes https://stackoverflow.com/a/7989085/13139418
$('input.yourClass:checkbox:checked').each(function () {
var sThisVal = $(this).val();
});
This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:
var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
arr.push($(this).val());
});
Instead of finding a way to get static variables working, I prefer to simply create a getter function. Also helpful if you need arrays belonging to a specific class, and a lot simpler to implement.
class MyClass
{
public static function getTypeList()
{
return array(
"type_a"=>"Type A",
"type_b"=>"Type B",
//... etc.
);
}
}
Wherever you need the list, simply call the getter method. For example:
if (array_key_exists($type, MyClass::getTypeList()) {
// do something important...
}
I had ran into this trouble when I left a php foreach: tag unclosed.
<?php foreach($many as $one): ?>
Closing it using the following solved the syntax error: unexpected end of file
<?php endforeach; ?>
Hope it helps someone
Use:
File.Exists(path)
MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx
Edit: In System.IO
To get any sort of file path use this (taken from https://github.com/iPaulPro/aFileChooser)
package com.yourpackage;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.File;
import java.io.FileFilter;
import java.text.DecimalFormat;
import java.util.Comparator;
import java.util.List;
/**
* @author Peli
* @author paulburke (ipaulpro)
* @version 2013-12-11
*/
public class FileUtils {
private FileUtils() {
} //private constructor to enforce Singleton pattern
/**
* TAG for log messages.
*/
static final String TAG = "FileUtils";
private static final boolean DEBUG = true; // Set to true to enable logging
public static final String MIME_TYPE_AUDIO = "audio/*";
public static final String MIME_TYPE_TEXT = "text/*";
public static final String MIME_TYPE_IMAGE = "image/*";
public static final String MIME_TYPE_VIDEO = "video/*";
public static final String MIME_TYPE_APP = "application/*";
public static final String HIDDEN_PREFIX = ".";
/**
* Gets the extension of a file name, like ".png" or ".jpg".
*
* @param uri
* @return Extension including the dot("."); "" if there is no extension;
* null if uri was null.
*/
public static String getExtension(String uri) {
if (uri == null) {
return null;
}
int dot = uri.lastIndexOf(".");
if (dot >= 0) {
return uri.substring(dot);
} else {
// No extension.
return "";
}
}
/**
* @return Whether the URI is a local one.
*/
public static boolean isLocal(String url) {
if (url != null && !url.startsWith("http://") && !url.startsWith("https://")) {
return true;
}
return false;
}
/**
* @return True if Uri is a MediaStore Uri.
* @author paulburke
*/
public static boolean isMediaUri(Uri uri) {
return "media".equalsIgnoreCase(uri.getAuthority());
}
/**
* Convert File into Uri.
*
* @param file
* @return uri
*/
public static Uri getUri(File file) {
if (file != null) {
return Uri.fromFile(file);
}
return null;
}
/**
* Returns the path only (without file name).
*
* @param file
* @return
*/
public static File getPathWithoutFilename(File file) {
if (file != null) {
if (file.isDirectory()) {
// no file to be split off. Return everything
return file;
} else {
String filename = file.getName();
String filepath = file.getAbsolutePath();
// Construct path without file name.
String pathwithoutname = filepath.substring(0,
filepath.length() - filename.length());
if (pathwithoutname.endsWith("/")) {
pathwithoutname = pathwithoutname.substring(0, pathwithoutname.length() - 1);
}
return new File(pathwithoutname);
}
}
return null;
}
/**
* @return The MIME type for the given file.
*/
public static String getMimeType(File file) {
String extension = getExtension(file.getName());
if (extension.length() > 0)
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.substring(1));
return "application/octet-stream";
}
/**
* @return The MIME type for the give Uri.
*/
public static String getMimeType(Context context, Uri uri) {
File file = new File(getPath(context, uri));
return getMimeType(file);
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is {@link LocalStorageProvider}.
* @author paulburke
*/
public static boolean isLocalStorageDocument(Uri uri) {
return LocalStorageProvider.AUTHORITY.equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
* @author paulburke
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
* @author paulburke
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
* @author paulburke
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is Google Photos.
*/
public static boolean isGooglePhotosUri(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
* @author paulburke
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
if (DEBUG)
DatabaseUtils.dumpCursor(cursor);
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* Get a file path from a Uri. This will quickGet the the path for Storage Access
* Framework Documents, as well as the _data field for the MediaStore and
* other file-based ContentProviders.<br>
* <br>
* Callers should check whether the path is local before assuming it
* represents a local file.
*
* @param context The context.
* @param uri The Uri to query.
* @author paulburke
* @see #isLocal(String)
* @see #getFile(Context, Uri)
*/
public static String getPath(final Context context, final Uri uri) {
if (DEBUG)
Log.d(TAG + " File -",
"Authority: " + uri.getAuthority() +
", Fragment: " + uri.getFragment() +
", Port: " + uri.getPort() +
", Query: " + uri.getQuery() +
", Scheme: " + uri.getScheme() +
", Host: " + uri.getHost() +
", Segments: " + uri.getPathSegments().toString()
);
// DocumentProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {
// LocalStorageProvider
if (isLocalStorageDocument(uri)) {
// The path is the id
return DocumentsContract.getDocumentId(uri);
}
// ExternalStorageProvider
else if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
// if ("primary".equalsIgnoreCase(type)) {
// return Environment.getExternalStorageDirectory() + "/" + split[1];
// }
return Environment.getExternalStorageDirectory() + "/" + split[1];
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
try {
final String id = DocumentsContract.getDocumentId(uri);
Log.d(TAG, "getPath: id= " + id);
final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}catch (Exception e){
e.printStackTrace();
List<String> segments = uri.getPathSegments();
if(segments.size() > 1) {
String rawPath = segments.get(1);
if(!rawPath.startsWith("/")){
return rawPath.substring(rawPath.indexOf("/"));
}else {
return rawPath;
}
}
}
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
// Return the remote address
if (isGooglePhotosUri(uri))
return uri.getLastPathSegment();
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Convert Uri into File, if possible.
*
* @return file A local file that the Uri was pointing to, or null if the
* Uri is unsupported or pointed to a remote resource.
* @author paulburke
* @see #getPath(Context, Uri)
*/
public static File getFile(Context context, Uri uri) {
if (uri != null) {
String path = getPath(context, uri);
if (path != null && isLocal(path)) {
return new File(path);
}
}
return null;
}
/**
* Get the file size in a human-readable string.
*
* @param size
* @return
* @author paulburke
*/
public static String getReadableFileSize(int size) {
final int BYTES_IN_KILOBYTES = 1024;
final DecimalFormat dec = new DecimalFormat("###.#");
final String KILOBYTES = " KB";
final String MEGABYTES = " MB";
final String GIGABYTES = " GB";
float fileSize = 0;
String suffix = KILOBYTES;
if (size > BYTES_IN_KILOBYTES) {
fileSize = size / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
if (fileSize > BYTES_IN_KILOBYTES) {
fileSize = fileSize / BYTES_IN_KILOBYTES;
suffix = GIGABYTES;
} else {
suffix = MEGABYTES;
}
}
}
return String.valueOf(dec.format(fileSize) + suffix);
}
/**
* Attempt to retrieve the thumbnail of given File from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param file
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, File file) {
return getThumbnail(context, getUri(file), getMimeType(file));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri) {
return getThumbnail(context, uri, getMimeType(context, uri));
}
/**
* Attempt to retrieve the thumbnail of given Uri from the MediaStore. This
* should not be called on the UI thread.
*
* @param context
* @param uri
* @param mimeType
* @return
* @author paulburke
*/
public static Bitmap getThumbnail(Context context, Uri uri, String mimeType) {
if (DEBUG)
Log.d(TAG, "Attempting to quickGet thumbnail");
if (!isMediaUri(uri)) {
Log.e(TAG, "You can only retrieve thumbnails for images and videos.");
return null;
}
Bitmap bm = null;
if (uri != null) {
final ContentResolver resolver = context.getContentResolver();
Cursor cursor = null;
try {
cursor = resolver.query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
final int id = cursor.getInt(0);
if (DEBUG)
Log.d(TAG, "Got thumb ID: " + id);
if (mimeType.contains("video")) {
bm = MediaStore.Video.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Video.Thumbnails.MINI_KIND,
null);
} else if (mimeType.contains(FileUtils.MIME_TYPE_IMAGE)) {
bm = MediaStore.Images.Thumbnails.getThumbnail(
resolver,
id,
MediaStore.Images.Thumbnails.MINI_KIND,
null);
}
}
} catch (Exception e) {
if (DEBUG)
Log.e(TAG, "getThumbnail", e);
} finally {
if (cursor != null)
cursor.close();
}
}
return bm;
}
/**
* File and folder comparator. TODO Expose sorting option method
*
* @author paulburke
*/
public static Comparator<File> sComparator = new Comparator<File>() {
@Override
public int compare(File f1, File f2) {
// Sort alphabetically by lower case, which is much cleaner
return f1.getName().toLowerCase().compareTo(
f2.getName().toLowerCase());
}
};
/**
* File (not directories) filter.
*
* @author paulburke
*/
public static FileFilter sFileFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return files only (not directories) and skip hidden files
return file.isFile() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Folder (directories) filter.
*
* @author paulburke
*/
public static FileFilter sDirFilter = new FileFilter() {
@Override
public boolean accept(File file) {
final String fileName = file.getName();
// Return directories only and skip hidden directories
return file.isDirectory() && !fileName.startsWith(HIDDEN_PREFIX);
}
};
/**
* Get the Intent for selecting content to be used in an Intent Chooser.
*
* @return The intent for opening a file with Intent.createChooser()
* @author paulburke
*/
public static Intent createGetContentIntent() {
// Implicitly allow the user to select a particular kind of data
final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// The MIME data type filter
intent.setType("*/*");
// Only return URIs that can be opened with ContentResolver
intent.addCategory(Intent.CATEGORY_OPENABLE);
return intent;
}
}
If you are using Windows command line to print the data, you should use
chcp 65001
This worked for me!
I did a little experiment to see which of these methods
string.startswith('hello')
string.rfind('hello') == 0
string.rpartition('hello')[0] == ''
string.rindex('hello') == 0
are most efficient to return whether a certain string begins with another string.
Here is the result of one of the many test runs I've made, where each list is ordered to show the least time it took (in seconds) to parse 5 million of each of the above expressions during each iteration of the while
loop I used:
['startswith: 1.37', 'rpartition: 1.38', 'rfind: 1.62', 'rindex: 1.62']
['startswith: 1.28', 'rpartition: 1.44', 'rindex: 1.67', 'rfind: 1.68']
['startswith: 1.29', 'rpartition: 1.42', 'rindex: 1.63', 'rfind: 1.64']
['startswith: 1.28', 'rpartition: 1.43', 'rindex: 1.61', 'rfind: 1.62']
['rpartition: 1.48', 'startswith: 1.48', 'rfind: 1.62', 'rindex: 1.67']
['startswith: 1.34', 'rpartition: 1.43', 'rfind: 1.64', 'rindex: 1.64']
['startswith: 1.36', 'rpartition: 1.44', 'rindex: 1.61', 'rfind: 1.63']
['startswith: 1.29', 'rpartition: 1.37', 'rindex: 1.64', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.44', 'rfind: 1.66', 'rindex: 1.68']
['startswith: 1.44', 'rpartition: 1.41', 'rindex: 1.61', 'rfind: 2.24']
['startswith: 1.34', 'rpartition: 1.45', 'rindex: 1.62', 'rfind: 1.67']
['startswith: 1.34', 'rpartition: 1.38', 'rindex: 1.67', 'rfind: 1.74']
['rpartition: 1.37', 'startswith: 1.38', 'rfind: 1.61', 'rindex: 1.64']
['startswith: 1.32', 'rpartition: 1.39', 'rfind: 1.64', 'rindex: 1.61']
['rpartition: 1.35', 'startswith: 1.36', 'rfind: 1.63', 'rindex: 1.67']
['startswith: 1.29', 'rpartition: 1.36', 'rfind: 1.65', 'rindex: 1.84']
['startswith: 1.41', 'rpartition: 1.44', 'rfind: 1.63', 'rindex: 1.71']
['startswith: 1.34', 'rpartition: 1.46', 'rindex: 1.66', 'rfind: 1.74']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.38', 'rpartition: 1.48', 'rfind: 1.68', 'rindex: 1.68']
['startswith: 1.35', 'rpartition: 1.42', 'rfind: 1.63', 'rindex: 1.68']
['startswith: 1.32', 'rpartition: 1.46', 'rfind: 1.65', 'rindex: 1.75']
['startswith: 1.37', 'rpartition: 1.46', 'rfind: 1.74', 'rindex: 1.75']
['startswith: 1.31', 'rpartition: 1.48', 'rfind: 1.67', 'rindex: 1.74']
['startswith: 1.44', 'rpartition: 1.46', 'rindex: 1.69', 'rfind: 1.74']
['startswith: 1.44', 'rpartition: 1.42', 'rfind: 1.65', 'rindex: 1.65']
['startswith: 1.36', 'rpartition: 1.44', 'rfind: 1.64', 'rindex: 1.74']
['startswith: 1.34', 'rpartition: 1.46', 'rfind: 1.61', 'rindex: 1.74']
['startswith: 1.35', 'rpartition: 1.56', 'rfind: 1.68', 'rindex: 1.69']
['startswith: 1.32', 'rpartition: 1.48', 'rindex: 1.64', 'rfind: 1.65']
['startswith: 1.28', 'rpartition: 1.43', 'rfind: 1.59', 'rindex: 1.66']
I believe that it is pretty obvious from the start that the startswith
method would come out the most efficient, as returning whether a string begins with the specified string is its main purpose.
What surprises me is that the seemingly impractical string.rpartition('hello')[0] == ''
method always finds a way to be listed first, before the string.startswith('hello')
method, every now and then. The results show that using str.partition
to determine if a string starts with another string is more efficient then using both rfind
and rindex
.
Another thing I've noticed is that string.rindex('hello') == 0
and string.rindex('hello') == 0
have a good battle going on, each rising from fourth to third place, and dropping from third to fourth place, which makes sense, as their main purposes are the same.
Here is the code:
from time import perf_counter
string = 'hello world'
places = dict()
while True:
start = perf_counter()
for _ in range(5000000):
string.startswith('hello')
end = perf_counter()
places['startswith'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rfind('hello') == 0
end = perf_counter()
places['rfind'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rpartition('hello')[0] == ''
end = perf_counter()
places['rpartition'] = round(end - start, 2)
start = perf_counter()
for _ in range(5000000):
string.rindex('hello') == 0
end = perf_counter()
places['rindex'] = round(end - start, 2)
print([f'{b}: {str(a).ljust(4, "4")}' for a, b in sorted(i[::-1] for i in places.items())])
From this blog post:
XE: Changing the default http port
Oracle XE uses the embedded http listener that comes with the XML DB (XDB) to serve http requests. The default port for HTTP access is 8080.
EDIT:
Update 8080 port to which port(9090 for example) you like
SQL> -- set http port
SQL> begin
2 dbms_xdb.sethttpport('9090');
3 end;
4 /
After changing the port, when we start Oracle it will go on port 8080, we should type manually new port(9090) in the address bar to run Oracle XE.
ASP.NET MVC will handle this for you if you use bundles for your JS/CSS. It will automatically append a version number in the form of a GUID to your bundles and only update this GUID when the bundle is updated (aka any of the source files have changes).
This also helps if you have a ton of JS/CSS files as it can greatly improve content load times!
I've solved this as is shown below:
long year = calendar.get(Calendar.YEAR);
long month = calendar.get(Calendar.MONTH) + 1;
long day = calendar.get(Calendar.DAY_OF_MONTH);
long calcDate = year * 100 + month;
calcDate = calcDate * 100 + day;
System.out.println("int: " + calcDate);
Actually, upon further reading on the file_get_contents()
function:
// Create a stream
$opts = [
"http" => [
"method" => "GET",
"header" => "Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
]
];
// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);
You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)
try:
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Where the folder you want to appear in the url is in the first part of the statement - this is what it will match against and the second part 'rewrites' it to your existing folder. the [NC] flag means that it will ignore case differences eg Apple/ will still forward.
See here for a tutorial: http://www.sitepoint.com/article/guide-url-rewriting/
There is also a nice test utility for windows you can download from here: http://www.helicontech.com/download/rxtest.zip Just to note for the tester you need to leave out the domain name - so the test would be against /folder1/login.php
to redirect from /folder1 to /apple try this:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
to redirect and then rewrite just combine the above in the htaccess file:
RewriteRule ^/folder1(.*)?$ /apple$1 [R]
RewriteRule ^/apple(.*)?$ /folder1$1 [NC]
Check out how Haar Wavelets are implemented by isk-daemon. You could use it's imgdb C++ code to calculate the difference between images on-the-fly:
isk-daemon is an open source database server capable of adding content-based (visual) image searching to any image related website or software.
This technology allows users of any image-related website or software to sketch on a widget which image they want to find and have the website reply to them the most similar images or simply request for more similar photos at each image detail page.
Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.
#!/usr/bin/env sh
this is how git bash knows a file is executable. chmod a+x
does nothing in gitbash. (Note: any "she-bang" will work, e.g. #!/bin/bash
, etc.)
I faced the same issue before. I cleared all the IE caches/browsing history/cookies & re-launch IE. It works after caches removed.
You may have a try. :)
I think it would be much easier to put an anchor
tag around i
. You can just use the css :hover
selector. Less moving parts makes maintenance easier, and less javascript to load makes the page quicker.
This will do the trick:
<style>
a.icon-link:hover {
background-color: pink;
}
</style>
<a href="#" class="icon-link" id="course-0"><i class="icon-thumbsup"></id></a>
Try:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<SeekBar
android:id="@+id/seekBar1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rotation="270"
/>
</RelativeLayout>
I had to add this:
bootRun {
String activeProfile = System.properties['spring.profiles.active']
String confLoc = System.properties['spring.config.location']
systemProperty "spring.profiles.active", activeProfile
systemProperty "spring.config.location", "file:$confLoc"
}
And now bootRun picks up the profile and config locations.
Thanks a lot @jst for the pointer.
You can do comparison with this down here.
latest('created')
is same as order_by('-created').first()
Please correct me if I am wrong
Use System.Windows.Forms.Timer.
private Timer timer1;
public void InitTimer()
{
timer1 = new Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 2000; // in miliseconds
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
isonline();
}
You can call InitTimer()
in Form1_Load()
.
Listed are the steps that could rectify the error:
services.msc
and strike Enterora
start these services and wait!!orcl
) mysql
or whatever you are using and start coding.PAll modules from package.json are installed to ./node_modules/
I couldn't find this explicitly stated but this is the package.json reference for NPM.
Until PHP 5.3 release don't expect to have a good ORM. It's a OO limitation of PHP.
Judging by the documentation for date/time functions, you should be able to do something like:
SELECT * FROM FOO
WHERE MY_DATE_FIELD >= NOW() - INTERVAL 1 DAY
In fact, depends what you want to get: - Just the min value:
SELECT MIN(price) FROM pieces
A table (multiples rows) whith the min value: Is as John Woo said above.
But, if can be different rows with same min value, the best is ORDER them from another column, because after or later you will need to do it (starting from John Woo answere):
SELECT * FROM pieces WHERE price = ( SELECT MIN(price) FROM pieces) ORDER BY stock ASC
Type in command line :
$ export http_proxy=http://proxy_host:proxy_port
for authenticated proxy,
$ export http_proxy=http://username:password@proxy_host:proxy_port
and then run
$ wget fileurl
for https, just use https_proxy instead of http_proxy. You could also put these lines in your ~/.bashrc file so that you don't need to execute this everytime.
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
The article for HSL and HSV on wikipedia contains some formulas. The calculations are a bit tricky, so it might be useful to take a look at existing implementations.
I know this is a bit late.
function Validatebodypanelbumper(theForm)
{
var regexp;
var extension = theForm.FileUpload.value.substr(theForm.FileUpload1.value.lastIndexOf('.'));
if ((extension.toLowerCase() != ".gif") &&
(extension.toLowerCase() != ".jpg") &&
(extension != ""))
{
alert("The \"FileUpload\" field contains an unapproved filename.");
theForm.FileUpload1.focus();
return false;
}
return true;
}
First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...
You can then make an IComparer:
public class TagComparer : IComparer<cTag>
{
public int Compare(cTag first, cTag second)
{
if (first != null && second != null)
{
// We can compare both properties.
return first.date.CompareTo(second.date);
}
if (first == null && second == null)
{
// We can't compare any properties, so they are essentially equal.
return 0;
}
if (first != null)
{
// Only the first instance is not null, so prefer that.
return -1;
}
// Only the second instance is not null, so prefer that.
return 1;
}
}
var list = new List<cTag>();
// populate list.
list.Sort(new TagComparer());
You can even do it as a delegate:
list.Sort((first, second) =>
{
if (first != null && second != null)
return first.date.CompareTo(second.date);
if (first == null && second == null)
return 0;
if (first != null)
return -1;
return 1;
});
I had a similar problem, having to wait for control existence and checking in intervals. Since there is no real sleep, wait or pause in JavaScript and using await / async is not supported properly in Internet Explorer, I made a solution using setTimeOut and injecting the function in case of successfully finding the element. Here is the complete sample code, so everyone can reproduce and use it for their own project:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
var ElementSearchStatus = {
None: 0,
Found: 1,
NotFound: 2,
Timeout: 3
};
var maxTimeout = 5;
var timeoutMiliseconds = 1000;
function waitForElement(elementId, count, timeout, onSuccessFunction) {
++count;
var elementSearchStatus = existsElement(elementId, count, timeout);
if (elementSearchStatus == ElementSearchStatus.None) {
window.setTimeout(waitForElement, timeoutMiliseconds, elementId, count, timeout, onSuccessFunction);
}
else {
if (elementSearchStatus == ElementSearchStatus.Found) {
onSuccessFunction();
}
}
}
function existsElement(elementId, count, timeout) {
var foundElements = $("#" + elementId);
if (foundElements.length > 0 || count > timeout) {
if (foundElements.length > 0) {
console.log(elementId + " found");
return ElementSearchStatus.Found;
}
else {
console.log("Search for " + elementId + " timed out after " + count + " tries.");
return ElementSearchStatus.Timeout;
}
}
else {
console.log("waiting for " + elementId + " after " + count + " of " + timeout);
return ElementSearchStatus.None;
}
}
function main() {
waitForElement("StartButton", 0, maxTimeout, function () {
console.log("found StartButton!");
DoOtherStuff("StartButton2")
});
}
function DoOtherStuff(elementId) {
waitForElement(elementId, 0, maxTimeout, function () {
console.log("found " + elementId);
DoOtherStuff("StartButton3");
});
}
</script>
</head>
<body>
<button type="button" id="StartButton" onclick="main();">Start Test</button>
<button type="button" id="StartButton2" onclick="alert('Hey ya Start Button 2');">Show alert</button>
</body>
</html>
datetime
is a builtin module, so there is no (Python) source file.
For modules coming from .py
(or .pyc
) files, you can use mymodule.__file__
, e.g.
> import random
> random.__file__
'C:\\Python25\\lib\\random.pyc'
It's a bit of a guess but could the quotes around happy be the problem? There have been some problems in the past where Android would either add or not recognize quotes around an SSID. Try setting up the hosted network connection again, but without the quotes that we see in the output for netsh wlan show hostednetwork
.
You can try using this code:
protected ServiceConnection mServerConn = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "onServiceConnected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "onServiceDisconnected");
}
}
public void start() {
// mContext is defined upper in code, I think it is not necessary to explain what is it
mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
mContext.startService(intent);
}
public void stop() {
mContext.stopService(new Intent(mContext, ServiceRemote.class));
mContext.unbindService(mServerConn);
}
A tty
is a physical terminal-teletype port on a computer (usually a serial port).
The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.
A pty
is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.
A terminal is simply a computer's user interface that uses text for input and output.
These use pseudo-teletype ports however, their naming and implementations have diverged a little.
Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts
for every new terminal window you open, e.g. /dev/pts/0
macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY
naming convention ttys
for every new terminal window you open e.g. /dev/ttys002
Microsoft Windows still has the concept of an LPT
port for Line Printer Terminals within it's Command Shell for output to a printer.
You no need to assign this to a local variable if you use arrow function. Arrow functions takes binding automatically and you can stay away with scope related issues.
Below code explains how to use arrow function in different scenarios
componentDidMount = () => {
VK.init(() => {
console.info("API initialisation successful");
VK.api('users.get',{fields: 'photo_50'},(data) => {
if(data.response){
that.setState({ //this available here and you can do setState
FirstName: data.response[0].first_name
});
console.info(that.state.FirstName);
}
});
}, () => {
console.info("API initialisation failed");
}, '5.34');
},
Make sure you are sending the proper parameters too. This happened to me after switching to UI-Router.
To fix it, I changed $routeParams to use $stateParams in my controller. The main issue was that $stateParams was no longer sending a proper parameter to the resource.
All the answers seem correct so I'll go ahead and give a complete answer here.
Firstly, the easiest way to do what you are trying to do is launch a Broadcast in Android when the app is killed manually, and define a custom BroadcastReceiver
to trigger a service restart following that.
Now lets jump into code.
Create your Service in YourService.java
Note the onCreate()
method, where we are starting a foreground service differently for Build versions greater than Android Oreo. This because of the strict notification policies introduced recently where we have to define our own notification channel to display them correctly.
The this.sendBroadcast(broadcastIntent);
in the onDestroy()
method is the statement which asynchronously sends a broadcast with the action name "restartservice"
. We'll be using this later as a trigger to restart our service.
Here we have defined a simple Timer task, which prints a counter value every 1 second in the Log
while incrementing itself every time it prints.
public class YourService extends Service {
public int counter=0;
@Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
stoptimertask();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
timerTask = new TimerTask() {
public void run() {
Log.i("Count", "========= "+ (counter++));
}
};
timer.schedule(timerTask, 1000, 1000); //
}
public void stoptimertask() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
Create a Broadcast Receiver to respond to your custom defined broadcasts in Restarter.java
The broadcast with the action name "restartservice"
which you just defined in YourService.java
is now supposed to trigger a method which will restart your service. This is done using BroadcastReceiver
in Android.
We override the built-in onRecieve()
method in BroadcastReceiver
to add the statement which will restart the service. The startService()
will not work as intended in and above Android Oreo 8.1, as strict background policies will soon terminate the service after restart once the app is killed. Therefore we use the startForegroundService()
for higher versions and show a continuous notification to keep the service running.
public class Restarter extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context, YourService.class));
} else {
context.startService(new Intent(context, YourService.class));
}
}
}
Define your MainActivity.java
to call the service on app start.
Here we define a separate isMyServiceRunning()
method to check the current status of the background service. If the service is not running, we start it by using startService()
.
Since the app is already running in foreground, we need not launch the service as a foreground service to prevent itself from being terminated.
Note that in onDestroy()
we are dedicatedly calling stopService()
, so that our overridden method gets invoked. If this was not done, then the service would have ended automatically after app is killed without invoking our modified onDestroy()
method in YourService.java
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private YourService mYourService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYourService = new YourService();
mServiceIntent = new Intent(this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
@Override
protected void onDestroy() {
//stopService(mServiceIntent);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
}
}
Finally register them in your AndroidManifest.xml
All of the above three classes need to be separately registered in AndroidManifest.xml
.
Note that we define an intent-filter
with the action name as "restartservice"
where the Restarter.java
is registered as a receiver
.
This ensures that our custom BroadcastReciever
is called whenever the system encounters a broadcast with the given action name.
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver
android:name="Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
</intent-filter>
</receiver>
<activity android:name="MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="YourService"
android:enabled="true" >
</service>
</application>
This should now restart your service again if the app was killed from the task-manager. This service will keep on running in background as long as the user doesn't Force Stop
the app from Application Settings.
UPDATE: Kudos to Dr.jacky for pointing it out. The above mentioned way will only work if the onDestroy()
of the service is called, which might not be the case certain times, which I was unaware of. Thanks.
Just a guess, but I think with the SYSTEM_ALERT_WINDOW permission (displayed as "Draw over other apps", see here) it could be possible: display your app as a fullscreen, system alert type window. This way it will hide any other apps, even the homescreen so if you press Home, it won't really be disabled, just without any visible effect.
MX Player has this permission declared, and Facebook Messenger has it too for displaying "chat heads" over anything - so it might be the solution.
Update (added from my comments): Next, use SYSTEM_UI_FLAG_HIDE_NAVIGATION in conjunction with capturing touch events/using OnSystemUiVisibilityChangeListener to override the default behaviour (navbar appearing on touch). Also, since you said exit immersive gesture does not work, you could try setting SYSTEM_UI_FLAG_IMMERSIVE_STICKY too (with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION).
I have encountered this with Maven projects too. This is what I had to do to get around the problem:
First update your web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>Servlet 3.0 Web Application</display-name>
Then right click on your project and select Properties -> Project Facets In there you will see the version of your Dynamic Web Module. This needs to change from version 2.3 or whatever to version 2.5 or above (I chose 3.0).
However to do this I had to uncheck the tick box for Dynamic Web Module -> Apply, then do a Maven Update on the project. Go back into the Project Facets window and it should already match your web.xml configuration - 3.0 in my case. You should be able to change it if not.
If this does not work for you then try right-clicking on the Dynamic Web Module Facet and select change version (and ensure it is not locked).
Or you can follow this steps:
don't forget to update your project
Hope that works!
You can join the table with itself (on sensor id), and add left.timestamp < right.timestamp
as join condition. Then you pick the rows, where right.id
is null
. Voila, you got the latest entry per sensor.
http://sqlfiddle.com/#!9/45147/37
SELECT L.* FROM sensorTable L
LEFT JOIN sensorTable R ON
L.sensorID = R.sensorID AND
L.timestamp < R.timestamp
WHERE isnull (R.sensorID)
But please note, that this will be very resource intensive if you have a little amount of ids and many values! So, I wouldn't recommend this for some sort of Measuring-Stuff, where each Sensor collects a value every minute. However in a Use-Case, where you need to track "Revisions" of something that changes just "sometimes", it's easy going.
From Python 3.0 changelog;
The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.
From the Python 3 email documentation it can be seen that io.StringIO
should be used instead:
from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()
Reference: https://docs.python.org/3/library/io.html
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details:
you can achieve vertical aligning with display:table-cell
:
#section1 {
height: 90%;
text-align:center;
display:table;
width:100%;
}
#section1 h1 {display:table-cell; vertical-align:middle}
Update - CSS3
For an alternate way to vertical align, you can use the following css 3 which should be supported in all the latest browsers:
#section1 {
height: 90%;
width:100%;
display:flex;
align-items: center;
justify-content: center;
}
Care and feeding of Eclipse's memory hunger is a pain...
More or less, keep trying smaller amounts til it works, that's your max.
In jquery use <
window.location.href = window.location.href.split("?")[0]
You have to add a condition in your componentDidUpdate
method.
The example is using fast-deep-equal
to compare the objects.
import equal from 'fast-deep-equal'
...
constructor(){
this.updateUser = this.updateUser.bind(this);
}
componentDidMount() {
this.updateUser();
}
componentDidUpdate(prevProps) {
if(!equal(this.props.user, prevProps.user)) // Check if it's a new user, you can also use some unique property, like the ID (this.props.user.id !== prevProps.user.id)
{
this.updateUser();
}
}
updateUser() {
if (this.props.isManager) {
this.props.dispatch(actions.fetchAllSites())
} else {
const currentUserId = this.props.user.get('id')
this.props.dispatch(actions.fetchUsersSites(currentUserId))
}
}
Using Hooks (React 16.8.0+)
import React, { useEffect } from 'react';
const SitesTableContainer = ({
user,
isManager,
dispatch,
sites,
}) => {
useEffect(() => {
if(isManager) {
dispatch(actions.fetchAllSites())
} else {
const currentUserId = user.get('id')
dispatch(actions.fetchUsersSites(currentUserId))
}
}, [user]);
return (
return <SitesTable sites={sites}/>
)
}
If the prop you are comparing is an object or an array, you should use useDeepCompareEffect
instead of useEffect
.
If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).
newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict
k
# [1, 2, 3]
+---------------------------------------------------------+
¦ k = list(d) ¦ 9 characters (excluding whitespace) ¦
+---------------+-----------------------------------------¦
¦ k = [*d] ¦ 6 characters ¦
+---------------+-----------------------------------------¦
¦ *k, = d ¦ 5 characters ¦
+---------------------------------------------------------+
A refinement on the answer by JSmyth:
console.logCopy = console.log.bind(console);
console.log = function()
{
if (arguments.length)
{
var timestamp = new Date().toJSON(); // The easiest way I found to get milliseconds in the timestamp
var args = arguments;
args[0] = timestamp + ' > ' + arguments[0];
this.logCopy.apply(this, args);
}
};
This:
.log
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
JSON.stringify(tempActivity, getCircularReplacer());
Where tempActivity is fething the data which produces the error "SyntaxError: Unexpected token o in JSON at position 1 - Stack Overflow"
If you want to do some checks then use this way
<select size="1" name="links" onchange="functionToTriggerClick(this.value)">
<option value="">Select a Search Engine</option>
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
<script>
function functionToTriggerClick(link) {
if(link != ''){
window.location.href=link;
}
}
</script>
Well, as most of the answers pointed out, you can include the jQuery file locally as well as use Google's CDN/Microsoft CDN servers. On choosing Google vs. Microsoft CDN go Google_CDN vs. Microsoft_CDN depending on your requirement.
Generally for intranet applications include jQuery file locally and never use the CDN method since for intranet, the LAN is 10x times faster than Internet. For Internet and public facing applications use a hybrid approach as suggested by cowgod elsewhere. Also don't forget to use the nice tool JS_Compressor to compress the extra JavaScript code you add to your jQuery library. It makes JavaScript really fast.
I think part of it is that you're stating the value you're selecting after CASE
, and then using WHEN x = y
syntax afterward, which is a combination of two different methods of using CASE
. It should either be
CASE X
WHEN a THEN ...
WHEN b THEN ...
or
CASE
WHEN x = a THEN ...
WHEN x = b THEN ...
The erase
method will be used in two ways:
Erasing single element:
vector.erase( vector.begin() + 3 ); // Deleting the fourth element
Erasing range of elements:
vector.erase( vector.begin() + 3, vector.begin() + 5 ); // Deleting from fourth element to sixth element
"this" is all about scope. Every function has its own scope, and since everything in JS is an object, even a function can store some values into itself using "this". OOP 101 teaches that "this" is only applicable to instances of an object. Therefore, every-time a function executes, a new "instance" of that function has a new meaning of "this".
Most people get confused when they try to use "this" inside of anonymous closure functions like:
(function(value) { this.value = value; $('.some-elements').each(function(elt){ elt.innerHTML = this.value; // uh oh!! possibly undefined }); })(2);
So here, inside each(), "this" doesn't hold the "value" that you expect it to (from
this.value = value;above it). So, to get over this (no pun intended) problem, a developer could:
(function(value) { var self = this; // small change self.value = value; $('.some-elements').each(function(elt){ elt.innerHTML = self.value; // phew!! == 2 }); })(2);
Try it out; you'll begin to like this pattern of programming
CREATE TABLE something (
column1 INTEGER NOT NULL,
column2 INTEGER NOT NULL,
value,
PRIMARY KEY ( column1, column2)
);
You use and
and or
to perform logical operations like in C, C++. Like literally and
is &&
and or
is ||
.
Say you want to build Logic Gates in Python:
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
Now try calling them:
print AND(False, False)
print OR(True, False)
False
True
Hope this helps!
PHP's strtotime
function will interpret timezone codes, like UTC. If you get the date from the database/client without the timezone code, but know it's UTC, then you can append it.
Assuming you get the date with timestamp code (like "Fri Mar 23 2012 22:23:03 GMT-0700 (PDT)", which is what Javascript code ""+(new Date())
gives):
$time = strtotime($dateWithTimeZone);
$dateInLocal = date("Y-m-d H:i:s", $time);
Or if you don't, which is likely from MySQL, then:
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
@gimel's answer is correct if you can guarantee the package hierarchy he mentions. If you can't -- if your real need is as you expressed it, exclusively tied to directories and without any necessary relationship to packaging -- then you need to work on __file__
to find out the parent directory (a couple of os.path.dirname
calls will do;-), then (if that directory is not already on sys.path
) prepend temporarily insert said dir at the very start of sys.path
, __import__
, remove said dir again -- messy work indeed, but, "when you must, you must" (and Pyhon strives to never stop the programmer from doing what must be done -- just like the ISO C standard says in the "Spirit of C" section in its preface!-).
Here is an example that may work for you:
import sys
import os.path
sys.path.append(
os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
import module_in_parent_dir
sendmail
works for me on the mac (10.6.8)
echo "Hello" | sendmail -f [email protected] [email protected]
Apple documentation says
A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.
to add to the existing answer
@interface YourClass : NSObject <NSCopying>
{
SomeOtherObject *obj;
}
// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
YourClass *another = [super copyWithZone:zone];
another.obj = [obj copyWithZone: zone];
return another;
}
Mbstring is a non-default extension. This means it is not enabled by default. You must explicitly enable the module with the configure option.
In case your php version is 7.0:
sudo apt-get install php7.0-mbstring
sudo service apache2 restart
In case your php version is 5.6:
sudo apt-get install php5.6-mbstring
sudo service apache2 restart
My way to effectively work with multiple files is to use tmux.
It allows you to split windows vertically and horizontally, as in:
I have it working this way on both my mac and linux machines and I find it better than the native window pane switching mechanism that's provided (on Macs). I find the switching easier and only with tmux have I been able to get the 'new page at the same current directory' working on my mac (despite the fact that there seems to be options to open new panes in the same directory) which is a surprisingly critical piece. An instant new pane at the current location is amazingly useful. A method that does new panes with the same key combos for both OS's is critical for me and a bonus for all for future personal compatibility. Aside from multiple tmux panes, I've also tried using multiple tabs, e.g. and multiple new windows, e.g. and ultimately I've found that multiple tmux panes to be the most useful for me. I am very 'visual' and like to keep my various contexts right in front of me, connected together as panes.
tmux also support horizontal and vertical panes which the older screen
didn't (though mac's iterm2 seems to support it, but again, the current directory setting didn't work for me). tmux 1.8
I think this answer can also work (it may require a little bit of modification though) :
SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)
I called ng-click
to angularjs controller on Encourage button,
<tr ng-cloak
ng-repeat="user in result.users">
<td>{{user.userName}}</rd>
<td>
<a class="btn btn-primary span11" ng-click="setUsername({{user.userName}})" href="#encouragementModal" data-toggle="modal">
Encourage
</a>
</td>
</tr>
I set userName
of encouragementModal
from angularjs controller.
/**
* Encouragement controller for AngularJS
*
* @param $scope
* @param $http
* @param encouragementService
*/
function EncouragementController($scope, $http, encouragementService) {
/**
* set invoice number
*/
$scope.setUsername = function (username) {
$scope.userName = username;
};
}
EncouragementController.$inject = [ '$scope', '$http', 'encouragementService' ];
I provided a place(userName
) to get value from angularjs controller on encouragementModal
.
<div id="encouragementModal" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h3>Confirm encouragement?</h3>
</div>
<div class="modal-body">
Do you really want to encourage <b>{{userName}}</b>?
</div>
<div class="modal-footer">
<button class="btn btn-info"
ng-click="encourage('${createLink(uri: '/encourage/')}',{{userName}})">
Confirm
</button>
<button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
</div>
</div>
If you use screen to run a process as root, beware of the possibility of privilege elevation attacks. If your own account gets compromised somehow, there will be a direct way to take over the entire server.
If this process needs to be run regularly and you have sufficient access on the server, a better option would be to use cron the run the job. You could also use init.d (the super daemon) to start your process in the background, and it can terminate as soon as it's done.
I just wanted to add that with flatMap
, you don't really need to use your own custom Observable inside the function and you can rely on standard factory methods/operators:
Observable.from(jsonFile).flatMap(new Func1<File, Observable<String>>() {
@Override public Observable<String> call(final File file) {
try {
String json = new Gson().toJson(new FileReader(file), Object.class);
return Observable.just(json);
} catch (FileNotFoundException ex) {
return Observable.<String>error(ex);
}
}
});
Generally, you should avoid throwing (Runtime-) exceptions from onXXX methods and callbacks if possible, even though we placed as many safeguards as we could in RxJava.
You can, using CSS variables (more precisely called CSS custom properties).
style="--my-color-var: orange;"
background-color: var(--my-color-var);
div {
width: 100px;
height: 100px;
position: relative;
border: 1px solid black;
}
div:after {
background-color: var(--my-color-var);
content: '';
position: absolute;
top: 0;
bottom: 0;
right: 0;
left: 0;
}
_x000D_
<div style="--my-color-var: orange;"></div>
_x000D_
.bubble {
position: relative;
width: 30px;
height: 15px;
padding: 0;
background: #FFF;
border: 1px solid #000;
border-radius: 5px;
text-align: center;
background-color: var(--bubble-color);
}
.bubble:after {
content: "";
position: absolute;
top: 4px;
left: -4px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent var(--bubble-color);
display: block;
width: 0;
z-index: 1;
}
.bubble:before {
content: "";
position: absolute;
top: 4px;
left: -5px;
border-style: solid;
border-width: 3px 4px 3px 0;
border-color: transparent #000;
display: block;
width: 0;
z-index: 0;
}
_x000D_
<div class='bubble' style="--bubble-color: rgb(100,255,255);"> 100 </div>
_x000D_
Another solution without the submit button:
HTML
<form>
<input class="submit_on_enter" type="text" name="q" placeholder="Search...">
</form>
jQuery
$(document).ready(function() {
$('.submit_on_enter').keydown(function(event) {
// enter has keyCode = 13, change it if you want to use another button
if (event.keyCode == 13) {
this.form.submit();
return false;
}
});
});
It contains your local IntelliJ IDE configs. I recommend adding this folder to your .gitignore
file:
# intellij configs
.idea/
A use case for it when you want to use a table with *ngIf and *ngFor - As putting a div in td/th will make the table element misbehave -. I faced this problem and that was the answer.
I personally would just use the JavaScript code to switch between 2 classes.
Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).
CSS with different images
.div {
/* button size etc properties */
}
.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}
Or CSS with image sprite
.div {
background: url(img/sprite.gif) no-repeat left top;
/* Other styles */
}
.expanded {background-position: left bottom;}
Then...
JavaScript code with images
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).addClass('collapsed').removeClass('expanded');
}
else
{
$(this).addClass('expanded').removeClass('collapsed');
}
});
}
JavaScript with sprite
Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass
/removeClass
method will work fine in this situation as well
The most elegant solution (unfortunately not Internet Explorer 6 friendly)
$(function){
$('#button').click(function(){
$(this).toggleClass('expanded');
});
}
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).removeClass('expanded');
}
else
{
$(this).addClass('expanded');
}
});
}
As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.
Could anyone help explain why
In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.
The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.
or give a solution for the code on windows? Thanks so much!
Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64
You can use AudioStream this way as well:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
public class AudioWizz extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L; //you like your cereal and the program likes their "serial"
static AudioWizz a;
static JButton playBuddon;
static JFrame frame;
public static void main(String arguments[]){
frame= new JFrame("AudioWizz");
frame.setSize(300,300);
frame.setVisible(true);
a= new AudioWizz();
playBuddon= new JButton("PUSH ME");
playBuddon.setBounds(10,10,80,30);
playBuddon.addActionListener(a);
frame.add(playBuddon);
frame.add(a);
}
public void actionPerformed(ActionEvent e){ //an eventListener
if (e.getSource() == playBuddon) {
try {
InputStream in = new FileInputStream("*.wav");
AudioStream sound = new AudioStream(in);
AudioPlayer.player.start(sound);
} catch(FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I came across this in PHP when using fopen()
on a file and then trying to unlink()
it before using fclose()
on it.
No good:
$handle = fopen('file.txt');
// do something
unlink('file.txt');
Good:
$handle = fopen('file.txt');
// do something
fclose($handle);
unlink('file.txt');
Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR
The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.
For example:
{ "things": ["a", "b", "c"] }
Would Unmarshal into a:
type Item struct {
Things []string
}
And not into:
type Item struct {
Things string
}
The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int
or float
field -- "1"
needs to Unmarshal into a string
, not into an int
like we saw with ShippingAdditionalCost int
Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
You can only include a script file in an HTML page, not in another script file. That said, you can write JavaScript which loads your "included" script into the same page:
var imported = document.createElement('script');
imported.src = '/path/to/imported/script';
document.head.appendChild(imported);
There's a good chance your code depends on your "included" script, however, in which case it may fail because the browser will load the "imported" script asynchronously. Your best bet will be to simply use a third-party library like jQuery or YUI, which solves this problem for you.
// jQuery
$.getScript('/path/to/imported/script.js', function()
{
// script is now loaded and executed.
// put your dependent JS here.
});
Take a look at Enumerable#each_slice:
foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]
To add return functionalty, you could do this:
func synchronize<T>(lockObj: AnyObject!, closure: ()->T) -> T
{
objc_sync_enter(lockObj)
var retVal: T = closure()
objc_sync_exit(lockObj)
return retVal
}
Subsequently, you can call it using:
func importantMethod(...) -> Bool {
return synchronize(self) {
if(feelLikeReturningTrue) { return true }
// do other things
if(feelLikeReturningTrueNow) { return true }
// more things
return whatIFeelLike ? true : false
}
}
Try this one in model class
[Required(ErrorMessage = "Enter full name.")]
[RegularExpression("([A-Za-z])+( [A-Za-z]+)", ErrorMessage = "Enter valid full name.")]
public string FullName { get; set; }
These days, once you have LINQ available, you can convert the dictionary keys and their values to a single string.
You can use the following code:
// convert the dictionary to an array of strings
string[] strArray = dict.Select(x => ("Key: " + x.Key + ", Value: " + x.Value)).ToArray();
// convert a string array to a single string
string result = String.Join(", ", strArray);
If we need to share multiple variables use the below format
//module.js
let name='foobar';
let city='xyz';
let company='companyName';
module.exports={
name,
city,
company
}
Usage
// main.js
require('./modules');
console.log(name); // print 'foobar'
use
$(document).height()property and set to the div from script and set
overflow=auto
for scrolling
It is indeed correct, as other answers have stated. You should note though, that some web crawlers will set off 404s for these by requesting them on your server as if a local URL. (They disregard the double slash and treat it as a single slash).
You may want to set up a rule on your webserver to catch these and redirect them.
For example, with Nginx, you'd add something like:
location ~* /(?<redirect_domain>((([a-z]|[0-9]|\-)+)\.)+([a-z])+)/(?<redirect_path>.*) {
return 301 $scheme:/$redirect_domain/$redirect_path;
}
Do note though, that if you use periods in your URIs, you'll need to increase the specificity or it will end up redirecting those pages to nonexistent domains.
Also, this is a rather massive regex to be running for each query -- in my opinion, it's worth punishing non-compliant browsers with 404s over a (slight) performance hit on the majority of compliant browsers.
In node, the Mongo driver will give you an ISO string, not the object. (ex: Mon Nov 24 2014 01:30:34 GMT-0800 (PST)
) So, simply convert it to a js Date by: new Date(ISOString);
With C++11, you can do std::string(v.data())
or, if your vector does not contain a '\0'
at the end, std::string(v.data(), v.size())
.
Use permission symbols instead of numbers
Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664
:
#!/usr/bin/env python3
import os
import stat
os.chmod(
'myfile',
stat.S_IRUSR |
stat.S_IWUSR |
stat.S_IRGRP |
stat.S_IWGRP |
stat.S_IROTH
)
This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat
.
Another advantage is the greater portability as mentioned in the docs:
Note: Although Windows supports
chmod()
, you can only set the file’s read-only flag with it (via thestat.S_IWRITE
andstat.S_IREAD
constants or a corresponding integer value). All other bits are ignored.
chmod +x
is demonstrated at: How do you do a simple "chmod +x" from within python?
Tested in Ubuntu 16.04, Python 3.5.2.
Reactstrap also has an implementation of Bootstrap Modals in React. This library targets Bootstrap version 4, whereas react-bootstrap targets version 3.X.
You could use a map function that allows multiple arguments, as does the fork of multiprocessing
found in pathos
.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> def add_and_subtract(x,y):
... return x+y, x-y
...
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
pathos
enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.
>>> from pathos.multiprocessing import ThreadingPool as TPool
>>>
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
Even more fun, is to build a nested function that we can pass into the Pool.
This is possible because pathos
uses dill
, which can serialize almost anything in python.
>>> def build_fun_things(f, g):
... def do_fun_things(x, y):
... return f(x,y), g(x,y)
... return do_fun_things
...
>>> def add(x,y):
... return x+y
...
>>> def sub(x,y):
... return x-y
...
>>> neato = build_fun_things(add, sub)
>>>
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap
as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)
Get pathos
here: https://github.com/uqfoundation
Change the port 80 to port 8080 and restart all services and access like localhost:8080/
It will work fine.
In order to use base_url()
, you must first have the URL Helper loaded. This can be done either in application/config/autoload.php
(on or around line 67):
$autoload['helper'] = array('url');
Or, manually:
$this->load->helper('url');
Once it's loaded, be sure to keep in mind that base_url()
doesn't implicitly print or echo out anything, rather it returns the value to be printed:
echo base_url();
Remember also that the value returned is the site's base url as provided in the config file. CodeIgniter will accomodate an empty value in the config file as well:
If this (base_url) is not set then CodeIgniter will guess the protocol, domain and path to your installation.
application/config/config.php, line 13
I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers
still had the old server name.
I had to drop the old server name and add the new server name to sys.servers
on the new server
sp_dropserver 'Server_A'
GO
sp_addserver 'Server',local
GO
In addition to @ericgol's answer: In the French version of Visual Studio Community 2017, type "Concepteur de classes" in the search bar.
You can also use array_keys()
. Newbie friendly:
$keys = array_keys($arrayToWalk);
$arraySize = count($arrayToWalk);
for($i=0; $i < $arraySize; $i++) {
echo '<option value="' . $keys[$i] . '">' . $arrayToWalk[$keys[$i]] . '</option>';
}
You should remove the references to it by assigning null or leaving the block where it was declared. After that, it will be automatically deleted by the garbage collector (not immediately, but eventually).
Example 1:
Object a = new Object();
a = null; // after this, if there is no reference to the object,
// it will be deleted by the garbage collector
Example 2:
if (something) {
Object o = new Object();
} // as you leave the block, the reference is deleted.
// Later on, the garbage collector will delete the object itself.
Not something that you are currently looking for, but FYI: you can invoke the garbage collector with the call System.gc()
If you're trying to insert in to last_accessed_on
, which is a DateTime2
, then your issue is with the fact that you are converting it to a varchar
in a format that SQL doesn't understand.
If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Or if you want to use CAST
, replace with:
CAST('2014-07-23 09:37:00.000' AS datetime2)
This is using the SQL ISO Date Format.
#visibilityOfElementLocated
None of the answers using isDisplayed
or similar are correct. They only check if the display
property is not none
, not if the element can actually be seen! Selenium had a bunch of static utility methods added in the ExpectedConditions
class. Two of them can be used in this case:
Usage
@Test
// visibilityOfElementLocated has been statically imported
public demo(){
By searchButtonSelector = By.className("search_button");
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.get(homeUrl);
WebElement searchButton = wait.until(
visibilityOfElementLocated
(searchButtonSelector));
//clicks the search button
searchButton.click();
This was my answer before finding out about the utility methods on ExpectedConditions
. It might still be relevant, as I assume it does more than the method mentioned above, which only checks the element has a height and a width.
In essence: this cannot be answered by Java and the findElementBy*
methods and WebElement#isDisplayed
alone, as they can only tell you if an element exists, not if it is actually visible. The OP hasn't defined what visible means, but it normally entails
opacity
> 0display
property set to something else than none
visibility
prop is set to visible
Most people would also include the requirement that it is actually within the viewport as well (so a person would be able to see it).
For some reason, this quite normal need is not met by the pure Java API, while front-ends to Selenium that builds upon it often implements some variation of isVisible
, which is why I knew this should be possible. And after browsing the source of the Node framework WebDriver.IO I found the source of isVisible
, which is now renamed to the more aptly name of isVisibleInViewport
in the 5.0-beta.
Basically, they implement the custom command as a call that delegates to a javascript that runs on the client and does the actual work! This is the "server" bit:
export default function isDisplayedInViewport () {
return getBrowserObject(this).execute(isDisplayedInViewportScript, {
[ELEMENT_KEY]: this.elementId, // w3c compatible
ELEMENT: this.elementId // jsonwp compatible
})
}
So the interesting bit is the javascript sent to run on the client:
/**
* check if element is visible and within the viewport
* @param {HTMLElement} elem element to check
* @return {Boolean} true if element is within viewport
*/
export default function isDisplayedInViewport (elem) {
const dde = document.documentElement
let isWithinViewport = true
while (elem.parentNode && elem.parentNode.getBoundingClientRect) {
const elemDimension = elem.getBoundingClientRect()
const elemComputedStyle = window.getComputedStyle(elem)
const viewportDimension = {
width: dde.clientWidth,
height: dde.clientHeight
}
isWithinViewport = isWithinViewport &&
(elemComputedStyle.display !== 'none' &&
elemComputedStyle.visibility === 'visible' &&
parseFloat(elemComputedStyle.opacity, 10) > 0 &&
elemDimension.bottom > 0 &&
elemDimension.right > 0 &&
elemDimension.top < viewportDimension.height &&
elemDimension.left < viewportDimension.width)
elem = elem.parentNode
}
return isWithinViewport
}
This piece of JS can actually be copied (almost) verbatim into your own codebase (remove export default
and replace const
with var
in case of non-evergreen browsers)! To use it, read it from File
into a String
that can be sent by Selenium for running on the client.
Another interesting and related script that might be worth looking into is selectByVisibleText.
If you haven't executed JS using Selenium before you could have a small peek into this or browse the JavaScriptExecutor API.
Usually, try to always use non-blocking async scripts (meaning #executeAsyncScript), but since we already have a synchronous, blocking script we might as well use the normal sync call. The returned object can be many types of Object, so cast approprately. This could be one way of doing it:
/**
* Demo of a java version of webdriverio's isDisplayedInViewport
* https://github.com/webdriverio/webdriverio/blob/v5.0.0-beta.2/packages/webdriverio/src/commands/element/isDisplayedInViewport.js
* The super class GuiTest just deals with setup of the driver and such
*/
class VisibleDemoTest extends GuiTest {
public static String readScript(String name) {
try {
File f = new File("selenium-scripts/" + name + ".js");
BufferedReader reader = new BufferedReader( new FileReader( file ) );
return reader.lines().collect(Collectors.joining(System.lineSeparator()));
} catch(IOError e){
throw new RuntimeError("No such Selenium script: " + f.getAbsolutePath());
}
}
public static Boolean isVisibleInViewport(RemoteElement e){
// according to the Webdriver spec a string that identifies an element
// should be deserialized into the corresponding web element,
// meaning the 'isDisplayedInViewport' function should receive the element,
// not just the string we passed to it originally - how this is done is not our concern
//
// This is probably when ELEMENT and ELEMENT_KEY refers to in the wd.io implementation
//
// Ref https://w3c.github.io/webdriver/#dfn-json-deserialize
return js.executeScript(readScript("isDisplayedInViewport"), e.getId());
}
public static Boolean isVisibleInViewport(String xPath){
driver().findElementByXPath("//button[@id='should_be_visible']");
}
@Test
public demo_isVisibleInViewport(){
// you can build all kinds of abstractions on top of the base method
// to make it more Selenium-ish using retries with timeouts, etc
assertTrue(isVisibleInViewport("//button[@id='should_be_visible']"));
assertFalse(isVisibleInViewport("//button[@id='should_be_hidden']"));
}
}
A single css code on hover can do the trick:
box-shadow: inset 100px 0 0 0 #e0e0e0;
A complete demo can be found in my fiddle:
Use This Code
@echo off
:: Get the current directory
for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A
echo CURRENT_DIR%%A
(echo this To confirm this code works fine)
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
You can use any of the following methods for setting the Drawable on TextView:
1- setCompoundDrawablesWithIntrinsicBounds(int, int, int, int)
2- setCompoundDrawables(Left_Drawable, Top_Drawable, Right_Drawable, Bottom_Drawable)
And to get drawable from resources you can use:
getResources().getDrawable(R.drawable.your_drawable_id);
From JDK-4045622, where Joshua Bloch describes the reasons why that particular (new) String.hashCode()
implementation was chosen
The table below summarizes the performance of the various hash functions described above, for three data sets:
1) All of the words and phrases with entries in Merriam-Webster's 2nd Int'l Unabridged Dictionary (311,141 strings, avg length 10 chars).
2) All of the strings in /bin/, /usr/bin/, /usr/lib/, /usr/ucb/ and /usr/openwin/bin/* (66,304 strings, avg length 21 characters).
3) A list of URLs gathered by a web-crawler that ran for several hours last night (28,372 strings, avg length 49 characters).
The performance metric shown in the table is the "average chain size" over all elements in the hash table (i.e., the expected value of the number of key compares to look up an element).
Webster's Code Strings URLs --------- ------------ ---- Current Java Fn. 1.2509 1.2738 13.2560 P(37) [Java] 1.2508 1.2481 1.2454 P(65599) [Aho et al] 1.2490 1.2510 1.2450 P(31) [K+R] 1.2500 1.2488 1.2425 P(33) [Torek] 1.2500 1.2500 1.2453 Vo's Fn 1.2487 1.2471 1.2462 WAIS Fn 1.2497 1.2519 1.2452 Weinberger's Fn(MatPak) 6.5169 7.2142 30.6864 Weinberger's Fn(24) 1.3222 1.2791 1.9732 Weinberger's Fn(28) 1.2530 1.2506 1.2439
Looking at this table, it's clear that all of the functions except for the current Java function and the two broken versions of Weinberger's function offer excellent, nearly indistinguishable performance. I strongly conjecture that this performance is essentially the "theoretical ideal", which is what you'd get if you used a true random number generator in place of a hash function.
I'd rule out the WAIS function as its specification contains pages of random numbers, and its performance is no better than any of the far simpler functions. Any of the remaining six functions seem like excellent choices, but we have to pick one. I suppose I'd rule out Vo's variant and Weinberger's function because of their added complexity, albeit minor. Of the remaining four, I'd probably select P(31), as it's the cheapest to calculate on a RISC machine (because 31 is the difference of two powers of two). P(33) is similarly cheap to calculate, but it's performance is marginally worse, and 33 is composite, which makes me a bit nervous.
Josh
As already stated there is nothing you can do except restore from a backup. At least now you will have learned to always wrap statements in a transaction to see what happens before you decide to commit. Also, if you don't have a backup of your database this will also teach you to make regular backups of your database.
While we haven't been much help for your imediate problem...hopefully these answers will ensure you don't run into this problem again in the future.
For example , a function which returns value of any parameters variable.
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}?
And this is how you can use this function assuming the URL is,
"http://example.com/?technology=jquery&blog=jquerybyexample".
var tech = GetURLParameter('technology');
var blog = GetURLParameter('blog');
So in above code variable "tech" will have "jQuery" as value and "blog" variable's will be "jquerybyexample".
It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide
In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.
int random_int ( int $min , int $max )
random_int — Generates cryptographically secure pseudo-random integers
which basically makes previous answers obsolete.
If it's just a true/false test, have your function return 0
for success, and return 1
for failure. The test would then be:
if function_name; then
do something
else
error condition
fi
It truly solved my problem using eval function.
single_quoted_dict_in_string = "{'key':'value', 'key2': 'value2'}"
desired_double_quoted_dict = eval(single_quoted_dict_in_string)
# Go ahead, now you can convert it into json easily
print(desired_double_quoted_dict)
If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.
var inputs;
function doThisWhenReady() {
inputs = document.getElementsByTagName('input');
//Other code here...
}
window.onReady = doThisWhenReady;
This will work also when the string is invalid or does not contain flags etc:
function regExpFromString(q) {_x000D_
let flags = q.replace(/.*\/([gimuy]*)$/, '$1');_x000D_
if (flags === q) flags = '';_x000D_
let pattern = (flags ? q.replace(new RegExp('^/(.*?)/' + flags + '$'), '$1') : q);_x000D_
try { return new RegExp(pattern, flags); } catch (e) { return null; }_x000D_
}_x000D_
_x000D_
console.log(regExpFromString('\\bword\\b'));_x000D_
console.log(regExpFromString('\/\\bword\\b\/gi'));_x000D_
_x000D_
There isn't any graph api for this, you need to use facebook xmpp chat api to send the message, good news is: I have made a php class which is too easy to use,call a function and message will be sent, its open source, check it out: facebook message api php the description says its a closed source but the it was made open source later, see the first comment, you can clone from github. It's a open source now.
try with sticky jquery plugin
https://github.com/garand/sticky
<script src="jquery.js"></script>_x000D_
<script src="jquery.sticky.js"></script>_x000D_
<script>_x000D_
$(document).ready(function(){_x000D_
$("#sticker").sticky({topSpacing:0});_x000D_
});_x000D_
</script>
_x000D_
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
In my case it is Asp.Net Core 3.1 API. I changed the HTTP GET method from public ActionResult GetValidationRulesForField( GetValidationRulesForFieldDto getValidationRulesForFieldDto)
to public ActionResult GetValidationRulesForField([FromQuery] GetValidationRulesForFieldDto getValidationRulesForFieldDto)
and its working.
Swift 4:
func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell?.isSelected == true { // check if cell has been previously selected
tableView.deselectRow(at: indexPath, animated: true)
return nil
} else {
return indexPath
}
}
Go on Android Developer official link as tutorial step by step see and got the code for your application package from play store if exists or play store apps not exists then open application from web browser.
Android Developer official link
https://developer.android.com/distribute/tools/promote/linking.html
Linking to a Application Page
From a web site: https://play.google.com/store/apps/details?id=<package_name>
From an Android app: market://details?id=<package_name>
Linking to a Product List
From a web site: https://play.google.com/store/search?q=pub:<publisher_name>
From an Android app: market://search?q=pub:<publisher_name>
Linking to a Search Result
From a web site: https://play.google.com/store/search?q=<search_query>&c=apps
From an Android app: market://search?q=<seach_query>&c=apps
I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]]
throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if
in if [[ -n $argument_label ]] ; then
cleans it up.
Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.
Include File "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Include File "flags-arguments.sh"
# $@ here represents all arguments passed in
for i in "$@"
do
arguments[$index]=$i;
prev_index="$(expr $index - 1)";
# this if block does something akin to "where $i contains ="
# "%=*" here strips out everything from the = to the end of the argument leaving only the label
if [[ $i == *"="* ]]
then argument_label=${i%=*}
else argument_label=${arguments[$prev_index]}
fi
if [[ -n $argument_label ]] ; then
# this if block only evaluates to true if the argument label exists in the variables array
if [[ -n ${variables[$argument_label]} ]] ; then
# dynamically creating variables names using declare
# "#$argument_label=" here strips out the label leaving only the value
if [[ $i == *"="* ]]
then declare ${variables[$argument_label]}=${i#$argument_label=}
else declare ${variables[$argument_label]}=${arguments[$index]}
fi
fi
fi
index=index+1;
done;
Your "script.sh"
. bin/includes/flags-declares.sh
# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value)
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";
. bin/includes/flags-arguments.sh
# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";
This worked for me using ssh:
Settings → Developer settings → Generate new token.
git remote set-url origin https://[APPLICATION]:[NEW TOKEN]@github.com/[ORGANISATION]/[REPO].git
An Error Was Encountered Unable to load the requested file:
Sometimes we face this error because the requested file doesn't exist in that directory.
Suppose we have a folder home
in views
directory and trying to load home_view.php
file as:
$this->load->view('home/home_view', $data);// $data is array
If home_view.php
file doesn't exist in views/home
directory then it will raise an error.
An Error Was Encountered Unable to load the requested file: home\home_view.php
So how to fix this error go to views/home
and check the home_view.php
file exist if not then create it.
I recommend looking at the dataset array.
The dataset array is a data type that ships with Statistics Toolbox. It is specifically designed to store hetrogeneous data in a single container.
The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features. The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".
This code 100% remove duplicate values from an array[as I used a[i]].....You can convert it in any OO language..... :)
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(a[i] == a[j])
{
for(int k=j;k<size;k++)
{
a[k]=a[k+1];
}
j--;
size--;
}
}
}
As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.
--EDIT--
Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/
It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.
I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.
Corrected the Fiddle - updated shows the Image duplicated into the Canvas...
And right click can be saved as a .PNG
<div style="text-align:center">
<img src="http://imgon.net/di-M7Z9.jpg" id="picture" style="display:none;" />
<br />
<div id="for_jcrop">here the image should apear</div>
<canvas id="rotate" style="border:5px double black; margin-top:5px; "></canvas>
</div>
Plus the JS on the fiddle page...
Cheers Si
Currently looking at saving this to File on the server --- ASP.net C# (.aspx web form page) Any advice would be cool....
In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".
Why is this happening?
The entire ext/mysql
PHP extension, which provides all functions named with the prefix mysql_
, was officially deprecated in PHP v5.5.0 and removed in PHP v7.
It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.
The manual has contained warnings against its use in new code since June 2011.
How can I fix it?
As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql
. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.
They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.
Hashphp.org has an excellent tutorial on migrating from ext/mysql
to PDO.
I understand that it's possible to suppress deprecation errors by setting
error_reporting
inphp.ini
to excludeE_DEPRECATED
:error_reporting = E_ALL ^ E_DEPRECATED
What will happen if I do that?
Yes, it is possible to suppress such error messages and continue using the old ext/mysql
extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.
Note also that this technique will suppress all E_DEPRECATED
messages, not just those to do with the ext/mysql
extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @
—however this will suppress all errors raised by that expression, not just E_DEPRECATED
ones.
You are starting a new project.
There is absolutely no reason to use ext/mysql
—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.
You have (your own) legacy codebase that currently depends upon ext/mysql
.
It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.
Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.
Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.
The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.
Consider whether you really need to upgrade to PHP v5.5 at this time.
You should begin planning to replace ext/mysql
with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.
However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
You are using a third party project that depends upon ext/mysql
.
Consider whether you really need to upgrade to PHP v5.5 at this time.
Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.
It is absolutely essential to perform regression testing.
SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID
angular.module('formComponents', [])
.directive('formInput', function() {
return {
restrict: 'E',
compile: function(element, attrs) {
var type = attrs.type || 'text';
var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
var htmlText = '<div class="control-group">' +
'<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
'<div class="controls">' +
'<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
'</div>' +
'</div>';
element.replaceWith(htmlText);
}
};
})
extern "C"
doesn't change the presence or absence of the __cplusplus
macro. It just changes the linkage and name-mangling of the wrapped declarations.
You can nest extern "C"
blocks quite happily.
If you compile your .c
files as C++ then anything not in an extern "C"
block, and without an extern "C"
prototype will be treated as a C++ function. If you compile them as C then of course everything will be a C function.
Yes
You can safely mix C and C++ in this way.
If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time
with the ability to do arithmetic. If you go past midnight, it just wraps around:
>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'
It's available from PyPi as nptime
("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime
The documentation is at http://tgs.github.io/nptime/
To add on:
you can insert a time check within a loop with intensive or possible deadlock, ie.
:
section_toc_conditionalBreakOff;
:
where within this section
if (toc > timeRequiredToBreakOff) % time conditional break off
return;
% other options may be:
% 1. display intermediate values with pause;
% 2. exit; % in some cases, extreme : kill/ quit matlab
end
By adding a callback argument, you are telling jQuery that you want to make a request for JSONP using a script element instead of a request for JSON using XMLHttpRequest.
JSONP is not JSON. It is a JavaScript program.
Change your server so it outputs the right MIME type for JSONP which is application/javascript
.
(While you are at it, stop telling jQuery that you are expecting JSON as that is contradictory: dataType: 'jsonp'
).
Here is the OOP way of adding a colorbar:
fig, ax = plt.subplots()
im = ax.scatter(x, y, c=c)
fig.colorbar(im, ax=ax)
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
Every array in java is considered as an object. The public final length
is the data member
which contains the number of components of the array (length
may be positive or zero)
DNS server is obtained via
getprop net.dns1
UPDATE: as of Android Nougat 7.x, ifconfig is present, and netcfg is gone. So ifconfig can be used to find the IP and netmask.
That is not how the TryGetValue
works. It returns true
or false
based on whether the key is found or not, and sets its out
parameter to the corresponding value if the key is there.
If you want to check if the key is there or not and do something when it's missing, you need something like this:
bool hasValue = Data_Array.TryGetValue("XML_File", out value);
if (hasValue) {
xmlfile = value;
} else {
// do something when the value is not there
}
You don't need to downgrade your gulp from gulp 4. Use gulp.series() to combine multiple tasks. At first install gulp globally with
npm install --global gulp-cli
and then install locally on your working directory with
npm install --save-dev gulp
Example:
package.json
{
"name": "gulp-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"browser-sync": "^2.26.3",
"gulp": "^4.0.0",
"gulp-sass": "^4.0.2"
},
"dependencies": {
"bootstrap": "^4.3.1",
"jquery": "^3.3.1",
"popper.js": "^1.14.7"
}
}
gulpfile.js
var gulp = require("gulp");
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
// Specific Task
function js() {
return gulp
.src(['node_modules/bootstrap/dist/js/bootstrap.min.js', 'node_modules/jquery/dist/jquery.min.js', 'node_modules/popper.js/dist/umd/popper.min.js'])
.pipe(gulp.dest('src/js'))
.pipe(browserSync.stream());
}
gulp.task(js);
// Specific Task
function gulpSass() {
return gulp
.src(['src/scss/*.scss'])
.pipe(sass())
.pipe(gulp.dest('src/css'))
.pipe(browserSync.stream());
}
gulp.task(gulpSass);
// Run multiple tasks
gulp.task('start', gulp.series(js, gulpSass));
Run gulp start
to fire multiple tasks & run gulp js
or gulp gulpSass
for specific task.
You just need to return
from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.
/* .... */
if (Date1 == Date2)
fprintf (stderr , "Indicating that the first date is equal to second date.\n");
return 0;
}
If you are searching for the index of the last occurrence of myvalue
in mylist
:
len(mylist) - mylist[::-1].index(myvalue) - 1
Since you explicitly asked for VB as well, let me just add that this verbatim string syntax doesn't exist in VB, only in C#. Rather, all strings are verbatim in VB (except for the fact that they cannot contain line breaks, unlike C# verbatim strings):
Dim path = "C:\My\Path"
Dim message = "She said, ""Hello, beautiful world."""
Escape sequences don't exist in VB (except for the doubling of the quote character, like in C# verbatim strings) which makes a few things more complicated. For example, to write the following code in VB you need to use concatenation (or any of the other ways to construct a string)
string x = "Foo\nbar";
In VB this would be written as follows:
Dim x = "Foo" & Environment.NewLine & "bar"
(&
is the VB string concatenation operator. +
could equally be used.)
The servlet API .jar file must not be embedded inside the webapp since, obviously, the container already has these classes in its classpath: it implements the interfaces contained in this jar.
The dependency should be in the provided
scope, rather than the default compile
scope, in your Maven pom:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
If you are not worried about security and you're simply looking to start a docker container on the host from within another docker container like the OP, you can share the docker server running on the host with the docker container by sharing it's listen socket.
Please see https://docs.docker.com/engine/security/security/#docker-daemon-attack-surface and see if your personal risk tolerance allows this for this particular application.
You can do this by adding the following volume args to your start command
docker run -v /var/run/docker.sock:/var/run/docker.sock ...
or by sharing /var/run/docker.sock within your docker compose file like this:
version: '3'
services:
ci:
command: ...
image: ...
volumes
- /var/run/docker.sock:/var/run/docker.sock
When you run the docker start command within your docker container, the docker server running on your host will see the request and provision the sibling container.
credit: http://jpetazzo.github.io/2015/09/03/do-not-use-docker-in-docker-for-ci/
Or try adding this...
$code = @"
[DllImport("kernel32.dll")]
public static extern int GetExitCodeProcess(IntPtr hProcess, out Int32 exitcode);
"@
$type = Add-Type -MemberDefinition $code -Name "Win32" -Namespace Win32 -PassThru
[Int32]$exitCode = 0
$type::GetExitCodeProcess($process.Handle, [ref]$exitCode)
By using this code, you can still let PowerShell take care of managing redirected output/error streams, which you cannot do using System.Diagnostics.Process.Start() directly.
Try using MAX
with a GROUP BY
.
SELECT u.userName, MAX(c.carPrice)
FROM users u
LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;
GROUP BY
The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.
For example, if we have a set of records representing temperatures over time and location in a table like this:
Location Time Temperature
-------- ---- -----------
London 12:00 10.0
Bristol 12:00 12.0
Glasgow 12:00 5.0
London 13:00 14.0
Bristol 13:00 13.0
Glasgow 13:00 7.0
...
Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:
SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;
I'm late, but:
BufferReader.java:
public BufferedReader(Reader in) {
this(in, defaultCharBufferSize);
}
(...)
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();
} finally {
in = null;
cb = null;
}
}
}
Try this :
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
<style type="text/css">
#btn_s{
width:100px;
}
#btn_i {
width:125px;
}
#formbox {
width:400px;
margin:auto 0;
text-align: center;
}
</style>
</head>
<body>
<form method="post" action="">
<div id="formbox">
<input value="Search" title="Search" type="submit" id="btn_s">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
</div>
</form>
</body>
This has 2 examples, you can use the one that fits best in your situation.
text-align:center
on the parent container, or create a container for this.auto
left and right margins to center it in the parent container.note that auto
is used with single blocks to center them in the parent space by distrubuting the empty space to the left and right.
Not smarter but simpler:
select info->>'name' from rabbits WHERE info->>'food' LIKE '%"carrots"%';
this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>
using namespace std;
template <typename T, typename U>
struct CompareByGetter {
U (T::*getter)() const;
CompareByGetter(U (T::*getter)() const) : getter(getter) {};
bool operator()(const T &lhs, const T &rhs) {
(lhs.*getter)() < (rhs.*getter)();
}
};
template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
return CompareByGetter<T,U>(getter);
}
//// sort_by
template <typename T, typename U>
struct CompareByMember {
U T::*field;
CompareByMember(U T::*f) : field(f) {}
bool operator()(const T &lhs, const T &rhs) {
return lhs.*field < rhs.*field;
}
};
template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
return CompareByMember<T,U>(f);
}
template <typename T, typename U>
struct CompareByFunction {
function<U(T)> f;
CompareByFunction(function<U(T)> f) : f(f) {}
bool operator()(const T& a, const T& b) const {
return f(a) < f(b);
}
};
template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
CompareByFunction<T,U> cmp{f};
return cmp;
}
struct mystruct {
double x,y,z;
string name;
double length() const {
return sqrt( x*x + y*y + z*z );
}
};
ostream& operator<< (ostream& os, const mystruct& ms) {
return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}
template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
os << "[";
for (auto it = begin(v); it != end(v); ++it) {
if ( it != begin(v) ) {
os << " ";
}
os << *it;
}
os << "]";
return os;
}
void sorting() {
vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };
function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};
cout << "unsorted " << vec1 << endl;
sort(begin(vec1), end(vec1), by(&mystruct::x) );
cout << "sort_by x " << vec1 << endl;
sort(begin(vec1), end(vec1), by(&mystruct::length));
cout << "sort_by len " << vec1 << endl;
sort(begin(vec1), end(vec1), by(f) );
cout << "sort_by name " << vec1 << endl;
}
def x(a):
print(a)
return a
def y(func_to_run, a):
return func_to_run(a)
y(x, 1)
That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.
C language leaves compiler some freedom about the location of the structural elements in the memory:
The C language provides some assurance to the programmer of the elements layout in the structure:
Problems related to the elements alignment:
How alignment works:
p.s More detailed info are available here: "Samuel P.Harbison, Guy L.Steele C A Reference, (5.6.2 - 5.6.7)"
define() is part of the AMD spec of js
See:
Edit: Also see Claudio's answer below. Likely the more relevant explanation.
You could implement a ring buffer. Make an array of 1000 elements, and some fields to store the start and end indexes and total size. Then just store the last 1000 elements in the ring buffer, and recalculate the average as needed.
in handlebars first register a function like below
Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});
you can register more than one function . to add another function just add like below
Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
let result;
switch (operator) {
case '+':
result = operand1 + operand2;
break;
case '-':
result = operand1 - operand2;
break;
case '*':
result = operand1 * operand2;
break;
case '/':
result = operand1 / operand2;
break;
}
return Number(result);
});
and in HTML page just include the conditions like
{{#ifEquals day "mon"}}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
//html code goes here
</html>
{{else ifEquals day "sun"}}
<html>
//html code goes here
</html>
{{else}}
//html code goes here
{{/ifEquals}}
In our case, the Windows service account that SQL Server and SQL Agent were running under were locked out in Active Directory.
If you also need to retrieve the values for the keys you are removing, this would be a pretty good way to do it:
values_removed = [d.pop(k, None) for k in entities_to_remove]
You could of course still do this just for the removal of the keys from d
, but you would be unnecessarily creating the list of values with the list comprehension. It is also a little unclear to use a list comprehension just for the function's side effect.
Sorry for updating an old POST. I got the reported problem and I solved it as said below.
Assuming you are using Eclipse + m2e maven plugin, if you get this access restriction error, right click on the project/module in which you have the error --> Properties --> Build Path --> Library --> Replace JDK/JRE to the one that is used in eclipse workspace.
I followed the above steps and the issue is resolved.
There are five common ways by which a class data store data that cannot be modified outside the storing class' control:
Because strings are of variable length, they cannot be value-type primitives, nor can their character data be stored in a struct. Among the remaining choices, the only one which wouldn't require that strings' character data be stored in some kind of immutable object would be #5. While it would be possible to design a framework around option #5, that choice would require that any code which wanted a copy of a string that couldn't be changed outside its control would have to make a private copy for itself. While it hardly be impossible to do that, the amount of extra code required to do that, and the amount of extra run-time processing necessary to make defensive copies of everything, would far outweigh the slight benefits that could come from having string
be mutable, especially given that there is a mutable string type (System.Text.StringBuilder
) which accomplishes 99% of what could be accomplished with a mutable string
.
Here's an example of using text-overflow:
.text {_x000D_
display: block;_x000D_
width: 100px;_x000D_
overflow: hidden;_x000D_
white-space: nowrap;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<span class="text">Hello world this is a long sentence</span>
_x000D_
If you're serializing just because you have to serialize for the implementation's sake (who cares if you serialize for an HTTPSession
, for instance...if it's stored or not, you probably don't care about de-serializing
a form object), then you can ignore this.
If you're actually using serialization, it only matters if you plan on storing and retrieving objects using serialization directly. The serialVersionUID
represents your class version, and you should increment it if the current version of your class is not backwards compatible with its previous version.
Most of the time, you will probably not use serialization directly. If this is the case, generate a default SerialVersionUID
by clicking the quick fix option and don't worry about it.
Enter
git log .
from the specific directory, it also gives commits in that directory.
There are multiple schemas for "JUnit" and "xUnit" results.
model/xsd
)Please note that there are several versions of the schema in use by the Jenkins xunit-plugin (the current latest version is junit-10.xsd
which adds support for Erlang/OTP Junit format).
Some testing frameworks as well as "xUnit"-style reporting plugins also use their own secret sauce to generate "xUnit"-style reports, those may not use a particular schema (please read: they try to but the tools may not validate against any one schema). Python unittests in Jenkins? gives a quick comparison of several of these libraries and slight differences between the xml reports generated.
try this one.It may help you as its working for me.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
put the code in your root htaccess file.and make sure that you have
$config['index_page'] = '';
in your config file.
Please let me know if you face any problem.
I have used redux-form and formik in the past, and recently React introduced Hook, and i have built a custom hook for it. Please check it out and see if it make your form validation much easier.
Github: https://github.com/bluebill1049/react-hook-form
Website: http://react-hook-form.now.sh
with this approach, you are no longer doing controlled input too.
example below:
import React from 'react'
import useForm from 'react-hook-form'
function App() {
const { register, handleSubmit, errors } = useForm() // initialise the hook
const onSubmit = (data) => { console.log(data) } // callback when validation pass
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input name="firstname" ref={register} /> {/* register an input */}
<input name="lastname" ref={register({ required: true })} /> {/* apply required validation */}
{errors.lastname && 'Last name is required.'} {/* error message */}
<input name="age" ref={register({ pattern: /\d+/ })} /> {/* apply a Refex validation */}
{errors.age && 'Please enter number for age.'} {/* error message */}
<input type="submit" />
</form>
)
}
J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.
For Python version < 2.6, here's the best I can come up with:
from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()
Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:
from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))
UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:
from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()
dtList = dtList.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()
I assumed empty string and whitespace are like null. If not you can use IsNullOrEmpty
(allow whitespace), or s != null
If the scripts are loaded within the <head>
of the document, then it's possible use the defer
attribute in script tag.
Example:
<script src="demo_defer.js" defer></script>
From https://developer.mozilla.org:
defer
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed, but before firing DOMContentLoaded.
This attribute must not be used if the src attribute is absent (i.e. for inline scripts), in this case it would have no effect.
To achieve a similar effect for dynamically inserted scripts use async=false instead. Scripts with the defer attribute will execute in the order in which they appear in the document.
The solution given by @annoyingmouse works for me.
But to use the checkbox in the header cell, I also had to fix select.dataTables.css.
It seems that they used :
table.dataTable tbody th.select-checkbox
instead of :
table.dataTable thead th.select-checkbox
So I had to add this to my css :
table.dataTable thead th.select-checkbox {
position: relative;
}
table.dataTable thead th.select-checkbox:before,
table.dataTable thead th.select-checkbox:after {
display: block;
position: absolute;
top: 1.2em;
left: 50%;
width: 12px;
height: 12px;
box-sizing: border-box;
}
table.dataTable tbody td.select-checkbox:before,
table.dataTable thead th.select-checkbox:before {
content: ' ';
margin-top: -6px;
margin-left: -6px;
border: 1px solid black;
border-radius: 3px;
}
To start the process with parameters, you can use following code:
string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);
To kill/exit the program again, you can use following code:
proc.CloseMainWindow();
proc.Close();
You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list)
Using Collections.synchronizedList()
is superfluous in that case (it creates a wrapper that synchronizes individual operations).
However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.
Instead, simply call clear()
- no iteration needed.
Edit:
If you need the single-method synchronization of Collections.synchronizedList()
later on, then this is the correct way:
List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly,
But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList()
is just useless additional overhead.
My rule of thumb is:
&
)const
if it's an incoming parameter)const T&
).int ¤t = someArray[i]
)Regardless which one you use, don't forget to document your functions and the meaning of their parameters if they are not obvious.
Forcefully Change History
Assuming you don't just want to delete the last commit, but you want to delete specific commits of the last n commits, go with:
git rebase -i HEAD~<number of commits to go back>
, so git rebase -i HEAD~5
if you want to see the last five commits.
Then in the text editor change the word pick
to drop
next to every commit you would like to remove. Save and quit the editor. Voila!
Additively Change History
Try git revert <commit hash>
. Revert will create a new commit that undoes the specified commit.
I had this same problem, and after some searching around, I found Reggie (https://github.com/mbrevoort/node-reggie). It looks pretty solid. It allows for lightweight publishing of NPM modules to private servers. Not perfect (no authentication upon installation), and it's still really young, but I tested it locally, and it seems to do what it says it should do.
That is... (and this just from their docs)
npm install -g reggie
reggie-server -d ~/.reggie
then cd into your module directory and...
reggie -u http://<host:port> publish
reggie -u http://127.0.0.1:8080 publish
finally, you can install packages from reggie just by using that url either in a direct npm install command, or from within a package.json... like so
npm install http://<host:port>/package/<name>/<version>
npm install http://<host:port>/package/foo/1.0.0
or..
dependencies: {
"foo": "http://<host:port>/package/foo/1.0.0"
}
Just want to point out
Apart from MaxRecivedMessageSize, there are also attributes under ReaderQuotas, you might hit number of items limit instead of size limit. MSDN link is here
Try the Parse method.
You can also use the FileFilter
interface to filter out what you want. It is best used when you create an anonymous class that implements it:
import java.io.File;
import java.io.FileFilter;
public class ListFiles {
public File[] findDirectories(File root) {
return root.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory();
}});
}
public File[] findFiles(File root) {
return root.listFiles(new FileFilter() {
public boolean accept(File f) {
return f.isFile();
}});
}
}
The :not
pseudo-class is not supported by IE. I'd got for something like this instead:
.registration_form_right input[type="text"],
.registration_form_right input[type="password"],
.registration_form_right input[type="submit"],
.registration_form_right input[type="button"] {
...
}
Some duplication there, but it's a small price to pay for higher compatibility.
I wasn't able to make it work with $scope, so I tried with rootScope, maybe a bit more dirty... (especially if you make a refresh on the page that do not register the event)
But I really like the idea of how things are loosely coupled.
I'm using angularjs 1.6.9
index.run.js
angular
.module('myApp')
.run(runBlock);
function runBlock($rootScope, ...)
{
$rootScope.$on('title-updated', function(event, newTitle) {
$rootScope.pageTitle = 'MyApp | ' + newTitle;
});
}
anyController.controller.js
angular
.module('myApp')
.controller('MainController', MainController);
function MainController($rootScope, ...)
{
//simple way :
$rootScope.$emit('title-updated', 'my new title');
// with data from rest call
TroncQueteurResource.get({id:tronc_queteur_id}).$promise.then(function(tronc_queteur){
vm.current.tronc_queteur = tronc_queteur;
$rootScope.$emit('title-updated', moment().format('YYYY-MM-DD') + ' - Tronc '+vm.current.tronc_queteur.id+' - ' +
vm.current.tronc_queteur.point_quete.name + ' - '+
vm.current.tronc_queteur.queteur.first_name +' '+vm.current.tronc_queteur.queteur.last_name
);
});
....}
index.html
<!doctype html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<title ng-bind="pageTitle">My App</title>
It's working for me :)
In Python 2:
data = raw_input('Enter something: ')
print data
In Python 3:
data = input('Enter something: ')
print(data)