Try change update="insTable:display"
to update="display"
. I believe you cannot prefix the id with the form ID like that.
I noticed that there is another CSS selector that does the same thing . The syntax is as follows :
[id|="name_id"]
This will select all elements ID which begins with the word enclosed in double quotes.
The following cites the C11 standard (final draft).
6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.
bool
(mapped by stdbool.h
to the internal name _Bool
for C) itself is an unsigned integer type:
... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.
According to 6.2.5p2:
An object declared as type _Bool is large enough to store the values 0 and 1.
AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool
for C++ and _Bool
for C.
Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool
behaves as in C++.
I have reformatted your code.
The error was situated in this line :
printf("%d", (**c));
To fix it, change to :
printf("%d", (*c));
The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.
In addition, the () was optional.
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int *c = NULL;
a = &b;
c = &a;
printf("%d", *c);
return 0;
}
EDIT :
The line :
c = &a;
must be replaced by :
c = a;
It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :
10
EDIT 2:
If you want to use a double * :
#include <stdio.h>
int main(void)
{
int b = 10;
int *a = NULL;
int **c = NULL;
a = &b;
c = &a;
printf("%d", **c);
return 0;
}
Output:
10
Here's an approach that could resolve your problem, and if not would help with troubleshooting.
Create a second Apache virtual server identical to the current one
Send all "normal" user traffic to the original virtual server
Send special or long-running traffic to the new virtual server
Special or long-running traffic could be report-generation, maintenance ops or anything else you don't expect to complete in <<1 second. This can happen serving APIs, not just web pages.
If your resource utilization is low but you still exceed MaxClients, the most likely answer is you have new connections arriving faster than they can be serviced. Putting any slow operations on a second virtual server will help prove if this is the case. Use the Apache access logs to quantify the effect.
In PowerShell v3, have a look at the Invoke-WebRequest and Invoke-RestMethod e.g.:
$msg = Read-Host -Prompt "Enter message"
$encmsg = [System.Web.HttpUtility]::UrlEncode($msg)
Invoke-WebRequest -Uri "http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$encmsg&encoding=windows-1255"
Here is a solution which sorts the properties alphabetically and prints them all together with their values:
public void logProperties() throws IllegalArgumentException, IllegalAccessException {
Class<?> aClass = this.getClass();
Field[] declaredFields = aClass.getDeclaredFields();
Map<String, String> logEntries = new HashMap<>();
for (Field field : declaredFields) {
field.setAccessible(true);
Object[] arguments = new Object[]{
field.getName(),
field.getType().getSimpleName(),
String.valueOf(field.get(this))
};
String template = "- Property: {0} (Type: {1}, Value: {2})";
String logMessage = System.getProperty("line.separator")
+ MessageFormat.format(template, arguments);
logEntries.put(field.getName(), logMessage);
}
SortedSet<String> sortedLog = new TreeSet<>(logEntries.keySet());
StringBuilder sb = new StringBuilder("Class properties:");
Iterator<String> it = sortedLog.iterator();
while (it.hasNext()) {
String key = it.next();
sb.append(logEntries.get(key));
}
System.out.println(sb.toString());
}
You could do something like this:
htmlComponent.ts
htmlVariable: string = "<b>Some html.</b>";
//this is html in TypeScript code that you need to display
htmlComponent.html
<div [innerHtml]="htmlVariable"></div>
//this is how you display html code from TypeScript in your html
First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:
raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it
freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level
Then you need to create a data frame out of it, melt it and plot it:
Names=c("Food","Music","People") # create list of names
data=data.frame(cbind(freq),Names) # combine them into a data frame
data=data[,c(5,3,1,2,4)] # sort columns
# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')
# plot everything
ggplot(data.m, aes(Names, value)) +
geom_bar(aes(fill = variable), position = "dodge", stat="identity")
Is this what you're after?
To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:
> head(df)
ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1 1 A 1980 450 338 154 36 13 9
2 2 A 2000 288 407 212 54 16 23
3 3 A 2020 196 434 246 68 19 36
4 4 B 1980 111 326 441 90 21 11
5 5 B 2000 63 298 443 133 42 21
6 6 B 2020 36 257 462 162 55 30
Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape
and plotted.
For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw))
to get this:
> data
Names Very.Bad Bad Good Very.Good
1 Food 7 6 5 2
2 Music 5 5 7 3
3 People 6 3 7 4
Just imagine you have Very.Bad
, Bad
, Good
and so on instead of X1PCE
, X2PCE
, X3PCE
. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw))
.
Sure, you can put your constants into a separate module. For example:
const.py:
A = 12
B = 'abc'
C = 1.2
main.py:
import const
print const.A, const.B, const.C
Note that as declared above, A
, B
and C
are variables, i.e. can be changed at run time.
You can set the hours, minutes, seconds and microseconds to whatever you like
datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()
s of the times
Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace()
once vs hundreds of calls to date()
For hibernate5 I solved this issue by puting next lines in my application.properties file:
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
The Philippe solution but cleaner:
My subtraction data is: '2018-09-22T11:05:00.000Z'
import datetime
import pandas as pd
df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)
Easy, as long as your filenames don't include newlines:
find . -maxdepth 1
If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):
find . -maxdepth 1 -print0
Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort
's -z
. Your own script similarly would need to account for this.
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
First things first, you need to check to make sure that localStorage is enabled. I would recommend doing it like this:
var localStorageEnabled = false;
try { localStorageEnabled = !!localStorage; } catch(e) {};
Yes, you can (in some cases) just check to see if the localStorage is a member of the window object. However, there are iframe sandboxing options (among other things) that will throw an exception if you even attempt to access the index 'localStorage'. Thus, for best-practices reasons, this is the best way to check to see if the localStorage is enabled. Then, you can just clear the localStorage like so.
if (localStorageEnabled) localStorage.clear();
For example, you could clear the localStorage after an error occurs in webkit browsers like so.
// clears the local storage upon error
if (localStorageEnabled)
window.onerror = localStorage.clear.bind(localStorage);
In the above example, you need the .bind(window)
because without it, the localStorage.clear
function will run in the context of the window
object, instead of the localStorage
object making it silently fail. To demonstrate this, look at the below example:
window.onerror = localStorage.clear;
is the same as:
window.onerror = function(){
localStorage.clear.call(window);
}
If your code can sensibly be written as a case statement, this is pretty decent:
case mybool
when TrueClass, FalseClass
puts "It's a bool!"
else
puts "It's something else!"
end
You can just use the method below:
document.write()
It is very simple, in the doc below I explain
document.write("<div class='div'>Some content inside the div (It is styled!)</div>")
_x000D_
.div {
background-color: red;
padding: 5px;
color: #fff;
font-family: Arial;
cursor: pointer;
}
.div:hover {
background-color: blue;
padding: 10px;
}
.div:hover:before {
content: 'Hover! ';
}
.div:active {
background-color: green;
padding: 15px;
}
.div:active:after {
content: ' Active! or clicked...';
}
_x000D_
<p>Below or above well show the div</p>
<p>Try pointing hover it and clicking on it. Those are tha styles aplayed. The text and background color changes.</p>
_x000D_
list( myBigList[i] for i in [87, 342, 217, 998, 500] )
I compared the answers with python 2.5.2:
19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]
20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))
22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)
24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )
Note that in Python 3, the 1st was changed to be the same as the 4th.
Another option would be to start out with a numpy.array
which allows indexing via a list or a numpy.array
:
>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])
The tuple
doesn't work the same way as those are slices.
The problem is in the import
line. You are importing a module, not a class. Assuming your file is named other_file.py
(unlike java, again, there is no such rule as "one class, one file"):
from other_file import findTheRange
if your file is named findTheRange too, following java's convenions, then you should write
from findTheRange import findTheRange
you can also import it just like you did with random
:
import findTheRange
operator = findTheRange.findTheRange()
Some other comments:
a) @Daniel Roseman is right. You do not need classes here at all. Python encourages procedural programming (when it fits, of course)
b) You can build the list directly:
randomList = [random.randint(0, 100) for i in range(5)]
c) You can call methods in the same way you do in java:
largestInList = operator.findLargest(randomList)
smallestInList = operator.findSmallest(randomList)
d) You can use built in function, and the huge python library:
largestInList = max(randomList)
smallestInList = min(randomList)
e) If you still want to use a class, and you don't need self
, you can use @staticmethod
:
class findTheRange():
@staticmethod
def findLargest(_list):
#stuff...
Please take a look at jpa-metamodels-with-maven-example.
org.hibernate.org:hibernate-jpamodelgen
.org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor
. <dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${version.hibernate-jpamodelgen}</version>
<scope>provided</scope>
</dependency>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<compilerArguments>-AaddGeneratedAnnotation=false</compilerArguments> <!-- suppress java.annotation -->
<processors>
<processor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.hibernate.orm</groupId>
<artifactId>hibernate-jpamodelgen</artifactId>
<version>${version.hibernate-jpamodelgen}</version>
</dependency>
</dependencies>
</plugin>
org.apache.openjpa:openjpa
.org.apache.openjpa.persistence.meta.AnnotationProcessor6
.<openjpa.metamodel>true<openjpa.metamodel>
. <dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<compilerArgs>
<arg>-Aopenjpa.metamodel=true</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.apache.openjpa.persistence.meta.AnnotationProcessor6</processor>
</processors>
<optionMap>
<openjpa.metamodel>true</openjpa.metamodel>
</optionMap>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa</artifactId>
<version>${version.openjpa}</version>
</dependency>
</dependencies>
</plugin>
org.eclipse.persistence:org.eclipse.persistence.jpa.modelgen.processor
.org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor
.persistence.xml
. <dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<scope>provided</scope>
</dependency>
<plugins>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.eclipse.persistence.internal.jpa.modelgen.CanonicalModelProcessor</processor>
</processors>
<compilerArguments>-Aeclipselink.persistencexml=src/main/resources-${environment.id}/META-INF/persistence.xml</compilerArguments>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>${version.eclipselink}</version>
</dependency>
</dependencies>
</plugin>
org.datanucleus:datanucleus-jpa-query
.org.datanucleus.jpa.query.JPACriteriaProcessor
. <dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jpa-query</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<executions>
<execution>
<id>process</id>
<goals>
<goal>process</goal>
</goals>
<phase>generate-sources</phase>
<configuration>
<processors>
<processor>org.datanucleus.jpa.query.JPACriteriaProcessor</processor>
</processors>
</configuration>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.datanucleus</groupId>
<artifactId>datanucleus-jpa-query</artifactId>
<version>${version.datanucleus}</version>
</dependency>
</dependencies>
</plugin>
Here's straightforward way without resorting to custom comparators or stuff like that:
Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;
for(YourRecord record : records) {
gasNames.add(record.getGasName());
}
// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);
Note: Using TreeSet
instead of HashSet
would give directly sorted arraylist and above Collections.sort
could be skipped, but TreeSet
is otherwise less efficent, so it's often better, and rarely worse, to use HashSet
even when sorting is needed.
Bytecode representation
Java's null
has direct JVM support: three instructions are used to implement it:
aconst_null
: e.g. to set a variable to null
as in Object o = null;
ifnull
and ifnonnull
: e.g. to compare an object to null
as in if (o == null)
Chapter 6 "The Java Virtual Machine Instruction Set " then mentions the effects of null
on other instructions: it throws a NullPointerException
for many of them.
2.4. "Reference Types and Values" also mentions null
in generic terms:
A reference value may also be the special null reference, a reference to no object, which will be denoted here by null. The null reference initially has no run-time type, but may be cast to any type. The default value of a reference type is null.
You can use 'onclick' attribute like this :
<a ... href="javascript: onclick();" ...>...</a>
I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.
Also, my templating engine is smarty, but I'm sure you get the idea.
The meat...
Updating the indicators:
<ol class="carousel-indicators">
{assign var='walker' value=0}
{foreach from=$item["imagearray"] key="key" item="value"}
<li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
<img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
</li>
{assign var='walker' value=1 + $walker}
{/foreach}
</ol>
Changing the CSS related to the indicators:
.carousel-indicators {
bottom:-50px;
height: 36px;
overflow-x: hidden;
white-space: nowrap;
}
.carousel-indicators li {
text-indent: 0;
width: 34px !important;
height: 34px !important;
border-radius: 0;
}
.carousel-indicators li img {
width: 32px;
height: 32px;
opacity: 0.5;
}
.carousel-indicators li:hover img, .carousel-indicators li.active img {
opacity: 1;
}
.carousel-indicators .active {
border-color: #337ab7;
}
When the carousel has slid, update the list of thumbnails:
$('#myCarousel').on('slid.bs.carousel', function() {
var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width();
var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
var toScroll = newIndicatorPosition + indicatorPosition;
var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
if (adjustedScroll < 0)
adjustedScroll = 0;
if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
adjustedScroll = widthEstimate - $(".carousel-indicators").width();
$('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);
indicatorPosition = adjustedScroll;
});
And, when your page loads, set the initial scroll position of the thumbnails:
var indicatorPosition = 0;
Unlike languages that employ 'true' lexical scoping, Python opts to have specific 'namespaces' for variables, whether it be global
, nonlocal
, or local. It could be argued that making developers consciously code with such namespaces in mind is more explicit, thus more understandable. I would argue that such complexities make the language more unwieldy, but I guess it's all down to personal preference.
Here are some examples regarding global
:-
>>> global_var = 5
>>> def fn():
... print(global_var)
...
>>> fn()
5
>>> def fn_2():
... global_var += 2
... print(global_var)
...
>>> fn_2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in fn_2
UnboundLocalError: local variable 'global_var' referenced before assignment
>>> def fn_3():
... global global_var
... global_var += 2
... print(global_var)
...
>>> fn_3()
7
The same patterns can be applied to nonlocal
variables too, but this keyword is only available to the latter Python versions.
In case you're wondering, nonlocal
is used where a variable isn't global, but isn't within the function definition it's being used. For example, a def
within a def
, which is a common occurrence partially due to a lack of multi-statement lambdas. There's a hack to bypass the lack of this feature in the earlier Pythons though, I vaguely remember it involving the use of a single-element list...
Note that writing to variables is where these keywords are needed. Just reading from them isn't ambiguous, thus not needed. Unless you have inner def
s using the same variable names as the outer ones, which just should just be avoided to be honest.
If you really need the indices you can just do what you said again for the inner list:
l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
for index2 in xrange(len(l[index1])):
print index1, index2, l[index1][index2]
But it is more pythonic to iterate through the list itself:
for inner_l in l:
for item in inner_l:
print item
If you really need the indices you can also use enumerate
:
for index1, inner_l in enumerate(l):
for index2, item in enumerate(inner_l):
print index1, index2, item, l[index1][index2]
Try calling read_csv
with encoding='latin1'
, encoding='iso-8859-1'
or encoding='cp1252'
(these are some of the various encodings found on Windows).
You can call UserPrincipal.FindByIdentity
inside System.DirectoryServices.AccountManagement
:
using System.DirectoryServices.AccountManagement;
using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}
I wanted a function to create a comma-delimited list of question marks for JDBC purposes, and found this post. So, I decided to take two variants and see which one performed better. After 1 million iterations, the garden-variety StringBuilder took 2 seconds (fun1), and the cryptic supposedly more optimal version (fun2) took 30 seconds. What's the point of being cryptic again?
private static String fun1(int size) {
StringBuilder sb = new StringBuilder(size * 2);
for (int i = 0; i < size; i++) {
sb.append(",?");
}
return sb.substring(1);
}
private static String fun2(int size) {
return new String(new char[size]).replaceAll("\0", ",?").substring(1);
}
I had the issue when I put jcenter()
before google()
in project level build.gradle. When I changed the order and put google()
before jcenter()
in build.gradle the problem disappeared
Here is my final build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
This code is better rewritten as:
for( Map.Entry me : entrys.entrySet() )
{
this.add( (Component) me.getValue() );
}
and it is equivalent to:
for( Component comp : entrys.getValues() )
{
this.add( comp );
}
When you enumerate the entries of a map, the iteration yields a series of objects which implement the Map.Entry
interface. Each one of these objects contains a key and a value.
It is supposed to be slightly more efficient to enumerate the entries of a map than to enumerate its values, but this factoid presumes that your Map
is a HashMap
, and also presumes knowledge of the inner workings (implementation details) of the HashMap
class. What can be said with a bit more certainty is that no matter how your map is implemented, (whether it is a HashMap
or something else,) if you need both the key and the value of the map, then enumerating the entries is going to be more efficient than enumerating the keys and then for each key invoking the map again in order to look up the corresponding value.
With itertools
you will obtain another generator object so in most of the cases you will need another step the take the first N elements (N
). There are at least two simpler solutions (a little bit less efficient in terms of performance but very handy) to get the elements ready to use from a generator
:
Using list comprehension:
first_N_element=[generator.next() for i in range(N)]
Otherwise:
first_N_element=list(generator)[:N]
Where N
is the number of elements you want to take (e.g. N=5 for the first five elements).
foreach
:
foreach (var money in myMoney) {
Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}
Alternatively, because it is a List<T>
.. which implements an indexer method []
, you can use a normal for
loop as well.. although its less readble (IMO):
for (var i = 0; i < myMoney.Count; i++) {
Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}
here's for SQL server, Oracle, PostgreSQL
which support window functions.
SELECT ROW_NUMBER() OVER (ORDER BY first_name, last_name) Sequence_no,
first_name,
last_name
FROM tableName
This jQuery solution works for me in Chrome and Firefox, for both Ctrl+S and Cmd+S.
$(document).keydown(function(e) {
var key = undefined;
var possible = [ e.key, e.keyIdentifier, e.keyCode, e.which ];
while (key === undefined && possible.length > 0)
{
key = possible.pop();
}
if (key && (key == '115' || key == '83' ) && (e.ctrlKey || e.metaKey) && !(e.altKey))
{
e.preventDefault();
alert("Ctrl-s pressed");
return false;
}
return true;
});
I don't have enough reputation to comment, but this is referring to dsissitka's answer. It works on Windows 10 as well.
To reiterate, the commands are:
cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081
You just need to specify the cursor as a pointer, not a hand, as pointer is now the standard, so, here's the example page code:
<div onclick="location.href='portable-display-stands.html';" id="smallbox">The content of the div here</div>
and the example CSS:
#smallbox {
cursor: pointer;
}
So the div is now a clickable element using 'onclick' and you've faked the hand cursor with the CSS...job done, works for me!
In case your json file does not have a script to stop the app, an option that I use is just by pressing ctrl+C on the cmd.
If support for the iPad 2 or iPod Touch is important for your application, I'd choose a barcode scanner SDK that can decode barcodes in blurry images, such as our Scandit barcode scanner SDK for iOS and Android. Decoding blurry barcode images is also helpful on phones with autofocus cameras because the user does not have to wait for the autofocus to kick in.
Scandit comes with a free community price plan and also has a product API that makes it easy to convert barcode numbers into product names.
(Disclaimer: I'm a co-founder of Scandit)
Latest Update: 16/01/2020
Preprocessor "NOT" required!
There is a lot of repetition in CSS. A single color may be used in several places.
For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.
For non-trivial projects, this is not always possible. By declaring a variable on the :root
pseudo-element, a CSS author can halt some instances of repetition by using the variable.
Set your variable at the top of your stylesheet:
CSS
Create a root class:
:root {
}
Create variables (-- [String] : [value])
:root {
--red: #b00;
--blue: #00b;
--fullwidth: 100%;
}
Set your variables anywhere in your CSS document:
h1 {
color: var(--red);
}
#MyText {
color: var(--blue);
width: var(--fullwidth);
}
See caniuse.com for current compatability.
Firefox: Version 31+ (Enabled by default)
Supported since 2014 (Leading the way as usual.)
Chrome: Version 49+ (Enabled by default).
Supported since 2016
Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).
Supported since 2016
Opera: Version 39+ (Enabled by default).
Supported since 2016
Android: Version 52+ (Enabled by default).
Supported since 2016
Edge: Version 15+ (Enabled by default).
Supported since 2017
CSS Custom Properties landed in Windows Insider Preview build 14986
IE: When pigs fly.
It's time to finally let this ship sink. No one enjoyed riding her anyway. ?
W3C SPEC
Full specification for upcoming CSS variables
A fiddle and snippet are attached below for testing:
(It will only work with supported browsers.)
:root {
--red: #b00;
--blue: #4679bd;
--grey: #ddd;
--W200: 200px;
--Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
float: var(--Lft);
width: var(--W200);
height: var(--W200);
margin: 10px;
padding: 10px;
border: 1px solid var(--red);
}
.Bx1 {
color: var(--red);
background: var(--grey);
}
.Bx2 {
color: var(--grey);
background: black;
}
.Bx3 {
color: var(--grey);
background: var(--blue);
}
.Bx4 {
color: var(--grey);
background: var(--red);
}
_x000D_
<p>If you see four square boxes then variables are working as expected.</p>
<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
_x000D_
You can use the XMLHttpRequest
object as follows:
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
That code would post someStuff
to url
. Just make sure that when you create your XMLHttpRequest
object, it will be cross-browser compatible. There are endless examples out there of how to do that.
Maybe this tool (archived version ) could help? It doesn't return the time, but it is a good tool to measure the time a command takes.
If you only want to look at the memory usage of an object, (answer to other question)
There is a module called Pympler which contains the
asizeof
module.Use as follows:
from pympler import asizeof asizeof.asizeof(my_object)
Unlike
sys.getsizeof
, it works for your self-created objects.>>> asizeof.asizeof(tuple('bcd')) 200 >>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'}) 400 >>> asizeof.asizeof({}) 280 >>> asizeof.asizeof({'foo':'bar'}) 360 >>> asizeof.asizeof('foo') 40 >>> asizeof.asizeof(Bar()) 352 >>> asizeof.asizeof(Bar().__dict__) 280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:
asizeof(*objs, **opts)
Return the combined size in bytes of all objects passed as positional arguments.
df = pd.concat([df['a'], df.b.apply(pd.Series)], axis=1)
This should be the code you need to hide the address bar:
window.addEventListener("load",function() {
setTimeout(function(){
// This hides the address bar:
window.scrollTo(0, 1);
}, 0);
});
Also nice looking Pokedex by the way! Hope this helps!
ifstream inFile;
string name, temp;
int age;
inFile.open("file.txt");
getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age;
cout << name << endl;
cout << age << endl;
inFile.close();
There is no collision in your example. You use the same key, so the old value gets replaced with the new one. Now, if you used two keys that map to the same hash code, then you'd have a collision. But even in that case, HashMap would replace your value! If you want the values to be chained in case of a collision, you have to do it yourself, e.g. by using a list as a value.
$blog is an object not an array
try using $blog->id
instead of $blog['id']
Depending what you're doing, you may not really have a 2-D array.
80% of the time you have simple list of "row-like objects", which might be proper sequences.
myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]
myArray[0][1] == 3.14159
myArray[1][1] == 2.71828
More often, they're instances of a class or a dictionary or a set or something more interesting that you didn't have in your previous languages.
myArray = [ {'pi':3.1415925,'r':2}, {'e':2.71828,'theta':.5} ]
20% of the time you have a dictionary, keyed by a pair
myArray = { (2009,'aug'):(some,tuple,of,values), (2009,'sep'):(some,other,tuple) }
Rarely, will you actually need a matrix.
You have a large, large number of collection classes in Python. Odds are good that you have something more interesting than a matrix.
Simple Css work for me
.modal-dialog {
max-width : 100% ;
}
for using both things variables value and kye
foreach($array as $key=>$value){
print "$key holds $value\n";
}
for using variables value only
foreach($array as $value){
print $value."\n";
}
if you want to do something repeatedly until equal the length of array us this
// for loop
for($i = 0; $i < count($array); $i++) {
// do something with $array[$i]
}
Thanks!
From PEP 3105: print As a Function in the What’s New in Python 2.6 document:
>>> from __future__ import print_function
>>> print('a', end='')
Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_function
at the beginning). The print
statement was removed and became the print()
function by default in Python 3.0.
By using ng-focus you can achieve your goal. you need to provide ng-focus in your input field. And while writing your ng-show derivatives you have to write a logic not equal too. Like the below code:
<input type="text" class="form-control" name="inputPhone" ng-model="demo.phoneNumber" required ng-focus>
<div ng-show="demoForm.inputPhone.$dirty && demoForm.inputPhone.$invalid && !demoForm.inputPhone.$focused"></div>
Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.
use fwrite() instead of file_put_contents()
This simple command works like a charm:
git name-rev <SHA>
For example (where test-branch is the branch name):
git name-rev 651ad3a
251ad3a remotes/origin/test-branch
Even this is working for complex scenarios, like:
origin/branchA/
/branchB
/commit<SHA1>
/commit<SHA2>
Here git name-rev commit<SHA2>
returns branchB.
$.ajax({
type: "POST",
data: formData,
url: "/Forms/GetJobData",
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
alert(response.responseText);
} else {
// DoSomethingElse()
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
Controller:
[HttpPost]
public ActionResult GetJobData(Jobs jobData)
{
var mimeType = jobData.File.ContentType;
var isFileSupported = IsFileSupported(mimeType);
if (!isFileSupported){
// Send "false"
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
else
{
// Send "Success"
return Json(new { success = true, responseText= "Your message successfuly sent!"}, JsonRequestBehavior.AllowGet);
}
}
---Supplement:---
basically you can send multiple parameters this way:
Controller:
return Json(new {
success = true,
Name = model.Name,
Phone = model.Phone,
Email = model.Email
},
JsonRequestBehavior.AllowGet);
Html:
<script>
$.ajax({
type: "POST",
url: '@Url.Action("GetData")',
contentType: 'application/json; charset=utf-8',
success: function (response) {
if(response.success){
console.log(response.Name);
console.log(response.Phone);
console.log(response.Email);
}
},
error: function (response) {
alert("error!");
}
});
You can use:
public function indexAction()
{
dump( $this->getParameter('api_user'));
}
For more information I recommend you read the doc :
http://symfony.com/doc/2.8/service_container/parameters.html
Make it very simple by query:
select substr('123.123',instr('123.123','.')+1, length('123.123')) from dual;
Put your number or column name instead 123.122
You can make this.
CREATE PROC [dbo].[sp_DELETE_MULTI_ROW]
@CODE XML
,@ERRFLAG CHAR(1) = '0' OUTPUT
AS
SET NOCOUNT ON
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
DELETE tb_SampleTest WHERE CODE IN( SELECT Item.value('.', 'VARCHAR(20)') FROM @CODE.nodes('RecordList/ID') AS x(Item) )
IF @@ROWCOUNT = 0 SET @ERRFLAG = 200
SET NOCOUNT OFF
We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.
let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0] //In dd-mm-yyyy format
Try recreate()
it will cause this Activity to be recreated.
you can just split it up and get the last element
var string="xxx_456";
var a=string.split("_");
alert(a[1]); #or a.pop
You might notice using class selector to get value of ASP.NET RadioButton
controls is always empty and here is the reason.
You create RadioButton
control in ASP.NET
as below:
<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />
And ASP.NET
renders following HTML for your RadioButton
<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>
For ASP.NET
we don't want to use RadioButton
control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.
The only remaining feasible way to get the value of the RadioButton
using jQuery is using css class as mentioned in this answer to a totally unrelated question as following
$('span.radios input:radio').click(function() {
var value = $(this).val();
});
Without using inheritance (as mentioned by author), it seems like you are looking for a solution that can transform
one class to another with preassumption of the developer knows and understand the similarity of 2 classes.
There's no existing solution for transforming between objects. What you can try out are:
You could make a recursive function do the work
L = size(M)
idx = zeros(L,1)
length(L)
as the maximum depthfor idx(depth) = 1:L(depth)
length(L)
, do the element operation, else call the function again with depth+1
Not as fast as vectorized methods if you want to check all the points, but if you don't need to evaluate most of them it can be quite a time saver.
You can also use Control-a + H to save loggings into screenlog.n file. One more Control-a + H to turn off.
C-a H: Begins/ends logging of the current window to the file "screenlog.n".
You can get the desired result with the code below. Two'H' in HH
is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
I was facing the same problem and based on guya answer I have extended the underscore library and also added a bit more of functionality that I was requiring. Here's the Gist.
/**
* Merges two object-like arrays based on a key property and also merges its array-like attributes specified in objectPropertiesToMerge.
* It also removes falsy values after merging object properties.
*
* @param firstArray The original object-like array.
* @param secondArray An object-like array to add to the firstArray.
* @param keyProperty The object property that will be used to check if objects from different arrays are the same or not.
* @param objectPropertiesToMerge The list of object properties that you want to merge. It all must be arrays.
* @returns The updated original array.
*/
function merge(firstArray, secondArray, keyProperty, objectPropertiesToMerge) {
function mergeObjectProperties(object, otherObject, objectPropertiesToMerge) {
_.each(objectPropertiesToMerge, function (eachProperty) {
object[eachProperty] = _.chain(object[eachProperty]).union(otherObject[eachProperty]).compact().value();
});
}
if (firstArray.length === 0) {
_.each(secondArray, function (each) {
firstArray.push(each);
});
} else {
_.each(secondArray, function (itemFromSecond) {
var itemFromFirst = _.find(firstArray, function (item) {
return item[keyProperty] === itemFromSecond[keyProperty];
});
if (itemFromFirst) {
mergeObjectProperties(itemFromFirst, itemFromSecond, objectPropertiesToMerge);
} else {
firstArray.push(itemFromSecond);
}
});
}
return firstArray;
}
_.mixin({
merge: merge
});
Hope it to be useful! Regards!
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
The framework creates threads to support each window you create, eg, as when you create a Form and .Show() it. When the windows close, the threads are terminated (ie, they exit).
This is normal behavior. However, if the application is creating threads, and there are a lot of thread exit messages corresponding to these threads (one could tell possibly by the thread's names, by giving them distinct names in the app), then perhaps this is indicative of a problem with the app creating threads when it shouldn't, due to a program logic error.
It would be an interesting followup to have the original poster let us know what s/he discovered regarding the problems with the server crashing. I have a feeling it wouldn't have anything to do with this... but it's hard to tell from the information posted.
Easier would just be using LINQ:
var array = new string[] { "test" }.ToList();
var array1 = new string[] { "test" }.ToList();
array.AddRange(array1);
var result = array.ToArray();
First convert the arrays to lists and merge them... After that just convert the list back to an array :)
You can use a Dictionary to keep track of the keys and values.
For instance...
dictOfStuff = {} ##Make a Dictionary
x = "Buffalo" ##OR it can equal the input of something, up to you.
dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like
print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.
A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.
You could try something like this to test and trim the length:
http://jsfiddle.net/orolo/wJDXL/
var longArray = [1, 2, 3, 4, 5, 6, 7, 8];_x000D_
_x000D_
if (longArray.length >= 6) {_x000D_
longArray.length = 3;_x000D_
}_x000D_
_x000D_
alert(longArray); //1, 2, 3
_x000D_
Using &
is fine for short commands, but that single line can get very long very quick. When that happens, switch to multi-line syntax.
FOR /r %%X IN (*.txt) DO (
ECHO %%X
DEL %%X
)
Placement of (
and )
matters. The round brackets after DO
must be placed on the same line, otherwise the batch file will be incorrect.
See if /?|find /V ""
for details.
import subprocess
filepath="D:/path/to/batch/myBatch.bat"
p = subprocess.Popen(filepath, shell=True, stdout = subprocess.PIPE)
stdout, stderr = p.communicate()
print p.returncode # is 0 if success
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
Default-Values are only considered for parameters NOT given to the function.
So given a function
procedure foo( bar1 IN number DEFAULT 3,
bar2 IN number DEFAULT 5,
bar3 IN number DEFAULT 8 );
if you call this procedure with no arguments then it will behave as if called with
foo( bar1 => 3,
bar2 => 5,
bar3 => 8 );
but 'NULL' is still a parameter.
foo( 4,
bar3 => NULL );
This will then act like
foo( bar1 => 4,
bar2 => 5,
bar3 => Null );
( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )
one way to treat NULL the same as a default value would be to default the value to NULL
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL );
and using a variable with the desired value then
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL )
AS
v_bar1 number := NVL( bar1, 3);
v_bar2 number := NVL( bar2, 5);
v_bar3 number := NVL( bar3, 8);
If View's height/width = wrap_content
use:
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
If View's height/width = match_parent
use:
android:gravity="center_vertical|center_horizontal"
<VirtualHost *:80>
ServerName www.YOURDOMAIN.COM
ServerAlias YOURDOMAIN.COM
DocumentRoot /var/www/YOURDOMAIN.COM/public_html
ErrorLog /var/www/YOURDOMAIN.COM/error.log
CustomLog /var/www/YOURDOMAIN.COM/requests.log combined
DocumentRoot /var/www/YOURDOMAIN.COM/public_html
<Directory />
Options FollowSymLinks
AllowOverride None
</Directory>
<Directory /var/www/YOURDOMAIN.COM/public_html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
</VirtualHost>
Static methods are treated as global by the JVM, there are not bound to an object instance at all.
It could conceptually be possible if you could call static methods from class objects (like in languages like Smalltalk) but it's not the case in Java.
EDIT
You can overload static method, that's ok. But you can not override a static method, because class are no first-class object. You can use reflection to get the class of an object at run-time, but the object that you get does not parallel the class hierarchy.
class MyClass { ... }
class MySubClass extends MyClass { ... }
MyClass obj1 = new MyClass();
MySubClass obj2 = new MySubClass();
ob2 instanceof MyClass --> true
Class clazz1 = obj1.getClass();
Class clazz2 = obj2.getClass();
clazz2 instanceof clazz1 --> false
You can reflect over the classes, but it stops there. You don't invoke a static method by using clazz1.staticMethod()
, but using MyClass.staticMethod()
. A static method is not bound to an object and there is hence no notion of this
nor super
in a static method. A static method is a global function; as a consequence there is also no notion of polymorphism and, therefore, method overriding makes no sense.
But this could be possible if MyClass
was an object at run-time on which you invoke a method, as in Smalltalk (or maybe JRuby as one comment suggest, but I know nothing of JRuby).
Oh yeah... one more thing. You can invoke a static method through an object obj1.staticMethod()
but that really syntactic sugar for MyClass.staticMethod()
and should be avoided. It usually raises a warning in modern IDE. I don't know why they ever allowed this shortcut.
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES
program which was causing the issue.
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
This solution requires you to add a second ListBox element and place it above the first one.
Like this:
Then you call the function CreateListBoxHeader to make the alignment correct and add header items.
Result:
Public Sub CreateListBoxHeader(body As MSForms.ListBox, header As MSForms.ListBox, arrHeaders)
' make column count match
header.ColumnCount = body.ColumnCount
header.ColumnWidths = body.ColumnWidths
' add header elements
header.Clear
header.AddItem
Dim i As Integer
For i = 0 To UBound(arrHeaders)
header.List(0, i) = arrHeaders(i)
Next i
' make it pretty
body.ZOrder (1)
header.ZOrder (0)
header.SpecialEffect = fmSpecialEffectFlat
header.BackColor = RGB(200, 200, 200)
header.Height = 10
' align header to body (should be done last!)
header.Width = body.Width
header.Left = body.Left
header.Top = body.Top - (header.Height - 1)
End Sub
Private Sub UserForm_Activate()
Call CreateListBoxHeader(Me.listBox_Body, Me.listBox_Header, Array("Header 1", "Header 2"))
End Sub
You can use template module to copy if script exists on local machine to remote machine and execute it.
- name: Copy script from local to remote machine
hosts: remote_machine
tasks:
- name: Copy script to remote_machine
template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
- name: Execute script on remote_machine
script: sh <remote_machine path>/script.sh
It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window
object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload
definition is simply being hit after the browser fires the window.onload
event.
This will read a csv file and it includes a csv line splitter that handles double quotes and it can read even if excel has it open.
public List<Dictionary<string, string>> LoadCsvAsDictionary(string path)
{
var result = new List<Dictionary<string, string>>();
var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
System.IO.StreamReader file = new System.IO.StreamReader(fs);
string line;
int n = 0;
List<string> columns = null;
while ((line = file.ReadLine()) != null)
{
var values = SplitCsv(line);
if (n == 0)
{
columns = values;
}
else
{
var dict = new Dictionary<string, string>();
for (int i = 0; i < columns.Count; i++)
if (i < values.Count)
dict.Add(columns[i], values[i]);
result.Add(dict);
}
n++;
}
file.Close();
return result;
}
private List<string> SplitCsv(string csv)
{
var values = new List<string>();
int last = -1;
bool inQuotes = false;
int n = 0;
while (n < csv.Length)
{
switch (csv[n])
{
case '"':
inQuotes = !inQuotes;
break;
case ',':
if (!inQuotes)
{
values.Add(csv.Substring(last + 1, (n - last)).Trim(' ', ','));
last = n;
}
break;
}
n++;
}
if (last != csv.Length - 1)
values.Add(csv.Substring(last + 1).Trim());
return values;
}
If the format of the id's in the two table varies then you want to join them, as such you can select to use an id from one-main table, say if you have table_customes
and table_orders
, and tha id for orders is like "101","102"..."110", just use one for customers
select customers.id, name, amount, date from customers.orders;
"Barack Obama" has a space between 'Barack' and 'Obama'. To accommodate that, use this code;
#include <stdio.h>
int main()
{
printf("Enter your name\n");
char a[80];
gets(a);
printf("Your name is %s\n", a);
return 0;
}
\d+
\d
represents any digit, +
for one or more. If you want to catch negative numbers as well you can use -?\d+
.
Note that as a string, it should be represented in C# as "\\d+"
, or @"\d+"
the proper way is:
.attr({target:'nw', title:'Opens in a new window'})
For completeness, I'll add that this can be done with dplyr
as well using slice
. The advantage of using this is that it can be part of a piped workflow.
df <- df %>%
.
.
slice(-c(2, 4, 6)) %>%
.
.
Of course, you can also use it without pipes.
df <- slice(df, -c(2, 4, 6))
The "not vector" format, -c(2, 4, 6)
means to get everything that is not at rows 2, 4 and 6. For an example using a range, let's say you wanted to remove the first 5 rows, you could do slice(df, 6:n())
. For more examples, see the docs.
It seems the docs/tool have been updated and you can now add the image
tag to your script. This was successful for me.
Example:
version: '2'
services:
baggins.api.rest:
image: my.image.name:rc2
build:
context: ../..
dockerfile: app/Docker/Dockerfile.release
ports:
...
This fiddle has both each
and direct json. http://jsfiddle.net/streethawk707/a9ssja22/.
Below are the two ways of iterating over array. One is with direct json passing and another is naming the json array while passing to content holder.
Eg1: The below example is directly calling json key (data) inside small_data variable.
In html use the below code:
<div id="small-content-placeholder"></div>
The below can be placed in header or body of html:
<script id="small-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#data}}
<tr>
<td>{{username}}
</td>
<td>{{email}}</td>
</tr>
{{/data}}
</tbody>
</table>
</script>
The below one is on document ready:
var small_source = $("#small-template").html();
var small_template = Handlebars.compile(small_source);
The below is the json:
var small_data = {
data: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" }
]
};
Finally attach the json to content holder:
$("#small-content-placeholder").html(small_template(small_data));
Eg2: Iteration using each.
Consider the below json.
var big_data = [
{
name: "users1",
details: [
{username: "alan1", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison1", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan1", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
},
{
name: "users2",
details: [
{username: "alan2", firstName: "Alan", lastName: "Johnson", email: "[email protected]" },
{username: "allison2", firstName: "Allison", lastName: "House", email: "[email protected]" },
{username: "ryan2", firstName: "Ryan", lastName: "Carson", email: "[email protected]" }
]
}
];
While passing the json to content holder just name it in this way:
$("#big-content-placeholder").html(big_template({big_data:big_data}));
And the template looks like :
<script id="big-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Username</th>
<th>email</th>
</thead>
<tbody>
{{#each big_data}}
<tr>
<td>{{name}}
<ul>
{{#details}}
<li>{{username}}</li>
<li>{{email}}</li>
{{/details}}
</ul>
</td>
<td>{{email}}</td>
</tr>
{{/each}}
</tbody>
</table>
</script>
Since you are loading in the spans via ajax you will have to attach delegate handlers to the events to catch them as they bubble up.
$(document).on('click','span',function(e){
console.log(e.target.id)
})
you will want to attach the event to the closest static member you can to increase efficiency.
$('#main_div').on('click','span',function(e){
console.log(e.target.id)
})
is better than binding to the document for instance.
This question may help you understand
In my case. I had the error because I forgot to make a commit after create a repository on github into an existing project. So I solved:
git add .
git commit -m"commentary"
Then I was able to type:
git push -u origin master
Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/')
followed by relative paths for os.system
, subprocess
methods, or whatever...
If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe
file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?
In my case I had to go to the MySQL installer, then configuration button for the MySQL server, then next until the option to "create the server as a windows service" ticked that, gave it a service name as MySQL8.0, next and then finish, that solved the issue and started a new service
This is how I delete files
if ((System.IO.File.Exists(fileName)))
{
System.IO.File.Delete(fileName);
}
Also make sure that the file name you are passing in your delete, is the accurate path
EDIT
You could use the following event instead as well or just use the code in this snippet and use in your method
void GridView1_SelectedIndexChanged(Object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = CustomersGridView.SelectedRow;
//Debug this line and see what value is returned if it contains the full path.
//If it does not contain the full path then add the path to the string.
string fileName = row.Cells[0].Text
if(fileName != null || fileName != string.empty)
{
if((System.IO.File.Exists(fileName))
System.IO.File.Delete(fileName);
}
}
You need
str.CopyTo(data);
data.Position = 0; // reset to beginning
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
And since your Test()
method is imitating the client it ought to Close()
or Dispose()
the str
Stream. And the memoryStream too, just out of principal.
use the float or real data types only if the precision provided by decimal (up to 38 digits) is insufficient
Approximate numeric data types do not store the exact values specified for many numbers; they store an extremely close approximation of the value.(Technet)
Avoid using float or real columns in WHERE clause search conditions, especially the = and <> operators (Technet)
so generally because the precision provided by decimal is [10E38 ~ 38 digits] if your number can fit in it, and smaller storage space (and maybe speed) of Float is not important and dealing with abnormal behaviors and issues of approximate numeric types are not acceptable, use Decimal generally.
more useful information
main source : MCTS Self-Paced Training Kit (Exam 70-433): Microsoft® SQL Server® 2008 Database Development - Chapter 3 - Tables , Data Types , and Declarative Data Integrity Lesson 1 - Choosing Data Types (Guidelines) - Page 93
One more way to do it (if you use form), note that input type is button
<input type="button" onclick="showMessage()" value="submit" />
Complete code is:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:
<input type="submit" onclick="showMessage()" value="submit" />
No need to set
return false;
from JavaScript function for neither of those two examples.
Create an iframe when button/link is clicked and append this to body.
$('<iframe />')
.attr('src', url)
.attr('id','iframe_download_report')
.hide()
.appendTo('body');
Create an iframe with delay and delete it after download.
var triggerDelay = 100;
var cleaningDelay = 20000;
var that = this;
setTimeout(function() {
var frame = $('<iframe style="width:1px; height:1px;" class="multi-download-frame"></iframe>');
frame.attr('src', url+"?"+ "Content-Disposition: attachment ; filename="+that.model.get('fileName'));
$(ev.target).after(frame);
setTimeout(function() {
frame.remove();
}, cleaningDelay);
}, triggerDelay);
You can create an array of pointers.
Car** mycars = new Car*[userInput];
for (int i=0; i<userInput; i++){
mycars[i] = new Car(...);
}
...
for (int i=0; i<userInput; i++){
delete mycars[i];
}
delete [] mycars;
or
Car() constructor does not need to be public. Add a static method to your class that builds an array:
static Car* makeArray(int length){
return new Car[length];
}
Alternatively, in plain text: (also available as a a screenshot)
Bracket Matching -. .- Line Numbering
Smart Indent -. | | .- UML Editing / Viewing
Source Control Integration -. | | | | .- Code Folding
Error Markup -. | | | | | | .- Code Templates
Integrated Python Debugging -. | | | | | | | | .- Unit Testing
Multi-Language Support -. | | | | | | | | | | .- GUI Designer (Qt, Eric, etc)
Auto Code Completion -. | | | | | | | | | | | | .- Integrated DB Support
Commercial/Free -. | | | | | | | | | | | | | | .- Refactoring
Cross Platform -. | | | | | | | | | | | | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Atom |Y |F |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y | | | | |*many plugins
Editra |Y |F |Y |Y | | |Y |Y |Y |Y | |Y | | | | | |
Emacs |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
Eric Ide |Y |F |Y | |Y |Y | |Y | |Y | |Y | |Y | | | |
Geany |Y |F |Y*|Y | | | |Y |Y |Y | |Y | | | | | |*very limited
Gedit |Y |F |Y¹|Y | | | |Y |Y |Y | | |Y²| | | | |¹with plugin; ²sort of
Idle |Y |F |Y | |Y | | |Y |Y | | | | | | | | |
IntelliJ |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |
JEdit |Y |F | |Y | | | | |Y |Y | |Y | | | | | |
KDevelop |Y |F |Y*|Y | | |Y |Y |Y |Y | |Y | | | | | |*no type inference
Komodo |Y |CF|Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | |Y | |
NetBeans* |Y |F |Y |Y |Y | |Y |Y |Y |Y |Y |Y |Y |Y | | |Y |*pre-v7.0
Notepad++ |W |F |Y |Y | |Y*|Y*|Y*|Y |Y | |Y |Y*| | | | |*with plugin
Pfaide |W |C |Y |Y | | | |Y |Y |Y | |Y |Y | | | | |
PIDA |LW|F |Y |Y | | | |Y |Y |Y | |Y | | | | | |VIM based
PTVS |W |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y | | |Y*| |Y |*WPF bsed
PyCharm |Y |CF|Y |Y*|Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |*JavaScript
PyDev (Eclipse) |Y |F |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y |Y | | | |
PyScripter |W |F |Y | |Y |Y | |Y |Y |Y | |Y |Y |Y | | | |
PythonWin |W |F |Y | |Y | | |Y |Y | | |Y | | | | | |
SciTE |Y |F¹| |Y | |Y | |Y |Y |Y | |Y |Y | | | | |¹Mac version is
ScriptDev |W |C |Y |Y |Y |Y | |Y |Y |Y | |Y |Y | | | | | commercial
Spyder |Y |F |Y | |Y |Y | |Y |Y |Y | | | | | | | |
Sublime Text |Y |CF|Y |Y | |Y |Y |Y |Y |Y | |Y |Y |Y*| | | |extensible w/Python,
TextMate |M |F | |Y | | |Y |Y |Y |Y | |Y |Y | | | | | *PythonTestRunner
UliPad |Y |F |Y |Y |Y | | |Y |Y | | | |Y |Y | | | |
Vim |Y |F |Y |Y |Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |
Visual Studio |W |CF|Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |Y |? |Y |
Visual Studio Code|Y |F |Y |Y |Y |Y |Y |Y |Y |Y |? |Y |? |? |? |? |Y |uses plugins
WingIde |Y |C |Y |Y*|Y |Y |Y |Y |Y |Y | |Y |Y |Y | | | |*support for C
Zeus |W |C | | | | |Y |Y |Y |Y | |Y |Y | | | | |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
Cross Platform -' | | | | | | | | | | | | | | | |
Commercial/Free -' | | | | | | | | | | | | | | '- Refactoring
Auto Code Completion -' | | | | | | | | | | | | '- Integrated DB Support
Multi-Language Support -' | | | | | | | | | | '- GUI Designer (Qt, Eric, etc)
Integrated Python Debugging -' | | | | | | | | '- Unit Testing
Error Markup -' | | | | | | '- Code Templates
Source Control Integration -' | | | | '- Code Folding
Smart Indent -' | | '- UML Editing / Viewing
Bracket Matching -' '- Line Numbering
Acronyms used:
L - Linux
W - Windows
M - Mac
C - Commercial
F - Free
CF - Commercial with Free limited edition
? - To be confirmed
I don't mention basics like syntax highlighting as I expect these by default.
This is a just dry list reflecting your feedback and comments, I am not advocating any of these tools. I will keep updating this list as you keep posting your answers.
PS. Can you help me to add features of the above editors to the list (like auto-complete, debugging, etc.)?
We have a comprehensive wiki page for this question https://wiki.python.org/moin/IntegratedDevelopmentEnvironments
We can handle this by using offset value
public static long convertDateTimeZone(long lngDate, String fromTimeZone,
String toTimeZone){
TimeZone toTZ = TimeZone.getTimeZone(toTimeZone);
Calendar toCal = Calendar.getInstance(toTZ);
TimeZone fromTZ = TimeZone.getTimeZone(fromTimeZone);
Calendar fromCal = Calendar.getInstance(fromTZ);
fromCal.setTimeInMillis(lngDate);
toCal.setTimeInMillis(fromCal.getTimeInMillis()
+ toTZ.getOffset(fromCal.getTimeInMillis())
- TimeZone.getDefault().getOffset(fromCal.getTimeInMillis()));
return toCal.getTimeInMillis();
}
Test Code snippet:
System.out.println(new Date().getTime())
System.out.println(convertDateTimeZone(new Date().getTime(), TimeZone
.getDefault().getID(), "EST"));
Output: 1387353270742 1387335270742
del list[:]
Will delete the values of that list variable
del list
Will delete the variable itself from memory
I can offer you a jquery solution
add this in your <head></head>
tag
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
add this after </ul>
<script> $('ul li:first').remove(); </script>
With the use of jQuery to handle the document ready event,
<script type="text/javascript">
function onLoadAlert() {
alert('<%: TempData["Resultat"]%>');
}
$(document).ready(onLoadAlert);
</script>
Or, even simpler - put the <script>
at the end of body
, not in the head
.
I believe using DFS correctly also depends on how are you going to represent your graph in the code. For example suppose you are using adjacent lists to keep track of neighbor nodes and your graph has 2 vertices and only one edge: V={1,2} and E={(1,2)}. In this case starting from vertex 1, DFS will mark it as VISITED and will put 2 in the queue. After that it will pop vertex 2 and since 1 is adjacent to 2, and 1 is VISITED, DFS will conclude that there is a cycle (which is wrong). In other words in Undirected graphs (1,2) and (2,1) are the same edge and you should code in a way for DFS not to consider them different edges. Keeping parent node for each visited node will help to handle this situation.
The best way to do this is with the following code:
Button button = (Button)findViewById(R.id.btn_register);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//do your fancy method
}
});
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
I like pprzemek's solution because it does not assume that the delimiters are single characters and it doesn't try to leverage a regex (which would not work well if the number of separators got to be crazy long).
Here's a more readable version of the above solution for clarity:
def split_string_on_multiple_separators(input_string, separators):
buffer = [input_string]
for sep in separators:
strings = buffer
buffer = [] # reset the buffer
for s in strings:
buffer = buffer + s.split(sep)
return buffer
Are you working with a @Service
too? Because if you are, then you can @Autowired
your PersonRepository
to the @Service
and then in the service just invoke the Name
class and use the form that @CuriosMind... proposed:
@Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
@Param("forename") String firstname);
}
and when invoking the method from the repository in the service, you can then pass those parameters.
Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
This is because you are reading a cursor, not an array. This means that you are reading sequentially through the results and when you get to the end you would need to reset the cursor to the beginning of the results to read them again.
If you did want to read over the results multiple times, you could use fetchAll to read the results into a true array and then it would work as you are expecting.
I use this:
function fnIsAppleMobile()
{
if (navigator && navigator.userAgent && navigator.userAgent != null)
{
var strUserAgent = navigator.userAgent.toLowerCase();
var arrMatches = strUserAgent.match(/(iphone|ipod|ipad)/);
if (arrMatches != null)
return true;
} // End if (navigator && navigator.userAgent)
return false;
} // End Function fnIsAppleMobile
var bIsAppleMobile = fnIsAppleMobile(); // TODO: Write complaint to CrApple asking them why they don't update SquirrelFish with bugfixes, then remove
Use input.nextLine();
instead of input.next();
A SilverStripe-specific answer worked out from reading: http://api.silverstripe.org/3.0/source-class-SS_Datetime.html#98-110:
Hopefully this will help someone using a SilverStripe template and trying to force reload a cached image on each page visit / refresh. In my case it is a GIF animation which only plays once and therefore did not replay after it was cached. In my template I simply added:
?$Now.Format(dmYHis)
to the end of the file path to create a unique time stamp and to force the browser to treat it as a new file.
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
// If the no button was pressed ...
if (result == DialogResult.No)
{
...
}
Hope it helps
Please refer below Ajax overview:
Use window.getSelection().toString()
.
You can read more on developer.mozilla.org
The accepted answer previously contained new Buffer()
, which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).
The Buffer
constructor is deprecated according to the documentation.
Here is an example of a vulnerability that can result from using it in the ws library.
The code snippets should read:
console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));
After this answer was written, it has been updated and now matches this.
PostgreSQL 13 introduced FORCE
option.
DROP DATABASE drops a database ... Also, if anyone else is connected to the target database, this command will fail unless you use the FORCE option described below.
FORCE
Attempt to terminate all existing connections to the target database. It doesn't terminate if prepared transactions, active logical replication slots or subscriptions are present in the target database.
DROP DATABASE db_name WITH (FORCE);
If you read a string from an XML file, the line break \n
in this string will not work in UILabel
text. The \n
is not parsed to a line break.
Here is a little trick to solve this issue:
// correct next line \n in string from XML file
NSString *myNewLineStr = @"\n";
myLabelText = [myLabelText stringByReplacingOccurrencesOfString:@"\\n" withString:myNewLineStr];
myLabel.text = myLabelText;
So you have to replace the unparsed \n
part in your string by a parsed \n
in a hardcoded NSString
.
Here are my other label settings:
myLabel.numberOfLines = 0;
myLabel.backgroundColor = [UIColor lightGrayColor];
myLabel.textColor = [UIColor redColor];
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];
myLabel.textAlignment = UITextAlignmentCenter;
Most important is to set numberOfLines
to 0
(= unlimited number of lines in label).
No idea why Apple has chosen to not parse \n
in strings read from XML?
Hope this helps.
Consider that we need to create the following XML document:
<?xml version="1.0"?>
<people>
<person first-name="eric" middle-initial="H" last-name="jung">
<address street="321 south st" city="denver" state="co" country="usa"/>
<address street="123 main st" city="arlington" state="ma" country="usa"/>
</person>
<person first-name="jed" last-name="brown">
<address street="321 north st" city="atlanta" state="ga" country="usa"/>
<address street="123 west st" city="seattle" state="wa" country="usa"/>
<address street="321 south avenue" city="denver" state="co" country="usa"/>
</person>
</people>
we can write the following code to generate the above XML
var doc = document.implementation.createDocument("", "", null);
var peopleElem = doc.createElement("people");
var personElem1 = doc.createElement("person");
personElem1.setAttribute("first-name", "eric");
personElem1.setAttribute("middle-initial", "h");
personElem1.setAttribute("last-name", "jung");
var addressElem1 = doc.createElement("address");
addressElem1.setAttribute("street", "321 south st");
addressElem1.setAttribute("city", "denver");
addressElem1.setAttribute("state", "co");
addressElem1.setAttribute("country", "usa");
personElem1.appendChild(addressElem1);
var addressElem2 = doc.createElement("address");
addressElem2.setAttribute("street", "123 main st");
addressElem2.setAttribute("city", "arlington");
addressElem2.setAttribute("state", "ma");
addressElem2.setAttribute("country", "usa");
personElem1.appendChild(addressElem2);
var personElem2 = doc.createElement("person");
personElem2.setAttribute("first-name", "jed");
personElem2.setAttribute("last-name", "brown");
var addressElem3 = doc.createElement("address");
addressElem3.setAttribute("street", "321 north st");
addressElem3.setAttribute("city", "atlanta");
addressElem3.setAttribute("state", "ga");
addressElem3.setAttribute("country", "usa");
personElem2.appendChild(addressElem3);
var addressElem4 = doc.createElement("address");
addressElem4.setAttribute("street", "123 west st");
addressElem4.setAttribute("city", "seattle");
addressElem4.setAttribute("state", "wa");
addressElem4.setAttribute("country", "usa");
personElem2.appendChild(addressElem4);
var addressElem5 = doc.createElement("address");
addressElem5.setAttribute("street", "321 south avenue");
addressElem5.setAttribute("city", "denver");
addressElem5.setAttribute("state", "co");
addressElem5.setAttribute("country", "usa");
personElem2.appendChild(addressElem5);
peopleElem.appendChild(personElem1);
peopleElem.appendChild(personElem2);
doc.appendChild(peopleElem);
If any text need to be written between a tag we can use innerHTML property to achieve it.
Example
elem = doc.createElement("Gender")
elem.innerHTML = "Male"
parent_elem.appendChild(elem)
For more details please follow the below link. The above example has been explained there in more details.
https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/How_to_create_a_DOM_tree
You can use maven-assembly-plugin, Here is the example from the official site: https://maven.apache.org/plugins/maven-assembly-plugin/usage.html
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>your main class</mainClass>
</manifest>
</archive>
</configuration>
<executions>
<execution>
<id>make-assembly</id> <!-- this is used for inheritance merges -->
<phase>package</phase> <!-- bind to the packaging phase -->
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
The least complicated, most straight-forward way of doing this is by simply wrapping your main query with the pivot in a common table expression, then grouping/aggregating.
WITH PivotCTE AS
(
select * from mytransactions
pivot (sum (totalcount) for country in ([Australia], [Austria])) as pvt
)
SELECT
numericmonth,
chardate,
SUM(totalamount) AS totalamount,
SUM(ISNULL(Australia, 0)) AS Australia,
SUM(ISNULL(Austria, 0)) Austria
FROM PivotCTE
GROUP BY numericmonth, chardate
The ISNULL
is to stop a NULL
value from nullifying the sum (because NULL
+ any value = NULL
)
You want to check that each character matches your requirements, which is why we use:
[A-Za-z0-9_]
And you can even use the shorthand version:
\w
Which is equivalent (in some regex flavors, so make sure you check before you use it). Then to indicate that the entire string must match, you use:
^
To indicate the string must start with that character, then use
$
To indicate the string must end with that character. Then use
\w+ or \w*
To indicate "1 or more", or "0 or more". Putting it all together, we have:
^\w*$
I think it suffices to hand the data over directly:
$("#inputhidden").select2("data", data, true);
Note that the second parameter seems to indicate that a refresh is desired.
Thanks to @Bergi for help with this.
If that doesn't automatically update you could either try calling it's updateResults method directly.
$("#inputhidden").select2("updateResults");
Or trigger it indirectly by sending a trigger to the "input.select2-input" like so:
var search = $("#inputhidden input.select2-input");
search.trigger("input");
If this is what you want only HTML and CSS solution
Here's the HTML
<div class="outer-container"> <!-- absolute positioned container -->
<div class="inner-container">
<div class="table-header">
<table id="headertable" width="100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th class="header-cell col1">One</th>
<th class="header-cell col2">Two</th>
<th class="header-cell col3">Three</th>
<th class="header-cell col4">Four</th>
<th class="header-cell col5">Five</th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table id="bodytable" width="100%" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
<tr>
<td class="body-cell col1">body row1</td>
<td class="body-cell col2">body row2</td>
<td class="body-cell col3">body row2</td>
<td class="body-cell col4">body row2</td>
<td class="body-cell col5">body row2 en nog meer</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
And this is the css
body {
margin:0;
padding:0;
height: 100%;
width: 100%;
}
table {
border-collapse: collapse; /* make simple 1px lines borders if border defined */
}
tr {
width: 100%;
}
.outer-container {
background-color: #ccc;
position: absolute;
top:0;
left: 0;
right: 300px;
bottom:40px;
overflow: scroll;
}
.inner-container {
width: 100%;
height: 100%;
position: relative;
overflow-x: visible;
overflow-y:visible;
}
.table-header {
float:left;
width: 100%;
}
.table-body {
float:left;
height: auto;
width: auto;
overflow: visible;
background-color: red;
}
.header-cell {
background-color: yellow;
text-align: left;
height: 40px;
}
.body-cell {
background-color: transparent;
text-align: left;
}
.col1, .col3, .col4, .col5 {
width:120px;
min-width: 120px;
}
.col2 {
min-width: 300px;
}
Let me know if this is what you need. Or some thing is missing. I went through the other answers and found that jquery has been used . I took it on assumption that you need css solution . If I am missing any more point please mention :)
For now, I'll redefine the enum as:
enum Audience: String {
case Public = "Public"
case Friends = "Friends"
case Private = "Private"
}
so that I can do:
audience.toRaw() // "Public"
But, isn't this new enum definition redundant? Can I keep the initial enum definition and do something like:
audience.toString() // "Public"
I realize I'm a little late but here's a shim for the new firefox 47 Object.values
method
Object.prototype.values = Object.prototype.values || function(obj) {
return this.keys(obj).map(function(key){
return obj[key];
});
};
I didn't have much luck with many of these solutions on all browsers. This is the solution that worked for me.
For router changes:
router.events.subscribe((val) => {
setTimeout(() => {
if (this.searchElement) {
this.searchElement.nativeElement.focus();
}
}, 1);
})
Then ngAfterViewInit()
for the onload scenario.
This function returns an array regardless of the size of the range.
Ranges will return an array unless the range is only 1 cell and then it returns a single value instead. This function will turn the single value into an array (1 based, the same as the array's returned by ranges)
This answer improves on previous answers as it will return an array from a range no matter what the size. It is also more efficient that other answers as it will return the array generated by the range if possible. Works with single dimension and multi-dimensional arrays
The function works by trying to find the upper bounds of the array. If that fails then it must be a single value so we'll create an array and assign the value to it.
Public Function RangeToArray(inputRange As Range) As Variant()
Dim size As Integer
Dim inputValue As Variant, outputArray() As Variant
' inputValue will either be an variant array for ranges with more than 1 cell
' or a single variant value for range will only 1 cell
inputValue = inputRange
On Error Resume Next
size = UBound(inputValue)
If Err.Number = 0 Then
RangeToArray = inputValue
Else
On Error GoTo 0
ReDim outputArray(1 To 1, 1 to 1)
outputArray(1,1) = inputValue
RangeToArray = outputArray
End If
On Error GoTo 0
End Function
Just use the css style "white-space: pre-wrap" and you should be good to go. I've had the same issue where I need to handle error messages for which the line breaks and white spaces are really particular. I just added this inline where I was binding the data and it works like Charm!
You can use the Sum
function, but you'll have to convert the strings to integers, like so:
int total = monValues.Sum(x => Convert.ToInt32(x));
Simple and easy way to show back button on toolbar
Paste this code in onCreate method
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Paste this override method outside the onCreate method
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
I'd like to emphasize that order of arguments is important.
For me java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000 -jar app.jar
command opens debugger port,
but java -jar app.jar -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8000
command doesn't.
Easiest way is to customize bootstrap
find variable:
@grid-float-breakpoint
which is set to @screen-sm, you can change it according to your needs. Hope it helps!
Finally, this is what I did:
private File getFileFromURL() {
URL url = this.getClass().getClassLoader().getResource("/sql");
File file = null;
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
file = new File(url.getPath());
} finally {
return file;
}
}
...
File folder = getFileFromURL();
File[] listOfFiles = folder.listFiles();
It's the same principle.
You can either use SelectedIndex and use ComboBox.Items[SelectedIndex].ToString(). Or just ComboBox.SelectedItem and cast it to any type you need :)
Having read the above answers i found that for my situation the following fixed the issue.
This threw the error
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(getApplicationContext());
dialog.show();
}
});
Based on the previous answers that suggested the context was the wrong one, i changed the getApplicationContext() to retrieve the context from the View passed in to the buttons onClick method.
myButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
MyDialogue dialog = new MyDialogue(v.getContext());
dialog.show();
}
});
I don't fully understand the workings of Java so i could be wrong, but I'm guessing that for my specific situation the cause could have been related to the fact that the above snippet was defined in an Abstract Activity class; inherited and used by many Activities, perhaps that contributed to the fact that getApplicationContext() doesn't return a valid context?? (Just a guess).
I will tell , how i solved almost similar problem. I developed a application using VS 2013 and tried to create wizard for it failed to do. Later i installed premium VS and tried and failed.
at last i used "ClickOnce" and it worked fine.
So i believe here also , "CLICKONCE" would help you.
So is this the answer?
"If you need to calculate something but not show it, set the element to visibility:hidden
and position:absolute
, add it to the DOM tree, get the offsetHeight, and remove it. (That's what the prototype library does behind the lines last time I checked)."
I have the same problem on a number of elements. There is no jQuery or Prototype to be used on the site but I'm all in favor of borrowing the technique if it works. As an example of some things that failed to work, followed by what did, I have the following code:
// Layout Height Get
function fnElementHeightMaxGet(DoScroll, DoBase, elementPassed, elementHeightDefault)
{
var DoOffset = true;
if (!elementPassed) { return 0; }
if (!elementPassed.style) { return 0; }
var thisHeight = 0;
var heightBase = parseInt(elementPassed.style.height);
var heightOffset = parseInt(elementPassed.offsetHeight);
var heightScroll = parseInt(elementPassed.scrollHeight);
var heightClient = parseInt(elementPassed.clientHeight);
var heightNode = 0;
var heightRects = 0;
//
if (DoBase) {
if (heightBase > thisHeight) { thisHeight = heightBase; }
}
if (DoOffset) {
if (heightOffset > thisHeight) { thisHeight = heightOffset; }
}
if (DoScroll) {
if (heightScroll > thisHeight) { thisHeight = heightScroll; }
}
//
if (thisHeight == 0) { thisHeight = heightClient; }
//
if (thisHeight == 0) {
// Dom Add:
// all else failed so use the protype approach...
var elBodyTempContainer = document.getElementById('BodyTempContainer');
elBodyTempContainer.appendChild(elementPassed);
heightNode = elBodyTempContainer.childNodes[0].offsetHeight;
elBodyTempContainer.removeChild(elementPassed);
if (heightNode > thisHeight) { thisHeight = heightNode; }
//
// Bounding Rect:
// Or this approach...
var clientRects = elementPassed.getClientRects();
heightRects = clientRects.height;
if (heightRects > thisHeight) { thisHeight = heightRects; }
}
//
// Default height not appropriate here
// if (thisHeight == 0) { thisHeight = elementHeightDefault; }
if (thisHeight > 3000) {
// ERROR
thisHeight = 3000;
}
return thisHeight;
}
which basically tries anything and everything only to get a zero result. ClientHeight with no affect. With the problem elements I typically get NaN in the Base and zero in the Offset and Scroll heights. I then tried the Add DOM solution and clientRects to see if it works here.
29 Jun 2011, I did indeed update the code to try both adding to DOM and clientHeight with better results than I expected.
1) clientHeight was also 0.
2) Dom actually gave me a height which was great.
3) ClientRects returns a result almost identical to the DOM technique.
Because the elements added are fluid in nature, when they are added to an otherwise empty DOM Temp element they are rendered according to the width of that container. This get weird, because that is 30px shorter than it eventually ends up.
I added a few snapshots to illustrate how the height is calculated differently.
The height differences are obvious. I could certainly add absolute positioning and hidden but I am sure that will have no effect. I continued to be convinced this would not work!
(I digress further) The height comes out (renders) lower than the true rendered height. This could be addressed by setting the width of the DOM Temp element to match the existing parent and could be done fairly accurately in theory. I also do not know what would result from removing them and adding them back into their existing location. As they arrived through an innerHTML technique I will be looking using this different approach.
* HOWEVER * None of that was necessary. In fact it worked as advertised and returned the correct height!!!
When I was able to get the menus visible again amazingly DOM had returned the correct height per the fluid layout at the top of the page (279px). The above code also uses getClientRects which return 280px.
This is illustrated in the following snapshot (taken from Chrome once working.)
Now I have noooooo idea why that prototype trick works, but it seems to. Alternatively, getClientRects also works.
I suspect the cause of all this trouble with these particular elements was the use of innerHTML instead of appendChild, but that is pure speculation at this point.
Assuming you're using WinForms, as it was the first thing I did when I was starting C# you need to create an event to close this form.
Lets say you've got a button called myNewButton. If you double click it on WinForms designer you will create an event. After that you just have to use this.Close
private void myNewButton_Click(object sender, EventArgs e) {
this.Close();
}
And that should be it.
The only reason for this not working is that your Event is detached from button. But it should create new event if old one is no longer attached when you double click on the button in WinForms designer.
You need to call self.a()
to invoke a
from b
. a
is not a global function, it is a method on the class.
You may want to read through the Python tutorial on classes some more to get the finer details down.
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)My tricky solution is:
Maven -> Update Project
again. Issue is resolved.
If you have Tomcat Server Running in Eclipse, you need to refresh project before restart Tomcat Server.
If you are using Angular2+ following code will help
You can use following syntax to get attribute value from html element
//to retrieve html element
const element = fixture.debugElement.nativeElement.querySelector('name of element'); // example a, h1, p
//get attribute value from that element
const attributeValue = element.attributeName // like textContent/href
Just use percentage widths and fixed table layout:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
with
table { table-layout: fixed; }
td { width: 33%; }
Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.
Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.
Facebook uses a very clever technique I described in context of my scrollbar plugin jsFancyScroll:
The scrolled content is actually scrolled natively by the browser scrolling mechanisms while the native scrollbar is hidden by using overflow definitions and the custom scrollbar is kept in sync by bi-directional event listening.
Feel free to use my plugin for your project: :)
https://github.com/leoselig/jsFancyScroll/
I highly recommend it over plugins such as TinyScrollbar that come with terrible performance issues!
declare @nReturn int = 0 EXEC @nReturn = Stored Procedures
HTML 5 does support iframes. There were a few interesting attributes added like "sandbox" and "srcdoc".
http://www.w3schools.com/html5/tag_iframe.asp
or you can use
<object data="framed.html" type="text/html"><p>This is the fallback code!</p></object>
If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.
Hibernate Optional findTopByClientIdAndStatusOrderByCreateTimeDesc(Integer clientId, Integer status);
"findTop"!! The only one result!
The one with the ORDER BY is going to be the slower one.
select * from table where random() < 0.01;
goes record by record, and decides to randomly filter it or not. This is going to be O(N)
because it only needs to check each record once.
select * from table order by random() limit 1000;
is going to sort the entire table, then pick the first 1000. Aside from any voodoo magic behind the scenes, the order by is O(N * log N)
.
The downside to the random() < 0.01
one is that you'll get a variable number of output records.
Note, there is a better way to shuffling a set of data than sorting by random: The Fisher-Yates Shuffle, which runs in O(N)
. Implementing the shuffle in SQL sounds like quite the challenge, though.
Taking into account that you want to resize to exact size and want to keep as much quality as needed I think you should try this.
Motivation: multiple-steps scaling could give you higher quality picture, however there is no guarantee that it will work better than using high inSampleSize. Actually, I think that you also can use inSampleSize like 5 (not pow of 2) to have direct scaling in one operation. Or just use 4 and then you can just use that image in UI. if you send it to server - than you can do scaling to exact size on server side which allow you to use advanced scaling techniques.
Notes: if the Bitmap loaded in step-3 is at least 4 times larger (so the 4*targetWidth < width) you probably can use several resizing to achieve better quality. at least that works in generic java, in android you don't have the option to specify the interpolation used for scaling http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
This is less for @easwee and more for others that might have the same question:
If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.
With the current, final standard, you would be done with
.container {
display: flex;
}
.container div {
flex: 1;
}
.column_center {
order: 2;
}
That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into
.container {
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.container div {
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
.column_center {
-webkit-box-ordinal-group: 2; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-ordinal-group: 2; /* OLD - Firefox 19- */
-ms-flex-order: 2; /* TWEENER - IE 10 */
-webkit-order: 2; /* NEW - Chrome */
order: 2; /* NEW, Spec - Opera 12.1, Firefox 20+ */
}
Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New
A Simple One-Line Solution:
let query = Object.assign.apply(null, location.search.slice(1).split('&').map(entry => ({ [entry.split('=')[0]]: entry.split('=')[1] })));
Expanded & Explained:
// define variable
let query;
// fetch source query
query = location.search;
// skip past the '?' delimiter
query = query.slice(1);
// split source query by entry delimiter
query = query.split('&');
// replace each query entry with an object containing the query entry
query = query.map((entry) => {
// get query entry key
let key = entry.split('=')[0];
// get query entry value
let value = entry.split('=')[1];
// define query object
let container = {};
// add query entry to object
container[key] = value;
// return query object
return container;
});
// merge all query objects
query = Object.assign.apply(null, query);
I found my solution for my Ubuntu 18 here.
sudo dpkg --add-architecture i386
Then:
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.
CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
DELETE YourTable
FROM YourTable
LEFT OUTER JOIN #temp T ON T.myid=s.id
WHERE s.id IS NULL
END
String now = DateTime.Now.ToString("YYYY-MM-DD HH:MI:SS");//make it datetime
DateTime.Parse(now);
this one gives you
2019-08-17 11:14:49.000
CURL OPERATION BETWEEN SERVER TO SERVER WITHOUT HTML FORM IN PHP USING MULTIPART/FORM-DATA
// files to upload
$filename = "https://example.s3.amazonaws.com/0.jpg";
// URL to upload to (Destination server)
$url = "https://otherserver/image";
AND
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
//CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($filename),
CURLOPT_HTTPHEADER => array(
//"Authorization: Bearer $TOKEN",
"Content-Type: multipart/form-data",
"Content-Length: " . strlen(file_get_contents($filename)),
"API-Key: abcdefghi" //Optional if required
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
//echo "code: ${info['http_code']}";
//print_r($info['request_header']);
var_dump($response);
$err = curl_error($curl);
echo "error";
var_dump($err);
curl_close($curl);
The private key password defined in your app/config is incorrect. First try verifying the the private key password by changing to another one as follows:
keytool -keypasswd -new changeit -keystore cacerts -storepass changeit -alias someapp -keypass password
The above example changes the password from password to changeit. This command will succeed if the private key password was password.
I've had exactly the same problem as you for a while now, and after looking at some of the suggestions above, I finally solved the problem.
It turns out (at least for me anyway), I needed to supply a key (a prop called 'key') to the component I am returning from my renderSeparator method. Adding a key to my renderRow or renderSectionHeader didn't do anything, but adding it to renderSeparator made the warning go away.
Hope that helps.
For the Javadoc tag @see
, you don't need to use @link
; Javadoc will create a link for you. Try
@see com.my.package.Class#method()
I think this is a solved problem (see above), but there's an interesting side case to keep in mind because it might get asked:
If there are exactly 4,294,967,295 (2^32 - 1) 32-bit integers with no repeats, and therefore only one is missing, there is a simple solution.
Start a running total at zero, and for each integer in the file, add that integer with 32-bit overflow (effectively, runningTotal = (runningTotal + nextInteger) % 4294967296). Once complete, add 4294967296/2 to the running total, again with 32-bit overflow. Subtract this from 4294967296, and the result is the missing integer.
The "only one missing integer" problem is solvable with only one run, and only 64 bits of RAM dedicated to the data (32 for the running total, 32 to read in the next integer).
Corollary: The more general specification is extremely simple to match if we aren't concerned with how many bits the integer result must have. We just generate a big enough integer that it cannot be contained in the file we're given. Again, this takes up absolutely minimal RAM. See the pseudocode.
# Grab the file size
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
# Print a '2' for every bit of the file.
for (c=0; c<sz; c++) {
for (b=0; b<4; b++) {
print "2";
}
}
MartinVonMartinsgrün and 4Levels methods confirmed work great on Mac OS X Mountain Lion.
The file I needed to update was ~/.profile.
However, I couldn't leave this question without recommending my favorite application, iTerm 2.
iTerm 2 lets you load global color schemes from a file. Really easy to experiment and try a bunch of color schemes.
Here's a screenshot of the iTerm 2 window and the color preferences.
Once I added the following to my ~/.profile file iTerm 2 was able to override the colors.
export CLICOLOR=1
export LSCOLORS=GxFxCxDxBxegedabagaced
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
Here is a great repository with some nice presets:
iTerm2 Color Schemes on Github by mbadolato
Bonus: Choose "Show/hide iTerm2 with a system-wide hotkey" and bind the key with BetterTouchTool for an instant hide/show the terminal with a mouse gesture.
You could also achieve this with the parse_date_time
or fast_strptime
functions from the lubridate
-package:
> parse_date_time(dates1, "ym")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
> fast_strptime(dates1, "%Y-%m")
[1] "2009-01-01 UTC" "2009-02-01 UTC" "2009-03-01 UTC"
The difference between those two is that parse_date_time
allows for lubridate-style format specification, while fast_strptime
requires the same format specification as strptime
.
For specifying the timezone, you can use the tz
-parameter:
> parse_date_time(dates1, "ym", tz = "CET")
[1] "2009-01-01 CET" "2009-02-01 CET" "2009-03-01 CET"
When you have irregularities in your date-time data, you can use the truncated
-parameter to specify how many irregularities are allowed:
> parse_date_time(dates2, "ymdHMS", truncated = 3)
[1] "2012-06-01 12:23:00 UTC" "2012-06-01 12:00:00 UTC" "2012-06-01 00:00:00 UTC"
Used data:
dates1 <- c("2009-01","2009-02","2009-03")
dates2 <- c("2012-06-01 12:23","2012-06-01 12",'2012-06-01")
The following will return true if the JTextField "name" does not contain text:
name.getText().isEmpty
With FluidXML you can generate and store an XML document very easily.
$doc = fluidxml();
$doc->add('Album', true)
->add('Track', 'Track Title');
$doc->save('album.xml');
Loading a document from a file is equally simple.
$doc = fluidify('album.xml');
$doc->query('//Track')
->attr('id', 123);
Write yourself an extension method
public static class ArrayExtensions {
public static void Fill<T>(this T[] originalArray, T with) {
for(int i = 0; i < originalArray.Length; i++){
originalArray[i] = with;
}
}
}
and use it like
int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);
will fill all the elements with 13
static methods don't use any instance variables of the class they are defined in. A very good explanation of the difference can be found on this page
Where the range is multiple cells:
Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[3,3]);
Where range is one cell:
Excel.Worksheet sheet = workbook.ActiveSheet;
Excel.Range rng = (Excel.Range) sheet.Cells[1, 1];
Adding another entry for the debate about whether batch normalization should be called before or after the non-linear activation:
In addition to the original paper using batch normalization before the activation, Bengio's book Deep Learning, section 8.7.1 gives some reasoning for why applying batch normalization after the activation (or directly before the input to the next layer) may cause some issues:
It is natural to wonder whether we should apply batch normalization to the input X, or to the transformed value XW+b. Io?e and Szegedy (2015) recommend the latter. More speci?cally, XW+b should be replaced by a normalized version of XW. The bias term should be omitted because it becomes redundant with the ß parameter applied by the batch normalization reparameterization. The input to a layer is usually the output of a nonlinear activation function such as the recti?ed linear function in a previous layer. The statistics of the input are thus more non-Gaussian and less amenable to standardization by linear operations.
In other words, if we use a relu activation, all negative values are mapped to zero. This will likely result in a mean value that is already very close to zero, but the distribution of the remaining data will be heavily skewed to the right. Trying to normalize that data to a nice bell-shaped curve probably won't give the best results. For activations outside of the relu family this may not be as big of an issue.
Keep in mind that there are reports of models getting better results when using batch normalization after the activation, while others get best results when the batch normalization is placed before the activation. It is probably best to test your model using both configurations, and if batch normalization after activation gives a significant decrease in validation loss, use that configuration instead.
It has been done there : http://www.jezra.net/projects/pageplayer
This happened to me after a java update, few things to check if you are sure your path has been set before:
if the path doesn't match the latest java install folder, change it (if your in eclipse check the eclipse.ini
too to make sure your using your systems default vm (ie no VM tag) )
go to the java directory, there should be a 'jdk' and a 'jre' in the path, for example:
C:\Program Files (x86)\Java\jdk1.8.0_72\jre
if not you probably installed the JRE only not the JDK that
finally if the lib
folder of the jdk (not jre) doesnt contain tools.jar
then you have a problem with the install
According to the examples base64 encoding is directly supported, although I've not tested it myself. Take your base64 string (derived from a file or loaded with any other method, POST/GET, websockets etc), turn it to a binary with atob, and then parse this to getDocument on the PDFJS API likePDFJS.getDocument({data: base64PdfData});
Codetoffel answer does work just fine for me though.
You use a self join when a table references data in itself.
E.g., an Employee
table may have a SupervisorID
column that points to the employee that is the boss of the current employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID
Python really tries hard to intelligently set sys.path
. How it is
set can get really complicated. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the initial values of sys.path
,
sys.executable
, sys.exec_prefix
, and sys.prefix
on a normal
python installation.
First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for sys.executable
, no ifs,
ands, or buts.
Next, it determines the initial values for sys.exec_prefix
and
sys.prefix
.
If there is a file called pyvenv.cfg
in the same directory as
sys.executable
or one directory up, python looks at it. Different
OSes do different things with this file.
One of the values in this config file that python looks for is
the configuration option home = <DIRECTORY>
. Python will use this directory instead of the directory containing sys.executable
when it dynamically sets the initial value of sys.prefix
later. If the applocal = true
setting appears in the
pyvenv.cfg
file on Windows, but not the home = <DIRECTORY>
setting,
then sys.prefix
will be set to the directory containing sys.executable
.
Next, the PYTHONHOME
environment variable is examined. On Linux and Mac,
sys.prefix
and sys.exec_prefix
are set to the PYTHONHOME
environment variable, if
it exists, superseding any home = <DIRECTORY>
setting in pyvenv.cfg
. On Windows,
sys.prefix
and sys.exec_prefix
is set to the PYTHONHOME
environment variable,
if it exists, unless a home = <DIRECTORY>
setting is present in pyvenv.cfg
,
which is used instead.
Otherwise, these sys.prefix
and sys.exec_prefix
are found by walking backwards
from the location of sys.executable
, or the home
directory given by pyvenv.cfg
if any.
If the file lib/python<version>/dyn-load
is found in that directory
or any of its parent directories, that directory is set to be to be
sys.exec_prefix
on Linux or Mac. If the file
lib/python<version>/os.py
is is found in the directory or any of its
subdirectories, that directory is set to be sys.prefix
on Linux,
Mac, and Windows, with sys.exec_prefix
set to the same value as
sys.prefix
on Windows. This entire step is skipped on Windows if
applocal = true
is set. Either the directory of sys.executable
is
used or, if home
is set in pyvenv.cfg
, that is used instead for
the initial value of sys.prefix
.
If it can't find these "landmark" files or sys.prefix
hasn't been
found yet, then python sets sys.prefix
to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of sys.prefix
and sys.exec_prefix
. Windows waits
until sys.path
is fully figured out to set a fallback value for
sys.prefix
.
Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in sys.path
.
sys.path
.
On Windows, this is always the empty string, which tells python to
use the full path where the script is located instead.sys.path
, unless you're
on Windows and applocal
is set to true in pyvenv.cfg
.<prefix>/lib/python35.zip
on Linux/Mac and
os.path.join(os.dirname(sys.executable), "python.zip")
on Windows, is added to sys.path
.applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;sys.prefix
.sys.exec_prefix
is added. On Windows, the directory
which was used (or would have been used) to search dynamically for sys.prefix
is
added.At this stage on Windows, if no prefix was found, then python will try to
determine it by searching all the directories in sys.path
for the landmark files,
as it tried to do with the directory of sys.executable
previously, until it finds something.
If it doesn't, sys.prefix
is left blank.
Finally, after all this, Python loads the site
module, which adds stuff yet further to sys.path
:
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses
sys.prefix
andsys.exec_prefix
; empty heads are skipped. For the tail part, it uses the empty string and thenlib/site-packages
(on Windows) orlib/pythonX.Y/site-packages
and thenlib/site-python
(on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
I've had multenum for "Multi-column enumerated lists" recommended to me, but I've never actually used it myself, yet.
Edit: The syntax doesn't exactly look like you could easily copy+paste lists into the LaTeX code. So, it may not be the best solution for your use case!
Yes this post is 8 years old, but incase someone comes on here also looking for an answer: you can now just use semicolons. However, you cannot use if/elif/else staments, for/while loops, and you can't define functions. The main use of this would be when using imported modules where you don't have to define any functions or use any if/elif/else/for/while statements/loops.
Here's an example that takes the artist of a song, the song name, and searches genius for the lyrics:
import bs4, requests; song = input('Input artist then song name\n'); print(bs4.BeautifulSoup(requests.get(f'https://genius.com/{song.replace(" ", "-")}-lyrics').text,'html.parser').select('.lyrics')[0].text.strip())
You can use reflection to find all the get
methods in your DAO objects and call the equivalent set
method in the DTO. This will only work if all such methods exist. It should be easy to find example code for this.
You can use an attribute like this: data-backdrop="static"
or with javascript:
$('#myModal').modal({
backdrop: 'static',
keyboard: false // to prevent closing with Esc button (if you want this too)
})
See this answer too: Disallow twitter bootstrap modal window from closing
<input type="button" value="submit" style="height: 100px; width: 100px; left: 250; top: 250;">
Use this with your requirements.
urls.py:
#...
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),
views.py:
from django.shortcuts import redirect
from .models import Element
def element_info(request):
# ...
element = Element.object.get(pk=1)
return redirect('element_update', pk=element.id)
def element_update(request, pk)
# ...
Dropping the table was not an option for me, since I'm keeping a running log. If every time I needed to insert I had to drop, the table would be meaningless.
My error was because I had a couple columns in the create table statement that were products of other columns, changing these fixed my problem. eg
create table foo (
field1 as int
,field2 as int
,field12 as field1 + field2 )
create table copyOfFoo (
field1 as int
,field2 as int
,field12 as field1 + field2) --this is the problem, should just be 'as int'
insert into copyOfFoo
SELECT * FROM foo
Start by selecting the sheets you want to combine:
ThisWorkbook.Sheets(Array("Sheet1", "Sheet2")).Select
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
"C:\tempo.pdf", Quality:= xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=True
With pure Javascript, you'd have to cycle through each option, and check the value of it individually.
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
(op[i].value.toLowerCase() == "stackoverflow")
? op[i].disabled = true
: op[i].disabled = false ;
}
Without enabling non-targeted elements:
// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
// lowercase comparison for case-insensitivity
if (op[i].value.toLowerCase() == "stackoverflow") {
op[i].disabled = true;
}
}
With jQuery you can do this with a single line:
$("option[value='stackoverflow']")
.attr("disabled", "disabled")
.siblings().removeAttr("disabled");
Without enabling non-targeted elements:
$("option[value='stackoverflow']").attr("disabled", "disabled");
? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
}
});
Without enabling non-targeted elements:
$("option").each(function(){
if ($(this).val().toLowerCase() == "stackoverflow") {
$(this).attr("disabled", "disabled");
}
});
Run PHP file from command Promp.
Please set Environment Variable as per below mention steps.
Now open Command prompt where your source file are available and run command "php test.php"
The accepted answer use ng-init
, but document says to avoid ng-init if possible.
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
You also can use ng-repeat
instead of ng-options
for your options. With ng-repeat
, you can use ng-selected
with ng-repeat
special properties. i.e. $index, $odd, $even to make this work without any coding.
$first
is one of the ng-repeat special properties.
<select ng-model="foo">
<option ng-selected="$first" ng-repeat="(id,value) in myOptions" value="{{id}}">
{{value}}
</option>
</select>
---------------------- EDIT ----------------
Although this works, I would prefer @mik-t's answer when you know what value to select, https://stackoverflow.com/a/29564802/454252, which uses track-by
and ng-options
without using ng-init
or ng-repeat
.
This answer should only be used when you must select the first item without knowing what value to choose. e.g., I am using this for auto completion which requires to choose the FIRST item all the time.
for java
driver.findelement(By.id('foo').clear();
or
webElement.clear();
If this element is a text entry element, this will clear the value.
Generally you can do
select * from your_table
order by case when name = 'core' then 1 else 2 end,
priority
Especially in MySQL you can also do
select * from your_table
order by name <> 'core',
priority
Since the result of a comparision in MySQL is either 0
or 1
and you can sort by that result.