You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
For me this simple command solved the problem:
sudo apt-get install postgresql postgresql-contrib libpq-dev python-dev
Then I can do:
pip install psycopg2
I'm sure there's a better way to achieve this and I would like to read about it, but a workaround I can think of is this:
rm
'ed directory to the original machine (ssh, ftp, whatever).pip uninstall
the package (should work again then).But, yes, I'd also love to hear about a decent solution for this situation.
I recommend that you try to use Postgres.app. (http://postgresapp.com)
This way you can easily turn Postgres on and off on your Mac.
Once you do, add the path to Postgres to your .profile
file by appending the following:
PATH="/Applications/Postgres.app/Contents/Versions/latest/bin:$PATH"
Only after you added Postgres to your path you can try to install psycopg2
either within a virtual environment (using pip) or into your global site packages.
You should put your model class before create_all()
call, like this:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(120), unique=True)
def __init__(self, username, email):
self.username = username
self.email = email
def __repr__(self):
return '<User %r>' % self.username
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
If your models are declared in a separate module, import them before calling create_all()
.
Say, the User
model is in a file called models.py
,
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql+psycopg2://login:pass@localhost/flask_app'
db = SQLAlchemy(app)
# See important note below
from models import User
db.create_all()
db.session.commit()
admin = User('admin', '[email protected]')
guest = User('guest', '[email protected]')
db.session.add(admin)
db.session.add(guest)
db.session.commit()
users = User.query.all()
print users
Important note: It is important that you import your models after initializing the db
object since, in your models.py
_you also need to import the db
object from this module.
I had the same error and it turned out to be a circular dependency between a module or class loaded by the settings and the settings module itself. In my case it was a middleware class which was named in the settings which itself tried to load the settings.
On Django 1.9, I tried django-admin runserver
and got the same error, but when I used python manage.py runserver
I got the intended result. This may solve this error for a lot of people!
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
Seems like you don't have permission to the Python folder. Try sudo chown -R $USER /Library/Python/2.7
Right, in Django 1.5 if DEBUG = False, configure ALLOWED_HOSTS, adding domains without the port number. example:
ALLOWED_HOSTS = ['localhost']
Use psycopg2-binary instead of psycopg2.
pip install psycopg2-binary
Or you will get the warning below:
UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi.
Reference: Psycopg 2.7.4 released | Psycopg
This is what helped me on Ubuntu if your python installed from Ubuntu installer. I did this after unsuccessfully trying 'apt-get install' and 'pip install':
In terminal:
sudo synaptic
then in synaptic searchfield write
psycopg2
choose
python-psycopg2
mark it for installation using mouse right-click and push 'apply'. Of course, if you don't have installed synaptic, then first do:
sudo apt-get install synaptic
sudo apt-get install libpq-dev
works for me on Ubuntu 15.4
This works for me in Ubuntu 12.04 and 15.10
if pip not installed:
sudo apt-get install python-pip
and then:
sudo apt-get update
sudo apt-get install libpq-dev python-dev
sudo pip install psycopg2
On Ubuntu, I had to delete /tmp/pip-build-root
.
New execute_values
method in Psycopg 2.7:
data = [(1,'x'), (2,'y')]
insert_query = 'insert into t (a, b) values %s'
psycopg2.extras.execute_values (
cursor, insert_query, data, template=None, page_size=100
)
The pythonic way of doing it in Psycopg 2.6:
data = [(1,'x'), (2,'y')]
records_list_template = ','.join(['%s'] * len(data))
insert_query = 'insert into t (a, b) values {}'.format(records_list_template)
cursor.execute(insert_query, data)
Explanation: If the data to be inserted is given as a list of tuples like in
data = [(1,'x'), (2,'y')]
then it is already in the exact required format as
the values
syntax of the insert
clause expects a list of records as in
insert into t (a, b) values (1, 'x'),(2, 'y')
Psycopg
adapts a Python tuple
to a Postgresql record
.
The only necessary work is to provide a records list template to be filled by psycopg
# We use the data list to be sure of the template length
records_list_template = ','.join(['%s'] * len(data))
and place it in the insert
query
insert_query = 'insert into t (a, b) values {}'.format(records_list_template)
Printing the insert_query
outputs
insert into t (a, b) values %s,%s
Now to the usual Psycopg
arguments substitution
cursor.execute(insert_query, data)
Or just testing what will be sent to the server
print (cursor.mogrify(insert_query, data).decode('utf8'))
Output:
insert into t (a, b) values (1, 'x'),(2, 'y')
I had this problem serving with Apache and found that using the absolute path to the sqlite3 db in my .env ////
as opposed to using the relative path ///
fixed the problem. All of the permissions and ownership mentioned above are necessary as well.
I was having this problem, the main reason was with 2 equal versions installed. One by postgres.app and one by HomeBrew.
If you choose to keep only the APP:
brew unlink postgresql
pip3 install psycopg2
$ sudo apt-get install libpq-dev
Year, this solve my problem. After execute this, do: pip install psycopg2
It's easy with rules:
CREATE RULE file_insert_defer AS ON INSERT TO file
WHERE (EXISTS ( SELECT * FROM file WHERE file.id = new.id)) DO INSTEAD NOTHING
But it fails with concurrent writes ...
It is an issue with bad sql execution which does not allow other queries to execute until the previous one gets suspended/rollback.
In PgAdmin4-4.24 there is an option of rollback, one can try this.
If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...
console.log($target); // jQuery object
$target.remove(); // remove target from the DOM
console.log($target); // $target still exists
Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)
$target = $();
console.log($target); // empty jQuery object
Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)
delete $target;
console.log($target); // error: $target is not defined
More reading: info about empty jQuery object, and info about delete
This is a solution that you can see in the vidios of the WWDC. You have to do a Gaussian Blur, so the first thing you have to do is to add a new .m and .h file with the code i'm writing here, then you have to make and screen shoot, use the desired effect and add it to your view, then your UITable UIView or what ever has to be transparent, you can play with applyBlurWithRadius, to archive the desired effect, this call works with any UIImage.
At the end the blured image will be the background and the rest of the controls above has to be transparent.
For this to work you have to add the next libraries:
Acelerate.framework,UIKit.framework,CoreGraphics.framework
I hope you like it.
Happy coding.
//Screen capture.
UIGraphicsBeginImageContext(self.view.bounds.size);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(c, 0, 0);
[self.view.layer renderInContext:c];
UIImage* viewImage = UIGraphicsGetImageFromCurrentImageContext();
viewImage = [viewImage applyLightEffect];
UIGraphicsEndImageContext();
//.h FILE
#import <UIKit/UIKit.h>
@interface UIImage (ImageEffects)
- (UIImage *)applyLightEffect;
- (UIImage *)applyExtraLightEffect;
- (UIImage *)applyDarkEffect;
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor;
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage;
@end
//.m FILE
#import "cGaussianEffect.h"
#import <Accelerate/Accelerate.h>
#import <float.h>
@implementation UIImage (ImageEffects)
- (UIImage *)applyLightEffect
{
UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyExtraLightEffect
{
UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyDarkEffect
{
UIColor *tintColor = [UIColor colorWithWhite:0.11 alpha:0.73];
return [self applyBlurWithRadius:1 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
}
- (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
{
const CGFloat EffectColorAlpha = 0.6;
UIColor *effectColor = tintColor;
int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
if (componentCount == 2) {
CGFloat b;
if ([tintColor getWhite:&b alpha:NULL]) {
effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
}
}
else {
CGFloat r, g, b;
if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
}
}
return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
}
- (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
{
if (self.size.width < 1 || self.size.height < 1) {
NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
return nil;
}
if (!self.CGImage) {
NSLog (@"*** error: image must be backed by a CGImage: %@", self);
return nil;
}
if (maskImage && !maskImage.CGImage) {
NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
return nil;
}
CGRect imageRect = { CGPointZero, self.size };
UIImage *effectImage = self;
BOOL hasBlur = blurRadius > __FLT_EPSILON__;
BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
if (hasBlur || hasSaturationChange) {
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectInContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(effectInContext, 1.0, -1.0);
CGContextTranslateCTM(effectInContext, 0, -self.size.height);
CGContextDrawImage(effectInContext, imageRect, self.CGImage);
vImage_Buffer effectInBuffer;
effectInBuffer.data = CGBitmapContextGetData(effectInContext);
effectInBuffer.width = CGBitmapContextGetWidth(effectInContext);
effectInBuffer.height = CGBitmapContextGetHeight(effectInContext);
effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
vImage_Buffer effectOutBuffer;
effectOutBuffer.data = CGBitmapContextGetData(effectOutContext);
effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext);
effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext);
effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
if (hasBlur) {
CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
NSUInteger radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
if (radius % 2 != 1) {
radius += 1;
}
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
}
BOOL effectImageBuffersAreSwapped = NO;
if (hasSaturationChange) {
CGFloat s = saturationDeltaFactor;
CGFloat floatingPointSaturationMatrix[] = {
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1,
};
const int32_t divisor = 256;
NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
int16_t saturationMatrix[matrixSize];
for (NSUInteger i = 0; i < matrixSize; ++i) {
saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
}
if (hasBlur) {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
effectImageBuffersAreSwapped = YES;
}
else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
}
}
if (!effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
if (effectImageBuffersAreSwapped)
effectImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
}
UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
CGContextRef outputContext = UIGraphicsGetCurrentContext();
CGContextScaleCTM(outputContext, 1.0, -1.0);
CGContextTranslateCTM(outputContext, 0, -self.size.height);
CGContextDrawImage(outputContext, imageRect, self.CGImage);
if (hasBlur) {
CGContextSaveGState(outputContext);
if (maskImage) {
CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
CGContextRestoreGState(outputContext);
}
if (tintColor) {
CGContextSaveGState(outputContext);
CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
CGContextFillRect(outputContext, imageRect);
CGContextRestoreGState(outputContext);
}
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
Just for the record, if you want to have a named sort-function, the syntax is as follows:
let sortFunction = (a, b) => {
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
users.sort(sortFunction)
Note that the following does NOT work:
users.sort(sortFunction(a,b))
Copy the btn_check.xml from android-sdk/platforms/android-#/data/res/drawable to your project's drawable folder and change the 'on' and 'off' image states to your custom images.
Then your xml will just need android:button="@drawable/btn_check"
<CheckBox
android:button="@drawable/btn_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true" />
If you want to use different default android icons, you can use android:button="@android:drawable/..."
I would add, and also to answer the question find mean bin values using histogram2d python that the scipy also have a function specially designed to compute a bidimensional binned statistic for one or more sets of data
import numpy as np
from scipy.stats import binned_statistic_2d
x = np.random.rand(100)
y = np.random.rand(100)
values = np.random.rand(100)
bin_means = binned_statistic_2d(x, y, values, bins=10).statistic
the function scipy.stats.binned_statistic_dd is a generalization of this funcion for higher dimensions datasets
string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>(); foreach (var line in lines) { string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); list1.Add(values[0]); list2.Add(values[1]); }
In my case over time I had saved a bunch of versions of myfile as myfile_bak, myfile_old, myfile_2010, backups/myfile etc. I wanted to put myfile's history in git using their modification dates. So rename the oldest to myfile, git add myfile
, then git commit --date=(modification date from ls -l) myfile
, rename next oldest to myfile, another git commit with --date, repeat...
To automate this somewhat, you can use shell-foo to get the modification time of the file. I started with ls -l
and cut
, but stat(1) is more direct
git commit --date="`stat -c %y myfile`" myfile
if you want to stay DRY, use an include.
{% if foo %}
{% with a as b %}
{% include "snipet.html" %}
{% endwith %}
{% else %}
{% with bar as b %}
{% include "snipet.html" %}
{% endwith %}
{% endif %}
or, even better would be to write a method on the model that encapsulates the core logic:
def Patient(models.Model):
....
def get_legally_responsible_party(self):
if self.age > 18:
return self
else:
return self.parent
Then in the template:
{% with patient.get_legally_responsible_party as p %}
Do html stuff
{% endwith %}
Then in the future, if the logic for who is legally responsible changes you have a single place to change the logic -- far more DRY than having to change if statements in a dozen templates.
First off, you shouldn't add $
when you're outside of strings ($class
in your first function being an exception), so it should be:
def doCopyMibArtefactsHere(projectName) {
step ([
$class: 'CopyArtifact',
projectName: projectName,
filter: '**/**.mib',
fingerprintArtifacts: true,
flatten: true
]);
}
def BuildAndCopyMibsHere(projectName, params) {
build job: project, parameters: params
doCopyMibArtefactsHere(projectName)
}
...
Now, as for your problem; the second function takes two arguments while you're only supplying one argument at the call. Either you have to supply two arguments at the call:
...
node {
stage('Prepare Mib'){
BuildAndCopyMibsHere('project1', null)
}
}
... or you need to add a default value to the functions' second argument:
def BuildAndCopyMibsHere(projectName, params = null) {
build job: project, parameters: params
doCopyMibArtefactsHere($projectName)
}
Shameless self plug: you could always use https://github.com/amoerie/jstreams
Works on Java 6 and up, a perfect fit for Android development.
It looks a lot like Scala operators, lodash, C# LINQ, etc.
Just Add the following in your onCreate method,
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawer, mToolbar, R.string.home_navigation_drawer_open, R.string.home_navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
}
};
mDrawer.addDrawerListener(toggle);
toggle.syncState();
and In strings.xml,
<string name="home_navigation_drawer_open">Open navigation drawer</string>
<string name="home_navigation_drawer_close">Close navigation drawer</string>
I would avoid inline javascript altogether, and as I mentioned in my comment, I'd also probably use <input type="button" />
for this. That being said...
<a href="http://stackoverflow.com/questions/16337937/how-to-call-javascript-from-a-href" id="mylink">Link.</a>
var clickHandler = function() {
alert('Stuff happens now.');
}
if (document.addEventListener) {
document.getElementById('mylink').addEventListener('click', clickHandler, false);
} else {
document.getElementById('mylink').attachEvent('click', clickHandler);
}
For those, who want to use Shell.Application.Namespace.Folder.CopyHere() and want to hide progress bars while copying, or use more options, the documentation is here:
https://docs.microsoft.com/en-us/windows/desktop/shell/folder-copyhere
To use powershell and hide progress bars and disable confirmations you can use code like this:
# We should create folder before using it for shell operations as it is required
New-Item -ItemType directory -Path "C:\destinationDir" -Force
$shell = New-Object -ComObject Shell.Application
$zip = $shell.Namespace("C:\archive.zip")
$items = $zip.items()
$shell.Namespace("C:\destinationDir").CopyHere($items, 1556)
Limitations of use of Shell.Application on windows core versions:
https://docs.microsoft.com/en-us/windows-server/administration/server-core/what-is-server-core
On windows core versions, by default the Microsoft-Windows-Server-Shell-Package is not installed, so shell.applicaton will not work.
note: Extracting archives this way will take a long time and can slow down windows gui
Use this code:
internal void SomeFunction() {
Dictionary<string, string> formField = new Dictionary<string, string>();
formField.Add("Name", "Henry");
formField.Add("Age", "21");
string body = GetBodyStringFromDictionary(formField);
// output : Name=Henry&Age=21
}
internal string GetBodyStringFromDictionary(Dictionary<string, string> formField)
{
string body = string.Empty;
foreach (var pair in formField)
{
body += $"{pair.Key}={pair.Value}&";
}
// delete last "&"
body = body.Substring(0, body.Length - 1);
return body;
}
I stumbled over the following algorithm which seems to be more efficient than Johnson's algorithm (at least for larger graphs). I am however not sure about its performance compared to Tarjan's algorithm.
Additionally, I only checked it out for triangles so far. If interested, please see "Arboricity and Subgraph Listing Algorithms" by Norishige Chiba and Takao Nishizeki (http://dx.doi.org/10.1137/0214017)
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
If you don't want to type, you can create the statements with this:
USE Databasename
SELECT 'DROP TABLE [' + name + '];'
FROM sys.tables
Then copy and paste into a new SSMS window to run it.
Mouse.GetPosition(mWindow)
gives you the mouse position relative to the parameter of your choice.
mWindow.PointToScreen()
convert the position to a point relative to the screen.
So mWindow.PointToScreen(Mouse.GetPosition(mWindow))
gives you the mouse position relative to the screen, assuming that mWindow
is a window(actually, any class derived from System.Windows.Media.Visual
will have this function), if you are using this inside a WPF window class, this
should work.
I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:
http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate
<input type=submit formnovalidate name=cancel value="Cancel">
Works on Safari 5 and Opera 10.
Three "default" textSize values:
- 14sp
- 18sp
- 22sp
These values are defined within the following TextAppearances:
- TextAppearance.Small
- TextAppearance.Medium
- TextAppearance.Large
More information about Typography can be found in the design guidelines
If you don't set a custom textSize or textAppearance, TextAppearance.Small will be used.
New guidelines related to font and typefaces. The standard rule of 14sp remains (body).
Examples how to set textappearances
AppCompat version:
android:textAppearance="@style/TextAppearance.AppCompat.Body"
Lollipop and up version:
android:textAppearance="@android:style/TextAppearance.Material.Body"
directly in the AWS Console bucket view.
When you have thousands or millions of files another way to get the wanted files is to copy them to another location using distributed copy. You run this on EMR in a Hadoop Job. The cool thing about AWS is that they provide their custom S3 version s3-dist-cp. It allows you to group wanted files using a regular expression in the groupBy field. You can use this for example in a custom step on EMR
[
{
"ActionOnFailure": "CONTINUE",
"Args": [
"s3-dist-cp",
"--s3Endpoint=s3.amazonaws.com",
"--src=s3://mybucket/",
"--dest=s3://mytarget-bucket/",
"--groupBy=MY_PATTERN",
"--targetSize=1000"
],
"Jar": "command-runner.jar",
"Name": "S3DistCp Step Aggregate Results",
"Type": "CUSTOM_JAR"
}
]
char name[10][10]
int i,j,n;//here "n" is number of enteries
printf("\nEnter size of array = ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
for(j=0;j<1;j++)
{
printf("\nEnter name = ");
scanf("%s",&name[i]);
}
}
//printing the data
for(i=0;i<n;i++)
{
for(j=0;j<1;j++)
{
printf("%d\t|\t%s\t|\t%s",rollno[i][j],name[i],sex[i]);
}
printf("\n");
}
Here try this!!!
Android makes it easy.
public void setTabTextColors(int normalColor, int selectedColor) {
setTabTextColors(createColorStateList(normalColor, selectedColor));
}
So, we just say
mycooltablayout.setTabTextColors(Color.parseColor("#1464f4"), Color.parseColor("#880088"));
That will give us a blue normal color and purple selected color.
Now we set the height
public void setSelectedTabIndicatorHeight(int height) {
mTabStrip.setSelectedIndicatorHeight(height);
}
And for height we say
mycooltablayout.setSelectedIndicatorHeight(6);
The problem is not with the splitting but rather with the WriteLine
. A \n
in a string printed with WriteLine
will produce an "extra" line.
Example
var text =
"somet interesting text\n" +
"some text that should be in the same line\r\n" +
"some text should be in another line";
string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
Console.WriteLine(s); //But will print 3 lines in total.
}
To fix the problem remove \n
before you print the string.
Console.WriteLine(s.Replace("\n", ""));
You can use IEnumerable to eliminate the need of a temp list.
public IEnumerable<T> GetFilteredItems(IEnumerable<T> collection)
{
foreach (T item in collection)
if (Matches<T>(item))
{
yield return item;
}
}
where Matches is the name of your filter method. And you can use this like:
IEnumerable<MyType> filteredItems = GetFilteredItems(myList);
foreach (MyType item in filteredItems)
{
// do sth with your filtered items
}
This will call GetFilteredItems function when needed and in some cases that you do not use all items in the filtered collection, it may provide some good performance gain.
Another solution but without using ng-click which still works even for other tags than <a>
:
<tr [routerLink]="['/about']">
This way you can also pass parameters to your route: https://stackoverflow.com/a/40045556/838494
(This is my first day with angular. Gentle feedback is welcome)
Ugh everyone's answers on here are incomplete, and lets stop using jquery in SO answers already please. Check jquery's documentation if you want info on jquery.
Here's a generalized pure-javascript function for testing whether or not an element has scrollbars in a complete way:
// dimension - Either 'y' or 'x'
// computedStyles - (Optional) Pass in the domNodes computed styles if you already have it (since I hear its somewhat expensive)
function hasScrollBars(domNode, dimension, computedStyles) {
dimension = dimension.toUpperCase()
if(dimension === 'Y') {
var length = 'Height'
} else {
var length = 'Width'
}
var scrollLength = 'scroll'+length
var clientLength = 'client'+length
var overflowDimension = 'overflow'+dimension
var hasVScroll = domNode[scrollLength] > domNode[clientLength]
// Check the overflow and overflowY properties for "auto" and "visible" values
var cStyle = computedStyles || getComputedStyle(domNode)
return hasVScroll && (cStyle[overflowDimension] == "visible"
|| cStyle[overflowDimension] == "auto"
)
|| cStyle[overflowDimension] == "scroll"
}
Linking the 6.1 SDK into Xcode 5 as described in the other answers is one step. However this still doesn't solve the problem that running on iOS 7 new UI elements are taken, view controllers are made full-size etc.
As described in this answer it is also required to switch the UI into legacy mode on iOS 7:
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"UIUseLegacyUI"];
[[NSUserDefaults standardUserDefaults] synchronize];
Beware: This is an undocumented key and not recommended for App Store builds!
Also, in my experience while testing on the device I found that it only works the second time I launch the app even though I'm running the code fairly early in the app launch, in +[AppDelegate initialize]
. Also there are subtle differences to a version built using Xcode 4.6. For instance, transparent navigation bars behave differently (causing the view to be full-size).
However, since Xcode 4.6.3 crashes on Mavericks (at least for me, see rdar://15318883), this is at least a solution to continue using Xcode 5 for debugging.
As a NOT TO DO - Another way would be to use:
divControl.Attributes.Add("style", "height: number");
But don't use this as its messy and the answer by AviewAnew is the correct way.
"".join may be used to copy the string in a list to a variable
>>> myList = list("Hello World")
>>> myString = "".join(myList)
>>> print(myList)
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> print(myString)
Hello World
There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):
CString str;
// ....
const char* cstr = (LPCTSTR)str;
Since there is still no solution for initial issue, here's my pure CSS two cents.
Mobile browsers (most of them) require font-size in inputs to be 16px. So
input[type="text"],_x000D_
input[type="number"],_x000D_
input[type="email"],_x000D_
input[type="tel"],_x000D_
input[type="password"] {_x000D_
font-size: 16px;_x000D_
}
_x000D_
solves the issue. So you don't need to disable zoom and loose accessibility features of you site.
If your base font-size is not 16px or not 16px on mobiles, you can use media queries.
@media screen and (max-width: 767px) {_x000D_
input[type="text"],_x000D_
input[type="number"],_x000D_
input[type="email"],_x000D_
input[type="tel"],_x000D_
input[type="password"] {_x000D_
font-size: 16px;_x000D_
}_x000D_
}
_x000D_
As suggeseted, the way to go is valgrind. It's a profiler that checks many aspects of the running performance of your application, including the usage of memory.
Running your application through Valgrind will allow you to verify if you forget to release memory allocated with malloc, if you free the same memory twice etc.
In my case a switch from openjdk7 to openjdk6 helped. Afterwards I changed the compliance level to 1.6 and all compiled fine.
Try this coding
<div>
<iframe id='iframe2' src="Mypage.aspx" frameborder="0" style="overflow: hidden; height: 100%;
width: 100%; position: absolute;"></iframe>
</div>
In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):
$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );
The previous answers all work to find the unique common elements, but will fail to account for repeated items in the lists. If you want the common elements to appear in the same number as they are found in common on the lists, you can use the following one-liner:
l2, common = l2[:], [ e for e in l1 if e in l2 and (l2.pop(l2.index(e)) or True)]
The or True
part is only necessary if you expect any elements to evaluate to False
.
I know this post is old but...
I was able to do this, my problem was that I forgot to make my property static.
public static class MyStaticClass
{
private static NonStaticObject _myObject = new NonStaticObject();
//property
public static NonStaticObject MyObject
{
get { return _myObject; }
set { _myObject = value; }
}
}
I'm assuming you mean a datetime picker in a winforms application.
in your code, you can do the following:
string theDate = dateTimePicker1.Value.ToShortDateString();
or, if you'd like to specify the format of the date:
string theDate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
I'm using xcode, my app usually took 1 - 2 minutes to be processed but today I waited for 15 minutes. What I did was increase the build, keep the version same and archive it again. And it went thru within 2 minutes while the previous build still stuck after an hour.
My advise is don't wait for Apple, just increase build and upload again. Apple is too noble to admit their system has bug or mistake. Time is money.
to scroll till particular element from the message box top checkout the following demo:
https://jsfiddle.net/6smajv0t/
function scrollToBottom(){_x000D_
const messages = document.getElementById('messages');_x000D_
const messagesid = document.getElementById('messagesid'); _x000D_
messages.scrollTop = messagesid.offsetTop - 10;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
setInterval(scrollToBottom, 1000);
_x000D_
#messages {_x000D_
height: 200px;_x000D_
overflow-y: auto;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="messages">_x000D_
<div class="message">_x000D_
Hello world1_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world2_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world3_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world4_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world5_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world7_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world8_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world9_x000D_
</div>_x000D_
<div class="message" >_x000D_
Hello world10_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world11_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world12_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world13_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world14_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world15_x000D_
</div>_x000D_
<div class="message" id="messagesid">_x000D_
Hello world16 here_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world17_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world18_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world19_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world20_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world21_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world22_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world23_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world24_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world25_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world26_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world27_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world28_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world29_x000D_
</div>_x000D_
<div class="message">_x000D_
Hello world30_x000D_
</div>_x000D_
</div>
_x000D_
I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:
This replaces all underscores with hyphens in any non-hidden file in the current directory
import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]
//For proper line spacing
NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];
UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];
[attributedString1 appendAttributedString:attributedString2];
Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N
for the S/U and U/S contention, as in No Conflict.
As for the HOLDLOCK hint the documentation states:
HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.
...
SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...
and the Transaction Isolation Level topic explains what SERIALIZABLE means:
No other transactions can modify data that has been read by the current transaction until the current transaction completes.
Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.
Therefore the behavior you see is perfectly explained by the product documentation:
SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...
After OP edit:
I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.
The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.
As others suggested, NSMutableArray has methods to do so but sometimes you are forced to use NSArray, I'd use:
NSArray* newArray = [oldArray subarrayWithRange:NSMakeRange(1, [oldArray count] - 1)];
This way, the oldArray stays as it was but a newArray will be created with the first item removed.
step by step
given you have a textbox as following,
<asp:TextBox ID="TextBox13" runat="server"
onkeypress="return functionx(event)" >
</asp:TextBox>
you create a JavaScript function like this:
<script type = "text/javascript">
function functionx(evt)
{
if (evt.charCode > 31 && (evt.charCode < 48 || evt.charCode > 57))
{
alert("Allow Only Numbers");
return false;
}
}
</script>
the first part of the if-statement excludes the ASCII control chars, the or statements exclued anything, that is not a number
You are looking for the SO_KEEPALIVE socket option.
The Java Socket API exposes "keep-alive" to applications via the setKeepAlive
and getKeepAlive
methods.
EDIT: SO_KEEPALIVE is implemented in the OS network protocol stacks without sending any "real" data. The keep-alive interval is operating system dependent, and may be tuneable via a kernel parameter.
Since no data is sent, SO_KEEPALIVE can only test the liveness of the network connection, not the liveness of the service that the socket is connected to. To test the latter, you need to implement something that involves sending messages to the server and getting a response.
Java8 +
import java.time.Instant;
Instant.now().getEpochSecond(); //timestamp in seconds format (int)
Instant.now().toEpochMilli(); // timestamp in milliseconds format (long)
The Collection#filter
method really does eager load all members.
Filtering at the SQL level will be added in doctrine 2.3.
Android Emulator Shortcuts
Ctrl+F11 Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
Home Home Button
F2 Left Softkey / Menu / Settings button (or PgUp)
Shift+F2 Right Softkey / Star button (or PgDn)
Esc Back Button
F3 Call/ dial Button
F4 Hang up / end call button
F5 Search Button
Ctrl+F5 Volume up (or + on numeric keyboard with Num Lock off) Ctrl+F6 Volume down (or + on numeric keyboard with Num Lock off) F7 Power Button Ctrl+F3 Camera Button
Ctrl+F11Switch layout orientation portrait/landscape backwards
Ctrl+F12 Switch layout orientation portrait/landscape forwards
F8 Toggle cell network
F9 Toggle code profiling
Alt+Enter Toggle fullscreen mode
F6 Toggle trackball mode
return JsonConvert.SerializeObject(images.ToList(), Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
using Newtonsoft.Json;
bash --rcfile <(echo '. ~/.bashrc; some_command')
dispenses the creation of temporary files. Question on other sites:
I had a similar problem. The catalina.out logged this log Message
Apr 17, 2013 5:14:46 PM org.apache.catalina.core.StandardContext start SEVERE: Error listenerStart
Check the localhost.log in the tomcat log directory (in the same directory as catalina.out), to see the exception which caused this error.
If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.
$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!
if (file_exists($vid)) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime_type = finfo_file($finfo, $vid); // check mime type
finfo_close($finfo);
if (preg_match('/video\/*/', $mime_type)) {
$video_attributes = _get_video_attributes($vid, $ffmpeg_path);
print_r('Codec: ' . $video_attributes['codec'] . '<br/>');
print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');
print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
. $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');
print_r('Size: ' . _human_filesize(filesize($vid)));
} else {
print_r('File is not a video.');
}
} else {
print_r('File does not exist.');
}
function _get_video_attributes($video, $ffmpeg) {
$command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
$output = shell_exec($command);
$regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
if (preg_match($regex_sizes, $output, $regs)) {
$codec = $regs [1] ? $regs [1] : null;
$width = $regs [3] ? $regs [3] : null;
$height = $regs [4] ? $regs [4] : null;
}
$regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
if (preg_match($regex_duration, $output, $regs)) {
$hours = $regs [1] ? $regs [1] : null;
$mins = $regs [2] ? $regs [2] : null;
$secs = $regs [3] ? $regs [3] : null;
$ms = $regs [4] ? $regs [4] : null;
}
return array('codec' => $codec,
'width' => $width,
'height' => $height,
'hours' => $hours,
'mins' => $mins,
'secs' => $secs,
'ms' => $ms
);
}
function _human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
EDIT: Handlebars now has a built-in way of accomplishing this; see the selected answer above. When working with plain Mustache, the below still applies.
Mustache can iterate over items in an array. So I'd suggest creating a separate data object formatted in a way Mustache can work with:
var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
},
mustacheFormattedData = { 'people' : [] };
for (var prop in o){
if (o.hasOwnProperty(prop)){
mustacheFormattedData['people'].push({
'key' : prop,
'value' : o[prop]
});
}
}
Now, your Mustache template would be something like:
{{#people}}
{{key}} : {{value}}
{{/people}}
Check out the "Non-Empty Lists" section here: https://github.com/janl/mustache.js
You can use these classes
input-lg
input
and
input-sm
for input fields and replace input with btn for buttons.
Check this documentation http://getbootstrap.com/getting-started/#migration
This will change only height of the element, to reduce the width you have to use grid system classes like col-xs-* col-md-* col-lg-*
.
Example col-md-3
. See doc here http://getbootstrap.com/css/#grid
Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:
// add values
list.add("one");
list.add("two");
// your code
for (String object: list) {
System.out.println(object);
}
Same thing happened to me. Eventually my solution was to navigate to the repository using terminal (on mac) and create a new js file with a slightly different name. It linked immediately so i copied contents of original file to new one. You also might want to lose the first /
after src=
and use ""
.
Simple, standard library only. Gives timezone-aware datetime, unlike datetime.utcnow()
.
from datetime import datetime,timezone
now_utc = datetime.now(timezone.utc)
If you want authentication try domainname\administrator as the username.
If you don't want authentication then remove all the tickboxes in the authenticated access section of the direcory security > edit window.
The main image manager in PIL
is PIL
's Image
module.
from PIL import Image
import math
foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
You can add optimize=True
to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's.
For other image extensions, you could decrease the quality of the new saved image.
You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully.
I defined this size:
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
just to show you what is (almost) normally done with horizontal images. For vertical images you might do:
x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)
. Remember, you can still delete that bit of code and define a new size.
You could just use REPLACE
:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as [email protected]
will be updated to [email protected]
.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT
, and append .org
to the SUBSTRING
manually instead. Notice the usage of UPPER
to make the search for the .com
ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
In react-router v2.4.0
or above and before v4
there are several options
<Route
path="/home"
onEnter={ auth }
onLeave={ showConfirm }
component={ Home }
>
You can prevent a transition from happening or prompt the user before leaving a route with a leave hook.
const Home = withRouter(
React.createClass({
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave)
},
routerWillLeave(nextLocation) {
// return false to prevent a transition w/o prompting the user,
// or return a string to allow the user to decide:
// return `null` or nothing to let other hooks to be executed
//
// NOTE: if you return true, other hooks will not be executed!
if (!this.state.isSaved)
return 'Your work is not saved! Are you sure you want to leave?'
},
// ...
})
)
Note that this example makes use of the withRouter
higher-order component introduced in v2.4.0.
However these solution doesn't quite work perfectly when changing the route in URL manually
In the sense that
For react-router v4
using Prompt or custom history:
However in react-router v4
, its rather easier to implement with the help of Prompt
from'react-router
According to the documentation
Prompt
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a
<Prompt>
.import { Prompt } from 'react-router' <Prompt when={formIsHalfFilledOut} message="Are you sure you want to leave?" />
message: string
The message to prompt the user with when they try to navigate away.
<Prompt message="Are you sure you want to leave?"/>
message: func
Will be called with the next location and action the user is attempting to navigate to. Return a string to show a prompt to the user or true to allow the transition.
<Prompt message={location => ( `Are you sure you want to go to ${location.pathname}?` )}/>
when: bool
Instead of conditionally rendering a
<Prompt>
behind a guard, you can always render it but passwhen={true}
orwhen={false}
to prevent or allow navigation accordingly.
In your render method you simply need to add this as mentioned in the documentation according to your need.
UPDATE:
In case you would want to have a custom action to take when user is leaving page, you can make use of custom history and configure your Router like
history.js
import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()
...
import { history } from 'path/to/history';
<Router history={history}>
<App/>
</Router>
and then in your component you can make use of history.block
like
import { history } from 'path/to/history';
class MyComponent extends React.Component {
componentDidMount() {
this.unblock = history.block(targetLocation => {
// take your action here
return false;
});
}
componentWillUnmount() {
this.unblock();
}
render() {
//component render here
}
}
Objects in JavaScript are collections of unordered properties. Objects are hashtables.
If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:
Here's a quick adaptation for your object1:
var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};
var index = [];
// build the index
for (var x in obj) {
index.push(x);
}
// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});
Then you would be able to do the following:
console.log(obj[index[1]]);
The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.
1 You may want to use the hasOwnProperty()
method to ensure that the properties belong to your object and are not inherited from Object.prototype
.
In Python 2.x, it is not guaranteed at all:
>>> False = 5
>>> 0 == False
False
So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.
In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1
, but on Python 3.x, this will always be the case, no matter what.
def merge(l1, l2, out=[]):
if l1==[]: return out+l2
if l2==[]: return out+l1
if l1[0]<l2[0]: return merge(l1[1:], l2, out+l1[0:1])
return merge(l1, l2[1:], out+l2[0:1])
def merge_sort(l): return (lambda h: l if h<1 else merge(merge_sort(l[:h]), merge_sort(l[h:])))(len(l)/2)
print(merge_sort([1,4,6,3,2,5,78,4,2,1,4,6,8]))
If --grace-period=0
is not working then you can do:
kubectl delete pods <pod> --grace-period=0 --force
Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:
import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)
#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability
#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%
#To find the variate for which the probability is given, let's say the
#value which needed to provide a 98% probability, you'd use the
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187
If you would like to add vector to itself both popular solutions will fail:
std::vector<std::string> v, orig;
orig.push_back("first");
orig.push_back("second");
// BAD:
v = orig;
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "", "" }
// BAD:
v = orig;
std::copy(v.begin(), v.end(), std::back_inserter(v));
// std::bad_alloc exception is generated
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
v.insert(v.end(), v.begin(), v.end());
// Now v contains: { "first", "second", "first", "second" }
// GOOD, but I can't guarantee it will work with any STL:
v = orig;
v.reserve(v.size()*2);
std::copy(v.begin(), v.end(), std::back_inserter(v));
// Now v contains: { "first", "second", "first", "second" }
// GOOD (best):
v = orig;
v.insert(v.end(), orig.begin(), orig.end()); // note: we use different vectors here
// Now v contains: { "first", "second", "first", "second" }
yes stale element error is thrown when (taking your scenario) you have defined locator strategy to click on 'Add Item' first and then when you close the pop up the page gets refreshed hence the reference defined for 'Add Item' is lost in the memory so to overcome this you have to redefine the locator strategy for 'Add Item' again
understand it with a dummy code
// clicking on view details
driver.findElement(By.id("")).click();
// closing the pop up
driver.findElement(By.id("")).click();
// and when you try to click on Add Item
driver.findElement(By.id("")).click();
// you get stale element exception as reference to add item is lost
// so to overcome this you have to re identify the locator strategy for add item
// Please note : this is one of the way to overcome stale element exception
// Step 1 please add a universal wait in your script like below
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); // just after you have initiated browser
You get this error because you let a .NET exception happen on your server side, and you didn't catch and handle it, and didn't convert it to a SOAP fault, either.
Now since the server side "bombed" out, the WCF runtime has "faulted" the channel - e.g. the communication link between the client and the server is unusable - after all, it looks like your server just blew up, so you cannot communicate with it any more.
So what you need to do is:
always catch and handle your server-side errors - do not let .NET exceptions travel from the server to the client - always wrap those into interoperable SOAP faults. Check out the WCF IErrorHandler interface and implement it on the server side
if you're about to send a second message onto your channel from the client, make sure the channel is not in the faulted state:
if(client.InnerChannel.State != System.ServiceModel.CommunicationState.Faulted)
{
// call service - everything's fine
}
else
{
// channel faulted - re-create your client and then try again
}
If it is, all you can do is dispose of it and re-create the client side proxy again and then try again
If you need refresh, this is another posibility:
setTimeout(function () {
$("#jsSegurosProductos").jsGrid("refresh");
}, 1000);
Ok, I've been working on this for a few hours, and I've developed what I believe to be the most pythonic solution yet. The following code snippets are python3 but shouldn't be too horribly painful to backport if you need.
The first thing we're gonna do is start with a mixin that makes your db models act kinda like dict
s:
from sqlalchemy.inspection import inspect
class ModelMixin:
"""Provide dict-like interface to db.Model subclasses."""
def __getitem__(self, key):
"""Expose object attributes like dict values."""
return getattr(self, key)
def keys(self):
"""Identify what db columns we have."""
return inspect(self).attrs.keys()
Now we're going to define our model, inheriting the mixin:
class MyModel(db.Model, ModelMixin):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(...)
bar = db.Column(...)
# etc ...
That's all it takes to be able to pass an instance of MyModel()
to dict()
and get a real live dict
instance out of it, which gets us quite a long way towards making jsonify()
understand it. Next, we need to extend JSONEncoder
to get us the rest of the way:
from flask.json import JSONEncoder
from contextlib import suppress
class MyJSONEncoder(JSONEncoder):
def default(self, obj):
# Optional: convert datetime objects to ISO format
with suppress(AttributeError):
return obj.isoformat()
return dict(obj)
app.json_encoder = MyJSONEncoder
Bonus points: if your model contains computed fields (that is, you want your JSON output to contain fields that aren't actually stored in the database), that's easy too. Just define your computed fields as @property
s, and extend the keys()
method like so:
class MyModel(db.Model, ModelMixin):
id = db.Column(db.Integer, primary_key=True)
foo = db.Column(...)
bar = db.Column(...)
@property
def computed_field(self):
return 'this value did not come from the db'
def keys(self):
return super().keys() + ['computed_field']
Now it's trivial to jsonify:
@app.route('/whatever', methods=['GET'])
def whatever():
return jsonify(dict(results=MyModel.query.all()))
I always use the clock_gettime() function, returning time from the CLOCK_MONOTONIC clock. The time returned is the amount of time, in seconds and nanoseconds, since some unspecified point in the past, such as system startup of the epoch.
#include <stdio.h>
#include <stdint.h>
#include <time.h>
int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}
int main(int argc, char **argv)
{
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
// Some code I am interested in measuring
clock_gettime(CLOCK_MONOTONIC, &end);
uint64_t timeElapsed = timespecDiff(&end, &start);
}
Is there a reason that you can't do this via Javascript? My advice would be to target the selectors with a universal rule (.foo
) and then parse back over to get the last foo with Javascript and set any additional styling you'll need.
Or as suggested by Stein, just add two classes if you can:
<div class="foo"></div>
<div class="foo last"></div>
.foo {}
.foo.last {}
"DeprecationWarning: Unhandled promise rejections are deprecated"
TLDR: A promise has resolve
and reject
, doing a reject
without a catch to handle it is deprecated, so you will have to at least have a catch
at top level.
You can use mkdir:
#include <sys/stat.h>
#include <sys/types.h>
int result = mkdir("/home/me/test.txt", 0777);
TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor.
You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable. Sadly, some of Microsoft's graphical tools put this meaningless clause in.
As for why this might appear in dynamic SQL, I have no idea. You're correct that there's no reason for it, and the result is the same without it (and again, in the case of a view definition or derived table, without both the TOP and ORDER BY clauses).
Don't use int
. Files over 2 gigabytes in size are common as dirt these days
Don't use unsigned int
. Files over 4 gigabytes in size are common as some slightly-less-common dirt
IIRC the standard library defines off_t
as an unsigned 64 bit integer, which is what everyone should be using. We can redefine that to be 128 bits in a few years when we start having 16 exabyte files hanging around.
If you're on windows, you should use GetFileSizeEx - it actually uses a signed 64 bit integer, so they'll start hitting problems with 8 exabyte files. Foolish Microsoft! :-)
Your tables should have as immediate children just tbody
and thead
elements, with the rows within*. So, amend the HTML to be:
<table border="1" width="100%" id="test">
<tbody>
<tr>
<td>
<table border="1" width="100%">
<tbody>
<tr>
<td>table 2</td>
</tr>
</tbody>
</table>
</td>
</tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
<tr><td>table 1</td></tr>
</tbody>
</table>
Then amend your selector slightly to this:
#test > tbody > tr:last-child { background:#ff0000; }
See it in action here. That makes use of the child selector, which:
...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.
So, you are targeting only direct children of tbody
elements that are themselves direct children of your #test
table.
The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:
#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }
* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:
...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.
The basic difference between
Blockquote
asymptotically upper bound and asymptotically tight Asym.upperbound means a given algorythm that can executes with maximum amount of time depending upon the number of inputs ,for eg in sorting algo if all the array (n)elements are in descending order then for ascending them it will take a running time of O(n) which shows upper bound complexity ,but if they are already sorted then it will take ohm(1).so we generally used "O"notation for upper bound complexity.
Asym. tightbound bound shows the for eg(c1g(n)<=f(n)<=c2g(n)) shows the tight bound limit such that the function have the value in between two bound (upper bound and lower bound),giving the average case.
fs/promises and fs.Dirent
Here's an efficient, non-blocking ls
program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist
or fs.stat
calls on every path -
// main.js
import { readdir } from "fs/promises"
import { join } from "path"
async function* ls (path = ".")
{ yield path
for (const dirent of await readdir(path, { withFileTypes: true }))
if (dirent.isDirectory())
yield* ls(join(path, dirent.name))
else
yield join(path, dirent.name)
}
async function* empty () {}
async function toArray (iter = empty())
{ let r = []
for await (const x of iter)
r.push(x)
return r
}
toArray(ls(".")).then(console.log, console.error)
Let's get some sample files so we can see ls
working -
$ yarn add immutable # (just some example package)
$ node main.js
[
'.',
'main.js',
'node_modules',
'node_modules/.yarn-integrity',
'node_modules/immutable',
'node_modules/immutable/LICENSE',
'node_modules/immutable/README.md',
'node_modules/immutable/contrib',
'node_modules/immutable/contrib/cursor',
'node_modules/immutable/contrib/cursor/README.md',
'node_modules/immutable/contrib/cursor/__tests__',
'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
'node_modules/immutable/contrib/cursor/index.d.ts',
'node_modules/immutable/contrib/cursor/index.js',
'node_modules/immutable/dist',
'node_modules/immutable/dist/immutable-nonambient.d.ts',
'node_modules/immutable/dist/immutable.d.ts',
'node_modules/immutable/dist/immutable.es.js',
'node_modules/immutable/dist/immutable.js',
'node_modules/immutable/dist/immutable.js.flow',
'node_modules/immutable/dist/immutable.min.js',
'node_modules/immutable/package.json',
'package.json',
'yarn.lock'
]
For added explanation and other ways to leverage async generators, see this Q&A.
You need to use HTML on a web page to get line breaks. For example "<br/>" will give you a line break.
You can directly apply slice()
to the variable. StackBlitz Demo
<li *ngFor="let item of list.slice(0, 10);">
{{item.text}}
</li>
Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.
I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.
Use this instead:
string objTextBox = t.Text;
The object t
is the TextBox
. The object you call objTextBox
is assigned the ID
property of the TextBox
.
So better code would be:
TextBox objTextBox = (TextBox)sender;
string theText = objTextBox.Text;
The ErrorDocument
directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot
. In your case, this means that the actual path to the ErrorDocument
is
ErrorDocument 404 /hellothere/error/404page.html
The answer is in the JavaDoc of the equals()
method:
Unlike
compareTo
, this method considers twoBigDecimal
objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).
In other words: equals()
checks if the BigDecimal
objects are exactly the same in every aspect. compareTo()
"only" compares their numeric value.
As to why equals()
behaves this way, this has been answered in this SO question.
This kind of a setup is simple and elegant :
env.json
{
"development": {
"facebook_app_id": "facebook_dummy_dev_app_id",
"facebook_app_secret": "facebook_dummy_dev_app_secret",
},
"production": {
"facebook_app_id": "facebook_dummy_prod_app_id",
"facebook_app_secret": "facebook_dummy_prod_app_secret",
}
}
common.js
var env = require('env.json');
exports.config = function() {
var node_env = process.env.NODE_ENV || 'development';
return env[node_env];
};
app.js
var common = require('./routes/common')
var config = common.config();
var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id
To run in production mode :
$ NODE_ENV=production node app.js
This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.
In this case oldDTE is null, so when you try to access oldDTE.Value the InvalidOperationException is thrown since there is no value. In your example you can simply do:
this.MyDateTime = newDT.MyDateTime;
So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.
if you are using Django 2.0 Then
python manage.py flush
will work
The best thing to do is.
1. fork twitter-bootstrap from github and clone locally.
they are changing really quickly the library/framework (they diverge internally. Some prefer library, i'd say that it's a framework, because change your layout from the time you load it on your page). Well... forking/cloning will let you fetch the new upcoming versions easily.
2. Do not modify the bootstrap.css file
It's gonna complicate your life when you need to upgrade bootstrap (and you will need to do it).
3. Create your own css file and overwrite whenever you want original bootstrap stuff
if they set a topbar with, let's say, color: black;
but you wan it white, create a new very specific selector for this topbar and use this rule on the specific topbar. For a table for example, it would be <table class="zebra-striped mycustomclass">
. If you declare your css file after bootstrap.css
, this will overwrite whatever you want to.
The catch is that hh is for format 12 hours and HH is for 24 hours.
24 hour format
$(function () {
$('#customElement').datetimepicker({
format: 'HH:mm',
});
});
12 hour format
$(function () {
$('#customElement').datetimepicker({
format: 'hh:mm',
});
});
In my case, for some reason, vendor
folder was disabled on VS Code settings:
"intelephense.files.exclude": [
"**/.git/**",
"**/.svn/**",
"**/.hg/**",
"**/CVS/**",
"**/.DS_Store/**",
"**/node_modules/**",
"**/bower_components/**",
"**/vendor/**", <-- remove this line!
"**/resources/views/**"
],
By removing the line containing vendor
folder it works ok on version Intelephense 1.5.4
if you want to just "bold", Mike Hofer's answer is mostly correct.
but notice that the tag bolds its contents by default, but you can change this behavior using css, example:
p strong {
font-weight: normal;
font-style: italic;
}
Now your "bold" is italic :)
So, try to use tags by its meaning, not by its default style.
If you have the product's ID you can use that to create a product object:
$_product = wc_get_product( $product_id );
Then from the object you can run any of WooCommerce's product methods.
$_product->get_regular_price();
$_product->get_sale_price();
$_product->get_price();
Update
Please review the Codex article on how to write your own shortcode.
Integrating the WooCommerce product data might look something like this:
function so_30165014_price_shortcode_callback( $atts ) {
$atts = shortcode_atts( array(
'id' => null,
), $atts, 'bartag' );
$html = '';
if( intval( $atts['id'] ) > 0 && function_exists( 'wc_get_product' ) ){
$_product = wc_get_product( $atts['id'] );
$html = "price = " . $_product->get_price();
}
return $html;
}
add_shortcode( 'woocommerce_price', 'so_30165014_price_shortcode_callback' );
Your shortcode would then look like [woocommerce_price id="99"]
ViewBag
is server side code.
Javascript
is client side code.
You can't really connect them.
You can do something like this:
var x = $('#' + '@(ViewBag.CC)').val();
But it will get parsed on the server, so you didn't really connect them.
Your style should look like this:
<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
<item name="android:indeterminateDrawable">@anim/mp3</item>
</style>
REPLACE INTO table(column_list) VALUES(value_list);
is a shorter form of
INSERT OR REPLACE INTO table(column_list) VALUES(value_list);
For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.
REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.
This is a work around.. not checked the speed..
INSERT OR IGNORE INTO table (column_list) VALUES(value_list);
followed by
UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'
This method allows a replace to occur without causing a trigger.
Would you be able to use a USB->RS232 adapter? I have a few, and they just use the FTDI driver. Then, you should be able to rename /dev/ttyUSB0 (or whatever gets created) as /dev/ttyS2 .
You must make sure that the input string has enough space to hold all the padding characters. Try this:
char hello[11] = "Hello";
StringPadRight(hello, 10, "0");
Note that I allocated 11 bytes for the hello
string to account for the null terminator at the end.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
A simpler way to do this is to use getPackage(). For example, to get Implementation-Version:
Application.class.getPackage().getImplementationVersion()
You can use this PHP library available on packagist:
https://github.com/CoreProc/gcm-php
After installing it you can do this:
$gcmClient = new GcmClient('your-gcm-api-key-here');
$message = new Message($gcmClient);
$message->addRegistrationId('xxxxxxxxxx');
$message->setData([
'title' => 'Sample Push Notification',
'message' => 'This is a test push notification using Google Cloud Messaging'
]);
try {
$response = $message->send();
// The send() method returns a Response object
print_r($response);
} catch (Exception $exception) {
echo 'uh-oh: ' . $exception->getMessage();
}
For t2/m3/c3/c4/r3/i2/d2 instances:
m1 small, medium, and large instances tend to perform higher than expected. c1.medium is another freak, at 800 MBit/s.
I gathered this by combing dozens of sources doing benchmarks (primarily using iPerf & TCP connections). Credit to CloudHarmony & flux7 in particular for many of the benchmarks (note that those two links go to google searches showing the numerous individual benchmarks).
The large instance size has the most variation reported:
Burstable (T2) instances appear to exhibit burstable networking performance too:
The CloudHarmony iperf benchmarks show initial transfers start at 1 GBit/s and then gradually drop to the sustained levels above after a few minutes. PDF links to reports below:
t2.small (PDF)
Note that these are within the same region - if you're transferring across regions, real performance may be much slower. Even for the larger instances, I'm seeing numbers of a few hundred MBit/s.
Instead of using (getApplicationContext)
use YourActivity.this
In summary, valid characters in the text are:
&
and <
.>
is not valid if following ]]
.Sections 2.2 and 2.4 of the XML specification provide the answer in detail:
Characters
Legal characters are tab, carriage return, line feed, and the legal characters of Unicode and ISO/IEC 10646
Character data
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.
EDIT: Note that you should probably use ES5 solution instead of this since ES5 support is widespread these days. It still works for jQuery though.
Easy and cross-browser way is by using jQuery.isEmptyObject
:
if ($.isEmptyObject(obj))
{
// do something
}
More: http://api.jquery.com/jQuery.isEmptyObject/
You need jquery though.
From official readxl
(tidyverse) documentation (changing first line):
path <- "data/datasets.xlsx"
path %>%
excel_sheets() %>%
set_names() %>%
map(read_excel, path = path)
Whilst M4N's answer (#if (!DEBUG)
) makes most sense, another option could be to use the preprocessor to amend other flag's values; e.g.
bool isRelease = true;
#if DEBUG
isRelease = false;
#endif
Or better, rather than referring to whether we're in release or debug mode, use flags that define the expected behavior and set them based on the mode:
bool sendEmails = true;
#if DEBUG
sendEmails = false;
#endif
This is different to using preprocessor flags, in that the flags are still there in production, so you incur the overhead of if (sendEmails) {/* send mails */}
each time that code's called, rather than the code existing in release but not existing in debug, but this can be advantageous; e.g. in your tests you may want to call your SendEmails()
method but on a mock, whilst running in debug to get additional output.
using indexOf...
public static int count(String string, String substr) {
int i;
int last = 0;
int count = 0;
do {
i = string.indexOf(substr, last);
if (i != -1) count++;
last = i+substr.length();
} while(i != -1);
return count;
}
public static void main (String[] args ){
System.out.println(count("i have a male cat. the color of male cat is Black", "male cat"));
}
That will show: 2
Another implementation for count(), in just 1 line:
public static int count(String string, String substr) {
return (string.length() - string.replaceAll(substr, "").length()) / substr.length() ;
}
Have you tried setting the painted border false?
JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);
It works on my mac :)
You may use pattern
defined in the additional-methods.js
file. Note that this additional-methods.js file must be included after jQuery Validate dependency, then you can just use
$("#frm").validate({_x000D_
rules: {_x000D_
Textbox: {_x000D_
pattern: /^[a-zA-Z'.\s]{1,40}$/_x000D_
},_x000D_
},_x000D_
messages: {_x000D_
Textbox: {_x000D_
pattern: 'The Textbox string format is invalid'_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>_x000D_
<form id="frm" method="get" action="">_x000D_
<fieldset>_x000D_
<p>_x000D_
<label for="fullname">Textbox</label>_x000D_
<input id="Textbox" name="Textbox" type="text">_x000D_
</p>_x000D_
</fieldset>_x000D_
</form>
_x000D_
The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:
Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.
EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage
function with Jcrop.
if (!$(row).hasClass("changed")) {
// do your stuff
}
The solution is already answered here above (long ago).
But the implicit question "why does it work in FF and IE but not in Chrome and Safari" is found in the error text "Not allowed to load local resource": Chrome and Safari seem to use a more strict implementation of sandboxing (for security reasons) than the other two (at this time 2011).
This applies for local access. In a (normal) server environment (apache ...) the file would simply not have been found.
I will provide a detailed differences between Visual Studio and Visual Studio Code below.
If you really look at it the most obvious difference is that .NET has been split into two:
All native user interface technologies (Windows Presentation Foundation, Windows Forms, etc.) are part of the framework, not the core.
The "Visual" in Visual Studio (from Visual Basic) was largely synonymous with visual UI (drag & drop WYSIWYG) design, so in that sense, Visual Studio Code is Visual Studio without the Visual!
The second most obvious difference is that Visual Studio tends to be oriented around projects & solutions.
Visual Studio Code:
Visual Studio:
Visual Studio is aimed to be the world’s best IDE (integrated development environment), which provide full stack develop toolsets, including a powerful code completion component called IntelliSense, a debugger which can debug both source code and machine code, everything about ASP.NET development, and something about SQL development.
In the latest version of Visual Studio, you can develop cross-platform application without leaving the IDE. And Visual Studio takes more than 8 GB disk space (according to the components you select).
In brief, Visual Studio is an ultimate development environment, and it’s quite heavy.
Reference: https://www.quora.com/What-is-the-difference-between-Visual-Studio-and-Visual-Studio-Code
The reason you are getting this error is that JavaScript is not waiting for the script to be loaded, so when you run
jQuery(document).ready(function(){...
there is not guarantee that the script is ready (and never will be).
This is not the most elegant solution but its workable. Essentially you can check every 1 second for the jQuery object ad run a function when its loaded with your code in it. I would add a timeout (say clearTimeout after its been run 20 times) as well to stop the check from occurring indefinitely.
var jQueryIsReady = function(){
//Your JQuery code here
}
var checkJquery = function(){
if(typeof jQuery === "undefined"){
return false;
}else{
clearTimeout(interval);
jQueryIsReady();
}
}
var interval = setInterval(checkJquery,1000);
Java 8 new feature forEach
style
import java.util.HashMap;
public class PrintMap {
public static void main(String[] args) {
HashMap<String, Integer> example = new HashMap<>();
example.put("a", 1);
example.put("b", 2);
example.put("c", 3);
example.put("d", 5);
example.forEach((key, value) -> System.out.println(key + " : " + value));
// Output:
// a : 1
// b : 2
// c : 3
// d : 5
}
}
df.insert(loc, column_name, value)
This will work if there is no other column with the same name. If a column, with your provided name already exists in the dataframe, it will raise a ValueError.
You can pass an optional parameter allow_duplicates
with True
value to create a new column with already existing column name.
Here is an example:
>>> df = pd.DataFrame({'b': [1, 2], 'c': [3,4]})
>>> df
b c
0 1 3
1 2 4
>>> df.insert(0, 'a', -1)
>>> df
a b c
0 -1 1 3
1 -1 2 4
>>> df.insert(0, 'a', -2)
Traceback (most recent call last):
File "", line 1, in
File "C:\Python39\lib\site-packages\pandas\core\frame.py", line 3760, in insert
self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates)
File "C:\Python39\lib\site-packages\pandas\core\internals\managers.py", line 1191, in insert
raise ValueError(f"cannot insert {item}, already exists")
ValueError: cannot insert a, already exists
>>> df.insert(0, 'a', -2, allow_duplicates = True)
>>> df
a a b c
0 -2 -1 1 3
1 -2 -1 2 4
In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.
<td align="center" valign="center">textgoeshere</td>
Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.
On C++17 you can by this way :
#include <filesystem>
#include <iostream>
#include <vector>
namespace fs = std::filesystem;
int main()
{
std::ios_base::sync_with_stdio(false);
for (const auto &entry : fs::recursive_directory_iterator(".")) {
if (entry.path().extension() == ".png") {
std::cout << entry.path().string() << std::endl;
}
}
return 0;
}
I use the below code which is more intuitive.
int countSetBits(int n) {
return !n ? 0 : 1 + countSetBits(n & (n-1));
}
Logic : n & (n-1) resets the last set bit of n.
P.S : I know this is not O(1) solution, albeit an interesting solution.
An easy way to remember it is the way "canonical" is used in theological circles, canonical truth is the real truth so if two people find it they have found the same truth. Same with canonical instance. If you think you have found two of them (i.e. a.equals(b)
) you really only have one (i.e. a == b
). So equality implies identity in the case of canonical object.
Now for the comparison. You now have the choice of using a==b
or a.equals(b)
, since they will produce the same answer in the case of canonical instance but a==b is comparison of the reference (the JVM can compare two numbers extremely rapidly as they are just two 32 bit patterns compared to a.equals(b)
which is a method call and involves more overhead.
If you want to change R's language in terminal to English forever, this works fine for me in macOS:
Open terminal.app, and say:
touch .bash_profile
Then say:
open -a TextEdit.app .bash_profile
These two commands will help you open ".bash_profile" file in TextEdit.
Add this to ".bash_profile" file:
export LANG=en_US.UTF-8
Then save the file, reopen terminal and type R
, you will find it's language has changed to english.
If you want language come back to it's original, just simply add a #
before export LANG=en_US.UTF-8
.
The following command may help you..
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
EXEC sp_configure 'ad hoc distributed queries', 1
RECONFIGURE
GO
Use document.title
:
console.log(document.title)
_x000D_
<title>Title test</title>
_x000D_
The keyboard height depends on the model, the QuickType bar, user settings... The best approach is calculate dinamically:
Swift 3.0
var heightKeyboard : CGFloat?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardShown(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
}
func keyboardShown(notification: NSNotification) {
if let infoKey = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
let rawFrame = (infoKey as AnyObject).cgRectValue {
let keyboardFrame = view.convert(rawFrame, from: nil)
self.heightKeyboard = keyboardFrame.size.height
// Now is stored in your heightKeyboard variable
}
}
This error also happens if you're using a self-signed certificate with a keyUsage
missing the value keyCertSign
.
I got the same error message. In my case, it was due to not using quotes.
Although the column was supposed to have only numbers, it was a Varchar column, and one of the rows had a letter in it.
So I was doing this:
select * from mytable where myid = 1234
While I should be doing this:
select * from mytable where myid = '1234'
If the column had all numbers, the conversion would have worked, but not in this case.
If you're going to bet your business or job on a development project, you want to be in control of the foundations - i.e. the build system. With Maven, you are not in control. It is declarative and opaque. The maven-framework developers have no idea how to build a transparent or intuitive system and this is clear from the log output and the documentation.
The dependency management is very tempting since it could same you some time at project inception but be warned, it is fundamentally broken and will eventually cause you a lot of headaches. When two dependencies have incompatible transient dependencies you will be blocked by a rat's nest of complexity that will break the build for your entire team and block development for days. The build process with Maven is also notoriously inconsistent for different developers in your team due to inconsistent states of their local repositories. Depending on when a developer created their environment, or what other projects they're working on, they will have different results. You'll find that you're deleting your entire local repository and having Maven re-download jars far more often than the first time setup for a dev branch. I believe OSGI is an initiative that is attempting to fix this fundamental problem. I would say that perhaps if something needs to be so complex, the fundamental premise is wrong.
I've been a maven user/victim for over 5 years now and I have to say that it will save you far more time to just check your dependencies into your source repository and write nice and simple ant tasks. With ant, you know EXACTLY what your build system is doing.
I've experienced many, many lost man weeks of time at several different companies due to Maven problems.
I've recently tried to bring an old GWT/Maven/Eclipse project back to life and 2 weeks of all my spare time later, I still can't get it to build consistently. It's time to cut my losses and develop using ant / eclipse me thinks...
I do not know if there is a better way, but you can create a custom bullet point graphic depicting a dash, and then let the browser know you want to use it in your list with the list-style-type property. An example on that page shows how to use a graphic as a bullet.
I have never tried to use :before in the way you have, although it may work. The downside is that it will not be supported by some older browsers. My gut reaction is that this is still important enough to take into consideration. In the future, this may not be as important.
EDIT: I have done a little testing with the OP's approach. In IE8, I couldn't get the technique to work, so it definitely is not yet cross-browser. Moreover, in Firefox and Chrome, setting list-style-type to none in conjunction appears to be ignored.
The padding inside a table-divider (TD) is a padding property applied to the cell itself.
CSS
td, th {padding:0}
The spacing in-between the table-dividers is a space between cell borders of the TABLE. To make it effective, you have to specify if your table cells borders will 'collapse' or be 'separated'.
CSS
table, td, th {border-collapse:separate}
table {border-spacing:6px}
Try this : https://www.google.ca/search?num=100&newwindow=1&q=css+table+cellspacing+cellpadding+site%3Astackoverflow.com ( 27 100 results )
IE will cache URLs in order to make loading faster, but if you're, say, polling a server at intervals trying to get new information, IE will cache that URL and will likely return the same data set you've always had.
Regardless of how you end up doing your GET request - vanilla JavaScript, Prototype, jQuery, etc - make sure that you put a mechanism in place to combat caching. In order to combat that, append a unique token to the end of the URL you're going to be hitting. This can be done by:
var sURL = '/your/url.html?' + (new Date()).getTime();
This will append a unique timestamp to the end of the URL and will prevent any caching from happening.
select a.user from (select user from users order by user) a where rownum = 1
will perform the best, another option is:
select a.user
from (
select user,
row_number() over (order by user) user_rank,
row_number() over (partition by dept order by user) user_dept_rank
from users
) a
where a.user_rank = 1 or user_dept_rank = 2
in scenarios where you want different subsets, but I guess you could also use RANK()
But, I also like row_number()
over(...)
since no grouping is required.
Yes, you can have it on multiple lines using the white-space css property :)
input[type="submit"] {_x000D_
white-space: normal;_x000D_
width: 100px;_x000D_
}
_x000D_
<input type="submit" value="Some long text that won't fit." />
_x000D_
add this to your element
white-space: normal;
width: 100px;
How to generate or reverse a Dockerfile from an image?
You can.
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage"
dfimage -sV=1.36 nginx:latest
It will pull the target docker image automaticlaly and export Dockerfile
. Parameter -sV=1.36
is not always required.
Reference: https://hub.docker.com/repository/docker/alpine/dfimage
$ docker pull centurylink/dockerfile-from-image
$ alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm centurylink/dockerfile-from-image"
$ dfimage --help
Usage: dockerfile-from-image.rb [options] <image_id>
-f, --full-tree Generate Dockerfile for all parent layers
-h, --help Show this message
For those who are looking for a solution to get an event and store something, in my case a HTML 5 element, on a useState
here's my solution:
const [anchorElement, setAnchorElement] = useState<HTMLButtonElement | null>(null);
const handleMenu = (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) : void => {
setAnchorElement(event.currentTarget);
};
I had a similar issue and it turned out to be Adblocker Pro. Be sure to check that this or other blocking extensions have been disabled. I lost around 1hr 30 mins due to this. Feel like such a noob ;)
I struggled with this for over a week and finally figured out how to make this work!
My issue was that everything would scroll as a 'block'. The text itself was scrolling, but as a chunk rather than line by line. This obviously didn't work for me, because it would cut off lines at the bottom. All of the previous solutions did not work for me, so I crafted my own.
Here is the easiest solution by far:
Make a class file called: 'PerfectScrollableTextView' inside a package, then copy and paste this code in:
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;
public class PerfectScrollableTextView extends TextView {
public PerfectScrollableTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setVerticalScrollBarEnabled(true);
setHorizontallyScrolling(false);
}
public PerfectScrollableTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setVerticalScrollBarEnabled(true);
setHorizontallyScrolling(false);
}
public PerfectScrollableTextView(Context context) {
super(context);
setVerticalScrollBarEnabled(true);
setHorizontallyScrolling(false);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
}
Finally change your 'TextView' in XML:
From: <TextView
To: <com.your_app_goes_here.PerfectScrollableTextView
I worked with Unity and had some problem with the BeginConnect and other async methods from socket.
There is something than I don't understand but the code samples before doesn't work for me.
So I wrote this piece of code to make it work. I test it on an adhoc network with android and pc, also in local on my computer. Hope it can help.
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System;
using System.Diagnostics;
class ConnexionParameter : Guardian
{
public TcpClient client;
public string address;
public int port;
public Thread principale;
public Thread thisthread = null;
public int timeout;
private EventWaitHandle wh = new AutoResetEvent(false);
public ConnexionParameter(TcpClient client, string address, int port, int timeout, Thread principale)
{
this.client = client;
this.address = address;
this.port = port;
this.principale = principale;
this.timeout = timeout;
thisthread = new Thread(Connect);
}
public void Connect()
{
WatchDog.Start(timeout, this);
try
{
client.Connect(IPAddress.Parse(address), port);
}
catch (Exception)
{
UnityEngine.Debug.LogWarning("Unable to connect service (Training mode? Or not running?)");
}
OnTimeOver();
//principale.Resume();
}
public bool IsConnected = true;
public void OnTimeOver()
{
try
{
if (!client.Connected)
{
/*there is the trick. The abort method from thread doesn't
make the connection stop immediately(I think it's because it rise an exception
that make time to stop). Instead I close the socket while it's trying to
connect , that make the connection method return faster*/
IsConnected = false;
client.Close();
}
wh.Set();
}
catch(Exception)
{
UnityEngine.Debug.LogWarning("Connexion already closed, or forcing connexion thread to end. Ignore.");
}
}
public void Start()
{
thisthread.Start();
wh.WaitOne();
//principale.Suspend();
}
public bool Get()
{
Start();
return IsConnected;
}
}
public static class Connexion
{
public static bool Connect(this TcpClient client, string address, int port, int timeout)
{
ConnexionParameter cp = new ConnexionParameter(client, address, port, timeout, Thread.CurrentThread);
return cp.Get();
}
//http://stackoverflow.com/questions/19653588/timeout-at-acceptsocket
public static Socket AcceptSocket(this TcpListener tcpListener, int timeoutms, int pollInterval = 10)
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutms);
var stopWatch = new Stopwatch();
stopWatch.Start();
while (stopWatch.Elapsed < timeout)
{
if (tcpListener.Pending())
return tcpListener.AcceptSocket();
Thread.Sleep(pollInterval);
}
return null;
}
}
and there a very simple watchdog on C# to make it work:
using System.Threading;
public interface Guardian
{
void OnTimeOver();
}
public class WatchDog {
int m_iMs;
Guardian m_guardian;
public WatchDog(int a_iMs, Guardian a_guardian)
{
m_iMs = a_iMs;
m_guardian = a_guardian;
Thread thread = new Thread(body);
thread.Start(this);
}
private void body(object o)
{
WatchDog watchdog = (WatchDog)o;
Thread.Sleep(watchdog.m_iMs);
watchdog.m_guardian.OnTimeOver();
}
public static void Start(int a_iMs, Guardian a_guardian)
{
new WatchDog(a_iMs, a_guardian);
}
}
you can got Current latlng using this
`
public class MainActivity extends ActionBarActivity {
private LocationManager locationManager;
private String provider;
private MyLocationListener mylistener;
private Criteria criteria;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //default
// user defines the criteria
criteria.setCostAllowed(false);
// get the best provider depending on the criteria
provider = locationManager.getBestProvider(criteria, false);
// the last known location of this provider
Location location = locationManager.getLastKnownLocation(provider);
mylistener = new MyLocationListener();
if (location != null) {
mylistener.onLocationChanged(location);
} else {
// leads to the settings because there is no last known location
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
// location updates: at least 1 meter and 200millsecs change
locationManager.requestLocationUpdates(provider, 200, 1, mylistener);
String a=""+location.getLatitude();
Toast.makeText(getApplicationContext(), a, 222).show();
}
private class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {
// Initialize the location fields
Toast.makeText(MainActivity.this, ""+location.getLatitude()+location.getLongitude(),
Toast.LENGTH_SHORT).show()
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, provider + "'s status changed to "+status +"!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " enabled!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Provider " + provider + " disabled!",
Toast.LENGTH_SHORT).show();
}
}
`
You can simply format your range as Text.
Also here is a nice article on the number formats and how you can program them.
Similarly, I needed to create an rpm with just a few files. Since these files were source controlled, and because it seemed silly, I didn't want to go through taring them up just to have rpm untar them. I came up with the following:
Set up your environment:
mkdir -p ~/rpm/{BUILD,RPMS}
echo '%_topdir %(echo "$HOME")/rpm' > ~/.rpmmacros
Create your spec file, foobar.spec, with the following contents:
Summary: Foo to the Bar
Name: foobar
Version: 0.1
Release: 1
Group: Foo/Bar
License: FooBarPL
Source: %{expand:%%(pwd)}
BuildRoot: %{_topdir}/BUILD/%{name}-%{version}-%{release}
%description
%{summary}
%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT/usr/bin
mkdir -p $RPM_BUILD_ROOT/etc
cd $RPM_BUILD_ROOT
cp %{SOURCEURL0}/foobar ./usr/bin/
cp %{SOURCEURL0}/foobar.conf ./etc/
%clean
rm -r -f "$RPM_BUILD_ROOT"
%files
%defattr(644,root,root)
%config(noreplace) %{_sysconfdir}/foobar.conf
%defattr(755,root,root)
%{_bindir}/foobar
Build your rpm:
rpmbuild -bb foobar.spec
There's a little hackery there specifying the 'source' as your current directory, but it seemed far more elegant then the alternative, which was to, in my case, write a separate script to create a tarball, etc, etc.
Note: In my particular situation, my files were arranged in folders according to where they needed to go, like this:
./etc/foobar.conf
./usr/bin/foobar
and so the prep section became:
%prep
rm -rf $RPM_BUILD_ROOT
mkdir -p $RPM_BUILD_ROOT
cd $RPM_BUILD_ROOT
tar -cC %{SOURCEURL0} --exclude 'foobar.spec' -f - ./ | tar xf -
Which is a little cleaner.
Also, I happen to be on a RHEL5.6 with rpm versions 4.4.2.3, so your mileage may vary.
Well I am new to tensorflow, I have Geforce 740m or something GPU with 2GB ram, I was running mnist handwritten kind of example for a native language with training data containing of 38700 images and 4300 testing images and was trying to get precision , recall , F1 using following code as sklearn was not giving me precise reults. once i added this to my existing code i started getting GPU errors.
TP = tf.count_nonzero(predicted * actual)
TN = tf.count_nonzero((predicted - 1) * (actual - 1))
FP = tf.count_nonzero(predicted * (actual - 1))
FN = tf.count_nonzero((predicted - 1) * actual)
prec = TP / (TP + FP)
recall = TP / (TP + FN)
f1 = 2 * prec * recall / (prec + recall)
plus my model was heavy i guess, i was getting memory error after 147, 148 epochs, and then I thought why not create functions for the tasks so I dont know if it works this way in tensrorflow, but I thought if a local variable is used and when out of scope it may release memory and i defined the above elements for training and testing in modules, I was able to achieve 10000 epochs without any issues, I hope this will help..
The Subject, in security, is the thing being secured. In this case it could be a persons email or a website or a machine.
If we take the example of an email, say my email, then the subject key container would be the protected location containing my private key.
The certificate store usually refers to Microsoft certificate store which contains certificates form trusted roots, machines on the network, people etc. In my case the subjects certificate store would be the place, within this store, holding my certificates.
If you are working within a microsoft domain then the subject name will invariably hold the Distinguished Name, of the subject, which is how the domain references the subject and holds it in its directory. e.g. CN=Mark Sutton, OU=Developers, O=Mycompany C=UK
To look at your certificates on a microsoft machine:-
Log in as you run>mmc Select File>add/remove snap-in and select certificates then select my user account click Finish then close then ok. Look in the personal area of the store.
In the other areas of the store you will see the other trusted certificates used to validate signatures etc.
For non-InnoDB tables you could also use the information schema tables:
Even if there are tools that allow you to mock your database in one way or another (e.g. jOOQ's MockConnection
, which can be seen in this answer - disclaimer, I work for jOOQ's vendor), I would advise not to mock larger databases with complex queries.
Even if you just want to integration-test your ORM, beware that an ORM issues a very complex series of queries to your database, that may vary in
Mocking all that to produce sensible dummy data is quite hard, unless you're actually building a little database inside your mock, which interprets the transmitted SQL statements. Having said so, use a well-known integration-test database that you can easily reset with well-known data, against which you can run your integration tests.
var json = { ... };
var key = "foo";
delete json[key]; // Removes json.foo from the dictionary.
You can use splice to remove elements from an array.
If you are working with more than 1 set of values and wish to have a list of dicts you can use this:
def as_dict_list(data: list, columns: list):
return [dict((zip(columns, row))) for row in data]
Real-life example would be a list of tuples from a db query paired to a tuple of columns from the same query. Other answers only provided for 1 to 1.
I got this issue when installing Bootstrap.
The following commands are what worked for me:
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/[email protected]
I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.
Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))
I wrote my self a helper method to get patterns for this.
public static String getPattern(int month) {
String first = "MMMM dd";
String last = ", yyyy";
String pos = (month == 1 || month == 21 || month == 31) ? "'st'" : (month == 2 || month == 22) ? "'nd'" : (month == 3 || month == 23) ? "'rd'" : "'th'";
return first + pos + last;
}
and then we can call it as
LocalDate localDate = LocalDate.now();//For reference
int month = localDate.getDayOfMonth();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(getPattern(month));
String date = localDate.format(formatter);
System.out.println(date);
the output is
December 12th, 2018
You have to go to its parent and remove it from there in javascript.
"Javascript won't let an element commit suicide, but it does permit infanticide"..:)
try this,
var element=document.getElementsByName(val))
element.parentNode.removeChild(element.options[0]); // to remove first option
My observation on initial accepted solution.
Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.
Simple but usefull way:
$query = $this->db->distinct()->select('order_id')->get_where('tbl_order_details', array('seller_id' => $seller_id));
return $query;
Unlimited loop in one-line command for use in cmd
windows:
FOR /L %N IN () DO @echo Oops
>>> import numpy
>>> print numpy.power.__doc__
power(x1, x2[, out])
First array elements raised to powers from second array, element-wise.
Raise each base in `x1` to the positionally-corresponding power in
`x2`. `x1` and `x2` must be broadcastable to the same shape.
Parameters
----------
x1 : array_like
The bases.
x2 : array_like
The exponents.
Returns
-------
y : ndarray
The bases in `x1` raised to the exponents in `x2`.
Examples
--------
Cube each element in a list.
>>> x1 = range(6)
>>> x1
[0, 1, 2, 3, 4, 5]
>>> np.power(x1, 3)
array([ 0, 1, 8, 27, 64, 125])
Raise the bases to different exponents.
>>> x2 = [1.0, 2.0, 3.0, 3.0, 2.0, 1.0]
>>> np.power(x1, x2)
array([ 0., 1., 8., 27., 16., 5.])
The effect of broadcasting.
>>> x2 = np.array([[1, 2, 3, 3, 2, 1], [1, 2, 3, 3, 2, 1]])
>>> x2
array([[1, 2, 3, 3, 2, 1],
[1, 2, 3, 3, 2, 1]])
>>> np.power(x1, x2)
array([[ 0, 1, 8, 27, 16, 5],
[ 0, 1, 8, 27, 16, 5]])
>>>
As per the discussed observation on numerical precision as per @GarethRees objection in comments:
>>> a = numpy.ones( (3,3), dtype = numpy.float96 ) # yields exact output
>>> a[0,0] = 0.46002700024131926
>>> a
array([[ 0.460027, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> b = numpy.power( a, 2 )
>>> b
array([[ 0.21162484, 1.0, 1.0],
[ 1.0, 1.0, 1.0],
[ 1.0, 1.0, 1.0]], dtype=float96)
>>> a.dtype
dtype('float96')
>>> a[0,0]
0.46002700024131926
>>> b[0,0]
0.21162484095102677
>>> print b[0,0]
0.211624840951
>>> print a[0,0]
0.460027000241
>>> c = numpy.random.random( ( 1000, 1000 ) ).astype( numpy.float96 )
>>> import zmq
>>> aClk = zmq.Stopwatch()
>>> aClk.start(), c**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 5663L) # 5 663 [usec]
>>> aClk.start(), c*c, aClk.stop()
(None, array([[ ...]], dtype=float96), 6395L) # 6 395 [usec]
>>> aClk.start(), c[:,:]*c[:,:], aClk.stop()
(None, array([[ ...]], dtype=float96), 6930L) # 6 930 [usec]
>>> aClk.start(), c[:,:]**2, aClk.stop()
(None, array([[ ...]], dtype=float96), 6285L) # 6 285 [usec]
>>> aClk.start(), numpy.power( c, 2 ), aClk.stop()
(None, array([[ ... ]], dtype=float96), 384515L) # 384 515 [usec]
goto Android->sdk->build-tools directory make sure you have all the versions required . if not , download them . after that goto File-->Settigs-->Build,Execution,Depoyment-->Gradle
choose use default gradle wapper (recommended)
and untick Offline work
gradle build finishes successfully for once you can change the settings
If it dosent simply solve the problem
check this link to find an appropriate support library revision
https://developer.android.com/topic/libraries/support-library/revisions
Make sure that the compile sdk and target version same as the support library version. It is recommended maintain network connection atleast for the first time build (Remember to rebuild your project after doing this)
You can use git cherry-pick to apply a single commit by itself to your current branch.
Example: git cherry-pick d42c389f
This method is much faster. You can only tel when placing a lot of files in a directory. My A:\ external hard drive contains almost 1 terabit so it makes a big difference when dealing with a lot of files.
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("A:\\");
FullDirList(di, "*");
Console.WriteLine("Done");
Console.Read();
}
static List<FileInfo> files = new List<FileInfo>(); // List that will hold the files and subfiles in path
static List<DirectoryInfo> folders = new List<DirectoryInfo>(); // List that hold direcotries that cannot be accessed
static void FullDirList(DirectoryInfo dir, string searchPattern)
{
// Console.WriteLine("Directory {0}", dir.FullName);
// list the files
try
{
foreach (FileInfo f in dir.GetFiles(searchPattern))
{
//Console.WriteLine("File {0}", f.FullName);
files.Add(f);
}
}
catch
{
Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
return; // We alredy got an error trying to access dir so dont try to access it again
}
// process each directory
// If I have been able to see the files in the directory I should also be able
// to look at its directories so I dont think I should place this in a try catch block
foreach (DirectoryInfo d in dir.GetDirectories())
{
folders.Add(d);
FullDirList(d, searchPattern);
}
}
By the way I got this thanks to your comment Jim Mischel
Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.
Commands are first read from /etc/zshenv this cannot be overridden.
Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
former affects all startup files, while the second only affects global
startup files (those shown here with an path starting with a /). If
one of the options is unset at any point, any subsequent startup
file(s) of the corresponding type will not be read. It is also possi-
ble for a file in $ZDOTDIR to re-enable GLOBAL_RCS. Both RCS and
GLOBAL_RCS are set by default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login
shell, commands are read from /etc/zprofile and then $ZDOTDIR/.zpro-
file. Then, if the shell is interactive, commands are read from
/etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if the shell is a login
shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
From this we can see the order files are read is:
/etc/zshenv # Read for every shell
~/.zshenv # Read for every shell except ones started with -f
/etc/zprofile # Global config for login shells, read before zshrc
~/.zprofile # User config for login shells
/etc/zshrc # Global config for interactive shells
~/.zshrc # User config for interactive shells
/etc/zlogin # Global config for login shells, read after zshrc
~/.zlogin # User config for login shells
~/.zlogout # User config for login shells, read upon logout
/etc/zlogout # Global config for login shells, read after user logout file
You can get more information here.
You can also simply use http authentication with Digest (Here some infos if you use Apache httpd, Apache Tomcat, and here an explanation of digest).
With Java, for interesting informations, take a look at :
Though Andrew already answered question with details , i am giving code how to exclude it in pom
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.9</version>
<configuration>
<excludes>
<exclude>**/*com/test/vaquar/khan/HealthChecker.class</exclude>
</excludes>
</configuration>
<executions>
<!-- prepare agent for measuring integration tests -->
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>jacoco-site</id>
<phase>package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
For Springboot application
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>sonar-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.sonarsource.scanner.maven</groupId>
<artifactId>sonar-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<configuration>
<excludes>
<!-- Exclude class from test coverage -->
<exclude>**/*com/khan/vaquar/Application.class</exclude>
<!-- Exclude full package from test coverage -->
<exclude>**/*com/khan/vaquar/config/**</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
Something neat...
I wanted to look up an "Exact Town ID" based on a "Partial Exact Town Name" BUT although I had the entire town name I was searching against a list of Partial town names. So I First found the "Exact Town Name" based on the part (which was actually a partial name since the "master list" is partial names unfortunately)... THEN searched for the "Exact Town ID" based on that Exact town name SO all my Vlookups/Index/Match-whatevers....were set to EXACT ....
=INDEX(county_cheatsheet!$E$1:$E$516,MATCH(VLOOKUP(LEFT(D3,3)&"*",county_cheatsheet!$E$1:$E$516,1,FALSE),county_cheatsheet!$E$1:E$516,0))
The lookup of the "first three letters of the partial town name against the list of partial town names is the MATCH(VLOOKUP(LEFT(D3,3)&"*" part
The ConcurrentHashMap
is very similar to the HashMap
class, except that ConcurrentHashMap
offers internally maintained concurrency. It means you do not need to have synchronized blocks when accessing ConcurrentHashMap
in multithreaded application.
To get all key-value pairs in ConcurrentHashMap
, below code which is similar to your code works perfectly:
//Initialize ConcurrentHashMap instance
ConcurrentHashMap<String, Integer> m = new ConcurrentHashMap<String, Integer>();
//Print all values stored in ConcurrentHashMap instance
for each (Entry<String, Integer> e : m.entrySet()) {
System.out.println(e.getKey()+"="+e.getValue());
}
Above code is reasonably valid in multi-threaded environment in your application. The reason, I am saying 'reasonably valid' is that, above code yet provides thread safety, still it can decrease the performance of application.
Hope this helps you.
For OSX 10.11 or more you can download from here https://developer.apple.com/download/more/.
(The link in the accepted answer doesn't display command line tools for El Capitan (OSX 10.11))
Add overflow: auto to the container div. http://www.quirksmode.org/css/clearing.html This website shows a few options when having this issue.
You have to add CORS on the server side:
If you are using nodeJS then:
First you need to install cors
by using below command :
npm install cors --save
Now add the following code to your app starting file like ( app.js or server.js
)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
Yet another way
$("#wizard li").click(function ()
{
$($(this),'#wizard"').index();
});
You should use the * operator, like foo(*values)
Read the Python doc unpackaging argument lists.
Also, do read this: http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/
def foo(x,y,z):
return "%d, %d, %d" % (x,y,z)
values = [1,2,3]
# the solution.
foo(*values)
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
It depends on many things. It's usually O(1), with a decent hash which itself is constant time... but you could have a hash which takes a long time to compute, and if there are multiple items in the hash map which return the same hash code, get
will have to iterate over them calling equals
on each of them to find a match.
In the worst case, a HashMap
has an O(n) lookup due to walking through all entries in the same hash bucket (e.g. if they all have the same hash code). Fortunately, that worst case scenario doesn't come up very often in real life, in my experience. So no, O(1) certainly isn't guaranteed - but it's usually what you should assume when considering which algorithms and data structures to use.
In JDK 8, HashMap
has been tweaked so that if keys can be compared for ordering, then any densely-populated bucket is implemented as a tree, so that even if there are lots of entries with the same hash code, the complexity is O(log n). That can cause issues if you have a key type where equality and ordering are different, of course.
And yes, if you don't have enough memory for the hash map, you'll be in trouble... but that's going to be true whatever data structure you use.
Search the file my.cnf and comment the line
skip-networking
to
#skip-networking
Restart mysql
You could fix merge conflicts in a number of ways as other have detailed.
I think the real key is knowing how changes flow with local and remote repositories. The key to this is understanding tracking branches. I have found that I think of the tracking branch as the 'missing piece in the middle' between me my local, actual files directory and the remote defined as origin.
I've personally got into the habit of 2 things to help avoid this.
Instead of:
git add .
git commit -m"some msg"
Which has two drawbacks -
a) All new/changed files get added and that might include some unwanted changes.
b) You don't get to review the file list first.
So instead I do:
git add file,file2,file3...
git commit # Then type the files in the editor and save-quit.
This way you are more deliberate about which files get added and you also get to review the list and think a bit more while using the editor for the message. I find it also improves my commit messages when I use a full screen editor rather than the -m
option.
[Update - as time has passed I've switched more to:
git status # Make sure I know whats going on
git add .
git commit # Then use the editor
]
Also (and more relevant to your situation), I try to avoid:
git pull
or
git pull origin master.
because pull implies a merge and if you have changes locally that you didn't want merged you can easily end up with merged code and/or merge conflicts for code that shouldn't have been merged.
Instead I try to do
git checkout master
git fetch
git rebase --hard origin/master # or whatever branch I want.
You may also find this helpful:
git branch, fork, fetch, merge, rebase and clone, what are the differences?
The best way to do this would be to use the promise returning function as it is, like this
lookupValue(file).then(function(res) {
// Write the code which depends on the `res.val`, here
});
The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.
So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.
Two-way binding just means that:
Backbone doesn't have a "baked-in" implementation of #2 (although you can certainly do it using event listeners). Other frameworks like Knockout do wire up two-way binding automagically.
In Backbone, you can easily achieve #1 by binding a view's "render" method to its model's "change" event. To achieve #2, you need to also add a change listener to the input element, and call model.set
in the handler.
Here's a Fiddle with two-way binding set up in Backbone.
It will be fixed 64 chars, so use char(64)
The Bootstrap Collapse has some Events that you can react to:
$(document).ready(function(){
$('#accordProfile').on('shown', function () {
$(".icon-chevron-down").removeClass("icon-chevron-down").addClass("icon-chevron-up");
});
$('#accordProfile').on('hidden', function () {
$(".icon-chevron-up").removeClass("icon-chevron-up").addClass("icon-chevron-down");
});
});
I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.
This code will:
This is not a fast method but will iterate through each one individually as you suggested is your intention.
Sub iterateThroughAll()
ScreenUpdating = False
Dim wks As Worksheet
Set wks = ActiveSheet
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
Set rowRange = wks.Range("A1:A" & LastRow)
'Loop through each row
For Each rrow In rowRange
'Find Last column in current row
LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))
'Loop through all cells in row up to last col
For Each cell In colRange
'Do something to each cell
Debug.Print (cell.Value)
Next cell
Next rrow
ScreenUpdating = True
End Sub
I find that the the approved answer, request.env['PATH_INFO']
, works for getting the base URL, but this does not always contain the full path if you have nested routes. You can use request.env['HTTP_REFERER']
to get the full path and then see if it matches a given route:
request.env['HTTP_REFERER'].match?(my_cool_path)
Actually every code runs well here, but your probleme probably come from your gender
variable. Did you try to do a simple System.out.println(gender);
before the comparaison ?
Consider a example where I have two databases namely allmsa.db and atlanta.db. Say the database allmsa.db has tables for all msas in US and database atlanta.db is empty.
Our target is to copy the table atlanta from allmsa.db to atlanta.db.
ATTACH '/mnt/fastaccessDS/core/csv/allmsa.db' AS AM;
note that we give the entire path of the database to be attached.sqlite> .databases
you can see the output asseq name file --- --------------- ---------------------------------------------------------- 0 main /mnt/fastaccessDS/core/csv/atlanta.db 2 AM /mnt/fastaccessDS/core/csv/allmsa.db
INSERT INTO atlanta SELECT * FROM AM.atlanta;
This should serve your purpose.
fpdf is python (too). And often used. See PyPI / pip search. But maybe it was renamed from pyfpdf to fpdf. From features: PNG, GIF and JPG support (including transparency and alpha channel)
When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.
Returns
["some string yay", "Other string yay"]
array_walk()
can be used with trim()
to trim array
<?php
function trim_value(&$value)
{
$value = trim($value);
}
$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);
array_walk($fruit, 'trim_value');
var_dump($fruit);
?>
See 2nd example at http://www.php.net/manual/en/function.trim.php
This cannot be done with the native javascript dialog box, but a lot of javascript libraries include more flexible dialogs. You can use something like jQuery UI's dialog box for this.
See also these very similar questions:
Here's an example, as demonstrated in this jsFiddle:
<html><head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.17/themes/base/jquery-ui.css">
</head>
<body>
<a class="checked" href="http://www.google.com">Click here</a>
<script type="text/javascript">
$(function() {
$('.checked').click(function(e) {
e.preventDefault();
var dialog = $('<p>Are you sure?</p>').dialog({
buttons: {
"Yes": function() {alert('you chose yes');},
"No": function() {alert('you chose no');},
"Cancel": function() {
alert('you chose cancel');
dialog.dialog('close');
}
}
});
});
});
</script>
</body><html>
I have to offer this as a better approach - you don't always have the luxury of an identity field:
UPDATE m
SET [status]=10
FROM (
Select TOP (10) *
FROM messages
WHERE [status]=0
ORDER BY [priority] DESC
) m
You can also make the sub-query as complicated as you want - joining multiple tables, etc...
Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages
table. It can be used to update the top N rows from any table, even if that table has no unique key at all.
IDisposable
is good for unsubscribing from events.
As I haven't seen it at serverfault yet, and the answer is quite simple:
Change:
ssh -f -L3310:remote.server:3306 [email protected] -N
To:
ssh -f -L3310:localhost:3306 [email protected] -N
And change:
mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name
To:
mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name
(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)
edit: well, to elaborate: if host is set to localhost
, a configured (or default) --socket
option is assumed. See the manual for which option files are sought / used. Under Windows, this can be a named pipe.
getCurrentActivity().getFragmentManager()
Try this
<div class="row row-offcanvas row-offcanvas-right">
<div class="col-xs-6 col-sm-3 sidebar-offcanvas" id="sidebar" role="navigation">Nav Content</div>
<div class="col-xs-12 col-sm-9">Content goes here</div>
</div>
This uses Bootstrap 3 so no need for extra CSS etc...
You should amend creation of the gesture recogniser to accept parameter (add colon ':')
UITapGestureRecognizer *letterTapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(highlightLetter:)];
And in your method highlightLetter: you can access the view attached to recogniser:
-(IBAction) highlightLetter:(UITapGestureRecognizer*)recognizer
{
UIView *view = [recognizer view];
}
All the above solutions require two database calls. The below sql code combine two sql statements into one.
select * from foo
where (
id = IFNULL((select min(id) from foo where id > 4),0)
or id = IFNULL((select max(id) from foo where id < 4),0)
)