The simple answer:
doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice
ADD 1 is probably faster than INC here
MOV 2 and DIV is very expensive; just shift right
64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code
If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.
I encountered the same issue. My bucket was private and had KMS encryption. I was able to resolve this issue by putting in additional KMS permissions in the role. The following list is the bare minimum set of roles needed.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowAttachmentBucketWrite",
"Effect": "Allow",
"Action": [
"s3:PutObject",
"kms:Decrypt",
"s3:AbortMultipartUpload",
"kms:Encrypt",
"kms:GenerateDataKey"
],
"Resource": [
"arn:aws:s3:::bucket-name/*",
"arn:aws:kms:kms-key-arn"
]
}
]
}
Reference: https://aws.amazon.com/premiumsupport/knowledge-center/s3-large-file-encryption-kms-key/
Using pgadmin4 :
Now there you can enable or disable login, roles and other options
Add the following line in MyApplicationDir\gradle.properties
org.gradle.jvmargs=-Xmx1024m
I think you need to use for example:
aws ecs list-container-instances --cluster default --region us-east-1
This depends of your region of course.
@T0xicCode's answer is correct, but I thought I would expand on the details since it actually took me about 20 hours to finally get a working solution implemented.
If you're looking to run Nginx in its own container and use it as a reverse proxy to load balance multiple applications on the same server instance then the steps you need to follow are as such:
Link Your Containers
When you docker run
your containers, typically by inputting a shell script into User Data
, you can declare links to any other running containers. This means that you need to start your containers up in order and only the latter containers can link to the former ones. Like so:
#!/bin/bash
sudo docker run -p 3000:3000 --name API mydockerhub/api
sudo docker run -p 3001:3001 --link API:API --name App mydockerhub/app
sudo docker run -p 80:80 -p 443:443 --link API:API --link App:App --name Nginx mydockerhub/nginx
So in this example, the API
container isn't linked to any others, but the
App
container is linked to API
and Nginx
is linked to both API
and App
.
The result of this is changes to the env
vars and the /etc/hosts
files that reside within the API
and App
containers. The results look like so:
/etc/hosts
Running cat /etc/hosts
within your Nginx
container will produce the following:
172.17.0.5 0fd9a40ab5ec
127.0.0.1 localhost
::1 localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
172.17.0.3 App
172.17.0.2 API
ENV Vars
Running env
within your Nginx
container will produce the following:
API_PORT=tcp://172.17.0.2:3000
API_PORT_3000_TCP_PROTO=tcp
API_PORT_3000_TCP_PORT=3000
API_PORT_3000_TCP_ADDR=172.17.0.2
APP_PORT=tcp://172.17.0.3:3001
APP_PORT_3001_TCP_PROTO=tcp
APP_PORT_3001_TCP_PORT=3001
APP_PORT_3001_TCP_ADDR=172.17.0.3
I've truncated many of the actual vars, but the above are the key values you need to proxy traffic to your containers.
To obtain a shell to run the above commands within a running container, use the following:
sudo docker exec -i -t Nginx bash
You can see that you now have both /etc/hosts
file entries and env
vars that contain the local IP address for any of the containers that were linked. So far as I can tell, this is all that happens when you run containers with link options declared. But you can now use this information to configure nginx
within your Nginx
container.
Configuring Nginx
This is where it gets a little tricky, and there's a couple of options. You can choose to configure your sites to point to an entry in the /etc/hosts
file that docker
created, or you can utilize the ENV
vars and run a string replacement (I used sed
) on your nginx.conf
and any other conf files that may be in your /etc/nginx/sites-enabled
folder to insert the IP values.
OPTION A: Configure Nginx Using ENV Vars
This is the option that I went with because I couldn't get the
/etc/hosts
file option to work. I'll be trying Option B soon enough and update this post with any findings.
The key difference between this option and using the /etc/hosts
file option is how you write your Dockerfile
to use a shell script as the CMD
argument, which in turn handles the string replacement to copy the IP values from ENV
to your conf file(s).
Here's the set of configuration files I ended up with:
Dockerfile
FROM ubuntu:14.04
MAINTAINER Your Name <[email protected]>
RUN apt-get update && apt-get install -y nano htop git nginx
ADD nginx.conf /etc/nginx/nginx.conf
ADD api.myapp.conf /etc/nginx/sites-enabled/api.myapp.conf
ADD app.myapp.conf /etc/nginx/sites-enabled/app.myapp.conf
ADD Nginx-Startup.sh /etc/nginx/Nginx-Startup.sh
EXPOSE 80 443
CMD ["/bin/bash","/etc/nginx/Nginx-Startup.sh"]
nginx.conf
daemon off;
user www-data;
pid /var/run/nginx.pid;
worker_processes 1;
events {
worker_connections 1024;
}
http {
# Basic Settings
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 33;
types_hash_max_size 2048;
server_tokens off;
server_names_hash_bucket_size 64;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Logging Settings
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
# Gzip Settings
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 3;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/plain text/xml text/css application/x-javascript application/json;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";
# Virtual Host Configs
include /etc/nginx/sites-enabled/*;
# Error Page Config
#error_page 403 404 500 502 /srv/Splash;
}
NOTE: It's important to include
daemon off;
in yournginx.conf
file to ensure that your container doesn't exit immediately after launching.
api.myapp.conf
upstream api_upstream{
server APP_IP:3000;
}
server {
listen 80;
server_name api.myapp.com;
return 301 https://api.myapp.com/$request_uri;
}
server {
listen 443;
server_name api.myapp.com;
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_pass http://api_upstream;
}
}
Nginx-Startup.sh
#!/bin/bash
sed -i 's/APP_IP/'"$API_PORT_3000_TCP_ADDR"'/g' /etc/nginx/sites-enabled/api.myapp.com
sed -i 's/APP_IP/'"$APP_PORT_3001_TCP_ADDR"'/g' /etc/nginx/sites-enabled/app.myapp.com
service nginx start
I'll leave it up to you to do your homework about most of the contents of nginx.conf
and api.myapp.conf
.
The magic happens in Nginx-Startup.sh
where we use sed
to do string replacement on the APP_IP
placeholder that we've written into the upstream
block of our api.myapp.conf
and app.myapp.conf
files.
This ask.ubuntu.com question explains it very nicely: Find and replace text within a file using commands
GOTCHA On OSX,
sed
handles options differently, the-i
flag specifically. On Ubuntu, the-i
flag will handle the replacement 'in place'; it will open the file, change the text, and then 'save over' the same file. On OSX, the-i
flag requires the file extension you'd like the resulting file to have. If you're working with a file that has no extension you must input '' as the value for the-i
flag.GOTCHA To use ENV vars within the regex that
sed
uses to find the string you want to replace you need to wrap the var within double-quotes. So the correct, albeit wonky-looking, syntax is as above.
So docker has launched our container and triggered the Nginx-Startup.sh
script to run, which has used sed
to change the value APP_IP
to the corresponding ENV
variable we provided in the sed
command. We now have conf files within our /etc/nginx/sites-enabled
directory that have the IP addresses from the ENV
vars that docker set when starting up the container. Within your api.myapp.conf
file you'll see the upstream
block has changed to this:
upstream api_upstream{
server 172.0.0.2:3000;
}
The IP address you see may be different, but I've noticed that it's usually 172.0.0.x
.
You should now have everything routing appropriately.
GOTCHA You cannot restart/rerun any containers once you've run the initial instance launch. Docker provides each container with a new IP upon launch and does not seem to re-use any that its used before. So
api.myapp.com
will get 172.0.0.2 the first time, but then get 172.0.0.4 the next time. ButNginx
will have already set the first IP into its conf files, or in its/etc/hosts
file, so it won't be able to determine the new IP forapi.myapp.com
. The solution to this is likely to useCoreOS
and itsetcd
service which, in my limited understanding, acts like a sharedENV
for all machines registered into the sameCoreOS
cluster. This is the next toy I'm going to play with setting up.
OPTION B: Use /etc/hosts
File Entries
This should be the quicker, easier way of doing this, but I couldn't get it to work. Ostensibly you just input the value of the /etc/hosts
entry into your api.myapp.conf
and app.myapp.conf
files, but I couldn't get this method to work.
UPDATE: See @Wes Tod's answer for instructions on how to make this method work.
Here's the attempt that I made in api.myapp.conf
:
upstream api_upstream{
server API:3000;
}
Considering that there's an entry in my /etc/hosts
file like so: 172.0.0.2 API
I figured it would just pull in the value, but it doesn't seem to be.
I also had a couple of ancillary issues with my Elastic Load Balancer
sourcing from all AZ's so that may have been the issue when I tried this route. Instead I had to learn how to handle replacing strings in Linux, so that was fun. I'll give this a try in a while and see how it goes.
Generally speaking, 5xx response codes indicate non-programmatic failures, such as a database connection failure, or some other system/library dependency failure. In many cases, it is expected that the client can re-submit the same request in the future and expect it to be successful.
Yes, some web-frameworks will respond with 5xx codes, but those are typically the result of defects in the code and the framework is too abstract to know what happened, so it defaults to this type of response; that example, however, doesn't mean that we should be in the habit of returning 5xx codes as the result of programmatic behavior that is unrelated to out of process systems. There are many, well defined response codes that are more suitable than the 5xx codes. Being unable to parse/validate a given input is not a 5xx response because the code can accommodate a more suitable response that won't leave the client thinking that they can resubmit the same request, when in fact, they can not.
To be clear, if the error encountered by the server was due to CLIENT input, then this is clearly a CLIENT error and should be handled with a 4xx response code. The expectation is that the client will correct the error in their request and resubmit.
It is completely acceptable, however, to catch any out of process errors and interpret them as a 5xx response, but be aware that you should also include further information in the response to indicate exactly what failed; and even better if you can include SLA times to address.
I don't think it's a good practice to interpret, "an unexpected error" as a 5xx error because bugs happen.
It is a common alert monitor to begin alerting on 5xx types of errors because these typically indicate failed systems, rather than failed code. So, code accordingly!
For some unknown reason, Android Studio incorrectly adds the android() method in the top-level build.gradle file.
Just delete the method and it works for me.
android {
compileSdkVersion 21
buildToolsVersion '21.1.2'
}
The underlining problem is simple – lack of permission to /var/run/docker.sock
unix domain socket.
From Daemon socket option chapter of Docker Command Line reference for Docker 1.6.0:
By default, a unix domain socket (or IPC socket) is created at
/var/run/docker.sock
, requiring either root permission, or docker group membership.
Steps necessary to grant rights to users are nicely described in Docker installation instructions for Fedora:
Granting rights to users to use Docker
The docker command line tool contacts the docker daemon process via a socket file
/var/run/docker.sock
owned byroot:root
. Though it's recommended to use sudo for docker commands, if users wish to avoid it, an administrator can create a docker group, have it own/var/run/docker.sock
, and add users to this group.
$ sudo groupadd docker
$ sudo chown root:docker /var/run/docker.sock
$ sudo usermod -a -G docker $USERNAME
Log out and log back in for above changes to take effect.
Please note that Docker packages of some Linux distributions (Ubuntu) do already place /var/run/docker.sock
in the docker
group making the first two of above steps unnecessary.
In case of OS X and boot2docker
the situation is different; the Docker daemon runs inside a VM so the DOCKER_HOST
environment variable must be set to this VM so that the Docker client could find the Docker daemon. This is done by running $(boot2docker shellinit)
in the shell.
As the whole thing is mixing up let's look at it function and code to simulate what it means consicely
The only way to get a row is via primary key
getRow(pk: PrimaryKey): Row
Primary key data structure can be this:
// If you decide your primary key is just the partition key.
class PrimaryKey(partitionKey: String)
// and in thids case
getRow(somePartitionKey): Row
However you can decide your primary key is partition key + sort key in this case:
// if you decide your primary key is partition key + sort key
class PrimaryKey(partitionKey: String, sortKey: String)
getRow(partitionKey, sortKey): Row
getMultipleRows(partitionKey): Row[]
So the bottom line:
Decided that your primary key is partition key only? get single row by partition key.
Decided that your primary key is partition key + sort key? 2.1 Get single row by (partition key, sort key) or get range of rows by (partition key)
In either way you get a single row by primary key the only question is if you defined that primary key to be partition key only or partition key + sort key
Building blocks are:
Think of Item as a row and of KV Attribute as cells in that row.
You can do (2) only if you decided that your PK is composed of (HashKey, SortKey).
More visually as its complex, the way I see it:
+----------------------------------------------------------------------------------+
|Table |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
|+------------------------------------------------------------------------------+ |
||Item | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|||primaryKey | |kv attr | |kv attr ...| |kv attr ...| |kv attr ...| | |
||+-----------+ +-----------+ +-----------+ +-----------+ +-----------+ | |
|+------------------------------------------------------------------------------+ |
| |
+----------------------------------------------------------------------------------+
+----------------------------------------------------------------------------------+
|1. Always get item by PrimaryKey |
|2. PK is (Hash,RangeKey), great get MULTIPLE Items by Hash, filter/sort by range |
|3. PK is HashKey: just get a SINGLE ITEM by hashKey |
| +--------------------------+|
| +---------------+ |getByPK => getBy(1 ||
| +-----------+ +>|(HashKey,Range)|--->|hashKey, > < or startWith ||
| +->|Composite |-+ +---------------+ |of rangeKeys) ||
| | +-----------+ +--------------------------+|
|+-----------+ | |
||PrimaryKey |-+ |
|+-----------+ | +--------------------------+|
| | +-----------+ +---------------+ |getByPK => get by specific||
| +->|HashType |-->|get one item |--->|hashKey ||
| +-----------+ +---------------+ | ||
| +--------------------------+|
+----------------------------------------------------------------------------------+
So what is happening above. Notice the following observations. As we said our data belongs to (Table, Item, KVAttribute). Then Every Item has a primary key. Now the way you compose that primary key is meaningful into how you can access the data.
If you decide that your PrimaryKey is simply a hash key then great you can get a single item out of it. If you decide however that your primary key is hashKey + SortKey then you could also do a range query on your primary key because you will get your items by (HashKey + SomeRangeFunction(on range key)). So you can get multiple items with your primary key query.
Note: I did not refer to secondary indexes.
I got same problem and I solved it using these steps.
1)Remove your .gradle file.(uuslly it in C:\Users{your_PC_name}
2)then go to the environment variable and add these to the system variable(as a new variable)
Variable name : _JAVA_OPTIONS
Variable value: -Xmx524m
3)go to your project folder and run these command
ionic cordova platform add android
4)Above command create platform folder in your project path
5)then run this command
ionic cordova build android
Wrong gradle file. The right one is build.gradle in your 'app' folder.
I have Android Studio 0.8.9 and after hours on forums the thing that finally worked for me was to manually download Gradle (latest version) then go to: C:\Users\.gradle\wrapper\dists\gradle-1.12-all\\ and replace the local archive with the recently downloaded archive and also replace the extracted data; after restarting Android Studio... he did some downloadings and builds and all sorts of stuff, but it finally worked.. Good Luck people!
In Eclipse, go to windows -> preferences -> gradle->arguments. Find JVM Arguments choose from radio button "USE :" and write arguments -Xms128m -Xmx512m Then click button Apply
use value
instead of query
(must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):
select
xt.Id
, x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
XmlTest xt
cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)
Rajesh's suggestion did not work for me. What I did was go to
File -> Settings ->HTTP Proxy(Under IDE Settings) ->Manual proxy configuration
I still left the proxy information in Project Settings under Gradle, like Rajesh suggested. But I'm not entirely sure if it's necessary.
I am using 0.8.6 Beta
Newer versions of OpenSSL say BEGIN PRIVATE KEY
because they contain the private key + an OID that identifies the key type (this is known as PKCS8 format). To get the old style key (known as either PKCS1 or traditional OpenSSL format) you can do this:
openssl rsa -in server.key -out server_new.key
Alternately, if you have a PKCS1 key and want PKCS8:
openssl pkcs8 -topk8 -nocrypt -in privkey.pem
Here is what it worked for me.. I wanted to create a hello world java application with gradle with the following requirements.
Here is the solution :
gradle init --type java-application
Runnable fat Jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
Copy Dependencies
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
Create jar with classpath dependecies in manifest
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Here is the complete build.gradle
plugins {
id 'java'
id 'application'
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.slf4j:slf4j-api:1.7.30'
implementation 'ch.qos.logback:logback-classic:1.2.3'
implementation 'ch.qos.logback:logback-core:1.2.3'
testImplementation 'junit:junit:4.13'
}
def outputJar = "${buildDir}/libs/${rootProject.name}.jar"
def dependsDir = "${buildDir}/libs/dependencies/"
def runnableJar = "${rootProject.name}_fat.jar";
//Create runnable fat jar
task fatJar(type: Jar) {
clean
println("Creating fat jar")
manifest {
attributes 'Main-Class': 'com.abc.gradle.hello.App'
}
archiveName "${runnableJar}"
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println("Fat jar is created")
}
//Copy dependent libraries to directory.
task copyDepends(type: Copy) {
from configurations.default
into "${dependsDir}"
}
//Create runnable jar with dependencies
task createJar(type: Jar) {
println("Cleaning...")
clean
manifest {
attributes('Main-Class': 'com.abc.gradle.hello.App',
'Class-Path': configurations.default.collect { 'dependencies/' +
it.getName() }.join(' ')
)
}
from {
configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }
} with jar
println "${outputJar} created"
}
Gradle build commands
Create fat jar : gradle fatJar
Copy dependencies : gradle copyDepends
Create runnable jar with dependencies : gradle createJar
More details can be read here : https://jafarmlp.medium.com/a-simple-java-project-with-gradle-2c323ae0e43d
this is working for me
i use this path
String FILENAME_PATH = "/mnt/sdcard/Download/Version";
public static String getStringFromFile (String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
If you want to see dependencies on project and all subprojects use in your top-level build.gradle:
subprojects {
task listAllDependencies(type: DependencyReportTask) {}
}
Then call gradle:
gradle listAllDependencies
I use another Eclipse plugin to import existing gradle projects.
You can install the Builship Gradle Gntegration 2.0 using the Eclipse Marketplace client.
Then you choose FIle ? Import ? Existing Gradle Project.
Finially, indicate your project root directory and click finish.
I have faced the similar issue and fixed by copying the missing Jar files in to .M2 Path,
For example: if you see the error message as Missing artifact tws:axis-client:jar:8.7
then you have to download "axis-client-8.7.jar" file and paste the same in to below location will resolve the issue.
C:\Users\UsernameXXX.m2\repository\tws\axis-client\8.7(Paste axis-client-8.7.jar).
finally, right click on project->Maven->Update Project...Thats it.
happy coding.
As others have noted, "SKU" stands for stock keeping unit. Here's what I find currently (3 February 2017) in the Apple documentation regarding the "SKU Number:"
SKU Number
A unique ID for your app in the Apple system that is not seen by users. You can use letters, numbers, hyphens, periods, and underscores. The SKU can’t
start with a hyphen, period, or underscore. Use a value that is meaningful to your organization. Can’t be edited after saving the iTunes Connect record.
(internet archive link:) iTunes Connect Properties
The JRE/JDK/Java 8 jurisdiction files can be found here:
Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 8 Download
Like James said above:
Install the files in ${java.home}/jre/lib/security/
.
I had the same problem at my office and I solved it adding the proxy in the destination of the R shortcut; clik on right button of the R icon, preferences, and in the destination field add
"C:\Program Files\R\your_R_version\bin\Rgui.exe" http_proxy=http://user_id:passwod@your_proxy:your_port/
Be sure to put the directory where you have the R program installed. That works for me. Hope this help.
In my build.gradle
I have the following task, which uses the usual linux proxy settings, HTTP_PROXY
and HTTPS_PROXY
, from the shell env:
task setHttpProxyFromEnv {
def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
for (e in System.getenv()) {
def key = e.key.toUpperCase()
if (key in map) {
def base = map[key]
def url = e.value.toURL()
println " - systemProp.${base}.proxy=${url.host}:${url.port}"
System.setProperty("${base}.proxyHost", url.host.toString())
System.setProperty("${base}.proxyPort", url.port.toString())
}
}
}
build.dependsOn setHttpProxyFromEnv
Compile is the process of creating an executable program from code written in a compiled programming language. Compiling allows the computer to run and understand the program without the need of the programming software used to create it. When a program is compiled it is often compiled for a specific platform (e.g. IBM platform) that works with IBM compatible computers, but not other platforms (e.g. Apple platform). The first compiler was developed by Grace Hopper while working on the Harvard Mark I computer. Today, most high-level languages will include their own compiler or have toolkits available that can be used to compile the program. A good example of a compiler used with Java is Eclipse and an example of a compiler used with C and C++ is the gcc command. Depending on how big the program is it should take a few seconds or minutes to compile and if no errors are encountered while being compiled an executable file is created.check this information
Finally find out the problem:
the port 443 was listening on HTTP instead of HTTPS, changed to HTTPS solved my issue.
SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description
FROM Orders
JOIN LineItems
ON LineItems.LineItemGUID =
(
SELECT TOP 1 LineItemGUID
FROM LineItems
WHERE OrderID = Orders.OrderID
)
In SQL Server 2005 and above, you could just replace INNER JOIN
with CROSS APPLY
:
SELECT Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description
FROM Orders
CROSS APPLY
(
SELECT TOP 1 LineItems.Quantity, LineItems.Description
FROM LineItems
WHERE LineItems.OrderID = Orders.OrderID
) LineItems2
Please note that TOP 1
without ORDER BY
is not deterministic: this query you will get you one line item per order, but it is not defined which one will it be.
Multiple invocations of the query can give you different line items for the same order, even if the underlying did not change.
If you want deterministic order, you should add an ORDER BY
clause to the innermost query.
I found the problem, here's the script of the slow and fast versions of the stored procedure:
dbo.ViewOpener__RenamedForCruachan__Slow.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS OFF
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Slow
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
dbo.ViewOpener__RenamedForCruachan__Fast.PRC
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE dbo.ViewOpener_RenamedForCruachan_Fast
@SessionGUID uniqueidentifier
AS
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
If you didn't spot the difference, I don't blame you. The difference is not in the stored procedure at all. The difference that turns a fast 0.5 cost query into one that does an eager spool of 6 million rows:
Slow: SET ANSI_NULLS OFF
Fast: SET ANSI_NULLS ON
This answer also could be made to make sense, since the view does have a join clause that says:
(table.column IS NOT NULL)
So there is some NULL
s involved.
The explanation is further proved by returning to Query Analizer, and running
SET ANSI_NULLS OFF
.
DECLARE @SessionGUID uniqueidentifier
SET @SessionGUID = 'BCBA333C-B6A1-4155-9833-C495F22EA908'
.
SELECT *
FROM Report_Opener_RenamedForCruachan
WHERE SessionGUID = @SessionGUID
ORDER BY CurrencyTypeOrder, Rank
And the query is slow.
So the problem isn't because the query is being run from a stored procedure. The problem is that Enterprise Manager's connection default option is ANSI_NULLS off
, rather than ANSI_NULLS on
, which is QA's default.
Microsoft acknowledges this fact in KB296769 (BUG: Cannot use SQL Enterprise Manager to create stored procedures containing linked server objects). The workaround is include the ANSI_NULLS
option in the stored procedure dialog:
Set ANSI_NULLS ON
Go
Create Proc spXXXX as
....
The URL should NOT contain the versions. The version has nothing to do with "idea" of the resource you are requesting. You should try to think of the URL as being a path to the concept you would like - not how you want the item returned. The version dictates the representation of the object, not the concept of the object. As other posters have said, you should be specifying the format (including version) in the request header.
If you look at the full HTTP request for the URLs which have versions, it looks like this:
(BAD WAY TO DO IT):
http://company.com/api/v3.0/customer/123
====>
GET v3.0/customer/123 HTTP/1.1
Accept: application/xml
<====
HTTP/1.1 200 OK
Content-Type: application/xml
<customer version="3.0">
<name>Neil Armstrong</name>
</customer>
The header contains the line which contains the representation you are asking for ("Accept: application/xml"). That is where the version should go. Everyone seems to gloss over the fact that you may want the same thing in different formats and that the client should be able ask for what it wants. In the above example, the client is asking for ANY XML representation of the resource - not really the true representation of what it wants. The server could, in theory, return something completely unrelated to the request as long as it was XML and it would have to be parsed to realize it is wrong.
A better way is:
(GOOD WAY TO DO IT)
http://company.com/api/customer/123
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+xml
<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+xml
<customer>
<name>Neil Armstrong</name>
</customer>
Further, lets say the clients think the XML is too verbose and now they want JSON instead. In the other examples you would have to have a new URL for the same customer, so you would end up with:
(BAD)
http://company.com/api/JSONv3.0/customers/123
or
http://company.com/api/v3.0/customers/123?format="JSON"
(or something similar). When in fact, every HTTP requests contains the format you are looking for:
(GOOD WAY TO DO IT)
===>
GET /customer/123 HTTP/1.1
Accept: application/vnd.company.myapp.customer-v3+json
<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.myapp-v3+json
{"customer":
{"name":"Neil Armstrong"}
}
Using this method, you have much more freedom in design and are actually adhering to the original idea of REST. You can change versions without disrupting clients, or incrementally change clients as the APIs are changed. If you choose to stop supporting a representation, you can respond to the requests with HTTP status code or custom codes. The client can also verify the response is in the correct format, and validate the XML.
There are many other advantages and I discuss some of them here on my blog: http://thereisnorightway.blogspot.com/2011/02/versioning-and-types-in-resthttp-api.html
One last example to show how putting the version in the URL is bad. Lets say you want some piece of information inside the object, and you have versioned your various objects (customers are v3.0, orders are v2.0, and shipto object is v4.2). Here is the nasty URL you must supply in the client:
(Another reason why version in the URL sucks)
http://company.com/api/v3.0/customer/123/v2.0/orders/4321/
Firstly, you should use randrange(0,1000)
or randint(0,999)
, not randint(0,1000)
. The upper limit of randint
is inclusive.
For efficiently, randint
is simply a wrapper of randrange
which calls random
, so you should just use random
. Also, use xrange
as the argument to sample
, not range
.
You could use
[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]
to generate 10,000 numbers in the range using sample
10 times.
(Of course this won't beat NumPy.)
$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop
$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]'
100 loops, best of 3: 9.24 msec per loop
$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop
$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
> a = range(x)
> shuffle(a)
> return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop
$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop
But since you don't care about the distribution of numbers, why not just use:
range(1000)*(10000/1000)
?
You can use the library: https://github.com/vivchar/RendererRecyclerViewAdapter
mRecyclerViewAdapter = new RendererRecyclerViewAdapter(); /* included from library */
mRecyclerViewAdapter.registerRenderer(new SomeViewRenderer(SomeModel.TYPE, this));
mRecyclerViewAdapter.registerRenderer(...); /* you can use several types of cells */
For each item, you should to implement a ViewRenderer, ViewHolder, SomeModel:
ViewHolder - it is a simple view holder of recycler view.
SomeModel - it is your model with ItemModel
interface
public class SomeViewRenderer extends ViewRenderer<SomeModel, SomeViewHolder> {
public SomeViewRenderer(final int type, final Context context) {
super(type, context);
}
@Override
public void bindView(@NonNull final SomeModel model, @NonNull final SomeViewHolder holder) {
holder.mTitle.setText(model.getTitle());
}
@NonNull
@Override
public SomeViewHolder createViewHolder(@Nullable final ViewGroup parent) {
return new SomeViewHolder(LayoutInflater.from(getContext()).inflate(R.layout.some_item, parent, false));
}
}
For more details you can look documentations.
I am using the following code in such cases:
obj, created = Model.objects.get_or_create(id=some_id)
if not created:
resp= "It was created"
else:
resp= "OK"
obj.save()
:set runtimepath?
This lists the path of all plugins loaded when a file is opened with Vim.
Use cursors.
A cursor can be thought of like a buffered reader, when reading through a document. If you think of each row as a line in a document, then you would read the next line, perform your operations, and then advance the cursor.
Ask this questions yourself? And you will decide your DB selection.
Also, you can use shelljs
plugin.
It's easy and it's cross-platform.
Install command:
npm install [-g] shelljs
What is shellJS
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
An example of how it works:
var shell = require('shelljs');
if (!shell.which('git')) {
shell.echo('Sorry, this script requires git');
shell.exit(1);
}
// Copy files to release dir
shell.rm('-rf', 'out/Release');
shell.cp('-R', 'stuff/', 'out/Release');
// Replace macros in each .js file
shell.cd('lib');
shell.ls('*.js').forEach(function (file) {
shell.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);
shell.sed('-i', /^.*REMOVE_THIS_LINE.*$/, '', file);
shell.sed('-i', /.*REPLACE_LINE_WITH_MACRO.*\n/, shell.cat('macro.js'), file);
});
shell.cd('..');
// Run external tool synchronously
if (shell.exec('git commit -am "Auto-commit"').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Also, you can use from the command line:
$ shx mkdir -p foo
$ shx touch foo/bar.txt
$ shx rm -rf foo
Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.
If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.
For more info on these techniques, please click here to refer the article
Lets say your data is -
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
You can use the data.items()
method to get the dictionary elements. Note, in django templates we do NOT put ()
. Also some users mentioned values[0]
does not work, if that is the case then try values.items
.
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Am pretty sure you can extend this logic to your specific dict.
To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.
return render_to_response('some_page.html', {'data': sorted(data.items())})
In template file:
{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}
I'm rather shocked that this has not been answered since the solution is very simple.
As mentioned in previous posts, you would not want to convert it using C#, but just once. This is easy to do with PuTTYGen.
Enjoy!
you have done it the correct way using
curl_setopt($ch, CURLOPT_POSTFIELDS,$body);
but i notice your missing
curl_setopt($ch, CURLOPT_POST,1);
would this work?
cat requirements.txt | while read x; do conda install "$x" -p ./lib ;done
or
conda install --file requirements.txt -p ./lib
Forward port of .live()
for jQuery >= 1.9
Avoids refactoring JS dependencies on .live()
Uses optimized DOM selector context
/**
* Forward port jQuery.live()
* Wrapper for newer jQuery.on()
* Uses optimized selector context
* Only add if live() not already existing.
*/
if (typeof jQuery.fn.live == 'undefined' || !(jQuery.isFunction(jQuery.fn.live))) {
jQuery.fn.extend({
live: function (event, callback) {
if (this.selector) {
jQuery(document).on(event, this.selector, callback);
}
}
});
}
Space char is hexadecimal 0x20, decimal 32 and octal \040.
>>> SPACE = 0x20
>>> a = chr(SPACE)
>>> type(a)
<class 'str'>
>>> print(f"'{a}'")
' '
The best way to go about it would be to get a SynchronizationContext
from the UI thread and use it. This class abstracts marshalling calls to other threads, and makes testing easier (in contrast to using WPF's Dispatcher
directly). For example:
class MyViewModel
{
private readonly SynchronizationContext _syncContext;
public MyViewModel()
{
// we assume this ctor is called from the UI thread!
_syncContext = SynchronizationContext.Current;
}
// ...
private void watcher_Changed(object sender, FileSystemEventArgs e)
{
_syncContext.Post(o => DGAddRow(crp.Protocol, ft), null);
}
}
put your CA & root certificate in /usr/share/ca-certificate or /usr/local/share/ca-certificate. Then
dpkg-reconfigure ca-certificates
or even reinstall ca-certificate package with apt-get.
After doing this your certificate is collected into system's DB: /etc/ssl/certs/ca-certificates.crt
Then everything should be fine.
Substrings with ${variablename:0:5}
are a bash feature, not available in basic shells. Are you sure you're running this under bash? Check the shebang line (at the beginning of the script), and make sure it's #!/bin/bash
, not #!/bin/sh
. And make sure you don't run it with the sh
command (i.e. sh scriptname
), since that overrides the shebang.
You can also invoke cmake itself to do this in a cross-platform way:
cmake -E env EnvironmentVariableName="Hello World" cmake ..
env [--unset=NAME]... [NAME=VALUE]... COMMAND [ARG]...
Run command in a modified environment.
Just be aware that this may only work the first time. If CMake re-configures with one of the consecutive builds (you just call e.g. make
, one CMakeLists.txt
was changed and CMake runs through the generation process again), the user defined environment variable may not be there anymore (in comparison to system wide environment variables).
So I transfer those user defined environment variables in my projects into a CMake cached variable:
cmake_minimum_required(VERSION 2.6)
project(PrintEnv NONE)
if (NOT "$ENV{EnvironmentVariableName}" STREQUAL "")
set(EnvironmentVariableName "$ENV{EnvironmentVariableName}" CACHE INTERNAL "Copied from environment variable")
endif()
message("EnvironmentVariableName = ${EnvironmentVariableName}")
Reference
The optimal algorithm uses n+log n-2 comparisons. Think of elements as competitors, and a tournament is going to rank them.
First, compare the elements, as in the tree
|
/ \
| |
/ \ / \
x x x x
this takes n-1 comparisons and each element is involved in comparison at most log n times. You will find the largest element as the winner.
The second largest element must have lost a match to the winner (he can't lose a match to a different element), so he's one of the log n elements the winner has played against. You can find which of them using log n - 1 comparisons.
The optimality is proved via adversary argument. See https://math.stackexchange.com/questions/1601 or http://compgeom.cs.uiuc.edu/~jeffe/teaching/497/02-selection.pdf or http://www.imada.sdu.dk/~jbj/DM19/lb06.pdf or https://www.utdallas.edu/~chandra/documents/6363/lbd.pdf
I wrote my own FactoryBean which instantiates an ObjectMapper (simplified version):
public class ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>{
@Override
public ObjectMapper getObject() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
return mapper;
}
@Override
public Class<?> getObjectType() {
return ObjectMapper.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
And the usage in the spring configuration:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
With : i << 2
const data = context.getImageData(x, y, width, height).data;
const pixels = [];
for (let i = 0, dx = 0; dx < data.length; i++, dx = i << 2) {
if (data[dx+3] <= 8)
console.log("transparent x= " + i);
}
Additionally, if you want to use the filter in your controller the same way you do it here:
<div ng-repeat="item in items | filter:criteriaMatch(criteria)">
{{ item }}
</div>
You could do something like:
var filteredItems = $scope.$eval('items | filter:filter:criteriaMatch(criteria)');
What worked for me was using the $setSubmitted
function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
Note that there is a very simple solution.
Download the software from http://www.microsoft.com/en-us/download/details.aspx?id=44266 and install it.
Find the installing directory, it is something like "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python"
Change the directory name "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0" to "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC"
Add a new environment variable "VS90COMNTOOLS" and its value is "C:\Users\USER_NAME\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\VC\VC"
Now everything is OK.
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
In nano 2.2.6 the line in ~/.nanorc to do this seems to be
set tabsize 4
Setting tabspace gave me the error: 'Unknown flag "tabspace"'
None of the above answers gave me any guidelines so I had to spend two hours learning about Groovy Methods.
I wanted be able to go against a production, sandbox and local environment. Because I'm lazy, I only wanted to change the URL at one place. Here is what I came up with:
flavorDimensions 'environment'
productFlavors {
production {
def SERVER_HOST = "evil-company.com"
buildConfigField 'String', 'API_HOST', "\"${SERVER_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${SERVER_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${SERVER_HOST}/\""
dimension 'environment'
}
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', "\"${LOCAL_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${LOCAL_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${LOCAL_HOST}/\""
applicationIdSuffix ".dev"
}
}
Alternative syntax, because you can only use ${variable}
with double quotes in Groovy Methods.
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', '"' + LOCAL_HOST + '"'
buildConfigField 'String', 'API_URL', '"https://' + LOCAL_HOST + '/api/v1/"'
buildConfigField 'String', 'WEB_URL', '"https://' + LOCAL_HOST + '"'
applicationIdSuffix ".dev"
}
What was hard for me to grasp was that strings needs to be declared as strings surrounded by quotes. Because of that restriction, I couldn't use reference API_HOST
directly, which was what I wanted to do in the first place.
the provided solutions seem a little complex? this might help:
https://msdn.microsoft.com/en-us/library/ms174420.aspx
select
mystuff,
DATEPART ( year, MyDateColumn ) as yearnr,
DATEPART ( week, MyDateColumn ) as weeknr
from mytable
group by ...etc
A string in different languages including C sharp and PHP is also considered an array of characters.
Knowing that in theory array operations should be faster than string ones you could do,
$foo = "bar";
$lastChar = strlen($foo) -1;
echo $foo[$lastChar];
$firstChar = 0;
echo $foo[$firstChar];
However, standard array functions like
count();
will not work on a string.
Johannes Sixt from the [email protected] mailing list suggested using following command line arguments:
git apply --ignore-space-change --ignore-whitespace mychanges.patch
This solved my problem.
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
No it's not the instance of anything, instanceof will always be false.
A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.
e.g. to flatten all but the last two dimensions:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.
$("#btn_screenshot").click(function(){_x000D_
element_to_png("container", "testhtmltocanvasimg");_x000D_
});_x000D_
_x000D_
_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
console.log("element_to_png called for element id " + srcElementID);_x000D_
html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
var myImage = canvas.toDataURL("image/png");_x000D_
$("#"+targetIMGid).attr("src", myImage);_x000D_
console.log("html2canvas completed. png rendered to " + targetIMGid);_x000D_
});_x000D_
}
_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
<img src="" id="testhtmltocanvasimg">_x000D_
</div>
_x000D_
I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!
You would simply need to do this in your onClick
:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
I don't know from where you saw that you need DialogFragment for simply showing an alert.
Hope this helps.
A simple way that solve my problem was:
npm cache clear
npm or a process controlled by it is watching too many files. Updating max_user_watches on the build node can fix it forever. For debian put the following on terminal:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
If you want know how Increase the amount of inotify watchers only click on link.
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
From the 18.03 docs:
I want to connect from a container to a service on the host
The host has a changing IP address (or none if you have no network access). From 18.03 onwards our recommendation is to connect to the special DNS name
host.docker.internal
, which resolves to the internal IP address used by the host.The gateway is also reachable as
gateway.docker.internal
.
EXAMPLE: Here's what I use for my MySQL connection string inside my container to access the MySQL instance on my host:
mysql://host.docker.internal:3306/my_awesome_database
Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error
fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported
I solved the problem by changing the line that generated the output file from:
out-file -FilePath GITVersion.h -InputObject $result
to:
out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result
If you're looking for "in-place" editing of a ListView
's contents (specifically the subitems of a ListView in details view mode), you'll need to implement this yourself, or use a third-party control.
By default, the best you can achieve with a "standard" ListView
is to set it's LabelEdit
property to true to allow the user to edit the text of the first column of the ListView
(assuming you want to allow a free-format text edit).
Some examples (including full source-code) of customized ListView
's that allow "in-place" editing of sub-items are:
why is my java logging not working
provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.
You might want to use jQuery's .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.
As many mentioned the recursive approach, this is the function you can pass the searched name and the property to begin with to:
public static void loopAttributes(PropertyInfo prop, string targetAttribute, object tempObject)
{
foreach (PropertyInfo nestedProp in prop.PropertyType.GetProperties())
{
if(nestedProp.Name == targetAttribute)
{
//found the matching attribute
}
loopAttributes(nestedProp, targetAttribute, prop.GetValue(tempObject);
}
}
//in the main function
foreach (PropertyInfo prop in rootObject.GetType().GetProperties())
{
loopAttributes(prop, targetAttribute, rootObject);
}
A couple of concerns for me with respect to using string escape in onClick and as the number of arguments grow, it will become cumbersome to maintain.
The following approach will have a one hop - On click - take the control to a handler method and handler method, based on the event object, can deduct the click event and corresponding object.
It also provides a cleaner way to add more arguments and have more flexibility.
<button type="button"
className="btn btn-default"
onClick="invoke"
name='gotoNode'
data-arg1='1234'>GotoNode</button>
In the JavaScript layer:
invoke = (event) => {
let nameOfFunction = this[event.target.name];
let arg1 = event.target.getAttribute('data-arg1');
// We can add more arguments as needed...
window[nameOfFunction](arg1)
// Hope the function is in the window.
// Else the respective object need to be used
})
}
The advantage here is that we can have as many arguments (in above example, data-arg1, data-arg2, etc.) as needed.
Encapsulation is used for 2 main reasons:
1.) Data hiding & protecting (the user of your class can't modify the data except through your provided methods).
2.) Combining the data and methods used to manipulate the data together into one entity (capsule). I think that the second reason is the answer your interviewer wanted to hear.
On the other hand, abstraction is needed to expose only the needed information to the user, and hiding unneeded details (for example, hiding the implementation of methods, so that the user is not affected if the implementation is changed).
file = open('Failed.py', 'w')
file.write('whatever')
file.close()
Here is a more pythonic version, which automatically closes the file, even if there was an exception in the wrapped block:
with open('Failed.py', 'w') as file:
file.write('whatever')
1> You can add image from layout itself:
<ImageView
android:id="@+id/iv_your_image"
android:layout_width="wrap_content"
android:layout_height="25dp"
android:background="@mipmap/your_image"
android:padding="2dp" />
OR
2> Programmatically in java class:
ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
OR for fragments:
View rowView= inflater.inflate(R.layout.your_layout, null, true);
ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
ivYouImage.setImageResource(R.mipmap.ic_changeImage);
For Access 2013, you could just do
Sendkeys "%fic"
This is the same as typing ALT, F, I, C on your keyboard.
It's probably a different sequence of letters for different versions, but the "%" symbol means "ALT", so keep that in the code. you may just need to change the letters, depending on what letters appear when you press ALT
The %
operator is for integers. You're looking for the fmod()
function.
#include <cmath>
int main()
{
double x = 6.3;
double y = 2.0;
double z = std::fmod(x,y);
}
Update (1/10/2018):
For Spark 2.2+ the best way to do this is probably using the to_date
or to_timestamp
functions, which both support the format
argument. From the docs:
>>> from pyspark.sql.functions import to_timestamp
>>> df = spark.createDataFrame([('1997-02-28 10:30:00',)], ['t'])
>>> df.select(to_timestamp(df.t, 'yyyy-MM-dd HH:mm:ss').alias('dt')).collect()
[Row(dt=datetime.datetime(1997, 2, 28, 10, 30))]
Original Answer (for Spark < 2.2)
It is possible (preferrable?) to do this without a udf:
from pyspark.sql.functions import unix_timestamp, from_unixtime
df = spark.createDataFrame(
[("11/25/1991",), ("11/24/1991",), ("11/30/1991",)],
['date_str']
)
df2 = df.select(
'date_str',
from_unixtime(unix_timestamp('date_str', 'MM/dd/yyy')).alias('date')
)
print(df2)
#DataFrame[date_str: string, date: timestamp]
df2.show(truncate=False)
#+----------+-------------------+
#|date_str |date |
#+----------+-------------------+
#|11/25/1991|1991-11-25 00:00:00|
#|11/24/1991|1991-11-24 00:00:00|
#|11/30/1991|1991-11-30 00:00:00|
#+----------+-------------------+
The three best way to do it using a single line of code
import cv2
import numpy as np
img = cv2.imread('Imgs/Saint_Roch_new/data/Point_4_Face.jpg')
dim = (256, 256)
resizedLena = cv2.resize(img, dim, interpolation = cv2.INTER_LINEAR)
X, Y = resizedLena, resizedLena
# Methode 1: Using Numpy (hstack, vstack)
Fusion_Horizontal = np.hstack((resizedLena, Y, X))
Fusion_Vertical = np.vstack((newIMG, X))
cv2.imshow('Fusion_Vertical using vstack', Fusion_Vertical)
cv2.waitKey(0)
# Methode 2: Using Numpy (contanate)
Fusion_Vertical = np.concatenate((resizedLena, X, Y), axis=0)
Fusion_Horizontal = np.concatenate((resizedLena, X, Y), axis=1)
cv2.imshow("Fusion_Horizontal usung concatenate", Fusion_Horizontal)
cv2.waitKey(0)
# Methode 3: Using OpenCV (vconcat, hconcat)
Fusion_Vertical = cv2.vconcat([resizedLena, X, Y])
Fusion_Horizontal = cv2.hconcat([resizedLena, X, Y])
cv2.imshow("Fusion_Horizontal Using hconcat", Fusion_Horizontal)
cv2.waitKey(0)
I was unable to use the JSONConvert method suggested by xhafan
In .Net 4.5 even after adding the "System.Web.Extensions" assembly reference I was still unable to access the JSONConvert.
However, once you add the reference you can get the same string print out using:
JavaScriptSerializer js = new JavaScriptSerializer();
string jsonstring = js.Serialize(yourClassObject);
The easiest way to calculate number of neurons in one layer is: Param value / (number of units * 4)
For example in Paul Lo's answer , number of neurons in one layer is 264710 / (514 * 4 ) = 130
The file extension .img
does not say anything about its content.
Most commonly .img files are a floppy/CD/DVD/ISO image, a filesystem image, a disk image, or even just (custom) binary data.
In case it is an CD/DVD image or a specific filesystem image (like fat, ntfs, ...) you can open these files with 7-Zip.
On *nix based systems also the file
tool or (libmagic) could help you find out what it is.
More input types and details found here on google website
Once a DataTable
has been filled, you can't change the type of a column.
Your best option in this scenario is to add an Int32
column to the DataTable
before filling it:
dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);
Then you can clone the data from your original table to the new table:
DataTable dataTableClone = dataTable.Clone();
Here's a post with more details.
Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service
Most of the examples above show how to reuse an existing comparable object in the compareTo function. If you would like to implement your own compareTo when you want to compare two objects of the same class, say an AirlineTicket object that you would like to sort by price(less is ranked first), followed by number of stopover (again, less is ranked first), you would do the following:
class AirlineTicket implements Comparable<Cost>
{
public double cost;
public int stopovers;
public AirlineTicket(double cost, int stopovers)
{
this.cost = cost; this.stopovers = stopovers ;
}
public int compareTo(Cost o)
{
if(this.cost != o.cost)
return Double.compare(this.cost, o.cost); //sorting in ascending order.
if(this.stopovers != o.stopovers)
return this.stopovers - o.stopovers; //again, ascending but swap the two if you want descending
return 0;
}
}
The "problem" with the media library in wordpress is always interesting. Check the following plugin to solve this: WordPress Real Media Library. WP RML creates a virtual folder structure based on an own taxonomy.
It allows you to organize your wordpress media library in a nice way with folders. It is easy to use, just drag&drop your files and move it to a specific folder. Filter when inserting media or create a gallery from a folder.
Turn your WordPress media library to the next level with folders / categories. Get organized with thousands of images.
RML (Real Media Library) is one of the most wanted media wordpress plugins. It is easy to use and it allows you to organize your thousands of images in folders. It is similar to wordpress categories like in the posts.
Use your mouse (or touch) to drag and drop your files. Create, rename, delete or reorder your folders If you want to select a image from the “Select a image”-dialog (e. g. featured image) you can filter when inserting media. Just install this plugin and it works fine with all your image and media files. It also supports multisite.
If you buy, you get: Forever FREE updates and high quality and fast support.
From the product description i can quote. If you want to try the plugin, there is also a demo on the plugin page.
A long time ago I started to open this thread and now there is a usable extension plugin for Real Media Library which allows you to physically manage your uploads folder.
Check out this plugin: https://wordpress.org/plugins/physical-custom-upload-folder/
Do you know the wp-content/uploads folder? There, the files are stored in year/month based folders. This can be a very complicated and mass process, especially when you are working with a FTP client like FileZilla.
Moving already uploaded files: This plugin does not allow to move the files physically when you move a file in the Real Media Library because WordPress uses the URL's in different places. It is very hard to maintain such a process. So this only works for new uploads.
(Please read on if you are developer) I as developer thought about a solution about this. Does it make sense to organize the uploads on server, too? Yes, i think. Many people ask to organize it physically. I think also that the process of moving files on server and updating the image references is very hard to develop. There are many plugins out now, which are saving the URLs in their own-created database-tables.
Please check this thread where i explained the problem: https://wordpress.stackexchange.com/questions/226675/physical-organization-of-wordpress-media-library-real-media-library-plugin
One can simply use the pydoc.locate
function.
from pydoc import locate
my_class = locate("module.submodule.myclass")
instance = my_class()
$ git branch --set-upstream-to=heroku/master master
and
$ git pull
worked for me!
I know this question is old, but I stumbled upon it looking for a pythonic way to get current domain.
def myview(request):
domain = request.build_absolute_uri('/')[:-1]
# that will build the complete domain: http://foobar.com
It's possible using the button
element.
<button name="name" value="value" type="submit">Sök</button>
From the W3C page on button
:
Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.
Solution
It is possible to use str_detect
of the stringr
package included in the tidyverse
package. str_detect
returns True
or False
as to whether the specified vector contains some specific string. It is possible to filter using this boolean value. See Introduction to stringr for details about stringr
package.
library(tidyverse)
# - Attaching packages -------------------- tidyverse 1.2.1 -
# ? ggplot2 2.2.1 ? purrr 0.2.4
# ? tibble 1.4.2 ? dplyr 0.7.4
# ? tidyr 0.7.2 ? stringr 1.2.0
# ? readr 1.1.1 ? forcats 0.3.0
# - Conflicts --------------------- tidyverse_conflicts() -
# ? dplyr::filter() masks stats::filter()
# ? dplyr::lag() masks stats::lag()
mtcars$type <- rownames(mtcars)
mtcars %>%
filter(str_detect(type, 'Toyota|Mazda'))
# mpg cyl disp hp drat wt qsec vs am gear carb type
# 1 21.0 6 160.0 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4
# 2 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4 Mazda RX4 Wag
# 3 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1 Toyota Corolla
# 4 21.5 4 120.1 97 3.70 2.465 20.01 1 0 3 1 Toyota Corona
The good things about Stringr
We should use rather stringr::str_detect()
than base::grepl()
. This is because there are the following reasons.
stringr
package start with the prefix str_
, which makes the code easier to read.stringr
package is always the data.frame (or value), then comes the parameters.(Thank you Paolo)object <- "stringr"
# The functions with the same prefix `str_`.
# The first argument is an object.
stringr::str_count(object) # -> 7
stringr::str_sub(object, 1, 3) # -> "str"
stringr::str_detect(object, "str") # -> TRUE
stringr::str_replace(object, "str", "") # -> "ingr"
# The function names without common points.
# The position of the argument of the object also does not match.
base::nchar(object) # -> 7
base::substr(object, 1, 3) # -> "str"
base::grepl("str", object) # -> TRUE
base::sub("str", "", object) # -> "ingr"
Benchmark
The results of the benchmark test are as follows. For large dataframe, str_detect
is faster.
library(rbenchmark)
library(tidyverse)
# The data. Data expo 09. ASA Statistics Computing and Graphics
# http://stat-computing.org/dataexpo/2009/the-data.html
df <- read_csv("Downloads/2008.csv")
print(dim(df))
# [1] 7009728 29
benchmark(
"str_detect" = {df %>% filter(str_detect(Dest, 'MCO|BWI'))},
"grepl" = {df %>% filter(grepl('MCO|BWI', Dest))},
replications = 10,
columns = c("test", "replications", "elapsed", "relative", "user.self", "sys.self"))
# test replications elapsed relative user.self sys.self
# 2 grepl 10 16.480 1.513 16.195 0.248
# 1 str_detect 10 10.891 1.000 9.594 1.281
Just wanted to add another simple way someone can sort the the WPF ListView
void SortListView(ListView listView)
{
IEnumerable listView_items = listView.Items.SourceCollection;
List<MY_ITEM_CLASS> listView_items_to_list = listView_items.Cast<MY_ITEM_CLASS>().ToList();
Comparer<MY_ITEM_CLASS> scoreComparer = Comparer<MY_ITEM_CLASS>.Create((first, second) => first.COLUMN_NAME.CompareTo(second.COLUMN_NAME));
listView_items_to_list.Sort(scoreComparer);
listView.ItemsSource = null;
listView.Items.Clear();
listView.ItemsSource = listView_items_to_list;
}
@Html.TextArea("txtNotes", "", 4, 0, new { @class = "k-textbox", style = "width: 100%; height: 100%;" })
The Eclipse (software) page on Wikipedia summarizes it pretty well:
Releases
Since 2006, the Eclipse Foundation has coordinated an annual Simultaneous Release. Each release includes the Eclipse Platform as well as a number of other Eclipse projects. Until the Galileo release, releases were named after the moons of the solar system.
So far, each Simultaneous Release has occurred at the end of June.
Release Main Release Platform version Projects Photon 27 June 2018 4.8 Oxygen 28 June 2017 4.7 Neon 22 June 2016 4.6 Mars 24 June 2015 4.5 Mars Projects Luna 25 June 2014 4.4 Luna Projects Kepler 26 June 2013 4.3 Kepler Projects Juno 27 June 2012 4.2 Juno Projects Indigo 22 June 2011 3.7 Indigo projects Helios 23 June 2010 3.6 Helios projects Galileo 24 June 2009 3.5 Galileo projects Ganymede 25 June 2008 3.4 Ganymede projects Europa 29 June 2007 3.3 Europa projects Callisto 30 June 2006 3.2 Callisto projects Eclipse 3.1 28 June 2005 3.1 Eclipse 3.0 28 June 2004 3.0
To summarize, Helios, Galileo, Ganymede, etc are just code names for versions of the Eclipse platform (personally, I'd prefer Eclipse to use traditional version numbers instead of code names, it would make things clearer and easier). My suggestion would be to use the latest version, i.e. Eclipse Oxygen (4.7) (in the original version of this answer, it said "Helios (3.6.1)").
On top of the "platform", Eclipse then distributes various Packages (i.e. the "platform" with a default set of plugins to achieve specialized tasks), such as Eclipse IDE for Java Developers, Eclipse IDE for Java EE Developers, Eclipse IDE for C/C++ Developers, etc (see this link for a comparison of their content).
To develop Java Desktop applications, the Helios release of Eclipse IDE for Java Developers should suffice (you can always install "additional plugins" if required).
Just to update these answers slightly with the new literal syntax in iOS 6--you can use Paths = @[indexPath] for a single object, or Paths = @[indexPath1, indexPath2,...] for multiple objects.
Personally, I've found the literal syntax for arrays and dictionaries to be immensely useful and big time savers. It's just easier to read, for one thing. And it removes the need for a nil at the end of any multi-object list, which has always been a personal bugaboo. We all have our windmills to tilt with, yes? ;-)
Just thought I'd throw this into the mix. Hope it helps.
\begin{equation}
\resizebox{.9\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
or
\begin{equation}
\resizebox{.8\hsize}{!}{$A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z$}
\end{equation}
As far as I know, F11 or F12 doesn't work, and nor does Right Ctrl + F12.
Hit Left Ctrl + F12, or Home, or PageUp, (not NUMPAD 7 or NUMPAD 9 like the website says) to rotate the emulator.
DATA = { u'spam': u'eggs', u'foo': frozenset([u'Gah!']), u'bar': { u'baz': 97 },
u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])]}
def convert(data):
if isinstance(data, basestring):
return str(data)
elif isinstance(data, collections.Mapping):
return dict(map(convert, data.iteritems()))
elif isinstance(data, collections.Iterable):
return type(data)(map(convert, data))
else:
return data
print DATA
print convert(DATA)
# Prints:
# {u'list': [u'list', (True, u'Maybe'), set([u'and', u'a', u'set', 1])], u'foo': frozenset([u'Gah!']), u'bar': {u'baz': 97}, u'spam': u'eggs'}
# {'bar': {'baz': 97}, 'foo': frozenset(['Gah!']), 'list': ['list', (True, 'Maybe'), set(['and', 'a', 'set', 1])], 'spam': 'eggs'}
Assumptions:
data.encode('utf-8')
rather than str(data)
if you need an explicit encoding).If you need to support other container types, hopefully it's obvious how to follow the pattern and add cases for them.
If you just need this for debugging to see how the XML looks like, then instead of print(xml.etree.ElementTree.tostring(e))
you can use dump
like this:
xml.etree.ElementTree.dump(e)
And this works both with Element
and ElementTree
objects as e
, so there should be no need for getroot
.
The documentation of dump
says:
xml.etree.ElementTree.dump(elem)
Writes an element tree or element structure to
sys.stdout
. This function should be used for debugging only.The exact output format is implementation dependent. In this version, it’s written as an ordinary XML file.
elem
is an element tree or an individual element.Changed in version 3.8: The
dump()
function now preserves the attribute order specified by the user.
if diff is a moment
var diff = moment(20111031) - moment(20111010);
var formated1 = moment(diff).format("hh:mm:ss");
console.log("format 1: "+formated1);
The rules for turning on the carry flag in binary/integer math are two:
The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)
The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).
In unsigned arithmetic, watch the carry flag to detect errors.
In signed arithmetic, the carry flag tells you nothing interesting.
The rules for turning on the overflow flag in binary/integer math are two:
If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)
If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)
Otherwise the "overflow" flag is turned off
Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.
If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.
If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.
For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt
If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me
Here's an example with a Windows path:
docker run -P -it --name organizr --mount src="/c/Users/MyUserName/AppData/Roaming/DockerConfigs/Organizr",dst=/config,type=bind organizrtools/organizr-v2:latest
As a side note, during all of this hair pulling, having to wrestle with figuring out, and retyping paths over and over and over again, I decided to whip up a small AutoHotkey
script to convert a Windows path to a "Docker Windows" formatted path. This way all I have to do is copy any Windows path that I want to use as a mount point to the clipboard, press the "Apps Key" on the keyboard, and it'll format it into a path format that Docker appreciates.
For example:
Copy this to your clipboard:
C:\Users\My PC\AppData\Roaming\DockerConfigs\Organizr
press the Apps Key
while the cursor is where you want it on the command-line, and it'll paste this there:
"/c/Users/My PC/AppData/Roaming/DockerConfigs/Organizr"
Saves a lot to time for me. Here it is for anyone else who may find it useful.
; --------------------------------------------------------------------------------------------------------------
;
; Docker Utility: Convert a Windows Formatted Path to a Docker Formatter Path
; Useful for (example) when mounting Windows volumes via the command-line.
;
; By: J. Scott Elblein
; Version: 1.0
; Date: 2/5/2019
;
; Usage: Cut or Copy the Windows formatted path to the clipboard, press the AppsKey on your keyboard
; (usually right next to the Windows Key), it'll format it into a 'docker path' and enter it
; into the active window. Easy example usage would be to copy your intended volume path via
; Explorer, place the cursor after the "-v" in your Docker command, press the Apps Key and
; then it'll place the formatted path onto the line for you.
;
; TODO:: I may or may not add anything to this depending on needs. Some ideas are:
;
; - Add a tray menu with the ability to do some things, like just replace the unformatted path
; on the clipboard with the formatted one rather than enter it automatically.
; - Add 'smarter' handling so the it first confirms that the clipboard text is even a path in
; the first place. (would need to be able to handle Win + Mac + Linux)
; - Add command-line handling so the script doesn't need to always be in the tray, you could
; just pass the Windows path to the script, have it format it, then paste and close.
; Also, could have it just check for a path on the clipboard upon script startup, if found
; do it's job, then exit the script.
; - Add an 'all-in-one' action, to copy the selected Windows path, and then output the result.
; - Whatever else comes to mind.
;
; --------------------------------------------------------------------------------------------------------------
#NoEnv
SendMode Input
SetWorkingDir %A_ScriptDir%
AppsKey::
; Create a new var, store the current clipboard contents (should be a Windows path)
NewStr := Clipboard
; Rip out the first 2 chars (should be a drive letter and colon) & convert the letter to lowercase
; NOTE: I could probably replace the following 3 lines with a regexreplace, but atm I'm lazy and in a rush.
tmpVar := SubStr(NewStr, 1, 2)
StringLower, tmpVar, tmpVar
; Replace the uppercase drive letter and colon with the lowercase drive letter and colon
NewStr := StrReplace(NewStr, SubStr(NewStr, 1, 2), tmpVar)
; Replace backslashes with forward slashes
NewStr := StrReplace(NewStr, "\", "/")
; Replace all colons with nothing
NewStr := StrReplace(NewStr, ":", "")
; Remove the last char if it's a trailing forward slash
NewStr := RegExReplace(NewStr, "/$")
; Append a leading forward slash if not already there
if RegExMatch(NewStr, "^/") == 0
NewStr := "/" . NewStr
; If there are any spaces in the path ... wrap in double quotes
if RegExMatch(NewStr, " ") > 0
NewStr := """" . NewStr . """"
; Send the result to the active window
SendInput % NewStr
If you want to do something like the following example, you'd have to use nested if
s.
If percentage is greater than or equal to 93%, then corresponding value in B should be 4 and if the percentage is greater than or equal to 90% and less than 92%, then corresponding value in B to be 3.7, etc.
Here's how you'd do it:
=IF(A2>=93%, 4, IF(A2>=90%, 3.7,IF(A2>=87%,3.3,0)))
instead of creating too many complicated functions and methods what I do is I create an event listener and automatically have mount and unmount done for me without having to worry about doing it manually. Here is an example.
//componentDidMount
useEffect( () => {
window.addEventListener("load", pageLoad);
//component will unmount
return () => {
window.removeEventListener("load", pageLoad);
}
});
now that this part is done I just run anything I want from the pageLoad function like this.
const pageLoad = () =>{
console.log(I was mounted and unmounted automatically :D)}
Php has an inbuilt JSON Serialising function.
json_encode
Please use that if you can and don't suffer Not Invented Here syndrome.
%__CD__%
, %CD%
, %=C:%
There's also another dynamic variable %__CD__%
which points to the current directory but alike %CD%
it has a backslash at the end.
This can be useful if you want to append files to the current directory.
With %=C:%
%=D:%
you can access the last accessed directory for the corresponding drive. If the variable is not defined you haven't accessed the drive on the current cmd session.
And %__APPDIR__%
expands to the executable that runs the current script a.k.a. cmd.exe
directory.
You may also have a look at some NIO application framework such as:
The documentation for focusout says (emphasis mine):
The
focusout
event is sent to an element when it, or any element inside of it, loses focus. This is distinct from theblur
event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).
The same distinction exists between the focusin and focus events.
Here is the code with line 156, it has try and catch above it
/// <summary>
/// Execute a SQL Query statement, using the default SQL connection for the application
/// </summary>
/// <param name="query">SQL query to execute</param>
/// <returns>DataTable of results</returns>
public static DataTable Query(string query)
{
DataTable results = new DataTable();
string configConnectionString = "ApplicationServices";
System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
System.Configuration.ConnectionStringSettings connString;
if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
{
connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];
if (connString != null)
{
try
{
using (SqlConnection conn = new SqlConnection(connString.ToString()))
using (SqlCommand cmd = new SqlCommand(query, conn))
using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
dataAdapter.Fill(results);
return results;
}
catch (Exception ex)
{
throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
}
}
else
{
throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
}
}
else
{
throw new SqlException(string.Format("No connection strings found in Web.config file."));
}
}
In Ubuntu 18.04 the QtCreator examples and API docs missing, This is my way to solve this problem, should apply to almost every Ubuntu release.
For QtCreator and Examples and API Docs:
sudo apt install `apt-cache search 5-examples | grep qt | grep example | awk '{print $1 }' | xargs `
sudo apt install `apt-cache search 5-doc | grep "Qt 5 " | awk '{print $1}' | xargs`
sudo apt-get install build-essential qtcreator qt5-default
If something is also missing, then:
sudo apt install `apt-cache search qt | grep 5- | grep ^qt | awk '{print $1}' | xargs `
Hope to be helpful.
Also posted in Ask Ubuntu: https://askubuntu.com/questions/450983/ubuntu-14-04-qtcreator-qt5-examples-missing
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? DISABLE TRIGGER ALL'
EXEC sp_MSForEachTable 'DELETE FROM ?'
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
EXEC sp_MSForEachTable 'ALTER TABLE ? ENABLE TRIGGER ALL'
EXEC sp_MSFOREACHTABLE 'SELECT * FROM ?'
GO
Best Way to Refresh Adapter/ListView on Android
Not only calling notifyDataSetChanged() will refresh the ListView data, setAdapter()
must be called before to load the information correctly:
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
If you have the .dSYM and the .crash file in the same sub-folder, these are the steps you can take:
$ atos -arch arm64 -o TheElements.app.dSYM/Contents/Resources/DWARF/TheElements -l 0x1000e4000 0x00000001000effdc
-[AtomicElementViewController myTransitionDidStop:finished:context:]
Authoritative source: https://developer.apple.com/library/content/technotes/tn2151/_index.html#//apple_ref/doc/uid/DTS40008184-CH1-SYMBOLICATE_WITH_ATOS
I believe all the existing answers contain the relevant information, but I would like to summarize.
The response object that is returned by requests
get and post operations contains two useful attributes:
response.text
- Contains str
with the response text.response.content
- Contains bytes
with the raw response content.You should choose one or other of these attributes depending on the type of response you expect.
response.text
response.content
.When writing responses to file you need to use the open function with the appropriate file write mode.
"w"
- plain write mode."wb"
- binary write mode.# Request the HTML for this web page:
response = requests.get("https://stackoverflow.com/questions/31126596/saving-response-from-requests-to-file")
with open("response.txt", "w") as f:
f.write(response.text)
# Request the profile picture of the OP:
response = requests.get("https://i.stack.imgur.com/iysmF.jpg?s=32&g=1")
with open("response.jpg", "wb") as f:
f.write(response.content)
The original code should work by using wb
and response.content
:
import requests
files = {'f': ('1.pdf', open('1.pdf', 'rb'))}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
file = open("out.xls", "wb")
file.write(response.content)
file.close()
But I would go further and use the with
context manager for open
.
import requests
with open('1.pdf', 'rb') as file:
files = {'f': ('1.pdf', file)}
response = requests.post("https://pdftables.com/api?&format=xlsx-single",files=files)
response.raise_for_status() # ensure we notice bad responses
with open("out.xls", "wb") as file:
file.write(response.content)
Using Swift and with a specific UIView
object this might help:
func findFirstResponder(inView view: UIView) -> UIView? {
for subView in view.subviews as! [UIView] {
if subView.isFirstResponder() {
return subView
}
if let recursiveSubView = self.findFirstResponder(inView: subView) {
return recursiveSubView
}
}
return nil
}
Just place it in your UIViewController
and use it like this:
let firstResponder = self.findFirstResponder(inView: self.view)
Take note that the result is an Optional value so it will be nil in case no firstResponder was found in the given views subview hierarchy.
Here is a snippet of a helper utility I have. This is namespaced javascript:
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}
You should use this with method detection else fire off an 'alternative' way of doing this. The time is fast approaching when this will be all that is needed. The other methods are hacks.
If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:
git reset hash-of-first-commit
git add -A
git commit --amend
Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.
Other answers deal with the technical aspect of the border-opacity issue, while I'd like to present a hack(pure CSS and HTML only). Basically create a container div, having a border div and then the content div.
<div class="container">
<div class="border-box"></div>
<div class="content-box"></div>
</div>
And then the CSS:(set content border to none, take care of positioning such that border thickness is accounted for)
.container {
width: 20vw;
height: 20vw;
position: relative;
}
.border-box {
width: 100%;
height: 100%;
border: 5px solid black;
position: absolute;
opacity: 0.5;
}
.content-box {
width: 100%;
height: 100%;
border: none;
background: green;
top: 5px;
left: 5px;
position: absolute;
}
Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN
Actual Code which I faced error:
Before changed the code:
if( ds.Tables[0].Rows[0][0] == null ) // Which is not working
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
After changed the code:
if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
{
seqno = 1;
}
else
{
seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
}
Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.
The question is old but I could not find a better solution I post mine here. Find all USB drives but not listing the partitions, thus removing the "part[0-9]" from the results. I ended up doing two grep, the last negates the result:
ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -vE "part[0-9]*$"
This results on my system:
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0
If I only want the partitions I could do:
ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -E "part[0-9]*$"
Where I get:
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part1
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part2
And when I do:
readlink -f /dev/disk/by-path/pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0
I get:
/dev/sdb
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
I read this information from the Java Tutorials.
The OP mentioned SCP, so here's that.
As others have pointed out, SFTP is a confusing since the upload syntax is completely different from the download syntax. It gets marginally easier to remember if you use the same form:
echo 'put LOCALPATH REMOTEPATH' | sftp USER@HOST
echo 'get REMOTEPATH LOCALPATH' | sftp USER@HOST
In reality, this is still a mess, and is why people still use "outdated" commands such as SCP:
scp USER@HOST:REMOTEPATH LOCALPATH
scp LOCALPATH USER@HOST:REMOTEPATH
SCP is secure but dated. It has some bugs that will never be fixed, namely crashing if the server's .bash_profile
emits a message. However, in terms of usability, the devs were years ahead.
onDestroy()
is meant for final cleanup - freeing up resources that you can on your own,closing open connections,readers,writers,etc. If you don't override it, the system does what it has to.
on the other hand, finish()
just lets the system know that the programmer wants the current Activity
to be finished. And hence, it calls up onDestroy()
after that.
Something to note:
it isn't necessary that only a call to finish()
triggers a call to onDestroy()
. No. As we know, the android system is free to kill activities if it feels that there are resources needed by the current Activity
that are needed to be freed.
String str = "a + b - c * d / e < f > g >= h <= i == j";
String reg = "\\s*[a-zA-Z]+";
String[] res = str.split(reg);
for (String out : res) {
if (!"".equals(out)) {
System.out.print(out);
}
}
Output : + - * / < > >= <= ==
You can also calculate correlations for all variables but exclude selected ones, for example:
mtcars <- data.frame(mtcars)
# here we exclude gear and carb variables
cors <- cor(subset(mtcars, select = c(-gear,-carb)))
Also, to calculate correlation between each variable and one column you can use sapply()
# sapply effectively calls the corelation function for each column of mtcars and mtcars$mpg
cors2 <- sapply(mtcars, cor, y=mtcars$mpg)
What about this syntax?
typedef struct
{
int a;
short b;
}
ABCD;
ABCD abc = { abc.a = 5, abc.b = 7 };
Just tested on a Microsoft Visual C++ 2015 and on g++ 6.0.2. Working OK.
You can make a specific macro also if you want to avoid duplicating variable name.
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
As @Hutch pointed out, one of the major limitations of sp_who2
is that it does not take any parameters so you cannot sort or filter it by default. You can save the results into a temp table, but then the you have to declare all the types ahead of time (and remember to DROP TABLE
).
Instead, you can just go directly to the source on master.dbo.sysprocesses
I've constructed this to output almost exactly the same thing that sp_who2
generates, except that you can easily add ORDER BY
and WHERE
clauses to get meaningful output.
SELECT spid,
sp.[status],
loginame [Login],
hostname,
blocked BlkBy,
sd.name DBName,
cmd Command,
cpu CPUTime,
physical_io DiskIO,
last_batch LastBatch,
[program_name] ProgramName
FROM master.dbo.sysprocesses sp
JOIN master.dbo.sysdatabases sd ON sp.dbid = sd.dbid
ORDER BY spid
Vertical alignment doesn't work with floated elements, indeed. That's because float lifts the element from the normal flow of the document. You might want to use other vertical aligning techniques, like the ones based on transform, display: table, absolute positioning, line-height, js (last resort maybe) or even the plain old html table (maybe the first choice if the content is actually tabular). You'll find that there's a heated debate on this issue.
However, this is how you can vertically align YOUR 3 divs:
.wrap{
width: 500px;
overflow:hidden;
background: pink;
}
.left {
width: 150px;
margin-right: 10px;
background: yellow;
display:inline-block;
vertical-align: middle;
}
.left2 {
width: 150px;
margin-right: 10px;
background: aqua;
display:inline-block;
vertical-align: middle;
}
.right{
width: 150px;
background: orange;
display:inline-block;
vertical-align: middle;
}
Not sure why you needed both fixed width, display: inline-block and floating.
This was a helpful question, but could be more so by giving actual code examples. Even the linked article does not actually show an implementation. I, therefore, humbly submit:
In your app.js
file, the top of the file:
var express = require('express')
, http = require('http')
, path = require('path');
app = express(); //IMPORTANT! define the global app variable prior to requiring routes!
var routes = require('./routes');
app.js will not have any reference to app.get()
method. Leave these to be defined in the individual routes files.
routes/index.js
:
require('./main');
require('./users');
and finally, an actual routes file, routes/main.js
:
function index (request, response) {
response.render('index', { title: 'Express' });
}
app.get('/',index); // <-- define the routes here now, thanks to the global app variable
There are errors here :
var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");
The code must change to:
var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");
By the way, there is another error at line 129 :
var createLi.appendChild(createSubList);
Replace it with:
createLi.appendChild(createSubList);
This is the first example in the manual page for mysql_query
:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die
, then I'd suggest trigger_error
.
Well, data.str().c_str()
yields a char const*
but your function Printfunc()
wants to have char*
s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be
void Printfunc(int a, char const* loc, char const* stream)
The alternative might be to turn the char const*
into a char*
but fixing the declaration is preferable:
Printfunc(num, addr, const_cast<char*>(data.str().c_str()));
Use
window.location.hash
to retrieve everything beyond and including the #
a = [2,3,4,5,6,7,8,9,0]
xyz = [0,12,4,6,242,7,9]
set(a) & set(xyz)
set([0, 9, 4, 6, 7])
Based on Yamikep's answer, I found a better and very simple solution which also handles ModelMultipleChoiceField
fields.
Removing field from form.cleaned_data
prevents fields from being saved:
class ReadOnlyFieldsMixin(object):
readonly_fields = ()
def __init__(self, *args, **kwargs):
super(ReadOnlyFieldsMixin, self).__init__(*args, **kwargs)
for field in (field for name, field in self.fields.iteritems() if
name in self.readonly_fields):
field.widget.attrs['disabled'] = 'true'
field.required = False
def clean(self):
for f in self.readonly_fields:
self.cleaned_data.pop(f, None)
return super(ReadOnlyFieldsMixin, self).clean()
Usage:
class MyFormWithReadOnlyFields(ReadOnlyFieldsMixin, MyForm):
readonly_fields = ('field1', 'field2', 'fieldx')
Do not try to detect credit card type as part of processing a payment. You are risking of declining valid transactions.
If you need to provide information to your payment processor (e.g. PayPal credit card object requires to name the card type), then guess it from the least information available, e.g.
$credit_card['pan'] = preg_replace('/[^0-9]/', '', $credit_card['pan']);
$inn = (int) mb_substr($credit_card['pan'], 0, 2);
// @see http://en.wikipedia.org/wiki/List_of_Bank_Identification_Numbers#Overview
if ($inn >= 40 && $inn <= 49) {
$type = 'visa';
} else if ($inn >= 51 && $inn <= 55) {
$type = 'mastercard';
} else if ($inn >= 60 && $inn <= 65) {
$type = 'discover';
} else if ($inn >= 34 && $inn <= 37) {
$type = 'amex';
} else {
throw new \UnexpectedValueException('Unsupported card type.');
}
This implementation (using only the first two digits) is enough to identify all of the major (and in PayPal's case all of the supported) card schemes. In fact, you might want to skip the exception altogether and default to the most popular card type. Let the payment gateway/processor tell you if there is a validation error in response to your request.
The reality is that your payment gateway does not care about the value you provide.
I tried both .empty()
as well as .remove()
for my dropdown and both were slow. Since I had almost 4,000 options there.
I used .html("")
which is much faster in my condition.
Which is below
$(dropdown).html("");
use dataType: 'jsonp', works for me.
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function
I think you are using the 64-bit version of the tool to install a 32-bit application. I've also faced this issue today and used this Framework path to cater .
C:\Windows\Microsoft.NET\Framework\v4.0.30319
and it should install your 32-bit application just fine.
You can execute an .exe from a Windows service very well in Windows XP. I have done it myself in the past.
You need to make sure you had checked the option "Allow to interact with the Desktop" in the Windows service properties. If that is not done, it will not execute.
I need to check in Windows 7 or Vista as these versions requires additional security privileges so it may throw an error, but I am quite sure it can be achieved either directly or indirectly. For XP I am certain as I had done it myself.
Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute
and right:0
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 999999;
margin-top: 0px;
position: absolute;
right:0;
}
here is the full code: http://jsfiddle.net/T9FJL/
Now which drive letter did that removable device get?
Two ways to locate e.g. a USB-disk in git Bash
:
$ cat /proc/partitions major minor #blocks name win-mounts 8 0 500107608 sda 8 1 1048576 sda1 8 2 131072 sda2 8 3 496305152 sda3 C:\ 8 4 1048576 sda4 8 5 1572864 sda5 8 16 0 sdb 8 32 0 sdc 8 48 0 sdd 8 64 0 sde 8 80 3952639 sdf 8 81 3950592 sdf1 E:\ $ mount C:/Program Files/Git on / type ntfs (binary,noacl,auto) C:/Program Files/Git/usr/bin on /bin type ntfs (binary,noacl,auto) C:/Users/se2982/AppData/Local/Temp on /tmp type ntfs (binary,noacl,posix=0,usertemp) C: on /c type ntfs (binary,noacl,posix=0,user,noumount,auto) E: on /e type vfat (binary,noacl,posix=0,user,noumount,auto) G: on /g type ntfs (binary,noacl,posix=0,user,noumount,auto) H: on /h type ntfs (binary,noacl,posix=0,user,noumount,auto)
... so; likely drive letter in this example => /e
(or E:\ if you must), when knowing that C, G, and H are other things (in Windows).
Another possibility is to denote where you can find OpenCV_DIR
in the CMakeLists.txt file. For example, the following cmake scripts work for me:
cmake_minimum_required(VERSION 2.8)
project(performance_test)
set(OpenCV_STATIC ON)
set(OpenCV_CUDA OFF)
set(OpenCV_DIR "${CMAKE_SOURCE_DIR}/../install")
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(${OpenCV_LIB_DIR})
file(GLOB my_source_files ./src/*)
add_executable( performance_test ${my_source_files})
target_link_libraries(performance_test ${OpenCV_LIBS})
Just to remind that you should set OpenCV_STATIC
and OpenCV_CUDA
as well before you invoke OpenCVConfig.cmake
. In my case the built library is static library that does not use CUDA.
You can kind of do this. Unfortunately there's no way to use an inset on text-shadow, but you can fake it with colour and position. Take the blur right down and arrange the shadow along the top right. Something like this might do the trick:
background-color:#D7CFBA;
color:#38373D;
font-weight:bold;
text-shadow:1px 1px 0 #FFFFFF;
... but you'll need to be really, really careful about which colours you use otherwise it will look off. It is essentially an optical illusion so won't work in every context. It also doesn't really look great at smaller font sizes, so be aware of that too.
For Windows 7 x64 with default Atom installation add this to your PATH
%USERPROFILE%\AppData\Local\atom\app-1.4.0\resources\cli
and restart any running consoles
(if you don't find Atom there - right-click Atom icon and navigate to Target)
Use a table variable if for a very small quantity of data (thousands of bytes)
Use a temporary table for a lot of data
Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.
In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.
But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.
This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.
My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.
Code For Merging PDF's in Itextsharp
public static void Merge(List<String> InFiles, String OutFile)
{
using (FileStream stream = new FileStream(OutFile, FileMode.Create))
using (Document doc = new Document())
using (PdfCopy pdf = new PdfCopy(doc, stream))
{
doc.Open();
PdfReader reader = null;
PdfImportedPage page = null;
//fixed typo
InFiles.ForEach(file =>
{
reader = new PdfReader(file);
for (int i = 0; i < reader.NumberOfPages; i++)
{
page = pdf.GetImportedPage(reader, i + 1);
pdf.AddPage(page);
}
pdf.FreeReader(reader);
reader.Close();
File.Delete(file);
});
}
With Homebrew and jenv:
Assumption: Mac machine and you already have installed homebrew.
Install cask:
$ brew tap caskroom/cask
$ brew tap caskroom/versions
To install latest java:
$ brew cask install java
To install java 8:
$ brew cask install java8
To install java 9:
$ brew cask install java9
If you want to install/manage multiple version then you can use 'jenv':
Install and configure jenv:
$ brew install jenv
$ echo 'export PATH="$HOME/.jenv/bin:$PATH"' >> ~/.bash_profile
$ echo 'eval "$(jenv init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
Add the installed java to jenv:
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home
$ jenv add /Library/Java/JavaVirtualMachines/jdk1.11.0_2.jdk/Contents/Home
To see all the installed java:
$ jenv versions
Above command will give the list of installed java:
* system (set by /Users/lyncean/.jenv/version)
1.8
1.8.0.202-ea
oracle64-1.8.0.202-ea
Configure the java version which you want to use:
$ jenv global oracle64-1.6.0.39
You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:
SELECT
airline, flt_no, fairport, tairport, depart, arrive, fare
FROM
flights
INNER JOIN
airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
airports to_port ON (to_port.code = flights.tairport)
WHERE
from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
Note that the to_port
and from_port
are aliases for the first and second copies of the airports
table.
I solved the problem this way:
We of course all understand that there's no perfect way to solve this problem, but some solutions can get you farther than others.
In particular, it's pretty easy to go beyond simple whitespace-splitters if you just have some lists of common prefixes (Mr, Dr, Mrs, etc.), infixes (von, de, del, etc.), suffixes (Jr, III, Sr, etc.) and so on. It's also helpful if you have some lists of common first names (in various languages/cultures, if your names are diverse) so that you can guess whether a word in the middle is likely to be part of the last name or not.
BibTeX also implements some heuristics that get you part of the way there; they're encapsulated in the Text::BibTeX::Name
perl module. Here's a quick code sample that does a reasonable job.
use Text::BibTeX;
use Text::BibTeX::Name;
$name = "Dr. Mario Luis de Luigi Jr.";
$name =~ s/^\s*([dm]rs?.?|miss)\s+//i;
$dr=$1;
$n=Text::BibTeX::Name->new($name);
print join("\t", $dr, map "@{[ $n->part($_) ]}", qw(first von last jr)), "\n";
typeid(uint8_t).name()
is nice, but it returns "unsigned char" while you may expect "uint8_t".
This piece of code will return you the appropriate type
#define DECLARE_SET_FORMAT_FOR(type) \
if ( typeid(type) == typeid(T) ) \
formatStr = #type;
template<typename T>
static std::string GetFormatName()
{
std::string formatStr;
DECLARE_SET_FORMAT_FOR( uint8_t )
DECLARE_SET_FORMAT_FOR( int8_t )
DECLARE_SET_FORMAT_FOR( uint16_t )
DECLARE_SET_FORMAT_FOR( int16_t )
DECLARE_SET_FORMAT_FOR( uint32_t )
DECLARE_SET_FORMAT_FOR( int32_t )
DECLARE_SET_FORMAT_FOR( float )
// .. to be exptended with other standard types you want to be displayed smartly
if ( formatStr.empty() )
{
assert( false );
formatStr = typeid(T).name();
}
return formatStr;
}
I think
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>Testing</div>
<div id="result" style="margin:1em 4em; background:rgb(200,200,255); height:500px"></div>
<div style="background:rgb(200,255,200); height:3000px; width:5000px;"></div>
<script>
(function(){
var link=$("#result");
var top = link.offset().top; // position from $(document).offset().top
var bottom = top + link.height(); // position from $(document).offset().top
var left = link.offset().left; // position from $(document).offset().left
var right = left + link.width(); // position from $(document).offset().left
var bottomFromBottom = $(document).height() - bottom;
// distance from document's bottom
var rightFromRight = $(document).width() - right;
// distance from document's right
var str="";
str+="top: "+top+"<br>";
str+="bottom: "+bottom+"<br>";
str+="left: "+left+"<br>";
str+="right: "+right+"<br>";
str+="bottomFromBottom: "+bottomFromBottom+"<br>";
str+="rightFromRight: "+rightFromRight+"<br>";
link.html(str);
})();
</script>
The result are
top: 44
bottom: 544
left: 72
right: 1277
bottomFromBottom: 3068
rightFromRight: 3731
in chrome browser of mine.
When the document is scrollable, $(window).height()
returns height of browser viewport, not the width of document of which some parts are hiden in scroll. See http://api.jquery.com/height/ .
<?php
header("Location: index.html");
?>
Just make sure nothing is actually written to the page prior to this code, or it won't work.
The proper way to get LF endings in Windows is to first set core.autocrlf
to false
:
git config --global core.autocrlf false
You need to do this if you are using msysgit, because it sets it to true
in its system settings.
Now git won’t do any line ending normalization. If you want files you check in to be normalized, do this: Set text=auto
in your .gitattributes
for all files:
* text=auto
And set core.eol
to lf
:
git config --global core.eol lf
Now you can also switch single repos to crlf (in the working directory!) by running
git config core.eol crlf
After you have done the configuration, you might want git to normalize all the files in the repo. To do this, go to to the root of your repo and run these commands:
git rm --cached -rf .
git diff --cached --name-only -z | xargs -n 50 -0 git add -f
If you now want git to also normalize the files in your working directory, run these commands:
git ls-files -z | xargs -0 rm
git checkout .
You can use the below statement to get the inserted Id to a variable-like thing.
INSERT INTO YOUR_TABLE(ID) VALUES ('10') returning ID into :Inserted_Value;
Now you can retrieve the value using the below statement
SELECT :Inserted_Value FROM DUAL;
The condition below:
//Element[@attribute1="abc" and @attribute2="xyz" and Data]
checks for the existence of the element Data within Element and not for element value Data.
Instead you can use
//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]
Use contains instead:
In [10]: df.b.str.contains('^f')
Out[10]:
0 False
1 True
2 True
3 False
Name: b, dtype: bool
There are a lot of solutions, here one: if you want only number erase the letters and the method receives a random and the result length.
public String GenerateRandom(Random oRandom, int iLongitudPin)
{
String sCharacters = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
int iLength = sCharacters.Length;
char cCharacter;
int iLongitudNuevaCadena = iLongitudPin;
String sRandomResult = "";
for (int i = 0; i < iLongitudNuevaCadena; i++)
{
cCharacter = sCharacters[oRandom.Next(iLength)];
sRandomResult += cCharacter.ToString();
}
return (sRandomResult);
}
I couldn't possibly explain it better than wikipedia does: http://en.wikipedia.org/wiki/MIME_type
In addition to e-mail applications, Web browsers also support various MIME types. This enables the browser to display or output files that are not in HTML format.
IOW, it helps the browser (or content consumer, because it may not just be a browser) determine what content they are about to consume; this means a browser may be able to make a decision on the correct plugin to use to display content, or a media player may be able to load up the correct codec or plugin.
Use the DATEDIFF to return value in milliseconds, seconds, minutes, hours, ...
DATEDIFF(interval, date1, date2)
interval REQUIRED - The time/date part to return. Can be one of the following values:
year, yyyy, yy = Year
quarter, qq, q = Quarter
month, mm, m = month
dayofyear = Day of the year
day, dy, y = Day
week, ww, wk = Week
weekday, dw, w = Weekday
hour, hh = hour
minute, mi, n = Minute
second, ss, s = Second
millisecond, ms = Millisecond
date1, date2 REQUIRED - The two dates to calculate the difference between
xlrd.xldate_as_tuple
is nice, but there's xlrd.xldate.xldate_as_datetime
that converts to datetime as well.
import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)
Try this code, I get working fine.
webSettings.setSupportZoom(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setDisplayZoomControls(false);
This is your array
products: any = [
{
"name": "John-Cena",
},
{
"name": "Brock-Lensar",
}
];
This is your ngFor loop Filter By :
<input type="text" [(ngModel)]='filterText' />
<ul *ngFor='let product of filterProduct'>
<li>{{product.name }}</li>
</ul>
There I'm using filterProduct instant of products, because i want to preserve my original data. Here model _filterText is used as a input box.When ever there is any change setter function will call. In setFilterText performProduct is called it will return the result only those who match with the input. I'm using lower case for case insensitive.
filterProduct = this.products;
_filterText : string;
get filterText() : string {
return this._filterText;
}
set filterText(value : string) {
this._filterText = value;
this.filterProduct = this._filterText ? this.performProduct(this._filterText) : this.products;
}
performProduct(value : string ) : any {
value = value.toLocaleLowerCase();
return this.products.filter(( products : any ) =>
products.name.toLocaleLowerCase().indexOf(value) !== -1);
}
Short explanation looks like:
If you having troubles with interpreting results you could try BM.Sense results analysis service
As Character is a class deriving from Object, you can assign null as "instance":
Character myChar = null;
Problem solved ;)
There is another way to reset the password through command prompt ...
1) Go to the Oracle Database Folder ( In my case Oracle Database 11g Express Edition) in the START MENU.
2) Within that folder click "Run SQL Commandline"
3) Type "connect username/password" (your username and old password without the quotation marks)
4) The message displayed is ...
ERROR: ORA-28001: the password has expired
Changing password for hr
--> New password:
Enter Username, Password image
5) Type the new password
6) Retype the new password
7) Message displayed is ...
Password changed Connected.
SQL>
8) GO TO Sql developer --> type the new password --> connected
Update: while the following solution works, there's a much easier method. See below.
Here's what I came up with, and I hope this comes in handy - to you or anybody else:
$('#element').attr('style', function(i, style)
{
return style && style.replace(/display[^;]+;?/g, '');
});
This will remove that inline style.
I'm not sure this is what you wanted. You wanted to override it, which, as pointed out already, is easily done by $('#element').css('display', 'inline')
.
What I was looking for was a solution to REMOVE the inline style completely. I need this for a plugin I'm writing where I have to temporarily set some inline CSS values, but want to later remove them; I want the stylesheet to take back control. I could do it by storing all of its original values and then putting them back inline, but this solution feels much cleaner to me.
Here it is in plugin format:
(function($)
{
$.fn.removeStyle = function(style)
{
var search = new RegExp(style + '[^;]+;?', 'g');
return this.each(function()
{
$(this).attr('style', function(i, style)
{
return style && style.replace(search, '');
});
});
};
}(jQuery));
If you include this plugin in the page before your script, you can then just call
$('#element').removeStyle('display');
and that should do the trick.
Update: I now realized that all this is futile. You can simply set it to blank:
$('#element').css('display', '');
and it'll automatically be removed for you.
Here's a quote from the docs:
Setting the value of a style property to an empty string — e.g.
$('#mydiv').css('color', '')
— removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's.css()
method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or<style>
element.
I don't think jQuery is doing any magic here; it seems the style
object does this natively.
I understand that my comment relate with windows, but may be someone be useful. For win run in cmd:
wmic process where "commandline like '%my_app.js%' AND name='node.exe' " CALL Terminate
then you can run your app again:
node my_app.js
Also you can use it in batch file, with escape quotes:
wmic process where "commandline like '%%my_app.js%%' AND name='node.exe' " CALL Terminate
node my_app.js
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));
Use the native pathname
property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href")
can return values like ../..
which would not give you the correct result.
If you need to keep the search
and hash
(e.g. foo?bar#baz
from http://quux.com/path/to/foo?bar#baz
) use this:
window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);
In my practice I found that it is best to use EditorTemplates with only one HtmlHelper in it - TextBox that is in most cases. If I want a template for more complex html structure, I'll write a separate HtmlHelper.
Given that we can stick the whole ViewData object in place of htmlAttributes of the TextBox. In addition we can write some customization code for some of the properties of the ViewData if they need special treatment:
@model DateTime?
@*
1) applies class datepicker to the input;
2) applies additionalViewData object to the attributes of the input
3) applies property "format" to the format of the input date.
*@
@{
if (ViewData["class"] != null) { ViewData["class"] += " datepicker"; }
else { ViewData["class"] = " datepicker"; }
string format = "MM/dd/yyyy";
if (ViewData["format"] != null)
{
format = ViewData["format"].ToString();
ViewData.Remove("format");
}
}
@Html.TextBox("", (Model.HasValue ? Model.Value.ToString(format) : string.Empty), ViewData)
Below are the examples of the syntax in the view and the outputted html:
@Html.EditorFor(m => m.Date)
<input class="datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="01/08/2012">
@Html.EditorFor(m => m.Date, new { @class = "myClass", @format = "M/dd" })
<input class="myClass datepicker" data-val="true" data-val-required="&#39;Date&#39; must not be empty." id="Date" name="Date" type="text" value="1/08">
Based on Ivan Laharnar with less code and simplier:
declare
lastSeq number;
begin
SELECT MAX(ID) + 1 INTO lastSeq FROM <TABLE_NAME>;
if lastSeq IS NULL then lastSeq := 1; end if;
execute immediate 'CREATE SEQUENCE <SEQUENCE_NAME> INCREMENT BY 1 START WITH ' || lastSeq || ' MAXVALUE 999999999 MINVALUE 1 NOCACHE';
end;
Simplest Definition of Looper & Handler:
Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into it from any other threads.
Details in general wording:
So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.
The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).
Example:
A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.
Read more here about Looper and Handler and the definition of Pipeline Thread:
if (getActivity() == null) return;
works also in some cases. Just breaks the code execution from it and make sure the app not crash
I find solution that instead of using ListBox I used ListView.It allows to change list items BackColor.
private void listView1_Refresh()
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView1.Items[i].BackColor = Color.Red;
for (int j = 0; j < existingStudents.Count; j++)
{
if (listView1.Items[i].ToString().Contains(existingStudents[j]))
{
listView1.Items[i].BackColor = Color.Green;
}
}
}
}
You have your print() statement in the for()
loop, It should be after so that it only prints once. the way it currently is, every time the max changes it prints a max
.
here is a portion of a procedure I use on my system to find text....
DECLARE @Search varchar(255)
SET @Search='[10.10.100.50]'
SELECT DISTINCT
o.name AS Object_Name,o.type_desc
FROM sys.sql_modules m
INNER JOIN sys.objects o ON m.object_id=o.object_id
WHERE m.definition Like '%'+@Search+'%'
ORDER BY 2,1
Here is an example to fully programmatically:
I am using the following class vars:
Spinner varSpinner;
List<String> varSpinnerData;
float varScaleX;
float varScaleY;
A - Init and render the Spinner (varRoot is a pointer to my main Activity):
public void renderSpinner() {
List<String> myArraySpinner = new ArrayList<String>();
myArraySpinner.add("red");
myArraySpinner.add("green");
myArraySpinner.add("blue");
varSpinnerData = myArraySpinner;
Spinner mySpinner = new Spinner(varRoot);
varSpinner = mySpinner;
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
mySpinner.setAdapter(spinnerArrayAdapter);
B - Resize and Add the Spinner to my View:
FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.WRAP_CONTENT);
myParamsLayout.gravity = Gravity.NO_GRAVITY;
myParamsLayout.leftMargin = (int) (100 * varScaleX);
myParamsLayout.topMargin = (int) (350 * varScaleY);
myParamsLayout.width = (int) (300 * varScaleX);;
myParamsLayout.height = (int) (60 * varScaleY);;
varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);
C - Make the Click handler and use this to set the font.
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {
Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);
((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
}
D - Update the Spinner with new data:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(1);
}
}
What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.
UPDATE:
This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:
private void updateInitSpinners(){
String mySelected = varSpinner.getSelectedItem().toString();
Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);
varSpinnerData.clear();
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
varSpinner.setAdapter(spinnerArrayAdapter);
varSpinnerData.add("Hello World");
varSpinnerData.add("Hello World 2");
((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
varSpinner.invalidate();
varSpinner.setSelection(0);
}
}
Hope this helps......
Put the h1
and h2
in a container with an id of container
then:
#container {
display: flex;
justify-content: space-beteen;
}
>>> now
datetime.datetime(2016, 1, 28, 18, 26, 12, 980861)
>>> later = now.replace(month=now.month+1)
>>> later
datetime.datetime(2016, 2, 28, 18, 26, 12, 980861)
EDIT: Fails on
y = datetime.date(2016, 1, 31); y.replace(month=2) results in ValueError: day is out of range for month
Ther is no simple way to do it, but you can use your own function like answered below.
Based on Ramon's answer I run into an error. The problem where spaces in the JSON I tried to write I got it fixed by changing the task in the playbook to look like:
- copy:
content: "{{ your_json_feed }}"
dest: "/path/to/destination/file"
As of now I am not sure why this was needed. My best guess is that it had something to do with how variables are replaced in Ansible and the resulting file is parsed.
Hi, I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.
My solution like this:
var userIDContent = $("#grid").getCell(id,"userID"); // Use getCell to get the content
//alert("userID:" +userID); // you can see the content here.
//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val(); // var userID = $(userIDContent).attr('attrName');
The answers provided by other folks (Ben James) are quite good and I have used them. As user889030 points out, the last array element may be empty. Actually, the first and last array elements can be empty. The code below addresses both issues.
# Split an input string into an array of substrings using any set
# whitespace characters
function explode_whitespace($str) {
# Split the input string into an array
$parts = preg_split('/\s+/', $str);
# Get the size of the array of substrings
$sizeParts = sizeof($parts);
# Check if the last element of the array is a zero-length string
if ($sizeParts > 0) {
$lastPart = $parts[$sizeParts-1];
if ($lastPart == '') {
array_pop($parts);
$sizeParts--;
}
# Check if the first element of the array is a zero-length string
if ($sizeParts > 0) {
$firstPart = $parts[0];
if ($firstPart == '')
array_shift($parts);
}
}
return $parts;
}
One simple way to validate a date string is to convert to a date object and test that, e.g.
// Expect input as d/m/y_x000D_
function isValidDate(s) {_x000D_
var bits = s.split('/');_x000D_
var d = new Date(bits[2], bits[1] - 1, bits[0]);_x000D_
return d && (d.getMonth() + 1) == bits[1];_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
console.log(s + ' : ' + isValidDate(s))_x000D_
})
_x000D_
When testing a Date this way, only the month needs to be tested since if the date is out of range, the month will change. Same if the month is out of range. Any year is valid.
You can also test the bits of the date string:
function isValidDate2(s) {_x000D_
var bits = s.split('/');_x000D_
var y = bits[2],_x000D_
m = bits[1],_x000D_
d = bits[0];_x000D_
// Assume not leap year by default (note zero index for Jan)_x000D_
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];_x000D_
_x000D_
// If evenly divisible by 4 and not evenly divisible by 100,_x000D_
// or is evenly divisible by 400, then a leap year_x000D_
if ((!(y % 4) && y % 100) || !(y % 400)) {_x000D_
daysInMonth[1] = 29;_x000D_
}_x000D_
return !(/\D/.test(String(d))) && d > 0 && d <= daysInMonth[--m]_x000D_
}_x000D_
_x000D_
['0/10/2017','29/2/2016','01/02'].forEach(function(s) {_x000D_
console.log(s + ' : ' + isValidDate2(s))_x000D_
})
_x000D_
head
and pipe with tail
will be slow for a huge file. I would suggest sed
like this:
sed 'NUMq;d' file
Where NUM
is the number of the line you want to print; so, for example, sed '10q;d' file
to print the 10th line of file
.
Explanation:
NUMq
will quit immediately when the line number is NUM
.
d
will delete the line instead of printing it; this is inhibited on the last line because the q
causes the rest of the script to be skipped when quitting.
If you have NUM
in a variable, you will want to use double quotes instead of single:
sed "${NUM}q;d" file
In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.
Please, see oficial encode()
and decode()
documentation from codecs
library. utf-8
is the default encoding for the functions, but there are severals standard encodings in Python 3, like latin_1
or utf_32
.
You can set the year range using this option per documentation here http://api.jqueryui.com/datepicker/#option-yearRange
yearRange: '1950:2013', // specifying a hard coded year range
or this way
yearRange: "-100:+0", // last hundred years
From the Docs
Default: "c-10:c+10"
The range of years displayed in the year drop-down: either relative to today's year ("-nn:+nn"), relative to the currently selected year ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats ("nnnn:-nn"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the minDate and/or maxDate options.
Use -
new Select(driver.findElement(By.id("gender"))).selectByVisibleText("Germany");
Of course, you need to import org.openqa.selenium.support.ui.Select;
A good way is to derive from TcpClient and override the Disposing(bool) method:
class MyClient : TcpClient {
public bool IsDead { get; set; }
protected override void Dispose(bool disposing) {
IsDead = true;
base.Dispose(disposing);
}
}
Which won't work if the other code created the instance. Then you'll have to do something desperate like using Reflection to get the value of the private m_CleanedUp member. Or catch the exception.
Frankly, none is this is likely to come to a very good end. You really did want to write to the TCP port. But you won't, that buggy code you can't control is now in control of your code. You've increased the impact of the bug. Talking to the owner of that code and working something out is by far the best solution.
EDIT: A reflection example:
using System.Reflection;
public static bool SocketIsDisposed(Socket s)
{
BindingFlags bfIsDisposed = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetProperty;
// Retrieve a FieldInfo instance corresponding to the field
PropertyInfo field = s.GetType().GetProperty("CleanedUp", bfIsDisposed);
// Retrieve the value of the field, and cast as necessary
return (bool)field.GetValue(s, null);
}
In my situation it was matter of the permissions:
sudo chmod -R +777 <your_folder_path>
I used this: config.log_level = :info
edit-in config/environments/performance.rb
Working great for me, rejecting SQL output, and show only rendering and important info.
SQL Server doesn't have regular expressions. It uses the LIKE pattern matching syntax which isn't the same.
As it happens, you are close. Just need leading+trailing wildcards and move the NOT
WHERE whatever NOT LIKE '%[a-z0-9]%'
A 'queuecomplete' event has been added. See Issue 317.
const filteredObject = Object.fromEntries(Object.entries(originalObject).filter(([key, value]) => key !== uuid))
typeof
is safer as it allows the identifier to never have been declared before:
if(typeof neverDeclared === "undefined") // no errors
if(neverDeclared === null) // throws ReferenceError: neverDeclared is not defined
Following Adam's idea. Make your prepared statement sort of select my_column from my_table where search_column in (#) Create a String x and fill it with a number of "?,?,?" depending on your list of values Then just change the # in the query for your new String x an populate
android:inputType="numberDecimal"
What about this formula for getting the last value:
=index(G:G;max((G:G<>"")*row(G:G)))
And this would be a final formula for your original task:
=DAYS360(G10;index(G:G;max((G:G<>"")*row(G:G))))
Suppose that your initial date is in G10.
I was able to achieve a redirect in react-router-dom using the following
<Route exact path="/" component={() => <Redirect to={{ pathname: '/YourRoute' }} />} />
For my case, I was looking for a way to redirect users whenever they visit the root URL http://myapp.com
to somewhere else within the app http://myapp.com/newplace
. so the above helped.
it just simple :import this directory
import {Component, Directive, Input, ViewChild} from '@angular/core';
Use JSON.stringify(<data>)
.
Change your code: data: sendInfo
to data: JSON.stringify(sendInfo)
.
Hope this can help you.
~$ echo $PATH
/home/jack/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games
~$ whereis lshw
lshw: /usr/bin/lshw /usr/share/man/man1/lshw.1.gz
Say you have a DIV
you want centred horizontally:
<div id="foo">Lorem ipsum</div>
In the CSS you'd style it with this:
#foo
{
margin:0 auto;
width:30%;
}
Which states that you have a top and bottom margin of zero pixels, and on either left or right, automatically work out how much is needed to be even.
Doesn't really matter what you put in for the width, as long as it's there and isn't 100%. Otherwise you wouldn't be setting the centre on anything.
But if you float it, left or right, then the bets are off since that pulls it out of the normal flow of elements on the page and the auto margin setting won't work.
Just wrote a class to compute smallest (not to be taken literally) number of edits to transform one string into another string:
http://www.raymondhill.net/finediff/
It has a static function to render a HTML version of the diff.
It's a first version, and likely to be improved, but it works just fine as of now, so I am throwing it out there in case someone needs to generate a compact diff efficiently, like I needed.
Edit: It's on Github now: https://github.com/gorhill/PHP-FineDiff
well, you can very quickly test the click dispatch via jQuery like so
$('#link-id').click();
If you're still having problem with click respecting the target, you can always do this
$('#link-id').click( function( event, anchor )
{
window.open( anchor.href, anchor.target, '' );
event.preventDefault();
return false;
});
Declare extern int x;
in file.h.
And define int x;
only in one cpp file.cpp.
This answer is for IE < 7, for modern browsers check Jonathan's answer above.
This answer is outdated and Jonathan's answer above (JSON.parse(jsonString)
) is now the best answer.
JSON.org has JSON parsers for many languages including four different ones for JavaScript. I believe most people would consider json2.js their goto implementation.
As Wingman said, Google App Engine is a great solution for your scenario.
You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android
And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4
If you always know the route, you can simply append the anchor like this:
href="#/route#anchorID
where route
is the current angular route and anchorID
matches an <a id="anchorID">
somewhere on the page
Use OrderedDicts: http://docs.python.org/2/library/collections.html#collections.OrderedDict
>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1
For those using Python 3
>>> list(x.keys()).index("c")
1
%20
is the space between AmberCRO SOP.
Try -
href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"
Or rename the folder as AmberCRO-SOP and write it as -
href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"
Validates such values as: "", "FIR", "FIR ", "FIR LAST"
/^[A-z]*$|^[A-z]+\s[A-z]*$/
You are correct in that your list contains a reference to the original dictionary.
a.append(b.copy())
should do the trick.
Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b)
, which makes a deep copy.
Use the operator sizeof
, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:
#include <iostream>
int main(int,char**)
{
std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
return 0;
}
Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.
Here's an example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">_x000D_
<option value="">Select...</option>_x000D_
<option value="https://google.com">Google</option>_x000D_
<option value="https://yahoo.com">Yahoo</option>_x000D_
</select>
_x000D_
For me, IntelliJ Event Log
(right bottom corner) had below logs:
Error running EntitmentTooling-Debug: Cannot run program "/path-to/apache-tomcat-8.5.15/bin/catalina.sh" (in directory "path-to/apache-tomcat-8.5.15/bin"): error=13, Permission denied
Error running EntitmentTooling-Debug: Unable to open debugger port (127.0.0.1:58804): java.net.SocketException "Socket closed"
The command
$ chmod a+x /path-to/apache-tomcat-8.5.15/bin/catalina.sh
to sufficiently change privileges worked for me.
Creating the template page is the correct answer. For this, just add this into the page you created inside the theme folder:
<?php
/*
Template Name: mytemplate
*/
?>
For running this code, you need to select "mytemplate" as the template of the page from the back end.
Please see this link for getting the correct details https://developer.wordpress.org/themes/template-files-section/page-template-files/.
If you only need to encode sets, not general Python objects, and want to keep it easily human-readable, a simplified version of Raymond Hettinger's answer can be used:
import json
import collections
class JSONSetEncoder(json.JSONEncoder):
"""Use with json.dumps to allow Python sets to be encoded to JSON
Example
-------
import json
data = dict(aset=set([1,2,3]))
encoded = json.dumps(data, cls=JSONSetEncoder)
decoded = json.loads(encoded, object_hook=json_as_python_set)
assert data == decoded # Should assert successfully
Any object that is matched by isinstance(obj, collections.Set) will
be encoded, but the decoded value will always be a normal Python set.
"""
def default(self, obj):
if isinstance(obj, collections.Set):
return dict(_set_object=list(obj))
else:
return json.JSONEncoder.default(self, obj)
def json_as_python_set(dct):
"""Decode json {'_set_object': [1,2,3]} to set([1,2,3])
Example
-------
decoded = json.loads(encoded, object_hook=json_as_python_set)
Also see :class:`JSONSetEncoder`
"""
if '_set_object' in dct:
return set(dct['_set_object'])
return dct
ok, so if you are using bootstrap-rtl.css, what you can do is go to the following class .modal-backdrop and remove the z-index attribute. after that all should be fine