Most likely it's because your system shutdown unexpectedly
Try
postgres -D /usr/local/var/postgres
You might see
FATAL: lock file "postmaster.pid" already exists HINT: Is another postmaster (PID 449) running in data directory "/usr/local/var/postgres"?
Then try
kill -9 PID
example
kill -9 419
And it should start postgres normally
In Centos 7
Error : publickey,gssapi-keyex,gssapi-with-mic
Ans : Root access to vi /etc/ssh/sshd_config and change the PasswordAuthentication ( no ) to yes.
2 . Restart the sshd services
root> systemctl restart sshd.service
As I wrote in the edits of the op, to edit existing excel documents you must use the xlutils
module (Thanks Oliver)
Here is the proper way to do it:
#xlrd, xlutils and xlwt modules need to be installed.
#Can be done via pip install <module>
from xlrd import open_workbook
from xlutils.copy import copy
rb = open_workbook("names.xls")
wb = copy(rb)
s = wb.get_sheet(0)
s.write(0,0,'A1')
wb.save('names.xls')
This replaces the contents of the cell located at a1 in the first sheet of "names.xls" with the text "a1", and then saves the document.
Create a Pivot Table. It has these features and many more.
If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.
Download this JAR and add it to your libraries: http://java.net/projects/javamail/downloads/download/javax.mail.jar
Only an addition to the above responses: A possibility in such cases is that you are calling an object, that for some reason is not available to your query. For example you may subset by row names or column names, and you will receive this error message when your requested row or column is not part of the data matrix or data frame anymore. Solution: As a short version of the responses above: you need to find the last working row name or column name, and the next called object should be the one that could not be found. If you run parallel codes like "foreach", then you need to convert your code to a for loop to be able to troubleshoot it.
I had the same problem, but in my case was originated by other factor. I write this to help other people with the same problem. I have a solutions with multiple projects. two of them work with the System.Web.Mvc, Normally our reference was pointing to external packages where we controlled the used version. For some reason one of the project reference goes to GAC and point to the GAC dll (version 4.0.0.1) and the program got the error. To correct it:
Simple check if the references to System.Web.Mvc point to the same dll in the same directory path.
I hope that help.
They serve the actual image inside CSS so there will be less HTTP requests per page.
Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.
The Exception means that the socket was closed unexpectedly from the other side. Since you are calling a web service, this should not happen - most likely you're sending a request that triggers a bug in the web service.
Try logging the entire request in those cases, and see if you notice anything unusual. Otherwise, get in contact with the web service provider and send them your logged problematical request.
For Perl, there's WWW::Mechanize.
tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].
Here is an in-place quicksort in Swift Beta:
func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}
And the same in C:
void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}
Both work:
var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]
quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))
// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]
Both are called in the same program as written.
var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}
let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();
let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();
This converts the absolute times to seconds:
static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;
mach_timebase_info_data_t timebase_info;
uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}
double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}
Here is a summary of the compiler's optimazation levels:
[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.
Time in seconds with [-Onone] for n=10_000:
Swift: 0.895296452
C: 0.001223848
Here is Swift's builtin sort() for n=10_000:
Swift_builtin: 0.77865783
Here is [-O] for n=10_000:
Swift: 0.045478346
C: 0.000784666
Swift_builtin: 0.032513488
As you can see, Swift's performance improved by a factor of 20.
As per mweathers' answer, setting [-Ofast] makes the real difference, resulting in these times for n=10_000:
Swift: 0.000706745
C: 0.000742374
Swift_builtin: 0.000603576
And for n=1_000_000:
Swift: 0.107111846
C: 0.114957179
Swift_sort: 0.092688548
For comparison, this is with [-Onone] for n=1_000_000:
Swift: 142.659763258
C: 0.162065333
Swift_sort: 114.095478272
So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.
It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:
A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.
They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance and overflow checks / precise arithmetic then choose another language for now.
BETA 3 UPDATE:
n=10_000 with [-O]:
Swift: 0.019697268
C: 0.000718064
Swift_sort: 0.002094721
Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.
FINAL UPDATE:
[-Onone]:
Swift: 0.678056695
C: 0.000973914
[-O]:
Swift: 0.001158492
C: 0.001192406
[-Ounchecked]:
Swift: 0.000827764
C: 0.001078914
To fix this error I upgraded my MySQL database to utf8mb4 which supports the full Unicode character set by following this detailed tutorial. I suggest going through it carefully, because there are quite a few gotchas (e.g. the index keys can become too large due to the new encodings after which you have to modify field types).
Scenario:
1) client-service-1.0-SNAPSHOT.jar
has dependency read-classpath-resource-1.0-SNAPSHOT.jar
2) we want to read content of class path resources (sample.txt
) of read-classpath-resource-1.0-SNAPSHOT.jar
through client-service-1.0-SNAPSHOT.jar
.
3) read-classpath-resource-1.0-SNAPSHOT.jar
has src/main/resources/sample.txt
Here is working sample code I prepared, after 2-3days wasting my development time, I found the complete end-to-end solution, hope this helps to save your time
1.pom.xml
of read-classpath-resource-1.0-SNAPSHOT.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
<name>classpath-test</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<org.springframework.version>4.3.3.RELEASE</org.springframework.version>
<mvn.release.plugin>2.5.1</mvn.release.plugin>
<output.path>${project.artifactId}</output.path>
<io.dropwizard.version>1.0.3</io.dropwizard.version>
<commons-io.verion>2.4</commons-io.verion>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.verion}</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<version>${mvn.release.plugin}</version>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>demo.read.classpath.resources.ClassPathResourceReadTest</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
2.ClassPathResourceReadTest.java
class in read-classpath-resource-1.0-SNAPSHOT.jar
that loads the class path resources file content.
package demo.read.classpath.resources;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public final class ClassPathResourceReadTest {
public ClassPathResourceReadTest() throws IOException {
InputStream inputStream = getClass().getResourceAsStream("/sample.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
List<Object> list = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
for (Object s1: list) {
System.out.println("@@@ " +s1);
}
System.out.println("getClass().getResourceAsStream('/sample.txt') lines: "+list.size());
}
}
3.pom.xml
of client-service-1.0-SNAPSHOT.jar
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>client-service</groupId>
<artifactId>client-service</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>jar-classpath-resource</groupId>
<artifactId>read-classpath-resource</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>2.5</version>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<useUniqueVersions>false</useUniqueVersions>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</manifest>
<manifestEntries>
<Implementation-Artifact-Id>${project.artifactId}</Implementation-Artifact-Id>
<Implementation-Source-SHA>${buildNumber}</Implementation-Source-SHA>
<Class-Path>sample.txt</Class-Path>
</manifestEntries>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.2</version>
<configuration>
<createDependencyReducedPom>false</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>com.crazy.issue.client.AccessClassPathResource</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
4.AccessClassPathResource.java
instantiate ClassPathResourceReadTest.java
class where, it is going to load sample.txt
and prints its content also.
package com.crazy.issue.client;
import demo.read.classpath.resources.ClassPathResourceReadTest;
import java.io.IOException;
public class AccessClassPathResource {
public static void main(String[] args) throws IOException {
ClassPathResourceReadTest test = new ClassPathResourceReadTest();
}
}
5.Run Executable jar as follows:
[ravibeli@localhost lib]$ java -jar client-service-1.0-SNAPSHOT.jar
****************************************
I am in resources directory of read-classpath-resource-1.0-SNAPSHOT.jar
****************************************
3) getClass().getResourceAsStream('/sample.txt'): 3
I don't think that you can get it much simpler than the documentation, however I'll try:
You can think Iterator as a helper pseudo-method (or pseudo-attribute) that gives (or holds) the next (or first) item in the iterable. (In practice it is just an object that defines the method next()
)
Iteration is probably best explained by the Merriam-Webster definition of the word :
b : the repetition of a sequence of computer instructions a specified number of times or until a condition is met — compare recursion
if (true)
{
return View();
}
else
{
return View("another view name");
}
you can easily find the current CodeIgniter version by
echo CI_VERSION
or you can navigate to System->core->codeigniter.php file and you can see the constant
/**
* CodeIgniter Version
*
* @var string
*
*/
const CI_VERSION = '3.1.6';
I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.
int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
for(int i=0; i<=names.size()-1; ++i) {
if(names[i]==req_name){
cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
return 0;
}
else if(names[i]!=req_name && i==names.size()-1) {
cout<<"That name is not an element in this vector"<<'\n';
} else {
continue;
}
}
You can use numpy.loadtext(filename)
. For example if this is your database .csv
:
ID | Name | Address | City | State | Zip | Phone | OPEID | IPEDS |
10 | Adam | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Carl | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Adolf | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
10 | Den | 130 W.. | Mo.. | AL... | 3.. | 334.. | 01023 | 10063 |
And you want the Name
column:
import numpy as np
b=np.loadtxt(r'filepath\name.csv',dtype=str,delimiter='|',skiprows=1,usecols=(1,))
>>> b
array([' Adam ', ' Carl ', ' Adolf ', ' Den '],
dtype='|S7')
More easily you can use genfromtext
:
b = np.genfromtxt(r'filepath\name.csv', delimiter='|', names=True,dtype=None)
>>> b['Name']
array([' Adam ', ' Carl ', ' Adolf ', ' Den '],
dtype='|S7')
You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
FlatMap behaves very much like map, the difference is that the function it applies returns an observable itself, so it's perfectly suited to map over asynchronous operations.
In the practical sense, the function Map applies just makes a transformation over the chained response (not returning an Observable); while the function FlatMap applies returns an Observable<T>
, that is why FlatMap is recommended if you plan to make an asynchronous call inside the method.
Summary:
A clear example can be seen here: http://blog.couchbase.com/why-couchbase-chose-rxjava-new-java-sdk .
Couchbase Java 2.X Client uses Rx to provide asynchronous calls in a convenient way. Since it uses Rx, it has the methods map and FlatMap, the explanation in their documentation might be helpful to understand the general concept.
To handle errors, override onError on your susbcriber.
Subscriber<String> mySubscriber = new Subscriber<String>() {
@Override
public void onNext(String s) { System.out.println(s); }
@Override
public void onCompleted() { }
@Override
public void onError(Throwable e) { }
};
It might help to look at this document: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/
A good source about how to manage errors with RX can be found at: https://gist.github.com/daschl/db9fcc9d2b932115b679
it is solved in react-router-dom 4.4.0 see: Route's proptypes fail
now it is beta, or just wait for final release.
npm install [email protected] --save
I know this is old as dirt but it ranked pretty high in google.
The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks
In the example given
num = 0
While num < 10
If status = "Fail" Then
num = 10
End If
num = num + 1
Wend
After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.
Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:
num = 0
While num < 10
If folder = "System32" Then
num = 10
End If
RecursiveDeleteFunction folder
num = num + 1
Wend
Using Do While
or Do Until
allows you to stop execution of the loop using Exit Do
instead of using trickery with your loop condition to maintain the While ... Wend
syntax. I would recommend using that instead.
I was getting e.data.indexOf is not a function
error, after debugging it, I found that it was actually a TypeError
, which meant, indexOf()
being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf()
method to make it work
e.data.toString().indexOf('<stringToBeMatchedToPosition>')
Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.
Its easy go to File - Data Modeler - Import - Data Dictionary - DB connection - OK
CORS support in Tomcat is provided via a filter. You need to add this filter to your web.xml
file and configure it to match your requirements. Full details on the configuration options available can be found in the Tomcat Documentation.
If it's an input element you can write something like....
<input type="radio" [checked]="condition">
The value of condition must be true or false.
Also for style attributes...
<h4 [style.color]="'red'">Some text</h4>
You can use:
PyXML:
from xml.dom.ext.reader import Sax2
from xml import xpath
doc = Sax2.FromXmlFile('foo.xml').documentElement
for url in xpath.Evaluate('//@Url', doc):
print url.value
libxml2:
import libxml2
doc = libxml2.parseFile('foo.xml')
for url in doc.xpathEval('//@Url'):
print url.content
Yahoo is the simplest option to get preliminary free data. The link described in eckesicle's answer could be easily used in a python code, but you first need all the tickers. I'd use the NYSE for this example, but this can be used for different exchanges as well.
I used this wiki page to download all company tickers with the following script (I'm not a very talented Pythonist, sorry if this code isn't very efficient):
import string
import urllib2
from bs4 import BeautifulSoup
global f
def download_page(url):
aurl = urllib2.urlopen(url)
soup = BeautifulSoup(aurl.read())
print url
for row in soup('table')[1]('tr'):
tds = row('td')
if (len(tds) > 0):
f.write(tds[1].string + '\n')
f = open('stock_names.txt', 'w')
url_part1 = 'http://en.wikipedia.org/wiki/Companies_listed_on_the_New_York_Stock_Exchange_'
url = url_part1 + '(0-9)'
download_page(url)
for letter in string.uppercase[:26]:
url_part2 = letter
url = url_part1 + '(' + letter + ')'
download_page(url)
f.close()
For downloading each ticker I used another quite similar script:
import string
import urllib2
from bs4 import BeautifulSoup
global f
url_part1 = 'http://ichart.finance.yahoo.com/table.csv?s='
url_part2 = '&d=0&e=28&f=2010&g=d&a=3&b=12&c=1996&ignore=.csv'
print "Starting"
f = open('stock_names.txt', 'r')
file_content = f.readlines()
count = 1;
print "About %d tickers will be downloaded" % len(file_content)
for ticker in file_content:
ticker = ticker.strip()
url = url_part1 + ticker + url_part2
try:
# This will cause exception on a 404
response = urllib2.urlopen(url)
print "Downloading ticker %s (%d out of %d)" % (ticker, count, len(file_content))
count = count + 1
history_file = open('C:\\Users\\Nitay\\Desktop\\Historical Data\\' + ticker + '.csv', 'w')
history_file.write(response.read())
history_file.close()
except Exception, e:
pass
f.close()
Notice that the major downside to this method is that different data is available for different companies - Companies that don't have data existing in the requested dates (newly listed) will get you a 404 page.
Also keep in mind that this method is only good for preliminary data - If you really want to test your algorithm you should pay a bit and use a trusted data supplier like CSIData or others
I can't seem to make that work without hacks either, so what I did was just use the drop-down menu in place of a select box and send the info through a hidden field, like so (using your code):
Jquery:
$('.dropdown-menu li').click(function(e){
e.preventDefault();
var selected = $(this).text();
$('.category').val(selected);
});
HTML:
<div class="container">
<div class="col-sm-7 pull-right well">
<form class="form-inline" action="#" method="get">
<div class="input-group col-sm-8">
<input class="form-control" type="text" value="" placeholder="Search" name="q">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Select <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
<input type="hidden" name="category" class="category">
</div><!-- /btn-group -->
</div>
<button class="btn btn-primary col-sm-3 pull-right" type="submit">Search</button>
</form>
</div>
</div>
Not sure if that will work for what you want, but it is an option for you.
iif has always been available in VB, even in VB6.
Dim foo as String = iif(bar = buz, cat, dog)
It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.
SaaS: Software as a Service Cloud application services or “Software as a Service” (SaaS) are probably the most popular form of cloud computing and are easy to use. SaaS uses the Web to deliver applications that are managed by a third-party vendor and whose interface is accessed on the clients’ side. Most SaaS applications can be run directly from a Web browser, without any downloads or installations required. SaaS eliminates the need to install and run applications on individual computers. With SaaS, it’s easy for enterprises to streamline their maintenance and support, because everything can be managed by vendors: applications, runtime, data, middleware, O/S, virtualization, servers, storage, and networking. Gmail is one famous example of an SaaS mail provider.
PaaS: Platform as a Service The most complex of the three, cloud platform services or “Platform as a Service” (PaaS) deliver computational resources through a platform. What developers gain with PaaS is a framework they can build upon to develop or customize applications. PaaS makes the development, testing, and deployment of applications quick, simple, and cost-effective, eliminating the need to buy the underlying layers of hardware and software. One comparison between SaaS vs. PaaS has to do with what aspects must be managed by users, rather than providers: With PaaS, vendors still manage runtime, middleware, O/S, virtualization, servers, storage, and networking, but users manage applications and data.
IaaS: Infrastructure as a Service Cloud infrastructure services, known as “Infrastructure as a Service” (IaaS), deliver computer infrastructure (such as a platform virtualization environment), storage, and networking. Instead of having to purchase software, servers, or network equipment, users can buy these as a fully outsourced service that is usually billed according to the amount of resources consumed. Basically, in exchange for a rental fee, a third party allows you to install a virtual server on their IT infrastructure. Compared to SaaS and PaaS, IaaS users are responsible for managing more: applications, data, runtime, middleware, and O/S. Vendors still manage virtualization, servers, hard drives, storage, and networking. What users gain with IaaS is infrastructure on top of which they can install any required platforms. Users are responsible for updating these if new versions are released.
I think who the best mix for html & Css for quick and clean mod is :
<table class="table text-center">
<thead>
<tr>
<th class="text-center">Uno</th>
<th class="text-center">Due</th>
<th class="text-center">Tre</th>
<th class="text-center">Quattro</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
close the <table>
init tag then copy where you want :)
I hope it can be useful
Have a good day
w stackoverflow
p.s. Bootstrap v3.2.0
Basically you use props to send information to and from Child and Parent.
Adding to all the wonderful answers, let me give a simple example that explains passing values from child to parent component in React
App.js
class App extends React.Component {
constructor(){
super();
this.handleFilterUpdate = this.handleFilterUpdate.bind(this);
this.state={name:'igi'}
}
handleFilterUpdate(filterValue) {
this.setState({
name: filterValue
});
}
render() {
return (
<div>
<Header change={this.handleFilterUpdate} name={this.state.name} />
<p>{this.state.name}</p>
</div>
);
}
}
Header.js
class Header extends React.Component {
constructor(){
super();
this.state={
names: 'jessy'
}
}
Change(event) {
// this.props.change(this.state.names);
this.props.change('jessy');
}
render() {
return (
<button onClick={this.Change.bind(this)}>click</button>
);
}
}
Main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
ReactDOM.render(<App />, document.getElementById('app'));
Thats it , now you can pass values from your client to the server.
Take a look at the Change function in the Header.js
Change(event) {
// this.props.change(this.state.names);
this.props.change('jessy');
}
This is how you push values into the props from client to the server
There is a secret pilot program which WhatsApp is working on with selected businesses
News coverage:
https://yourstory.com/2017/09/app-fridays-whatsapp-for-business-bookmyshow/
https://yourstory.com/2017/09/bookmyshows-product-team-decrypts-how-whatsapp-for-business-works/
http://gadgets.ndtv.com/apps/news/whatsapp-business-bookmyshow-pilot-1750740
For some of my technical experiments, I was trying to figure out how beneficial and feasible it is to implement bots for different chat platforms in terms of market share and so possibilities of adaptation. Especially when you have bankruptly failed twice, it's important to validate ideas and fail more faster.
Popular chat platforms like Messenger, Slack, Skype etc. have happily (in the sense officially) provided APIs for bots to interact with, but WhatsApp has not yet provided any API.
However, since many years, a lot of activities has happened around this - struggle towards automated interaction with WhatsApp platform:
Bots App Bots App is interesting because it shows that something is really tried and tested.
Yowsup A project still actively developed to interact with WhatsApp platform.
Yallagenie Yallagenie claim that there is a demo bot which can be interacted with at +971 56 112 6652
Hubtype Hubtype is working towards having a bot platform for WhatsApp for business.
Fred Fred's task was to automate WhatsApp conversations, however since it was not officially supported by WhatsApp - it was shut down.
Oye Gennie A bot blocked by WhatsApp.
App/Website to WhatsApp We can use custom URL schemes and Android intent system to interact with WhatsApp but still NOT WhatsApp API.
Chat API daemon Probably created by inspecting the API calls in WhatsApp web version. NOT affiliated with WhatsApp.
WhatsBot Deactivated WhatsApp bot. Created during a hackathon.
No API claim WhatsApp co-founder clearly stated this in a conference that they did not had any plans for APIs for WhatsApp.
Bot Ware They probably are expecting WhatsApp to release their APIs for chat bot platforms.
Vixi They seems to be talking about how some platform which probably would work for WhatsApp. There is no clarity as such.
Unofficial API This API can shut off any time.
And the number goes on...
You can check the socket.connected
property:
var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
console.log('check 2', socket.connected);
});
It's updated dynamically, if the connection is lost it'll be set to false
until the client picks up the connection again. So easy to check for with setInterval
or something like that.
Another solution would be to catch disconnect
events and track the status yourself.
In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.
Example: http://jsfiddle.net/jaredwilli/qFuDr/
<canvas id="canvas"></canvas>
(function() {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d');
// resize the canvas to fill browser window dynamically
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
/**
* Your drawings need to be inside this function otherwise they will be reset when
* you resize the browser window and the canvas goes will be cleared.
*/
drawStuff();
}
resizeCanvas();
function drawStuff() {
// do your drawing stuff here
}
})();
* { margin:0; padding:0; } /* to remove the top and left whitespace */
html, body { width:100%; height:100%; } /* just to be sure these are full screen*/
canvas { display:block; } /* To remove the scrollbars */
That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.
With ECMAScript 6, you can use variable property names with the object literal syntax, like this:
var keyName = 'myKey';
var obj = {
[keyName]: 1
};
obj.myKey;//1
This syntax is available in the following newer browsers:
Edge 12+ (No IE support), FF34+, Chrome 44+, Opera 31+, Safari 7.1+
(https://kangax.github.io/compat-table/es6/)
You can add support to older browsers by using a transpiler such as babel. It is easy to transpile an entire project if you are using a module bundler such as rollup or webpack.
I was getting an error despite importing the following,
import nltk
nltk.download()
but for google colab this solved my issue.
!python3 -c "import nltk; nltk.download('all')"
Okay I modifed @AndroidMechanics Code, because on devices were facebook is disabled the app crashes!
here is the modifed getFacebookUrl:
public String getFacebookPageURL(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
boolean activated = packageManager.getApplicationInfo("com.facebook.katana", 0).enabled;
if(activated){
if ((versionCode >= 3002850)) {
return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
} else {
return "fb://page/" + FACEBOOK_PAGE_ID;
}
}else{
return FACEBOOK_URL;
}
} catch (PackageManager.NameNotFoundException e) {
return FACEBOOK_URL;
}
}
The only added thing is to look if the app is disabled or not if it is disabled the app will call the webbrowser!
If you're looking for a quick solution to load images over HTTPS then the free reverse proxy service at https://images.weserv.nl/ may interest you. It was exactly what I was looking for.
If you're looking for a paid solution, I have previously used Cloudinary.com which also works well but is too expensive solely for this task, in my opinion.
Just restarting the server with command npm start
did the trick. Thanks all for the suggestions.
>>> "{:.1f}".format(45.34531)
'45.3'
Or use the builtin round:
>>> round(45.34531, 1)
45.299999999999997
This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.
- (UIImage *) scaleProportionalToSize: (CGSize)size
{
float widthRatio = size.width/self.size.width;
float heightRatio = size.height/self.size.height;
if(widthRatio > heightRatio)
{
size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
} else {
size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
}
return [self scaleToSize:size];
}
https://docs.oracle.com/javase/8/docs/platform/serialization/spec/serialTOC.html
Default serialization is somewhat verbose, and assumes the widest possible usage scenario of the serialized object, and accordingly the default format (Serializable) annotates the resultant stream with information about the class of the serialized object.
Externalization give the producer of the object stream complete control over the precise class meta-data (if any) beyond the minimal required identification of the class (e.g. its name). This is clearly desirable in certain situations, such as closed environments, where producer of the object stream and its consumer (which reifies the object from the stream) are matched, and additional metadata about the class serves no purpose and degrades performance.
Additionally (as Uri point out) externalization also provides for complete control over the encoding of the data in the stream corresponding to Java types. For (a contrived) example, you may wish to record boolean true as 'Y' and false as 'N'. Externalization allows you to do that.
If you want to just accept defaults you can use:
\n | ./shell_being_run
If you need to allow html input for action-method parameter (opposed to "model property") there's no built-in way to do that but you can easily achieve this using a custom model binder:
public ActionResult AddBlogPost(int userId,
[ModelBinder(typeof(AllowHtmlBinder))] string htmlBody)
{
//...
}
The AllowHtmlBinder code:
public class AllowHtmlBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var request = controllerContext.HttpContext.Request;
var name = bindingContext.ModelName;
return request.Unvalidated[name]; //magic happens here
}
}
Find the complete source code and the explanation in my blog post: https://www.jitbit.com/alexblog/273-aspnet-mvc-allowing-html-for-particular-action-parameters/
I found a way to solve this problem:
If this does not work,
If that did not work and "World Wide Web Publishing Service" was not available,
In your Controller, you should be able to access a dictionary (hash) called params
. So, if you know what the names of each query parameter is, then just do params[:param1]
to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.
Some simple examples here.
This link has the break down
http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property
assign implies __unsafe_unretained ownership.
copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.
retain implies __strong ownership.
strong implies __strong ownership.
unsafe_unretained implies __unsafe_unretained ownership.
weak implies __weak ownership.
private boolean isValidEmailID(String email) {
String PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern = Pattern.compile(PATTERN);
Matcher matcher = pattern.matcher(email);
return matcher.matches();
}
Got inspired by all the answers above and this is what I have done. I am passing some props like some data, and some components.
import React from "react";
const Parent = ({ children }) => {
const { setCheckoutData } = actions.shop;
const { Input, FieldError } = libraries.theme.components.forms;
const onSubmit = (data) => {
setCheckoutData(data);
};
const childrenWithProps = React.Children.map(
children,
(child) =>
React.cloneElement(child, {
Input: Input,
FieldError: FieldError,
onSubmit: onSubmit,
})
);
return <>{childrenWithProps}</>;
};
Coobird's answer is the correct, complete one. However, I combined his hints with those from another site to create code that works in my app (iOS/Objective-C), which I wanted to share with anyone who comes here looking for such a thing. Please, if you like/up-vote this answer, do the same for the originals; all I did was "stand on the shoulders of giants."
As for sort-order, my technique is a modified painter's algorithm: each object has (a) an altitude of the base (I call "level") and (b) an X/Y for the "base" or "foot" of the image (examples: avatar's base is at his feet; tree's base is at it's roots; airplane's base is center-image, etc.) Then I just sort lowest to highest level, then lowest (highest on-screen) to highest base-Y, then lowest (left-most) to highest base-X. This renders the tiles the way one would expect.
Code to convert screen (point) to tile (cell) and back:
typedef struct ASIntCell { // like CGPoint, but with int-s vice float-s
int x;
int y;
} ASIntCell;
// Cell-math helper here:
// http://gamedevelopment.tutsplus.com/tutorials/creating-isometric-worlds-a-primer-for-game-developers--gamedev-6511
// Although we had to rotate the coordinates because...
// X increases NE (not SE)
// Y increases SE (not SW)
+ (ASIntCell) cellForPoint: (CGPoint) point
{
const float halfHeight = rfcRowHeight / 2.;
ASIntCell cell;
cell.x = ((point.x / rfcColWidth) - ((point.y - halfHeight) / rfcRowHeight));
cell.y = ((point.x / rfcColWidth) + ((point.y + halfHeight) / rfcRowHeight));
return cell;
}
// Cell-math helper here:
// http://stackoverflow.com/questions/892811/drawing-isometric-game-worlds/893063
// X increases NE,
// Y increases SE
+ (CGPoint) centerForCell: (ASIntCell) cell
{
CGPoint result;
result.x = (cell.x * rfcColWidth / 2) + (cell.y * rfcColWidth / 2);
result.y = (cell.y * rfcRowHeight / 2) - (cell.x * rfcRowHeight / 2);
return result;
}
I got the error as, "svn: Commit blocked by pre-commit hook (exit code 1) with output: Failed with exception: Lost connection to MySQL server at 'reading initial communication packet', system error: 104."
I tried 'svn commit' after 'svn cleanup'. And It works fine!.
I prefer to use date-fns library for date manipulating. It is really great modular and consistent tool. You can get start and end of the day this way:
var startOfDay = dateFns.startOfDay;_x000D_
var endOfDay = dateFns.endOfDay;_x000D_
_x000D_
console.log('start of day ==> ', startOfDay(new Date('2015-11-11')));_x000D_
console.log('end of day ==> ', endOfDay(new Date('2015-11-11')));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/1.29.0/date_fns.min.js"></script>
_x000D_
DO it like
$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$yourPHPVAR%'");
Do not forget the %
at the end
Use namespace
using System.Collections.Specialized;
Make instance of DataContext
Class
LinqToSqlDataContext dc = new LinqToSqlDataContext();
Use
OrderedDictionary dict = dc.TableName.ToDictionary(d => d.key, d => d.value);
In order to retrieve the values use namespace
using System.Collections;
ICollection keyCollections = dict.Keys;
ICOllection valueCollections = dict.Values;
String[] myKeys = new String[dict.Count];
String[] myValues = new String[dict.Count];
keyCollections.CopyTo(myKeys,0);
valueCollections.CopyTo(myValues,0);
for(int i=0; i<dict.Count; i++)
{
Console.WriteLine("Key: " + myKeys[i] + "Value: " + myValues[i]);
}
Console.ReadKey();
All this is about cultures. If you have any other culture than "US English" (and also as good manners of development), you should use something like this:
var d = Convert.ToDecimal("1.2345", new CultureInfo("en-US"));
// (or 1,2345 with your local culture, for instance)
(obviously, you should replace the "en-US" with the culture of your number local culture)
the same way, if you want to do ToString()
d.ToString(new CultureInfo("en-US"));
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
int i, parameter = 0;
if (argc >= 2) {
/* there is 1 parameter (or more) in the command line used */
/* argv[0] may point to the program name */
/* argv[1] points to the 1st parameter */
/* argv[argc] is NULL */
parameter = atoi(argv[1]); /* better to use strtol */
if (parameter > 0) {
for (i = 0; i < parameter; i++) printf("%d ", i);
} else {
fprintf(stderr, "Please use a positive integer.\n");
}
}
return 0;
}
More fast way using directly a no-string array but a string:
string[] StringSplit(string StringToSplit, string Delimitator)
{
return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}
StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/
In my case, the API responded with a CORS error. I instead formatted the query parameters into query string. It successfully posted data and also avoided the CORS issue.
var data = {};
const params = new URLSearchParams({
contact: this.ContactPerson,
phoneNumber: this.PhoneNumber,
email: this.Email
}).toString();
const url =
"https://test.com/api/UpdateProfile?" +
params;
axios
.post(url, data, {
headers: {
aaid: this.ID,
token: this.Token
}
})
.then(res => {
this.Info = JSON.parse(res.data);
})
.catch(err => {
console.log(err);
});
The job of the DispatcherServlet is to take an incoming URI and find the right combination of handlers (generally methods on Controller classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.
I might have
/WEB-INF/jsp/pages/Home.jsp
and a method on a class
@RequestMapping(value="/pages/Home.html")
private ModelMap buildHome() {
return somestuff;
}
The Dispatcher servlet is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.
How it accomplishes this varies widely with configuration and Spring version.
There's also no reason the end result has to be web pages. It can do the same thing to locate RMI end points, handle SOAP requests, anything that can come into a servlet.
Besides the window resize functions mentioned it is important to understand that the resize events fire a lot if used without a deboucing the events.
Paul Irish has an excellent function that debounces the resize calls a great deal. Very recommended to use. Works cross-browser. Tested it in IE8 the other day and all was fine.
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
Make sure to check out the demo to see the difference.
Here is the function for completeness.
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
Doing a git remote update will also update the list of branches available from the remote repository.
If you are using TortoiseGit, as of version 1.8.3.0, you can do "Git -> Sync" and there will be a "Remote Update" button in the lower left of the window that appears. Click that. Then you should be able to do "Git -> Switch/Checkout" and have the new remote branch appear in the dropdown of branches you can select.
In Linux I resolve this problem by going to the root command prompt type:
# mysqladmin -u root password 'Secret Phrase Here'
Then go back and login. Works every time!
I don't know if javaw will write to the %errorlevel% variable, but it might.
echo %errorlevel%
after you run it directly to see.
Other than that, you can pipe the output of javaw to a file, then use find
to see what the results were. Without knowing the output of it, I can't really help you with that.
In my case it was the university wifi blocking port 3306. I was able to connect by using a mobile hotspot.
Change to a mobile hotspot or another network, and if it works there, then you know that original network is blocking port 3306. If you get the same error on more than 1 network, then you know it's specific to your machine.
<?php
require_once 'PHPUnit/Framework.php';
class ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testException()
{
$this->expectException(InvalidArgumentException::class);
// or for PHPUnit < 5.2
// $this->setExpectedException(InvalidArgumentException::class);
//...and then add your test code that generates the exception
exampleMethod($anInvalidArgument);
}
}
expectException() PHPUnit documentation
PHPUnit author article provides detailed explanation on testing exceptions best practices.
One line reduce
with ES6 fancy spread syntax is here!
var options = [_x000D_
{ name: 'One', assigned: true }, _x000D_
{ name: 'Two', assigned: false }, _x000D_
{ name: 'Three', assigned: true }, _x000D_
];_x000D_
_x000D_
const filtered = options_x000D_
.reduce((result, {name, assigned}) => [...result, ...assigned ? [name] : []], []);_x000D_
_x000D_
console.log(filtered);
_x000D_
GUI solution:
If you are using RStudio then you can check the package version in the Packages
pane.
You should use 'tag_name' outside of quotes; then its interpreted as a field of the record. Concatenate using '||' with the literal percent signs:
SELECT id FROM TAG_TABLE WHERE 'aaaaaaaa' LIKE '%' || tag_name || '%';
Make a list from items in an iterable
It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.
[expression1(item) for item in iterable]
[expression1(item) if conditional1 for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable]
[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]
The value of item
doesn't need to be used in any of the conditional clauses. A conditional3
can be used as a switch to either add or not add a value to the output list.
For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:
newlist = [s for s in firstlist if s.strip()]
Both of the examples immediately above didn't work for me. Opening a recordset on the table and adding a record does work to add the record, except:
myLong = CLng(rs!AutoNumberField)
returns Null if put between rs.AddNew and rs.Update. If put after rs.Update, it does return something, but it's always wrong, and always the same incorrect value. Looking at the table directly after adding the new record shows an autonumber field value different than the one returned by the above statement.
myLong = DLookup("AutoNumberField","TableName","SomeCriteria")
will work properly, as long as it's done after rs.Update, and there are any other fields which can uniquely identify the record.
The problem with your query is that in CASE
expressions, the THEN
and ELSE
parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.
You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:
WHERE
DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0
OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
)
The strpos()
finds the offset of the underscore, then substr grabs everything from that index plus 1, onwards.
$data = "123_String";
$whatIWant = substr($data, strpos($data, "_") + 1);
echo $whatIWant;
If you also want to check if the underscore character (_
) exists in your string before trying to get it, you can use the following:
if (($pos = strpos($data, "_")) !== FALSE) {
$whatIWant = substr($data, $pos+1);
}
select
{
-webkit-appearance: none;
}
If you need to you can also add an image that contains the arrow as part of the background.
It working 100% in safari..i tried
@media screen and (-webkit-min-device-pixel-ratio:0)
{
::i-block-chrome, Class Name {your styles}
}
ReactJs defines the following synthetic events for mouse events:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
As you can see there is no hover event, because browsers do not define a hover event natively.
You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.
This command works for me. It does its work recursively
find . -name "node_modules" -type d -prune -exec rm -rf '{}' +
. - current folder
"node_modules" - folder name
I wouldn't recommend it. The problem is, it looks like a common error where you try to compare values, but use a single =
instead of ==
or ===
. For example, when you see this:
if (value = someFunction()) {
...
}
you don't know if that's what they meant to do, or if they intended to write this:
if (value == someFunction()) {
...
}
If you really want to do the assignment in place, I would recommend doing an explicit comparison as well:
if ((value = someFunction()) === <whatever truthy value you are expecting>) {
...
}
This is sort of coming at the question from the other end but I thought I'd throw it in as I really had to dig on the internet to find this out.
There is a lot of stuff about how to check roles but not much saying what you are actually checking when you say hasRole("blah")
HasRole checks the granted authorities for the currently authenticated principal
So really when you see hasRole("blah") really means hasAuthority("blah").
In the case I've seen, you do this with a class that Implements UserDetails which defines a method called getAuthorities. In this you'll basically add some new SimpleGrantedAuthority("some name")
to a list based on some logic. The names in this list are the things checked by the hasRole statements.
I guess in this context the UserDetails object is the currently authenticated principal. There's some magic that happens in and around authentication providers and more specifically the authentication-manager that makes this happen.
You need to read from the configuration section manually before your code returns a JsonResult object. Simply read from web.config in single line:
var jsonResult = Json(resultsForAjaxUI);
jsonResult.MaxJsonLength = (ConfigurationManager.GetSection("system.web.extensions/scripting/webServices/jsonSerialization") as System.Web.Configuration.ScriptingJsonSerializationSection).MaxJsonLength;
return jsonResult;
Be sure you defined configuration element in web.config
my 5c: In integration and networking the idempotency is very important. Several examples from real-life: Imagine, we deliver data to the target system. Data delivered by a sequence of messages. 1. What would happen if the sequence is mixed in channel? (As network packages always do :) ). If the target system is idempotent, the result will not be different. If the target system depends of the right order in the sequence, we have to implement resequencer on the target site, which would restore the right order. 2. What would happen if there are the message duplicates? If the channel of target system does not acknowledge timely, the source system (or channel itself) usually sends another copy of the message. As a result we can have duplicate message on the target system side. If the target system is idempotent, it takes care of it and result will not be different. If the target system is not idempotent, we have to implement deduplicator on the target system side of the channel.
You should be able to do this with a pretty standard DAO recordset loop. You can see some examples at the following links:
http://msdn.microsoft.com/en-us/library/bb243789%28v=office.12%29.aspx
http://www.granite.ab.ca/access/email/recordsetloop.htm
My own standard loop looks something like this:
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT * FROM Contacts")
'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
rs.MoveFirst 'Unnecessary in this case, but still a good habit
Do Until rs.EOF = True
'Perform an edit
rs.Edit
rs!VendorYN = True
rs("VendorYN") = True 'The other way to refer to a field
rs.Update
'Save contact name into a variable
sContactName = rs!FirstName & " " & rs!LastName
'Move to the next record. Don't ever forget to do this.
rs.MoveNext
Loop
Else
MsgBox "There are no records in the recordset."
End If
MsgBox "Finished looping through records."
rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
This solution might be a bit complicated, but boost-range
has also some other nice things to offer.
#include <iostream>
#include <vector>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
boost::copy(b, std::back_inserter(a));
for (auto& iter : a) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
Often ones intention is to combine vector a
and b
just iterate over it doing some operation. In this case, there is the ridiculous simple join
function.
#include <iostream>
#include <vector>
#include <boost/range/join.hpp>
#include <boost/range/algorithm/copy.hpp>
int main(int, char**) {
std::vector<int> a = { 1,2,3 };
std::vector<int> b = { 4,5,6 };
std::vector<int> c = { 7,8,9 };
// Just creates an iterator
for (auto& iter : boost::join(a, boost::join(b, c))) {
std::cout << iter << " ";
}
std::cout << "\n";
// Can also be used to create a copy
std::vector<int> d;
boost::copy(boost::join(a, boost::join(b, c)), std::back_inserter(d));
for (auto& iter : d) {
std::cout << iter << " ";
}
return EXIT_SUCCESS;
}
For large vectors this might be an advantage, as there is no copying. It can be also used for copying an generalizes easily to more than one container.
For some reason there is nothing like boost::join(a,b,c)
, which could be reasonable.
I dont know what is the exact reason but I solved the problem running:
app/console cache:clear --env=prod
On a MAC, you need to use nm *.o | c++filt
, as there is no -C
option in nm
.
Try to create a new empty project; then you can copy the public_html to the new project folder and it will appear .
I got this error when I updated node using NVM.
to remove this run;
npm rebuild node-sass
I have solved it by discarding my local amended commit and adding the new changes on top:
# Rewind to commit before conflicting
git reset --soft HEAD~1
# Pull the remote version
git pull
# Add the new commit on top
git add ...
git commit
git push
Use trigger
to fire your own event. When ever you change class add trigger with name
$("#main").on('click', function () {
$("#chld").addClass("bgcolorRed").trigger("cssFontSet");
});
$('#chld').on('cssFontSet', function () {
alert("Red bg set ");
});
$_='~s/blue/red/g';
Uh, what??
Just
s/blue/red/g;
or, if you insist on using a variable (which is not necessary when using $_, but I just want to show the right syntax):
$_ =~ s/blue/red/g;
In 2019, this kind of task became super-easy.
JSON.stringify(Object.fromEntries(formData));
Object.fromEntries
: Supported in Chrome 73+, Firefox 63+, Safari 12.1
But why stop with MessageBox-specific implementation? Use the class below like this:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dg;
using (DialogCenteringService centeringService = new DialogCenteringService(this)) // center message box
{
dg = MessageBox.Show(this, "Are you sure?", "Confirm exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
}
if (dg == DialogResult.No)
{
e.Cancel = true;
}
}
The code that you can use with anything that shows dialog windows, even if they're owned by another thread (our app has multiple UI threads):
(Here is the updated code which takes monitor working areas into account, so that the dialog isn't centered between two monitors or is partly off-screen. With it you'll need enum SetWindowPosFlags
, which is below)
public class DialogCenteringService : IDisposable
{
private readonly IWin32Window owner;
private readonly HookProc hookProc;
private readonly IntPtr hHook = IntPtr.Zero;
public DialogCenteringService(IWin32Window owner)
{
if (owner == null) throw new ArgumentNullException("owner");
this.owner = owner;
hookProc = DialogHookProc;
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, GetCurrentThreadId());
}
private IntPtr DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
{
return CallNextHookEx(hHook, nCode, wParam, lParam);
}
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == (int)CbtHookAction.HCBT_ACTIVATE)
{
try
{
CenterWindow(msg.hwnd);
}
finally
{
UnhookWindowsHookEx(hHook);
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
public void Dispose()
{
UnhookWindowsHookEx(hHook);
}
private void CenterWindow(IntPtr hChildWnd)
{
Rectangle recChild = new Rectangle(0, 0, 0, 0);
bool success = GetWindowRect(hChildWnd, ref recChild);
if (!success)
{
return;
}
int width = recChild.Width - recChild.X;
int height = recChild.Height - recChild.Y;
Rectangle recParent = new Rectangle(0, 0, 0, 0);
success = GetWindowRect(owner.Handle, ref recParent);
if (!success)
{
return;
}
Point ptCenter = new Point(0, 0);
ptCenter.X = recParent.X + ((recParent.Width - recParent.X) / 2);
ptCenter.Y = recParent.Y + ((recParent.Height - recParent.Y) / 2);
Point ptStart = new Point(0, 0);
ptStart.X = (ptCenter.X - (width / 2));
ptStart.Y = (ptCenter.Y - (height / 2));
//MoveWindow(hChildWnd, ptStart.X, ptStart.Y, width, height, false);
Task.Factory.StartNew(() => SetWindowPos(hChildWnd, (IntPtr)0, ptStart.X, ptStart.Y, width, height, SetWindowPosFlags.SWP_ASYNCWINDOWPOS | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOOWNERZORDER | SetWindowPosFlags.SWP_NOZORDER));
}
// some p/invoke
// ReSharper disable InconsistentNaming
public delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
public delegate void TimerProc(IntPtr hWnd, uint uMsg, UIntPtr nIDEvent, uint dwTime);
private const int WH_CALLWNDPROCRET = 12;
// ReSharper disable EnumUnderlyingTypeIsInt
private enum CbtHookAction : int
// ReSharper restore EnumUnderlyingTypeIsInt
{
// ReSharper disable UnusedMember.Local
HCBT_MOVESIZE = 0,
HCBT_MINMAX = 1,
HCBT_QS = 2,
HCBT_CREATEWND = 3,
HCBT_DESTROYWND = 4,
HCBT_ACTIVATE = 5,
HCBT_CLICKSKIPPED = 6,
HCBT_KEYSKIPPED = 7,
HCBT_SYSCOMMAND = 8,
HCBT_SETFOCUS = 9
// ReSharper restore UnusedMember.Local
}
[DllImport("kernel32.dll")]
static extern int GetCurrentThreadId();
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);
[DllImport("user32.dll")]
private static extern int MoveWindow(IntPtr hWnd, int X, int Y, int nWidth, int nHeight, bool bRepaint);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, SetWindowPosFlags uFlags);
[DllImport("User32.dll")]
public static extern UIntPtr SetTimer(IntPtr hWnd, UIntPtr nIDEvent, uint uElapse, TimerProc lpTimerFunc);
[DllImport("User32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
public static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
public static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
public static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
// ReSharper restore InconsistentNaming
}
[Flags]
public enum SetWindowPosFlags : uint
{
// ReSharper disable InconsistentNaming
/// <summary>
/// If the calling thread and the thread that owns the window are attached to different input queues, the system posts the request to the thread that owns the window. This prevents the calling thread from blocking its execution while other threads process the request.
/// </summary>
SWP_ASYNCWINDOWPOS = 0x4000,
/// <summary>
/// Prevents generation of the WM_SYNCPAINT message.
/// </summary>
SWP_DEFERERASE = 0x2000,
/// <summary>
/// Draws a frame (defined in the window's class description) around the window.
/// </summary>
SWP_DRAWFRAME = 0x0020,
/// <summary>
/// Applies new frame styles set using the SetWindowLong function. Sends a WM_NCCALCSIZE message to the window, even if the window's size is not being changed. If this flag is not specified, WM_NCCALCSIZE is sent only when the window's size is being changed.
/// </summary>
SWP_FRAMECHANGED = 0x0020,
/// <summary>
/// Hides the window.
/// </summary>
SWP_HIDEWINDOW = 0x0080,
/// <summary>
/// Does not activate the window. If this flag is not set, the window is activated and moved to the top of either the topmost or non-topmost group (depending on the setting of the hWndInsertAfter parameter).
/// </summary>
SWP_NOACTIVATE = 0x0010,
/// <summary>
/// Discards the entire contents of the client area. If this flag is not specified, the valid contents of the client area are saved and copied back into the client area after the window is sized or repositioned.
/// </summary>
SWP_NOCOPYBITS = 0x0100,
/// <summary>
/// Retains the current position (ignores X and Y parameters).
/// </summary>
SWP_NOMOVE = 0x0002,
/// <summary>
/// Does not change the owner window's position in the Z order.
/// </summary>
SWP_NOOWNERZORDER = 0x0200,
/// <summary>
/// Does not redraw changes. If this flag is set, no repainting of any kind occurs. This applies to the client area, the nonclient area (including the title bar and scroll bars), and any part of the parent window uncovered as a result of the window being moved. When this flag is set, the application must explicitly invalidate or redraw any parts of the window and parent window that need redrawing.
/// </summary>
SWP_NOREDRAW = 0x0008,
/// <summary>
/// Same as the SWP_NOOWNERZORDER flag.
/// </summary>
SWP_NOREPOSITION = 0x0200,
/// <summary>
/// Prevents the window from receiving the WM_WINDOWPOSCHANGING message.
/// </summary>
SWP_NOSENDCHANGING = 0x0400,
/// <summary>
/// Retains the current size (ignores the cx and cy parameters).
/// </summary>
SWP_NOSIZE = 0x0001,
/// <summary>
/// Retains the current Z order (ignores the hWndInsertAfter parameter).
/// </summary>
SWP_NOZORDER = 0x0004,
/// <summary>
/// Displays the window.
/// </summary>
SWP_SHOWWINDOW = 0x0040,
// ReSharper restore InconsistentNaming
}
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that are defined in the List interface. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList-specific methods and use ArrayList-specific members in addition to those whose definitions are inherited from List.
Nevertheless, when you call a method of a List interface in the first example, which was implemented in ArrayList, the method from ArrayList will be called (because the List interface doesn't implement any methods).
That's called polymorphism. You can read up on it.
In MacOS Catalina 10.15.5 the .npmrc
file path can be found at
/Users/<user-name>/.npmrc
Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.
You are ready to go.
Note:
As mentioned by @oligofren, the command npm config ls -l
will npm configurations. You will get the .npmrc file from config parameter userconfig
@Adamski: You can avoid buffer entirely.
Code copied from http://www.exampledepot.com/egs/java.io/File2ByteArray.html (Yes, it is very verbose, but needs half the size of memory as the other solution.)
// Returns the contents of the file in a byte array.
public static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
// You cannot create an array using a long type.
// It needs to be an int type.
// Before converting to an int type, check
// to ensure that file is not larger than Integer.MAX_VALUE.
if (length > Integer.MAX_VALUE) {
// File is too large
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file "+file.getName());
}
// Close the input stream and return bytes
is.close();
return bytes;
}
In the context definition, define only two DbSet contexts per context class.
Java is 'Big-endian' as noted above. That means that the MSB of an int is on the left if you examine memory (on an Intel CPU at least). The sign bit is also in the MSB for all Java integer types.
Reading a 4 byte unsigned integer from a binary file stored by a 'Little-endian' system takes a bit of adaptation in Java. DataInputStream's readInt() expects Big-endian format.
Here's an example that reads a four byte unsigned value (as displayed by HexEdit as 01 00 00 00) into an integer with a value of 1:
// Declare an array of 4 shorts to hold the four unsigned bytes
short[] tempShort = new short[4];
for (int b = 0; b < 4; b++) {
tempShort[b] = (short)dIStream.readUnsignedByte();
}
int curVal = convToInt(tempShort);
// Pass an array of four shorts which convert from LSB first
public int convToInt(short[] sb)
{
int answer = sb[0];
answer += sb[1] << 8;
answer += sb[2] << 16;
answer += sb[3] << 24;
return answer;
}
In order to make it easier I assume that you wish to apply a unique constraint only for column year and the primary key is a column named id.
In order to find duplicate values you should run,
SELECT year, COUNT(id)
FROM YOUR_TABLE
GROUP BY year
HAVING COUNT(id) > 1
ORDER BY COUNT(id);
Using the sql statement above you get a table which contains all the duplicate years in your table. In order to delete all the duplicates except of the the latest duplicate entry you should use the above sql statement.
DELETE
FROM YOUR_TABLE A USING YOUR_TABLE_AGAIN B
WHERE A.year=B.year AND A.id<B.id;
You can do it like this as well,
let copiedData = JSON.parse(JSON.stringify(data));
For completeness, you can also achieve this in functional components:
const [, updateState] = useState();
const forceUpdate = useCallback(() => updateState({}), []);
// ...
forceUpdate();
Or, as a reusable hook:
const useForceUpdate = () => {
const [, updateState] = useState();
return useCallback(() => updateState({}), []);
}
// const forceUpdate = useForceUpdate();
See: https://stackoverflow.com/a/53215514/2692307
Please note that using a force-update mechanism is still bad practice as it goes against the react mentality, so it should still be avoided if possible.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
I personally suggest to use the autoNumeric plugin from http://www.decorplanit.com/plugin/ - it supports all different variations like prefix/suffix handling, currency handling, negative value formatting, min, max etc.
One line answer:
IFS=$'\n'; for line in $(cat file.txt); do echo "$line" ; done
Seeing this error during the use of Guzzle as well. The following header fixed it for me:
'headers' => [
'accept-encoding' => 'gzip, deflate',
],
I issued the request with Postman which gave me a complete response and no error. Then I started adding the headers that Postman sends to the Guzzle request and this was the one that fixed it.
You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)
listener.ora
This file is located in:
%ORACLE_HOME%\network\admin\listener.ora
.Replace localhost
with 0.0.0.0
# ...
LISTENER =
(DESCRIPTION_LIST =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
(ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
)
)
# ...
Windows: WinKey + r
services.msc
Linux (CentOs):
sudo systemctl restart oracle-xe
I know this is a bit old, but in case another beginner is going through this, I'll share some code that covers a bit more of the basic operations, here is another example that also includes the option to cancel the process and also report to the user the status of the process. I'm going to add on top of the code given by Alex Aza in the solution above
public Form1()
{
InitializeComponent();
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted; //Tell the user how the process went
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.WorkerSupportsCancellation = true; //Allow for the process to be cancelled
}
//Start Process
private void button1_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
//Cancel Process
private void button2_Click(object sender, EventArgs e)
{
//Check if background worker is doing anything and send a cancellation if it is
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(1000);
backgroundWorker1.ReportProgress(i);
//Check if there is a request to cancel the process
if (backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
//If the process exits the loop, ensure that progress is set to 100%
//Remember in the loop we set i < 100 so in theory the process will complete at 99%
backgroundWorker1.ReportProgress(100);
}
private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.Text = "Process was cancelled";
}
else if (e.Error != null)
{
lblStatus.Text = "There was an error running the process. The thread aborted";
}
else
{
lblStatus.Text = "Process was completed";
}
}
If you're willing to include the jQuery UI library, in addition to jQuery itself, then you can simply use hide()
, with additional arguments, as follows:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this).hide('slide',{direction:'right'},1000);
});
});
Without using jQuery UI, you could achieve your aim just using animate()
:
$(document).ready(
function(){
$('#slider').click(
function(){
$(this)
.animate(
{
'margin-left':'1000px'
// to move it towards the right and, probably, off-screen.
},1000,
function(){
$(this).slideUp('fast');
// once it's finished moving to the right, just
// removes the the element from the display, you could use
// `remove()` instead, or whatever.
}
);
});
});
If you do choose to use jQuery UI, then I'd recommend linking to the Google-hosted code, at: https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js
You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.
from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random
fig = pyplot.figure()
ax = Axes3D(fig)
sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))
random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)
ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()
The code above generates a figure like:
As said, to follow redirects you can use the flag -L
or --location
:
curl -L http://www.example.com
But, if you want limit the number of redirects, add the parameter --max-redirs
--max-redirs <num>
Set maximum number of redirection-followings allowed. If
-L
,--location
is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.
If you mind to use LINQ Expression;
public static Dictionary<string, object> ConvertFromObjectToDictionary(object arg)
{
return arg.GetType().GetProperties().ToDictionary(property => property.Name, property => property.GetValue(arg));
}
To preserve the branching and merging structure is important to use the --preserve-merges
option when doing the rebase:
git rebase --preserve-merges -i HEAD^^
You are mixing the 2 different CASE
syntaxes inappropriately.
Use this style (Searched)
CASE
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Or this style (Simple)
CASE u.nnmu
WHEN '0' THEN mu.naziv_mesta
WHEN '1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
Not This (Simple but with boolean search predicates)
CASE u.nnmu
WHEN u.nnmu ='0' THEN mu.naziv_mesta
WHEN u.nnmu ='1' THEN m.naziv_mesta
ELSE 'GRESKA'
END as mesto_utovara,
In MySQL this will end up testing whether u.nnmu
is equal to the value of the boolean expression u.nnmu ='0'
itself. Regardless of whether u.nnmu
is 1
or 0
the result of the case expression itself will be 1
For example if nmu = '0'
then (nnmu ='0'
) evaluates as true
(1) and (nnmu ='1'
) evaluates as false
(0). Substituting these into the case expression gives
SELECT CASE '0'
WHEN 1 THEN '0'
WHEN 0 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
if nmu = '1'
then (nnmu ='0'
) evaluates as false
(0) and (nnmu ='1'
) evaluates as true
(1). Substituting these into the case expression gives
SELECT CASE '1'
WHEN 0 THEN '0'
WHEN 1 THEN '1'
ELSE 'GRESKA'
END as mesto_utovara
Since $http.get
returns a 'promise' with the extra convenience methods success
and error
(which just wrap the result of then
) you should be able to use (regardless of your Angular version):
$http.get('/someUrl')
.then(function success(response) {
console.log('succeeded', response); // supposed to have: data, status, headers, config, statusText
}, function error(response) {
console.log('failed', response); // supposed to have: data, status, headers, config, statusText
})
Not strictly an answer to the question, but if you're getting bitten by the "my version of Angular is different than the docs" issue you can always dump all of the arguments
, even if you don't know the appropriate method signature:
$http.get('/someUrl')
.success(function(data, foo, bar) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
})
.error(function(baz, foo, bar, idontknow) {
console.log(arguments); // includes data, status, etc including unlisted ones if present
});
Then, based on whatever you find, you can 'fix' the function arguments to match.
Being a computer nerd and not a maths nerd I'd do:
char buffer[64];
int len = sprintf(buffer, "%d", theNum);
You also might have accidentally added some wrong text in my.ini
file. Make sure no invalid character is added at the beginning of the file.
CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}
, doing the following should succeed:
add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)
Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/
Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters
and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.
PHP provides two types of array.
normal array : This array is dynamic.
SplFixedArray : this is a standard php library which provides the ability to create array of fix size.
php
supports c style date functions. You can add or substract date-periods with English-language style phrases via the strtotime
function. examples...
$Today=date('y:m:d');
// add 3 days to date
$NewDate=Date('y:m:d', strtotime('+3 days'));
// subtract 3 days from date
$NewDate=Date('y:m:d', strtotime('-3 days'));
// PHP returns last sunday's date
$NewDate=Date('y:m:d', strtotime('Last Sunday'));
// One week from last sunday
$NewDate=Date('y:m:d', strtotime('+7 days Last Sunday'));
or
<select id="date_list" class="form-control" style="width:100%;">
<?php
$max_dates = 15;
$countDates = 0;
while ($countDates < $max_dates) {
$NewDate=Date('F d, Y', strtotime("+".$countDates." days"));
echo "<option>" . $NewDate . "</option>";
$countDates += 1;
}
?>
You can also query the INFORMATION_SCHEMA.SCHEMATA view:
SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA
I believe querying the INFORMATION_SCHEMA views is recommended as they protect you from changes to the underlying sys tables. From the SQL Server 2008 R2 Help:
Information schema views provide an internal, system table-independent view of the SQL Server metadata. Information schema views enable applications to work correctly although significant changes have been made to the underlying system tables. The information schema views included in SQL Server comply with the ISO standard definition for the INFORMATION_SCHEMA.
Ironically, this is immediately preceded by this note:
Some changes have been made to the information schema views that break backward compatibility. These changes are described in the topics for the specific views.
A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.JAR file is like winzip file except that Jar files are platform independent.
A WAR file is simply a JAR file but contains only Web related Java files like Servlets, JSP, HTML.
To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.
I had similar issues when migrating to androidx.
If by adding the below two lines to gradle.properties did not solve the issue
android.useAndroidX=true
android.enableJetifier=true
Then try
If you still run into issues with migration then manually try to replace the libraries which are causing the issue.
For example
If you have an issue with android.support.annotation.NonNull
change it to androidx.annotation.NonNull
as indicated in the below class mappings table.
You could use flatMap. It can filter and map in one.
$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])
If you start application on a remote server while logged in by ssh then another way would be to start ssh with -x
parameter or add ForwardX11 no
in your /etc/ssh/ssh_config
. In this case ssh will not create environment variable DISPLAY.
It could be even caused by your ad blocker.
Try to disable it or adding an exception for the domain from which the images come from.
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
Using multiple selections: select one pair of line breaks, then use Quick Find All (Alt+F3), or Quick Add Next (Ctrl+D) repeatedly, to select them all; then hit Enter to replace them with single line breaks.
Epsilon is the value that the 2 numbers can be off by. So it will assert to true as long as Math.abs(expected - actual) < epsilon
apt-get install python-dev
...solved the problem for me.
this is what I have done. Check it out, hope it can help.
#!/bin/bash
#
# So something to show.
echo "UNO" > UNO.txt
echo "DOS" > DOS.txt
#
# Initialize Pid List
dPidLst=""
#
# Generate background processes
tail -f UNO.txt&
dPidLst="$dPidLst $!"
tail -f DOS.txt&
dPidLst="$dPidLst $!"
#
# Report process IDs
echo PID=$$
echo dPidLst=$dPidLst
#
# Show process on current shell
ps -f
#
# Start killing background processes from list
for dPid in $dPidLst
do
echo killing $dPid. Process is still there.
ps | grep $dPid
kill $dPid
ps | grep $dPid
echo Just ran "'"ps"'" command, $dPid must not show again.
done
Then just run it as: ./bgkill.sh
with proper permissions of course
root@umsstd22 [P]:~# ./bgkill.sh
PID=23757
dPidLst= 23758 23759
UNO
DOS
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 23757 3937 0 11:55 pts/5 00:00:00 /bin/bash ./bgkill.sh
root 23758 23757 0 11:55 pts/5 00:00:00 tail -f UNO.txt
root 23759 23757 0 11:55 pts/5 00:00:00 tail -f DOS.txt
root 23760 23757 0 11:55 pts/5 00:00:00 ps -f
killing 23758. Process is still there.
23758 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23758 Terminated tail -f UNO.txt
Just ran 'ps' command, 23758 must not show again.
killing 23759. Process is still there.
23759 pts/5 00:00:00 tail
./bgkill.sh: line 24: 23759 Terminated tail -f DOS.txt
Just ran 'ps' command, 23759 must not show again.
root@umsstd22 [P]:~# ps -f
UID PID PPID C STIME TTY TIME CMD
root 3937 3935 0 11:07 pts/5 00:00:00 -bash
root 24200 3937 0 11:56 pts/5 00:00:00 ps -f
>>> 'QH QD JC KD JS'.split()
['QH', 'QD', 'JC', 'KD', 'JS']
Return a list of the words in the string, using
sep
as the delimiter string. Ifmaxsplit
is given, at mostmaxsplit
splits are done (thus, the list will have at mostmaxsplit+1
elements). Ifmaxsplit
is not specified, then there is no limit on the number of splits (all possible splits are made).If
sep
is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example,'1,,2'.split(',')
returns['1', '', '2']
). Thesep
argument may consist of multiple characters (for example,'1<>2<>3'.split('<>')
returns['1', '2', '3']
). Splitting an empty string with a specified separator returns['']
.If
sep
is not specified or isNone
, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with aNone
separator returns[]
.For example,
' 1 2 3 '.split()
returns['1', '2', '3']
, and' 1 2 3 '.split(None, 1)
returns['1', '2 3 ']
.
If you are using SQL Server, Use the LEN
(Length) function:
SELECT EmployeeName FROM EmployeeTable WHERE LEN(EmployeeName) > 4
MSDN for it states:
Returns the number of characters of the specified string expression,
excluding trailing blanks.
For oracle/plsql you can use Length()
, mysql also uses Length.
Here is the Oracle documentation:
http://www.techonthenet.com/oracle/functions/length.php
And here is the mySQL Documentation of Length(string)
:
http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_length
For PostgreSQL, you can use length(string)
or char_length(string)
. Here is the PostgreSQL documentation:
http://www.postgresql.org/docs/current/static/functions-string.html#FUNCTIONS-STRING-SQL
I would suggest following extension methods for string parsing into int value with ability to define default value in case parsing is not possible:
public static int ParseInt(this string value, int defaultIntValue = 0)
{
return int.TryParse(value, out var parsedInt) ? parsedInt : defaultIntValue;
}
public static int? ParseNullableInt(this string value)
{
if (string.IsNullOrEmpty(value))
return null;
return value.ParseInt();
}
@Ahmed
Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
In my opinion i had missed to map my local branch with remote repo. i did below and it worked fine.
git checkout master
git remote add origin https://github.com/yourrepo/project.git
git push -u origin master
git pull
git merge myBranch1FromMain
Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.
or you can manually enable the storage permission-
goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.
But i suggest go the for first one which is, Implement runtime permissions in your code.
Demo :
<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>
Based on your question:
<connectionStrings>
<add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
Refer links:
http://www.connectionstrings.com/store-connection-string-in-webconfig/
Retrive connection string from web.config file:
write the below code in your file where you want;
string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;
SqlConnection con = new SqlConnection(connstring);
or you can go in your way like
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);
Note:
The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)
PowerMockito is made for this. Use maven dependency
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-core</artifactId>
<version>2.0.7</version>
<scope>test</scope>
</dependency>
Then you can do
import org.powermock.reflect.Whitebox;
...
MyClass sut = new MyClass();
SomeType rval = Whitebox.invokeMethod(sut, "myPrivateMethod", params, moreParams);
Use breakpoint mixins like this:
.something {
padding: 5px;
@include media-breakpoint-up(sm) {
padding: 20px;
}
@include media-breakpoint-up(md) {
padding: 40px;
}
}
v4 alpha6 breakpoints reference
Below full options and values.
Breakpoint & up (toggle on value and above):
@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }
breakpoint & up values:
// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
breakpoint & down (toggle on value and down):
@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }
breakpoint & down values:
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }
// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }
// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }
// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width
breakpoint only:
@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }
breakpoint only values (toggle in between values only):
// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }
// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }
// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }
// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }
// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }
For closing cmd window, especially after ending weblogic or JBOSS app servers console with Ctrl+C, I'm using 'call
' command instead of 'start
' in my batch files. My startWLS.cmd file then looks like:
call [BEA_HOME]\user_projects\domains\test_domain\startWebLogic.cmd
After Ctrl+C(and 'Y' answer) cmd window is automatically closed.
Here are some static methods you can use to get the MaxLength, or any other attribute.
using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Linq.Expressions;
public static class AttributeHelpers {
public static Int32 GetMaxLength<T>(Expression<Func<T,string>> propertyExpression) {
return GetPropertyAttributeValue<T,string,MaxLengthAttribute,Int32>(propertyExpression,attr => attr.Length);
}
//Optional Extension method
public static Int32 GetMaxLength<T>(this T instance,Expression<Func<T,string>> propertyExpression) {
return GetMaxLength<T>(propertyExpression);
}
//Required generic method to get any property attribute from any class
public static TValue GetPropertyAttributeValue<T, TOut, TAttribute, TValue>(Expression<Func<T,TOut>> propertyExpression,Func<TAttribute,TValue> valueSelector) where TAttribute : Attribute {
var expression = (MemberExpression)propertyExpression.Body;
var propertyInfo = (PropertyInfo)expression.Member;
var attr = propertyInfo.GetCustomAttributes(typeof(TAttribute),true).FirstOrDefault() as TAttribute;
if (attr==null) {
throw new MissingMemberException(typeof(T).Name+"."+propertyInfo.Name,typeof(TAttribute).Name);
}
return valueSelector(attr);
}
}
Using the static method...
var length = AttributeHelpers.GetMaxLength<Player>(x => x.PlayerName);
Or using the optional extension method on an instance...
var player = new Player();
var length = player.GetMaxLength(x => x.PlayerName);
Or using the full static method for any other attribute (StringLength for example)...
var length = AttributeHelpers.GetPropertyAttributeValue<Player,string,StringLengthAttribute,Int32>(prop => prop.PlayerName,attr => attr.MaximumLength);
Inspired by the Mikael Engver's answer.
You can use ng-change instead of ng-click:
<!doctype html>
<html>
<head>
<script src="http://code.angularjs.org/1.2.3/angular.min.js"></script>
<script>
var app = angular.module('myapp', []);
app.controller('mainController', function($scope) {
$scope.vm = {};
$scope.vm.myClick = function($event) {
alert($event);
}
});
</script>
</head>
<body ng-app="myapp">
<div ng-controller="mainController">
<input type="checkbox" ng-model="vm.myChkModel" ng-change="vm.myClick(vm.myChkModel)">
</div>
</body>
</html>
Run this:
SELECT CASE transaction_isolation_level
WHEN 0 THEN 'Unspecified'
WHEN 1 THEN 'ReadUncommitted'
WHEN 2 THEN 'ReadCommitted'
WHEN 3 THEN 'Repeatable'
WHEN 4 THEN 'Serializable'
WHEN 5 THEN 'Snapshot' END AS TRANSACTION_ISOLATION_LEVEL
FROM sys.dm_exec_sessions
where session_id = @@SPID
This is part of my code which makes spaces into underscores for naming my files:
$file = basename($_FILES['upload']['name']);
$file = str_replace(' ','_',$file);
Here it is:
SELECT
OBJECT_NAME(f.parent_object_id) TableName,
COL_NAME(fc.parent_object_id,fc.parent_column_id) ColName
FROM
sys.foreign_keys AS f
INNER JOIN
sys.foreign_key_columns AS fc
ON f.OBJECT_ID = fc.constraint_object_id
INNER JOIN
sys.tables t
ON t.OBJECT_ID = fc.referenced_object_id
WHERE
OBJECT_NAME (f.referenced_object_id) = 'YourTableName'
This way, you'll get the referencing table and column name.
Edited to use sys.tables instead of generic sys.objects as per comment suggestion. Thanks, marc_s
Webkit browsers like Safari and Chrome subtract the scroll bar width from the visible page width when calculating width: 100% or 100vw. More at DM Rutherford's Scrolling and Page Width.
Try using overflow-y: overlay
instead.
I'm not sure what format you're looking for in your difference but here's how to do it using DateTime
$datetime1 = new DateTime();
$datetime2 = new DateTime('2011-01-03 17:13:00');
$interval = $datetime1->diff($datetime2);
$elapsed = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $elapsed;
I got same problem if i understand your question correctly, I want to know the last inserted id after every insert performance in SQLite operation. i tried the following statement:
select * from table_name order by id desc limit 1
The id is the first column and primary key of the table_name, the mentioned statement show me the record with the largest id.
But the premise is u never deleted any row so the numbers of id equal to the numbers of rows.
Based on @mehyaa answer, but much shorter:
HTML (right after <body>
):
<img id = "loading" src = "loading.gif" alt = "Loading indicator">
CSS:
#loading {
position: absolute;
top: 50%;
left: 50%;
width: 32px;
height: 32px;
/* 1/2 of the height and width of the actual gif */
margin: -16px 0 0 -16px;
z-index: 100;
}
Javascript (jQuery, since I'm already using it):
$(window).load(function() {
$('#loading').remove();
});
I made a script to solve this which is here. You don't need any extra software for this.
Installation:
brew install akashaggarwal7/tools/tsay
Usage:
sleep 5; tsay
Feel free to contribute!
Maybe this helps:
and run devenv /resetuserdata
.
Expect, that all of your user settings such as Visual Studio layout, linked Microsoft account or start page might disappear.
In matplotlib grey colors can be given as a string of a numerical value between 0-1.
For example c = '0.1'
Then you can convert your third variable in a value inside this range and to use it to color your points.
In the following example I used the y position of the point as the value that determines the color:
from matplotlib import pyplot as plt
x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [125, 32, 54, 253, 67, 87, 233, 56, 67]
color = [str(item/255.) for item in y]
plt.scatter(x, y, s=500, c=color)
plt.show()
No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.
I recently wrote a gem to simplify this process and to neaten up your views, etc etc.
Check it out at: http://github.com/platform45/easy_dates
W3C says:
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head profile="http://www.w3.org/2005/10/profile">
<link rel="icon"
type="image/png"
href="http://example.com/myicon.png">
[…]
</head>
[…]
</html>
See http://www.w3.org/2005/10/howto-favicon
But keep in mind: Some browser need a while to recognize that there is a favicon - try to delete the cookies and reopen your site! (And be sure the icon is at the path :) )
In JavaScript functions are objects.
document.getElementById('foo').onclick = function(){
prompt('Hello world');
}
This is a comment on the top answer, but I felt it was worth its own answer because it helped me answer the problem.
If you want to keep Bootstrap declared after JQuery UI (I did because I wanted to use the Bootstrap tooltip), declaring the following (I declared it after $(document).ready
) will allow the button to appear again (answer from https://stackoverflow.com/a/23428433/4660870)
var bootstrapButton = $.fn.button.noConflict() // return $.fn.button to previously assigned value
$.fn.bootstrapBtn = bootstrapButton // give $().bootstrapBtn the Bootstrap functionality
UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'
You can build your HttpContent
using the combination of JObject
to avoid and JProperty
and then call ToString()
on it when building the StringContent
:
/*{
"agent": {
"name": "Agent Name",
"version": 1
},
"username": "Username",
"password": "User Password",
"token": "xxxxxx"
}*/
JObject payLoad = new JObject(
new JProperty("agent",
new JObject(
new JProperty("name", "Agent Name"),
new JProperty("version", 1)
),
new JProperty("username", "Username"),
new JProperty("password", "User Password"),
new JProperty("token", "xxxxxx")
)
);
using (HttpClient client = new HttpClient())
{
var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");
using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JObject.Parse(responseBody);
}
}
Since this hasn't been mentioned yet but answers the question I had when I found this page, you can also specify that an index should be unique when adding it via t.references
or t.belongs_to
:
create_table :accounts do |t|
t.references :user, index: { unique: true } # or t.belongs_to
# other columns...
end
(as of at least Rails 4.2.7
)
python -c 'import os; print (os.path.getsize("... filename ..."))'
portable, all flavours of python, avoids variation in stat dialects
Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).
(I don't see anything obviously wrong with the code you have posted above)
Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?
C++20 std::source_location
C++ has finally added a non-macro option, and it will likely dominate at some point in the future when C++20 becomes widespread:
The documentation says:
constexpr const char* function_name() const noexcept;
6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.
where NTBS means "Null Terminated Byte String".
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:
#include <iostream>
#include <string_view>
#include <source_location>
void log(std::string_view message,
const std::source_location& location std::source_location::current()
) {
std::cout << "info:"
<< location.file_name() << ":"
<< location.line() << ":"
<< location.function_name() << " "
<< message << '\n';
}
int main() {
log("Hello world!");
}
Possible output:
info:main.cpp:16:main Hello world!
__PRETTY_FUNCTION__
vs __FUNCTION__
vs __func__
vs std::source_location::function_name
Answered at: What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?
Indeed, you can use the "create" method of Mongoose, it can contain an array of documents, see this example:
Candy.create({ candy: 'jelly bean' }, { candy: 'snickers' }, function (err, jellybean, snickers) {
});
The callback function contains the inserted documents. You do not always know how many items has to be inserted (fixed argument length like above) so you can loop through them:
var insertedDocs = [];
for (var i=1; i<arguments.length; ++i) {
insertedDocs.push(arguments[i]);
}
A better solution would to use Candy.collection.insert()
instead of Candy.create()
- used in the example above - because it's faster (create()
is calling Model.save()
on each item so it's slower).
See the Mongo documentation for more information: http://docs.mongodb.org/manual/reference/method/db.collection.insert/
(thanks to arcseldon for pointing this out)
AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.
$watch() :-
This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.
$digest() -
This function iterates through all the watches in the $scope object, and its child $scope objects
(if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.
$apply() -
Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.
'sprintf' will work fine, if your first argument is a pointer to a character (a pointer to a character is an array in 'c'), you'll have to make sure you have enough space for all the digits and a terminating '\0'. For example, If an integer uses 32 bits, it has up to 10 decimal digits. So your code should look like:
int i;
char s[11];
...
sprintf(s,"%ld", i);
Have a read through this blog post with an example of transition animations, I've included the code below:
package com.as400samplecode;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button nextActivity = (Button) findViewById(R.id.nextActivity);
nextActivity.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.nextActivity:
Intent nextActivity = new Intent(this,NextActivity.class);
startActivity(nextActivity);
//push from bottom to top
overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
//slide from right to left
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
break;
// More buttons go here (if any) ...
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity"
android:background="@color/ivory">
<Button android:id="@+id/nextActivity" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginTop="15dp"
android:text="Go to Next Activity" />
</RelativeLayout>
package com.as400samplecode;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class NextActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
Button previousActivity = (Button) findViewById(R.id.previousActivity);
previousActivity.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.previousActivity:
finish();
//push from top to bottom
overridePendingTransition(R.anim.push_down_in, R.anim.push_down_out);
//slide from left to right
//overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
break;
// More buttons go here (if any) ...
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".NextActivity"
android:background="@color/khaki">
<Button android:id="@+id/previousActivity" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" android:layout_marginTop="15dp"
android:text="Go to Previous Activity" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="-100%p" android:toYDelta="0" android:duration="5000"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="100%p" android:duration="5000" />
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="100%p" android:toYDelta="0" android:duration="5000"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="0" android:toYDelta="-100%p" android:duration="5000"/>
<alpha android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="5000" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="-100%" android:toXDelta="0%"/>
<alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="100%" android:toXDelta="0%" />
<alpha android:duration="5000" android:fromAlpha="0.0" android:toAlpha="1.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="-100%"/>
<alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="false" >
<translate android:duration="5000" android:fromXDelta="0%" android:toXDelta="100%"/>
<alpha android:duration="5000" android:fromAlpha="1.0" android:toAlpha="0.0" />
</set>
If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...
git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'
The correct answer for traditional Spring architectures is to place transactional semantics on the service classes, for the reasons that others have already described.
An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction
as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED
so that the domain objects use any existing transactions, such as transactions that were started at the service bean.
Technically this technique makes use of AspectJ and <context:spring-configured />
. Roo uses AspectJ inter-type definitions to separate the entity semantics (transactions and persistence) from the domain object stuff (basically fields and business methods).
After Much Fannying about, deleting this that etc, I found the way to delete a "website" from your list (which is, in fact what the original question was - minus all the flaffing) is
That's it… Done.
Remember: for this exercise only Account means Website.
Set it with a px value. Changing the code like below should work
el.css('marginLeft', mrg + 'px');
Ussing UNION
UNION is combines the results of two or more queries into a single result set that includes all the rows that belong to all queries in the union.
UNION Example: SELECT 121 AS [Column1], 221 AS [Column2] UNION SELECT 321 AS [Column1], 422 AS [Column2]
Output: Column1 Column2 ------------------- 121 221 321 422
Ussing JOINs
JOINs, you can retrieve data from two or more tables based on logical relationships between the tables.
JOIN Example: SELECT a.Column1, b.Column2 FROM TblA a INNER JOIN TblB b ON a.Id = b.id
You need $event.currentTarget
instead of $event.target
.
In Windows 10, no need to restart nor run in Administrator's mode but instead set openssl config like so:
set OPENSSL_CONF=C:\Program Files (x86)\GnuWin32\share\openssl.cnf
Of course, if you are using GnuWin32
In my case, the problem was I used wrong alias for git commit -m
. I used gc
alias which dit not meant git commit -m
Use List.Insert(0, ...)
. But are you sure a LinkedList
isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.
yum install -y yum-utils
yum-config-manager --add-repo http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo
yum-config-manager --enable epel-apache-maven
yum install -y apache-maven
for JVM developer, this is a SDK manager for all the tool you need.
Install sdkman:
yum install -y zip unzip
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
Install Maven:
sdk install maven
It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)
here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working
Just close (stop) and open (start) the database. This solved my problem.
You can use exec
for that:
>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>>
I'm assuming your column is 38 characters in length, so you want to truncate itemdescription
to fit within the database. A utility function like the following should do what you want:
/**
* Truncates s to fit within len. If s is null, null is returned.
**/
public String truncate(String s, int len) {
if (s == null) return null;
return s.substring(0, Math.min(len, s.length()));
}
then you just call it like so:
String value = "_";
if (itemdescription != null && itemdescription.length() > 0) {
value = truncate(itemdescription, 38);
}
pstmt2.setString(3, value);
It does not use the -f
option in readlink, and it should therefore work on BSD/Mac OS X.
.
dot operator)foo->dir1/dir2/bar bar->./../doe doe->script
I am looking for corner cases where this code does not work. Please let me know.
pushd . > /dev/null
SCRIPT_PATH="${BASH_SOURCE[0]}";
while([ -h "${SCRIPT_PATH}" ]); do
cd "`dirname "${SCRIPT_PATH}"`"
SCRIPT_PATH="$(readlink "`basename "${SCRIPT_PATH}"`")";
done
cd "`dirname "${SCRIPT_PATH}"`" > /dev/null
SCRIPT_PATH="`pwd`";
popd > /dev/null
echo "srcipt=[${SCRIPT_PATH}]"
echo "pwd =[`pwd`]"
The script must be on disk somewhere. Let it be over a network. If you try to run this script from a PIPE it will not work
wget -o /dev/null -O - http://host.domain/dir/script.sh |bash
Technically speaking, it is undefined. Practically speaking, there is no sane way to detect this. (A co-process can not access the environment of the parent.)
If you are working a lot with graphs and ggplot, you might be tired to add the theme() each time. If you don't want to change the default theme as suggested earlier, you may find easier to create your own personal theme.
personal_theme = theme(plot.title =
element_text(hjust = 0.5))
Say you have multiple graphs, p1, p2 and p3, just add personal_theme to them.
p1 + personal_theme
p2 + personal_theme
p3 + personal_theme
dat <- data.frame(
time = factor(c("Lunch","Dinner"),
levels=c("Lunch","Dinner")),
total_bill = c(14.89, 17.23)
)
p1 = ggplot(data=dat, aes(x=time, y=total_bill,
fill=time)) +
geom_bar(colour="black", fill="#DD8888",
width=.8, stat="identity") +
guides(fill=FALSE) +
xlab("Time of day") + ylab("Total bill") +
ggtitle("Average bill for 2 people")
p1 + personal_theme
plt.close()
will close current instance.
plt.close(2)
will close figure 2
plt.close(plot1)
will close figure with instance plot1
plt.close('all')
will close all fiures
Found here.
Remember that plt.show()
is a blocking function, so in the example code you used above, plt.close()
isn't being executed until the window is closed, which makes it redundant.
You can use plt.ion()
at the beginning of your code to make it non-blocking, although this has other implications.
After our discussion in the comments, I've put together a bit of an example just to demonstrate how the plot functionality can be used.
Below I create a plot:
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
....
par_plot, = plot(x_data,y_data, lw=2, color='red')
In this case, ax
above is a handle to a pair of axes. Whenever I want to do something to these axes, I can change my current set of axes to this particular set by calling axes(ax)
.
par_plot
is a handle to the line2D instance. This is called an artist. If I want to change a property of the line, like change the ydata, I can do so by referring to this handle.
I can also create a slider widget by doing the following:
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
The first line creates a new axes for the slider (called axsliderA
), the second line creates a slider instance sA
which is placed in the axes, and the third line specifies a function to call when the slider value changes (update
).
My update function could look something like this:
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
The par_plot.set_ydata(y_data)
changes the ydata property of the Line2D object with the handle par_plot
.
The draw()
function updates the current set of axes.
Putting it all together:
from pylab import *
import matplotlib.pyplot as plt
import numpy
def update(val):
A = sA.val
B = sB.val
C = sC.val
y_data = A*x_data*x_data + B*x_data + C
par_plot.set_ydata(y_data)
draw()
x_data = numpy.arange(-100,100,0.1);
fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)
ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')
axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)
axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)
axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)
axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;
par_plot, = plot(x_data,y_data, lw=2, color='red')
show()
A note about the above: When I run the application, the code runs sequentially right through (it stores the update
function in memory, I think), until it hits show(), which is blocking. When you make a change to one of the sliders, it runs the update function from memory (I think?).
This is the reason why show() is implemented in the way it is, so that you can change values in the background by using functions to process the data.
<form target="_blank">
<button class="btn btn-primary" formaction="http://www.google.com">Google</button>
</form>
Use "$@"
instead of plain $@
if you actually wish your parameters to be passed the same.
Observe:
$ cat no_quotes.sh
#!/bin/bash
echo_args.sh $@
$ cat quotes.sh
#!/bin/bash
echo_args.sh "$@"
$ cat echo_args.sh
#!/bin/bash
echo Received: $1
echo Received: $2
echo Received: $3
echo Received: $4
$ ./no_quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./no_quotes.sh "one quoted arg"
Received: one
Received: quoted
Received: arg
Received:
$ ./quotes.sh first second
Received: first
Received: second
Received:
Received:
$ ./quotes.sh "one quoted arg"
Received: one quoted arg
Received:
Received:
Received:
While sort
takes O(n log(n)) time, I prefer using
awk '!seen[$0]++'
awk '!seen[$0]++'
is an abbreviation for awk '!seen[$0]++ {print}'
, print line(=$0) if seen[$0]
is not zero.
It take more space but only O(n) time.
In addition to @ShinDarth answer.
I did what he said but my package did not updated the angular version, and I know that this post is about angular-cli
, but i think that this can help too.
-ng new projectname
that generated a package.-npm install
.Now my ng serve
is working again, maybe there is a better way to do all that, if someone know, please share, because this is a pain to do with all projects that need update.
It has something to do with your link and content. Try the following two links:
String path="http://www.ted.com/talks/download/video/8584/talk/761";
String path1="http://commonsware.com/misc/test2.3gp";
Uri uri=Uri.parse(path1);
VideoView video=(VideoView)findViewById(R.id.VideoView01);
video.setVideoURI(uri);
video.start();
Start with "path1", it is a small light weight video stream and then try the "path", it is a higher resolution than "path1", a perfect high resolution for the mobile phone.
Please check this jsFiddle. (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).
As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:
$scope.$watch('users', function(value) {
$scope.users = [];
});
This will result on an error message:
Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...
Make sure that your code doesn't have this kind of situations.
update:
This is your problem:
<div ng-init="user.score=user.id+1">
You shouldn't change objects/models during the render or otherwise, it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').
If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init
exactly to avoid these kinds of situations:
Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)
Here's a jsFiddle with a working example.
when?
When an object is not thread-safe, instead of synchronization which hampers the scalability, give one object to every thread and keep it thread scope, which is ThreadLocal. One of most often used but not thread-safe objects are database Connection and JMSConnection.
How ?
One example is Spring framework uses ThreadLocal heavily for managing transactions behind the scenes by keeping these connection objects in ThreadLocal variables. At high level, when a transaction is started it gets the connection ( and disables the auto commit ) and keeps it in ThreadLocal. on further db calls it uses same connection to communicate with db. At the end, it takes the connection from ThreadLocal and commits ( or rollback ) the transaction and releases the connection.
I think log4j also uses ThreadLocal for maintaining MDC.
ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store
So Everything will be stored on ephemeral.
if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.
Use this code to create suitable parameter from your type:
private SqlParameter GenerateTypedParameter(string name, object typedParameter)
{
DataTable dt = new DataTable();
var properties = typedParameter.GetType().GetProperties().ToList();
properties.ForEach(p =>
{
dt.Columns.Add(p.Name, Nullable.GetUnderlyingType(p.PropertyType) ?? p.PropertyType);
});
var row = dt.NewRow();
properties.ForEach(p => { row[p.Name] = (p.GetValue(typedParameter) ?? DBNull.Value); });
dt.Rows.Add(row);
return new SqlParameter
{
Direction = ParameterDirection.Input,
ParameterName = name,
Value = dt,
SqlDbType = SqlDbType.Structured
};
}
You did two mistakes . I think you misplace FROM and WHERE keywords.
SELECT DISTINCT Description, Date as treatmentDate
FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I --Here you use "." operator to "I" alias
WHERE -- WHERE should be located here.
P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”
It is generally best to explicitly specify essential attributes such as type=text
instead of defaulting them. The reason is that there is no simple reliable way to refer to the input
elements with defaulted type
attribute.
Since all of the solutions to date used fluent syntax, here is a solution in query expression syntax, for those interested:
var peopleDifference =
from person2 in peopleList2
where !(
from person1 in peopleList1
select person1.ID
).Contains(person2.ID)
select person2;
I think it is different enough from the answers given to be of interest to some, even thought it most likely would be suboptimal for Lists. Now for tables with indexed IDs, this would definitely be the way to go.
You can also, do this.
$(window).on("scroll", function () {
if ($(this).scrollTop() > 800) {
#code here
} else {
#code here
}
});
pip install pywin32
didn't work for me but pypiwin32
did.
may be you can do by using AJAX or jquery...
just send that file url on one page and then open like normally open pdf file in that page and use ajax.
1)so as soon as user will click on the button. then u call that function in which u above tast. So by this way there will be only one page and by that you can show as many pdf without refreshing page.
2) if u don't have many pdf and if u don't know then just upload that file on google docs and then just put the share link file....and then just use ajax or jquery.
i prefer jquery if u don't have use AJAX.
If you're using node:
values.js
:export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js
):
import { someValues } from './values'
console.log(someValues);
Yes. You can use Process.Start
to launch an executable, including a console application.
If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.
DECLARE @IDQuery VARCHAR(MAX)
SET @IDQuery = 'SELECT ID FROM SomeTable WHERE Condition=Something'
DECLARE @ExcludedList TABLE(ID VARCHAR(MAX))
INSERT INTO @ExcludedList EXEC(@IDQuery)
SELECT * FROM A WHERE Id NOT IN (@ExcludedList)
I know I'm responding to an old post but I wanted to share an example of how to use Variable Tables when one wants to avoid using dynamic SQL. I'm not sure if its the most efficient way, however this has worked in the past for me when dynamic SQL was not an option.
foreach($array as $value=>$name)
{
if($value == $_GET['sel'])
{
echo "<option selected='selected' value='".$value."'>".$name."</option>";
}
else
{
echo "<option value='".$value."'>".$name."</option>";
}
}
Yes there is, you can simply put <hr>
in your code where you want it, I already use it in one of my admin panel side bar.