For those who are getting Error Unknown URI: content://downloads/public_downloads
.
I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub.
Here InputStream
methods are used to fetch file from Download
directory.
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
if (id != null && id.startsWith("raw:")) {
return id.substring(4);
}
String[] contentUriPrefixesToTry = new String[]{
"content://downloads/public_downloads",
"content://downloads/my_downloads",
"content://downloads/all_downloads"
};
for (String contentUriPrefix : contentUriPrefixesToTry) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
try {
String path = getDataColumn(context, contentUri, null, null);
if (path != null) {
return path;
}
} catch (Exception e) {}
}
// path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
String fileName = getFileName(context, uri);
File cacheDir = getDocumentCacheDir(context);
File file = generateFileName(fileName, cacheDir);
String destinationPath = null;
if (file != null) {
destinationPath = file.getAbsolutePath();
saveFileFromUri(context, uri, destinationPath);
}
return destinationPath;
}
I confronted similar issue when I wanted to post image file to a rest API from Python (Not wechat API though). The solution for me was to use 'data' parameter to post the file in binary data instead of 'files'. Requests API reference
data = open('your_image.png','rb').read()
r = requests.post(your_url,data=data)
Hope this works for your case.
Make sure you are connecting with a USB and not a lightning cable. I had this problem trying to connect using a cord with lightning cables on both ends and it would not list the device. But switching to a USB to lightning cable worked.
Just do it with a simple filestream.
var sr1 = new FileStream(FilePath, FileMode.Create);
sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
sr1.Close();
sr1.Dispose();
_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.
First, add the dependency of FFmpeg library
implementation 'com.writingminds:FFmpegAndroid:0.3.2'
Then load in activity
FFmpeg ffmpeg;
private void trimVideo(ProgressDialog progressDialog) {
outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
+ "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
+ "filter_apply.mp4";
if (startTrim.equals("")) {
startTrim = "00:00:00";
}
if (endTrim.equals("")) {
endTrim = timeTrim(player.getDuration());
}
String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};
execFFmpegBinary1(cmd, progressDialog);
}
private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {
ProgressDialog progressDialog = prpg;
try {
ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
@Override
public void onFailure(String s) {
progressDialog.dismiss();
Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
Log.d(TAG, "FAILED with output : " + s);
}
@Override
public void onSuccess(String s) {
Log.d(TAG, "SUCCESS wgith output : " + s);
// pathVideo = outputAudioMux;
String finalPath = outputAudioMux;
videoPath = outputAudioMux;
Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
intent.putExtra("pathGPU", finalPath);
startActivity(intent);
finish();
MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);
}
@Override
public void onProgress(String s) {
Log.d(TAG, "Started gcommand : ffmpeg " + command);
progressDialog.setMessage("Please Wait video triming...");
}
@Override
public void onStart() {
Log.d(TAG, "Startedf command : ffmpeg " + command);
}
@Override
public void onFinish() {
Log.d(TAG, "Finished f command : ffmpeg " + command);
progressDialog.dismiss();
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// do nothing for now
}
}
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onFailure() {
showUnsupportedExceptionDialog();
}
@Override
public void onSuccess() {
Log.d("dd", "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
showUnsupportedExceptionDialog();
} catch (Exception e) {
Log.d("dd", "EXception no controlada : " + e);
}
}
private void showUnsupportedExceptionDialog() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Not Supported")
.setMessage("Device Not Supported")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create()
.show();
}
public String timeTrim(long milliseconds) {
String finalTimerString = "";
String minutString = "";
String secondsString = "";
// Convert total duration into time
int hours = (int) (milliseconds / (1000 * 60 * 60));
int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
// Add hours if there
if (hours < 10) {
finalTimerString = "0" + hours + ":";
} else {
finalTimerString = hours + ":";
}
if (minutes < 10) {
minutString = "0" + minutes;
} else {
minutString = "" + minutes;
}
// Prepending 0 to seconds if it is one digit
if (seconds < 10) {
secondsString = "0" + seconds;
} else {
secondsString = "" + seconds;
}
finalTimerString = finalTimerString + minutString + ":" + secondsString;
// return timer string
return finalTimerString;
}
Also use another feature by FFmpeg
===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};
===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Flip horizontally :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};
===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};
===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};
===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
===> Add two mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
===> Add three mp3 files
StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(firstSngname);
sb.append(" -i ");
sb.append(textSngname);
sb.append(" -i ");
sb.append(mAudioFilename);
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
sb.append(finalfile);
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
As you say, ordinal is a bit risky. Consider for example:
public enum Boolean {
TRUE, FALSE
}
public class BooleanTest {
@Test
public void testEnum() {
assertEquals(0, Boolean.TRUE.ordinal());
assertEquals(1, Boolean.FALSE.ordinal());
}
}
If you stored this as ordinals, you might have rows like:
> SELECT STATEMENT, TRUTH FROM CALL_MY_BLUFF
"Alice is a boy" 1
"Graham is a boy" 0
But what happens if you updated Boolean?
public enum Boolean {
TRUE, FILE_NOT_FOUND, FALSE
}
This means all your lies will become misinterpreted as 'file-not-found'
Better to just use a string representation
Even if an object has no unmanaged resources, disposing might help GC by breaking object graphs. In general, if an object implements IDisposable, Dispose() should be called.
Whether Dispose() actually does something or not depends on the given class. In case of DataSet, Dispose() implementation is inherited from MarshalByValueComponent. It removes itself from container and calls Disposed event. The source code is below (disassembled with .NET Reflector):
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (this)
{
if ((this.site != null) && (this.site.Container != null))
{
this.site.Container.Remove(this);
}
if (this.events != null)
{
EventHandler handler = (EventHandler) this.events[EventDisposed];
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
}
}
If you just want to show label below the marker, then you can extend google maps Marker to add a setter method for label and you can define the label object by extending google maps overlayView like this..
<script type="text/javascript">
var point = { lat: 22.5667, lng: 88.3667 };
var markerSize = { x: 22, y: 40 };
google.maps.Marker.prototype.setLabel = function(label){
this.label = new MarkerLabel({
map: this.map,
marker: this,
text: label
});
this.label.bindTo('position', this, 'position');
};
var MarkerLabel = function(options) {
this.setValues(options);
this.span = document.createElement('span');
this.span.className = 'map-marker-label';
};
MarkerLabel.prototype = $.extend(new google.maps.OverlayView(), {
onAdd: function() {
this.getPanes().overlayImage.appendChild(this.span);
var self = this;
this.listeners = [
google.maps.event.addListener(this, 'position_changed', function() { self.draw(); })];
},
draw: function() {
var text = String(this.get('text'));
var position = this.getProjection().fromLatLngToDivPixel(this.get('position'));
this.span.innerHTML = text;
this.span.style.left = (position.x - (markerSize.x / 2)) - (text.length * 3) + 10 + 'px';
this.span.style.top = (position.y - markerSize.y + 40) + 'px';
}
});
function initialize(){
var myLatLng = new google.maps.LatLng(point.lat, point.lng);
var gmap = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var myMarker = new google.maps.Marker({
map: gmap,
position: myLatLng,
label: 'Hello World!',
draggable: true
});
}
</script>
<style>
.map-marker-label{
position: absolute;
color: blue;
font-size: 16px;
font-weight: bold;
}
</style>
This will work.
In order to run ssh-add
on Windows one could install git using choco install git
. The ssh-add
command is recognized once C:\Program Files\Git\usr\bin
has been added as a PATH variable and the command prompt has been restarted:
C:\Users\user\Desktop\repository>ssh-add .ssh/id_rsa
Enter passphrase for .ssh/id_rsa:
Identity added: .ssh/id_rsa (.ssh/id_rsa)
C:\Users\user\Desktop\repository>
SET SCAN OFF is obsolete http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a90842/apc.htm
I have came after another solution to this...here is the code
$('.selector').popover({
html: true,
trigger: 'manual',
container: $(this).attr('id'),
placement: 'top',
content: function () {
$return = '<div class="hover-hovercard"></div>';
}
}).on("mouseenter", function () {
var _this = this;
$(this).popover("show");
$(this).siblings(".popover").on("mouseleave", function () {
$(_this).popover('hide');
});
}).on("mouseleave", function () {
var _this = this;
setTimeout(function () {
if (!$(".popover:hover").length) {
$(_this).popover("hide")
}
}, 100);
});
This can also happen if you have a naming policy around version, prohibiting the version# you are trying to deploy. In my case I was trying to upload a version (to release repo) 2.0.1
but later found out that our nexus configuration doesn't allow anything other than whole number for releases.
I tried later with version 2
and deployed it successfully.
The error message definitely dosen't help:
Return code is: 400, ReasonPhrase: Repository does not allow updating assets: maven-releases-xxx. -> [Help 1]
A better message could have been version 2.0.1 violates naming policy
var startDate = new DateTime(2007, 3, 24);
var endDate = new DateTime(2009, 6, 26);
var dateDiff = endDate.Subtract(startDate);
var date = string.Format("{0} years {1} months {2} days", (int)dateDiff.TotalDays / 365,
(int)(dateDiff.TotalDays % 365) / 30, (int)(dateDiff.TotalDays % 365) / 30);
Console.WriteLine(date);
I suppose you cannot change the dao.find()
method to return an instance of Optional<Obj>
, so you have to create the appropriate one yourself.
The following code should help you out. I've create the class OptionalAction
,
which provides the if-else mechanism for you.
public class OptionalTest
{
public static Optional<DbObject> getObjectFromDb()
{
// doa.find()
DbObject v = find();
// create appropriate Optional
Optional<DbObject> object = Optional.ofNullable(v);
// @formatter:off
OptionalAction.
ifPresent(object)
.then(o -> o.setAvailable(true))
.elseDo(o -> System.out.println("Fatal! Object not available!"));
// @formatter:on
return object;
}
public static void main(String[] args)
{
Optional<DbObject> object = getObjectFromDb();
if (object.isPresent())
System.out.println(object.get());
else
System.out.println("There is no object!");
}
// find may return null
public static DbObject find()
{
return (Math.random() > 0.5) ? null : new DbObject();
}
static class DbObject
{
private boolean available = false;
public boolean isAvailable()
{
return available;
}
public void setAvailable(boolean available)
{
this.available = available;
}
@Override
public String toString()
{
return "DbObject [available=" + available + "]";
}
}
static class OptionalAction
{
public static <T> IfAction<T> ifPresent(Optional<T> optional)
{
return new IfAction<>(optional);
}
private static class IfAction<T>
{
private final Optional<T> optional;
public IfAction(Optional<T> optional)
{
this.optional = optional;
}
public ElseAction<T> then(Consumer<? super T> consumer)
{
if (optional.isPresent())
consumer.accept(optional.get());
return new ElseAction<>(optional);
}
}
private static class ElseAction<T>
{
private final Optional<T> optional;
public ElseAction(Optional<T> optional)
{
this.optional = optional;
}
public void elseDo(Consumer<? super T> consumer)
{
if (!optional.isPresent())
consumer.accept(null);
}
}
}
}
$date = strtotime("+1 day");
echo date('m-d-y',$date);
This will give you lines 1 to 20000
in newfile1.csv
and lines 20001 to the end
in file newfile2.csv
It overcomes the 8K character limit per line too.
This uses a helper batch file called findrepl.bat
from - https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat
Place findrepl.bat
in the same folder as the batch file or on the path.
It's more robust than a plain batch file, and quicker too.
findrepl /o:1:20000 <file.csv >newfile1.csv
findrepl /o:20001 <file.csv >newfile2.csv
Attaching a Simple Snippet for renaming your current branch (local and on origin):
git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>
Explanation from git docs:
git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.
The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.
--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.
I faced the same issue. In my case, part of my variables were in a dictionary i.e. with_dict variable (looping) and I had to run 3 commands on each item.key. This solution is more relevant where you have to use with_dict dictionary with running multiple commands (without requiring with_items)
Using with_dict and with_items in one task didn't help as it was not resolving the variables.
My task was like:
- name: Make install git source
command: "{{ item }}"
with_items:
- cd {{ tools_dir }}/{{ item.value.artifact_dir }}
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} all
- make prefix={{ tools_dir }}/{{ item.value.artifact_dir }} install
with_dict: "{{ git_versions }}"
roles/git/defaults/main.yml was:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
The above resulted in an error similar to the following for each {{ item }} (for 3 commands as mentioned above). As you see, the values of tools_dir is not populated (tools_dir is a variable which is defined in a common role's defaults/main.yml and also item.value.git_tar_dir value was not populated/resolved).
failed: [server01.poc.jenkins] => (item=cd {# tools_dir #}/{# item.value.git_tar_dir #}) => {"cmd": "cd '{#' tools_dir '#}/{#' item.value.git_tar_dir '#}'", "failed": true, "item": "cd {# tools_dir #}/{# item.value.git_tar_dir #}", "rc": 2}
msg: [Errno 2] No such file or directory
Solution was easy. Instead of using "COMMAND" module in Ansible, I used "Shell" module and created a a variable in roles/git/defaults/main.yml
So, now roles/git/defaults/main.yml looks like:
---
tool: git
default_git: git_2_6_3
git_versions:
git_2_6_3:
git_tar_name: git-2.6.3.tar.gz
git_tar_dir: git-2.6.3
git_tar_url: https://www.kernel.org/pub/software/scm/git/git-2.6.3.tar.gz
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} all && make prefix={{ tools_dir }}/{{ item.value.git_tar_dir }} install"
#or use this if you want git installation to work in ~/tools/git-x.x.x
git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make prefix=`pwd` all && make prefix=`pwd` install"
#or use this if you want git installation to use the default prefix during make
#git_pre_requisites_install_cmds: "cd {{ tools_dir }}/{{ item.value.git_tar_dir }} && make all && make install"
and the task roles/git/tasks/main.yml looks like:
- name: Make install from git source
shell: "{{ git_pre_requisites_install_cmds }}"
become_user: "{{ build_user }}"
with_dict: "{{ git_versions }}"
tags:
- koba
This time, the values got successfully substituted as the module was "SHELL" and ansible output echoed the correct values. This didn't require with_items: loop.
"cmd": "cd ~/tools/git-2.6.3 && make prefix=/home/giga/tools/git-2.6.3 all && make prefix=/home/giga/tools/git-2.6.3 install",
First thing Correctly specify all settings in the .ENV file for Mail.
I LOST 6 HOURS FOR THIS
Example
MAIL_DRIVER=smtp
MAIL_MAILER=smtp
MAIL_HOST=smtp.yandex.ru
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=password //Create password for Apps in settings. NOT PASTE YOUR REAL MAIL PASSWORD
MAIL_ENCRYPTION=SSL
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
creating local.properties
file in the root directory solved my issue
I somehow lost this file after pulling from GitHub
this is how my local.properties
file looks like now:
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Sat Feb 06 11:53:03 EST 2016
sdk.dir=/Users/****/Library/Android/sdk
Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.
The following is from the Secure Coding Guidelines 2.0.
Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).
With some HTML changes, you can absolutely achieve this with CSS:
Lorem ipsum dolor sit amet
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
list, for ease of selecting with CSS -->
<ul class="controls">
<li class="show"><a href="#textarea">Show</a></li>
<li class="hide"><a href="#">Hide</a></li>
</ul>
<p>Here is some more text</p>
Coupled with the CSS:
#textarea {
display: none; /* hidden by default */
}
#textarea:target {
display: block; /* shown when a link targeting this id is clicked */
}
#textarea + ul.controls {
list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}
/* hiding the hide link when the #textarea is not targeted,
hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
display: none;
}
/* Showing the hide link when the #textarea is targeted,
showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
display: inline-block;
}
Or, you could use a label
and an input
of type="checkbox"
:
Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>
<p>Here is some more text</p>
With the CSS:
#textarea {
/* hide by default: */
display: none;
}
/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
display: block;
}
/* position the checkbox off-screen: */
input[type="checkbox"] {
position: absolute;
left: -1000px;
}
/* Aesthetics only, adjust to taste: */
label {
display: block;
}
/* when the checkbox is unchecked (its default state) show the text
'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
content: 'Show ';
}
/* when the checkbox is checked 'Hide ' in the label element; the
general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
content: 'Hide ';
}
find /path/to/ \( -iname '*.gif' -o -iname '*.jpg' \) -print0
will work. There might be a more elegant way.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
FWIW, I got this error when I was implementing core data in to an existing project. It turned out I forgot to link CoreData.h to my project. I had already added the CoreData framework to my project but solved the issue by linking to the framework in my pre-compiled header just like Apple's templates do:
#import <Availability.h>
#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
#endif
I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\
) character:
Hello
\
\
\
World!
This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:
World!
Personally I find this cleaner for a large number of line breaks compared to using <br>
.
Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.
I would suggest a much more simple solution. Just use Certifire.
Certifire is a macOS application that generates Apple Push Notification Certificates with just one click in a couple of seconds.
Here are the steps:
1. Download the app.
2. Log in using your Apple Developer Account credentials.
3. Choose the App-ID
4. Click "Generate" button
5. You're done!
You will get APN certificates in .pem format as well as in .p12 format.
Even more, you will get also combined .pem and .p12 too (key+cert)!
Much more, you will get no-passphrase versions of all these certificates also!
Arrays.sort(arr);
int max=0,mode=0,count=0;
for(int i=0;i<N;i=i+count) {
count = 1;
for(int j=i+1; j<N; j++) {
if(arr[i] == arr[j])
count++;
}
if(count>max) {
max=count;
mode = arr[i];
}
}
Seeing that:
Set the date to highlight on first opening if the field is blank. Specify either an actual date via a Date object or as a string in the current dateFormat, or a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null for today.
If the current dateFormat is not recognized, you can still use the Date object using new Date(year, month, day)
In your example, this should work (I didn't test it) :
<script type="text/javascript">
$(function() {
$("#birthdate" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1920:2010',
dateFormat : 'dd-mm-yy',
defaultDate: new Date(1985,01,01)
});
});
</script>
The best approach you can use, is to resize the main view, specially if your application uses a footer.
on MainViewController.m using the viewDidLoad method, after [super viewDidLoad];
NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[vComp objectAtIndex:0] intValue] >= 7) {
// iOS 7 or above
CGRect oldBounds = [self.view bounds];
CGRect newViewBounds = CGRectMake( 0, -10, oldBounds.size.width, oldBounds.size.height-20 );
CGRect newWebViewBounds = CGRectMake( 0, -20, oldBounds.size.width, oldBounds.size.height-40 );
[self.view setBounds:newViewBounds];
[self.webView setBounds:newWebViewBounds];
}
then you won't need to modify any javascript into your application
You can use
for i in $(seq $END); do echo $i; done
In Typescript you need to set types of HTMLAttributes
and React.FunctionComponent
.
In most cases you will need will be extending it to another interface or type.
const List: React.FunctionComponent<ListProps &
React.HTMLAttributes<HTMLDivElement>> = (
props: ListProps & React.HTMLAttributes<HTMLDivElement>
) => {
return (
<div className={props.className}>
<img className="mr-3" src={props.icon} alt="" />
{props.context}
</div>
);
};
interface ListProps {
context: string;
icon: string;
}
All the above-mentioned code did not work for me. When I dig into the problem I realize that it was not working because I'd placed the style after the href. When I placed the style before the href it was working as expected.
<a style="text-decoration:none" href="http://yoursite.com/">yoursite</a>
However, avpicture_get_size is defined.
No, as the header (<libavcodec/avcodec.h>
) just declares it.
The definition is in the library itself.
So you might like to add the linker option to link libavcodec
when invoking gcc:
-lavcodec
Please also note that libraries need to be specified on the command line after the files needing them:
gcc -I$HOME/ffmpeg/include program.c -lavcodec
Not like this:
gcc -lavcodec -I$HOME/ffmpeg/include program.c
Referring to Wyzard's comment, the complete command might look like this:
gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec
For libraries not stored in the linkers standard location the option -L
specifies an additional search path to lookup libraries specified using the -l
option, that is libavcodec.x.y.z
in this case.
For a detailed reference on GCC's linker option, please read here.
If you want to take a component class as a parameter (vs an instance), use React.ComponentClass
:
function renderGreeting(Elem: React.ComponentClass<any>) {
return <span>Hello, <Elem />!</span>;
}
Solution:
Step1: Uncomment the php_curl.dll from php.ini
Step2: Copy the following three files from php installed directory.i.e "C:\\php7".
libeay32.dll,
libssh2.dll,
ssleay32.dll
Step3: Paste the files under two place
httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"
Step4: Restart apache.
That's all. I solve the problem by this way.Hope it might work for you.
The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html
Mutex are used for " Locking Mechanisms ". one process at a time can use a shared resource
whereas
Semaphores are used for " Signaling Mechanisms " like "I am done , now can continue"
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.
You could build it like this:
<?php
Schema::create('feeds', function($table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->morphs('target');
});
Build the feed model like so:
<?php
class Feed extends Eloquent
{
protected $fillable = ['user_id', 'target_type', 'target_id'];
public function user()
{
return $this->belongsTo('User');
}
public function target()
{
return $this->morphTo();
}
}
Then keep it up to date with something like:
<?php
Vote::created(function(Vote $vote) {
$target_type = 'Vote';
$target_id = $vote->id;
$user_id = $vote->user_id;
Feed::create(compact('target_type', 'target_id', 'user_id'));
});
You could make the above much more generic/robust—this is just for demonstration purposes.
At this point, your feed items are really easy to retrieve all at once:
<?php
Feed::whereIn('user_id', $my_friend_ids)
->with('user', 'target')
->orderBy('created_at', 'desc')
->get();
The problem is that the ?:
operator cannot determine the return type because you are either returning an int
value or a DBNull type value, which are not compatible.
You can of course cast the instance of AgeIndex to be type object
which would satisfy the ?:
requirement.
You can use the ??
null-coalescing operator as follows
SqlParameter[] parameters = new SqlParameter[1];
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (object)AgeItem.AgeIndex ?? DBNull.Value;
parameters[0] = planIndexParameter;
Here is a quote from the MSDN documentation for the ?:
operator that explains the problem
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
1-Delete the migration file. 2-connect to your database and drop the table created by the migration. 3-recreate the file of the migration with the the right sql.
The SGI STL has an extension called select1st
. Too bad it's not in standard STL!
Run this command in your terminal:
$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$
This simple command works like a charm:
git name-rev <SHA>
For example (where test-branch is the branch name):
git name-rev 651ad3a
251ad3a remotes/origin/test-branch
Even this is working for complex scenarios, like:
origin/branchA/
/branchB
/commit<SHA1>
/commit<SHA2>
Here git name-rev commit<SHA2>
returns branchB.
Try this:
Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row
Range("A2:L" & Lastrow).Select
Let's pretend that the value of Lastrow
is 50. When you use the following:
Range("A2:L2" & Lastrow).Select
Then it is selecting a range from A2 to L250.
I had the same problem, and my solution was to eliminate the line
android:screenOrientation="portrait"
and then add this in the activity:
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
Now that the Android 5.0 docs are available, we have the official documentation for the Toolbar widget:
A standard toolbar for use within application content.
A Toolbar is a generalization of action bars for use within application layouts. While an action bar is traditionally part of an Activity's opaque window decor controlled by the framework, a Toolbar may be placed at any arbitrary level of nesting within a view hierarchy.
A Toolbar
widget can also be used to replace the action bar:
An application may choose to designate a Toolbar as the action bar for an Activity using the
setActionBar()
method.
The deprecation of tabs in the action bar is most probably due to this, since toolbars cannot contain tab themselves.
Also, it's available for previous Android verions via the appcompat library. See this post by Chris Banes for more information. An excerpt:
Android 5.0 introduces a new Toolbar widget. This is a generalization of the ActionBar pattern but gives you much more control and flexibility in using it. Toolbar is a view in your hierarchy just like any other, making it easier to interleave with the rest of your views, animate, react to scroll events.
try
.insertAfter()
here
$(content).insertAfter('#bla');
var myVar = $("#start").find('.myClass').first().val();
class="mb-0"
m - sets margin
b - sets bottom margin or padding
0 - sets 0 margin or padding
CSS class
.mb-0{
margin-bottom: 0
}
Point to your mongodb instalation e.g C:\Program Files\MongoDB\Serve\bin and run mongod.exe so you can open connection to 127.0.0.1:27017.
getimagesize('image.jpg')
function works only if allow_url_fopen
is set to 1 or On inside php.ini file on the server,
if it is not enabled, one should use
ini_set('allow_url_fopen',1);
on top of the file where getimagesize() function is used.
Best way is
Add permission manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then you can get GPS location or if GPS location is not available then this function return NETWORK location
public static Location getLocationWithCheckNetworkAndGPS(Context mContext) {
LocationManager lm = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
assert lm != null;
isGpsEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkLocationEnabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Location networkLoacation = null, gpsLocation = null, finalLoc = null;
if (isGpsEnabled)
if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return null;
}gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkLocationEnabled)
networkLoacation = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gpsLocation != null && networkLoacation != null) {
//smaller the number more accurate result will
if (gpsLocation.getAccuracy() > networkLoacation.getAccuracy())
return finalLoc = networkLoacation;
else
return finalLoc = gpsLocation;
} else {
if (gpsLocation != null) {
return finalLoc = gpsLocation;
} else if (networkLoacation != null) {
return finalLoc = networkLoacation;
}
}
return finalLoc;
}
You need to tell the Range.RemoveDuplicates method what column to use. Additionally, since you have expressed that you have a header row, you should tell the .RemoveDuplicates method that.
Sub dedupe_abcd()
Dim icol As Long
With Sheets("Sheet1") '<-set this worksheet reference properly!
icol = Application.Match("abcd", .Rows(1), 0)
With .Cells(1, 1).CurrentRegion
.RemoveDuplicates Columns:=icol, Header:=xlYes
End With
End With
End Sub
Your original code seemed to want to remove duplicates from a single column while ignoring surrounding data. That scenario is atypical and I've included the surrounding data so that the .RemoveDuplicates process does not scramble your data. Post back a comment if you truly wanted to isolate the RemoveDuplicates process to a single column.
1)
$stateProvider
.state('app.example1', {
url: '/example',
views: {
'menuContent': {
templateUrl: 'templates/example.html',
controller: 'ExampleCtrl'
}
}
})
.state('app.example2', {
url: '/example2/:object',
views: {
'menuContent': {
templateUrl: 'templates/example2.html',
controller: 'Example2Ctrl'
}
}
})
2)
.controller('ExampleCtrl', function ($state, $scope, UserService) {
$scope.goExample2 = function (obj) {
$state.go("app.example2", {object: JSON.stringify(obj)});
}
})
.controller('Example2Ctrl', function ($state, $scope, $stateParams) {
console.log(JSON.parse($state.params.object));
})
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
background: <background-color>
url('../assets/icons/my-icon.svg')
<background-position-x background-position-y>
<background-repeat>;
It allows you combining background-color
, background-image
, background-position
and background-repeat
properties.
background: #696969 url('../assets/icons/my-icon.svg') center center no-repeat;
Well, I do my coding in NetBeans 8.1:
First: Create a new project, select Java application and name your project.
Then modify your code after public class to look like the following:
/**
* @param args the command line arguments
* @throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws FileNotFoundException {
try (Scanner scanner = new Scanner(new File("C:\\Users\\YourName\\Folder\\file.csv"))) {
scanner.useDelimiter(",");
while(scanner.hasNext()){
System.out.print(scanner.next()+"|");
}}
}
}
Or you can use std::advance
vector<int>::iterator i = L.begin();
advance(i, 2);
The most votes answer works fine except the 1st week and last week of year. When datecol value is '2009-01-01', the result will be 01/03/2009 and 12/28/2008.
My solution:
DECLARE @Date date = '2009-03-01', @WeekNum int, @StartDate date;
SELECT @WeekNum = DATEPART(WEEK, @Date);
SELECT @StartDate = DATEADD(DAY, -(DATEPART(WEEKDAY, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0)) + 6), DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0));
SELECT CONVERT(nvarchar, CASE WHEN @WeekNum = 1 THEN CAST(DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date), 0) AS date) ELSE DATEADD(DAY, 7 * @WeekNum, @StartDate) END, 101) AS StartOfWeek
,CONVERT(nvarchar, CASE WHEN @WeekNum = DATEPART(WEEK, DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0))) THEN DATEADD(DAY, -1, DATEADD(YEAR, DATEDIFF(YEAR, 0, @Date) + 1, 0)) ELSE DATEADD(DAY, 7 * @WeekNum + 6, @StartDate) END, 101) AS EndOfWeek;
This will display 01/01/2009 and 01/03/2009 for the 1st week, and display 03/01/2009 and 03/07/2009 for the 10th week.
I think this would be what you want exactly. You can replace the variables with their expressions as you wish.
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
data = sc.textFile('path_to_data')
header = data.first() #extract header
data = data.filter(row => row != header) #filter out header
How about this:
import unicodedata
def strip_accents(s):
return ''.join(c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) != 'Mn')
This works on greek letters, too:
>>> strip_accents(u"A \u00c0 \u0394 \u038E")
u'A A \u0394 \u03a5'
>>>
The character category "Mn" stands for Nonspacing_Mark
, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).
And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".
If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.
I had to upgrade my version of Cordova to support the latest version of Gradle. Updating the distributionUrl in GradleBuilder.js didn't work for me.
To print address in pointer to pointer:
printf("%p",emp1)
to dereference once and print the second address:
printf("%p",*emp1)
You can always verify with debugger, if you are on linux use ddd
and display memory, or just plain gdb
, you will see the memory address so you can compare with the values in your pointers.
InstallUtil classes ( ServiceInstaller ) are considered an anti-pattern by the Windows Installer community. It's a fragile, out of process, reinventing of the wheel that ignores the fact that Windows Installer has built-in support for Services.
Visual Studio deployment projects ( also not highly regarded and deprecated in the next release of Visual Studio ) do not have native support for services. But they can consume merge modules. So I would take a look at this blog article to understand how to create a merge module using Windows Installer XML that can express the service and then consume that merge module in your VDPROJ solution.
Augmenting InstallShield using Windows Installer XML - Windows Services
well first of all you need to install this packege below:
sudo apt install ipython
jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb
two option is avaliable either --to python or --to=python mine was like this works fine: jupyter nbconvert --to python while.ipynb
jupyter nbconvert --to python while.ipynb
[NbConvertApp] Converting notebook while.ipynb to python [NbConvertApp] Writing 758 bytes to while.py
pip3 install ipython
if it does not work for you try, by pip3.
pip3 install ipython
Yes, you can use jQuery to make this done, the idea is
Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.
<form name="input" action="handle_email.php" method="post">
<input type="hidden" name="email" id="email" />
<input type="submit" value="Submit" />
</form>
<script>
$("form").submit(function() {
var emailFromOtherTextBox = $("#email_textbox").val();
$("#email").val(emailFromOtherTextBox );
return true;
});
</script>
also see http://api.jquery.com/submit/
Problem for me was that I was running the jupyter
command from the wrong directory.
Once I navigated to the path containing the script, everything worked.
Path-
C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\Scripts
For a list X = ['a', 'b', 'c', 'd', 'e', 'f']
and a desired shift value of shift
less than list length, we can define the function list_shift()
as below
def list_shift(my_list, shift):
assert shift < len(my_list)
return my_list[shift:] + my_list[:shift]
Examples,
list_shift(X,1)
returns ['b', 'c', 'd', 'e', 'f', 'a']
list_shift(X,3)
returns ['d', 'e', 'f', 'a', 'b', 'c']
To expand on Konrad's comment:
As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined;
Because of this, functional code is generally easier to parallelize. Since there are (generally) no side effects of the functions, and they (generally) just act on their arguments, a lot of concurrency issues go away.
Functional programming is also used when you need to be capable of proving your code is correct. This is much harder to do with procedural programming (not easy with functional, but still easier).
Disclaimer: I haven't used functional programming in years, and only recently started looking at it again, so I might not be completely correct here. :)
If you are using an array (and purely an array), the lookup of "contains" is O(N)
, because worst case, you must iterate the entire array. Now if the array is sorted you can use a binary search, which reduces the search time to log(N)
with the overhead of the sort.
If this is something that is invoked repeatedly, place it in a function:
private boolean inArray(int[] array, int value)
{
for (int i = 0; i < array.length; i++)
{
if (array[i] == value)
{
return true;
}
}
return false;
}
Following Felix Klings advice I tried it out in my chrome browser.
console.dir([1,2])
gives the following output:
Array[2]
0: 1
1: 2
length: 2
__proto__: Array[0]
While console.log([1,2])
gives the following output:
[1, 2]
So I believe console.dir()
should be used to get more information like prototype etc in arrays and objects.
You can even set the prof. pic size to its high resolution that is '1080x1080'
replace "150x150" with 1080x1080 and remove /vp/ from the link.
I tried most of these answers and they were all failing for TextViews that had autolink enabled but also had to use long press in the same place!
I made a custom class that works.
public class TextViewLinkLongPressUrl extends TextView {
private boolean isLongClick = false;
public TextViewLinkLongPressUrl(Context context) {
super(context);
}
public TextViewLinkLongPressUrl(Context context, AttributeSet attrs) {
super(context, attrs);
}
public TextViewLinkLongPressUrl(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setText(CharSequence text, BufferType type) {
super.setText(text, type);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP && isLongClick) {
isLongClick = false;
return false;
}
if (event.getAction() == MotionEvent.ACTION_UP) {
isLongClick = false;
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isLongClick = false;
}
return super.onTouchEvent(event);
}
@Override
public boolean performLongClick() {
isLongClick = true;
return super.performLongClick();
}
}
Since Java 8, you can do that in three lines:
try (Stream<Path> files = Files.list(Paths.get("your/path/here"))) {
long count = files.count();
}
Regarding the 5000 child nodes and inode aspects:
This method will iterate over the entries but as Varkhan suggested you probably can't do better besides playing with JNI or direct system commands calls, but even then, you can never be sure these methods don't do the same thing!
However, let's dig into this a little:
Looking at JDK8 source, Files.list
exposes a stream that uses an Iterable
from Files.newDirectoryStream
that delegates to FileSystemProvider.newDirectoryStream
.
On UNIX systems (decompiled sun.nio.fs.UnixFileSystemProvider.class
), it loads an iterator: A sun.nio.fs.UnixSecureDirectoryStream
is used (with file locks while iterating through the directory).
So, there is an iterator that will loop through the entries here.
Now, let's look to the counting mechanism.
The actual count is performed by the count/sum reducing API exposed by Java 8 streams. In theory, this API can perform parallel operations without much effort (with multihtreading). However the stream is created with parallelism disabled so it's a no go...
The good side of this approach is that it won't load the array in memory as the entries will be counted by an iterator as they are read by the underlying (Filesystem) API.
Finally, for the information, conceptually in a filesystem, a directory node is not required to hold the number of the files that it contains, it can just contain the list of it's child nodes (list of inodes). I'm not an expert on filesystems, but I believe that UNIX filesystems work just like that. So you can't assume there is a way to have this information directly (i.e: there can always be some list of child nodes hidden somewhere).
I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list)
for strings. For non-strings (such as an array of ints) this may be better:
" ".join(str(item) for item in my_list)
The 2nd option is the one you want.
In your web.config
, make sure these keys exist:
<configuration>
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
</configuration>
ElektroStudios answer is a bit misleading.
"when you launch a bat file the working dir is the dir where it was launched" This is true if the user clicks on the batch file in the explorer.
However, if the script is called from another script using the CALL command, the current working directory does not change.
Thus, inside your script, it is better to use %~dp0subfolder\file1.txt
Please also note that %~dp0 will end with a backslash when the current script is not in the current working directory. Thus, if you need the directory name without a trailing backslash, you could use something like
call :GET_THIS_DIR
echo I am here: %THIS_DIR%
goto :EOF
:GET_THIS_DIR
pushd %~dp0
set THIS_DIR=%CD%
popd
goto :EOF
I wouldn't put it in the same <p>
, since IMHO the two infos are semantically too different. If you must, I'd suggest this:
<p style="text-align:right">
<span style="float:left">I'll be on the left</span>
I'll be on the right
</p>
Basically the difference between them are performance characteristics and blocking behavior.
Taking the easiest first, ArrayBlockingQueue
is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.
The most important difference between LinkedBlockingQueue
and ConcurrentLinkedQueue
is that if you request an element from a LinkedBlockingQueue
and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue
will return right away with the behavior of an empty queue.
Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.
Here's a sample template to help you get started
Requires 0 libraries and uses only javascript to inject both HTML and CSS.
The function was borrowed from the user @Husky above
Useful if you want to run a tampermonkey script and wanted to add a toggle overlay on a website (e.g. a note app for instance)
// INJECTING THE HTML_x000D_
document.querySelector('body').innerHTML += '<div id="injection">Hello World</div>';_x000D_
_x000D_
// CSS INJECTION FUNCTION_x000D_
//https://stackoverflow.com/questions/707565/how-do-you-add-css-with-javascript_x000D_
function insertCss( code ) {_x000D_
var style = document.createElement('style');_x000D_
style.type = 'text/css';_x000D_
if (style.styleSheet) {_x000D_
// IE_x000D_
style.styleSheet.cssText = code;_x000D_
} else {_x000D_
// Other browsers_x000D_
style.innerHTML = code;_x000D_
}_x000D_
document.getElementsByTagName("head")[0].appendChild( style );_x000D_
}_x000D_
_x000D_
// INJECT THE CSS INTO FUNCTION_x000D_
// Write the css as you normally would... but treat it as strings and concatenate for multilines_x000D_
insertCss(_x000D_
"#injection {color :red; font-size: 30px;}" +_x000D_
"body {background-color: lightblue;}"_x000D_
)
_x000D_
$("#"+document.getElementById("<%= ButtonID.ClientID %>")).trigger("click");
Here's a different approach. The heart of it was created by turning on the Macro Recorder and filtering the columns per your specifications. Then there's a bit of code to copy the results. It will run faster than looping through each row and column:
Sub FilterAndCopy()
Dim LastRow As Long
Sheets("Sheet2").UsedRange.Offset(0).ClearContents
With Worksheets("Sheet1")
.Range("$A:$E").AutoFilter
.Range("$A:$E").AutoFilter field:=1, Criteria1:="#N/A"
.Range("$A:$E").AutoFilter field:=2, Criteria1:="=String1", Operator:=xlOr, Criteria2:="=string2"
.Range("$A:$E").AutoFilter field:=3, Criteria1:=">0"
.Range("$A:$E").AutoFilter field:=5, Criteria1:="Number"
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible).EntireRow.Copy _
Destination:=Sheets("Sheet2").Range("A1")
End With
End Sub
As a side note, your code has more loops and counter variables than necessary. You wouldn't need to loop through the columns, just through the rows. You'd then check the various cells of interest in that row, much like you did.
I got the same problem! then realized that my directory was not empty. I found the solution in another thread: not able to delete the directory through Java
/**
* Force deletion of directory
* @param path
* @return
*/
static public boolean deleteDirectory(File path) {
if (path.exists()) {
File[] files = path.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return (path.delete());
}
Put for div same name as in href target.
ex: <div name="link">
and <a href="#link">
I would recommend doing it like this to keep things in line with HTML5.
<meta charset="UTF-8">
EG:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.
For example, linux systems generally have a useradd
command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl
(which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser
instead.)
Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed
, which uses the -r
option to invoke extended regular expressions; on OS X, you'd use the -E
option to get the same effect. Similarly, in linux you might use ls --color=auto
to get colorized output; on macOS, the closest equivalent is ls -G
.
EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l
), while most OS X commands require options to come strictly first (ls -l file1 file2
).
Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig
to change your network configuration. On OS X, ifconfig
will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup
, and then let the config daemon apply them to the live network state.
Your Application.java
class should extend the SpringBootServletInitializer
class
ex:
public class Application extends SpringBootServletInitializer {}
If you are using the actuator module, you can shutdown the application via JMX
or HTTP
if the endpoint is enabled.
add to application.properties
:
endpoints.shutdown.enabled=true
Following URL will be available:
/actuator/shutdown
- Allows the application to be gracefully shutdown (not enabled by default).
Depending on how an endpoint is exposed, the sensitive parameter may be used as a security hint.
For example, sensitive endpoints will require a username/password when they are accessed over HTTP
(or simply disabled if web security is not enabled).
From the Spring boot documentation
You can actualy fake the transparency of option
DOMElements with the following CSS:
option {
/* Whatever color you want */
background-color: #82caff;
}
The option
tag does not support rgba
colors yet.
The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.
If you do not like assets folder you can edit .angular-cli.json
and add other folders you need.
"assets": [
"assets",
"img",
"favicon.ico"
]
If input stream is not closed properly then this exception may happen. make sure : If inputstream used is not used "Before" in some way then where you are intended to read. i.e if read 2nd time from same input stream in single operation then 2nd call will get this exception. Also make sure to close input stream in finally block or something like that.
The scope of a variable is always the block it is inside. For example if you do something like
if(...)
{
int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
int y = 8; //y is created
} //y leaves scope, since the block ends.
cout << y << endl; //Gives error since y is not defined.
The solution is to define y outside of the if blocks
int y; //y is created
if(...)
{
y = 5;
}
else
{
y = 8;
}
cout << y << endl; //Ok
In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:
//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
int y, c;
int d=date;
if (month==1||month==2)
{
y=((year-1)%100);
c=(year-1)/100;
}
else
{
y=year%100;
c=year/100;
}
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}
they're listed in /proc/net/tcp.
it's the second column, after the ":", in hex:
> cat /proc/net/tcp
sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
0: 00000000:0016 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 10863 1 ffff88020c785400 99 0 0 10 -1
1: 0100007F:0277 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 7983 1 ffff88020eb7b3c0 99 0 0 10 -1
2: 0500010A:948F 0900010A:2328 01 00000000:00000000 02:00000576 00000000 1000 0 10562454 2 ffff88010040f7c0 22 3 30 5 3
3: 0500010A:E077 5F2F7D4A:0050 01 00000000:00000000 02:00000176 00000000 1000 0 10701021 2 ffff880100474080 41 3 22 10 -1
4: 0500010A:8773 16EC97D1:0050 01 00000000:00000000 02:00000BDC 00000000 1000 0 10700849 2 ffff880104335440 57 3 18 10 -1
5: 0500010A:8772 16EC97D1:0050 01 00000000:00000000 02:00000BF5 00000000 1000 0 10698952 2 ffff88010040e440 46 3 0 10 -1
6: 0500010A:DD2C 0900010A:0016 01 00000000:00000000 02:0006E764 00000000 1000 0 9562907 2 ffff880104334740 22 3 30 5 4
7: 0500010A:AAA4 6A717D4A:0050 08 00000000:00000001 02:00000929 00000000 1000 0 10696677 2 ffff880106cc77c0 45 3 0 10 -1
so i guess one of those :50
in the third column must be stackoverflow :o)
look in man 5 proc
for more details. and picking that apart with sed etc is left as an exercise for the gentle reader...
Is to do with IPv6
All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx
Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...
You can use two elements, one inside the other, and give the outer one overflow: hidden
and a width equal to the inner element together with a bottom padding so that the shadow on all the other sides are "cut off"
#outer {
width: 100px;
overflow: hidden;
padding-bottom: 10px;
}
#outer > div {
width: 100px;
height: 100px;
background: orange;
-moz-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
-webkit-box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
box-shadow: 0 4px 4px rgba(0, 0, 0, 0.4);
}
Alternatively, float the outer element to cause it to shrink to the size of the inner element. See: http://jsfiddle.net/QJPd5/1/
I needed to change the menu icon for the fragment. I altered Charles’s answer to this question a bit for the fragment:
private Menu top_menu;
//...
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
//...
rootview = inflater.inflate(R.layout.first_content,null);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_menu, menu);
this.top_menu = menu;
}
// my procedure
private void updateIconMenu() {
if(top_menu!= null) {
MenuItem nav_undo = top_menu.findItem(R.id.action_undo);
nav_undo.setIcon( R.drawable.back);
}
}
IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).
We are just completing a Memory Safety checking tool for Windows, that handles GCC and Micrsoft Visual C (not C++ yet), and are looking for Beta testers.
EDIT June 12, 2011: Not Beta anymore, now production for GCC and Microsoft Visual Studio C.
Alternatively, since pip
itself is written in python, you can just call it with the python version you want to install the package for:
python2.7 -m pip install foo
When you create your table, put your td with class = "suma"
$(function(){
//funcion suma todo
var sum = 0;
$('.suma').each(function(x,y){
sum += parseInt($(this).text());
})
$('#lblTotal').text(sum);
// funcion suma por check
$( "input:checkbox").change(function(){
if($(this).is(':checked')){
$(this).parent().parent().find('td:last').addClass('suma2');
}else{
$(this).parent().parent().find('td:last').removeClass('suma2');
}
suma2Total();
})
function suma2Total(){
var sum2 = 0;
$('.suma2').each(function(x,y){
sum2 += parseInt($(this).text());
})
$('#lblTotal2').text(sum2);
}
});
$("element").data('bs.modal').isShown
won't work if the modal hasn't been shown before. You will need to add an extra condition:
$("element").data('bs.modal')
so the answer taking into account first appearance:
if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
...
}
It would help to have sample information about your output. Recursively using rbind
on bigger and bigger things is not recommended. My first guess at something that would help you:
z <- list(1:3,4:6,7:9)
do.call(rbind,z)
See a related question for more efficiency, if needed.
if cordova app copy a valid png file to
resources\android\icon.png
and then run
ionic resources --icon
This expression 12-4-2005
is a calculated int and the value is -1997
. You should do like this instead '2005-04-12'
with the '
before and after.
Here are two extension methods you can use. They ensure any existing classes are preserved and do not duplicate classes being added.
public static void RemoveCssClass(this WebControl control, String css) {
control.CssClass = String.Join(" ", control.CssClass.Split(' ').Where(x => x != css).ToArray());
}
public static void AddCssClass(this WebControl control, String css) {
control.RemoveCssClass(css);
css += " " + control.CssClass;
control.CssClass = css;
}
Usage: hlCreateNew.AddCssClass("disabled");
Usage: hlCreateNew.RemoveCssClass("disabled");
If you use the Angular CLI to create your components, let's say CarComponent
, it attaches app
to the selector name (i.e app-car
) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car>
or change the selector in the CarComponent
to selector: 'car'
As previously stated, it's not directly possible, but you can set up Apache or nginx + SSL on a EC2 instance, CNAME your desired domain to that, and reverse-proxy to the (non-custom domain) S3 URLs.
I go with the simple answer. Works for me.
long startTime = System.currentTimeMillis();
doReallyLongThing();
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.
Average across a couple of runs (the more the better) and you'll get a decent idea.
Saw your problems.
Solutions:
First Download Subversion 1.8.13 ( 1.8 ) client Download link (https://subversion.apache.org/packages.html) at the time of this post the android studio version is less than 1.4 in my case 1.3.2 so you must avoid the issues here subversion command line client version is too old so just download the 1.8 preferably.
Then unzipped in a folder. There will have one folder "bin".
Then
Go to settings - > Version control -> Subversion
Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.
follow the picture:
Don't forget to give the end name like svn.exe last as per image.
Apply -> Ok
Restart your android studio now.
Happy Coding!
SELECT * FROM SysColumns WHERE Name like 'a%'
Will get you a list of columns, you will want to filter more to restrict it to your target table
From there you can construct some ad-hoc sql
With dataclasses, a feature added in Python 3.7, there is now yet another (quite convenient) way to achieve setting default values on class instances. The decorator dataclass
will automatically generate a few methods on your class, such as the constructor. As the documentation linked above notes, "[t]he member variables to use in these generated methods are defined using PEP 526 type annotations".
Considering OP's example, we could implement it like this:
from dataclasses import dataclass
@dataclass
class Foo:
num: int = 0
When constructing an object of this class's type we could optionally overwrite the value.
print('Default val: {}'.format(Foo()))
# Default val: Foo(num=0)
print('Custom val: {}'.format(Foo(num=5)))
# Custom val: Foo(num=5)
This solved my problem:
sudo rm /usr/local/cuda/bin/gcc
sudo rm /usr/local/cuda/bin/g++
sudo apt install gcc-4.4 g++-4.4
sudo ln -s /usr/bin/gcc-4.4 /usr/local/cuda/bin/gcc
sudo ln -s /usr/bin/g++-4.4 /usr/local/cuda/bin/g++
String extends Object, which means an Object. Object o = a;
If you really want to get as Object, you may do like below.
String s = "Hi";
Object a =s;
I would tend to prefer using NULL for the clarity of what is required and what is optional. One word of warning about using default values that depend on other arguments, as suggested by Jthorpe. The value is not set when the function is called, but when the argument is first referenced! For instance:
foo <- function(x,y=length(x)){
x <- x[1:10]
print(y)
}
foo(1:20)
#[1] 10
On the other hand, if you reference y before changing x:
foo <- function(x,y=length(x)){
print(y)
x <- x[1:10]
}
foo(1:20)
#[1] 20
This is a bit dangerous, because it makes it hard to keep track of what "y" is being initialized as if it's not called early on in the function.
You forgot to specify the variable name. It should be CERas.CERAS newCeras = new CERas.CERAS();
I have constructed this JavaScript script to parse a CSV in string to array object. I find it better to break down the whole CSV into lines, fields and process them accordingly. I think that it will make it easy for you to change the code to suit your need.
//
//
// CSV to object
//
//
const new_line_char = '\n';
const field_separator_char = ',';
function parse_csv(csv_str) {
var result = [];
let line_end_index_moved = false;
let line_start_index = 0;
let line_end_index = 0;
let csr_index = 0;
let cursor_val = csv_str[csr_index];
let found_new_line_char = get_new_line_char(csv_str);
let in_quote = false;
// Handle \r\n
if (found_new_line_char == '\r\n') {
csv_str = csv_str.split(found_new_line_char).join(new_line_char);
}
// Handle the last character is not \n
if (csv_str[csv_str.length - 1] !== new_line_char) {
csv_str += new_line_char;
}
while (csr_index < csv_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === new_line_char) {
if (in_quote === false) {
if (line_end_index_moved && (line_start_index <= line_end_index)) {
result.push(parse_csv_line(csv_str.substring(line_start_index, line_end_index)));
line_start_index = csr_index + 1;
} // Else: just ignore line_end_index has not moved or line has not been sliced for parsing the line
} // Else: just ignore because we are in a quote
}
csr_index++;
cursor_val = csv_str[csr_index];
line_end_index = csr_index;
line_end_index_moved = true;
}
// Handle \r\n
if (found_new_line_char == '\r\n') {
let new_result = [];
let curr_row;
for (var i = 0; i < result.length; i++) {
curr_row = [];
for (var j = 0; j < result[i].length; j++) {
curr_row.push(result[i][j].split(new_line_char).join('\r\n'));
}
new_result.push(curr_row);
}
result = new_result;
}
return result;
}
function parse_csv_line(csv_line_str) {
var result = [];
//let field_end_index_moved = false;
let field_start_index = 0;
let field_end_index = 0;
let csr_index = 0;
let cursor_val = csv_line_str[csr_index];
let in_quote = false;
// Pretend that the last char is the separator_char to complete the loop
csv_line_str += field_separator_char;
while (csr_index < csv_line_str.length) {
if (cursor_val === '"') {
in_quote = !in_quote;
} else if (cursor_val === field_separator_char) {
if (in_quote === false) {
if (field_start_index <= field_end_index) {
result.push(parse_csv_field(csv_line_str.substring(field_start_index, field_end_index)));
field_start_index = csr_index + 1;
} // Else: just ignore field_end_index has not moved or field has not been sliced for parsing the field
} // Else: just ignore because we are in quote
}
csr_index++;
cursor_val = csv_line_str[csr_index];
field_end_index = csr_index;
field_end_index_moved = true;
}
return result;
}
function parse_csv_field(csv_field_str) {
with_quote = (csv_field_str[0] === '"');
if (with_quote) {
csv_field_str = csv_field_str.substring(1, csv_field_str.length - 1); // remove the start and end quotes
csv_field_str = csv_field_str.split('""').join('"'); // handle double quotes
}
return csv_field_str;
}
// Initial method: check the first newline character only
function get_new_line_char(csv_str) {
if (csv_str.indexOf('\r\n') > -1) {
return '\r\n';
} else {
return '\n'
}
}
Use of pointer before character array
Normally, Character array is used to store single elements in it i.e 1 byte each
eg:
char a[]={'a','b','c'};
we can't store multiple value in it.
by using pointer before the character array we can store the multi dimensional array elements in the array
i.e.
char *a[]={"one","two","three"};
printf("%s\n%s\n%s",a[0],a[1],a[2]);
I use an Android Studio plug-in called "adb idea" -- has a drop down menu for various functions (Uninstall, Kill, Start, etc) that you can target at any connected or simulated device. One could argue it takes me a step away from having a deeper understanding of the power of adb commands and I'd probably agree....though I'm really operating at a lower level of understanding anyway so for me it helps to have a helper. ADB Idea
I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes.
string Filename = "BinaryFile.bin";
FILE* pFile;
pFile = fopen(Filename.c_str(), "rb");
fseek(pFile, 0L, SEEK_END);
size_t size = ftell(pFile);
fseek(pFile, 0L, SEEK_SET);
uint8_t* ByteArray;
ByteArray = new uint8_t[size];
if (pFile != NULL)
{
int counter = 0;
do {
ByteArray[counter] = fgetc(pFile);
counter++;
} while (counter <= size);
fclose(pFile);
}
for (size_t i = 0; i < 800; i++) {
printf("%02X ", ByteArray[i]);
}
Use the following for multiple .cpp files
g++ *.cpp
./a.out
The setstate is asynchronous in react, so to see the updated state in console use the callback as shown below (Callback function will execute after the setstate update)
The below method is "not recommended" but for understanding, if you mutate state directly you can see the updated state in the next line. I repeat this is "not recommended"
dict((el,0) for el in a)
will work well.
Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}
.
Search "maven-jar-plugin" in pom.xml and add version tag maven version
Are you looking for something like this?
SELECT CASE WHEN LEFT(created_ts, 1) LIKE '[0-9]'
THEN CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 1), 101)
ELSE CONVERT(VARCHAR(10), CONVERT(datetime, created_ts, 109), 101)
END created_ts
FROM table1
Output:
| CREATED_TS | |------------| | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 02/20/2012 | | 11/29/2012 | | 11/16/2011 | | 02/20/2012 | | 11/29/2012 |
Here is SQLFiddle demo
I've had similar requirements as described in the question and it took a while to figure things out based on existing answers, so I would like to share my final solution.
Requirements
The state of my view (component, technically) can be changed by the user (filter settings, sorting options, etc.) When state changes happen, i.e. the user changes the sorting direction, I want to:
additionally, I would like to:
Solution: Change state without reloading component
A state change does not cause a component reload when using route parameters or query parameters. The component instance stays alive. I see no good reason to mess with the router state by using Location.go()
or location.replaceState()
.
var state = { q: 'foo', sort: 'bar' };
var url = this.router.createUrlTree([], { relativeTo: this.activatedRoute, queryParams: state }).toString();
this.router.navigateByUrl(url);
The state
object will be transformed to URL query params by Angular's Router
:
https://localhost/some/route?q=foo&sort=bar
Solution: Handling state changes to make API calls
The state changes triggered above can be handled by subscribing to ActivatedRoute.queryParams
:
export class MyComponent implements OnInit {
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit()
{
this.activatedRoute.queryParams.subscribe((params) => {
// params is the state object passed to the router on navigation
// Make API calls here
});
}
}
The state
object of the above axample will be passed as the params
argument of the queryParams
observable. In the handler API calls can be made if necessary.
But: I would prefer handling the state changes directly in my component and avoid the detour over ActivatedRoute.queryParams
. IMO, navigating the router, letting Angular do routing magic and handle the queryParams
change to do something, completely obfuscates whats happening in my component with regards to maintenability and readability of my code. What I do instead:
Compare the state passed in to queryParams
observable with the current state in my component, do nothing, if it hasn't changed there and handle state changes directly instead:
export class MyComponent implements OnInit {
private _currentState;
constructor(private activatedRoute: ActivatedRoute) { }
ngOnInit()
{
this.activatedRoute.queryParams.subscribe((params) => {
// Following comparison assumes, that property order doesn't change
if (JSON.stringify(this._currentState) == JSON.stringify(params)) return;
// The followig code will be executed only when the state changes externally, i.e. through navigating to a URL with params by the user
this._currentState = params;
this.makeApiCalls();
});
}
updateView()
{
this.makeApiCalls();
this.updateUri();
}
updateUri()
{
var url = this.router.createUrlTree([], { relativeTo: this.activatedRoute, queryParams: this._currentState }).toString();
this.router.navigateByUrl(url);
}
}
Solution: Specify browser history behavior
var createHistoryEntry = true // or false
var url = ... // see above
this.router.navigateByUrl(url, { replaceUrl : !createHistoryEntry});
Solution: Complex objects as state
This is beyond the original question but adresses common scenarios and might thus be useful: The state
object above is limited to flat objects (an object with only simple string/bool/int/... properties but no nested objects). I found this limiting, because I need to distinguish between properties that need to be handled with a backend call and others, that are only used by the component internally. I wanted a state object like:
var state = { filter: { something: '', foo: 'bar' }, viewSettings: { ... } };
To use this state as queryParams object for the router, it needs to be flattened. I simply JSON.stringify
all first level properties of the object:
private convertToParamsData(data) {
var params = {};
for (var prop in data) {
if (Object.prototype.hasOwnProperty.call(data, prop)) {
var value = data[prop];
if (value == null || value == undefined) continue;
params[prop] = JSON.stringify(value, (k, v) => {
if (v !== null) return v
});
}
}
return params;
}
and back, when handling the queryParams returned passed in by the router:
private convertFromParamsData(params) {
var data = {};
for (var prop in params) {
if (Object.prototype.hasOwnProperty.call(params, prop)) {
data[prop] = JSON.parse(params[prop]);
}
}
return data;
}
Finally: A ready-to-use Angular service
And finally, all of this isolated in one simple service:
import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { Location } from '@angular/common';
import { map, filter, tap } from 'rxjs/operators';
@Injectable()
export class QueryParamsService {
private currentParams: any;
externalStateChange: Observable<any>;
constructor(private activatedRoute: ActivatedRoute, private router: Router, private location: Location) {
this.externalStateChange = this.activatedRoute.queryParams
.pipe(map((flatParams) => {
var params = this.convertFromParamsData(flatParams);
return params
}))
.pipe(filter((params) => {
return !this.equalsCurrentParams(params);
}))
.pipe(tap((params) => {
this.currentParams = params;
}));
}
setState(data: any, createHistoryEntry = false) {
var flat = this.convertToParamsData(data);
const url = this.router.createUrlTree([], { relativeTo: this.activatedRoute, queryParams: flat }).toString();
this.currentParams = data;
this.router.navigateByUrl(url, { replaceUrl: !createHistoryEntry });
}
private equalsCurrentParams(data) {
var isEqual = JSON.stringify(data) == JSON.stringify(this.currentParams);
return isEqual;
}
private convertToParamsData(data) {
var params = {};
for (var prop in data) {
if (Object.prototype.hasOwnProperty.call(data, prop)) {
var value = data[prop];
if (value == null || value == undefined) continue;
params[prop] = JSON.stringify(value, (k, v) => {
if (v !== null) return v
});
}
}
return params;
}
private convertFromParamsData(params) {
var data = {};
for (var prop in params) {
if (Object.prototype.hasOwnProperty.call(params, prop)) {
data[prop] = JSON.parse(params[prop]);
}
}
return data;
}
}
which can be used like:
@Component({
selector: "app-search",
templateUrl: "./search.component.html",
styleUrls: ["./search.component.scss"],
providers: [QueryParamsService]
})
export class ProjectSearchComponent implements OnInit {
filter : any;
viewSettings : any;
constructor(private queryParamsService: QueryParamsService) { }
ngOnInit(): void {
this.queryParamsService.externalStateChange
.pipe(debounce(() => interval(500))) // Debounce optional
.subscribe(params => {
// Set state from params, i.e.
if (params.filter) this.filter = params.filter;
if (params.viewSettings) this.viewSettings = params.viewSettings;
// You might want to init this.filter, ... with default values here
// If you want to write default values to URL, you can call setState here
this.queryParamsService.setState(params, false); // false = no history entry
this.initializeView(); //i.e. make API calls
});
}
updateView() {
var data = {
filter: this.filter,
viewSettings: this.viewSettings
};
this.queryParamsService.setState(data, true);
// Do whatever to update your view
}
// ...
}
Don't forget the providers: [QueryParamsService]
statement on component level to create a new service instance for the component. Don't register the service globally on app module.
I have used the Apache Commons StringEscapeUtils.unescapeHtml4() for this:
Unescapes a string containing entity escapes to a string containing the actual Unicode characters corresponding to the escapes. Supports HTML 4.0 entities.
Something like:
>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']
I've tried all the possibilities. Nothing worked for me except the following. var element = document.querySelectorAll("input[id=btn1]"); element[0].setAttribute("disabled",true);
You can save the current scroll amount and then set it later:
var tempScrollTop = $(window).scrollTop();
..//Your code
$(window).scrollTop(tempScrollTop);
I found a solution for this in my case, try to update the NuGet Package Manager.
To do this:
This let me install packages without problem again.
Hope this helps!
When you create a new window using open
, it returns a reference to the new window, you can use that reference to write to the newly opened window via its document
object.
Here is an example:
var newWin = open('url','windowName','height=300,width=300');
newWin.document.write('html to write...');
You have to set all parent containers to a 100% width if you want to cover the whole page with it. You have to set an absolute value at width and height for the #content div at the very least.
body, html {
height: 100%;
width: 100%;
}
div#content {
width: 100%; height: 100%;
}
What finally worked for me was:
Finally worked. I have not yet re-tried with 64-bit installer, since I have a time critical project, but will do when again I have spare time.
P.S. what broke Anaconda for me was a blue screen I got while updating Anaconda. I guess it did not clear all old files and this broke the new installs.
In my case I did it like this:
int cursor = 0;
do {
if (integer.equals(remove))
integerList.remove(cursor);
else cursor++;
} while (cursor != integerList.size());
From the man page:
-h, --no-filename
Suppress the prefixing of file names on output. This is the default when there
is only one file (or only standard input) to search.
I don't think you can. Your best option might be to encapsulate the thing you want to pass "by ref" onto another class instance, and pass the (outer) class's reference (by value). If you see what I mean...
i.e. your method changes the internal state of the object it is passed, which is then visible to the caller.
Use this simple inline onClick function on a button if you want to programatically write data to the clipboard.
onClick={() => {navigator.clipboard.writeText(this.state.textToCopy)}}
Just surfed in from the web and felt I could contribute. I noticed that with the above code posted by @calethebrewer can result in multiple calls over the selector and unexpected behaviour for example: -
$(document).on('mouseover', '.selector', function() {
//do something
});
$(document).on('mouseout', '.selector', function() {
//do something
});
This fiddle http://jsfiddle.net/TWskH/12/ illustraits my point. When animating elements such as in plugins I have found that these multiple triggers result in unintended behavior which may result in the animation or code being called more than is necessary.
My suggestion is to simply replace with mouseenter/mouseleave: -
$(document).on('mouseenter', '.selector', function() {
//do something
});
$(document).on('mouseleave', '.selector', function() {
//do something
});
Although this prevented multiple instances of my animation from being called, I eventually went with mouseover/mouseleave as I needed to determine when children of the parent were being hovered over.
I use this query here to get all relevant info (relevant for me, at least :-)) from SQL Server:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Product Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
That gives you an output something like this:
Product Version Product Level Product Edition CLR Version
10.0.2531.0 SP1 Developer Edition (64-bit) v2.0.50727
Default Collation Instance LCID Server Name
Latin1_General_CI_AS NULL 1033 *********
To bring more confusion in this already rich thread, I happened to bump in the same unresolved external on fprintf
main.obj : error LNK2019: unresolved external symbol __imp__fprintf referenced in function _GenerateInfoFile
Even if in my case it was in a rather different context : under Visual Studio 2005 (Visual Studio 8.0) and the error was happening in my own code (the very same I was compiling), not a third party.
It happened that this error was triggered by /MD option in my compiler flags. Switching to /MT removed the issue. This is weird because usually, linking statically (MT) raises more problem than dynamically (MD)... but just in case it serves other, I put it there.
I came across this question when I was trying similar things.
A very nice and simple sample is presented at w3schools website.
https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
<h2>Modal Example</h2>_x000D_
<!-- Trigger the modal with a button -->_x000D_
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" role="dialog">_x000D_
<div class="modal-dialog">_x000D_
_x000D_
<!-- Modal content-->_x000D_
<div class="modal-content">_x000D_
<div class="modal-header">_x000D_
<button type="button" class="close" data-dismiss="modal">×</button>_x000D_
<h4 class="modal-title">Modal Header</h4>_x000D_
</div>_x000D_
<div class="modal-body">_x000D_
<p>Some text in the modal.</p>_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
To start with Socket.IO I suggest you read first the example on the main page:
On the server side, read the "How to use" on the GitHub source page:
https://github.com/Automattic/socket.io
And on the client side:
https://github.com/Automattic/socket.io-client
Finally you need to read this great tutorial:
http://howtonode.org/websockets-socketio
Hint: At the end of this blog post, you will have some links pointing on source code that could be some help.
This should work
<a href="#" onclick="function hi(){alert('Hi!')};hi()">click</a>
You may inline any javascript inside the onclick as if you were assigning the method through javascript. I think is just a matter of making code cleaner keeping your js inside a script block
Your first idea used to be the way but I've also noticed issues doing this using Firefox, try a straight http:// to the file - href='http://server/directory/file.xlsx'
Do not use a KeyListener for this as you'll miss much including pasting of text. Also a KeyListener is a very low-level construct and as such, should be avoided in Swing applications.
The solution has been described many times on SO: Use a DocumentFilter. There are several examples of this on this site, some written by me.
For example: using-documentfilter-filterbypass
Also for tutorial help, please look at: Implementing a DocumentFilter.
Edit
For instance:
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.PlainDocument;
public class DocFilter {
public static void main(String[] args) {
JTextField textField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(textField);
PlainDocument doc = (PlainDocument) textField.getDocument();
doc.setDocumentFilter(new MyIntFilter());
JOptionPane.showMessageDialog(null, panel);
}
}
class MyIntFilter extends DocumentFilter {
@Override
public void insertString(FilterBypass fb, int offset, String string,
AttributeSet attr) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.insert(offset, string);
if (test(sb.toString())) {
super.insertString(fb, offset, string, attr);
} else {
// warn the user and don't allow the insert
}
}
private boolean test(String text) {
try {
Integer.parseInt(text);
return true;
} catch (NumberFormatException e) {
return false;
}
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text,
AttributeSet attrs) throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.replace(offset, offset + length, text);
if (test(sb.toString())) {
super.replace(fb, offset, length, text, attrs);
} else {
// warn the user and don't allow the insert
}
}
@Override
public void remove(FilterBypass fb, int offset, int length)
throws BadLocationException {
Document doc = fb.getDocument();
StringBuilder sb = new StringBuilder();
sb.append(doc.getText(0, doc.getLength()));
sb.delete(offset, offset + length);
if (test(sb.toString())) {
super.remove(fb, offset, length);
} else {
// warn the user and don't allow the insert
}
}
}
Why is this important?
Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.
small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):
var objDiv = document.getElementById(id);
var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);
// add new content to div
$('#' + id ).append("new line at end<br>"); // this is jquery!
// doScroll is true, if we the bottom line is already visible
if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
import { Http, Response } from '@angular/http';
constructor(private _http: Http, private router: Router) {
}
return this._http.get('http://url/login/' + email + '/' + password)
.map((res: Response) => {
return res.json();
}).catch(this._handleError);
DENSE_RANK() is a rank with no gaps, i.e. it is “dense”.
select Name,EmailId,salary,DENSE_RANK() over(order by salary asc) from [dbo].[Employees]
RANK()-It contain gap between the rank.
select Name,EmailId,salary,RANK() over(order by salary asc) from [dbo].[Employees]
mvc:annotation-driven is a tag added in Spring 3.0 which does the following:
context:annotation-config Looks for annotations on beans in the same application context it is defined and declares support for all the general annotations like @Autowired, @Resource, @Required, @PostConstruct etc etc.
I have posted a new post about how to build an Android NDK application with OpenCV included using Android Studio and Gradle. More information can be seen here, I have summarized two methods:
(1) run ndk-build
within Gradle task
sourceSets.main.jni.srcDirs = []
task ndkBuild(type: Exec, description: 'Compile JNI source via NDK') {
ndkDir = project.plugins.findPlugin('com.android.application').getNdkFolder()
commandLine "$ndkDir/ndk-build",
'NDK_PROJECT_PATH=build/intermediates/ndk',
'NDK_LIBS_OUT=src/main/jniLibs',
'APP_BUILD_SCRIPT=src/main/jni/Android.mk',
'NDK_APPLICATION_MK=src/main/jni/Application.mk'
}
tasks.withType(JavaCompile) {
compileTask -> compileTask.dependsOn ndkBuild
}
(2) run ndk-build
with an external tool
Parameters: NDK_PROJECT_PATH=$ModuleFileDir$/build/intermediates/ndk NDK_LIBS_OUT=$ModuleFileDir$/src/main/jniLibs NDK_APPLICATION_MK=$ModuleFileDir$/src/main/jni/Application.mk APP_BUILD_SCRIPT=$ModuleFileDir$/src/main/jni/Android.mk V=1
More information can be seen here
Try -
$("#column_select").change(function () {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -
$(document).ready(function() {
$("#layout_select").children('option:gt(0)').hide();
$("#column_select").change(function() {
$("#layout_select").children('option').hide();
$("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})
})
Demo - http://jsfiddle.net/Mxkfr/2
EDIT
I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -
$(document).ready(function() {
var optarray = $("#layout_select").children('option').map(function() {
return {
"value": this.value,
"option": "<option value='" + this.value + "'>" + this.text + "</option>"
}
})
$("#column_select").change(function() {
$("#layout_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#layout_select").html(addoptarr.join(''))
}).change();
})
Demo - http://jsfiddle.net/N7Xpb/1/
Copy code using clone and appendTo function :
Here is also working example jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
$(function(){
$('#copy').clone().appendTo('#copied');
});
</script>
</body>
</html>
Using Value2
gives a performance benefit. As per Charles Williams blog
Range.Value2 works the same way as Range.Value, except that it does not check the cell format and convert to Date or Currency. And thats probably why its faster than .Value when retrieving numbers.
So
DirArray = [a1:a5].Value2
Increment a counter every time you render a screen and clear that counter for some time interval over which you want to measure the frame-rate.
Ie. Every 3 seconds, get counter/3 and then clear the counter.
As per the documentation: This allows you to switch from the default ASCII to other encodings such as UTF-8, which the Python runtime will use whenever it has to decode a string buffer to unicode.
This function is only available at Python start-up time, when Python scans the environment. It has to be called in a system-wide module, sitecustomize.py
, After this module has been evaluated, the setdefaultencoding()
function is removed from the sys
module.
The only way to actually use it is with a reload hack that brings the attribute back.
Also, the use of sys.setdefaultencoding()
has always been discouraged, and it has become a no-op in py3k. The encoding of py3k is hard-wired to "utf-8" and changing it raises an error.
I suggest some pointers for reading:
I had the same problem and for some reason, even a git clean -f -d
would not do it. Here is why: For some reason, if your file is ignored by Git (via a .gitignore entry, I assume), it still bothers about overwriting this with a later pull, but a clean will not remove it, unless you add -x
.
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
I've found this works:
Rows(CStr(iVar1) & ":" & CStr(iVar2)).Select
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
In addition to grouping by the field name, you may also group by ordinal, or position of the field within the table. 1 corresponds to the first field (regardless of name), 2 is the second, and so on.
This is generally ill-advised if you're grouping on something specific, since the table/view structure may change. Additionally, it may be difficult to quickly comprehend what your SQL query is doing if you haven’t memorized the table fields.
If you are returning a unique set, or quickly performing a temporary lookup, this is nice shorthand syntax to reduce typing. If you plan to run the query again at some point, I’d recommend replacing those to avoid future confusion and unexpected complications (due to scheme changes).
Just adding that you can pass the link_to
method a block:
<%= link_to href: 'http://www.example.com/' do %>
<%= image_tag 'happyface.png', width: 136, height: 67, alt: 'a face that is unnervingly happy'%>
<% end %>
results in:
<a href="/?href=http%3A%2F%2Fhttp://www.example.com/k%2F">
<img alt="a face that is unnervingly happy" height="67" src="/assets/happyface.png" width="136">
</a>
This has been a life saver when the designer has given me complex links with fancy css3 roll-over effects.
There used to be a statement in the SQLite documentation that the practical size limit of a database file was a few dozen GB:s. That was mostly due to the need for SQLite to "allocate a bitmap of dirty pages" whenever you started a transaction. Thus 256 byte of RAM were required for each MB in the database. Inserting into a 50 GB DB-file would require a hefty (2^8)*(2^10)=2^18=256 MB of RAM.
But as of recent versions of SQLite, this is no longer needed. Read more here.
you can also pyramid of stars like this
for (var i = 5; i >= 1; i--) {
var py = "";
for (var j = i; j >= 1; j--) {
py += j;
}
console.log(py);
}
str = "hello world!";
str.Substring(10, str.Length-10)
you will need to perform the length checks else this would throw an error
As RichieHindle pointed out the shortcut for column (block) selection is Alt+Shift+A
. The problem I ran into is that the Android SDK on Eclipse uses 3 shortcuts that all start with Alt+Shift+A
, so if you type that, you'll be given a choice of continuing with D
, S
, or R
.
To solve this I redefined the column selection as Alt+Shift+A,A
(Alt
, Shift
, A
pressed together and then followed by a subsequent A
). To do this go to Windows > Preferences
then type keys
or navigate to General > Keys
. Under the Keys enter the filter text
of block selection
to quickly find the shortcut listing for toggle block selection
. Here you can adjust the shortcut for column selection as you wish.
$(".list li").sort(asc_sort).appendTo('.list');
//$("#debug").text("Output:");
// accending sort
function asc_sort(a, b){
return ($(b).text()) < ($(a).text()) ? 1 : -1;
}
// decending sort
function dec_sort(a, b){
return ($(b).text()) > ($(a).text()) ? 1 : -1;
}
live demo : http://jsbin.com/eculis/876/edit
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
ES6 introduces Array.from
which lets you create an Array
from any "array-like" or iterables objects:
Array.from({length: 10}, (x, i) => i);
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In this case {length: 10}
represents the minimal definition of an "array-like" object: an empty object with just a length
property defined.
Array.from
allows for a second argument to map over the resulting array.
Below command will push all the branches(including the ones which you have never checked-out but present in your git repo, you can see them by git branch -a
)
git push origin '*:*'
NOTE: This command comes handy when you are migrating version control service(i.e migrating from Gitlab to GitHub)
you can simple use some div
to make a container and the display: flex;
to make the content appear side-by-side like this:
CSS
.splitscreen {
display:flex;
}
.splitscreen .left {
flex: 1;
}
.splitscreen .right {
flex: 1;
}
HTML
<div class="splitscreen">
<div class="left">
<!-- content -->
</div>
<div class="right">
<!-- content -->
</div>
</div>
using flex
you say who will use more space on the screen.
int is a primitive datatype whereas Integer is an object. Creating an object with Integer will give you access to all the methods that are available in the Integer class. But, if you create a primitive data type with int, you will not be able to use those inbuild methods and you have to define them by yourself. But, if you don't want any other methods and want to make the program more memory efficient, you can go with primitive datatype because creating an object will increase the memory consumption.
There is similar issue. I added listener as given here
https://stackoverflow.com/questions/3145936/spring-security-j-spring-security-logout-problem
It worked for me adding below lines to web.xml. Posting it very late, should help someone looking for answer.
<listener>
<listener-class> org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
Help is your best saviour, there is a logs action that you can call to check logs for all running processes.
forever --help
Shows the commands
logs Lists log files for all forever processes
logs <script|index> Tails the logs for <script|index>
Sample output of the above command, for three processes running. console.log output's are stored in these logs.
info: Logs for running Forever processes
data: script logfile
data: [0] server.js /root/.forever/79ao.log
data: [1] server.js /root/.forever/ZcOk.log
data: [2] server.js /root/.forever/L30K.log
This causes headaches so I updated a solution that will run using the most common hardware and software tools available to users in December 2014. Please note that the JDK/SDK/JRE/Netbeans and their subsequent classes, template libraries compilers, editors and debuggerz are free.
This program was tested with Java v8 u25. It was written and built using
Netbeans IDE 8.0.2, JDK 1.8, OS is win8.1 (apologies) and browser is Chrome (double-apologies)
- meant to assist UNIX-cmd-line OG's deal with modern GUI-Web-based IDEs
at ZERO COST - because information (and IDEs) should always be free.
By Tapper7. For Everyone.
code block:
package modchk; //Netbeans requirement.
import java.util.Scanner;
//import java.io.*; is not needed Netbeans automatically includes it.
public class Modchk {
public static void main(String[] args){
int input1;
int input2;
//Explicity define the purpose of the .exe to user:
System.out.println("Modchk by Tapper7. Tests IOStream and basic bool modulo fxn.\n"
+ "Commented and coded for C/C++ programmers new to Java\n");
//create an object that reads integers:
Scanner Cin = new Scanner(System.in);
//the following will throw() if you don't do you what it tells you or if
//int entered == ArrayIndex-out-of-bounds for your system. +-~2.1e9
System.out.println("Enter an integer wiseguy: ");
input1 = Cin.nextInt(); //this command emulates "cin >> input1;"
//I test like Ernie Banks played hardball: "Let's play two!"
System.out.println("Enter another integer...anyday now: ");
input2 = Cin.nextInt();
//debug the scanner and istream:
System.out.println("the 1st N entered by the user was " + input1);
System.out.println("the 2nd N entered by the user was " + input2);
//"do maths" on vars to make sure they are of use to me:
System.out.println("modchk for " + input1);
if(2 % input1 == 0){
System.out.print(input1 + " is even\n"); //<---same output effect as *.println
}else{
System.out.println(input1 + " is odd");
}//endif input1
//one mo' 'gain (as in istream dbg chk above)
System.out.println("modchk for " + input2);
if(2 % input2 == 0){
System.out.print(input2 + " is even\n");
}else{
System.out.println(input2 + " is odd");
}//endif input2
}//end main
}//end Modchk
You should form the command with the contents of the textboxes:
sql = "insert into Main (Firt Name, Last Name) values(" + textbox2.Text +
"," + textbox3.Text+ ")";
This, of course, provided that you manage to open the connection correctly.
It would be helpful to know what is happening with your current code. If you are getting some error displayed in that message box, it would be great to know what it's saying.
You should also validate the inputs before actually running the command (i.e. make sure they don't contain malicious code).
Let's say I have Table1
with primary key _id
and a boolean column doc_availability
; Table2
with foreign key _id
and DateTime column last_update
and I want to change the availability of a document with _id
14 in Table1
to 0 i.e unavailable and update Table2
with the timestamp when the document was last updated. The following query would do the task:
UPDATE Table1, Table2
SET doc_availability = 0, last_update = NOW()
WHERE Table1._id = Table2._id AND Table1._id = 14
I prefer the oneliner:
print(sorted(df['Column Name'].unique()))
Ideally you should use a transparent PNG with the circle in white and the background of the image transparent. Then you can set the background-color
of the .fb-icon
to blue on hover. So you're CSS would be:
fb-icon{
background:none;
}
fb-icon:hover{
background:#0000ff;
}
Additionally, if you don't want to use PNG's you can also use a sprite and alter the background position. A sprite is one large image with a collection of smaller images which can be used as a background image by changing the background position. So for eg, if your original circle image with the white background is 100px X 100px, you can increase the height of the image to 100px X 200px, so that the top half is the original image with the white background, while the lower half is the new image with the blue background. Then you set setup your CSS as:
fb-icon{
background:url('path/to/image/image.png') no-repeat 0 0;
}
fb-icon:hover{
background:url('path/to/image/image.png') no-repeat 0 -100px;
}
If Perl is an option, you can try this:
perl -ne 'printf "%s,$_" , $.-1' file
$_
is the line
$.
is the line number
Select * from TableName Where ColumnName LIKE '%[^A-Za-z0-9, ]%'
This will give you all the row which contains any special character.
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
You need to instantiate the class it is contained within, or make the method static.
So if it is contained within class Foo:
Foo x = new Foo();
List<Integer> stuff = x.myNumbers();
or alternatively shorthand:
List<Integer> stuff = new Foo().myNumbers();
or if you make it static like so:
public static List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
you can call it like so:
List<Integer> stuff = Foo.myNumbers();
I had the same problem running Ubuntu 18.04. I tried multiple solutions but my device (OnePlus 5T) was always unauthorized.
Solution
Configure udev rules on Ubuntu. To do this, just follow the official documentation: https://developer.android.com/studio/run/device
The idVendor of my device (OnePlus) is not listed. To get it, just connect your device and use lsusb
:
Bus 003 Device 008: ID 2a70:4ee7
In this example, 2a70
is the idVendor.
Remove existing adb keys on Ubuntu:
rm -v ~/.android/adbkey* ~/.android/adbkey ~/.android/adbkey.pub
'Revoke USB debugging authorizations' on your device configuration (developer options).
Finally, restart the adb server to create a new key:
sudo adb kill-server
sudo adb devices
After that, I got the authorization prompt on my device and I authorized it.
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value
assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
Heres what I do for Bootstrap 3/4
Use container-fluid instead of container.
Add this to my CSS
@media (min-width: 1400px) {
.container-fluid{
max-width: 1400px;
}
}
This removes margins below 1400px width screen
You could also try doing something like this:
var myArray = [{'name': 'test'}, {'name':'test2'}];
var myObject = {'name': 'test'};
myArray.splice(myArray.indexOf(myObject),1);
line=`sed -n 2p myfile`
echo $line
implementation 'com.treebo:internetavailabilitychecker:1.0.1'
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
InternetAvailabilityChecker.init(this);
}
@Override
public void onLowMemory() {
super.onLowMemory();
InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
}
}
if list item view contains button or checkbox or imagebutton, the onitemclicklistener and onitemlongclicklistener not working due to it has own onclick listener.
set focusable as false
holder.button.setFocusable(false);
Remove "values" when you're appending a group of rows, and remove the extra parentheses. You can avoid the circular reference by using an alias for avg(CurrencyColumn) (as you did in your example) or by not using an alias at all.
If the column names are the same in both tables, your query would be like this:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn) as CurrencyColumn1
FROM Table1
GROUP BY LongIntColumn;
And it would work without an alias:
INSERT INTO Table2 (LongIntColumn, Junk)
SELECT LongIntColumn, avg(CurrencyColumn)
FROM Table1
GROUP BY LongIntColumn;
Example using uuencode:
uuencode surfing.jpeg surfing.jpeg | mail [email protected]
and reference article:
http://www.shelldorado.com/articles/mailattachments.html
you may apt install sharutils
to have uuencode
command
Yes, but none of them will manage to produce readable enough code to worth the effort. You will spend more time trying to read the decompiled source with assembler blocks inside, than rewriting your old app from scratch.
Settings > Language & input > Current keyboard > Hardware Switch ON.
This option worked.
There is not really any other way in JavaScript to concatenate strings.
You could theoretically use .concat()
, but that's way slower than just +
Libraries are more often than not slower than native JavaScript, especially on basic operations like string concatenation, or numerical operations.
Simply put: +
is the fastest.