PYTHONPATH is an environment variable whose value is a list of directories. Once set, it is used by Python to search for imported modules, along with other std. and 3rd-party library directories listed in Python's "sys.path".
As any other environment variables, you can either export it in shell or in ~/.bashrc, see here. You can query os.environ['PYTHONPATH'] for its value in Python as shown below:
$ python3 -c "import os, sys; print(os.environ['PYTHONPATH']); print(sys.path) if 'PYTHONPATH' in sorted(os.environ) else print('PYTHONPATH is not defined')"
IF defined in shell as
$ export PYTHONPATH=$HOME/Documents/DjangoTutorial/mysite
THEN result =>
/home/Documents/DjangoTutorial/mysite
['', '/home/Documents/DjangoTutorial/mysite', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
ELSE result =>
PYTHONPATH is not defined
To set PYTHONPATH to multiple paths, see here.
Note that one can add or delete a search path via sys.path.insert(), del or remove() at run-time, but NOT through os.environ[]. Example:
>>> os.environ['PYTHONPATH']="$HOME/Documents/DjangoTutorial/mysite"
>>> 'PYTHONPATH' in sorted(os.environ)
True
>>> sys.path // but Not there
['', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>> sys.path.insert(0,os.environ['PYTHONPATH'])
>>> sys.path // It's there
['$HOME/Documents/DjangoTutorial/mysite', '', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages']
>>>
In summary, PYTHONPATH is one way of specifying the Python search path(s) for imported modules in sys.path. You can also apply list operations directly to sys.path without the aid of PYTHONPATH.
When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT
variable for you; after all, your script runs in their environment.
Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000
instead of process.env.PORT || 3000
where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.
This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;
app.listen(port);
The simplest way in Python:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
This assumes that your program takes at least a tenth of second to run.
Prints:
--- 0.764891862869 seconds ---
Create enviroment variable in your .bashrc
export RUNSERVER_PORT=8010
Create alias
alias runserver='django-admin runserver $RUNSERVER_PORT'
Im using zsh and virtualenvs wrapper. I put export in projects postactivate script and asign port for every project.
workon someproject
runserver
In the context of a revision list, A...B
is how git-rev-parse
defines it. git-log takes a revision list. git-diff
does not take a list of revisions - it takes one or two revisions, and has defined the A...B
syntax to mean how it's defined in the git-diff
manpage. If git-diff
did not explicitly define A...B
, then that syntax would be invalid. Note that the git-rev-parse
manpage describes A...B
in the "Specifying Ranges" section, and everything in that section is only valid in situations where a revision range is valid (i.e. when a revision list is desired).
To get a log containing just x, y, and z, try git log HEAD..branch
(two dots, not three). This is identical to git log branch --not HEAD
, and means all commits on branch that aren't on HEAD.
Example query:
SELECT TO_CHAR(TO_DATE('2017-08-23','YYYY-MM-DD'), 'MM/DD/YYYY') FROM dual;
In the first case alternatively to multiline forEach
you can use the peek
stream operation:
entryList.stream()
.peek(entry -> entry.setTempId(tempId))
.forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));
In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach
. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.
Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.
The best way to use is white-space: nowrap;
This will align the text to one line.
This example selects a new Range
of Cells
defined by the current cell to a cell 5 to the right.
Note that .Offset
takes arguments of Offset(row, columns)
and can be quite useful.
Sub testForStackOverflow()
Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub
I suggest to approximate locally the Earth surface as a sphere with radius given by the WGS84 ellipsoid at the given latitude. I suspect that the exact computation of latMin and latMax would require elliptic functions and would not yield an appreciable increase in accuracy (WGS84 is itself an approximation).
My implementation follows (It's written in Python; I have not tested it):
# degrees to radians
def deg2rad(degrees):
return math.pi*degrees/180.0
# radians to degrees
def rad2deg(radians):
return 180.0*radians/math.pi
# Semi-axes of WGS-84 geoidal reference
WGS84_a = 6378137.0 # Major semiaxis [m]
WGS84_b = 6356752.3 # Minor semiaxis [m]
# Earth radius at a given latitude, according to the WGS-84 ellipsoid [m]
def WGS84EarthRadius(lat):
# http://en.wikipedia.org/wiki/Earth_radius
An = WGS84_a*WGS84_a * math.cos(lat)
Bn = WGS84_b*WGS84_b * math.sin(lat)
Ad = WGS84_a * math.cos(lat)
Bd = WGS84_b * math.sin(lat)
return math.sqrt( (An*An + Bn*Bn)/(Ad*Ad + Bd*Bd) )
# Bounding box surrounding the point at given coordinates,
# assuming local approximation of Earth surface as a sphere
# of radius given by WGS84
def boundingBox(latitudeInDegrees, longitudeInDegrees, halfSideInKm):
lat = deg2rad(latitudeInDegrees)
lon = deg2rad(longitudeInDegrees)
halfSide = 1000*halfSideInKm
# Radius of Earth at given latitude
radius = WGS84EarthRadius(lat)
# Radius of the parallel at given latitude
pradius = radius*math.cos(lat)
latMin = lat - halfSide/radius
latMax = lat + halfSide/radius
lonMin = lon - halfSide/pradius
lonMax = lon + halfSide/pradius
return (rad2deg(latMin), rad2deg(lonMin), rad2deg(latMax), rad2deg(lonMax))
EDIT: The following code converts (degrees, primes, seconds) to degrees + fractions of a degree, and vice versa (not tested):
def dps2deg(degrees, primes, seconds):
return degrees + primes/60.0 + seconds/3600.0
def deg2dps(degrees):
intdeg = math.floor(degrees)
primes = (degrees - intdeg)*60.0
intpri = math.floor(primes)
seconds = (primes - intpri)*60.0
intsec = round(seconds)
return (int(intdeg), int(intpri), int(intsec))
If you are using the Android flavor of Java, might I suggest using a SparseArray. It's a more memory efficient mapping of integers to objects and easier to iterate over than a Map
For an easy and appropriate way of doing this, first download a prepackaged release of freeglut from here. Then read its Readme.txt.
I copied some important parts of that package here:
... Create a folder on your PC which is readable by all users, for example “C:\Program Files\Common Files\MSVC\freeglut\” on a typical Windows system. Copy the “lib\” and “include\” folders from this zip archive to that location ... freeglut DLL can be placed in the same folder as your application...
... Open up the project properties, and select “All Configurations” (this is necessary to ensure our changes are applied for both debug and release builds). Open up the “general” section under “C/C++”, and configure the “include\” folder you created above as an “Additional Include Directory”. If you have more than one GLUT package which contains a “glut.h” file, it’s important to ensure that the freeglut include folder appears above all other GLUT include folders ... Open up the “general” section under “Linker”, and configure the “lib\” folder you created above as an “Additional Library Directory”...
You have two options
INNER JOIN x
ON x.qid = y.qid OR (x.qid IS NULL AND y.qid IS NULL)
or easier
INNER JOIN x
ON x.qid IS NOT DISTINCT FROM y.qid
This happened to me when my git remote (bitbucket.org) changed their IP address. The quick fix was to remove and re-add the remote, then everything worked as expected. If you're not familiar with how to remove and re-add a remote in git, here are the steps:
Copy the SSH git URL of your existing remote. You can print it to the terminal using this command:
git remote -v
which will print out something like this:
origin [email protected]:account-name/repo-name.git (fetch)
origin [email protected]:account-name/repo-name.git (push)
Remove the remote from your local git repo:
git remote rm origin
Add the remote back to your local repo:
git remote add origin [email protected]:account-name/repo-name.git
I am using Windows 7 and have struggled with the same issue. I fixed it by changing my environment variables.
To change your environment variables click here
I added ";%JAVA_HOME%/bin" to the end of paths variable and added a new "JAVA_HOME" variable and set its value to the location of my JDK "C:\Program Files\Java\jdk1.8.0_11". After that I restarted my Node.js command prompt and it worked.
Please note you JDK directory may be different then mine. Also depending on your setup, you may need to restart you computer after setting the environment variables.
Are you sure you need a list in this case? If you are populating the list with many items, performance will suffer with myList.Contains
or myList.Any
; the run-time will be quadratic. You might want to consider using a better data structure. For example,
public class MyClass
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
public class MyClassComparer : EqualityComparer<MyClass>
{
public override bool Equals(MyClass x, MyClass y)
{
if(x == null || y == null)
return x == y;
return x.Property1 == y.Property1 && x.Property2 == y.Property2;
}
public override int GetHashCode(MyClass obj)
{
return obj == null ? 0 : (obj.Property1.GetHashCode() ^ obj.Property2.GetHashCode());
}
}
You could use a HashSet in the following manner:
var set = new HashSet<MyClass>(new MyClassComparer());
foreach(var myClass in ...)
set.Add(myClass);
Of course, if this definition of equality for MyClass
is 'universal', you needn't write an IEqualityComparer
implementation; you could just override GetHashCode
and Equals
in the class itself.
This was an issue for me years ago and I'd previously fixed it in Eclipse by excluding 1.7 from my projects, but it became an issue again for IntelliJ, which I recently installed. I fixed it by:
Uninstalling the JDK:
cd /Library/Java/JavaVirtualMachines
sudo rm -rf jdk1.8.0_45.jdk
(I had jdk1.8.0_45.jdk
installed; obviously you should uninstall whichever java version is listed in that folder. The offending files are located in that folder and should be deleted.)
Note that the next time you create a new project, or open an existing project, you will need to set the project SDK to point to the new JDK install. You also may still see this bug or have it creep back if you have JDK 1.7 installed in your JavaVirtualMachines folder (which is what I believe happened to me).
If you're talking about ASP.NET MVC then you should have a controller method that returns the following:
return Redirect("http://www.google.com");
Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.
My favourites have always been
use constant FALSE => 1==0;
use constant TRUE => not FALSE;
which is completely independent from the internal representation.
date.ToString("o") // The Round-trip ("O", "o") Format Specifier
date.ToString("s") // The Sortable ("s") Format Specifier, conforming to ISO86801
For Linux (I am using Fedora 30) the Shortcut is (Window/Start + Space) Try that and tell me. That works for me
This worked for me:
#include <iostream>
#include <pthread.h>
using namespace std;
void* print_message(void*) {
cout << "Threading\n";
}
int main() {
pthread_t t1;
pthread_create(&t1, NULL, &print_message, NULL);
cout << "Hello";
// Optional.
void* result;
pthread_join(t1,&result);
// :~
return 0;
}
A parent ViewGroup into which the fragment's View is to be inserted,
A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.
In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .
View rootView = inflater.inflate(R.layout.fragment_photos, container, false);
So, You need to call rootView
in here
ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);
If you are looking for a way to import all your images from the image
// Import all images in image folder
function importAll(r) {
let images = {};
r.keys().map((item, index) => { images[item.replace('./', '')] = r(item); });
return images;
}
const images = importAll(require.context('../images', false, /\.(gif|jpe?g|svg)$/));
Then:
<img src={images['image-01.jpg']}/>
You can find the original thread here: Dynamically import images from a directory using webpack
I have done something similar to this. One approach is to interpolate over the animation time the height of the view over time inside the rows onMeasure
while issuing requestLayout()
for the listView. Yes it may be be better to do inside the listView code directly but it was a quick solution (that looked good!)
First you should read an explanation on the output of free
. Bottom line: you have at least 10.7 GB of memory readily usable by processes.
Then you should define what "memory usage" is for a process (it's not easy or unambiguous, trust me).
Then we might be able to help more :-)
In case, if you need a no jquery solution
<label class="custom-file">
<input type="file" id="myfile" class="custom-file-input" onchange="this.nextElementSibling.innerText = this.files[0].name">
<span class="custom-file-control"></span>
</label>
Have a look at this picture: Graphical Projections
The glOrtho
command produces an "Oblique" projection that you see in the bottom row. No matter how far away vertexes are in the z direction, they will not recede into the distance.
I use glOrtho every time I need to do 2D graphics in OpenGL (such as health bars, menus etc) using the following code every time the window is resized:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, windowWidth, windowHeight, 0.0f, 0.0f, 1.0f);
This will remap the OpenGL coordinates into the equivalent pixel values (X going from 0 to windowWidth and Y going from 0 to windowHeight). Note that I've flipped the Y values because OpenGL coordinates start from the bottom left corner of the window. So by flipping, I get a more conventional (0,0) starting at the top left corner of the window rather.
Note that the Z values are clipped from 0 to 1. So be careful when you specify a Z value for your vertex's position, it will be clipped if it falls outside that range. Otherwise if it's inside that range, it will appear to have no effect on the position except for Z tests.
Better to use a HashSet
than an ArrayList
when you are checking for existence of a value.
Java docs for HashSet
says: "This class offers constant time performance for the basic operations (add, remove, contains and size)"
ArrayList.contains()
might have to iterate the whole list to find the instance you are looking for.
Since it wasn't mentioned, you can also use the CSS white-space property
body{
white-space:pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "hello\nthere";
?>
</body>
Would display
hello
there
The sp_xml_preparedocument
stored procedure will parse the XML and the OPENXML
rowset provider will show you a relational view of the XML data.
For details and more examples check the OPENXML documentation.
As for your question,
DECLARE @XML XML
SET @XML = '<rows><row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row></rows>'
DECLARE @handle INT
DECLARE @PrepareXmlStatus INT
EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML
SELECT *
FROM OPENXML(@handle, '/rows/row', 2)
WITH (
IdInvernadero INT,
IdProducto INT,
IdCaracteristica1 INT,
IdCaracteristica2 INT,
Cantidad INT,
Folio INT
)
EXEC sp_xml_removedocument @handle
Web Audio API is right tool for this job. There is little bit of work involved in loading sounds files and playing it. Luckily there are plenty of libraries out there that simplify the job. Being interested in sounds I also created a library called musquito you can check out that as well.
Currently it supports only fading sound effect and I'm working on other things like 3D spatialization.
You can do it like this:
alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'
Check out a working example here: http://jsfiddle.net/LtjzW/1/
cls
$exactadminfile = "C:\temp\files\admin" #First folder to check the file
$userfile = "C:\temp\files\user" #Second folder to check the file
$filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
foreach ($filename in $filenames) {
if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
Write-Warning "$filename absent from both locations"
} else {
Write-Host " $filename File is there in one or both Locations" #if file exists there at both locations or at least in one location
}
}
If you have space in the name of the keys, you can use this in bash:
redis-cli keys "pattern: *" | xargs -L1 -I '$' echo '"$"' | xargs redis-cli del
To remove the association between the local and remote branch run:
git config --unset branch.<local-branch-name>.remote
git config --unset branch.<local-branch-name>.merge
Optionally delete the local branch afterwards if you don't need it:
git branch -d <branch>
This won't delete the remote branch.
You maybe wanted to do the following:
foreach($user->data as $mydata)
{
echo $mydata->name . "\n";
foreach($mydata->values as $values)
{
echo $values->value . "\n";
}
}
With GCC 4.1.2, to print the whole of a std::vector<int> called myVector, do the following:
print *(myVector._M_impl._M_start)@myVector.size()
To print only the first N elements, do:
print *(myVector._M_impl._M_start)@N
Explanation
This is probably heavily dependent on your compiler version, but for GCC 4.1.2, the pointer to the internal array is:
myVector._M_impl._M_start
And the GDB command to print N elements of an array starting at pointer P is:
print P@N
Or, in a short form (for a standard .gdbinit):
p P@N
Short and simple:
def ave(x,y):
return (x + y) / 2.0
map(ave, a[:-1], a[1:])
And here's how it looks:
>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
Due to some stupidity in how Python handles a map
over two lists, you do have to truncate the list, a[:-1]
. It works more as you'd expect if you use itertools.imap
:
>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
In numpy
, index and dimension numbering starts with 0. So axis 0
means the 1st dimension. Also in numpy
a dimension can have length (size) 0. The simplest case is:
In [435]: x = np.zeros((0,), int)
In [436]: x
Out[436]: array([], dtype=int32)
In [437]: x[0]
...
IndexError: index 0 is out of bounds for axis 0 with size 0
I also get it if x = np.zeros((0,5), int)
, a 2d array with 0 rows, and 5 columns.
So someplace in your code you are creating an array with a size 0 first axis.
When asking about errors, it is expected that you tell us where the error occurs.
Also when debugging problems like this, the first thing you should do is print the shape
(and maybe the dtype
) of the suspected variables.
pandas
pandas
, when sending a Series
or DataFrame
to a numpy.array
, as with the following:
try-except
blockif x.size != 0:
You can use Redirect::away($url)
I got a silly error it took me an embarrassingly long to solve.... Check out my pom.xml ...
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.outbottle</groupId>
<artifactId>PersonalDetailsMVC</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>PersonalDetailsMVC</name>
<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.0.1.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<javax.servlet.version>3.0.1</javax.servlet.version>
</properties>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${javax.servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>7.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
Problem was my package name. It MUST be "com.outbottle" (then config/controllers/model/etc) for it to work. As you can see above, I used Maven (for the first time), Spring, 1.8 JDK and nearly had a stroke debugging this issue. All running on Glassfish (Tomcat is ok too for the above pom config). That said, I'm all happy with myself now and know Maven and Spring much better for the next step of my Spring learning curve. Hoping this helps you also!
form_for @user, :url => url_for(:controller => 'mycontroller', :action => 'myaction')
or
form_for @user, :url => whatever_path
I had the same problem. I set url in that way:
git remote set-url origin https://github.com/zkirkland/Random-Python-Tests.git
I also removed from config file this entry: askpass = /bin/echo
.
Then "git push" asked me for username and password and this time it worked.
Adapting this to MySQL -- there is no FROM
clause in UPDATE
, but this works:
UPDATE
item_master im
JOIN
group_master gm ON im.sku=gm.sku
JOIN
Manufacturer_Master mm ON gm.ManufacturerID=mm.ManufacturerID
SET
im.mf_item_number = gm.SKU --etc
WHERE
im.mf_item_number like 'STA%'
AND
gm.manufacturerID=34
Running a simple test, I thought I'd document what works and what doesn't. Often I see people checking to see if the object's class is a member of the other class or is equal to the other class.
For the line below, we have some poorly formed data that can be an NSArray
, an NSDictionary
or (null)
.
NSArray *hits = [[[myXML objectForKey: @"Answer"] objectForKey: @"hits"] objectForKey: @"Hit"];
These are the tests that were performed:
NSLog(@"%@", [hits class]);
if ([hits isMemberOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isMemberOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSDictionary class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSArray class]]) {
NSLog(@"%@", [hits class]);
}
if ([hits isKindOfClass:[NSMutableArray class]]) {
NSLog(@"%@", [hits class]);
}
isKindOfClass
worked rather well while isMemberOfClass
didn't.
The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.
Can I put my method readConfig() into constructor?
Invoking a not overridable method in a constructor is an acceptable approach.
While if the method is only used by the constructor you may wonder if extracting it into a method (even private
) is really required.
If you choose to extract some logic done by the constructor into a method, as for any method you have to choose a access modifier that fits to the method requirement but in this specific case it matters further as protecting the method against the overriding of the method has to be done at risk of making the super class constructor inconsistent.
So it should be private
if it is used only by the constructor(s) (and instance methods) of the class.
Otherwise it should be both package-private
and final
if the method is reused inside the package or in the subclasses.
which would give me benefit of one time calling or is there another mechanism to do that ?
You don't have any benefit or drawback to use this way.
I don't encourage to perform much logic in constructors but in some cases it may make sense to init multiple things in a constructor.
For example the copy constructor may perform a lot of things.
Multiple JDK classes illustrate that.
Take for example the HashMap
copy constructor that constructs a new HashMap
with the same mappings as the specified Map
parameter :
public HashMap(Map<? extends K, ? extends V> m) {
this.loadFactor = DEFAULT_LOAD_FACTOR;
putMapEntries(m, false);
}
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
int s = m.size();
if (s > 0) {
if (table == null) { // pre-size
float ft = ((float)s / loadFactor) + 1.0F;
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
(int)ft : MAXIMUM_CAPACITY);
if (t > threshold)
threshold = tableSizeFor(t);
}
else if (s > threshold)
resize();
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
K key = e.getKey();
V value = e.getValue();
putVal(hash(key), key, value, false, evict);
}
}
}
Extracting the logic of the map populating in putMapEntries()
is a good thing because it allows :
clone()
and putAll()
use it tooSource control is best way to handle this problem, if you don't want to pay then try bitbucket
It's free, allows private repo for upto 5 members team.
async function blobToBase64(blob) {
return new Promise((resolve, _) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
let blob = null; // <= your blob object goes here
blobToBase64(blob)
.then(base64String => console.log(base64String));
See also:
MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:
MERGE INTO mytable d
USING (SELECT 1 id, 'x' name from dual) s
ON (d.id = s.id)
WHEN MATCHED THEN UPDATE SET d.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);
Alternatively you can do this in PL/SQL:
BEGIN
INSERT INTO mytable (id, name) VALUES (1, 'x');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE mytable
SET name = 'x'
WHERE id = 1;
END;
This is a way:
values = [1, 2, 3]
Foo.__table__.insert().execute([{'bar': x} for x in values])
This will insert like this:
INSERT INTO `foo` (`bar`) VALUES (1), (2), (3)
Reference: The SQLAlchemy FAQ includes benchmarks for various commit methods.
[Update]
The original answer was written prior to jQuery 1.3, and the functions that existed at the time where not adequate by themselves to calculate the whole width.
Now, as J-P correctly states, jQuery has the functions outerWidth and outerHeight which include the border
and padding
by default, and also the margin
if the first argument of the function is true
[Original answer]
The width
method no longer requires the dimensions
plugin, because it has been added to the jQuery Core
What you need to do is get the padding, margin and border width-values of that particular div and add them to the result of the width
method
Something like this:
var theDiv = $("#theDiv");
var totalWidth = theDiv.width();
totalWidth += parseInt(theDiv.css("padding-left"), 10) + parseInt(theDiv.css("padding-right"), 10); //Total Padding Width
totalWidth += parseInt(theDiv.css("margin-left"), 10) + parseInt(theDiv.css("margin-right"), 10); //Total Margin Width
totalWidth += parseInt(theDiv.css("borderLeftWidth"), 10) + parseInt(theDiv.css("borderRightWidth"), 10); //Total Border Width
Split into multiple lines to make it more readable
That way you will always get the correct computed value, even if you change the padding or margin values from the css
The first solution is to use the java.util.Random
class:
import java.util.Random;
Random rand = new Random();
// Obtain a number between [0 - 49].
int n = rand.nextInt(50);
// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;
Another solution is using Math.random()
:
double random = Math.random() * 49 + 1;
or
int random = (int)(Math.random() * 50 + 1);
What are the problems of static and stack?
The problem with "static" allocation is that the allocation is made at compile-time: you can't use it to allocate some variable number of data, the number of which isn't known until run-time.
The problem with allocating on the "stack" is that the allocation is destroyed as soon as the subroutine which does the allocation returns.
I could write an entire application without allocate variables in the heap?
Perhaps but not a non-trivial, normal, big application (but so-called "embedded" programs might be written without the heap, using a subset of C++).
What garbage collector does ?
It keeps watching your data ("mark and sweep") to detect when your application is no longer referencing it. This is convenient for the application, because the application doesn't need to deallocate the data ... but the garbage collector might be computationally expensive.
Garbage collectors aren't a usual feature of C++ programming.
What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?
Learn the C++ mechanisms for deterministic memory deallocation:
This is an old topic, but in case anyone else is still looking...
I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)
However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.
So I wrote the small sub below to force the error - hope it's useful.
Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.
Function adoIsConnected(adoCn As ADODB.Connection) As Boolean
'----------------------------------------------------------------
'#PURPOSE: Checks whether the supplied db connection is alive and
' hasn't had it's TCP connection forcibly closed by remote
' host, for example, as happens during an undock event
'#RETURNS: True if the supplied db is connected and error-free,
' False otherwise
'#AUTHOR: Belladonna
'----------------------------------------------------------------
Dim i As Long
Dim cmd As New ADODB.Command
'Set up SQL command to return 1
cmd.CommandText = "SELECT 1"
cmd.ActiveConnection = adoCn
'Run a simple query, to test the connection
On Error Resume Next
i = cmd.Execute.Fields(0)
On Error GoTo 0
'Tidy up
Set cmd = Nothing
'If i is 1, connection is open
If i = 1 Then
adoIsConnected = True
Else
adoIsConnected = False
End If
End Function
I think your asking to select only <span class = "my_class">hello</span>
this element, You have do like this, If I am understand your question correctly this is the answer,
$("#my_id [class='my_class']").addClass('test');
<a href="<?php echo site_url('controller/function'); ?>Compose</a>
<a href="<?php echo site_url('controller/function'); ?>Inbox</a>
<a href="<?php echo site_url('controller/function'); ?>Outbox</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
<a href="<?php echo site_url('controller/function'); ?>logout</a>
*This solution is for reactive-form
You may have heard the confirm password is known as cross-field validation. While the field level validator that we usually write can only be applied to a single field. For cross-filed validation, you probably have to write some parent level validator. For specifically the case of confirming password, I would rather do:
this.form.valueChanges.subscribe(field => {
if (field.password !== field.confirm) {
this.confirm.setErrors({ mismatch: true });
} else {
this.confirm.setErrors(null);
}
});
And here is the template:
<mat-form-field>
<input matInput type="password" placeholder="Password" formControlName="password">
<mat-error *ngIf="password.hasError('required')">Required</mat-error>
</mat-form-field>
<mat-form-field>
<input matInput type="password" placeholder="Confirm New Password" formControlName="confirm">`enter code here`
<mat-error *ngIf="confirm.hasError('mismatch')">Password does not match the confirm password</mat-error>
</mat-form-field>
I had the same issue today on windows 32 bit,with node 0.10.25, and grunt 0.4.5.
I followed dongho's answer, with just few extra steps. here are the steps I used to solve the error:
1) create your package.json
$ npm init
2) install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json
$ npm install grunt --save-dev
3) then create gruntfile.js
, with a sample code like this:
module.exports = function(grunt) {
grunt.initConfig({
jshint: {
files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
options: {
globals: {
jQuery: true
}
}
},
watch: {
files: ['<%= jshint.files %>'],
tasks: ['jshint']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint']);
};
here, src/**/*.js
and test/**/*.js
should be the paths to actual JS files you are using in your project
4) run npm install grunt-contrib-jshint --save-dev
5) run npm install grunt-contrib-watch --save-dev
6) run $ grunt
Note: when you require common package like concat, uglify etc, you need to add those modules via npm install
, just the way we installed jshint and watch in step 4 & 5
I have written one easy step, but because of this performance will be degraded
Here is my code snippet:-
for (int tempReg = 0; tempReg < reg.Matches(lines).Count; tempReg++)
{
foreach (Match match in reg.Matches(lines))
{
var aStringBuilder = new StringBuilder(lines);
aStringBuilder.Insert(startIndex, match.ToString().Replace(",", " ");
lines[k] = aStringBuilder.ToString();
tempReg = 0;
break;
}
}
I prefer this variant on the enumerator method with a pipeline, because you don't have to refer to the hash table in the foreach (tested in PowerShell 5):
$hash = @{
'a' = 3
'b' = 2
'c' = 1
}
$hash.getEnumerator() | foreach {
Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}
Output:
Key = c and Value = 1
Key = b and Value = 2
Key = a and Value = 3
Now, this has not been deliberately sorted on value, the enumerator simply returns the objects in reverse order.
But since this is a pipeline, I now can sort the objects received from the enumerator on value:
$hash.getEnumerator() | sort-object -Property value -Desc | foreach {
Write-Host ("Key = " + $_.key + " and Value = " + $_.value);
}
Output:
Key = a and Value = 3
Key = b and Value = 2
Key = c and Value = 1
TL;DR
Use one of these for universal conversion needs
//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8
bigDecimal.toBigInteger().intValueExact()
Reasoning
The answer depends on what the requirements are and how you answer these question.
BigDecimal
potentially have a non-zero fractional part?BigDecimal
potentially not fit into the Integer
range?If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact()
as others have suggested and let it blow up when something unexpected happens.
If you are not absolutely 100% confident about question number 2, then intValue()
is always the wrong answer.
Making it better
Let's use the following assumptions based on the other answers.
intValueExact()
and auto-boxing doBigDecimal
is larger than the Integer
range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.Given those params, intValueExact()
throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue()
doesn't throw an exception when it should if our BigDecimal
is too large.
To get the best of both worlds, round off the BigDecimal
first, then convert. This also has the benefit of giving you more control over the rounding process.
Spock Groovy Test
void 'test BigDecimal rounding'() {
given:
BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
String decimalAsBigIntString = decimal.toBigInteger().toString()
String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()
expect: 'decimals that can be truncated within Integer range to do so without exception'
//GOOD: Truncates without exception
'' + decimal.intValue() == decimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
// decimal.intValueExact() == decimalAsBigIntString
//GOOD: Truncates without exception
'' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
//'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
//BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
//'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString
and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
//BAD: hugeDecimal.intValue() is 0
//'' + reallyHuge.intValue() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
//GOOD: Throws conversionOverflow ArithmeticException because to large
//'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString
and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
//decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}
managed to fix this by copying the below folder from another Visual Studio setup (non-express)
from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc
to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc
Linux shared library minimal runnable ABI example
In the context of shared libraries, the most important implication of "having a stable ABI" is that you don't need to recompile your programs after the library changes.
So for example:
if you are selling a shared library, you save your users the annoyance of recompiling everything that depends on your library for every new release
if you are selling closed source program that depends on a shared library present in the user's distribution, you could release and test less prebuilts if you are certain that ABI is stable across certain versions of the target OS.
This is specially important in the case of the C standard library, which many many programs in your system link to.
Now I want to provide a minimal concrete runnable example of this.
main.c
#include <assert.h>
#include <stdlib.h>
#include "mylib.h"
int main(void) {
mylib_mystruct *myobject = mylib_init(1);
assert(myobject->old_field == 1);
free(myobject);
return EXIT_SUCCESS;
}
mylib.c
#include <stdlib.h>
#include "mylib.h"
mylib_mystruct* mylib_init(int old_field) {
mylib_mystruct *myobject;
myobject = malloc(sizeof(mylib_mystruct));
myobject->old_field = old_field;
return myobject;
}
mylib.h
#ifndef MYLIB_H
#define MYLIB_H
typedef struct {
int old_field;
} mylib_mystruct;
mylib_mystruct* mylib_init(int old_field);
#endif
Compiles and runs fine with:
cc='gcc -pedantic-errors -std=c89 -Wall -Wextra'
$cc -fPIC -c -o mylib.o mylib.c
$cc -L . -shared -o libmylib.so mylib.o
$cc -L . -o main.out main.c -lmylib
LD_LIBRARY_PATH=. ./main.out
Now, suppose that for v2 of the library, we want to add a new field to mylib_mystruct
called new_field
.
If we added the field before old_field
as in:
typedef struct {
int new_field;
int old_field;
} mylib_mystruct;
and rebuilt the library but not main.out
, then the assert fails!
This is because the line:
myobject->old_field == 1
had generated assembly that is trying to access the very first int
of the struct, which is now new_field
instead of the expected old_field
.
Therefore this change broke the ABI.
If, however, we add new_field
after old_field
:
typedef struct {
int old_field;
int new_field;
} mylib_mystruct;
then the old generated assembly still accesses the first int
of the struct, and the program still works, because we kept the ABI stable.
Here is a fully automated version of this example on GitHub.
Another way to keep this ABI stable would have been to treat mylib_mystruct
as an opaque struct, and only access its fields through method helpers. This makes it easier to keep the ABI stable, but would incur a performance overhead as we'd do more function calls.
API vs ABI
In the previous example, it is interesting to note that adding the new_field
before old_field
, only broke the ABI, but not the API.
What this means, is that if we had recompiled our main.c
program against the library, it would have worked regardless.
We would also have broken the API however if we had changed for example the function signature:
mylib_mystruct* mylib_init(int old_field, int new_field);
since in that case, main.c
would stop compiling altogether.
Semantic API vs Programming API
We can also classify API changes in a third type: semantic changes.
The semantic API, is usually a natural language description of what the API is supposed to do, usually included in the API documentation.
It is therefore possible to break the semantic API without breaking the program build itself.
For example, if we had modified
myobject->old_field = old_field;
to:
myobject->old_field = old_field + 1;
then this would have broken neither programming API, nor ABI, but main.c
the semantic API would break.
There are two ways to programmatically check the contract API:
formal verification. Harder to do, but produces mathematical proof of correctness, essentially unifying documentation and tests into a "human" / machine verifiable manner! As long as there isn't a bug in your formal description of course ;-)
This concept is closely related to the formalization of Mathematics itself: https://math.stackexchange.com/questions/53969/what-does-formal-mean/3297537#3297537
List of everything that breaks C / C++ shared library ABIs
TODO: find / create the ultimate list:
Java minimal runnable example
What is binary compatibility in Java?
Tested in Ubuntu 18.10, GCC 8.2.0.
"Server unable to read htaccess file" means just that. Make sure that the permissions on your .htaccess
file are world-readable.
It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:
google.loader.ClientLocation.address.city
You need to load jquery first before bootstrap.
require.config({
paths: {
jquery: 'libs/jquery/jquery',
underscore: 'libs/underscore/underscore',
backbone: 'libs/backbone/backbone',
bootstrap: 'libs/bootstrap',
jquerytablesorter: 'libs/tablesorter/jquery.tablesorter',
tablesorter: 'libs/tablesorter/tables',
ajaxupload: 'libs/ajax-upload',
templates: '../templates'
},
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
exports: 'Backbone'
},
'jquery': {
exports: '$'
},
'bootstrap': {
deps: ['jquery'],
exports: '$'
},
'jquerytablesorter': {
deps: ['jquery'],
exports: '$'
},
'tablesorter': {
deps: ['jquery'],
exports: '$'
},
'ajaxupload': {
deps: ['jquery'],
exports: '$'
},
'underscore': {
exports: '_'
},
}
});
require(['app', ], function(App) {
App.initialize();
});
Works like charm! quick and easy fix.
This was happening for me in my Apache/2.4.18 (Ubuntu) setup. In my case, the error I was seeing was:
... AH01144: No protocol handler was valid for the URL /~socket.io/. If you are using a DSO version of mod_proxy, make sure the proxy submodules are included in the configuration using LoadModule.
The configuration related to this was:
ProxyPass /~socket.io/ ws://127.0.0.1:8090/~socket.io/
ProxyPassReverse /~socket.io/ ws://127.0.0.1:8090/~socket.io/
"No protocol handler was valid for the URL /~socket.io/
" meant that Apache could not handle the request being sent to "ws://127.0.0.1:8090/~socket.io/
"
I had proxy_http
loaded, but also needed proxy_wstunnel
. Once that was enabled all was good.
you can use _.range([optional] start, end)
. It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range()
method.
Example:
CODE
var dayOfMonth = _.range(1,32); // It creates a new list from 1 to 31.
//HTML Now, you can use it in For loop
<div *ngFor="let day of dayOfMonth">{{day}}</div>
I ran into this today and got it to work with:
EXECUTE sp_rename N'dbo.table_name.original_field_name', N'new_field_name', 'COLUMN'
To get this syntax, I followed Martin Smith's advice above - open up the table in design view, rename the column and then click table designer | generate change script. This produced the script below which does the renaming in two steps:
/* To prevent any potential data loss issues, you should review this script in
detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
EXECUTE sp_rename N'dbo.table_name.original_field_name', N'Tmp_new_field_name_1', COLUMN'
GO
EXECUTE sp_rename N'dbo.table_name.Tmp_new_field_name_1', N'new_field_name', 'COLUMN'
GO
ALTER TABLE dbo.table_name SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
I've only used jdom. It's pretty easy.
Go here for documentation and to download it: http://www.jdom.org/
If you have a very very large document then it's better not to read it all into memory, but use a SAX parser which calls your methods as it hits certain tags and attributes. You have to then create a state machine to deal with the incoming calls.
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.
REST stands for REpresentational State Transfer and goes a little something like this:
We have a bunch of uniquely addressable 'entities' that we want made available via a web application. Those entities each have some identifier and can be accessed in various formats. REST defines a bunch of stuff about what GET, POST, etc mean for these purposes.
the basic idea with REST is that you can attach a bunch of 'renderers' to different entities so that they can be available in different formats easily using the same HTTP verbs and url formats.
For more clarification on what RESTful means and how it is used google rails. Rails is a RESTful framework so there's loads of good information available in its docs and associated blog posts. Worth a read even if you arent keen to use the framework. For example: http://www.sitepoint.com/restful-rails-part-i/
RESTless means not restful. If you have a web app that does not adhere to RESTful principles then it is not RESTful
If your value under test is a Double (not a primitive) and might be null
(which is obviously not a number too), then you should use the following term:
(value==null || Double.isNaN(value))
Since isNaN()
wants a primitive (rather than boxing any primitive double to a Double), passing a null
value (which can't be unboxed to a Double) will result in an exception instead of the expected false
.
One possible way to do this in just one line by using a map, simple I am checking whether a > b
if it is true
I am assigning c
to a
otherwise b
c := map[bool]int{true: a, false: b}[a > b]
However, this looks amazing but in some cases it might NOT be the perfect solution because of evaluation order. For example, if I am checking whether an object is not nil
get some property out of it, look at the following code snippet which will panic
in case of myObj equals nil
type MyStruct struct {
field1 string
field2 string
}
var myObj *MyStruct
myObj = nil
myField := map[bool]string{true: myObj.field1, false: "empty!"}[myObj != nil}
Because map will be created and built first before evaluating the condition so in case of myObj = nil
this will simply panic.
Not to forget to mention that you can still do the conditions in just one simple line, check the following:
var c int
...
if a > b { c = a } else { c = b}
set myDIR=LOG
IF not exist %myDIR% (mkdir %myDIR%)
"location" directive should be inside a 'server' directive, e.g.
server {
listen 8765;
location / {
resolver 8.8.8.8;
proxy_pass http://$http_host$uri$is_args$args;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
If you're not too concerned with performance, you could always try listening on a port using the ServerSocket class. If it throws an exception odds are it's being used.
public static boolean isAvailable(int portNr) {
boolean portFree;
try (var ignored = new ServerSocket(portNr)) {
portFree = true;
} catch (IOException e) {
portFree = false;
}
return portFree;
}
EDIT: If all you're trying to do is select a free port then new ServerSocket(0)
will find one for you.
Like this ?
<script>
var meta = document.createElement('meta');
meta.setAttribute('http-equiv', 'X-UA-Compatible');
meta.setAttribute('content', 'IE=Edge');
document.getElementsByTagName('head')[0].appendChild(meta);
</script>
Just write this your work get done
sudo rm /etc/nginx/sites-enabled/default
sudo service nginx restart
systemctl status nginx
Happy Learning
You can make the single letter optional by adding a ?
after it as:
([A-Z]{1}?)
The quantifier {1}
is redundant so you can drop it.
In addition to what provided in the other answers, the keyword "zorder" allows one to decide the order in which different objects are plotted vertically. E.g.:
plt.plot(x,y,zorder=1)
plt.scatter(x,y,zorder=2)
plots the scatter symbols on top of the line, while
plt.plot(x,y,zorder=2)
plt.scatter(x,y,zorder=1)
plots the line over the scatter symbols.
See, e.g., the zorder demo
?max
shows you that there is an extra parameter na.rm
that you can set to TRUE
.
Apart from that, if you really want to remove the NA
s, just use something like:
myvec[!is.na(myvec)]
Have you tried using the official JQueryUI implementation (not jQuery only) : ?
create procedure dbo.PrintMax @text nvarchar(max) as begin declare @i int, @newline nchar(2), @print varchar(max); set @newline = nchar(13) + nchar(10); select @i = charindex(@newline, @text); while (@i > 0) begin select @print = substring(@text,0,@i); while (len(@print) > 8000) begin print substring(@print,0,8000); select @print = substring(@print,8000,len(@print)); end print @print; select @text = substring(@text,@i+2,len(@text)); select @i = charindex(@newline, @text); end print @text; end
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
You can do what you want if you use an iterator object to go over the elements in your set. You can remove them on the go an it's ok. However removing them while in a for loop (either "standard", of the for each kind) will get you in trouble:
Set<Integer> set = new TreeSet<Integer>();
set.add(1);
set.add(2);
set.add(3);
//good way:
Iterator<Integer> iterator = set.iterator();
while(iterator.hasNext()) {
Integer setElement = iterator.next();
if(setElement==2) {
iterator.remove();
}
}
//bad way:
for(Integer setElement:set) {
if(setElement==2) {
//might work or might throw exception, Java calls it indefined behaviour:
set.remove(setElement);
}
}
As per @mrgloom's comment, here are more details as to why the "bad" way described above is, well... bad :
Without getting into too much details about how Java implements this, at a high level, we can say that the "bad" way is bad because it is clearly stipulated as such in the Java docs:
https://docs.oracle.com/javase/8/docs/api/java/util/ConcurrentModificationException.html
stipulate, amongst others, that (emphasis mine):
"For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected" (...)
"Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this exception."
To go more into details: an object that can be used in a forEach loop needs to implement the "java.lang.Iterable" interface (javadoc here). This produces an Iterator (via the "Iterator" method found in this interface), which is instantiated on demand, and will contain internally a reference to the Iterable object from which it was created. However, when an Iterable object is used in a forEach loop, the instance of this iterator is hidden to the user (you cannot access it yourself in any way).
This, coupled with the fact that an Iterator is pretty stateful, i.e. in order to do its magic and have coherent responses for its "next" and "hasNext" methods it needs that the backing object is not changed by something else than the iterator itself while it's iterating, makes it so that it will throw an exception as soon as it detects that something changed in the backing object while it is iterating over it.
Java calls this "fail-fast" iteration: i.e. there are some actions, usually those that modify an Iterable instance (while an Iterator is iterating over it). The "fail" part of the "fail-fast" notion refers to the ability of an Iterator to detect when such "fail" actions happen. The "fast" part of the "fail-fast" (and, which in my opinion should be called "best-effort-fast"), will terminate the iteration via ConcurrentModificationException as soon as it can detect that a "fail" action has happen.
Here's how I did it in Swift 4.2:
extension Date {
/// Create a date from specified parameters
///
/// - Parameters:
/// - year: The desired year
/// - month: The desired month
/// - day: The desired day
/// - Returns: A `Date` object
static func from(year: Int, month: Int, day: Int) -> Date? {
let calendar = Calendar(identifier: .gregorian)
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
return calendar.date(from: dateComponents) ?? nil
}
}
Usage:
let marsOpportunityLaunchDate = Date.from(year: 2003, month: 07, day: 07)
I recently had same issue with Spring 4.0.
It was caused by a collision in names from spring-beans-4.0.xsd
and spring-context-4.0.xsd
.
Opening spring-context-4.0.xsd
you can see that spring-beans-4.0.xsd
is imported like follow:
<xsd:import namespace="http://www.springframework.org/schema/beans"
schemaLocation="http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"/>
These name's collisions make Eclipse complain about "...A schema cannot contain two global components with the same name..."
A noteworthy aspect is that I hadn't this problem with Eclipse Kepler SR2 but Eclipse Luna SR1, comparing both preferences about XML Validation, they were the same.
It was solved by removing spring-context-4.0.xsd from xsi:schemaLocation attribute:
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
After this everything worked as expected.
Steps:
Run this code It will open google print service popup.
function openPrint(x) {
if (x > 0) {
openPrint(--x); print(x); openPrint(--x);
}
}
Try it on console where x is integer .
openPrint(1); // Will open Chrome Print Popup Once
openPrint(2); // Will open Chrome Print Popup Twice after 1st close and so on
Thanks
You have installed the library in a non-standard location ($HOME/zlib/
). That means the compiler will not know where your header files are and you need to tell the compiler that.
You can add a path to the list that the compiler uses to search for header files by using the -I
(upper-case i) option.
Also note that the LD_LIBRARY_PATH
is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L
option.
All-together the command line should look like
$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz
If you add this to your meta tags:
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
IE8 will render the page like IE7.
You could use a list comprehension or a generator expression instead:
', '.join([str(x) for x in list]) # list comprehension
', '.join(str(x) for x in list) # generator expression
This is a shot in the dark, but you might try shrinking the image and then enlarging it again. This can be done with Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter)
. Make sure and set the filter parameter to true. It'll run in native code so it might be faster.
The Accept Ranges
header (the bit in writeHead()
) is required for the HTML5 video controls to work.
I think instead of just blindly send the full file, you should first check the Accept Ranges
header in the REQUEST, then read in and send just that bit. fs.createReadStream
support start
, and end
option for that.
So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat
to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream
to send the requested part to the client.
var fs = require("fs"),
http = require("http"),
url = require("url"),
path = require("path");
http.createServer(function (req, res) {
if (req.url != "/movie.mp4") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
} else {
var file = path.resolve(__dirname,"movie.mp4");
fs.stat(file, function(err, stats) {
if (err) {
if (err.code === 'ENOENT') {
// 404 Error if file not found
return res.sendStatus(404);
}
res.end(err);
}
var range = req.headers.range;
if (!range) {
// 416 Wrong range
return res.sendStatus(416);
}
var positions = range.replace(/bytes=/, "").split("-");
var start = parseInt(positions[0], 10);
var total = stats.size;
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
res.writeHead(206, {
"Content-Range": "bytes " + start + "-" + end + "/" + total,
"Accept-Ranges": "bytes",
"Content-Length": chunksize,
"Content-Type": "video/mp4"
});
var stream = fs.createReadStream(file, { start: start, end: end })
.on("open", function() {
stream.pipe(res);
}).on("error", function(err) {
res.end(err);
});
});
}
}).listen(8888);
Great Article... worked like a breeze on Amazon Linux AMI.
Two more useful commands:
To change the default FTP upload folder
Step 1:
edit /etc/vsftpd/vsftpd.conf
Step 2: Create a new entry at the bottom of the page:
local_root=/var/www/html
To apply read, write, delete permission to the files under folder so that you can manage using a FTP device
find /var/www/html -type d -exec chmod 777 {} \;
Simple:
if ( $name eq 'tom' && $password eq '123!'
|| $name eq 'frank' && $password eq '321!'
) {
(use the high-precedence &&
and ||
in expressions, reserving and
and or
for flow control, to avoid common precedence errors)
Better:
my %password = (
'tom' => '123!',
'frank' => '321!',
);
if ( exists $password{$name} && $password eq $password{$name} ) {
Here is another (working) solution : just resize your images to the size you want :)
.pdflink:after {
display: block;
width: 20px;
height: 10px;
content:url('/images/pdf.png');
}
you need pdf.png to be 20px * 10px for this to work. The 20px/10px in the css are here to give the size of the block so that the elements that come after the block are not all messed up with the image
Don't forget to keep a copy of the raw image in its original size
In my case, the problem was caused by some Response.Write commands at Master Page of the website (code behind). They were there only for debugging purposes (that's not the best way, I know)...
SELECT
tab1.std_name, tab1.stdCode, tab1.payment,
SUBSTRING_INDEX(tab1.payment, '|', 1) as rupees,
SUBSTRING(tab1.payment, LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 1)) + 2,LENGTH(SUBSTRING_INDEX(tab1.payment, '|', 2))) as date
FROM (
SELECT DISTINCT
si.std_name, hfc.stdCode,
if(isnull(hfc.payDate), concat(hfc.coutionMoneyIn,'|', year(hfc.startDtae), '-', monthname(hfc.startDtae)), concat(hfc.payMoney, '|', monthname(hfc.payDate), '-', year(hfc.payDate))) AS payment
FROM hostelfeescollection hfc
INNER JOIN hostelfeecollectmode hfm ON hfc.tranId = hfm.tranId
INNER JOIN student_info_1 si ON si.std_code = hfc.stdCode
WHERE hfc.tranId = 'TRAN-AZZZY69454'
) AS tab1
Upgrade to latest Angular 5
Angular Dep packages:
npm install @angular/{animations,common,compiler,core,forms,http,platform-browser,platform-browser-dynamic,router}@latest --save
Other packages that are installed by the angular cli
npm install --save core-js@latest rxjs@latest zone.js@latest
Angular Dev packages:
npm install --save-dev @angular/{compiler-cli,cli,language-service}@latest
Types Dev packages:
npm install --save-dev @types/{jasmine,jasminewd2,node}@latest
Other packages that are installed as dev dev by the angular cli:
npm install --save-dev codelyzer@latest jasmine-core@latest jasmine-spec-reporter@latest karma@latest karma-chrome-launcher@latest karma-cli@latest karma-coverage-istanbul-reporter@latest karma-jasmine@latest karma-jasmine-html-reporter@latest protractor@latest ts-node@latest tslint@latest
Install the latest supported version used by the Angular cli (don't do @latest):
npm install --save-dev [email protected]
Rename file angular-cli.json to .angular-cli.json and update the content:
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "project3-example"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css"
],
"scripts": [],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}
IF you want to clear not only Data, but also ComboBoxes, Checkboxes, try
dataGridView.Columns.Clear();
A mix of native Javascript and jQuery:
var gFireEvent = function (oElem,sEvent)
{
try {
if( typeof sEvent == 'string' && o.isDOM( oElem ))
{
var b = !!(document.createEvent),
evt = b?document.createEvent("HTMLEvents"):document.createEventObject();
if( b )
{ evt.initEvent(sEvent, true, true );
return !oElem.dispatchEvent(evt);
}
return oElem.fireEvent('on'+sEvent,evt);
}
} catch(e) {}
return false;
};
// Next you can do is (bIsMob etc you have to determine yourself):
if( <<< bIsMob || bIsTab || bisTouch >>> )
{
$(document).on('mousedown', function(e)
{
gFireEvent(e.target,'mouseover' );
}).on('mouseup', function(e)
{
gFireEvent(e.target,'mouseout' );
});
}
Another way to do this, which I personally find slightly more convenient and intuitive (without having to remember the --args
parameter), is to compile normally, and use r arg1 arg2 arg3
directly from within gdb
, like so:
$ gcc -g *.c *.h
$ gdb ./a.out
(gdb) r arg1 arg2 arg3
On git bash, simply run $ git log -1
you will see, these lines following your command.
commit d25c95d88a5e8b7e15ba6c925a1631a5357095db .. (info about your head)
d25c95d88a5e8b7e15ba6c925a1631a5357095db, is your SHA for last commit.
If the value is a String, then this might work:
map.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(), e -> Optional.ofNullable(e.getValue()).orElse("")))
let prices = {_x000D_
"apple": 100,_x000D_
"banana": 300,_x000D_
"orange": 250_x000D_
};_x000D_
_x000D_
let sum = 0;_x000D_
for (let price of Object.values(prices)) {_x000D_
sum += price;_x000D_
}_x000D_
_x000D_
alert(sum)
_x000D_
Your svn merge
syntax is wrong.
You want to checkout a working copy of trunk
and then use the svn merge --reintegrate
option:
$ pwd
/home/user/project-trunk
$ svn update # (make sure the working copy is up to date)
At revision <N>.
$ svn merge --reintegrate ^/project/branches/branch_1
--- Merging differences between repository URLs into '.':
U foo.c
U bar.c
U .
$ # build, test, verify, ...
$ svn commit -m "Merge branch_1 back into trunk!"
Sending .
Sending foo.c
Sending bar.c
Transmitting file data ..
Committed revision <N+1>.
See the SVN book chapter on merging for more details.
Note that at the time it was written, this was the right answer (and was accepted), but things have moved on. See the answer of topek, and http://subversion.apache.org/docs/release-notes/1.8.html#auto-reintegrate
Basically
extern linkage
variable is visible in all filesinternal linkage
variable is visible in single file.Explain: const variables internally link by default unless otherwise declared as extern
external linkage
const
global variable is internal linkage
extern const
global variable is external linkage
A pretty good material about linkage in C++
http://www.goldsborough.me/c/c++/linker/2016/03/30/19-34-25-internal_and_external_linkage_in_c++/
To pass the value you must included the hidden value value="hiddenValue"
in the <input>
statement like so:
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:
This code goes on the page where you want to hide the value.
<form action="anotherPage.jsp" method="GET">
<input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">
</form>
Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name)
method of the implicit request
object, as so:
<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>
The output of the above script will be:
The Hidden Value is hiddenValue
ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key
Even if your data falls within your specified limits (e.g. c(0, 335)
), adding a geom_jitter()
statement could push some points outside those limits, producing the same error message.
library(ggplot2)
range(mtcars$hp)
#> [1] 52 335
# No jitter -- no error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
scale_y_continuous(limits=c(0,335))
# Jitter is too large -- this generates the error message
ggplot(mtcars, aes(mpg, hp)) +
geom_point() +
geom_jitter(position = position_jitter(w = 0.2, h = 0.2)) +
scale_y_continuous(limits=c(0,335))
#> Warning: Removed 1 rows containing missing values (geom_point).
Created on 2020-08-24 by the reprex package (v0.3.0)
For development purposes on Windows you can
add to Chrome shortcut flag --ignore-certificate-errors
It expected to ignore certificate errors and allow you to access invalid certificate websites.
Better detailed instructions in https://support.opendns.com/entries/66657664.
You can use from the pd.to_numeric(s)
Rebase and Cherry-pick is the only way you can keep clean commit history. Avoid using merge and avoid creating merge conflict. If you are using gerrit set one project to Merge if necessary and one project to cherry-pick mode and try yourself.
Note to the above solution (from A Paul): The solution doesn't work, cause it doesn't reconstructs back a HashMap< String, Object > - instead it creates a HashMap< String, LinkedHashMap >.
Reason why is because during demarshalling, each Object (JSON marshalled as a LinkedHashMap) is used as-is, it takes 1-on-1 the LinkedHashMap (instead of converting the LinkedHashMap back to its proper Object).
If you had a HashMap< String, MyOwnObject > then proper demarshalling was possible - see following example:
ObjectMapper mapper = new ObjectMapper();
TypeFactory typeFactory = mapper.getTypeFactory();
MapType mapType = typeFactory.constructMapType(HashMap.class, String.class, MyOwnObject.class);
HashMap<String, MyOwnObject> map = mapper.readValue(new StringReader(hashTable.toString()), mapType);
OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx
with this very illustrative diagram:
(source: microsoft.com)
in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.
it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.
You don't have to use Calendar. You can just play with timestamps :
Date d = initDate();//intialize your date to any date
Date dateBefore = new Date(d.getTime() - n * 24 * 3600 * 1000 l ); //Subtract n days
UPDATE DO NOT FORGET TO ADD "l" for long by the end of 1000.
Please consider the below WARNING:
Adding 1000*60*60*24
milliseconds to a java date will once in a great while add zero days or two days to the original date in the circumstances of leap seconds, daylight savings time and the like. If you need to be 100% certain only one day is added, this solution is not the one to use.
ugh, just to iterate over my own case, which gave out approximately the same error - in the Resource declaration (server.xml) make sure to NOT omit driverClassName, and that e.g. for Oracle it is "oracle.jdbc.OracleDriver", and that the right JAR file (e.g. ojdbc14.jar) exists in %CATALINA_HOME%/lib
import nltk
nltk.download()
MyClass selItem = (MyClass) myList.getSelectedItem(); //
You never instantiated your class.
You don't have to test the dataset.
The Fill()
method returns the # of rows added.
There are two ways to do it.
In the method that opens the dialog, pass in the following configuration option disableClose
as the second parameter in MatDialog#open()
and set it to true
:
export class AppComponent {
constructor(private dialog: MatDialog){}
openDialog() {
this.dialog.open(DialogComponent, { disableClose: true });
}
}
Alternatively, do it in the dialog component itself.
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>){
dialogRef.disableClose = true;
}
}
Here's what you're looking for:
And here's a Stackblitz demo
Here's some other use cases and code snippets of how to implement them.
As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:
import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
selector: 'app-third-dialog',
templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {
}
@HostListener('window:keyup.esc') onKeyUp() {
this.dialogRef.close();
}
}
P.S. This is an answer which originated from this answer, where the demo was based on this answer.
To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick
to listen for click events to the backdrop.
Initially, the dialog will have the configuration option disableClose
set as true
. This ensures that the esc
keypress, as well as clicking on the backdrop will not cause the dialog to close.
Afterwards, subscribe to the MatDialogRef#backdropClick
method (which emits when the backdrop gets clicked and returns as a MouseEvent
).
Anyways, enough technical talk. Here's the code:
openDialog() {
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
// ...
}
Alternatively, this can be done in the dialog component:
export class DialogComponent {
constructor(private dialogRef: MatDialogRef<DialogComponent>) {
dialogRef.disableClose = true;
/*
Subscribe to events emitted when the backdrop is clicked
NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
See https://stackoverflow.com/a/41086381 for more info
*/
dialogRef.backdropClick().subscribe(() => {
// Close the dialog
dialogRef.close();
})
}
}
Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with
while (m.find()) {
//do something???
}
Use regex to find a match maybe?
Or create an array
String[] a = new String[]{
"tom",
"bob",
"harry"
};
if(a.contains(stringtomatch)){
//do something
}
This is a very common case in DataTables when it's not able to find the request field define in DataTable configuration.
For Example:
"aoColumns": [{
mData: 'mobile', sWidth: "149px;"
}, {
mData: 'name', sWidth: "121px;"
}, {
mData: 'productName', sWidth: "116px;"
}
}];
Here, If DataTable doesn't receive above mentioned properties. It'll generate this warning:
DataTables warning: Requested unknown parameter '0' from the data source for row '0'
To overcome this you just need to simply set a default value in "aoColumns"
For Example:
"aoColumns": [{
mData: 'mobile',sDefaultContent : '',sWidth: "149px;"
}, {
mData: 'name',sDefaultContent : '', sWidth: "121px;"
}, {
mData: 'productName',sDefaultContent : '', sWidth: "116px;"
}
}];
sDefaultContent will supress the warning.
Note: This property could be changed based on version of dataTables you are using.
You may need to handle javax.persistence.RollbackException
This gives me the most reliable results:
Sub RangeToPicture()
Dim FileName As String: FileName = "C:\file.bmp"
Dim rPrt As Range: Set rPrt = ThisWorkbook.Sheets("Sheet1").Range("A1:C6")
Dim chtObj As ChartObject
rPrt.CopyPicture xlScreen, xlBitmap
Set chtObj = ActiveSheet.ChartObjects.Add(1, 1, rPrt.Width, rPrt.Height)
chtObj.Activate
ActiveChart.Paste
ActiveChart.Export FileName
chtObj.Delete
End Sub
For reference, you can also utilize initWithDictionary
to init the NSMutableDictionary
with a literal one:
NSMutableDictionary buttons = [[NSMutableDictionary alloc] initWithDictionary: @{
@"touch": @0,
@"app": @0,
@"back": @0,
@"volup": @0,
@"voldown": @0
}];
The way C compilers (at least everyone I know of) work the endianness has to be decided at compile time. Even for biendian processors (like ARM och MIPS) you have to choose endianness at compile time. Further more the endianness is defined in all common file formats for executables (such as ELF). Although it is possible to craft a binary blob of biandian code (for some ARM server exploit maybe?) it probably has to be done in assembly.
I want to return odd numbers of an array
If i read that correctly, you want something like this?
List<Integer> getOddNumbers(int[] integers) {
List<Integer> oddNumbers = new ArrayList<Integer>();
for (int i : integers)
if (i % 2 != 0)
oddNumbers.add(i);
return oddNumbers;
}
All of these answers miss one important point -- the n'th line is the n'th line in the file, and not the n'th row in the dataset. I have a situation where I download some antiquated stream gauge data from the USGS. The head of the dataset is commented with '#', the first line after that are the labels, next comes a line that describes the date types, and last the data itself. I never know how many comment lines there are, but I know what the first couple of rows are. Example:
----------------------------- WARNING ----------------------------------
Some of the data that you have obtained from this U.S. Geological Survey database
may not have received Director's approval. ... agency_cd site_no datetime tz_cd 139719_00065 139719_00065_cd
5s 15s 20d 6s 14n 10s USGS 08041780 2018-05-06 00:00 CDT 1.98 A
It would be nice if there was a way to automatically skip the n'th row as well as the n'th line.
As a note, I was able to fix my issue with:
import pandas as pd
ds = pd.read_csv(fname, comment='#', sep='\t', header=0, parse_dates=True)
ds.drop(0, inplace=True)
If you're using Eclipse PDT, this is done by opening up the PHP explorer view, then clicking the upside-down triangle in the top-right of that window. A context window appears, and the filters option is available there. Clicking the Filters menu option opens a new window, where .* files can be unchecked, thus allowing the editing of .htaccess files.
I searched forever for this, so I'm sorta answering my own question here. I'm sure someone else will have the same problem too, so I hope this helps someone else as well.
I created a code to jump to the desired back stack index, it worked fine to my purpose.
ie. I have Fragment1, Fragment2 and Fragment3, I want to jump from Fragment3 to Fragment1
I created a method called onBackPressed in Fragment3 that jumps to Fragment1
Fragment3:
public void onBackPressed() {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.popBackStack(fragmentManager.getBackStackEntryAt(fragmentManager.getBackStackEntryCount()-2).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
In the activity, I need to know if my current fragment is the Fragment3, so I call the onBackPressed of my fragment instead calling super
FragmentActivity:
@Override
public void onBackPressed() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.my_fragment_container);
if (f instanceof Fragment3)
{
((Fragment3)f).onBackPressed();
} else {
super.onBackPressed();
}
}
<script type="text/javascript">
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tableHolder').load('getTable.php', function(){
setTimeout(refreshTable, 5000);
});
}
</script>
Seems to be identical just in case that SQL server will not try to read data which is not required for the query, the optimizer is clever enough
It can have sense when join on complex query (i.e which have joings, groupings etc itself) then, yes, it is better to specify required fields.
But there is one more point. If the query is simple there is no difference but EVERY extra action even which is supposed to improve performance makes optimizer works harder and optimizer can fail to get the best plan in time and will run not optimal query. So extras select can be a such action which can even decrease performance
A quick grep of the libstd++
code base revealed the following two usages of __gx_personality_v0
:
In libsupc++/unwind-cxx.h
// GNU C++ personality routine, Version 0.
extern "C" _Unwind_Reason_Code __gxx_personality_v0
(int, _Unwind_Action, _Unwind_Exception_Class,
struct _Unwind_Exception *, struct _Unwind_Context *);
In libsupc++/eh_personality.cc
#define PERSONALITY_FUNCTION __gxx_personality_v0
extern "C" _Unwind_Reason_Code
PERSONALITY_FUNCTION (int version,
_Unwind_Action actions,
_Unwind_Exception_Class exception_class,
struct _Unwind_Exception *ue_header,
struct _Unwind_Context *context)
{
// ... code to handle exceptions and stuff ...
}
(Note: it's actually a little more complicated than that; there's some conditional compilation that can change some details).
So, as long as your code isn't actually using exception handling, defining the symbol as void*
won't affect anything, but as soon as it does, you're going to crash - __gxx_personality_v0
is a function, not some global object, so trying to call the function is going to jump to address 0 and cause a segfault.
To only find the first locations, use lapply()
with min()
:
my_string <- c("test1", "test1test1", "test1test1test1")
unlist(lapply(gregexpr(pattern = '1', my_string), min))
#> [1] 5 5 5
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(min) %>%
unlist()
#> [1] 5 5 5
To only find the last locations, use lapply()
with max()
:
unlist(lapply(gregexpr(pattern = '1', my_string), max))
#> [1] 5 10 15
# or the readable tidyverse form
my_string %>%
gregexpr(pattern = '1') %>%
lapply(max) %>%
unlist()
#> [1] 5 10 15
You have to make the UL
inside the div
behave like a block. Try adding
.navigation ul {
display: inline-block;
}
You can use JQuery, don't forget to replace Your-Api-Key
string from the code below, follow the link to find your own Api key google developers console
<script>
$.getJSON('https://www.googleapis.com/youtube/v3/videospart=statistics&id=Qq7mpb-hCBY&key=Your-Api-Key', function(data) {
console.log("viewCount: ", data.items[ 0 ].statistics.viewCount);
});
</script>
I got this error when sending a GET request with postman. The request required no parameters. My mistake was I had a blank line in the request body.
The Android implementation of mipmaps in 4.3 is exactly the technique from 1983 explained in the Wikipedia article :)
Each bitmap image of the mipmap set is a downsized duplicate of the main texture, but at a certain reduced level of detail. Although the main texture would still be used when the view is sufficient to render it in full detail, the renderer will switch to a suitable mipmap image (...) when the texture is viewed from a distance or at a small size.
Although this is described as a technique for 3D graphics (as it mentions "viewing from a distance"), it applies just as well to 2D (translated as "drawn is a smaller space", i.e. "downscaled").
For a concrete Android example, imagine you have a View with a certain background drawable (in particular, a BitmapDrawable
). You now use an animation to scale it to 0.15 of its original size. Normally, this would require downscaling the background bitmap for each frame. This "extreme" downscaling, however, may produce visual artifacts.
You can, however, provide a mipmap, which means that the image is already pre-rendered for a few specific scales (let's say 1.0, 0.5, and 0.25). Whenever the animation "crosses" the 0.5 threshold, instead of continuing to downscale the original, 1.0-sized image, it will switch to the 0.5 image and downscale it, which should provide a better result. And so forth as the animation continues.
This is a bit theoretical, since it's actually done by the renderer. According to the source of the Bitmap class, it's just a hint, and the renderer may or may not honor it.
/**
* Set a hint for the renderer responsible for drawing this bitmap
* indicating that it should attempt to use mipmaps when this bitmap
* is drawn scaled down.
*
* If you know that you are going to draw this bitmap at less than
* 50% of its original size, you may be able to obtain a higher
* quality by turning this property on.
*
* Note that if the renderer respects this hint it might have to
* allocate extra memory to hold the mipmap levels for this bitmap.
*
* This property is only a suggestion that can be ignored by the
* renderer. It is not guaranteed to have any effect.
*
* @param hasMipMap indicates whether the renderer should attempt
* to use mipmaps
*
* @see #hasMipMap()
*/
public final void setHasMipMap(boolean hasMipMap) {
nativeSetHasMipMap(mNativeBitmap, hasMipMap);
}
I'm not quite sure why this would be especially suitable for application icons, though. Although Android on tablets, as well as some launchers (e.g. GEL), request an icon "one density higher" to show it bigger, this is supposed to be done using the regular mechanism (i.e. drawable-xxxhdpi
, &c).
I have not used bundle exec
much, but am setting it up now.
I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.
Here's how to set up RVM so you can use bundle exec
by default within a specific project directory:
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.
The HTML in your example will be:
<tr>
<td>TEST</td>
</tr>
Read the PHP documentation that explains it.
Python has a built in method on strings called replace which is used as so:
string.replace(old, new)
So you would use:
string.replace(" ", "_")
I had this problem a while ago and I wrote code to replace characters in a string. I have to start remembering to check the python documentation because they've got built in functions for everything.
You cannot test for string[]
in the general case but you can test for Array
quite easily the same as in JavaScript https://stackoverflow.com/a/767492/390330
If you specifically want for string
array you can do something like:
if (Array.isArray(value)) {
var somethingIsNotString = false;
value.forEach(function(item){
if(typeof item !== 'string'){
somethingIsNotString = true;
}
})
if(!somethingIsNotString && value.length > 0){
console.log('string[]!');
}
}
What you may want to do is first, on your local machine, make a bare clone of the repository
git clone --bare /path/to/repo /path/to/bare/repo.git # don't forget the .git!
Now, archive up the new repo.git directory using tar/gzip or whatever your favorite archiving tool is and then copy the archive to the server.
Unarchive the repo on your server. You'll then need to set up a remote on your local repository:
git remote add repo-name user@host:/path/to/repo.git #this assumes you're using SSH
You will then be able to push to and pull from the remote repo with:
git push repo-name branch-name
git pull repo-name branch-name
Use
res.sendFile()
instead of
res.render()
.
What your trying to do is send a whole file.
This worked for me.
One idiom is:
cd some_dir && ./configure --some-flags && make && make install
I realize that can get long, but for larger scripts you could break it into logical functions.
Can a Python function be an argument of another function?
Yes.
def myfunc(anotherfunc, extraArgs):
anotherfunc(*extraArgs)
To be more specific ... with various arguments ...
>>> def x(a,b):
... print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
... z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>
HTML
<input type="text" [(ngModel)]="obj.mobile" name="mobile" id="mobile" class="form-control" placeholder="Mobile/E-mail" />
TS
onClickClear(){
this.obj.mobile= undefined;
}
No, only use semicolons when they're required.
Here is another FastRGB implementation found here:
public class FastRGB {
public int width;
public int height;
private boolean hasAlphaChannel;
private int pixelLength;
private byte[] pixels;
FastRGB(BufferedImage image) {
pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
width = image.getWidth();
height = image.getHeight();
hasAlphaChannel = image.getAlphaRaster() != null;
pixelLength = 3;
if (hasAlphaChannel)
pixelLength = 4;
}
short[] getRGB(int x, int y) {
int pos = (y * pixelLength * width) + (x * pixelLength);
short rgb[] = new short[4];
if (hasAlphaChannel)
rgb[3] = (short) (pixels[pos++] & 0xFF); // Alpha
rgb[2] = (short) (pixels[pos++] & 0xFF); // Blue
rgb[1] = (short) (pixels[pos++] & 0xFF); // Green
rgb[0] = (short) (pixels[pos++] & 0xFF); // Red
return rgb;
}
}
What is this?
Reading an image pixel by pixel through BufferedImage's getRGB method is quite slow, this class is the solution for this.
The idea is that you construct the object by feeding it a BufferedImage instance, and it reads all the data at once and stores them in an array. Once you want to get pixels, you call getRGB
Dependencies
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
Considerations
Although FastRGB makes reading pixels much faster, it could lead to high memory usage, as it simply stores a copy of the image. So if you have a 4MB BufferedImage in the memory, once you create the FastRGB instance, the memory usage would become 8MB. You can however, recycle the BufferedImage instance after you create the FastRGB.
Be careful to not fall into OutOfMemoryException when using it on devices such as Android phones, where RAM is a bottleneck
This worked for me: Add compile 'com.android.support:appcompat-v7:21.0.3' to the gradle. Change the sdk target to 21. Hope it works for you!
C:\>sqlplus /nolog
SQL> connect / as SYSDBA
SQL> select * from dba_profiles;
SQL> alter profile default limit password_life_time unlimited;
SQL> alter user database_name identified by new_password;
SQL> commit;
SQL> exit;
Use boost::algorithm::ends_with
(see e.g. http://www.boost.org/doc/libs/1_34_0/doc/html/boost/algorithm/ends_with.html ):
#include <boost/algorithm/string/predicate.hpp>
// works with const char*
assert(boost::algorithm::ends_with("mystring", "ing"));
// also works with std::string
std::string haystack("mystring");
std::string needle("ing");
assert(boost::algorithm::ends_with(haystack, needle));
std::string haystack2("ng");
assert(! boost::algorithm::ends_with(haystack2, needle));
onDestroyed()
is wrong name for
onDestroy()
Did you make a mistake only in this question or in your code too?
I also followed Josh Frankel's advice and created a Sublime Macro + added key binding. The difference is that this script ensures that spacing is first set to tabs and set to a tab size of 2. The macro won't work if that's not the starting point.
Here's a gist of the macro: https://gist.github.com/drivelous/aa8dc907de34efa3e462c65a96e05f09
In Mac, to use the macro + key binding:
spaces2to4.sublime-macro
and copy/paste the code from the gist. For me this is located at:
/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/spaces2to4.sublime-macro
Sublime Text
> Preferences
> Key Bindings
{
"keys": ["super+shift+o"],
"command": "run_macro_file",
"args": {
"file":"Packages/User/spaces2to4.sublime-macro"
}
}
Now ? + shift + o
now automatically converts each file from 2 space indentation to 4 (but will keep indenting if you run it further)
All of the aforementioned answers are great... I'm just adding one no one had mentioned yet about persisting data through activities and that is to use the built in android SQLite database to persist relevant data... In fact you can place your databaseHelper in the application state and call it as needed throughout the activates.. Or just make a helper class and make the DB calls when needed... Just adding another layer for you to consider... But all of the other answers would suffice as well.. Really just preference
$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, TRUE);
Try this - worked for me.
You can also define case insensitive during the pattern compile:
pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)
And
has precedence over Or
, so, even if a <=> a1 Or a2
Where a And b
is not the same as
Where a1 Or a2 And b,
because that would be Executed as
Where a1 Or (a2 And b)
and what you want, to make them the same, is the following (using parentheses to override rules of precedence):
Where (a1 Or a2) And b
Here's an example to illustrate:
Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0
Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F
For those who like to consult references (in alphabetic order):
You can install maven from m2eclipse - http://download.eclipse.org/technology/m2e/releases
You can also try this
// create a thread
Thread newWindowThread = new Thread(new ThreadStart(() =>
{
// create and show the window
FaxImageLoad obj = new FaxImageLoad(destination);
obj.Show();
// start the Dispatcher processing
System.Windows.Threading.Dispatcher.Run();
}));
// set the apartment state
newWindowThread.SetApartmentState(ApartmentState.STA);
// make the thread a background thread
newWindowThread.IsBackground = true;
// start the thread
newWindowThread.Start();
Maybe you should use a display inline-block too:
.circle {
display: inline-block;
height: 25px;
width: 25px;
background-color: #bbb;
border-radius: 50%;
z-index: -1;
}
If you have a single Buffer
you can use its toString
method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8
if you don't provide a parameter, but I've explicitly set the encoding in this example.
var req = http.request(reqOptions, function(res) {
...
res.on('data', function(chunk) {
var textChunk = chunk.toString('utf8');
// process utf8 text chunk
});
});
If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8
-character may be contained in the first Buffer
(chunk) and the second byte in the second Buffer
then you should use a StringDecoder
. :
var StringDecoder = require('string_decoder').StringDecoder;
var req = http.request(reqOptions, function(res) {
...
var decoder = new StringDecoder('utf8');
res.on('data', function(chunk) {
var textChunk = decoder.write(chunk);
// process utf8 text chunk
});
});
This way bytes of incomplete characters are buffered by the StringDecoder
until all required bytes were written to the decoder.
You can use:
>>> lst = [None] * 5
>>> lst
[None, None, None, None, None]
Rather than making a bunch of global variables, you might consider creating a class that has a bunch of public static constants. It's still global, but this way it's wrapped in a class so you know where the constant is coming from and that it's supposed to be a constant.
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class GlobalConstants {
public:
static const int myConstant;
static const int myOtherConstant;
};
#endif
Constants.cpp
#include "Constants.h"
const int GlobalConstants::myConstant = 1;
const int GlobalConstants::myOtherConstant = 3;
Then you can use this like so:
#include "Constants.h"
void foo() {
int foo = GlobalConstants::myConstant;
}
Add to the enviroment vars the following varibale and value to identify the place of the tnsnames.ora file:
TNS_ADMIN
C:\oracle\product\10.2.0\client_1\network\admin
To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.
I would recommend using WordPress custom fields to store eligible postcodes for each product. add_post_meta() and update_post_meta are what you're looking for. It's not recommended to alter the default WordPress table structure. All postmetas are inserted in wp_postmeta
table. You can find the corresponding products within wp_posts
table.
Yes, there are many well documented algorithms like:
A good summary ("Sam's String Metrics") can be found here (original link dead, so it links to Internet Archive)
Also check these projects:
One of the biggest causes of this issue is the active .NET Framework version. The .NET framework runtime version affects which security protocols are enabled by default.
There doesn't seem to be any authoritative documentation on how it specifically works in different versions, but it seems the defaults are determined more or less as follows:
(For the older versions, your mileage may vary somewhat based on which .NET runtimes are installed on the system. For example, there could be a situation where you are using a very old framework and TLS 1.0 is not supported, or using 4.6.x and TLS 1.3 is not supported)
Microsoft's documentation strongly advises using 4.7+ and the system defaults:
We recommend that you:
- Target .NET Framework 4.7 or later versions on your apps. Target .NET Framework 4.7.1 or later versions on your WCF apps.
- Do not specify the TLS version. Configure your code to let the OS decide on the TLS version.
- Perform a thorough code audit to verify you're not specifying a TLS or SSL version.
For ASP.NET sites: check the targetFramework
version in your <httpRuntime>
element, as this (when present) determines which runtime is actually used by your site:
<httpRuntime targetFramework="4.5" />
Better:
<httpRuntime targetFramework="4.7" />
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
use the above page to refer more Functions in MySQL
SELECT STR_TO_DATE(StringColumn, '%d-%b-%y')
FROM table
say for example use the below query to get output
SELECT STR_TO_DATE('23-feb-14', '%d-%b-%y') FROM table
For String format use the below link
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
You are asking a question about two different things:
Meta
inner class in Django models:
This is just a class container with some options (metadata) attached to the model. It defines such things as available permissions, associated database table name, whether the model is abstract or not, singular and plural versions of the name etc.
Short explanation is here: Django docs: Models: Meta options
List of available meta options is here: Django docs: Model Meta options
For latest version of Django: Django docs: Model Meta options
Metaclass in Python:
The best description is here: What are metaclasses in Python?
**
In addition to the answers in this thread, here is another detail that was not mentioned elsewhere. This expands on the answer by Brad Solomon
Unpacking with **
is also useful when using python str.format
.
This is somewhat similar to what you can do with python f-strings
f-string but with the added overhead of declaring a dict to hold the variables (f-string does not require a dict).
## init vars
ddvars = dict()
ddcalc = dict()
pass
ddvars['fname'] = 'Huomer'
ddvars['lname'] = 'Huimpson'
ddvars['motto'] = 'I love donuts!'
ddvars['age'] = 33
pass
ddcalc['ydiff'] = 5
ddcalc['ycalc'] = ddvars['age'] + ddcalc['ydiff']
pass
vdemo = []
## ********************
## single unpack supported in py 2.7
vdemo.append('''
Hello {fname} {lname}!
Today you are {age} years old!
We love your motto "{motto}" and we agree with you!
'''.format(**ddvars))
pass
## ********************
## multiple unpack supported in py 3.x
vdemo.append('''
Hello {fname} {lname}!
In {ydiff} years you will be {ycalc} years old!
'''.format(**ddvars,**ddcalc))
pass
## ********************
print(vdemo[-1])
This should do what you're looking for:
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}
Usage:
echo clean('a|"bc!@£de^&$f g');
Will output: abcdef-g
Edit:
Hey, just a quick question, how can I prevent multiple hyphens from being next to each other? and have them replaced with just 1?
function clean($string) {
$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
Another way is to rename the following files:
.git/refs/head/[branch-name]
to .git/refs/head/new-branch-name
..git/refs/remotes/[all-remote-names]/[branch-name]
to .git/refs/remotes/[all-remote-names]/new-branch-name
.Rename head and remotes both on your local PC and on origins(s)/remote server(s).
If your current branch-name contains slashes (/
) Git will create the directories like so:
current branch-name: "awe/some/branch"
.git/refs/head/awe/some/branch
.git/refs/remotes/[all-remote-names]/awe/some/branch
wish branch-name: "new-branch-name"
branch
file from .git/refs/*/awe/some/
..git/refs/head/
.branch
file from all of .git/refs/remotes/*/awe/some/
..git/refs/remotes/*/
.branch
files to new-branch-name
..git/refs/head/new-branch-name
.git/refs/remotes/[all-remote-names]/new-branch-name
awe/some/branch
to new-branch-name
(local and remote!)Information: This way might not be the best, but it still works for people who might have problems with the other ways
I would check to see if the SqlDataReader has rows returned first:
SqlDataReader dr = cmd10.ExecuteReader();
if (dr.HasRows)
{
...
}
my servlet contains this as a code how to keep this in scheduler if a user presses accept
if(bt.equals("accept")) {
ScheduledExecutorService scheduler=Executors.newScheduledThreadPool(1);
String lat=request.getParameter("latlocation");
String lng=request.getParameter("lnglocation");
requestingclass.updatelocation(lat,lng);
}
If you are looking for a full-fledged IDE like Visual Studio, I think Eclipse might be your best bet.
Eclipse is also highly extensible and configurable.
See here: http://www.eclipse.org/downloads/
SVG 1.2 Tiny added text wrapping, but most implementations of SVG that you will find in the browser (with the exception of Opera) have not implemented this feature. It's typically up to you, the developer, to position text manually.
The SVG 1.1 specification provides a good overview of this limitation, and the possible solutions to overcome it:
Each ‘text’ element causes a single string of text to be rendered. SVG performs no automatic line breaking or word wrapping. To achieve the effect of multiple lines of text, use one of the following methods:
- The author or authoring package needs to pre-compute the line breaks and use multiple ‘text’ elements (one for each line of text).
- The author or authoring package needs to pre-compute the line breaks and use a single ‘text’ element with one or more ‘tspan’ child elements with appropriate values for attributes ‘x’, ‘y’, ‘dx’ and ‘dy’ to set new start positions for those characters who start new lines. (This approach allows user text selection across multiple lines of text -- see Text selection and clipboard operations.)
- Express the text to be rendered in another XML namespace such as XHTML [XHTML] embedded inline within a ‘foreignObject’ element. (Note: the exact semantics of this approach are not completely defined at this time.)
http://www.w3.org/TR/SVG11/text.html#Introduction
As a primitive, text wrapping can be simulated by using the dy
attribute and tspan
elements, and as mentioned in the spec, some tools can automate this. For example, in Inkscape, select the shape you want, and the text you want, and use Text -> Flow into Frame. This will allow you to write your text, with wrapping, which will wrap based on the bounds of the shape. Also, make sure you follow these instructions to tell Inkscape to maintain compatibility with SVG 1.1:
http://wiki.inkscape.org/wiki/index.php/FAQ#What_about_flowed_text.3F
Furthermore, there are some JavaScript libraries that can be used to dynamically automate text wrapping: http://www.carto.net/papers/svg/textFlow/
It's interesting to note CSVG's solution to wrapping a shape to a text element (e.g. see their "button" example), although it's important to mention that their implementation is not usable in a browser: http://www.csse.monash.edu.au/~clm/csvg/about.html
I'm mentioning this because I have developed a CSVG-inspired library that allows you to do similar things and does work in web browsers, although I haven't released it yet.
This might be an exception occurring in the finalizer. If you are doing the Pattern of ~Class(){ Dispose(false); } check what are you disposing as an un-managed resource. Just put a try..catch there and you should be fine.
We found the issue as we had this mysterious failure with no logs We did the usual recommended pattern of using a "void Dispose(bool disposing)".
Looking at the answers on this question about the finalizer we found a possible place where the Disposal of the unmanaged resources could throw an exception.
It turns out somewhere we did not dispose the object properly thus the finalizer took over the diposal of unmanaged resources thus behold an exception occurred.
In this case was using the Kafka Rest API to clean up the client from Kafka. Seems that it did threw exception at some point then this issue occurred.
If you are using OS X systems, there is no service
commands. So you won't be able to execure sudo service mongod start
.
Check this answer https://unix.stackexchange.com/a/155746 for more help!
Provided that your int column is nullable, you may write:
UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>
By definition, a UUID is 32 hexadecimal digits, separated in 5 groups by hyphens, just as you have described. You shouldn't miss any with your regular expression.
Why do you need 'input:radio[name=cols]'
. Don't know your html, but assuming that ids are unique, you can simply do this.
$('#'+newcol).prop('checked', true);
$('img').mouseover(function(){
var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
$(this).attr("src", newSrc);
});
$('img').mouseout(function(){
var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
$(this).attr("src", newSrc);
});
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
Here's a simple solution based on a combination of what dipali and Piyush Gupta posted:
public boolean dbHasData(String searchTable, String searchColumn, String searchKey) {
String query = "Select * from " + searchTable + " where " + searchColumn + " = ?";
return getReadableDatabase().rawQuery(query, new String[]{searchKey}).moveToFirst();
}
/
performs an integer division in Python 2:
>>> 1/2
0
If one of the numbers is a float, it works as expected:
>>> 1.0/2
0.5
>>> 16**(1.0/2)
4.0
it is simple just use .qsize() example:
a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue
The above snippet applies for Queue()
class of python. Thanks @rayryeng for the update.
for deque from collections
we can use len()
as stated here by K Z.
Try this query it ll change the records ends with .com
UPDATE tablename SET email = replace(email, '.com', '.org') WHERE email LIKE '%.com';
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class CsvFile {
public static void main(String[]args){
PrintWriter pw = null;
try {
pw = new PrintWriter(new File("NewData.csv"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
StringBuilder builder = new StringBuilder();
String columnNamesList = "Id,Name";
// No need give the headers Like: id, Name on builder.append
builder.append(columnNamesList +"\n");
builder.append("1"+",");
builder.append("Chola");
builder.append('\n');
pw.write(builder.toString());
pw.close();
System.out.println("done!");
}
}
To add multiple Lines in a configuration file you can use " "
instead of ' '
and escape sequence \n
for the new line in lineinfile
ansible module:
- name: Configure core-site.xml
lineinfile:
path: /etc/hadoop/core-site.xml
insertafter: '^<configuration>'
line: "Line 1 \n Line 2 \n Line 3"
How about simply (Please note, come up with a better name for the class name this is simply an example):
.centerText{
text-align: center;
}
<div>
<table style="width:100%">
<tbody>
<tr>
<td class="centerText">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td class="centerText">Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
Example here
You can place the css
in a separate file, which is recommended.
In my example, I created a file called styles.css
and placed my css
rules in it.
Then include it in the html document in the <head>
section as follows:
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
The alternative, not creating a seperate css file, not recommended at all...
Create <style>
block in your <head>
in the html document. Then just place your rules there.
<head>
<style type="text/css">
.centerText{
text-align: center;
}
</style>
</head>