You can use Uber's H3,point_dist()
function to compute the spherical distance between two (lat, lng) points. We can set return unit ('km', 'm', or 'rads'). The default unit is Km.
Example :
import H3
coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)
distance = h3.point_dist(coords_1,coords_2) #278.4584889328128
Hope this will usefull!
I guess you want it along the curvature of the earth. Your two points and the center of the earth are on a plane. The center of the earth is the center of a circle on that plane and the two points are (roughly) on the perimeter of that circle. From that you can calculate the distance by finding out what the angle from one point to the other is.
If the points are not the same heights, or if you need to take into account that the earth is not a perfect sphere it gets a little more difficult.
I tried most of solutions but did not seem anyone to work. However I found a walk around for it below.
The structure of the form is: form
=> label
, input
and submit button
. After we choose a file, the filename will be shown by the label by doing so manually in JavaScript.
So my strategy is: initially the submit button
is disabled, after a file is chosen, the submit button disabled
attribute will be removed such that I can submit file. After I submit, I clear the label
which makes it look like I clear the file input
but actually not. Then I will disable the submit button again to prevent from submitting the form.
By setting the submit button
disable
or not, I stop the file from submitted many times unless I choose another file.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){_x000D_
let strX = "";_x000D_
function replacer(key, value){_x000D_
if (value === undefined){return "undef"}_x000D_
return value_x000D_
} _x000D_
for (let arg of arguments){_x000D_
let lastChar;_x000D_
if (typeof arg!== "string"){_x000D_
let _arg = JSON.stringify(arg, replacer);_x000D_
_arg = _arg.replace('{',"");_x000D_
_arg = _arg.replace('}',""); _x000D_
_arg = _arg.replace(/:/g,"=");_x000D_
_arg = _arg.replace(/"/g,"");_x000D_
strX+=_arg;_x000D_
}else{_x000D_
strX+=arg;_x000D_
lastChar = arg[arg.length-1];_x000D_
}_x000D_
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};_x000D_
}_x000D_
console.log(strX) _x000D_
}_x000D_
let a = 42, b = 3, c;_x000D_
debugVar("Begin:",{a,b,c},"end")
_x000D_
To diagnose this issue, place the line of code causing the TargetInvocationException inside the try block.
To troubleshoot this type of error, get the inner exception. It could be due to a number of different issues.
try
{
// code causing TargetInvocationException
}
catch (Exception e)
{
if (e.InnerException != null)
{
string err = e.InnerException.Message;
}
}
You can be more precise with CSS background-origin:
background-origin: content-box;
This will make image respect the padding of the box.
Or, to get a pseudo-random int in the range 0 to 19, for example, you could use the higher bits like this:
j = ((rand() >> 15) % 20;
I fell into this dilemma once, and researched quite a bit on google for opinions. What I found was that indeed many see saving images to disk better for larger images, while mySQL allows for easier access, specially from languages like PHP.
I found a similar question
MySQL BLOB vs File for Storing Small PNG Images?
My final verdict was that for things such as a profile picture, just a small square image that needs to be there per user, mySQL would be better than storing a bunch of thumbs in the hdd, while for photo albums and things like that, folders/image files are better.
Hope it helps
I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.
From RFC 4918:
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
Hide php warnings in file
error_reporting(0);
Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.
So in your code you could have:
strFolder = Wscript.Arguments.Item(0)
Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing
Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.
I think use drop duplicate
sometimes will not so useful depending dataframe.
I found this:
[in] df['col_1'].unique()
[out] array(['A', 'B', 'C'], dtype=object)
And work for me!
https://riptutorial.com/pandas/example/26077/select-distinct-rows-across-dataframe
There is bug in MySQL 5.6 version. Even mysqld show as :
Default options are read from the following files in the given order:
C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Realy settings are reading in following order :
Default options are read from the following files in the given order:
C:\ProgramData\MySQL\MySQL Server 5.6\my.ini C:\Windows\my.ini C:\Windows\my.cnf C:\my.ini C:\my.cnf c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.ini c:\Program Files (x86)\MySQL\MySQL Server 5.6\my.cnf
Check file: "C:\ProgramData\MySQL\MySQL Server 5.6\my.ini"
Hope it help somebody.
We could not uninstall a program, stuck with the "Windows error 2 cannot load Java VM". Added the Java path to the PATH variable, uninstalled and re-installed Java 8, the problem would not go away.
Then I found this solution online and it worked for us on the first shot: - Uninstall Java 8 - Install Java 6
Whatever the reason, with Java 6, the error went away, we uninstalled the program, and re-installed Java 8.
In Visual Studio 2017, unchecked the ContextSwitchDeadlock option by:
Debug > Windows > Exception Settings
In Exception Setting Windows: Uncheck the ContextSwitchDeadlock option
value_counts()
is now a DataFrame method since pandas 1.1.0
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.value_counts.html
I found a mod_rewrite
solution that works well for both proxied and unproxied servers.
If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.
RewriteEngine On
# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]
# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on
# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
For sending emails from gmail smtp and using php mail function, First you have to setup the sendmail in your local machine, Once it is set it mean you have setup your local smtp server, you will then be able to send emails from the account you set in your sendmail smtp account, in my case I followed the instructions from https://www.developerfiles.com/how-to-send-emails-from-localhost-mac-os-x-el-capitan/ and was able to setup the account,
May be helpful for late comers.
#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
using namespace cv;
using namespace std;
int main(int argc, char *argv[])
{
if (argc != 2) {
cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
return -1;
}else{
Mat image;
Mat grayImage;
image = imread(argv[1], IMREAD_COLOR);
if (!image.data) {
cout << "Could not open the image file" << endl;
return -1;
}
else {
int height = image.rows;
int width = image.cols;
cvtColor(image, grayImage, CV_BGR2GRAY);
namedWindow("Display window", WINDOW_AUTOSIZE);
imshow("Display window", image);
namedWindow("Gray Image", WINDOW_AUTOSIZE);
imshow("Gray Image", grayImage);
cvWaitKey(0);
image.release();
grayImage.release();
return 0;
}
}
}
This method works for me, it's not dynamic but straight to the point:
const fs = require('fs');
const express = require('express');
const app = express();
app.get( '/logo.gif', function( req, res ) {
fs.readFile( 'logo.gif', function( err, data ) {
if ( err ) {
console.log( err );
return;
}
res.write( data );
return res.end();
});
});
app.listen( 80 );
Try this its worked for me
SELECT * from bookedroom
WHERE UNIX_TIMESTAMP('2020-8-07 5:31')
between UNIX_TIMESTAMP('2020-8-07 5:30') and
UNIX_TIMESTAMP('2020-8-09 5:30')
Your question is a little off the mark. In particular, you say "that the element needs to be added into the first empty slot in an array, lie (sic) a Java push function would do."
The verb "Push" is not something that is used with an Array in any language that I know of except JavaScript. I suspect that it's only in JavaScript because it could be there (since JavaScript is a completely dynamic language). I'm pretty sure it wasn't designed in intentionally.
A JavaScript-style Push operation in C# could be written in this somewhat inefficient manner:
int [] myArray = new int [] {1, 2, 3, 4};
var tempList = myArray.ToList();
tempList.Add(5);
myArray = tempList.ToArray(); //equiv: myArray.Push(5);
"Push" is used in some types of containers, particularly Stacks, Queues and Deques (which get two pushes - one from the front, one from the back). I urge you not to include Push as a verb in your explanation of arrays. It adds nothing to a CS student's vocabulary.
In C#, as in most traditional procedural languages, an array is a collection of elements of a single type, contained in a fixed length contiguous block of memory. When you allocate an array, the space for every array element is allocated (and, in C# those elements are initialized to the default value of the type, null for reference types).
In C#, arrays of reference types are filled with object references; arrays of value types are filled with instances of that value type. As a result, an array of 4 strings uses the same memory as an array of 4 instance of your application class (since they are both reference types). But, an array of 4 DateTime instances is significantly longer that of an array of 4 short integers.
In C#, an instance of an array is an instance of System.Array, a reference type. Arrays have a few properties and methods (like the Length property). Otherwise, there isn't much you can do with an array: you can read (or write) from (or to) individual elements using an array index. Arrays of type T also implement IEnumerable<T>
, so you can iterate through the elements of an array.
Arrays are mutable (the values in an array can be written to), but they have a fixed length - they can't be extended or shortened. They are ordered, and they can't be re-arranged (except by swizzling the values manually).
C# arrays are covariant. If you were to ask the C# language designers, this would be the feature they regret the most. It's one of the few ways you can break C# type safety. Consider this code (assuming that Cat and Dog classes inherit from Animal):
Cat[] myCats = new Cat[]{myCat, yourCat, theirCat};
Animal[] animals = (Animal[]) myCats; //legal but dangerous
animals[1] = new Dog(); //heading off the cliff
myCats[1].Speak(); //Woof!
That "feature" is the result of the lack of generic types and explicit covariance/contravariance in the initial version of the .NET Framework and the urge to copy a Java "feature".
Arrays do show up in many core .NET APIs (for example, System.Reflection). They are there, again, because the initial release did not support generic collections.
In general, an experienced C# programmer will not use many arrays in his applications, preferring to use more capable collections such as List<T>
, Dictionary<TKey, TValue>
, HashSet<T>
and friends. In particular, that programmer will tend to pass collections around using IEnumerable<T>
an interface that all collections implement. The big advantage of using IEnumerable<T>
as parameters and return types (where possible and logical) is that collections accessed via IEnumerable<T>
references are immutable. It's kinda-sorta like using const
correctly in C++.
One thing you might consider adding in to your lectures on arrays - after everyone has mastered the basics - is the new Span<T>
type. Spans may make C# arrays useful.
Finally, LINQ (Language Integrated Query) introduced a lot of functionality to collections (by adding Extension Methods to IEnumerable<T>
). Make sure your student do not have a using System.Linq;
statement up at the top of their code - mixing LINQ in to a beginning student's class on arrays would bewilder him or her.
BTW: what kind of class is it you teach? At what level?
A DataInputStream
is just a decorator over an InputStream
(which System.in
is) which allows to read using more convenient methods.
As to the Float.valueOf()
, well, that's curious because Float
has .parseFloat()
as well. Here the code grabs a Float
with .valueOf()
which it turns into the primitive float
type using .floatValue()
, which is unnecessary with Java 1.5+ due to auto unboxing.
And as other answers rightly say, these methods are obsolete anyway.
You can't do that, unless you take the child out of the parent and place it via positioning.
The only way I know and it actually works, is to use a translucid image (.png with transparency) for the parent's background. The only disavantage is that you can't control the opacity via CSS, other than that it works!
Set the style on the textbox as text-transform: uppercase?
yes, and its quick and simple though very hidden:
binwidth=5
bin(x,width)=width*floor(x/width)
plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes
check out help smooth freq
to see why the above makes a histogram
to deal with ranges just set the xrange variable.
There is pure CSS4 solution:
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
user-select
is a CSS Module Level 4 specification, that is currently a draft and non-standard CSS property, but browsers support it well — see #search=user-select.
.selectable{
-webkit-touch-callout: all; /* iOS Safari */
-webkit-user-select: all; /* Safari */
-khtml-user-select: all; /* Konqueror HTML */
-moz-user-select: all; /* Firefox */
-ms-user-select: all; /* Internet Explorer/Edge */
user-select: all; /* Chrome and Opera */
}
_x000D_
<div class="selectable">
click and all this will be selected
</div>
_x000D_
Read more on user-select here on MDN and play with it here in w3scools
If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:
sourceSets {
test {
java.srcDirs += [
'src/customDir/test/kotlin'
]
print(java.srcDirs) // Clean
}
}
Pay attention to the operator +=
and if you want to run integration tests change test
to androidTest
.
GL
I solved the same issue by following steps:
Check the angular version: Using command: ng version My angular version is: Angular CLI: 7.3.10
After that I have support version of ngx bootstrap from the link: https://www.npmjs.com/package/ngx-bootstrap
In package.json file update the version: "bootstrap": "^4.5.3", "@ng-bootstrap/ng-bootstrap": "^4.2.2",
Now after updating package.json, use the command npm update
After this use command ng serve and my error got resolved
Object.keys
for getting all property names of the object and filter all values that exact or partial match with specified string.
function filterByValue(array, string) {
return array.filter(o =>
Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));
}
const arrayOfObject = [{
name: 'Paul',
country: 'Canada',
}, {
name: 'Lea',
country: 'Italy',
}, {
name: 'John',
country: 'Italy'
}];
console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]
_x000D_
You can also filter by specific key such as.
Object.keys(o).some(k => o.country.toLowerCase().includes(string.toLowerCase())));
Now you can just check array count after filtered to check value contains or not.
Hope it's helpful.
public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}
To access the memory of an object directly (to do a "core dump") you'll need to head into unsafe code.
If you want something more compact than BinaryWriter or a raw memory dump will give you, then you need to write some custom serialisation code that extracts the critical information from the object and packs it in an optimal way.
edit P.S. It's very easy to wrap the BinaryWriter approach into a DeflateStream to compress the data, which will usually roughly halve the size of the data.
Do a replace on formatting characters, then check the remaining for phone validity. In PHP,
$replace = array( ' ', '-', '/', '(', ')', ',', '.' ); //etc; as needed
preg_match( '/1?[0-9]{10}((ext|x)[0-9]{1,4})?/i', str_replace( $replace, '', $phone_num );
Breaking a complex regexp like this can be just as effective, but much more simple.
Use '›'
›
-> single right angle quote. For single left angle quote, use ‹
select ROUND(CASE
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))!='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
WHEN CONVERT( float, REPLACE( isnull( value1,''),',',''))!='' AND CONVERT( float, REPLACE( isnull( value2,''),',',''))='' then CONVERT( float, REPLACE( isnull( value3,''),',',''))
else CONVERT( float, REPLACE(isnull( value1,''),',','')) end,0) from Tablename where ID="123"
The most simplest tool comes with glibc and is called getconf
:
$ getconf _NPROCESSORS_ONLN
4
This isuse because of coflict merge. If you have new commit in origin and not get those files; also you have changed the local master branch files then you got this error. You should fetch again to a new directory and copy your files into that path. Finally, you should commit and push your changes.
The property pDoc.parentElement
or pDoc.parentNode
will get you the parent element.
I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,
<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />
This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.
For me the fix was to right click on my webapp module > Maven > Update Project
The specification for 'mailto' body says:
The body of a message is simply lines of US-ASCII characters. The only two limitations on the body are as follows:
- CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.
- Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.
https://tools.ietf.org/html/rfc5322#section-2.3
Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.
There are more than one way to increment a variable in bash, but what you tried is not correct.
You can use for example arithmetic expansion:
i=$((i+1))
or only:
((i=i+1))
or:
((i+=1))
or even:
((i++))
Or you can use let:
let "i=i+1"
or only:
let "i+=1"
or even:
let "i++"
See also: http://tldp.org/LDP/abs/html/dblparens.html.
Your problem is that all chapters, whether they're in the appendix or not, default to starting on an odd-numbered page when you're in two-sided layout mode. A few possible solutions:
The simplest solution is to use the openany
option to your document class, which makes chapters start on the next page, irrespective of whether it's an odd or even numbered page. This is supported in the standard book documentclass, eg \documentclass[openany]{book}
. (memoir
also supports using this as a declaration \openany
which can be used in the middle of a document to change the behavior for subsequent pages.)
Another option is to try the \let\cleardoublepage\clearpage
command before your appendices to avoid the behavior.
Or, if you don't care using a two-sided layout, using the option oneside
to your documentclass
(eg \documentclass[oneside]{book}
) will switch to using a one-sided layout.
I don't think that there are any neat tricks you can do storing this as you can do for example with an MD5 hash.
I think your best bet is to store it as a CHAR(60)
as it is always 60 chars long
I'm guessing this will help.
When passed as functions arguments, arrays act the same way as pointers. So you don't need to reference them. Simply type:
int x[]
or
int x[a]
. Both ways will work. I guess its the same thing Konrad Rudolf was saying, figured as much.
for ( i = 0; i < total.length; i++ ); // remove this
{
if (total[i]!=0)
System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}
The for loop loops until i=26
(where 26 is total.length
) and then your if
is executed, going over the bounds of the array. Remove the ;
at the end of the for
loop.
You don't need to use
adb shell getevent -l
command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.
Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/
You should check out this plugin:
https://github.com/kemayo/maphilight
and the demo:
http://davidlynch.org/js/maphilight/docs/demo_usa.html
if anything, you might be able to borrow some code from it to fix yours.
Wow, I found yet another case for this problem. None of the above worked. Eventually I used python's ability to introspect what was being loaded. For python 2.7 this means:
import imp
imp.find_module("cv2")
This turned up a completely unexpected "cv2.pyd" file in an Anaconda DLL directory that wasn't touched by multiple uninstall/install attempts. Python was looking there first and not finding my good installation. I deleted that cv2.pyd file and tried imp.find_module("cv2") again and python immediately found the right file and cv2 started working.
So if none of the other solutions work for you, make sure you use python introspection to see what file python is trying to load.
I don't think you can - there is a W3C draft API to get audio or video, but there is no implementation yet on any of the major mobile OSs.
Second best The only option is to go with Dennis' suggestion to use PhoneGap. This will mean you need to create a native app and add it to the mobile app store/marketplace.
There is an issue with the Command + F solution. It will replace all 0's if you click replace all. This means if you do not review every zero, zero's contained in important cells will also be removed. For example, if you have phone numbers that have (420) area codes they will all be changed to (40).
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
I have created a module for pipes in the same directory where my pipes are present
import { NgModule } from '@angular/core';
///import pipe...
import { Base64ToImage, TruncateString} from './'
@NgModule({
imports: [],
declarations: [Base64ToImage, TruncateString],
exports: [Base64ToImage, TruncateString]
})
export class SharedPipeModule { }
Now import that module in app.module:
import {SharedPipeModule} from './pipe/shared.pipe.module'
@NgModule({
imports: [
...
, PipeModule.forRoot()
....
],
Now it can be used by importing the same in the nested module
Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!
for (int i = 0; i < 3; i++) {
LinearLayout linearDummy = new LinearLayout(getActivity());
linearDummy.setOrientation(LinearLayout.VERTICAL);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();
} else {
linearDummy.setId(View.generateViewId());
}
fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();
xNumberLinear.addView(linearDummy);
}
Although not part of Django, Airflow is a more recent project (as of 2016) that is useful for task management.
Airflow is a workflow automation and scheduling system that can be used to author and manage data pipelines. A web-based UI provides the developer with a range of options for managing and viewing these pipelines.
Airflow is written in Python and is built using Flask.
Airflow was created by Maxime Beauchemin at Airbnb and open sourced in the spring of 2015. It joined the Apache Software Foundation’s incubation program in the winter of 2016. Here is the Git project page and some addition background information.
I'm not entirely sure of the general purpose of the function, but you could always do this:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
Try to use the following approach (it works for me):
@Query("SELECT u.username FROM User u WHERE u.username LIKE CONCAT('%',:username,'%')")
List<String> findUsersWithPartOfName(@Param("username") String username);
Notice: The table name in JPQL must start with a capital letter.
You can use a WScript
object and call the Sleep
method on it:
Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds
Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):
Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000
You can also try running with JRockit. It's a JVM optimized for servers, but many long running client applications, like IDE's, run very well on JRockit. Eclipse is no exception. JRockit doesn't have a perm-space so you don't need to configure it.
It's possible set a pause time target(ms) to avoid long gc pauses stalling the UI.
-showsplash
org.eclipse.platform
-vm
C:\jrmc-3.1.2-1.6.0\bin\javaw.exe
-vmargs
-XgcPrio:deterministic
-XpauseTarget:20
I usually don't bother setting -Xmx and -Xms and let JRockit grow the heap as it sees necessary. If you launch your Eclipse application with JRockit you can also monitor, profile and find memory leaks in your application using the JRockit Mission Control tools suite. You download the plugins from this update site. Note, only works for Eclipse 3.3 and Eclipse 3.4
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
I found the solution here:
How to properly -filter multiple strings in a PowerShell copy script
You have to use -Include
flag for Get-ChildItem
My Example:
$Location = "C:\user\files"
$result = (Get-ChildItem $Location\* -Include *.png, *.gif, *.jpg)
Dont forget put "*" after path location.
I would use a https://docs.flutter.io/flutter/widgets/Stack-class.html to be able to freely position widgets.
To create circles
new BoxDecoration(
color: effectiveBackgroundColor,
image: backgroundImage != null
? new DecorationImage(image: backgroundImage, fit: BoxFit.cover)
: null,
shape: BoxShape.circle,
),
and https://docs.flutter.io/flutter/widgets/Transform/Transform.rotate.html to position the white dots.
To understand why it is necessary to distinguish between int
and long
literals, consider:
long l = -1 >>> 1;
versus
int a = -1;
long l = a >>> 1;
Now as you would rightly expect, both code fragments give the same value to variable l
. Without being able to distinguish int
and long
literals, what is the interpretation of -1 >>> 1
?
-1L >>> 1 // ?
or
(int)-1 >>> 1 // ?
So even if the number is in the common range, we need to specify type. If the default changed with magnitude of the literal, then there would be a weird change in the interpretations of expressions just from changing the digits.
This does not occur for byte
, short
and char
because they are always promoted before performing arithmetic and bitwise operations. Arguably their should be integer type suffixes for use in, say, array initialisation expressions, but there isn't. float
uses suffix f
and double
d
. Other literals have unambiguous types, with there being a special type for null
.
In the course of developing an in-house address verification service at a German company I used to work for I've come across a number of ways to tackle this issue. I'll do my best to sum up my findings below:
Free, Open Source Software
Clearly, the first approach anyone would take is an open-source one (like openstreetmap.org), which is never a bad idea. But whether or not you can really put this to good and reliable use depends very much on how much you need to rely on the results.
Addresses are an incredibly variable thing. Verifying U.S. addresses is not an easy task, but bearable, but once you're going for Europe, especially the U.K. with their extensive Postal Code system, the open-source approach will simply lack data.
Web Services / APIs
Enterprise-Class Software
Money gets it done, obviously. But not every business or developer can spend ~$0.15 per address lookup (that's $150 for 1,000 API requests) - a very expensive business model the vast majority of address validation APIs have implemented.
What I ended up integrating: streetlayer API
Since I was not willing to take on the programmatic approach of verifying address data manually I finally came to the conclusion that I was in need of an API with a price tag that would not make my boss want to fire me and still deliver solid and reliable international verification results.
Long story short, I ended up integrating an API built by apilayer, called "streetlayer API". I was easily convinced by a simple JSON integration, surprisingly accurate validation results and their developer-friendly pricing. Also, 100 requests/month are entirely free.
Hope this helps!
I had the same issue with missing references. Below my scenario:
All version numbers in project and packages match, doing nuget restore (in all its ways) did not work.
How I fixed it: simply delete the package folders in the solution root and execute nuget restore. At this point the dlls are correctly downloaded and can be added for the missing references.
I searched many times for it, finally used custom timestamps
like below:
$now = Carbon::now()->toDateTimeString();
Model::insert([
['name'=>'Foo', 'created_at'=>$now, 'updated_at'=>$now],
['name'=>'Bar', 'created_at'=>$now, 'updated_at'=>$now],
['name'=>'Baz', 'created_at'=>$now, 'updated_at'=>$now],
..................................
]);
If all you need is a subject line (as in an alert message) simply do:
mailx -s "This is all she wrote" < /dev/null "myself@myaddress"
I would recommend using CSS for this. You should create a CSS rule to enforce the centering, for example:
.ui-helper-center {
text-align: center;
}
And then add the ui-helper-center
class to the table cells for which you wish to control the alignment:
<td class="ui-helper-center">Content</td>
EDIT: Since this answer was accepted, I felt obligated to edit out the parts that caused a flame-war in the comments, and to not promote poor and outdated practices.
See Gabe's answer for how to include the CSS rule into your page.
Another option, if you want to define your constants in one place:
module DSL
module Constants
MY_CONSTANT = 1
end
end
But still make them globally visible without having to access them in fully qualified way:
DSL::Constants::MY_CONSTANT # => 1
MY_CONSTANT # => NameError: uninitialized constant MY_CONSTANT
Object.instance_eval { include DSL::Constants }
MY_CONSTANT # => 1
After setting up GOPRIVATE
and git config ...
People may still meeting problems like this when fetching private source:
https fetch: Get "https://private/user/repo?go-get=1": EOF
They can't use private repo without .git
extension.
The reason is the go tool has no idea about the VCS protocol of this repo, git
or svn
or any other, unlike github.com
or golang.org
them are hardcoded into go's source.
Then the go tool will do a https
query before fetching your private repo:
https://private/user/repo?go-get=1
If your private repo has no support for https
request, please use replace
to tell it directly :
require private/user/repo v1.0.0
...
replace private/user/repo => private.server/user/repo.git v1.0.0
From what I remember on Windows the search order for a dll is:
C:\windows\system32 or c:\windows\SysWOW64
(for 32-bit process on 64-bit box).Path
environment variableIn addition I'd check the dependencies of the DLL, the dependency walker provided with Visual Studio can help you out here, it can also be downloaded for free: http://www.dependencywalker.com
dataGridView1.DataSource = (from S in EE.Stagaire
join F in EE.Filiere on
S.IdFiliere equals F.IdFiliere
where S.Nom.StartsWith("A")
select new
{
ID=S.Id,
Name = S.Nom,
Prénon= S.Prenon,
Email=S.Email,
MoteDePass=S.MoteDePass,
Filiere = F.Filiere1
}).Take(1).ToList();
Best Practice - use singular. You have a list of items that make up an Enum. Using an item in the list sounds strange when you say Versions.1_0
. It makes more sense to say Version.1_0
since there is only one 1_0 Version.
I used a combination of Attila Fulop (Lea Verou) solution for modern browsers and Gavin Brock solution for old browsers as follows:
if (history.pushState) {
// IE10, Firefox, Chrome, etc.
window.history.pushState(null, null, '#' + id);
} else {
// IE9, IE8, etc
window.location.hash = '#!' + id;
}
As observed by Gavin Brock, to capture the id back you will have to treat the string (which in this case can have or not the "!") as follows:
id = window.location.hash.replace(/^#!?/, '');
Before that, I tried a solution similar to the one proposed by user706270, but it did not work well with Internet Explorer: as its Javascript engine is not very fast, you can notice the scroll increase and decrease, which produces a nasty visual effect.
The following adds elements to a list in a loop.
l<-c()
i=1
while(i<100) {
b<-i
l<-c(l,b)
i=i+1
}
To rephrase Jarret Meyer's answer, you need to change the parameter name to 'id' or add a route like this:
routes.MapRoute(
"ViewStockNext", // Route name
"Inventory/ViewStockNext/{firstItem}", // URL with parameters
new { controller = "Inventory", action = "ViewStockNext" } // Parameter defaults
);
The reason is the default route only looks for actions with no parameter or a parameter called 'id'.
Edit: Heh, nevermind Jarret added a route example after posting.
Step 1: Add the submodule
git submodule add git://some_repository.git some_repository
Step 2: Fix the submodule to a particular commit
By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.
git checkout -b some_branch origin/some_branch
Now the submodule is fixed on the development branch instead of HEAD of master.
From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .
I couldn't get the first method to work, and I know this is an old topic, but this is what I ended up doing for a solution:
=IF(ISNA(MATCH(A1,B:B,0)),"Not Matched", A1)
Basically, MATCH A1 to Column B exactly (the 0 stands for match exactly to a value in Column B). ISNA tests for #N/A response which match will return if the no match is found. Finally, if ISNA is true, write "Not Matched" to the selected cell, otherwise write the contents of the matched cell.
Its working for me Perfectly.
SELECT NAME FROM TABLE_NAME WHERE NAME = 'test Name' COLLATE NOCASE
Add following dependency or download Gson jar file
implementation 'com.google.code.gson:gson:2.8.6'
Follow github repo for documentation and more.
Information provided by @Gord
As of September 2019 pywin32
is now available from PyPI and installs the latest version (currently version 224). This is done via the pip
command
pip install pywin32
If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx
is the version you require, e.g. 224
pip install pywin32==xxx
This differs to the pip
command below as that one uses pypiwin32
which currently installs an older (namely 223)
Browsing the docs I see no reason for these commands to work for all python3.x
versions, I am unsure on python2.7
and below so you would have to try them and if they do not work then the solutions below will work.
Probably now undesirable solutions but certainly still valid as of September 2019
There is no version of specific version ofwin32api
. You have to get the pywin32
module which currently cannot be installed via pip
. It is only available from this link at the moment.
https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/
The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python
version :)
EDIT
Since I posted my answer there are other alternatives to downloading the win32api
module.
It is now available to download through pip
using this command;
pip install pypiwin32
Also it can be installed from this GitHub repository as provided in comments by @Heath
In swift
yourLabel.intrinsicContentSize().width
I think this statement might do what you want.
INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);
I guess ch
is a declared as char
. Since char
is a primitive data type and not and object, you can't call any methof from it. You should use Character.isLetter(ch)
.
PHP foreach loop can be used with Indexed arrays
, Associative arrays
and Object public variables
.
In foreach loop, the first thing php does is that it creates a copy of the array which is to be iterated over. PHP then iterates over this new copy
of the array rather than the original one. This is demonstrated in the below example:
<?php
$numbers = [1,2,3,4,5,6,7,8,9]; # initial values for our array
echo '<pre>', print_r($numbers, true), '</pre>', '<hr />';
foreach($numbers as $index => $number){
$numbers[$index] = $number + 1; # this is making changes to the origial array
echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # showing data from the copied array
}
echo '<hr />', '<pre>', print_r($numbers, true), '</pre>'; # shows the original values (also includes the newly added values).
Besides this, php does allow to use iterated values as a reference to the original array value
as well. This is demonstrated below:
<?php
$numbers = [1,2,3,4,5,6,7,8,9];
echo '<pre>', print_r($numbers, true), '</pre>';
foreach($numbers as $index => &$number){
++$number; # we are incrementing the original value
echo 'Inside of the array = ', $index, ': ', $number, '<br />'; # this is showing the original value
}
echo '<hr />';
echo '<pre>', print_r($numbers, true), '</pre>'; # we are again showing the original value
Note: It does not allow original array indexes
to be used as references
.
Source: http://dwellupper.io/post/47/understanding-php-foreach-loop-with-examples
I recommend not using WebClient.DownloadString
. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM (
) incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!
Instead, this slight variation will work correctly with BOMs:
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
If you are verifying if a lock is applied on a table or not, try the below query.
SELECT resource_type, resource_associated_entity_id,
request_status, request_mode,request_session_id,
resource_description, o.object_id, o.name, o.type_desc
FROM sys.dm_tran_locks l, sys.objects o
WHERE l.resource_associated_entity_id = o.object_id
and resource_database_id = DB_ID()
Last revision merged from trunk to branch can be found by running this command inside the working copy directory:
svn log -v --stop-on-copy
Here is one way to test which YAML implementation the user has selected on the virtualenv (or the system) and then define load_yaml_file
appropriately:
load_yaml_file = None
if not load_yaml_file:
try:
import yaml
load_yaml_file = lambda fn: yaml.load(open(fn))
except:
pass
if not load_yaml_file:
import commands, json
if commands.getstatusoutput('ruby --version')[0] == 0:
def load_yaml_file(fn):
ruby = "puts YAML.load_file('%s').to_json" % fn
j = commands.getstatusoutput('ruby -ryaml -rjson -e "%s"' % ruby)
return json.loads(j[1])
if not load_yaml_file:
import os, sys
print """
ERROR: %s requires ruby or python-yaml to be installed.
apt-get install ruby
OR
apt-get install python-yaml
OR
Demonstrate your mastery of Python by using pip.
Please research the latest pip-based install steps for python-yaml.
Usually something like this works:
apt-get install epel-release
apt-get install python-pip
apt-get install libyaml-cpp-dev
python2.7 /usr/bin/pip install pyyaml
Notes:
Non-base library (yaml) should never be installed outside a virtualenv.
"pip install" is permanent:
https://stackoverflow.com/questions/1550226/python-setup-py-uninstall
Beware when using pip within an aptitude or RPM script.
Pip might not play by all the rules.
Your installation may be permanent.
Ruby is 7X faster at loading large YAML files.
pip could ruin your life.
https://stackoverflow.com/questions/46326059/
https://stackoverflow.com/questions/36410756/
https://stackoverflow.com/questions/8022240/
Never use PyYaml in numerical applications.
https://stackoverflow.com/questions/30458977/
If you are working for a Fortune 500 company, your choices are
1. Ask for either the "ruby" package or the "python-yaml"
package. Asking for Ruby is more likely to get a fast answer.
2. Work in a VM. I highly recommend Vagrant for setting it up.
""" % sys.argv[0]
os._exit(4)
# test
import sys
print load_yaml_file(sys.argv[1])
Under use strict
, say:
(my $new = $original) =~ s/foo/bar/;
instead.
To calculate the distance you need signal strength and frequency of the signal. Here is the java code:
public double calculateDistance(double signalLevelInDb, double freqInMHz) {
double exp = (27.55 - (20 * Math.log10(freqInMHz)) + Math.abs(signalLevelInDb)) / 20.0;
return Math.pow(10.0, exp);
}
The formula used is:
distance = 10 ^ ((27.55 - (20 * log10(frequency)) + signalLevel)/20)
Example: frequency = 2412MHz, signalLevel = -57dbm, result = 7.000397427391188m
This formula is transformed form of Free Space Path Loss(FSPL) formula. Here the distance is measured in meters and the frequency - in megahertz. For other measures you have to use different constant (27.55). Read for the constants here.
For more information read here.
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
You could create a user form:
It is happened to me with laravel 5.1 on php-7 when I was running bunch of unitests.
The solution was - to change memory_limit in php.ini but it should be correct one. So you need one responsible for server, located there:
/etc/php/7.0/cli/php.ini
so you need a line with
memory_limit
After that you need to restart php service
sudo service php7.0-fpm restart
to check if it was changed successfully I used command line to run this:
php -i
the report contained following line
memory_limit => 2048M => 2048M
Now test cases are fine.
If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
Also see this SO thread: Open directory dialog
Why does it have to be encoded? A request looks like this:
GET /url HTTP/1.1
(Ignoring headers)
There are 3 fields separated by a white space. If you put a space in your url:
GET /url end_url HTTP/1.1
You know have 4 fields, the HTTP server will tell you it is an invalid request.
GET /url%20end_url HTTP/1.1
3 fields => valid
Note: in the query string (after ?), a space is usually encoded as a +
GET /url?var=foo+bar HTTP/1.1
rather than
GET /url?var=foo%20bar HTTP/1.1
I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.
git add .
git commit -m "some comments"
git push --set-upstream origin master
I wonder why String.prototype.concat
is not getting any love. In my tests (assuming you already have an array of strings), it outperforms all other methods.
Test code:
const numStrings = 100;
const strings = [...new Array(numStrings)].map(() => Math.random().toString(36).substring(6));
const concatReduce = (strs) => strs.reduce((a, b) => a + b);
const concatLoop = (strs) => {
let result = ''
for (let i = 0; i < strings.length; i++) {
result += strings[i];
}
return result;
}
// Case 1: 52,570 ops/s
concatLoop(strings);
// Case 2: 96,450 ops/s
concatReduce(strings)
// Case 3: 138,020 ops/s
strings.join('')
// Case 4: 169,520 ops/s
''.concat(...strings)
Here is a non-numpy solution:
>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]
% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;
I looked for a C/C++ API for Google Voice for quite a while and never found anything close (the closest was a C# API). Since I really needed it, I decided to just write one myself:
http://github.com/mastermind202/GoogleVoice
I hope others find it useful. Feedback and suggestions welcome.
using flexbox:
h2 {
display: flex;
align-items: center;
}
h2 span {
content:"";
flex: 1 1 auto;
border-top: 1px solid #000;
}
html:
<h2>Title <span></span></h2>
Bubble-sort (or, safer yet, bi-directional bubble sort) is likely ideal for mostly sorted lists, though I bet a tweaked comb-sort (with a much lower initial gap size) would be a little faster when the list wasn't quite as perfectly sorted. Comb sort degrades to bubble-sort.
IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:
<?php
// First Array To Compare
$a1 = array('foo','bar','c');
// Target Array
$b1 = array('foo','bar');
// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
if (!in_array($x,$b1)) {
$b=false;
}
};
// Actual Test on array (can be repeated with others, but guard
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);
This relies on a closure; comparison function can become much more powerful. Good luck!
On Windows you can have in your PATH
PATH = ...;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\; ...
remove it from PATH env, then
npm install -g typescript@latest
it worked for me to solve the
"TypeScript error TS1005: ';' expected"
See also how to update TypeScript to latest version with npm?
Just add water style="display:none";
to the <div>
Fiddles I say: http://jsfiddle.net/krY56/13/
jQuery:
function toggler(divId) {
$("#" + divId).toggle();
}
Preferred to have a CSS Class .hidden
.hidden {
display:none;
}
This query will use index if you have it for signup_date
field
SELECT users.id, DATE_FORMAT(users.signup_date, '%Y-%m-%d')
FROM users
WHERE signup_date >= CURDATE() && signup_date < (CURDATE() + INTERVAL 1 DAY)
I had a similar issue with 50,000 rdf/xml files in 5,000 directories (the Project Gutenberg catalog file). I solved it with riot (in the jena distribution)
the directory is cache/epub/NN/nn.rdf (where NN is a number)
in the directory above the directory where all the files are, i.e. in cache
riot epub/*/*.rdf --output=turtle > allTurtle.ttl
This produces possibly many warnings but the result is in a format which can be loaded into jena (using the fuseki web interface).
surprisingly simple (at least in this case).
$str = 'abcdef';
echo $str[0]; // a
The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.
this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;
Use this query:
ALTER TABLE tablename ADD columname DATATYPE(size);
And here is an example:
ALTER TABLE Customer ADD LastName VARCHAR(50);
This annotation is commonly used to eliminate NullPointerExceptions
. @Nullable
says that this parameter might be null
. A good example of such behaviour can be found in Google Guice. In this lightweight dependency injection framework you can tell that this dependency might be null
. If you would try to pass null
without an annotation the framework would refuse to do it's job.
What is more @Nullable
might be used with @NotNull
annotation. Here you can find some tips on how to use them properly. Code inspection in IntelliJ checks the annotations and helps to debug the code.
I had the exact same message as displayed in the question. I have tried many suggestions with little luck. I was about to install WAMP (I'm on Windows) and was about to uninstall MySql 8.0 first, when I noticed a program included in the installation: 'MySQL Installer - Community' so I tried that. With this installer I set up a new connection, added password to root, added another user with password, set my choice of locations for all logs and ran the install. The result was that it now totally works.
os.chdir()
is the Pythonic version of cd
.
there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.
I haven't seen anybody use this method, but it worked for me and is short and sweet:
int num = 5542;
String number = String.valueOf(num);
for(int i = 0; i < number.length(); i++) {
int j = Character.digit(number.charAt(i), 10);
System.out.println("digit: " + j);
}
This will output:
digit: 5
digit: 5
digit: 4
digit: 2
I had the same issue today. I solve this problem by removing any PATH
in .bashrc
for older rvm
.
You can just use nextLine();
as pause
import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);
void Read()
{
System.out.print("Press any key to continue . . . ");
scan.nextLine();
}
However any button you press except Enter
means you will have to press Enter after that but I found it better than scan.next();
You can use the WinAPI to get the date and time, this method is specific to Windows, but if you are targeting Windows only, or are already using the WinAPI then this is definitly a possibility1:
You can get both the time and date by using the SYSTEMTIME
struct
. You also need to call one of two functions (either GetLocalTime()
or GetSystemTime()
) to fill out the struct.
GetLocalTime()
will give you the time and date specific to your time zone.
GetSystemTime()
will give you the time and date in UTC.
The SYSTEMTIME
struct
has the following members:
wYear
, wMonth
, wDayOfWeek
, wDay
, wHour
, wMinute
, wSecond
and wMilliseconds
You then need to just access the struct in the regular way
Actual example code:
#include <windows.h> // use to define SYSTEMTIME , GetLocalTime() and GetSystemTime()
#include <stdio.h> // For printf() (could otherwise use WinAPI equivalent)
int main(void) { // Or any other WinAPI entry point (e.g. WinMain/wmain)
SYSTEMTIME t; // Declare SYSTEMTIME struct
GetLocalTime(&t); // Fill out the struct so that it can be used
// Use GetSystemTime(&t) to get UTC time
printf("Year: %d, Month: %d, Day: %d, Hour: %d, Minute:%d, Second: %d, Millisecond: %d", t.wYear, t.wMonth, t.wDay, t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); // Return year, month, day, hour, minute, second and millisecond in that order
return 0;
}
(Coded for simplicity and clarity, see the original answer for a better formatted method)
The output will be something like this:
Year: 2018, Month: 11, Day: 24, Hour: 12, Minute:28, Second: 1, Millisecond: 572
Useful References:
All the WinAPI documentation (most already listed above):
An extremely good beginners tutorial on this subject by Zetcode:
Simple operations with datetime on Codeproject:
1: As mentioned in the comments in Ori Osherov's answer ("Given that OP started with date +%F, they're almost certainly not using Windows. – melpomene Sep 9 at 22:17
") the OP is not using Windows, however since this question has no platform specific tag (nor does it mention anywhere that the answer should be for that particular system), and is one of the top results when Googling "get time in c" both answers belong here, some users searching for an answer to this question may be on Windows and therefore will be useful to them.
UPDATE t
SET cumulative_sum = (
SELECT SUM(x.count)
FROM t x
WHERE x.id <= t.id
)
You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.
I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.
The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.
Overall application stages are :
{
fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
if (fileExtension.equalsIgnoreCase("xlsx")) {
workbook = createWorkbook(openOPCPackage(inputSheetFile));
} else {
workbook =
createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
}
sheet = workbook.getSheetAt(0);
}
{
Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();
//skip a header
if (rowIterator.hasNext()) {
rowIterator.next();
}
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
// inserting rows
}
}
Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).
Used pattern :
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"
Used reference file:
'<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>'
Example for Input:
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
Markit On Demand provides a set of free financial APIs for playing around with. Looks like there is a stock quote API, a stock ticker/company search and a charting API available. Look at http://dev.markitondemand.com
Enable edit and Continue only work run IIS Express. Don't work in Local ISS or External Host.
I was working with a list of toasts (alert messages), List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:
var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
var command = entry.AlertStyle;
var message = entry.Message;
if (command === "danger") { command = "error"; }
toastr[command](message);
});
The answer on modifying was correct. Yet, I think it should be mentioned that /var/lib/jenkins/config.xml
looks something like this if you have activated "Project-based Matrix Authorization Strategy". Deleting /var/lib/jenkins/config.xml
and restarting jenkins also does the trick. I also deleted the users in /var/lib/jenkins/users
to start from scratch.
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
<permission>hudson.model.Computer.Configure:jenkins-admin</permission>
<permission>hudson.model.Computer.Connect:jenkins-admin</permission>
<permission>hudson.model.Computer.Create:jenkins-admin</permission>
<permission>hudson.model.Computer.Delete:jenkins-admin</permission>
<permission>hudson.model.Computer.Disconnect:jenkins-admin</permission>
<!-- if this is missing for your user and it is the only one, bad luck -->
<permission>hudson.model.Hudson.Administer:jenkins-admin</permission>
<permission>hudson.model.Hudson.Read:jenkins-admin</permission>
<permission>hudson.model.Hudson.RunScripts:jenkins-admin</permission>
<permission>hudson.model.Item.Build:jenkins-admin</permission>
<permission>hudson.model.Item.Cancel:jenkins-admin</permission>
<permission>hudson.model.Item.Configure:jenkins-admin</permission>
<permission>hudson.model.Item.Create:jenkins-admin</permission>
<permission>hudson.model.Item.Delete:jenkins-admin</permission>
<permission>hudson.model.Item.Discover:jenkins-admin</permission>
<permission>hudson.model.Item.Read:jenkins-admin</permission>
<permission>hudson.model.Item.Workspace:jenkins-admin</permission>
<permission>hudson.model.View.Configure:jenkins-admin</permission>
<permission>hudson.model.View.Create:jenkins-admin</permission>
<permission>hudson.model.View.Delete:jenkins-admin</permission>
<permission>hudson.model.View.Read:jenkins-admin</permission>
</authorizationStrategy>
The easiest way to freeze the UI would be to make the AJAX call synchronous.
Usually synchronous AJAX calls defeat the purpose of using AJAX because it freezes the UI, but if you want to prevent the user from interacting with the UI, then do it.
You should use > or < and == here. So the solution would be:
list.sort(function(item1, item2) {
var val1 = item1.attr,
val2 = item2.attr;
if (val1 == val2) return 0;
if (val1 > val2) return 1;
if (val1 < val2) return -1;
});
Just store the index generated in a variable, and then access the array using this varaible:
int idx = new Random().nextInt(fruits.length);
String random = (fruits[idx]);
P.S. I usually don't like generating new Random
object per randoization - I prefer using a single Random
in the program - and re-use it. It allows me to easily reproduce a problematic sequence if I later find any bug in the program.
According to this approach, I will have some variable Random r
somewhere, and I will just use:
int idx = r.nextInt(fruits.length)
However, your approach is OK as well, but you might have hard time reproducing a specific sequence if you need to later on.
You can't wait()
on an object unless the current thread owns that object's monitor. To do that, you must synchronize
on it:
class Runner implements Runnable
{
public void run()
{
try
{
synchronized(Main.main) {
Main.main.wait();
}
} catch (InterruptedException e) {}
System.out.println("Runner away!");
}
}
The same rule applies to notify()
/notifyAll()
as well.
The Javadocs for wait()
mention this:
This method should only be called by a thread that is the owner of this object's monitor. See the
Throws:notify
method for a description of the ways in which a thread can become the owner of a monitor.
IllegalMonitorStateException
– if the current thread is not the owner of this object's monitor.
And from notify()
:
A thread becomes the owner of the object's monitor in one of three ways:
- By executing a synchronized instance method of that object.
- By executing the body of a
synchronized
statement that synchronizes on the object.- For objects of type
Class
, by executing a synchronized static method of that class.
Replace '\n'
with "\n"
. The escape sequence is not recognized when you use '
.
See the manual.
For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen
should get "wb", not "w").
You can do it for any Java char using the one liner here:
System.out.println( "\\u" + Integer.toHexString('÷' | 0x10000).substring(1) );
But it's only going to work for the Unicode characters up to Unicode 3.0, which is why I precised you could do it for any Java char.
Because Java was designed way before Unicode 3.1 came and hence Java's char primitive is inadequate to represent Unicode 3.1 and up: there's not a "one Unicode character to one Java char" mapping anymore (instead a monstrous hack is used).
So you really have to check your requirements here: do you need to support Java char or any possible Unicode character?
Ah, the dreaded loose comparison operator strikes again. Never use it. Always use strict comparison, === or !== instead.
Bonus fact: 0 == ''
You can use a simple regex like this:
public static string StripHTML(string input)
{
return Regex.Replace(input, "<.*?>", String.Empty);
}
Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)
Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?
I will start my answer saying that most of previous answers were perfectly good answers at the time of writing them. So, thank you to them who wrote them.
Now, you can also use String Interpolation for same solution.
Edit: Adding this explanation after receiving a perfectively valid constructive comment from Heretic Monkey. I have preferred to use .ToString whenever I had need to convert an integer to string and not add the result to any other string. And, I have preferred to use interpolation whenever I had need to combine string(s) and an integer, like in below examples.
i.ToString("00")
01
i.ToString("000")
001
i.ToString("0000")
0001
$"Prefix_{i:00}"
Prefix_01
$"Prefix_{i:000}"
Prefix_001
$"Prefix_{i:0000}_Suffix"
Prefix_0001_Suffix
Let's assume you have such history
---o---o---o---M---W---x-------x-------*
/
---A---B
Where A, B failed commits and W - is revert of M
So before I start fixing found problems I do cherry-pick of W commit to my branch
git cherry-pick -x W
Then I revert W commit on my branch
git revert W
After I can continue fixing.
The final history could look like:
---o---o---o---M---W---x-------x-------*
/ /
---A---B---W---W`----------C---D
When I send a PR it will clearly shows that PR is undo revert and adds some new commits.
Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler
, which defines a method that is invoked when a proxy method is invoked.
You create them by using the call
Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
The arguments are:
classLoader
. Once the class is generated, it is loaded with this class loader.interfaces
. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.invocationHandler
. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler
. When a method from any of the supported interfaces, or hashCode
, equals
, or toString
, is invoked, the method invoke
is invoked on the handler, passing the Method
object for the method to be invoked and the arguments passed.For more on this, see the documentation for the Proxy
class.
Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.
It is a generic type parameter, see Generics documentation.
T
is not a reserved keyword. T
, or any given name, means a type parameter. Check the following method (just as a simple example).
T GetDefault<T>()
{
return default(T);
}
Note that the return type is T
. With this method you can get the default value of any type by calling the method as:
GetDefault<int>(); // 0
GetDefault<string>(); // null
GetDefault<DateTime>(); // 01/01/0001 00:00:00
GetDefault<TimeSpan>(); // 00:00:00
.NET uses generics in collections, ... example:
List<int> integerList = new List<int>();
This way you will have a list that only accepts integers, because the class is instancited with the type T
, in this case int
, and the method that add elements is written as:
public class List<T> : ...
{
public void Add(T item);
}
Some more information about generics.
You can limit the scope of the type T
.
The following example only allows you to invoke the method with types that are classes:
void Foo<T>(T item) where T: class
{
}
The following example only allows you to invoke the method with types that are Circle
or inherit from it.
void Foo<T>(T item) where T: Circle
{
}
And there is new()
that says you can create an instance of T
if it has a parameterless constructor. In the following example T
will be treated as Circle
, you get intellisense...
void Foo<T>(T item) where T: Circle, new()
{
T newCircle = new T();
}
As T
is a type parameter, you can get the object Type
from it. With the Type
you can use reflection...
void Foo<T>(T item) where T: class
{
Type type = typeof(T);
}
As a more complex example, check the signature of ToDictionary
or any other Linq method.
public static Dictionary<TKey, TSource> ToDictionary<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector);
There isn't a T
, however there is TKey
and TSource
. It is recommended that you always name type parameters with the prefix T
as shown above.
You could name TSomethingFoo
if you want to.
Using category or extension to make our life a bit easier.
extension String {
func lines() -> [String] {
var lines = [String]()
self.enumerateLines { (line, stop) -> () in
lines.append(line)
}
return lines
}
}
// then
for line in string.lines() {
// do the right thing
}
After trying a lot of methods, I found out, to get the time in millis at GMT you need to create two separate SimpleDateFormat
objects, one for formatting in GMT and another one for parsing.
Here is the code:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = new Date();
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date dateTime= dateParser.parse(format.format(date));
long gmtMilliSeconds = dateTime.getTime();
This works fine. :)
System.out.println(array.toString());
should be:
System.out.println(Arrays.toString(array));
I'm putting this in a new answer because no linebreaks / codeblocks in comments. I assume you want those nans to turn into a blank string? I couldn't find a nice way to do this, only do the ugly method:
s = pd.Series([1001.,1002.,None])
a = s.loc[s.isnull()].fillna('')
b = s.loc[s.notnull()].astype(int).astype(str)
result = pd.concat([a,b])
If, like me, you had dynamically created buttons on your page, the
$("#your-bs-button's-id").on("click", function(event) {
or
$(".your-bs-button's-class").on("click", function(event) {
methods won't work because they only work on current elements (not future elements). Instead you need to reference a parent item that existed at the initial loading of the web page.
$(document).on("click", "#your-bs-button's-id", function(event) {
or more generally
$("#pre-existing-element-id").on("click", ".your-bs-button's-class", function(event) {
There are many other references to this issue on stack overflow here and here.
An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.
The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080
), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host
) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).
They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.
Just because it’s a really useful paper, here are some other figures. Please download it for full access.
Taking a look at Disk I/O:
Now looking at CPU overhead:
Now some examples of memory (read the paper for details, memory can be extra tricky):
In XML a line break is a normal character. You can do this:
<xml>
<text>some text
with
three lines</text>
</xml>
and the contents of <text>
will be
some text with three lines
If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n
won't work, on the other hand, because XML has no escape sequences*.
* Note that 

is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.
This is where neither 

nor things like \n
will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.
Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br>
tags to force line breaks on screen.
Here is a JavaScript function that inserts <br>
into a multi-line string:
function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }
Alternatively you can force line breaks at new line characters with CSS:
div.lines {
white-space: pre-line;
}
That code is invalid as you can only pass variables into language constructs. empty()
is a language construct.
You have to do this in two lines:
$result = array_intersect($people, $criminals);
$result = !empty($result);
I had this issue when animating some views and the app would go into background mode and come back. I handled it by setting a flag isActive. I set it to NO in
- (void)applicationWillResignActive:(UIApplication *)application
and YES in
- (void)applicationDidBecomeActive:(UIApplication *)application
and animate or not animate my views accordingly. Took care of the issue.
Check this out: http://qrdroid.com/web-masters.php
You can create a link in your web form, something like:
http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}
When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.
A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:
You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.
In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.
This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.
In case someone is using C# (or see Note about VB.NET below) and has reached this point, but is still stuck, please read on.
Joshua's answer helped me, but not all the way. You will notice Peter asked "Where would you get the button from?", but was unanswered.
The only way it worked for me was to do one of the following to add my event hander (after setting my DataGridView's DataSource to my DataTable and after adding the DataGridViewButtonColumn to the DataGridView):
Either:
dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
or:
dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);
And then add the handler method (either dataGridView1_CellClick or dataGridView1_CellContentClick) shown in the various answers above.
Note: VB.NET is different from C# in this respect, because we can simply add a Handles clause to our method's signature or issue an AddHandler statement as described in the Microsoft doc's "How to: Call an Event Handler in Visual Basic"
I've found that using OnTime
can be painful, particularly when:
This article by Chip Pearson was very illuminating. I prefer to use the Windows Timer now, instead of OnTime
.
I would have added this as a comment, but my reputation is not yet high enough.
Under version 4.5.4.1deb2ubuntu2, and I am guessing any other versions 4.5.x or newer. There is no need to modify the config.inc.php file at all. Instead go one more directory down conf.d.
Create a new file with the '.php' extension and add the lines. This is a better modularized approach and isolates each remote database server access information.
I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.
Here is the code :
div:has(>input[disabled=disabled]) {
display: none;
}
Maybe it could help some of you.
The solution is to use the same IP and Port number in both client and server. Try, in client to use TCP_IP = 'write the ip number here' TCP_PORT = writ the port number here s.connect((TCP_IP, TCP_PORT))
Your issue is that your selector is for an anchor element <a>
. You are treating the <a>
tag as if it represents the page which is not the case.
$('head')
will work as long as this selector is being executed by the page that needs the css.
Why not simply add the css file to the page in question. Any particular reason to attempt this dynamically from another page? I am not even familiar with a way to inject css to remote pages like this ... seems like it would be a major security hole.
ADDENDUM to your reasoning:
Then you should simply pass a parameter to the page, read it using javascript, and then do whatever is needed based on the parameter.
It's actually really easy. Highlight the DATE column and make sure that its set as date in Excel. Highlight everything you want to change, Then go to [DATA]>[SORT]>[COLUMN] and set sorting by date. Hope it helps.
Login into your server using a shell program like putty.
Type in the following command on the command line
zcat DB_File_Name.sql.gz | mysql -u username -p Target_DB_Name
where
DB_File_Name.sql.gz
= full path of the sql.gz file to be imported
username
= your mysql username
Target_DB_Name
= database name where you want to import the database
When you hit enter in the command line, it will prompt for password. Enter your MySQL password.
You are done!
The other answers here presuppose that you have a regex engine which supports non-greedy matching, which is an extension introduced in Perl 5 and widely copied to other modern languages; but it is by no means ubiquitous.
Many older or more conservative languages and editors only support traditional regular expressions, which have no mechanism for controlling greediness of the repetition operator *
- it always matches the longest possible string.
The trick then is to limit what it's allowed to match in the first place. Instead of .*
you seem to be looking for
[^>]*
which still matches as many of something as possible; but the something is not just .
"any character", but instead "any character which isn't >
".
Depending on your application, you may or may not want to enable an option to permit "any character" to include newlines.
Even if your regular expression engine supports non-greedy matching, it's better to spell out what you actually mean. If this is what you mean, you should probably say this, instead of rely on non-greedy matching to (hopefully, probably) Do What I Mean.
For example, a regular expression with a trailing context after the wildcard like .*?><br/>
will jump over any nested >
until it finds the trailing context (here, ><br/>
) even if that requires straddling multiple >
instances and newlines if you let it, where [^>]*><br/>
(or even [^\n>]*><br/>
if you have to explicitly disallow newline) obviously can't and won't do that.
Of course, this is still not what you want if you need to cope with <img title="quoted string with > in it" src="other attributes"> and perhaps <img title="nested tags">
, but at that point, you should finally give up on using regular expressions for this like we all told you in the first place.
You have to repeat your expression everywhere you want to use it:
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Replace(Postcode, ' ', '') LIKE 'NW101%'
or you can make it a subquery
select P
from (
SELECT Replace(Postcode, ' ', '') AS P
FROM Contacts
) t
WHERE P LIKE 'NW101%'
As long and your input
and label
elements are associated by their id
and for
attributes, you should be able to do something like this:
$('.input').each(function() {
$this = $(this);
$label = $('label[for="'+ $this.attr('id') +'"]');
if ($label.length > 0 ) {
//this input has a label associated with it, lets do something!
}
});
If for
is not set then the elements have no semantic relation to each other anyway, and there is no benefit to using the label tag in that instance, so hopefully you will always have that relationship defined.
I took the idea from @antron and implemented it differently: generating a true enum class.
This implementation meets all the requirements listed in original question but currently has only one real limitation: it assumes the enum values are either not provided or, if provided, must start with 0 and go up sequentially without gaps.
This is not an intrinsic limitation - simply that I don't use ad-hoc enum values. If this is needed, one can replace vector lookup with traditional switch/case implementation.
The solution uses some c++17 for inline variables but this can be easily avoided if needed. It also uses boost:trim because of simplicity.
Most importantly, it takes only 30 lines of code and no black magic macros. The code is below. It's meant to be put in header and included in multiple compilation modules.
It can be used the same way as was suggested earlier in this thread:
ENUM(Channel, int, Red, Green = 1, Blue)
std::out << "My name is " << Channel::Green;
//prints My name is Green
Pls let me know if this is useful and how it can be improved further.
#include <boost/algorithm/string.hpp>
struct EnumSupportBase {
static std::vector<std::string> split(const std::string s, char delim) {
std::stringstream ss(s);
std::string item;
std::vector<std::string> tokens;
while (std::getline(ss, item, delim)) {
auto pos = item.find_first_of ('=');
if (pos != std::string::npos)
item.erase (pos);
boost::trim (item);
tokens.push_back(item);
}
return tokens;
}
};
#define ENUM(EnumName, Underlying, ...) \
enum class EnumName : Underlying { __VA_ARGS__, _count }; \
struct EnumName ## Support : EnumSupportBase { \
static inline std::vector<std::string> _token_names = split(#__VA_ARGS__, ','); \
static constexpr const char* get_name(EnumName enum_value) { \
int index = (int)enum_value; \
if (index >= (int)EnumName::_count || index < 0) \
return "???"; \
else \
return _token_names[index].c_str(); \
} \
}; \
inline std::ostream& operator<<(std::ostream& os, const EnumName & es) { \
return os << EnumName##Support::get_name(es); \
}
I found the answer:
$mail->AddEmbeddedImage('img/2u_cs_mini.jpg', 'logo_2u');
and on the <img>
tag put src='cid:logo_2u'
UPDATE: This is only true if you use ONLYOFFICE instead of MS Excel.
There is actually a flow in all answers provided here and also in the accepted one. The flow is that whenever you have an empty cell in excel and copy that, in the clipboard you have 2 tab chars next to each other, so after splitting you get one additional item in array, which then appears as an extra cell in that row and moves all other cells by one. So to avoid that you basically need to replace all double tab (tabs next to each other only) chars in a string with one tab char and only then split it.
An updated version of @userfuser's jsfiddle is here to fix that issue by filtering pasted data with removeExtraTabs
http://jsfiddle.net/sTX7y/794/
function removeExtraTabs(string) {
return string.replace(new RegExp("\t\t", 'g'), "\t");
}
function generateTable() {
var data = removeExtraTabs($('#pastein').val());
var rows = data.split("\n");
var table = $('<table />');
for (var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for (var x in cells) {
row.append('<td>' + cells[x] + '</td>');
}
table.append(row);
}
// Insert into DOM
$('#excel_table').html(table);
}
$(document).ready(function() {
$('#pastein').on('paste', function(event) {
$('#pastein').on('input', function() {
generateTable();
$('#pastein').off('input');
})
})
})
Why involve Notepad?
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
Debugging build step failures is indeed very annoying.
The best solution I have found is to make sure that each step that does real work succeeds, and adding a check after those that fails. That way you get a committed layer that contains the outputs of the failed step that you can inspect.
A Dockerfile, with an example after the # Run DB2 silent installer
line:
#
# DB2 10.5 Client Dockerfile (Part 1)
#
# Requires
# - DB2 10.5 Client for 64bit Linux ibm_data_server_runtime_client_linuxx64_v10.5.tar.gz
# - Response file for DB2 10.5 Client for 64bit Linux db2rtcl_nr.rsp
#
#
# Using Ubuntu 14.04 base image as the starting point.
FROM ubuntu:14.04
MAINTAINER David Carew <[email protected]>
# DB2 prereqs (also installing sharutils package as we use the utility uuencode to generate password - all others are required for the DB2 Client)
RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y sharutils binutils libstdc++6:i386 libpam0g:i386 && ln -s /lib/i386-linux-gnu/libpam.so.0 /lib/libpam.so.0
RUN apt-get install -y libxml2
# Create user db2clnt
# Generate strong random password and allow sudo to root w/o password
#
RUN \
adduser --quiet --disabled-password -shell /bin/bash -home /home/db2clnt --gecos "DB2 Client" db2clnt && \
echo db2clnt:`dd if=/dev/urandom bs=16 count=1 2>/dev/null | uuencode -| head -n 2 | grep -v begin | cut -b 2-10` | chgpasswd && \
adduser db2clnt sudo && \
echo '%sudo ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers
# Install DB2
RUN mkdir /install
# Copy DB2 tarball - ADD command will expand it automatically
ADD v10.5fp9_linuxx64_rtcl.tar.gz /install/
# Copy response file
COPY db2rtcl_nr.rsp /install/
# Run DB2 silent installer
RUN mkdir /logs
RUN (/install/rtcl/db2setup -t /logs/trace -l /logs/log -u /install/db2rtcl_nr.rsp && touch /install/done) || /bin/true
RUN test -f /install/done || (echo ERROR-------; echo install failed, see files in container /logs directory of the last container layer; echo run docker run '<last image id>' /bin/cat /logs/trace; echo ----------)
RUN test -f /install/done
# Clean up unwanted files
RUN rm -fr /install/rtcl
# Login as db2clnt user
CMD su - db2clnt
Some advantages:
First off, that's not JSON. It's a JavaScript object literal. JSON is a string representation of data, that just so happens to very closely resemble JavaScript syntax.
Second, you have an object. They are unsorted. The order of the elements cannot be guaranteed. If you want guaranteed order, you need to use an array. This will require you to change your data structure.
One option might be to make your data look like this:
var json = [{
"name": "user1",
"id": 3
}, {
"name": "user2",
"id": 6
}, {
"name": "user3",
"id": 1
}];
Now you have an array of objects, and we can sort it.
json.sort(function(a, b){
return a.id - b.id;
});
The resulting array will look like:
[{
"name": "user3",
"id" : 1
}, {
"name": "user1",
"id" : 3
}, {
"name": "user2",
"id" : 6
}];
Google treat Gmail accounts differently depending on the available user information, probably to curb spammers.
I couldn't use SMTP until I did the phone verification. Made another account to double check and I was able to confirm it.
I have been trying to do this for a while also. Here is what I do now. Highlight the email you want to create as a file. Click on Create. Hover over Special, then click on Link message. This will open up a new tab for the link. At the bottom of the message is a small yellow piece of paper icon. Copy this icon and paste into your message like you would any other file. It is tiny, so I put a statement like "see email attachment ---->" in front of the icon. You might like this way. Not sure though.
As you see in an error UseCalls.java:27: error: cannot find symbol
return String.parseString(input);
there is no method parseString
in String
class. There is no need to parse it as long as JOptionPane.showInputDialog(prompt);
already returns a string.
Pure Java solution using Streams, works since Java 8.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
// ...
public static String inputStreamToString(InputStream is) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
}
As mentioned by Christoffer Hammarström below other answer it is safer to explicitly specify the Charset. I.e. The InputStreamReader constructor can be changes as follows:
new InputStreamReader(is, Charset.forName("UTF-8"))
Posting your HTML might help a bit. Instead, you can get the element first and then check if it is null or not and then ask for its value rather than just asking for the value directly without knowing if the element is visible on the HTML or not.
element1 = document.getElementById(id);
if(element1 != null)
{
//code to set the value variable.
}
I think the easiest way to do that is by using apache collections api - CollectionUtils.subtract(list1,list2) as long the lists are of the same type.
Try:
SELECT MEMBSHIP_ID
FROM user_payment
WHERE user_id=1
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);
Or:
SELECT MEMBSHIP_ID
FROM (
SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
FROM user_payment
WHERE user_id=1 )
WHERE rn = 1
I agree that it is not possible in general.
The only thing CSS3 can do (which helped in my case) is to select elements that have no children:
table td:empty
{
background-color: white;
}
Or have any children (including text):
table td:not(:empty)
{
background-color: white;
}
Many tricks work, but the Ajax request split the file name at 19 characters? Look at the output of the ajax request to see that:
The file name is okay to go into the href attribute, but the $(this).attr("href")
use
the text of the <a href='full/file/name' >
Split file name </a>
So the $(data).find("a:contains(.jpg)")
is not able to detect the extension.
I hope this is useful
To get left/right centering, then applying text-align: center
to the div
and margin: auto
to the p
.
For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div
Getting EXIF data from a JPEG image involves:
Another difference is that <import>
allows importing by referring to another namespace. <include>
only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.
For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.
Code sample of valid and invalid imports and includes:
Valid:
<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>
<xsd:include schemaLocation="classpath://mine.xsd"/>
Invalid:
<xsd:include namespace="some/name/space"/>
There are lots of great answers which discuss differences in the use cases for each function. None of the answer discuss the differences in performance. That is reasonable cause various functions expects various input and produces various output, yet most of them have a general common objective to evaluate by series/groups. My answer is going to focus on performance. Due to above the input creation from the vectors is included in the timing, also the apply
function is not measured.
I have tested two different functions sum
and length
at once. Volume tested is 50M on input and 50K on output. I have also included two currently popular packages which were not widely used at the time when question was asked, data.table
and dplyr
. Both are definitely worth to look if you are aiming for good performance.
library(dplyr)
library(data.table)
set.seed(123)
n = 5e7
k = 5e5
x = runif(n)
grp = sample(k, n, TRUE)
timing = list()
# sapply
timing[["sapply"]] = system.time({
lt = split(x, grp)
r.sapply = sapply(lt, function(x) list(sum(x), length(x)), simplify = FALSE)
})
# lapply
timing[["lapply"]] = system.time({
lt = split(x, grp)
r.lapply = lapply(lt, function(x) list(sum(x), length(x)))
})
# tapply
timing[["tapply"]] = system.time(
r.tapply <- tapply(x, list(grp), function(x) list(sum(x), length(x)))
)
# by
timing[["by"]] = system.time(
r.by <- by(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)
# aggregate
timing[["aggregate"]] = system.time(
r.aggregate <- aggregate(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)
# dplyr
timing[["dplyr"]] = system.time({
df = data_frame(x, grp)
r.dplyr = summarise(group_by(df, grp), sum(x), n())
})
# data.table
timing[["data.table"]] = system.time({
dt = setnames(setDT(list(x, grp)), c("x","grp"))
r.data.table = dt[, .(sum(x), .N), grp]
})
# all output size match to group count
sapply(list(sapply=r.sapply, lapply=r.lapply, tapply=r.tapply, by=r.by, aggregate=r.aggregate, dplyr=r.dplyr, data.table=r.data.table),
function(x) (if(is.data.frame(x)) nrow else length)(x)==k)
# sapply lapply tapply by aggregate dplyr data.table
# TRUE TRUE TRUE TRUE TRUE TRUE TRUE
# print timings
as.data.table(sapply(timing, `[[`, "elapsed"), keep.rownames = TRUE
)[,.(fun = V1, elapsed = V2)
][order(-elapsed)]
# fun elapsed
#1: aggregate 109.139
#2: by 25.738
#3: dplyr 18.978
#4: tapply 17.006
#5: lapply 11.524
#6: sapply 11.326
#7: data.table 2.686
There is a very useful module for formatting text (bold, underline, colors..) in Python. It uses curses
lib but it's very straight-forward to use.
An example:
from terminal import render
print render('%(BG_YELLOW)s%(RED)s%(BOLD)sHey this is a test%(NORMAL)s')
print render('%(BG_GREEN)s%(RED)s%(UNDERLINE)sAnother test%(NORMAL)s')
I wrote a simple module named colors.py to make this a little more pythonic:
import colors
with colors.pretty_output(colors.BOLD, colors.FG_RED) as out:
out.write("This is a bold red text")
with colors.pretty_output(colors.BG_GREEN) as out:
out.write("This output have a green background but you " +
colors.BOLD + colors.FG_RED + "can" + colors.END + " mix styles")
Even you can use like default value the value of another variable
having a file defvalue.sh
#!/bin/bash
variable1=$1
variable2=${2:-$variable1}
echo $variable1
echo $variable2
run ./defvalue.sh first-value second-value
output
first-value
second-value
and run ./defvalue.sh first-value
output
first-value
first-value
Use this tool (hosted here for free) to convert your curl command to equivalent Python requests code:
Example: This,
curl 'https://www.example.com/' -H 'Connection: keep-alive' -H 'Cache-Control: max-age=0' -H 'Origin: https://www.example.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Cookie: SESSID=ABCDEF' --data-binary 'Pathfinder' --compressed
Gets converted neatly to:
import requests
cookies = {
'SESSID': 'ABCDEF',
}
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'https://www.example.com',
'Accept-Encoding': 'gzip, deflate, br',
}
data = 'Pathfinder'
response = requests.post('https://www.example.com/', headers=headers, cookies=cookies, data=data)
Another solution is you could use a background image to mimic the look of a left border
You might need to tweak for IE (as per usual) but it's worth a shot if that's the design you are going for.
On the one hand, this has been answered. On the other hand, most of the answers require many lines of code. This Python answer does not require many lines of code, merely many lines of thought ^_^ :
div_round_up = lambda a, b: a // b if a % b == 0 else a // b + 1
def optimum_change(*coins):
wallet = [0 for i in range(0, len(coins) - 1)]
for j in range(0, len(wallet)):
target = coins[j + 1] - 1
target -= sum(wallet[i] * coins[i] for i in range(0, j))
wallet[j] = max(0, div_round_up(target, coins[j]))
return wallet
optimum_change(1, 5, 10, 25, 100)
# [4, 1, 2, 3]
This is a very simple rescaling algorithm that may perhaps break for inputs which I haven't considered yet, but I think it should be robust. It basically says, "to add a new coin type to the wallet, peek at the next coin type N, then add the amount of new coins necessary to make target = N - 1
." It calculates that you need at least ceil((target - wallet_value)/coin_value)
to do so, and does not check if this will also make every number in between. Notice that the syntax encodes the "from 0 to 99 cents" by appending the final number "100" since that yields the appropriate final target
.
The reason it does not check is something like, "if it can, it automatically will." Put more directly, once you do this step for a penny (value 1), the algorithm can "break" a nickel (value 5) into any subinterval 0 - 4. Once you do it for a nickel, the algorithm can now "break" a dime (value 10). And so on.
Of course, it does not require those particular inputs; you can use strange currencies too:
>>> optimum_change(1, 4, 7, 8, 100)
[3, 1, 0, 12]
Notice how it automatically ignores the 7 coin because it knows it can already "break" 8's with the change it has.
try:
gsub('\\$', '', '$5.00$')
Checkout the entry on the numpy example list. Here is the entry on .loadtxt()
>>> from numpy import *
>>>
>>> data = loadtxt("myfile.txt") # myfile.txt contains 4 columns of numbers
>>> t,z = data[:,0], data[:,3] # data is 2D numpy array
>>>
>>> t,x,y,z = loadtxt("myfile.txt", unpack=True) # to unpack all columns
>>> t,z = loadtxt("myfile.txt", usecols = (0,3), unpack=True) # to select just a few columns
>>> data = loadtxt("myfile.txt", skiprows = 7) # to skip 7 rows from top of file
>>> data = loadtxt("myfile.txt", comments = '!') # use '!' as comment char instead of '#'
>>> data = loadtxt("myfile.txt", delimiter=';') # use ';' as column separator instead of whitespace
>>> data = loadtxt("myfile.txt", dtype = int) # file contains integers instead of floats
My problem was my Target profile didn't have the proper code signing option selected:
Target Menu -> Code Signing -> Code Signing Identity
Choose "iPhone developer" then select the provisional profile you created.
It depends what kind of UUID you want.
The standard Java UUID
class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID
instances from long
, byte[]
or String
representations, and provide some appropriate accessors.)
The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.
For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.
Typing cd
will take you back to your home directory.
Whereas typing cd ..
will move you up only one directory (the direct parent of the current directory).
Let me explain a little more by my example.
Task: correct info, where abiturients (students about to leave secondary school) have submitted applications to university earlier, than they got school certificates (yes, they got certificates earlier, than they were issued (by certificate date specified). So, we will increase application submit date to fit certificate issue date.
Thus. next MySQL-like statement:
UPDATE applications a
JOIN (
SELECT ap.id, ab.certificate_issued_at
FROM abiturients ab
JOIN applications ap
ON ab.id = ap.abiturient_id
WHERE ap.documents_taken_at::date < ab.certificate_issued_at
) b
ON a.id = b.id
SET a.documents_taken_at = b.certificate_issued_at;
Becomes PostgreSQL-like in such a way
UPDATE applications a
SET documents_taken_at = b.certificate_issued_at -- we can reference joined table here
FROM abiturients b -- joined table
WHERE
a.abiturient_id = b.id AND -- JOIN ON clause
a.documents_taken_at::date < b.certificate_issued_at -- Subquery WHERE
As you can see, original subquery JOIN
's ON
clause have become one of WHERE
conditions, which is conjucted by AND
with others, which have been moved from subquery with no changes. And there is no more need to JOIN
table with itself (as it was in subquery).
The -std=c++14
flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y
. Using godbolt.org it appears that the earilest version to support -std=c++14
is GCC 4.9.0 or Clang 3.5.0
Actually you get promise
on $http.get
.
Try to use followed flow:
<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
<span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
<span>{{document.Name}}</span>
</li>
Where documents
is your array.
$scope.documents = [];
$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
result.data.forEach(function(val, i) {
$scope.documents.push(/* put data here*/);
});
}, function(error) {
alert(error.message);
});
This is an ultimate solution to set the border color of a TextBox:
public class BorderedTextBox : UserControl
{
TextBox textBox;
public BorderedTextBox()
{
textBox = new TextBox()
{
BorderStyle = BorderStyle.FixedSingle,
Location = new Point(-1, -1),
Anchor = AnchorStyles.Top | AnchorStyles.Bottom |
AnchorStyles.Left | AnchorStyles.Right
};
Control container = new ContainerControl()
{
Dock = DockStyle.Fill,
Padding = new Padding(-1)
};
container.Controls.Add(textBox);
this.Controls.Add(container);
DefaultBorderColor = SystemColors.ControlDark;
FocusedBorderColor = Color.Red;
BackColor = DefaultBorderColor;
Padding = new Padding(1);
Size = textBox.Size;
}
public Color DefaultBorderColor { get; set; }
public Color FocusedBorderColor { get; set; }
public override string Text
{
get { return textBox.Text; }
set { textBox.Text = value; }
}
protected override void OnEnter(EventArgs e)
{
BackColor = FocusedBorderColor;
base.OnEnter(e);
}
protected override void OnLeave(EventArgs e)
{
BackColor = DefaultBorderColor;
base.OnLeave(e);
}
protected override void SetBoundsCore(int x, int y,
int width, int height, BoundsSpecified specified)
{
base.SetBoundsCore(x, y, width, textBox.PreferredHeight, specified);
}
}
.NET and .NET Core are two different implementations of the .NET runtime. Both Core and Framework (but especially Framework) have different profiles that include larger or smaller (or just plain different) selections of the many APIs and assemblies Microsoft has created for .NET, depending on where they are installed and in what profile.
For example, there are some different APIs available in Universal Windows apps than in the "normal" Windows profile. Even on Windows, you might have the "Client" profile vs. the "Full" profile. Additionally, and there are other implementations (like Mono) that have their own sets of libraries.
.NET Standard is a specification for which sets of API libraries and assemblies must be available. An app written for .NET Standard 1.0 should be able to compile and run with any version of Framework, Core, Mono, etc., that advertises support for the .NET Standard 1.0 collection of libraries. Similar is true for .NET Standard 1.1, 1.5, 1.6, 2.0, etc. As long as the runtime provides support for the version of Standard targeted by your program, your program should run there.
A project targeted at a version of Standard will not be able to make use of features that are not included in that revision of the standard. This doesn't mean you can't take dependencies on other assemblies, or APIs published by other vendors (i.e.: items on NuGet). But it does mean that any dependencies you take must also include support for your version of .NET Standard. .NET Standard is evolving quickly, but it's still new enough, and cares enough about some of the smaller runtime profiles, that this limitation can feel stifling. (Note a year and a half later: this is starting to change, and recent .NET Standard versions are much nicer and more full-featured).
On the other hand, an app targeted at Standard should be able to be used in more deployment situations, since in theory it can run with Core, Framework, Mono, etc. For a class library project looking for wide distribution, that's an attractive promise. For a class library project used mainly for internal purposes, it may not be as much of a concern.
.NET Standard can also be useful in situations where the system administrator team is wanting to move from ASP.NET on Windows to ASP.NET for .NET Core on Linux for philosophical or cost reasons, but the Development team wants to continue working against .NET Framework in Visual Studio on Windows.
In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.
Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):
1. Add your Apple ID in Xcode
Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.
2. Click the General tab in the Project Navigator
3. Choose your Apple ID from the Team popup menu.
4. Connect your device and choose it in the scheme menu.
5. Click the Fix Issues button
If you get an error about the bundle name being invalid, change it to something unique.
6. Run your app
In Xcode, click the Build and run button.
7. Trust the app developer in the device settings
After running your app, you will get a security error because the app you want to run is not from the App Store.
On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.
8. Run your app on your device again.
That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.
None of these options show up for me. The way to paste data from Excel is as follows:
Add an extra column to the left of your spreadsheet data (if you don't have row numbers showing in PL/SQL Developer you may not have to have an extra empty column to the left).
Copy the rows of data from your spreadsheet including the empty column.
In PL/SQL Developer, open your table in edit mode. You can right-click the table name in the object browser and select Edit Data or write your own select statement that includes the rowid and click the lock icon. Be sure your columns are ordered the same as in your spreadsheet.
Here's the part that took me forever to figure out: click on the left side of the first empty row to highlight it. It will not work if you don't have the first empty row highlighted.
Paste as usual using Ctrl+V or right-click Paste.
I couldn't find this info anywhere when I needed it, so I wanted to be sure to post it.
@Navaneeth and @Antfish, no need to transform you can do like this also because in above solution only top border is visible so for inside curve you can use bottom border.
.box {_x000D_
width: 500px;_x000D_
height: 100px;_x000D_
border: solid 5px #000;_x000D_
border-color: transparent transparent #000 transparent;_x000D_
border-radius: 0 0 240px 50%/60px;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Don't forget about spaces:
source=""
samples=("")
if [ $1 = "country" ]; then
source="country"
samples="US Canada Mexico..."
else
echo "try again"
fi