Documentation on UISwitch says:
[mySwitch setOn:NO];
In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.
To send an HTTP DELETE with some headers via axios
I've done this:
const deleteUrl = "http//foo.bar.baz";
const httpReqHeaders = {
'Authorization': token,
'Content-Type': 'application/json'
};
// check the structure here: https://github.com/axios/axios#request-config
const axiosConfigObject = {headers: httpReqHeaders};
axios.delete(deleteUrl, axiosConfigObject);
The axios
syntax for different HTTP verbs (GET, POST, PUT, DELETE) is tricky because sometimes the 2nd parameter is supposed to be the HTTP body, some other times (when it might not be needed) you just pass the headers as the 2nd parameter.
However let's say you need to send an HTTP POST request without an HTTP body, then you need to pass undefined
as the 2nd parameter.
Bare in mind that according to the definition of the configuration object (https://github.com/axios/axios#request-config) you can still pass an HTTP body in the HTTP call via the data
field when calling axios.delete
, however for the HTTP DELETE verb it will be ignored.
This confusion between the 2nd parameter being sometimes the HTTP body and some other time the whole config
object for axios
is due to how the HTTP rules have been implemented. Sometimes an HTTP body is not needed for an HTTP call to be considered valid.
I have debian 9 and to fix this i used the new library as follows:
ln -s /usr/bin/gpgv /usr/bin/gnupg2
I was trying to install docker-compose on "Ubuntu 16.04.5 LTS" but after installing it like this:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
I was getting:
-bash: /usr/local/bin/docker-compose: Permission denied
and while I was using it with sudo I was getting:
sudo: docker-compose: command not found
So here's the steps that I took and solved my problem:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo ln -sf /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose
To override this and fix the issue on your local machine you can do the following changes within your php.ini
configuration file.
php.ini
configuration file you can use the following command: php --ini
After running this command you should see an output like the following:
Configuration File (php.ini) Path: /usr/local/etc/php/7.3
Loaded Configuration File: /usr/local/etc/php/7.3/php.ini <---- note the path
Scan for additional .ini files in: /usr/local/etc/php/7.3/conf.d
Additional .ini files parsed: /usr/local/etc/php/7.3/conf.d/ext-opcache.ini
The file we want to change is the Loaded Configuration.
Open and search for the memory_limit
you can set the memory_limit = -1
to give an unlimited amount of memory to PHP processes or you can set 512MB, 1G, 2G, 5G,....
$ nano /usr/local/etc/php/7.3/php.ini
locate and set:
$ memory_limit = -1 or memory_limit = 1G
After saving your file, you can verify the PHP changes by running this command which will output the current memory settings in your php.ini
file:
php -r "echo ini_get('memory_limit').PHP_EOL;"
NOTE: After saving, the new memory will be working. You don't need to do anything else.
$ sudo groupadd docker
$ sudo usermod -aG docker $USER
$ newgrp - docker
$ docker run hello-world
If anyone is still having trouble, remember you can run composer with any php version that you have installed e.g. $ php7.3 -f /usr/local/bin/composer update
Use which composer
command to help locate the composer executable.
My problem was fideloper proxy
version.
when i upgraded laravel 5.5 to 5.8 this happened
just sharing if anybody get help
change you composer json fideloper version:
"fideloper/proxy": "^4.0",
After that you need to run update composer that's it.
composer update
For macOs users you can use Homebrew instead :
# For php v7.0
brew install [email protected]
# For php v7.1
brew install [email protected]
# For php v7.2
brew install [email protected]
# For php v7.3
brew install [email protected]
# For php v7.4
brew install [email protected]
Use this to delete everything:
docker system prune -a --volumes
Remove all unused containers, volumes, networks and images
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all volumes not used by at least one container
- all images without at least one container associated to them
- all build cache
https://docs.docker.com/engine/reference/commandline/system_prune/#extended-description
Disable package-lock.json globally
type the following in your terminal:
npm config set package-lock false
this really work for me like magic
I was facing similar issue on my mac, and I found that docker wasn't running in my machine, I just went to applications and invoked whale and then it worked .
Trying "docker exec ... < data.sql"
in Window PowerShell responses with:
The '<' operator is reserved for future use.
But one can wrap it out with cmd /c
to eliminate the issue:
cmd /c "docker exec -i mysql-container mysql -uuser -ppassword name_db < data.sql"
You can try
$sudo service network-manager restart
Worked for me.
You should be able to add:
restart: always
to every service you want to restart in the docker-compose.yml
file.
See: https://github.com/compose-spec/compose-spec/blob/master/spec.md#restart
For CentOS, RHEL, Fedora:
$ yum search php-xml
============================================================================================================ N/S matched: php-xml ============================================================================================================
php-xml.x86_64 : A module for PHP applications which use XML
php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php-xmlseclibs.noarch : PHP library for XML Security
php54-php-xml.x86_64 : A module for PHP applications which use XML
php54-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php55-php-xml.x86_64 : A module for PHP applications which use XML
php55-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php56-php-xml.x86_64 : A module for PHP applications which use XML
php56-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php70-php-xml.x86_64 : A module for PHP applications which use XML
php70-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php71-php-xml.x86_64 : A module for PHP applications which use XML
php71-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php72-php-xml.x86_64 : A module for PHP applications which use XML
php72-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php73-php-xml.x86_64 : A module for PHP applications which use XML
php73-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
Then select the php-xml version matching your php version:
# php -v
PHP 7.2.11 (cli) (built: Oct 10 2018 10:00:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
# sudo yum install -y php72-php-xml.x86_64
Given this .env
file:
DB_NAME=foo
DB_USER=bar
DB_PASSWORD=baz
And this mongo-init.sh
file:
mongo --eval "db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD'); db = db.getSiblingDB('$DB_NAME'); db.createUser({ user: '$DB_USER', pwd: '$DB_PASSWORD', roles: [{ role: 'readWrite', db: '$DB_NAME' }] });"
This docker-compose.yml
will create the admin database and admin user, authenticate as the admin user, then create the real database and add the real user:
version: '3'
services:
# app:
# build: .
# env_file: .env
# environment:
# DB_HOST: 'mongodb://mongodb'
mongodb:
image: mongo:4
environment:
MONGO_INITDB_ROOT_USERNAME: admin-user
MONGO_INITDB_ROOT_PASSWORD: admin-password
DB_NAME: $DB_NAME
DB_USER: $DB_USER
DB_PASSWORD: $DB_PASSWORD
ports:
- 27017:27017
volumes:
- db-data:/data/db
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
volumes:
db-data:
Other answers suppose you use minikube with VM, so your local images are not accessible from minikube VM.
In case if you use minikube with --vm-driver=none
, you can easily reuse local images by setting image_pull_policy
to Never:
kubectl run hello-foo --image=foo --image-pull-policy=Never
or setting imagePullPolicy
field for cotainers in corresponding .yaml
manifests.
Docker Compose does not support the deploy
key. It's only respected when you use your version 3 YAML file in a Docker Stack.
This message is printed when you add the deploy
key to you docker-compose.yml
file and then run docker-compose up -d
WARNING: Some services (database) use the 'deploy' key, which will be ignored. Compose does not support 'deploy' configuration - use
docker stack deploy
to deploy to a swarm.
The documentation (https://docs.docker.com/compose/compose-file/#deploy) says:
Specify configuration related to the deployment and running of services. This only takes effect when deploying to a swarm with docker stack deploy, and is ignored by docker-compose up and docker-compose run.
I had the same issue, docker-compose was creating a directory instead of a file, then crashing mid-way.
what i did :
run the container without mapping the file
copy the config file to the host location :
docker cp containername:/var/www/html/config.php ./config.php
remove the container (docker-compose down)
put the mapping back and remount up the container
docker compose will find the config file, and will map that instead of trying to create a directory.
So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.
While ENV
, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG
and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args
at every build without changing our docker file.
For more details, you can refer this.
I would avoid using a relative path. Remember that docker is a daemon/client relationship.
When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database
is then relative to the daemon, not the client.
Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.
In short, don't use a relative path, use an absolute path.
I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.
import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)
np.split(df, [100,200,300], axis=0]
wants explicit index numbers which may or may not be desirable.
Depending on your flavour of Linux and PHP version these may vary.
(sudo) yum install zip unzip php-zip
(sudo) apt install zip unzip php-zip
This is a very commonly asked question, you'll be able to find more useful info in the aether by searching <distro> php <version> zip extension
.
I was getting the same exception, but in my case I am using PowerShell to run commands
So, I fixed this with an instruction to unblock multiple files first.
PS C:\> dir C:\executable_file_Path\*PowerShell* | Unblock-File
and then use the following to load the package
& 'C:\path_to_executable\php.exe' "c:\path_to_composer_.phar_file\composer.phar "require desired/package
I was able to resolve by removing composer and reinstalling the proper way. Here is what I did:
I was then able to get composer install to work again. Found my answer at the bottom of this issue: https://github.com/composer/composer/issues/5510
As @alucic mentioned, use:
composer require vendor/package:version
or you can use:
composer update vendor/package:version
You should probably review this StackOverflow post about differences between composer install and composer update.
Related to question about version numbers, you can review Composer documentation on versions, but here in short:
So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.
Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.
It was two things:
I added the volume in docker-compose.yml
:
node:
volumes:
- ./node:/app
I moved the npm install && nodemon app.js
pieces into a CMD
because RUN
adds things to the Union File System, and my volume isn't part of UFS.
# Set the base image to Ubuntu
FROM node:boron
# File Author / Maintainer
MAINTAINER Amin Shah Gilani <[email protected]>
# Install nodemon
RUN npm install -g nodemon
# Add a /app volume
VOLUME ["/app"]
# Define working directory
WORKDIR /app
# Expose port
EXPOSE 8080
# Run npm install
CMD npm install && nodemon app.js
According to the docker-compose reference,
Expose ports. Either specify both ports (HOST:CONTAINER), or just the container port (a random host port will be chosen).
My docker-compose.yml
looks like:
mysql:
image: mysql:5.7
ports:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
-------------------------------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 0.0.0.0:32769->3306/tcp
Expose ports without publishing them to the host machine - they’ll only be accessible to linked services. Only the internal port can be specified.
Ports are not exposed to host machines, only exposed to other services.
mysql:
image: mysql:5.7
expose:
- "3306"
If I do docker-compose ps
, it will look like:
Name Command State Ports
---------------------------------------------------------------
mysql_1 docker-entrypoint.sh mysqld Up 3306/tcp
In recent versions of Docker, expose
doesn't have any operational impact anymore, it is just informative. (see also)
To install Docker for Mac with homebrew:
brew cask install docker
To install the command line completion:
brew install bash-completion
brew install docker-completion
brew install docker-compose-completion
brew install docker-machine-completion
Below is working solution for me, please follow these steps
Open PowerShell as administrator or CMD prompt as administrator
Run this command in PowerShell-> bcdedit /set hypervisorlaunchtype auto
Now restart the system and try again.
cheers.
I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as
KAPACITOR_BASE_URL: http://kapacitor:9092
In above http://[**kapacitor**]:9092
would not resolve to http://172.20.0.2:9092
I resolved the static IPs issues using subnetting configurations.
version: "3.3"
networks:
frontend:
ipam:
config:
- subnet: 172.20.0.0/24
services:
db:
image: postgres:9.4.4
networks:
frontend:
ipv4_address: 172.20.0.5
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
redis:
image: redis:latest
networks:
frontend:
ipv4_address: 172.20.0.6
ports:
- "6379"
influxdb:
image: influxdb:latest
ports:
- "8086:8086"
- "8083:8083"
volumes:
- ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
- ../influxdb/inxdb:/var/lib/influxdb
networks:
frontend:
ipv4_address: 172.20.0.4
environment:
INFLUXDB_HTTP_AUTH_ENABLED: "false"
INFLUXDB_ADMIN_ENABLED: "true"
INFLUXDB_USERNAME: "db_username"
INFLUXDB_PASSWORD: "12345678"
INFLUXDB_DB: db_customers
kapacitor:
image: kapacitor:latest
ports:
- "9092:9092"
networks:
frontend:
ipv4_address: 172.20.0.2
depends_on:
- influxdb
volumes:
- ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
- ../kapacitor/kapdb:/var/lib/kapacitor
environment:
KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086
web:
build: .
environment:
RAILS_ENV: $RAILS_ENV
command: bundle exec rails s -b 0.0.0.0
ports:
- "3000:3000"
networks:
frontend:
ipv4_address: 172.20.0.3
links:
- db
- kapacitor
depends_on:
- db
volumes:
- .:/var/app/current
environment:
DATABASE_URL: postgres://postgres@db
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: postgres
INFLUX_URL: http://influxdb:8086
INFLUX_USER: db_username
INFLUX_PWD: 12345678
KAPACITOR_BASE_URL: http://172.20.0.2:9092
KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000
volumes:
postgres_data:
Using Manjaro(Arch) Linux:
$ sudo pacman -S php-gd
In file /etc/php/php-ini, add the line:
extension=gd.so
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
You have to create a separate volume for mysql data.
So it will look like this:
volumes_from:
- data
volumes:
- ./mysql-data:/var/lib/mysql
And no, /var/lib/mysql
is a path inside your mysql container and has nothing to do with a path on your host machine. Your host machine may even have no mysql at all. So the goal is to persist an internal folder from a mysql container.
The output of dpkg -s ...
demonstrates that docker-compose
is not installed from a package. Without more information from you there are at least two possibilities:
docker-compose simply isn't installed at all, and you need to install it.
The solution here is simple: install docker-compose
.
docker-compose is installed in your $HOME
directory (or other location not on root's $PATH
).
There are several solution in this case. The easiest is probably to replace:
sudo docker-compose ...
With:
sudo `which docker-compose` ...
This will call sudo
with the full path to docker-compose
.
You could alternatively install docker-compose
into a system-wide directory, such as /usr/local/bin
.
Check if the following folders exists, if not create these folders.
UPDATE: As of docker-compose file version 3.5:
I came across a similar problem and I solved it by adding a small change in one of my docker-compose.yml project.
For instance, we have two API's scoring
and ner
. Scoring
API needs to send a request to the ner
API for processing the input request. In order to do that they both are supposed to share the same network.
Note: Every container has its own network which is automatically created at the time of running the app inside docker. For example ner API network will be created like ner_default
and scoring API network will be named as scoring default
. This solution will work for version: '3'.
As in the above scenario, my scoring API wants to communicate with ner API then I will add the following lines. This means Whenever I create the container for ner API then it automatically added to the scoring_default network.
networks:
default:
external:
name: scoring_default
version: '3'
services:
ner:
container_name: "ner_api"
build: .
...
networks:
default:
external:
name: scoring_default
version: '3'
services:
api:
build: .
...
We can see this how the above containers are now a part of the same network called scoring_default
using the command:
docker inspect scoring_default
{
"Name": "scoring_default",
....
"Containers": {
"14a6...28bf": {
"Name": "ner_api",
"EndpointID": "83b7...d6291",
"MacAddress": "0....",
"IPv4Address": "0.0....",
"IPv6Address": ""
},
"7b32...90d1": {
"Name": "scoring_api",
"EndpointID": "311...280d",
"MacAddress": "0.....3",
"IPv4Address": "1...0",
"IPv6Address": ""
},
...
}
I ran into the same issue several times. Restarting docker seems to do the trick
The docker-compose documentation for the 'up' command clearly states that it updates the container should the image be changed since the last 'up' was performed:
If there are existing containers for a service, and the service’s configuration or image was changed after the container’s creation, docker-compose up picks up the changes by stopping and recreating the containers (preserving mounted volumes).
So by using 'stop' followed by 'pull' and then 'up' this should therefore avoid issues of lost volumes for the running containers, except of course, for containers whose images have been updated.
I am currently experimenting with this process and will include my results in this comment shortly.
The command
clause does work as @Karthik says above.
As a simple example, the following service will have a -inMemory
added to its ENTRYPOINT
when docker-compose up
is run.
version: '2'
services:
local-dynamo:
build: local-dynamo
image: spud/dynamo
command: -inMemory
Unfortunately we need to run docker-compose logs
separately from docker-compose run
. In order to get this to work reliably we need to suppress the docker-compose run
exit status then redirect the log and exit with the right status.
#!/bin/bash
set -euo pipefail
docker-compose run app | tee app.log || failed=yes
docker-compose logs --no-color > docker-compose.log
[[ -z "${failed:-}" ]] || exit 1
The thing is that you are using the option -t
when running your container.
Could you check if enabling the tty
option (see reference) in your docker-compose.yml file the container keeps running?
version: '2'
services:
ubuntu:
build: .
container_name: ubuntu
volumes:
- ~/sph/laravel52:/www/laravel
ports:
- "80:80"
tty: true
Jenkins "boolean" parameters are really just a shortcut for the "choice parameter" type with the choices hardcoded to the strings "true" and "false", and with a checkbox to set the string variable. But in the end, it is just that: a string variable, with nothing to do with a true boolean. That's why you need to convert the string to a boolean if you don't want to do a string comparison like:
if (myBoolean == "true")
This works for me with php 7.2
sudo apt-get install php7.2-xml
For me it only fetched new dependencies from Docker Hub with both --no-cache
and --pull
(which are available for docker-compose build
.
# other steps before rebuild
docker-compose build --no-cache --pull nginx # rebuild nginx
# other steps after rebuild, e.g. up (see other answers)
On Linux, you can download the Docker Compose binary from the Compose repository release page on GitHub. Follow the instructions from the link, which involve running the curl command in your terminal to download the binaries. These step-by-step instructions are also included below.
1:Run this command to download the current stable release of Docker Compose:
sudo curl -L "https://github.com/docker/compose/releases/download/1.26.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
To install a different version of Compose, substitute 1.26.2 with the version of Compose you want to use.
2:Apply executable permissions to the binary:
sudo chmod +x /usr/local/bin/docker-compose
Note: If the command docker-compose fails after installation, check your path. You can also create a symbolic link to /usr/bin or any other directory in your path.
If anyone from the future also wanders up here:
docker-compose exec container_name sh
or
docker-compose exec container_name bash
or you can run single lines like
docker-compose exec container_name php -v
That is after you already have your containers up and running
This error can occur especially when you are updating large libraries or libraries with a lot of dependencies. Composer can be quite memory hungry.
Be sure that your composer itself is updated to the latest version:
php composer.phar --self-update
You can increase the memory limit for composer temporarily by adding the composer memory limit environment variable:
COMPOSER_MEMORY_LIMIT=128MB php composer.phar update
Use the format “128M” for megabyte or “2G” for gigabyte. You can use the value “-1” to ignore the memory limit completely.
Another way would be to increase the PHP memory limit:
php -d memory_limit=512M composer.phar update ...
Maybe I am answering very late. But I was also having a problem configuring host network in docker compose. Then I read the documentation thoroughly and made the changes and it worked. Please note this configuration is for docker-compose version "3.7". Here einwohner_net and elk_net_net are my user-defined networks required for my application. I am using host net to get some system metrics.
Link To Documentation https://docs.docker.com/compose/compose-file/#host-or-none
version: '3.7'
services:
app:
image: ramansharma/einwohnertomcat:v0.0.1
deploy:
replicas: 1
ports:
- '8080:8080'
volumes:
- type: bind
source: /proc
target: /hostfs/proc
read_only: true
- type: bind
source: /sys/fs/cgroup
target: /hostfs/sys/fs/cgroup
read_only: true
- type: bind
source: /
target: /hostfs
read_only: true
networks:
hostnet: {}
networks:
- einwohner_net
- elk_elk_net
networks:
einwohner_net:
elk_elk_net:
external: true
hostnet:
external: true
name: host
When you installed composer pretty sure you used $ sudo
command because of that the ~/.composer
folder was created by the root.
Run this to fix the issue:
$ sudo chown -R $USER $HOME/.composer
The post needs an update after the links
option is deprecated.
Basically, links
is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network
. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.
For docker run
, --link
is also deprecated and should be replaced by a custom network.
docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image
depends_on
expresses start order (and implicitly image pulling order), which was a good side effect of links
.
On Ubuntu 16.04 php7 is now the default, so if you follow the top answers and are still having this issue, check your php version.
php --version
If your default php version is php7, but you followed an answer using php5 packages, you can use the following command to set the default version of php to php5.6:
sudo update-alternatives --set php $(which php5.6)
It seems like the other answers here all misunderstood your question. If I understand correctly, you want to make requests to localhost:6379 (the default for redis) and have them be forwarded, automatically, to the same port on your redis container.
https://unix.stackexchange.com/a/101906/38639 helped me get to the right answer.
First, you'll need to install the nc
command on your image. On CentOS, this package is called nmap-ncat, so in the example below, just replace this with the appropriate package if you are using a different OS as your base image.
Next, you'll need to tell it to run a certain command each time the container boots up. You can do this using CMD.
# Add this to your Dockerfile
RUN yum install -y --setopt=skip_missing_names_on_install=False nmap-ncat
COPY cmd.sh /usr/local/bin/cmd.sh
RUN chmod +x /usr/local/bin/cmd.sh
CMD ["/usr/local/bin/cmd.sh"]
Finally, we'll need to set up port-forwarding in cmd.sh. I found that nc
, even with the -l
and -k
options, will occasionally terminate when a request is completed, so I'm using a while-loop to ensure that it's always running.
# cmd.sh
#! /usr/bin/env bash
while nc -l -p 6379 -k -c "nc redis 6379" || true; do true; done &
tail -f /dev/null # Or any other command that never exits
This issue occurs due to openssl and extension director so uncomment below extensions in php.ini
file
extension=php_openssl.dll
extension_dir = "ext"
Its works on my machine.
For fixing:
No matching client found for package name 'com.example.exampleapp:
You should get a valid google-service.json
file for your package from here
For fixing:
Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 8.3.0.:
You should move apply plugin: 'com.google.gms.google-services'
to the end of your app gradle.build
file. Something like this:
dependencies {
...
}
apply plugin: 'com.google.gms.google-services'
I am pretty sure that those volumes are actually mounted on your system. Look in /proc/mounts and you will see them there. You will likely need to sudo umount <path>
or sudo umount -f -n <path>
. You should be able to get the mounted path either in /proc/mounts or through docker volume inspect
Is there slight possibility you deleted default machine? But, first check if all files are there (OSX, similar on other systems)
brew install docker docker-compose docker-machine xhyve docker-machine-driver-xhyve
brew link docker docker-compose docker-machine xhyve docker-machine-driver-xhyve
sudo chown root:wheel /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
sudo chmod u+s /usr/local/opt/docker-machine-driver-xhyve/bin/docker-machine-driver-xhyve
Also, install Docker App, as it much easier to maintain containers:
brew cask reinstall docker
ans start Docker app from finder (wait until service is fully started)
Then, check instalation with:
docker-machine ls
if no machines are present in list, create one and start it:
docker-machine create default
docker-machine start default
After this, build, compose and all other commands should work properly.
For me it has worked this in this order:
php artisan config:cache
php artisan config:clear
php artisan cache:clear
And I've tried all the rests without luck.
For some reasons, @ChintanSoni's answer didn't worked. I tried deleting the build
folder manually but couldn't delete some files since they were being used by some process. Cleaning and re-building the project didn't help so I opened task manager
, selected JAVA(TM) Platform SE binary
and pressed on 'End task`.
Then I tried to run the project once again and it started compiling fine.
This feature was added in Compose 1.6.
Reference: https://docs.docker.com/compose/compose-file/#args
services:
web:
build:
context: .
args:
FOO: foo
This is for mac or ubuntu user, try this on terminal
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
You should run:
composer dump-autoload
and if does not work you should:
re-install composer
you need to download the previous version, xampp actually present bug in its latest version.
Good Luck!
you can try:
services:
nameis:
container_name: hi_my
build: .
image: hi_my_nameis:v1.0.0
First Login to your server and check the PHP version which is installed on your server.
And then run the following commands:
sudo apt-get install php7.2-curl
sudo service apache2 restart
Replace the PHP version ( php7.2 ), with your PHP version.
You can set the max_fails and fail_timeout directives of nginx to indicate that the nginx should retry the x number of connection requests to the container before failing on the upstream server unavailability.
You can tune these two numbers as per your infrastructure and speed at which the whole setup is coming up. You can read more details about the health checks section of the below URL: http://nginx.org/en/docs/http/load_balancing.html
Following is the excerpt from http://nginx.org/en/docs/http/ngx_http_upstream_module.html#server
max_fails=number
sets the number of unsuccessful attempts to communicate with the server that should happen in the duration set by the fail_timeout parameter to consider the server unavailable for a duration also set by the fail_timeout parameter. By default, the number of unsuccessful attempts is set to 1. The zero value disables the accounting of attempts. What is considered an unsuccessful attempt is defined by the proxy_next_upstream, fastcgi_next_upstream, uwsgi_next_upstream, scgi_next_upstream, and memcached_next_upstream directives.
fail_timeout=time
sets the time during which the specified number of unsuccessful attempts to communicate with the server should happen to consider the server unavailable; and the period of time the server will be considered unavailable. By default, the parameter is set to 10 seconds.
To be precise your modified nginx config file should be as follows (this script is assuming that all the containers are up by 25 seconds at least, if not, please change the fail_timeout or max_fails in below upstream section): Note: I didn't test the script myself, so you could give it a try!
upstream phpupstream {
server waapi_php_1:9000 fail_timeout=5s max_fails=5;
}
server {
listen 80;
root /var/www/test;
error_log /dev/stdout debug;
access_log /dev/stdout;
location / {
# try to serve file directly, fallback to app.php
try_files $uri /index.php$is_args$args;
}
location ~ ^/.+\.php(/|$) {
# Referencing the php service host (Docker)
fastcgi_pass phpupstream;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
# We must reference the document_root of the external server ourselves here.
fastcgi_param SCRIPT_FILENAME /var/www/html/public$fastcgi_script_name;
fastcgi_param HTTPS off;
}
}
Also, as per the following Note from docker (https://github.com/docker/docker.github.io/blob/master/compose/networking.md#update-containers), it is evident that the retry logic for checking the health of the other containers is not docker's responsibility and rather the containers should do the health check themselves.
Updating containers
If you make a configuration change to a service and run docker-compose up to update it, the old container will be removed and the new one will join the network under a different IP address but the same name. Running containers will be able to look up that name and connect to the new address, but the old address will stop working.
If any containers have connections open to the old container, they will be closed. It is a container's responsibility to detect this condition, look up the name again and reconnect.
To see how much space each container's log is taking up, use this:
docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl
(you might need a sudo
before ls
).
I claimed 3.5gb space in ubuntu AWS through this.
clean docker
docker stop $(docker ps -qa) && docker system prune -af --volumes
build again
docker build .
docker-compose build
docker-compose up
For php 7.1
sudo apt-get install php7.1-mbstring
Cheers!
For ones who got permission denied
for saving operation, here is the command that worked for me:
$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png --output py.png
For docker-compose version 2 file format, you can build and tag an image for one service and then use that same built image for another service.
For my case, I want to set up an elasticsearch cluster with 2 nodes, they both need to use the same image, but configured to run differently. I also want to build my own custom elasticsearch image from my own Dockerfile. So this is what I did (docker-compose.yml
):
version: '2'
services:
es-master:
build: ./elasticsearch
image: porter/elasticsearch
ports:
- "9200:9200"
container_name: es_master
es-node:
image: porter/elasticsearch
depends_on:
- es-master
ports:
- "9200"
command: elasticsearch --discovery.zen.ping.unicast.hosts=es_master
You can see that in the first service definition es-master
, I use the build
option to build an image from the Dockerfile in ./elasticsearch
. I tag the image with the name porter/elasticsearch
with the image
option.
Then, I reference this built image in the es-node
service definition with the image
option, and also use a depends_on
to make sure the other container es-master
is built and run first.
If you forget to run:
php artisan key:generate
You would be face this error : Composer could not find a composer.json
Using restart: unless-stopped
or restart: always
may solve this problem.
If worker container
stops when rabbitMQ is not ready, it will be restarted until it is.
To restart a service with changes here are the steps that I performed:
docker-compose stop -t 1 worker
docker-compose build worker
docker-compose up --no-start worker
docker-compose start worker
database_password: password
would between quotes: " or '.
like so:
database_password: "password"
Yes, docker has restart policies such as docker run --restart=always
that will handle this. This is also available in the compose.yml config file as restart: always
.
curl -sS https://getcomposer.org/installer | sudo php
sudo mv composer.phar /usr/local/bin/composer
export PATH="$HOME/.composer/vendor/bin:$PATH"
If you have installed by this way simply
Delete composer.phar from where you've putted it.
In this case path will be /usr/local/bin/composer
Note: There is no need to delete the exported path.
Oh, just with this:
$ docker-compose up client server database
Use:
docker attach <container name/id here>
The other way, albeit there is a danger to it, is to use attach
, but if you Ctrl + C to exit the session, you will also stop the container. If you just want to see what is happening, use docker logs -f
.
:~$ docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach to a running container
Options:
--detach-keys string Override the key sequence for detaching a container
--help Print usage
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
try using ";" to separate the commands if you are in verions two e.g.
command: "sleep 20; echo 'a'"
You can just move node_modules
into a /
folder.
FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
RUN npm install \
&& mv node_modules /node_modules
COPY . /worker/
As of docker-compose version 3 and later, you can just use the hostname
key:
version: '3'
services:
dns:
hostname: 'your-name'
If the .env
a file is missing, then there is another way to generate a .env file
You can download env.example, rename it to .env
and edit it. Just set up correct DB credentials etc.
Don't forget to When you use the php artisan key:generate
it will generate the new key to your .env
file
As pointed out before, the problem was that the files were not visible by the fpm container. However to share data among containers the recommended pattern is using data-only containers (as explained in this article).
Long story short: create a container that just holds your data, share it with a volume, and link this volume in your apps with volumes_from
.
Using compose (1.6.2 in my machine), the docker-compose.yml
file would read:
version: "2"
services:
nginx:
build:
context: .
dockerfile: nginx/Dockerfile
ports:
- "80:80"
links:
- fpm
volumes_from:
- data
fpm:
image: php:fpm
volumes_from:
- data
data:
build:
context: .
dockerfile: data/Dockerfile
volumes:
- /var/www/html
Note that data
publishes a volume that is linked to the nginx
and fpm
services. Then the Dockerfile
for the data service, that contains your source code:
FROM busybox
# content
ADD path/to/source /var/www/html
And the Dockerfile
for nginx, that just replaces the default config:
FROM nginx
# config
ADD config/default.conf /etc/nginx/conf.d
For the sake of completion, here's the config file required for the example to work:
server {
listen 0.0.0.0:80;
root /var/www/html;
location / {
index index.php index.html;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass fpm:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
}
which just tells nginx to use the shared volume as document root, and sets the right config for nginx to be able to communicate with the fpm container (i.e.: the right HOST:PORT
, which is fpm:9000
thanks to the hostnames defined by compose, and the SCRIPT_FILENAME
).
I had accidentally commented out:
require __DIR__.'/../bootstrap/autoload.php';
in /public/index.php
When pasting in some debugging statements.
"better" is relative. It all depends on what your needs are. Docker compose is for orchestrating multiple containers. If these images already exist in the docker registry, then it's better to list them in the compose file. If these images or some other images have to be built from files on your computer, then you can describe the processes of building those images in a Dockerfile.
I understand that Dockerfiles are used in Docker Compose, but I am not sure if it is good practice to put everything in one large Dockerfile with multiple FROM commands for the different images?
Using multiple FROM in a single dockerfile is not a very good idea because there is a proposal to remove the feature. 13026
If for instance, you want to dockerize an application which uses a database and have the application files on your computer, you can use a compose file together with a dockerfile as follows
mysql:
image: mysql:5.7
volumes:
- ./db-data:/var/lib/mysql
environment:
- "MYSQL_ROOT_PASSWORD=secret"
- "MYSQL_DATABASE=homestead"
- "MYSQL_USER=homestead"
ports:
- "3307:3306"
app:
build:
context: ./path/to/Dockerfile
dockerfile: Dockerfile
volumes:
- ./:/app
working_dir: /app
FROM php:7.1-fpm
RUN apt-get update && apt-get install -y libmcrypt-dev \
mysql-client libmagickwand-dev --no-install-recommends \
&& pecl install imagick \
&& docker-php-ext-enable imagick \
&& docker-php-ext-install pdo_mysql \
&& curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
Use .env file to define dynamic values in docker-compse.yml. Be it port or any other value.
Sample docker-compose:
testcore.web:
image: xxxxxxxxxxxxxxx.dkr.ecr.ap-northeast-2.amazonaws.com/testcore:latest
volumes:
- c:/logs:c:/logs
ports:
- ${TEST_CORE_PORT}:80
environment:
- CONSUL_URL=http://${CONSUL_IP}:8500
- HOST=${HOST_ADDRESS}:${TEST_CORE_PORT}
Inside .env file you can define the value of these variables:
CONSUL_IP=172.31.28.151
HOST_ADDRESS=172.31.16.221
TEST_CORE_PORT=10002
"config": {
"platform": {
"ext-pcntl": "7.2",
"ext-posix": "7.2"
}
}
Try running dockerd
or sudo dockerd
if required first to start daemon. If you start dockerd
with sudo
you may want to run docker-compose up
with sudo
also. otherwise it's fine.
Working solution from https://github.com/docker/compose/issues/4181
Basic docker-compose.yml
with extra hosts:
version: '3'
services:
api:
build: .
ports:
- "5003:5003"
extra_hosts:
- "your-host.name.com:162.242.195.82" #host and ip
- "your-host--1.name.com your-host--2.name.com:50.31.209.229" #multiple hostnames with same ip
The content in the /etc/hosts
file in the created container:
162.242.195.82 your-host.name.com
50.31.209.229 your-host--1.name.com your-host--2.name.com
You can check the /etc/hosts
file with the following commands:
$ docker-compose -f path/to/file/docker-compose.yml run api bash # 'api' is service name
#then inside container bash
root@f7c436910676:/app# cat /etc/hosts
This is happening because there is a field in .env
file named, APP_KEY, which is blank now, we need some random key for this variable.
Follow these steps to get rid of this problem.
1) .env.example
to .env
2) Go to your root directory in your command prompt (If you are using windows)/terminal (If you are using MAC or LINUX) where you have installed laravel project/files and run following command
php artisan key:generate
and then run your project. It's all done.
In Laravel Version - 4, HTML and Form existed, but not now.
Why:
The only reason is they have collected some user requirements and they want it more lightweight and so they removed it as in the sense that a user can add it manually.
What to do to add HTML & Forms in Laravel 5.2 or 5.3:
For 5.2:
Go to the Laravel Collective site and installation processes have demonstrated their.
Like for 5.2: on the command line, run the command
composer require "laravelcollective/html":"^5.2.0"
Then, in the provider array which is in config/app.php. Add this line at last using a comma(,):
Collective\Html\HtmlServiceProvider::class,
For using HTML and FORM text we need to alias them in the aliases array of config/app.php. Add the two lines at the last
'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,
And for 5.3:
Just run the command
composer require "laravelcollective/html":"^5.3.0"
And the rest of the procedure is like 5.2.
Then you can use Laravel Form and other HTML links in your projects. For this, follow this documentation:
5.2: https://laravelcollective.com/docs/5.2/html
5.3: https://laravelcollective.com/docs/5.3/html
Demo Code:
To open a form, open and close a tag:
{!! Form::open(['url' => 'foo/bar']) !!}
{!! Form::close() !!}
And for creating label and input text with a Bootstrap form-control class and other use:
{!! Form::label('title', 'Post Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}
And for more, use the documentation, https://laravelcollective.com/.
Just run the following commands,
composer update
Or
composer install
following commands will do the same perfectly
rm -rf vendor
composer install
You are probably connecting fine but don't have sufficient privileges to run show dbs
.
You don't need to run the db.auth if you pass the auth in the command line:
mongo somewhere.mongolayer.com:10011/my_database -u username -p password
Once you connect are you able to see collections?
> show collections
If so all is well and you just don't have admin privileges to the database and can't run the show dbs
I solved the problem by deleting reference to the file and adding it again in project. In my case it works.
You need to create another migration file - and place it in there:
Run
Laravel 4: php artisan migrate:make rename_stnk_column
Laravel 5: php artisan make:migration rename_stnk_column
Then inside the new migration file place:
class RenameStnkColumn extends Migration
{
public function up()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id', 'id_stnk');
});
}
public function down()
{
Schema::table('stnk', function(Blueprint $table) {
$table->renameColumn('id_stnk', 'id');
});
}
}
For zsh and bash:
export PATH="$HOME/.config/composer/vendor/bin:$PATH"
source ~/.zshrc
source ~/.bashrc
For bash only:
export PATH=~/.config/composer/vendor/bin:$PATH
source ~/.bashrc
I faced the same problem today. You need to enable the intl PHP extension in your PHP configuration (.ini
).
Solution Xampp (Windows)
/xampp/php/php.ini
;extension=php_intl.dll
to extension=php_intl.dll
(remove the semicolon)/xampp/php/ic*.dll
files to /xampp/apache/bin
Solution Linux (thanks to Annamalai Somasundaram)
Install the php5-intl extension sudo apt-get install php5-intl
1.1. Alternatively use sudo yum install php5-intl
if you are on CentOS or Fedora.
Restart apache sudo service apache2 restart
Solution Mac/OSX (homebrew) (thanks to deizel)
brew install php56-intl
No available formula for php56-intl
follow these instructions.sudo apachectl restart
Eventually you can run composer install
to check if it's working. It will give an error if it's not.
If our CustomTableSeeder is in same directory with DatabaseSeeder we should use like below:
$this->call('database\seeds\CustomTableSeeder');
in our DatabaseSeeder File; then another error will be thrown that says: 'DB Class not found' then we should add our DB facade to our CustomTableSeeder File like below:
use Illuminate\Support\Facades\DB;
it worked for me!
With df.plot()
Normally when quickly plotting a DataFrame, I use pd.DataFrame.plot()
. This takes the index as the x value, the value as the y value and plots each column separately with a different color.
A DataFrame in this form can be achieved by using set_index
and unstack
.
import matplotlib.pyplot as plt
import pandas as pd
carat = [5, 10, 20, 30, 5, 10, 20, 30, 5, 10, 20, 30]
price = [100, 100, 200, 200, 300, 300, 400, 400, 500, 500, 600, 600]
color =['D', 'D', 'D', 'E', 'E', 'E', 'F', 'F', 'F', 'G', 'G', 'G',]
df = pd.DataFrame(dict(carat=carat, price=price, color=color))
df.set_index(['color', 'carat']).unstack('color')['price'].plot(style='o')
plt.ylabel('price')
With this method you do not have to manually specify the colors.
This procedure may make more sense for other data series. In my case I have timeseries data, so the MultiIndex consists of datetime and categories. It is also possible to use this approach for more than one column to color by, but the legend is getting a mess.
Based on comments, and due to the fact that @Thinkerer (the OP - original poster) created a plunker for this case, I decided to append another answer with more details.
The first and important change:
// instead of this
$urlRouterProvider.otherwise('/tab/post');
// we have to use this
$urlRouterProvider.otherwise('/tab/posts');
because the states definition is:
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: 'tabs.html'
})
.state('tab.posts', {
url: '/posts',
views: {
'tab-posts': {
templateUrl: 'tab-posts.html',
controller: 'PostsCtrl'
}
}
})
and we need their concatenated url '/tab'
+ '/posts'
. That's the url we want to use as a otherwise
The rest of the application is really close to the result we need...
E.g. we stil have to place the content into same view targetgood, just these were changed:
.state('tab.newpost', {
url: '/newpost',
views: {
// 'tab-newpost': {
'tab-posts': {
templateUrl: 'tab-newpost.html',
controller: 'NavCtrl'
}
}
because .state('tab.newpost'
would be replacing the .state('tab.posts'
we have to place it into the same anchor:
<ion-nav-view name="tab-posts"></ion-nav-view>
Finally some adjustments in controllers:
$scope.create = function() {
$state.go('tab.newpost');
};
$scope.close = function() {
$state.go('tab.posts');
};
As I already said in my previous answer and comments ... the $state.go()
is the only right way how to use ionic
or ui-router
Check that all here
Final note - I made running just navigation between tab.posts
... tab.newpost
... the rest would be similar
I did this and it works on osx:
lunch your terminal
nano ~/.bash_profile
And paste
export PATH=~/.composer/vendor/bin:$PATH
press control + x
press the y key
press the return / enter key
I modified the code as follow:
ViewModel
using System.Collections.Generic;
using ContosoUniversity.Models;
namespace ContosoUniversity.ViewModels
{
public class InstructorIndexData
{
public PagedList.IPagedList<Instructor> Instructors { get; set; }
public PagedList.IPagedList<Course> Courses { get; set; }
public PagedList.IPagedList<Enrollment> Enrollments { get; set; }
}
}
Controller
public ActionResult Index(int? id, int? courseID,int? InstructorPage,int? CoursePage,int? EnrollmentPage)
{
int instructPageNumber = (InstructorPage?? 1);
int CoursePageNumber = (CoursePage?? 1);
int EnrollmentPageNumber = (EnrollmentPage?? 1);
var viewModel = new InstructorIndexData();
viewModel.Instructors = db.Instructors
.Include(i => i.OfficeAssignment)
.Include(i => i.Courses.Select(c => c.Department))
.OrderBy(i => i.LastName).ToPagedList(instructPageNumber,5);
if (id != null)
{
ViewBag.InstructorID = id.Value;
viewModel.Courses = viewModel.Instructors.Where(
i => i.ID == id.Value).Single().Courses.ToPagedList(CoursePageNumber,5);
}
if (courseID != null)
{
ViewBag.CourseID = courseID.Value;
viewModel.Enrollments = viewModel.Courses.Where(
x => x.CourseID == courseID).Single().Enrollments.ToPagedList(EnrollmentPageNumber,5);
}
return View(viewModel);
}
View
<div>
Page @(Model.Instructors.PageCount < Model.Instructors.PageNumber ? 0 : Model.Instructors.PageNumber) of @Model.Instructors.PageCount
@Html.PagedListPager(Model.Instructors, page => Url.Action("Index", new {InstructorPage=page}))
</div>
I hope this would help you!!
Globally install Composer on OS X 10.11 El Capitan
This command will NOT work in OS X 10.11:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/bin --filename=composer
Instead, let's write to the /usr/local/bin path for the user:
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
Now we can access the composer command globally, just like before.
Older versions of Homestead maps folders in ~/Code
to say for example by default ~/Code/laravel/public
. Notice the case capitalisations in ~/Code
. These are case sensitive. New versions use lower case ~/code
. Update these directories in your Homestead.yaml
according to your actual directories.
TL;DR;
Update ~/Code
to ~/code
or vice versa depending on your actual directory names.
From the composer help create-project
command
The create-project command creates a new project from a given
package into a new directory. If executed without params and in a directory with a composer.json file it installs the packages for the current project.
You can use this command to bootstrap new projects or setup a clean
version-controlled installation for developers of your project.[version]
You can also specify the version with the package name using = or : as separator.
To install unstable packages, either specify the version you want, or use the --stability=dev (where dev can be one of RC, beta, alpha or dev).
This command works:
composer create-project laravel/laravel=4.1.27 your-project-name --prefer-dist
This works with the * notation.
To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")
Yii::app()->baseUrl
The following Code would return just "localhost/yiistore2/upload" without http[s]://
Yii::app()->getBaseUrl(true)
Or you could get the webroot path (would return "d:\wamp\www\yii2store")
Yii::getPathOfAlias('webroot')
You can do any one of the below two methods:
Running the below command (most recommended way to remove your package without updating your other packages)
$ composer remove vendor/package
Go to your composer.json file and then run command like below it will remove your package (but it will also update your other packages)
$ composer update
I solved this by copying it over to the missing directory:
cp /opt/X11/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib
brew reinstall libpng kept installing libpng16, not libpng15 so I was forced to do the above.
For php.ini 5.6 version (check version using php -v)
;extension=php_intl.dll ; remove semicolon and keep like this extension=php_intl.dll
For php.ini 7.* version
;extension=intl ; remove semicolon and keep like this extension=intl
Note - After That Make Sure to Restart Your Xampp,Wamp Server in you Local Machine.
On production servers I rename vendor
to vendor-<datetime>
, and during deployment will have two vendor dirs.
A HTTP cookie causes my system to choose the new vendor autoload.php
, and after testing I do a fully atomic/instant switch between them to disable the old vendor dir for all future requests, then I delete the previous dir a few days later.
This avoids any problem caused by filesystem caches I'm using in apache/php, and also allows any active PHP code to continue using the previous vendor dir.
Despite other answers recommending against it, I personally run composer install
on the server, since this is faster than rsync from my staging area (a VM on my laptop).
I use --no-dev --no-scripts --optimize-autoloader
. You should read the docs for each one to check if this is appropriate on your environment.
For windows, I made composer.cmd and used the below text:
php c:\programs\php\composer.phar %*
where composer.phar is installed and c:\programs\php\ is added to my path.
Not sure why this isn't done automatically.
I was able to install composer on HostGator's shared hosting. Logged in to SSH with Putty, right after login you should be in your home directory, which is usually /home/username, where username is your username obviously. Then ran the curl command posted by @niutech above. This downloaded the composer to my home directory and it's now accessible and working well.
dont use php composer.phar self-update
First go to Your project directory
simply use composer.phar self-update
This works for me
Run composer self-update
and composer clearcache
remove vendor and composer.lock
restart your local environment and then run
php -d memory_limit=-1 /usr/local/bin/composer install
Laravel's Autoload is a bit different:
1) It will in fact use Composer for some stuff
2) It will call Composer with the optimize flag
3) It will 'recompile' loads of files creating the huge bootstrap/compiled.php
4) And also will find all of your Workbench packages and composer dump-autoload them, one by one.
First execute composer clearcache
Then clear your vendors folder
rm -rf vendor/*
or better yet just remove the specific module which makes problems to avoid having to download all over again.
Enable in php 7 try below command
sudo apt-get install php7.0-curl
Typically, software will run in different environments:
development
testing
staging
production
The dependencies which are declared in the require
section of composer.json
are typically dependencies which are required for running an application or a package in
staging
production
environments, whereas the dependencies declared in the require-dev
section are typically dependencies which are required in
developing
testing
environments.
For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:
friendsofphp/php-cs-fixer
(to detect and fix coding style issues)squizlabs/php_codesniffer
(to detect and fix coding style issues)phpunit/phpunit
(to drive the development using tests)Now, in development
and testing
environments, you would typically run
$ composer install
to install both production
and development
dependencies.
However, in staging
and production
environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run
$ composer install --no-dev
to install only production
dependencies.
In other words, the sections
require
require-dev
indicate to composer
which packages should be installed when you run
$ composer install
or
$ composer install --no-dev
That is all.
Note Development dependencies of packages your application or package depend on will never be installed
For reference, see:
I also had same problem then I found this on there documentation page
So if you want to create a project by name of test_laravel
in directory /Applications/MAMP/htdocs/
then what you need to do is
go to your project parent directory
cd /Applications/MAMP/htdocs
and fire this command
composer create-project laravel/laravel test_laravel --prefer-dist
that's it, this is really easy and it also creates Application Key automatically for you
I solved the same problem in Vagrant. I increased the value of memory_limit and delete composer cache: sudo rm -R ~/.composer and finally vagrant reload.
Wamp works with another php.ini that is in C:\wamp\bin\apache\Apache2.4.4\bin\php.ini. So you need to manualy find the correct file, that is in C:\wamp\bin\php\php5.4.12\php.ini. Uncomment the extension=php_openssl.dll line and just try to install Composer again.
The syntax is using a colon - if there is no colon the above error will occur.
<?php while($query->fetch()): ?>
....
<?php endwhile; ?>
The alternative to this syntax is using curly brackets:
<?php while($query->fetch()) { ?>
....
<?php } ?>
In my case I was calling View::make('User/index')
, where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index')
all started working.
Try this:
export HTTPS_PROXY_REQUEST_FULLURI=false
solved this issue for me working behind a proxy at a company few weeks ago.
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
Because you wanted to install specific package "I need to install only 1 package for my SF2 distribution (DoctrineFixtures)."
php composer.phar require package/package-name:package-version
would be enough
Simply Add 'carousel-item' class in place of item class.
You can use cURL and CRON to run .php files at set times.
Here's an example of what cURL needs to run the .php file:
curl http://localhost/myscript.php
Then setup the CRON job to run the above cURL:
nano -w /var/spool/cron/root
or
crontab -e
Followed by:
01 * * * * /usr/bin/curl http://www.yoursite.com/script.php
For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/
For more info about cURL: What is cURL in PHP?
For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800
Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )
NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.
Best of luck with the automatic PHP running :-)
I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY
To install a new package and only that, you have two options:
Using the require
command, just run:
composer require new/package
Composer will guess the best version constraint to use, install the package, and add it to composer.lock
.
You can also specify an explicit version constraint by running:
composer require new/package ~2.5
–OR–
Using the update
command, add the new package manually to composer.json
, then run:
composer update new/package
If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag --with-dependencies
. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).
Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If php -m
doesn't list mcrypt then it's missing.
Important: Don't forget to specify new/package
when using composer update
! Omitting that argument will cause all dependencies, as well as composer.lock
, to be updated.
List installed dependencies:
composer show -i
composer show -i -t
-i
short for --installed
.
-t
short for --tree
.
You can Set the namespace like:
{!! \Illuminate\Support\Str::words($item->description, 10,'....') !!}
Late answer but adding so other can learn the reason.
You also need to edit the php.ini file in the "wamp\bin\php\php-X.Y.Z" location.
You should make a symlink to php.ini. Sorry for russian link.
\path-to-your-android-sdk-folder\platforms\android-xx\data\res
That package in fact is available through packagist. You don't need a custom repository definition in this case. Just make sure you add a require
(which is always needed) with a matching version constraint.
In general, if a package is available on packagist, do not add a VCS repo. It will just slow things down.
For packages that are not available via packagist, use a VCS (or git) repository, as shown in your question. When you do, make sure that:
require
for the package in questionrequire
matches the versions provided by the VCS repo. You can use composer show <packagename>
to find the available versions. In this case ~2.3
would be a good option.require
matches the name in the remote composer.json
. In this case, it is gedmo/doctrine-extensions
.Here is a sample composer.json
that installs the same package via a VCS repo:
{
"repositories": [
{
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git"
}
],
"require": {
"gedmo/doctrine-extensions": "~2.3"
}
}
The VCS repo docs explain all of this quite well.
If there is a git (or other VCS) repository with a composer.json
available, do not use a "package" repo. Package repos require you to provide all of the metadata in the definition and will completely ignore any composer.json
present in the provided dist and source. They also have additional limitations, such as not allowing for proper updates in most cases.
Avoid package repos (see also the docs).
If you’re concerned about your code breaking, you should commit the composer.lock
to your version control system to ensure all your project collaborators are using the same version of the code. Without a lock file, you will get new third-party code being pulled down each time.
The exception is when you use a meta apps, libraries where the dependencies should be updated on install (like the Zend Framework 2 Skeleton App). So the aim is to grab the latest dependencies each time when you want to start developing.
Source: Composer: It’s All About the Lock File
See also: What are the differences between composer update and composer install?
The composer documentation states that:
After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.
Assuming your "src" dir resides at the same level as "vendor" dir:
the following config is absolutely correct:
{
"autoload": {
"psr-0": {"AppName": "src/"}
}
}
but you must re-update/install dependencies to make it work for you, i.e. run:
php composer.phar update
This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.
Also as noted by @Dom, you can use composer dump-autoload
to update the autoloader without having to go through an update.
An alternative solution is to simply add a route to your routes.rb
It basically catches the Apple request and renders a 404 back to the client. This way your log files aren't cluttered.
# routes.rb at the near-end
match '/:png', via: :get, controller: 'application', action: 'apple_touch_not_found', png: /apple-touch-icon.*\.png/
then add a method 'apple_touch_not_found' to your application_controller.rb
# application_controller.rb
def apple_touch_not_found
render plain: 'apple-touch icons not found', status: 404
end
ColumnNames
is a property of type List<String>
so when you are setting up you need to pass a List<String>
in the Returns
call as an argument (or a func which return a List<String>
)
But with this line you are trying to return just a string
input.SetupGet(x => x.ColumnNames).Returns(temp[0]);
which is causing the exception.
Change it to return whole list:
input.SetupGet(x => x.ColumnNames).Returns(temp);
"No suitable driver" usually means that the JDBC
URL you've supplied to connect has incorrect syntax or when the driver isn't loaded at all.
When the method getConnection is called, the DriverManager
will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.(using Class.forName()
)
For Example
import oracle.jdbc.driver.OracleDriver;
Class.forName("oracle.jdbc.driver.OracleDriver");
Also check that you have ojdbc6.jar
in your classpath. I would suggest to place .jar
at physical location to JBoss "$JBOSS_HOME/server/default/lib/"
directory of your project.
EDIT:
You have mentioned hibernate
lately.
Check that your hibernate.cfg.xml
file has connection properties something like this:
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="hibernate.connection.username">scott</property>
<property name="hibernate.connection.password">tiger</property>
A bit more generic if you put the batch in the same folder as composer.phar:
@ECHO OFF
SET SUBDIR=%~dp0
php %SUBDIR%/composer.phar %*
I'd write it as a comment, but code isn't avail there
Similar approach to @Samuel-bergström:
@font-face {_x000D_
font-family: 'FontAwesome';_x000D_
//src: url('@{fa-font-path}/fontawesome-webfont.eot?v=@{fa-version}');_x000D_
src: _x000D_
//url('@{fa-font-path}/fontawesome-webfont.eot?#iefix&v=@{fa-version}') format('embedded-opentype'),_x000D_
//url('@{fa-font-path}/fontawesome-webfont.woff2?v=@{fa-version}') format('woff2'),_x000D_
url('@{fa-font-path}/fontawesomeregular.woff?v=@{fa-version}') format('woff'),_x000D_
url('@{fa-font-path}/fontawesomeregular.ttf?v=@{fa-version}') format('truetype'),_x000D_
url('@{fa-font-path}/fontawesomeregular.svg?v=@{fa-version}#fontawesomeregular') format('svg');_x000D_
// src: url('@{fa-font-path}/FontAwesome.otf') format('opentype'); // used when developing fonts_x000D_
font-weight: normal;_x000D_
font-style: normal;_x000D_
}
_x000D_
I know it may be 'controversial' to comment out other file types, but happy to hear how to generate .eot or .otf files in the comments.
and finally, as Samuel mentions, update your CSS/LESS with:
.fa-XXX:before { content: "\f501"; }
For MAC and LINUX use the following procedure:
Add the directory where composer.phar is located to you PATH:
export PATH=$PATH:/yourdirectory
and then rename composer.phar to composer:
mv composer.phar composer
Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.
When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.
When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.
You'll find more details about the specification and how to generate such a certificate in this answer.
If you want a certain message, use this:
String phoneNo = "";//The phone number you want to text
String sms= "";//The message you want to text to the phone
Intent smsIntent = new Intent(Intent.ACTION_VIEW, Uri.fromParts("sms", phoneNo, null));
smsIntent.putExtra("sms_body",sms);
startActivity(smsIntent);
Primitive data type
The primitive data type is a basic type provided by a programming language as a basic building block. So it's predefined data types. A primitive type has always a value. It storing simple value.
It specifies the size and type of variable values, so the size of a primitive type depends on the data type and it has no additional methods.
And these are reserved keywords in the language. So we can't use these names as variable, class or method name. A primitive type starts with a lowercase letter. When declaring the primitive types we don't need to allocate memory. (memory is allocated and released by JRE-Java Runtime Environment in Java)
+================+=========+===================================================================================+
| Primitive type | Size | Description |
+================+=========+===================================================================================+
| byte | 1 byte | Stores whole numbers from -128 to 127 |
+----------------+---------+-----------------------------------------------------------------------------------+
| short | 2 bytes | Stores whole numbers from -32,768 to 32,767 |
+----------------+---------+-----------------------------------------------------------------------------------+
| int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 |
+----------------+---------+-----------------------------------------------------------------------------------+
| long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
+----------------+---------+-----------------------------------------------------------------------------------+
| float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits |
+----------------+---------+-----------------------------------------------------------------------------------+
| char | 2 bytes | Stores a single character/letter or ASCII values |
+----------------+---------+-----------------------------------------------------------------------------------+
| boolean | 1 bit | Stores true or false values |
+----------------+---------+-----------------------------------------------------------------------------------+
Reference data type
Reference data type refers to objects. Most of these types are not defined by programming language(except for String, arrays in JAVA). Reference types of value can be null. It storing an address of the object it refers to. Reference or non-primitive data types have all the same size. and reference types can be used to call methods to perform certain operations.
when declaring the reference type need to allocate memory. In Java, we used new
keyword to allocate memory, or alternatively, call a factory method.
Example:
List< String > strings = new ArrayList<>() ; // Calling `new` to instantiate an object and thereby allocate memory.
Point point = Point(1,2) ; // Calling a factory method.
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
To do it by using f-string and with control of the number of trailing digits:
print(f'A number -> {my_number:>20.5f}')
I also made a solution, which is working with Stacks. It's a more modular approach so u don't have to specify each Fragment and Detail Fragment in your FragmentPagerAdapter
. It's build on top of the Example from ActionbarSherlock which derives if I'm right from the Google Demo App.
/**
* This is a helper class that implements the management of tabs and all
* details of connecting a ViewPager with associated TabHost. It relies on a
* trick. Normally a tab host has a simple API for supplying a View or
* Intent that each tab will show. This is not sufficient for switching
* between pages. So instead we make the content part of the tab host
* 0dp high (it is not shown) and the TabsAdapter supplies its own dummy
* view to show as the tab content. It listens to changes in tabs, and takes
* care of switch to the correct paged in the ViewPager whenever the selected
* tab changes.
*
* Changed to support more Layers of fragments on each Tab.
* by sebnapi (2012)
*
*/
public class TabsAdapter extends FragmentPagerAdapter
implements TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final TabHost mTabHost;
private final ViewPager mViewPager;
private ArrayList<String> mTabTags = new ArrayList<String>();
private HashMap<String, Stack<TabInfo>> mTabStackMap = new HashMap<String, Stack<TabInfo>>();
static final class TabInfo {
public final String tag;
public final Class<?> clss;
public Bundle args;
TabInfo(String _tag, Class<?> _class, Bundle _args) {
tag = _tag;
clss = _class;
args = _args;
}
}
static class DummyTabFactory implements TabHost.TabContentFactory {
private final Context mContext;
public DummyTabFactory(Context context) {
mContext = context;
}
@Override
public View createTabContent(String tag) {
View v = new View(mContext);
v.setMinimumWidth(0);
v.setMinimumHeight(0);
return v;
}
}
public interface SaveStateBundle{
public Bundle onRemoveFragment(Bundle outState);
}
public TabsAdapter(FragmentActivity activity, TabHost tabHost, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mTabHost = tabHost;
mViewPager = pager;
mTabHost.setOnTabChangedListener(this);
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
/**
* Add a Tab which will have Fragment Stack. Add Fragments on this Stack by using
* addFragment(FragmentManager fm, String _tag, Class<?> _class, Bundle _args)
* The Stack will hold always the default Fragment u add here.
*
* DON'T ADD Tabs with same tag, it's not beeing checked and results in unexpected
* beahvior.
*
* @param tabSpec
* @param clss
* @param args
*/
public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args){
Stack<TabInfo> tabStack = new Stack<TabInfo>();
tabSpec.setContent(new DummyTabFactory(mContext));
mTabHost.addTab(tabSpec);
String tag = tabSpec.getTag();
TabInfo info = new TabInfo(tag, clss, args);
mTabTags.add(tag); // to know the position of the tab tag
tabStack.add(info);
mTabStackMap.put(tag, tabStack);
notifyDataSetChanged();
}
/**
* Will add the Fragment to Tab with the Tag _tag. Provide the Class of the Fragment
* it will be instantiated by this object. Proivde _args for your Fragment.
*
* @param fm
* @param _tag
* @param _class
* @param _args
*/
public void addFragment(FragmentManager fm, String _tag, Class<?> _class, Bundle _args){
TabInfo info = new TabInfo(_tag, _class, _args);
Stack<TabInfo> tabStack = mTabStackMap.get(_tag);
Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
if(frag instanceof SaveStateBundle){
Bundle b = new Bundle();
((SaveStateBundle) frag).onRemoveFragment(b);
tabStack.peek().args = b;
}
tabStack.add(info);
FragmentTransaction ft = fm.beginTransaction();
ft.remove(frag).commit();
notifyDataSetChanged();
}
/**
* Will pop the Fragment added to the Tab with the Tag _tag
*
* @param fm
* @param _tag
* @return
*/
public boolean popFragment(FragmentManager fm, String _tag){
Stack<TabInfo> tabStack = mTabStackMap.get(_tag);
if(tabStack.size()>1){
tabStack.pop();
Fragment frag = fm.findFragmentByTag("android:switcher:" + mViewPager.getId() + ":" + mTabTags.indexOf(_tag));
FragmentTransaction ft = fm.beginTransaction();
ft.remove(frag).commit();
notifyDataSetChanged();
return true;
}
return false;
}
public boolean back(FragmentManager fm) {
int position = mViewPager.getCurrentItem();
return popFragment(fm, mTabTags.get(position));
}
@Override
public int getCount() {
return mTabStackMap.size();
}
@Override
public int getItemPosition(Object object) {
ArrayList<Class<?>> positionNoneHack = new ArrayList<Class<?>>();
for(Stack<TabInfo> tabStack: mTabStackMap.values()){
positionNoneHack.add(tabStack.peek().clss);
} // if the object class lies on top of our stacks, we return default
if(positionNoneHack.contains(object.getClass())){
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
@Override
public Fragment getItem(int position) {
Stack<TabInfo> tabStack = mTabStackMap.get(mTabTags.get(position));
TabInfo info = tabStack.peek();
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
@Override
public void onTabChanged(String tabId) {
int position = mTabHost.getCurrentTab();
mViewPager.setCurrentItem(position);
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// Unfortunately when TabHost changes the current tab, it kindly
// also takes care of putting focus on it when not in touch mode.
// The jerk.
// This hack tries to prevent this from pulling focus out of our
// ViewPager.
TabWidget widget = mTabHost.getTabWidget();
int oldFocusability = widget.getDescendantFocusability();
widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
mTabHost.setCurrentTab(position);
widget.setDescendantFocusability(oldFocusability);
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
Add this for back button functionality in your MainActivity:
@Override
public void onBackPressed() {
if (!mTabsAdapter.back(getSupportFragmentManager())) {
super.onBackPressed();
}
}
If u like to save the Fragment State when it get's removed. Let your Fragment implement the interface SaveStateBundle
return in the function a bundle with your save state. Get the bundle after instantiation by this.getArguments()
.
You can instantiate a tab like this:
mTabsAdapter.addTab(mTabHost.newTabSpec("firstTabTag").setIndicator("First Tab Title"),
FirstFragmentActivity.FirstFragmentFragment.class, null);
works similiar if u want to add a Fragment on top of a Tab Stack. Important: I think, it won't work if u want to have 2 instances of same class on top of two Tabs. I did this solution quick together, so I can only share it without providing any experience with it.
Instead of using a UIView
, as @ImreKelényi suggests, you can use a CALayer
:
// Add a bottomBorder.
CALayer *bottomBorder = [CALayer layer];
bottomBorder.frame = CGRectMake(0.0f, 43.0f, toScrollView.frame.size.width, 1.0f);
bottomBorder.backgroundColor = [UIColor colorWithWhite:0.8f
alpha:1.0f].CGColor;
[toScrollView.layer addSublayer:bottomBorder];
Try this -
EditText myEditText = (EditText) findViewById(R.id.vnosEmaila);
String text = myEditText.getText().toString();
In my case it was a bit different
In the Prefix Header there was a define missing
#ifdef DEBUG
# define TWDLog(fmt, ...) NSLog((@"\n%s\n" fmt), __PRETTY_FUNCTION__, ##__VA_ARGS__)
#else
# define TWDLog(...)
#endif
So search for PROJECTNAME-Prefix.pch
and check if it has something missing in both projects
Many others have done an excellent job here giving a basic answer, especially Tobias Mühl. As mentioned, GMail's Api very closely matches the definition given by RFC2368 and RFC6068. This is true of the extended form of the mailto: links, but it's also true in the commonly-used forms found in the other answers. Of the five parameters, four are identical (such as to
, cc
, bcc
and body
) and one received only slight modification (su
is gmail's version of subject
).
If you want to know more about what you can do with mailTo gmail URLs, then these RFCs might be of help. Unfortunately, Google has not published any source themselves.
To clarify the parameters:
to
- Email to whosu
(gmail API) / subject
(mailTo API) - Email Titlebody
- Email Bodybcc
- Email Blind-Carbon Copycc
- Email Carbon Copy addressYou can define foreign key by:
public class Parent
{
public int Id { get; set; }
public virtual ICollection<Child> Childs { get; set; }
}
public class Child
{
public int Id { get; set; }
// This will be recognized as FK by NavigationPropertyNameForeignKeyDiscoveryConvention
public int ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
Now ParentId is foreign key property and defines required relation between child and existing parent. Saving the child without exsiting parent will throw exception.
If your FK property name doesn't consists of the navigation property name and parent PK name you must either use ForeignKeyAttribute data annotation or fluent API to map the relation
Data annotation:
// The name of related navigation property
[ForeignKey("Parent")]
public int ParentId { get; set; }
Fluent API:
modelBuilder.Entity<Child>()
.HasRequired(c => c.Parent)
.WithMany(p => p.Childs)
.HasForeignKey(c => c.ParentId);
Other types of constraints can be enforced by data annotations and model validation.
Edit:
You will get an exception if you don't set ParentId
. It is required property (not nullable). If you just don't set it it will most probably try to send default value to the database. Default value is 0 so if you don't have customer with Id = 0 you will get an exception.
You can try this:
function getLengthInBytes(str) {
var b = str.match(/[^\x00-\xff]/g);
return (str.length + (!b ? 0: b.length));
}
It works for me.
If you refer to the Google Documents you can use this method for android 4.1 and above, call this method before setContentView()
public void hideStatusBar() {
View view = getWindow().getDecorView();
int uiOption = View.SYSTEM_UI_FLAG_FULLSCREEN;
view.setSystemUiVisibility(uiOption);
ActionBar actionBar = getActionBar();
if (actionBar != null) {
actionBar.hide();
}
}
UIImageView *imageView = [[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MyImage.png"]]autorelease];
NSLog(@"Size of my Image => %f, %f ", [[imageView image] size].width, [[imageView image] size].height) ;
You could use a string stream and read the elements into the vector.
Here are many different examples...
A copy of one of the examples:
std::vector<std::string> split(const std::string& s, char seperator)
{
std::vector<std::string> output;
std::string::size_type prev_pos = 0, pos = 0;
while((pos = s.find(seperator, pos)) != std::string::npos)
{
std::string substring( s.substr(prev_pos, pos-prev_pos) );
output.push_back(substring);
prev_pos = ++pos;
}
output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word
return output;
}
How to use PUT method using WebRequest.
//JsonResultModel class
public class JsonResultModel
{
public string ErrorMessage { get; set; }
public bool IsSuccess { get; set; }
public string Results { get; set; }
}
// HTTP_PUT Function
public static JsonResultModel HTTP_PUT(string Url, string Data)
{
JsonResultModel model = new JsonResultModel();
string Out = String.Empty;
string Error = String.Empty;
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
try
{
req.Method = "PUT";
req.Timeout = 100000;
req.ContentType = "application/json";
byte[] sentData = Encoding.UTF8.GetBytes(Data);
req.ContentLength = sentData.Length;
using (System.IO.Stream sendStream = req.GetRequestStream())
{
sendStream.Write(sentData, 0, sentData.Length);
sendStream.Close();
}
System.Net.WebResponse res = req.GetResponse();
System.IO.Stream ReceiveStream = res.GetResponseStream();
using (System.IO.StreamReader sr = new
System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
{
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
Out += str;
count = sr.Read(read, 0, 256);
}
}
}
catch (ArgumentException ex)
{
Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
}
catch (WebException ex)
{
Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
}
catch (Exception ex)
{
Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
}
model.Results = Out;
model.ErrorMessage = Error;
if (!string.IsNullOrWhiteSpace(Out))
{
model.IsSuccess = true;
}
return model;
}
String phoneNumber = "0123456789";
String message = "Hello World!";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Include the following permission in your AndroidManifest.xml file
<uses-permission android:name="android.permission.SEND_SMS" />
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
if you didnot set your activity style it shows you black background .if you want to make changes such as white background, black text of listview then it is difficult process.
ADD android:theme="@style/AppTheme" in Android Manifest.
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="@drawable/YOUR DRAWABLE XML" />
<item android:drawable="@drawable/YOUR DRAWABLE XML" />
</selector>
When a there are 2 columns for primary keys they make up a composite primary key therefore you have to make sure that in the table that is being referenced there are also 2 columns of the same data type.
In addition to what everyone else has said, I would suggest you analyze your approach in longer terms than just now. It is currently the case that items are unique. It is currently the case that resorting the items would require a new list. It is almost required that the list are currently short. Even though I don't have the domain specifics, it is not much of a stretch to think those requirements could change. If you serialize your list, you are baking in an inflexibility that is not necessary in a more-normalized design. Btw, that does not necessarily mean a full Many:Many relationship. You could just have a single child table with a foreign key to the parent and a character column for the item.
If you still want to go down this road of serializing the list, you might consider storing the list in XML. Some databases such as SQL Server even have an XML data type. The only reason I'd suggest XML is that almost by definition, this list needs to be short. If the list is long, then serializing it in general is an awful approach. If you go the CSV route, you need to account for the values containing the delimiter which means you are compelled to use quoted identifiers. Persuming that the lists are short, it probably will not make much difference whether you use CSV or XML.
I needed either: both -alpha background
and -flatten
, or -fill
.
I made a new PNG with a transparent background and a red dot in the middle.
convert image.png -background green -alpha off green.png
failed: it produced an image with black background
convert image.png -background green -alpha background -flatten green.png
produced an image with the correct green background.
Of course, with another file that I renamed image.png
, it failed to do anything. For that file, I found that the color of the transparent pixels was "#d5d5d5" so I filled that color with green:
convert image.png -fill green -opaque "#d5d5d5" green.png
replaced the transparent pixels with the correct green.
I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.
The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119
// This class implements a UITextView that has a UITextField behind it, where the
// UITextField provides the border.
//
class TextView : UITextView, UITextViewDelegate
{
var textField = TextField();
required init?(coder: NSCoder)
{
fatalError("This class doesn't support NSCoding.")
}
override init(frame: CGRect, textContainer: NSTextContainer?)
{
super.init(frame: frame, textContainer: textContainer);
self.delegate = self;
// Create a background TextField with clear (invisible) text and disabled
self.textField.borderStyle = UITextBorderStyle.RoundedRect;
self.textField.textColor = UIColor.clearColor();
self.textField.userInteractionEnabled = false;
self.addSubview(textField);
self.sendSubviewToBack(textField);
}
convenience init()
{
self.init(frame: CGRectZero, textContainer: nil)
}
override func layoutSubviews()
{
super.layoutSubviews()
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
// UITextViewDelegate - Note: If you replace delegate, your delegate must call this
func scrollViewDidScroll(scrollView: UIScrollView)
{
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
}
Without resorting to the bit converter and bit shifting (need to be sure of encoding) this is fastest method I use as an extension method 'Right'.
string myString = "123456789123456789";
if (myString > 6)
{
char[] cString = myString.ToCharArray();
Array.Reverse(myString);
Array.Resize(ref myString, 6);
Array.Reverse(myString);
string val = new string(myString);
}
Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:
window.onbeforeunload=function(e){
// only take action (iterate) if my SCHEDULED_REQUEST object contains data
for (var key in SCHEDULED_REQUEST){
postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
for (var i=0;i<1000;i++){
// do something unnoticable but time consuming like writing a lot to console
console.log('buying some time to finish saving data');
};
break;
};
}; // no return string --> user will leave as normal but data is send to server
Edit: See also Synchronous_AJAX and how to do that with jquery
Here's a complete Java 7 program:
class GETHTTPResource {
public static void main(String[] args) throws Exception {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
}
}
The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.
Assuming you use underscorejs it's possible to elegantly generate random string in just two lines:
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var random = _.sample(possible, 5).join('');
List items are normally block elements. Turn them into inline elements via the display
property.
In the code you gave, you need to use a context selector to make the display: inline
property apply to the list items, instead of the list itself (applying display: inline
to the overall list will have no effect):
#ul_top_hypers li {
display: inline;
}
Here is the working example:
#div_top_hypers {_x000D_
background-color:#eeeeee;_x000D_
display:inline; _x000D_
}_x000D_
#ul_top_hypers li{_x000D_
display: inline;_x000D_
}
_x000D_
<div id="div_top_hypers">_x000D_
<ul id="ul_top_hypers">_x000D_
<li>‣ <a href="" class="a_top_hypers"> Inbox</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Compose</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Reports</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> Preferences</a></li>_x000D_
<li>‣ <a href="" class="a_top_hypers"> logout</a></li>_x000D_
</ul>_x000D_
</div>
_x000D_
I think I've come up with the solution to match the behaviour of Apple's apps.
First, in your viewWillAppear: subscribe to the keyboard notifications, so you know when the keyboard will show and hide, and the system will tell you the size of the keyboard, but dont' forget to unregister in your viewWillDisappear:.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
Implement the methods similar to the below so that you adjust the size of your tableView to match the visible area once the keyboard shows. Here I'm tracking the state of the keyboard separately so I can choose when to set the tableView back to full height myself, since you get these notifications on every field change. Don't forget to implement keyboardWillHide: and choose somewhere appropriate to fix your tableView size.
-(void) keyboardWillShow:(NSNotification *)note
{
CGRect keyboardBounds;
[[note.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue: &keyboardBounds];
keyboardHeight = keyboardBounds.size.height;
if (keyboardIsShowing == NO)
{
keyboardIsShowing = YES;
CGRect frame = self.view.frame;
frame.size.height -= keyboardHeight;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.3f];
self.view.frame = frame;
[UIView commitAnimations];
}
}
Now here's the scrolling bit, we work out a few sizes first, then we see where we are in the visible area, and set the rect we want to scroll to to be either the half view above or below the middle of the text field based on where it is in the view. In this case, we have an array of UITextFields and an enum that keeps track of them, so multiplying the rowHeight by the row number gives us the actual offset of the frame within this outer view.
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
CGRect frame = textField.frame;
CGFloat rowHeight = self.tableView.rowHeight;
if (textField == textFields[CELL_FIELD_ONE])
{
frame.origin.y += rowHeight * CELL_FIELD_ONE;
}
else if (textField == textFields[CELL_FIELD_TWO])
{
frame.origin.y += rowHeight * CELL_FIELD_TWO;
}
else if (textField == textFields[CELL_FIELD_THREE])
{
frame.origin.y += rowHeight * CELL_FIELD_THREE;
}
else if (textField == textFields[CELL_FIELD_FOUR])
{
frame.origin.y += rowHeight * CELL_FIELD_FOUR;
}
CGFloat viewHeight = self.tableView.frame.size.height;
CGFloat halfHeight = viewHeight / 2;
CGFloat midpoint = frame.origin.y + (textField.frame.size.height / 2);
if (midpoint < halfHeight)
{
frame.origin.y = 0;
frame.size.height = midpoint;
}
else
{
frame.origin.y = midpoint;
frame.size.height = midpoint;
}
[self.tableView scrollRectToVisible:frame animated:YES];
}
This seems to work quite nicely.
Please find in the below code which enables to perform the date validation for any of the supplied format or based on user locale to validate start/from and end/to dates. There could be some better approaches but have come up with this. Have tested it for the formats like: MM/dd/yyyy, dd/MM/yyyy, yyyy-MM-dd, yyyy.MM.dd, yyyy/MM/dd and dd-MM-yyyy.
Note supplied date format and date string go hand in hand.
<script type="text/javascript">
function validate(format) {
if(isAfterCurrentDate(document.getElementById('start').value, format)) {
alert('Date is after the current date.');
} else {
alert('Date is not after the current date.');
}
if(isBeforeCurrentDate(document.getElementById('start').value, format)) {
alert('Date is before current date.');
} else {
alert('Date is not before current date.');
}
if(isCurrentDate(document.getElementById('start').value, format)) {
alert('Date is current date.');
} else {
alert('Date is not a current date.');
}
if (isBefore(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Start/Effective Date cannot be greater than End/Expiration Date');
} else {
alert('Valid dates...');
}
if (isAfter(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('End/Expiration Date cannot be less than Start/Effective Date');
} else {
alert('Valid dates...');
}
if (isEquals(document.getElementById('start').value, document.getElementById('end').value, format)) {
alert('Dates are equals...');
} else {
alert('Dates are not equals...');
}
if (isDate(document.getElementById('start').value, format)) {
alert('Is valid date...');
} else {
alert('Is invalid date...');
}
}
/**
* This method gets the year index from the supplied format
*/
function getYearIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'YYYY'
|| tokens[0] === 'yyyy') {
return 0;
} else if (tokens[1]=== 'YYYY'
|| tokens[1] === 'yyyy') {
return 1;
} else if (tokens[2] === 'YYYY'
|| tokens[2] === 'yyyy') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the year string located at the supplied index
*/
function getYear(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the month index from the supplied format
*/
function getMonthIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'MM'
|| tokens[0] === 'mm') {
return 0;
} else if (tokens[1] === 'MM'
|| tokens[1] === 'mm') {
return 1;
} else if (tokens[2] === 'MM'
|| tokens[2] === 'mm') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the month string located at the supplied index
*/
function getMonth(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method gets the date index from the supplied format
*/
function getDateIndex(format) {
var tokens = splitDateFormat(format);
if (tokens[0] === 'DD'
|| tokens[0] === 'dd') {
return 0;
} else if (tokens[1] === 'DD'
|| tokens[1] === 'dd') {
return 1;
} else if (tokens[2] === 'DD'
|| tokens[2] === 'dd') {
return 2;
}
// Returning the default value as -1
return -1;
}
/**
* This method returns the date string located at the supplied index
*/
function getDate(date, index) {
var tokens = splitDateFormat(date);
return tokens[index];
}
/**
* This method returns true if date1 is before date2 else return false
*/
function isBefore(date1, date2, format) {
// Validating if date1 date is greater than the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
> new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method returns true if date1 is after date2 else return false
*/
function isAfter(date1, date2, format) {
// Validating if date2 date is less than the date1 date
if (new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()
< new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
) {
return true;
}
return false;
}
/**
* This method returns true if date1 is equals to date2 else return false
*/
function isEquals(date1, date2, format) {
// Validating if date1 date is equals to the date2 date
if (new Date(getYear(date1, getYearIndex(format)),
getMonth(date1, getMonthIndex(format)) - 1,
getDate(date1, getDateIndex(format))).getTime()
=== new Date(getYear(date2, getYearIndex(format)),
getMonth(date2, getMonthIndex(format)) - 1,
getDate(date2, getDateIndex(format))).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date is
* equals to the current date.
*/
function isCurrentDate(date, format) {
// Validating if the supplied date is the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
=== new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is before the current date.
*/
function isBeforeCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
< new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method validates and returns true if the supplied date value
* is after the current date.
*/
function isAfterCurrentDate(date, format) {
// Validating if the supplied date is before the current date
if (new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))).getTime()
> new Date(new Date().getFullYear(),
new Date().getMonth(),
new Date().getDate()).getTime()) {
return true;
}
return false;
}
/**
* This method splits the supplied date OR format based
* on non alpha numeric characters in the supplied string.
*/
function splitDateFormat(dateFormat) {
// Spliting the supplied string based on non characters
return dateFormat.split(/\W/);
}
/*
* This method validates if the supplied value is a valid date.
*/
function isDate(date, format) {
// Validating if the supplied date string is valid and not a NaN (Not a Number)
if (!isNaN(new Date(getYear(date, getYearIndex(format)),
getMonth(date, getMonthIndex(format)) - 1,
getDate(date, getDateIndex(format))))) {
return true;
}
return false;
}
Below is the HTML snippet
<input type="text" name="start" id="start" size="10" value="05/31/2016" />
<br/>
<input type="text" name="end" id="end" size="10" value="04/28/2016" />
<br/>
<input type="button" value="Submit" onclick="javascript:validate('MM/dd/yyyy');" />
Here's my take on this. I had to process the input string word by word, which could have been done by using space to count words but I felt it would be tedious and I should split the words into vectors.
#include<iostream>
#include<vector>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{
char x = '\0';
string s = "";
vector<string> q;
x = getchar();
while(x != '\n')
{
if(x == ' ')
{
q.push_back(s);
s = "";
x = getchar();
continue;
}
s = s + x;
x = getchar();
}
q.push_back(s);
for(int i = 0; i<q.size(); i++)
cout<<q[i]<<" ";
return 0;
}
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
There exist many open source projects that handle all the drawing of line charts for you with a couple of lines of code. Here's how you can draw a line chart from data in a couple text (CSV
) file with the XChart library. Disclaimer: I'm the lead developer of the project.
In this example, two text files exist in ./CSV/CSVChartRows/
. Notice that each row in the files represents a data point to be plotted and that each file represents a different series. series1
contains x
, y
, and error bar
data, whereas series2
contains just x
and y
, data.
1,12,1.4
2,34,1.12
3,56,1.21
4,47,1.5
1,56
2,34
3,12
4,26
public class CSVChartRows {
public static void main(String[] args) throws Exception {
// import chart from a folder containing CSV files
XYChart chart = CSVImporter.getChartFromCSVDir("./CSV/CSVChartRows/", DataOrientation.Rows, 600, 400);
// Show it
new SwingWrapper(chart).displayChart();
}
}
Sometimes it's case sensitive. Have you tried going to http://localhost/phpMyAdmin
?
I know its late but i recently ran into this situation. After wasting entire day I finally found the solution. I am suprised that I got this info on oracle's website whereas this seems nowhere to be found on IBM's website.
If you want to use JDBC drivers for DB2 that are compatible with JDK 1.5 or 1.4 , you need to use the jar db2jcc.jar
, which is available in SQLLIB/java/
folder of your db2 installation.
To make it more specific Create a tracking branch, which means you are now tracking a remote branch.
git branch --track branch remote-branch
git branch --track exp remotes/origin/experimental
After which you can
git branch # to see the remote tracking branch "exp" created .
Then to work on that branch do
git checkout branchname
git checkout exp
After you have made changes to the branch. You can git fetch and git merge with your remote tracking branch to merge your changes and push to the remote branch as below.
git fetch origin
git merge origin/experimental
git push origin/experimental
Hope it helps and gives you an idea, how this works.
Not to trample on BBoy's already decent answer, but I've done the code that maintains aspect ratio. I took his suggestion, so he should get partial credit here!
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
pd.DefaultPageSettings.Landscape = true; //or false!
pd.PrintPage += (sender, args) =>
{
Image i = Image.FromFile(@"C:\...\...\image.jpg");
Rectangle m = args.MarginBounds;
if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
{
m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
}
else
{
m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
}
args.Graphics.DrawImage(i, m);
};
pd.Print();
You can try to use btn-sm, btn-xs and btn-lg classes like this:
.btn-xl {
padding: 10px 20px;
font-size: 20px;
border-radius: 10px;
}
You can make use of Bootstrap .btn-group-justified
css class. Or you can simply add:
.btn-xl {
padding: 10px 20px;
font-size: 20px;
border-radius: 10px;
width:50%; //Specify your width here
}
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
If the other answers don't work you can check if something else is using the port with netstat:
netstat -ano | findstr <your port number>
If nothing is already using it, the port might be excluded, try this command to see if the range is blocked by something else:
netsh interface ipv4 show excludedportrange protocol=tcp
It's not exactly the answer to this question but I dealt with this problem with the Shift + Win + [left,right] arrow keys
shortcut. You can move the currently active window to another monitor with it.
i tried all the solutions here and nothing worked in my C# .net 4.0 project. Hoping to help someone here the solution that worked for me:
As main class variables:
private static string appGuid = "WRITE AN UNIQUE GUID HERE";
private static Mutex mutex;
When you need to check if app is already running:
bool mutexCreated;
mutex = new Mutex(true, "Global\\" + appGuid, out mutexCreated);
if (mutexCreated)
mutex.ReleaseMutex();
if (!mutexCreated)
{
//App is already running, close this!
Environment.Exit(0); //i used this because its a console app
}
I needed to close other istances only with some conditions, this worked well for my purpose
This worked for with maven 3.5.4 and now Intellij Idea see this code as source:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>
</configuration>
</plugin>
you can use Random.Next() also to generate a random number. you can see the MSDN link: http://msdn.microsoft.com/en-us/library/9b3ta19y.aspx
0 0 1-30/3 * *
This would run every three days starting 1st. Here are the 20 scheduled runs -
a bug(?!) in iOS10/Swift3/Xcode 8?
if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
let playerItem = AVPlayerItem(url: url)
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame=CGRect(x: 10, y: 10, width: 300, height: 300)
self.view.layer.addSublayer(playerLayer)
}
does not work (empty rect...)
this works:
if let url = URL(string: "http://devstreaming.apple.com/videos/wwdc/2016/102w0bsn0ge83qfv7za/102/hls_vod_mvp.m3u8"){
let player = AVPlayer(url: url)
let controller=AVPlayerViewController()
controller.player=player
controller.view.frame = self.view.frame
self.view.addSubview(controller.view)
self.addChildViewController(controller)
player.play()
}
Same URL...
This seems to work:
declare @d datetime
set @d = '2014-04-17 13:55:12'
select replace(convert(varchar(8), @d, 112)+convert(varchar(8), @d, 114), ':','')
Result:
20140417135512
Knockout.js validation is handy but it is not robust. You always have to create server side validation replica. In your case (as you use knockout.js) you are sending JSON data to server and back asynchronously, so you can make user think that he sees client side validation, but in fact it would be asynchronous server side validation.
Take a look at example here upida.cloudapp.net:8080/org.upida.example.knockout/order/create?clientId=1 This is a "Create Order" link. Try to click "save", and play with products. This example is done using upida library (there are spring mvc version and asp.net mvc of this library) from codeplex.
In my case, the problem was that I assigned a .swift class to the viewController in the storyboard, while the project was Objective C.
Instead of the timeout you could use a counter:
var count = 0;
$thing.bind('touchstart click', function(){
count++;
if (count %2 == 0) { //count 2% gives the remaining counts when devided by 2
// do something
}
return false
});
HTTPS (HTTP over SSL) sends all HTTP content over a SSL tunel, so HTTP content and headers are encrypted as well.
Either the user doesn't have privileges needed to see the table, the table doesn't exist or you are running the query in the wrong schema
Does the table exist?
select owner,
object_name
from dba_objects
where object_name = any ('CUSTOMER','customer');
What privileges did you grant?
grant select, insert on customer to user;
Are you running the query against the owner from the first query?
This is now supported in Chrome by the "Pause on all exceptions" button.
To enable it:
Note that this button has multiple states. Keep clicking the button to switch between
String value = someMethod();
switch(0) {
default:
if ("apple".equals(value)) {
method1();
break;
}
if ("carrot".equals(value)) {
method2();
break;
}
if ("mango".equals(value)) {
method3();
break;
}
if ("orance".equals(value)) {
method4();
break;
}
}
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
So here is the scenario that I faced, and how I solved it.
[branch-a]
[Hundreds of commits] -> [R] -> [I]
here R
is the commit that I needed to be removed, and I
is a single commit that comes after R
I made a revert commit and squashed them together
git revert [commit id of R]
git rebase -i HEAD~3
During the interactive rebase squash the last 2 commits.
for OS's that support select
:
import select
# your code
select.select([], [], [])
This is the method which i used to convert the integer to string.Correct me if i did wrong.
/**
* @param a
* @return
*/
private String convertToString(int a) {
int c;
char m;
StringBuilder ans = new StringBuilder();
// convert the String to int
while (a > 0) {
c = a % 10;
a = a / 10;
m = (char) ('0' + c);
ans.append(m);
}
return ans.reverse().toString();
}
Hadley Wickham
dplyr
packages is always a saver in case of data wrangling.
To add the desired division as a third variable I would use mutate()
d <- mutate(d, new = min / count2.freq)
if(antennaHeight.compareTo(Double.valueOf(0))>=0)
In the above code,
antennaHeight.compareTo(Double.valueOf(0))
--- this 'll return int, comparing this with 0 gives the solution.
int x = -1;
Calendar cal = ...;
cal.add(Calendar.DATE, x);
For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str
to int
) so you must do this yourself. You'll like that in the long-run, trust me!
I created a program with hibernate, in which I created two POJO classes, both with an object of each other as data members. When in the main method I tried to save them in the database I also got this error.
This happens because both of the classes are referring each other, hence creating a loop which causes this error.
So, check whether any such kind of relationships exist in your program.
Your null pointer exception seems to be on this line:
String url = intent.getExtras().getString("userurl");
because intent.getExtras()
returns null when the intent doesn't have any extras.
You have to realize that this piece of code:
Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);
doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass
and if that doesn't exist, your app crashes.
Also, there is no such thing as "android.intent.action.start"
so the manifest should look more like:
<activity android:name=".start" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name= ".Main">
</activity>
I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.
For IE8 native browser alone:
.classname{
*color: green; /* This is for IE8 Native browser alone */
}
To be simple,
Mono is third party implementation of .Net framework for Linux/Android/iOs
.Net Core is microsoft's own implementation for same.
.Net Core is future. and Mono will be dead eventually. Having said that .Net Core is not matured enough. I was struggling to implement it with IBM Bluemix and later dropped the idea. Down the time (may be 1-2 years), it should be better.
n = 2
a=dataframe['name'].value_counts()[:n].index.tolist()
dataframe["name"].value_counts()[a]
Most of the answers here try to offer alternative to how to write the HTML code to include more data because at least up to CSS3 you cannot select an element by partial inner text. But it can be done, you just need to add a bit of vanilla JavaScript, notice since female also contains male it will be selected:
cells = document.querySelectorAll('td');_x000D_
console.log(cells);_x000D_
[].forEach.call(cells, function (el) {_x000D_
if(el.innerText.indexOf("male") !== -1){_x000D_
//el.click(); click or any other option_x000D_
console.log(el)_x000D_
}_x000D_
});
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Peter</td>_x000D_
<td>male</td>_x000D_
<td>34</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Susanne</td>_x000D_
<td>female</td>_x000D_
<td>14</td>_x000D_
</tr>_x000D_
</table>
_x000D_
<table>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">male</td>
<td data-content="34">34</td>
</tr>
<tr>
<td data-conten="Susanne">Susanne</td>
<td data-content="female">female</td>
<td data-content="14">14</td>
</tr>
</table>
Yes, it prints GARBAGE unless you are lucky.
VERY IMPORTANT.
The type of the printf/sprintf/fprintf argument MUST match the associated format type char.
If the types don't match and it compiles, the results are very undefined.
Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.
If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).
printf("%d\n", (int) ch)
In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.
printf("%d", (int) sizeof('\n'))
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
I just want one result
implies that you expect only one row to be returned. So either adapt your query, e.g.
SELECT player_id
FROM players p
WHERE CONCAT(p.first_name, ' ', p.last_name) = ?
LIMIT 0, 1
(and then use getSingleResult()
as recommended by AdrienBrault) or fetch rows as an array and access the first item:
// ...
$players = $query->getArrayResult();
$myPlayer = $players[0];
Cameron MacFarland nailed it.
I'd like to add that the .NET 4.0 client profile will be included in Windows Update and future Windows releases. Expect most computers to have the client profile, not the full profile. Do not underestimate that fact if you're doing business-to-consumer (B2C) sales.
function get() {_x000D_
var arrayOfRows = document.getElementById("ta").value.split("\n");_x000D_
var docfrag = document.createDocumentFragment();_x000D_
_x000D_
var p = document.getElementById("result");_x000D_
while (p.firstChild) {_x000D_
p.removeChild(p.firstChild);_x000D_
}_x000D_
_x000D_
arrayOfRows.forEach(function(row, index, array) {_x000D_
var span = document.createElement("span");_x000D_
span.textContent = row;_x000D_
docfrag.appendChild(span);_x000D_
if(index < array.length - 1) {_x000D_
docfrag.appendChild(document.createElement("br"));_x000D_
}_x000D_
});_x000D_
_x000D_
p.appendChild(docfrag);_x000D_
}
_x000D_
<textarea id="ta" rows=3></textarea><br>_x000D_
<button onclick="get()">get</button>_x000D_
<p id="result"></p>
_x000D_
You can split textarea rows into array:
var arrayOfRows = postText.value.split("\n");
Then use it to generate, maybe, more p tags...
All the above solutions are fine. And here I'm gonna combine all the solutions so that it should work for all the situations.
For Linux and Mac
sed -i old 's/\DEFINER\=`[^`]*`@`[^`]*`//g' file.sql
For Windows
download atom or notepad++, open your dump sql file with atom or notepad++, press Ctrl+F
search the word DEFINER, and remove the line DEFINER=admin
@%
(or may be little different for you) from everywhere and save the file.
As for example
before removing that line: CREATE DEFINER=admin
@%
PROCEDURE MyProcedure
After removing that line: CREATE PROCEDURE MyProcedure
SET @@SESSION.SQL_LOG_BIN= 0;
SET @@GLOBAL.GTID_PURGED=/*!80000 '+'*/ '';
SET @@SESSION.SQL_LOG_BIN = @MYSQLDUMP_TEMP_LOG_BIN;
For end of line use:
git diff --ignore-space-at-eol
Instead of what are you using currently:
git diff -w (--ignore-all-space)
For start of line... you are out of luck if you want a built in solution.
However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".
Try remove_missing
instead with vars = the_variable
. It is very important that you set the vars
argument, otherwise remove_missing
will remove all rows that contain an NA
in any column!! Setting na.rm = TRUE
will suppress the warning message.
ggplot(data = remove_missing(MyData, na.rm = TRUE, vars = the_variable),aes(x= the_variable, fill=the_variable, na.rm = TRUE)) +
geom_bar(stat="bin")
You will use the following query:
SELECT * FROM [table] GROUP BY NUMBER;
Where [table]
is the name of the table.
This provides a unique listing for the NUMBER
column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.
I'm using a similar code as those that use the while loop but I call the entry count in every loop... so I suppose it's somewhat slower
FragmentManager manager = getFragmentManager();
while (manager.getBackStackEntryCount() > 0){
manager.popBackStackImmediate();
}
The underlying data type of a datetime in Excel is a 64-bit floating point number where the length of a day equals 1
and 1st Jan 1900 00:00
equals 1
. So 11th June 2009 17:30
is about 39975.72917
.
If a cell contains a numeric value such as this, it can be converted to a datetime simply by applying a datetime format to the cell.
So, if you can convert your datetimes to numbers using the above formula, output them to the relevant cells and then set the cell formats to the appropriate datetime format, e.g. yyyy-mm-dd hh:mm:ss
, then it should be possible to achieve what you want.
Also Stefan de Bruijn has pointed out that there is a bug in Excel in that it incorrectly assumes 1900 is a leap year so you need to take that into account when making your calculations (Wikipedia).
See under the heading One Operating System Running On Multiple Platforms where it states:
Most of the source code for Windows NT is written in C or C++.
May be sometimes upgrading to a superuser might not be a good option. So apart from super user there are lot of other options which you can use. Open your terminal and type the following:
$ sudo su - postgres
[sudo] password for user: (type your password here)
$ psql
postgres@user:~$ psql
psql (10.5 (Ubuntu 10.5-1.pgdg18.04+1))
Type "help" for help.
postgres=# ALTER USER my_user WITH option
Also listing the list of options
SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB | CREATEROLE | NOCREATEROLE |
CREATEUSER | NOCREATEUSER | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION|
NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT connlimit |
[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' | VALID UNTIL 'timestamp'
So in command line it will look like
postgres=# ALTER USER my_user WITH LOGIN
OR use an encrypted password.
postgres=# ALTER USER my_user WITH ENCRYPTED PASSWORD '5d41402abc4b2a76b9719d911017c592';
OR revoke permissions after a specific time.
postgres=# ALTER USER my_user WITH VALID UNTIL '2019-12-29 19:09:00';
If you still need to use the HTTP Module you need to configure it (.NET 4.0 framework) as follows:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="MyModule" type="[Namespace].[Class], [assembly]"/>
</modules>
<validation validateIntegratedModeConfiguration="false"/>
</system.webServer>
Bitcode makes crash reporting harder. Here is a quote from HockeyApp (which also true for any other crash reporting solutions):
When uploading an app to the App Store and leaving the "Bitcode" checkbox enabled, Apple will use that Bitcode build and re-compile it on their end before distributing it to devices. This will result in the binary getting a new UUID and there is an option to download a corresponding dSYM through Xcode.
Note: the answer was edited on Jan 2016 to reflect most recent changes
arr[title] = link;
You're not pushing into the array, you're setting the element with the key title
to the value link
. As such your array should be an object.
You can try following sample http://jsfiddle.net/xKJB8/3/
<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());
This will get you your comma seperated values as well as add the fixed notation to the end.
nStr="1000";
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
commaSeperated = x1 + x2 + ".00";
alert(commaSeperated);
Thank you drifty0pine!
The first solution, it´s works!
[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)
but I had need put more ../
until the folder where was my file, like this:
[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)
resize()
not only allocates memory, it also creates as many instances as the desired size which you pass to resize()
as argument. But reserve()
only allocates memory, it doesn't create instances. That is,
std::vector<int> v1;
v1.resize(1000); //allocation + instance creation
cout <<(v1.size() == 1000)<< endl; //prints 1
cout <<(v1.capacity()==1000)<< endl; //prints 1
std::vector<int> v2;
v2.reserve(1000); //only allocation
cout <<(v2.size() == 1000)<< endl; //prints 0
cout <<(v2.capacity()==1000)<< endl; //prints 1
Output (online demo):
1
1
0
1
So resize()
may not be desirable, if you don't want the default-created objects. It will be slow as well. Besides, if you push_back()
new elements to it, the size()
of the vector will further increase by allocating new memory (which also means moving the existing elements to the newly allocated memory space). If you have used reserve()
at the start to ensure there is already enough allocated memory, the size()
of the vector will increase when you push_back()
to it, but it will not allocate new memory again until it runs out of the space you reserved for it.
Accessing direct properties and related are explained
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
$order_data = array(
'order_id' => $order->get_id(),
'order_number' => $order->get_order_number(),
'order_date' => date('Y-m-d H:i:s', strtotime(get_post($order->get_id())->post_date)),
'status' => $order->get_status(),
'shipping_total' => $order->get_total_shipping(),
'shipping_tax_total' => wc_format_decimal($order->get_shipping_tax(), 2),
'fee_total' => wc_format_decimal($fee_total, 2),
'fee_tax_total' => wc_format_decimal($fee_tax_total, 2),
'tax_total' => wc_format_decimal($order->get_total_tax(), 2),
'cart_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_cart_discount(), 2),
'order_discount' => (defined('WC_VERSION') && (WC_VERSION >= 2.3)) ? wc_format_decimal($order->get_total_discount(), 2) : wc_format_decimal($order->get_order_discount(), 2),
'discount_total' => wc_format_decimal($order->get_total_discount(), 2),
'order_total' => wc_format_decimal($order->get_total(), 2),
'order_currency' => $order->get_currency(),
'payment_method' => $order->get_payment_method(),
'shipping_method' => $order->get_shipping_method(),
'customer_id' => $order->get_user_id(),
'customer_user' => $order->get_user_id(),
'customer_email' => ($a = get_userdata($order->get_user_id() )) ? $a->user_email : '',
'billing_first_name' => $order->get_billing_first_name(),
'billing_last_name' => $order->get_billing_last_name(),
'billing_company' => $order->get_billing_company(),
'billing_email' => $order->get_billing_email(),
'billing_phone' => $order->get_billing_phone(),
'billing_address_1' => $order->get_billing_address_1(),
'billing_address_2' => $order->get_billing_address_2(),
'billing_postcode' => $order->get_billing_postcode(),
'billing_city' => $order->get_billing_city(),
'billing_state' => $order->get_billing_state(),
'billing_country' => $order->get_billing_country(),
'shipping_first_name' => $order->get_shipping_first_name(),
'shipping_last_name' => $order->get_shipping_last_name(),
'shipping_company' => $order->get_shipping_company(),
'shipping_address_1' => $order->get_shipping_address_1(),
'shipping_address_2' => $order->get_shipping_address_2(),
'shipping_postcode' => $order->get_shipping_postcode(),
'shipping_city' => $order->get_shipping_city(),
'shipping_state' => $order->get_shipping_state(),
'shipping_country' => $order->get_shipping_country(),
'customer_note' => $order->get_customer_note(),
'download_permissions' => $order->is_download_permitted() ? $order->is_download_permitted() : 0,
);
Additional details
$line_items_shipping = $order->get_items('shipping');
foreach ($line_items_shipping as $item_id => $item) {
if (is_object($item)) {
if ($meta_data = $item->get_formatted_meta_data('')) :
foreach ($meta_data as $meta_id => $meta) :
if (in_array($meta->key, $line_items_shipping)) {
continue;
}
// html entity decode is not working preoperly
$shipping_items[] = implode('|', array('item:' . wp_kses_post($meta->display_key), 'value:' . str_replace('×', 'X', strip_tags($meta->display_value))));
endforeach;
endif;
}
}
//get fee and total
$fee_total = 0;
$fee_tax_total = 0;
foreach ($order->get_fees() as $fee_id => $fee) {
$fee_items[] = implode('|', array(
'name:' . html_entity_decode($fee['name'], ENT_NOQUOTES, 'UTF-8'),
'total:' . wc_format_decimal($fee['line_total'], 2),
'tax:' . wc_format_decimal($fee['line_tax'], 2),
));
$fee_total += $fee['line_total'];
$fee_tax_total += $fee['line_tax'];
}
// get tax items
foreach ($order->get_tax_totals() as $tax_code => $tax) {
$tax_items[] = implode('|', array(
'rate_id:'.$tax->id,
'code:' . $tax_code,
'total:' . wc_format_decimal($tax->amount, 2),
'label:'.$tax->label,
'tax_rate_compound:'.$tax->is_compound,
));
}
// add coupons
foreach ($order->get_items('coupon') as $_ => $coupon_item) {
$coupon = new WC_Coupon($coupon_item['name']);
$coupon_post = get_post((WC()->version < '2.7.0') ? $coupon->id : $coupon->get_id());
$discount_amount = !empty($coupon_item['discount_amount']) ? $coupon_item['discount_amount'] : 0;
$coupon_items[] = implode('|', array(
'code:' . $coupon_item['name'],
'description:' . ( is_object($coupon_post) ? $coupon_post->post_excerpt : '' ),
'amount:' . wc_format_decimal($discount_amount, 2),
));
}
foreach ($order->get_refunds() as $refunded_items){
$refund_items[] = implode('|', array(
'amount:' . $refunded_items->get_amount(),
'reason:' . $refunded_items->get_reason(),
'date:'. date('Y-m-d H-i-s',strtotime((WC()->version < '2.7.0') ? $refunded_items->date_created : $refunded_items->get_date_created())),
));
}
The solution given didn't work for me on the desktop, it just showed both divs, although the mobile only showed the mobile div. So I did a little search and found the min-width option. I updated my code to the following and it works fine now :)
CSS:
@media all and (min-width: 480px) {
.deskContent {display:block;}
.phoneContent {display:none;}
}
@media all and (max-width: 479px) {
.deskContent {display:none;}
.phoneContent {display:block;}
}
HTML:
<div class="deskContent">Content for desktop</div>
<div class="phoneContent">Content for mobile</div>
The question is already answered, however when I first saw it I thought of NodeJS Buffer. But it is way slower than the +, so it is likely that nothing can be faster than + in string concetanation.
Tested with the following code:
function a(){
var s = "hello";
var p = "world";
s = s + p;
return s;
}
function b(){
var s = new Buffer("hello");
var p = new Buffer("world");
s = Buffer.concat([s,p]);
return s;
}
var times = 100000;
var t1 = new Date();
for( var i = 0; i < times; i++){
a();
}
var t2 = new Date();
console.log("Normal took: " + (t2-t1) + " ms.");
for ( var i = 0; i < times; i++){
b();
}
var t3 = new Date();
console.log("Buffer took: " + (t3-t2) + " ms.");
Output:
Normal took: 4 ms.
Buffer took: 458 ms.
Install ASP.NET Core module
Download the installer using the following link: https://www.microsoft.com/net/permalink/dotnetcore-current-windows-runtime-bundle-installer
Here is the code that works if you are making a REST api call behind a proxy:
require "uri"
require 'net/http'
proxy_host = '<proxy addr>'
proxy_port = '<proxy_port>'
proxy_user = '<username>'
proxy_pass = '<password>'
uri = URI.parse("https://saucelabs.com:80/rest/v1/users/<username>")
proxy = Net::HTTP::Proxy(proxy_host, proxy_port, proxy_user, proxy_pass)
req = Net::HTTP::Get.new(uri.path)
req.basic_auth(<sauce_username>,<sauce_password>)
result = proxy.start(uri.host,uri.port) do |http|
http.request(req)
end
puts result.body
Combining the suggestions of cletus and helios,
import java.util.Random;
public class EnumTest {
private enum Season { WINTER, SPRING, SUMMER, FALL }
private static final RandomEnum<Season> r =
new RandomEnum<Season>(Season.class);
public static void main(String[] args) {
System.out.println(r.random());
}
private static class RandomEnum<E extends Enum<E>> {
private static final Random RND = new Random();
private final E[] values;
public RandomEnum(Class<E> token) {
values = token.getEnumConstants();
}
public E random() {
return values[RND.nextInt(values.length)];
}
}
}
Edit: Oops, I forgot the bounded type parameter, <E extends Enum<E>>
.
@Baba's answer is great. But you don't need to use explode
because fputcsv
takes an array as a parameter
For instance, if you have a three columns, four lines document, here's a more straight version:
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$user_CSV[0] = array('first_name', 'last_name', 'age');
// very simple to increment with i++ if looping through a database result
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);
$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
// though CSV stands for "comma separated value"
// in many countries (including France) separator is ";"
fputcsv($fp, $line, ',');
}
fclose($fp);
divToUpdate.innerHTML = "";
When I started using json, I was confused and unable to figure it out for some time, but finally I got what I wanted
Here is the simple solution
import json
m = {'id': 2, 'name': 'hussain'}
n = json.dumps(m)
o = json.loads(n)
print(o['id'], o['name'])
Supposing that you are using ECLIPSE:
Right click PROJECT PROPERTIES ANDROID
If you have a version of ANDROID checked, you must change it to a GOOGLE API. Choose a version of GOOGLE APIS compatible with your project's target version.
You don't need any environment.ts or such file to be provided by your seed project. Just have a configuration.ts and add all such entries which require runtime decision (example:- logging configuration and urls). This will fit in any design structure and also help in future
configuration.ts
export class Configuration {
isInProductionMode : bool = true;
// other configuration
serviceUrl : string = "http://myserver/myservice.svc";
logFileName : string = "...";
}
// Now use in your startup code (main.ts or equivalent as per the seed project design
import { Configuration } from './configuration';
import { enableProdMode } from '@angular/core';
....
if (Configuration.isInProductionMode)
enableProdMode();
I could be wrong because I've never used Angular, but I believe you are probably using ng-bind
, which will create just a TextNode.
You will want to use ng-bind-html
instead.
http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml
Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'
http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe
Here's a demo:
You need to be careful though, You need to setup the EDMX file exactly as it was before deleting it (if you choose the delete/regenerate route), otherwise, you'll have a naming mismatch between your code and the EF generated model (especialy for pluralization and singularization)
Hope this will prevent you some headaches =)
gradlew
is a wrapper(w - character) that uses gradle
.
Under the hood gradlew
performs three main things:
gradle
versiongradle
taskUsing Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.
To create a wrapper run:
gradle wrapper
This command generate:
gradle-wrapper.properties
will contain the information about the Gradle distribution
*./
Is used on Unix to specify the current directory
How about
a["abc"] = [1, 2]
This will result in:
>>> a
{'abc': [1, 2]}
Is that what you were looking for?
According to React philosophy component can't change its props. they should be received from the parent and should be immutable. Only parent can change the props of its children.
nice explanation on state vs props
also, read this thread Why can't I update props in react.js?
Xcode->Product->Clean + Xcode Restart
After attempting many of the other mentioned solutions, to my eternal embarrassment, doing an Xcode->Product->Clean and restarting Xcode, did the trick.
I solved a similar issue by just deleting the .git
folder from my project and reintegrating with version control through IntelliJ.
Note: The .git
folder is hidden. You can view it in the terminal with ls -a
, and then remove it using rm -rf .git
.
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.
No prompt use:
dir /x
Procure o nome reduzido do diretório na linha do "Program Files (x86)"
27/08/2018 15:07 <DIR> PROGRA~2 Program Files (x86)
Coloque a seguinte configuração em php.ini para a opção:
extension_dir="C:\PROGRA~2\path\to\php\ext"
Acredito que isso resolverá seu problema.
Zorro
I think I figured out the questions after reading the log. Thanks to Will's reminder, I checked the log and found out the some program else is listening to that port. Before I can start to figure out which program, my computer was restarted and localhost:8080 works and showing tomcat page. Whooh
To clear the referencing memory, and run the next MYSQL fetch
If you either use Buffered
or Unbuffered
result set for fetching data, first you must simply clear the fetched data from the memory, once you have fetched all the data. As you can't execute another MYSQL procedure on the same connection until you clear the fetched memory.
Add this below function right end of your script, so it will solve the problem
$numRecords->close(); or $numRecords->free(); // This clears the referencing memory, and will be ready for the next MYSQL fetch
Apart from the rest of the answers, I would like to show one difference in React.
If I throw a new Error()
and I am in development mode, I will get an error screen and a console log. If I throw a string literal, I will only see it in the console and possibly miss it, if I am not watching the console log.
Throwing an error logs into the console and shows an error screen while in development mode (the screen won't be visible in production).
throw new Error("The application could not authenticate.");
Whereas the following code only logs into the console:
throw "The application could not authenticate.";
For completeness -- also check phpCallGraph.
Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.
I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki
But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.
There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...
Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.
However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.
So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.
Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.
Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.
See https://serverfault.com/questions/84815/how-can-i-get-the-size-of-an-amazon-s3-bucket
Answered by Vic...
<?php
if (!class_exists('S3')) require_once 'S3.php';
// Instantiate the class
$s3 = new S3('accessKeyId', 'secretAccessKey');
S3::$useSSL = false;
// List your buckets:
echo "S3::listBuckets(): ";
echo '<pre>' . print_r($s3->listBuckets(), 1). '</pre>';
$totalSize = 0;
$objects = $s3->getBucket('name-of-your-bucket');
foreach ($objects as $name => $val) {
// If you want to get the size of a particular directory, you can do
// only that.
// if (strpos($name, 'directory/sub-directory') !== false)
$totalSize += $val['size'];
}
echo ($totalSize / 1024 / 1024 / 1024) . ' GB';
?>
I have created a demo for you.
Here is how your nested structure should be in Bootstrap 3:
<div class="form-group">
<label for="birthday" class="col-xs-2 control-label">Birthday</label>
<div class="col-xs-10">
<div class="form-inline">
<div class="form-group">
<input type="text" class="form-control" placeholder="year"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="month"/>
</div>
<div class="form-group">
<input type="text" class="form-control" placeholder="day"/>
</div>
</div>
</div>
</div>
Notice how the whole form-inline
is nested within the col-xs-10
div containing the control of the horizontal form. In other terms, the whole form-inline
is the "control" of the birthday label in the main horizontal form.
Note that you will encounter a left and right margin problem by nesting the inline form within the horizontal form. To fix this, add this to your css:
.form-inline .form-group{
margin-left: 0;
margin-right: 0;
}
if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.
<div>
<div style="padding-bottom: 33%;">
i have 33% height of my parents width
</div>
</div>
I would use regular expression matching to sum over variables with certain pattern names. For example:
df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))
This way you can create more than one variable as a sum of certain group of variables of your data frame.
In order to get access to the post data we have to use body-parser
. Basically what the body-parser
is which allows express to read the body and then parse that into a Json
object that we can understand.
This worked like a charm for me, of-course it requires super-user privileges :-)
# hcitool cc <target-bdaddr>; hcitool auth <target-bdaddr>
To get <target-bdaddr>
you may issue below command:
$ hcitool scan
Note: Exclude #
& $
as they are command line prompts.
One more solution with ES6
isPalin = str => [...str].every((c, i) => c === str[str.length-1-i]);
For example, if you want to change com.example.app
to my.awesome.game
, then:
In your Project pane, click on the little gear icon ( )
Uncheck the Compact Empty Middle Packages
option
Your package directory will now be broken up into individual directories
Individually select each directory you want to rename, and:
Right-click it
Select Refactor
Click on Rename
In the pop-up dialog, click on Rename Package
instead of Rename Directory
Enter the new name and hit Refactor
Click Do Refactor in the bottom
Allow a minute to let Android Studio update all changes
Note: When renaming com
in Android Studio, it might give a warning. In such case, select Rename All
Now open your Gradle Build File (build.gradle
- Usually app
or mobile
). Update the applicationId
in the defaultConfig
to your new Package Name and Sync Gradle, if it hasn't already been updated automatically:
You may need to change the package=
attribute in your manifest.
Clean and Rebuild.
Done! Anyway, Android Studio needs to make this process a little simpler.
I could able to make it work only by adding GRANT OPTION
, without that always receive permission denied error
GRANT ALL PRIVILEGES ON mydb.* TO 'myuser'@'localhost' WITH GRANT OPTION;
I am a beginner with Angular and I did the basic mistake of not including the app name in the angular root element. So, changing the code from
<html data-ng-app>
to
<html data-ng-app="myApp">
worked for me. @PSL, has covered this already in his answer above.
Nicely explained above!
For all those who may suffer like me to get this working in a localized Windows (mine is XP in Slovak), you may try to replace the %
with a !
So:
SET TEXT=Hello World
SET SUBSTRING=!TEXT:~3,5!
ECHO !SUBSTRING!
Here is a solution to prevent session shearing between browser tabs for a java application. This will work for IE (JSP/Servlet)
1)first page JS
BODY onload="javascript:initPageLoad()"
function initPageLoad() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var serverResponse = xmlhttp.responseText;
top.document.title=serverResponse;
}
};
xmlhttp.open("GET", 'data.do', true);
xmlhttp.send();
}
2)common JS for all pages
window.onunload = function() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var serverResponse = xmlhttp.responseText;
}
};
xmlhttp.open("GET", 'data.do?reset=true', true);
xmlhttp.send();
}
var readyStateCheckInterval = setInterval(function() {
if (document.readyState === "complete") {
init();
clearInterval(readyStateCheckInterval);
}}, 10);
function init(){
if(document.title==""){
window.onunload=function() {};
window.open('', '_self', ''); window.close();
}
}
3)web.xml - servlet mapping
<servlet-mapping>
<servlet-name>myAction</servlet-name>
<url-pattern>/data.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myAction</servlet-name>
<servlet-class>xx.xxx.MyAction</servlet-class>
</servlet>
4)servlet code
public class MyAction extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
Integer sessionCount = (Integer) request.getSession().getAttribute(
"sessionCount");
PrintWriter out = response.getWriter();
Boolean reset = Boolean.valueOf(request.getParameter("reset"));
if (reset)
sessionCount = new Integer(0);
else {
if (sessionCount == null || sessionCount == 0) {
out.println("hello Title");
sessionCount = new Integer(0);
}
sessionCount++;
}
request.getSession().setAttribute("sessionCount", sessionCount);
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "private, no-store, no-cache, must- revalidate");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
}
}
The <Comment>
tag contains two text nodes and two <br>
nodes as children.
Your xpath expression was
//*[contains(text(),'ABC')]
To break this down,
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.[]
are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.contains
is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment>
element -- namely BLAH BLAH BLAH
. Since that doesn't match, you don't get a <Comment>
in your results.You need to change this to
//*[text()[contains(.,'ABC')]]
*
is a selector that matches any element (i.e. tag) -- it returns a node-set.[]
are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.text()
is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.[]
are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as .
within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.contains
is a function that operates on a string. Here it is passed an individual text node (.
). Since it is passed the second text node in the <Comment>
tag individually, it will see the 'ABC'
string and be able to match it.One more thing to check: make sure that your source file contains the correct package declaration corresponding to the subdirectory it's in. The error mentioned by the OP can be seen when trying to run a "main type" declared in a file in a subdirectory but missing the package statement.
I am on a 64 bit system, and I only got this to work after installing both the 32 and 64 bit versions of the redistributable. I did not try the 64 bit version by itself due to the other posters' warnings about using the 32 bit version (and am too lazy to uninstall the 32 bit version now that I have it working), so I don't know if the 32 bit version is needed or not in cases like mine.
The fundamental problem can often be simply solved by changing an =
to IN
, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:
WITH accounts_to_delete AS
(
SELECT account_id
FROM accounts a
INNER JOIN customers c
ON a.customer_id = c.id
WHERE c.customer_name='Some Customer'
)
-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
WHERE accounts.guid =
(
SELECT account_id
FROM accounts_to_delete
);
-- this succeeds with any number of accounts:
DELETE FROM accounts
WHERE accounts.guid IN
(
SELECT account_id
FROM accounts_to_delete
);
You may be able to do this by modifying the request options as below. If you are using a self-signed certificate or a missing intermediary, setting strictSSL to false will not force request package to validate the certificate.
var options = {
host: 'jira.example.com',
path: '/secure/attachment/206906/update.xlsx',
strictSSL: false
}
Just divide the number of td to 100%. Example, you have 4 td's:
<html>
<table>
<tr>
<td style="width:25%">This is a text</td>
<td style="width:25%">This is some text, this is some text</td>
<td style="width:25%">This is another text, this is another text</td>
<td style="width:25%">This is the last text, this is the last text</td>
</tr>
</table>
</html>
We use 25% in each td to maximize the 100% space of the entire table
I had a similar issue and found that applying overflow: hidden;
to both html
and body
solved my problem.
html,
body {
overflow: hidden;
}
For iOS 9, you may need to use this instead: (Thanks chaenu!)
html,
body {
overflow: hidden;
position: relative;
height: 100%;
}
Regarding @Suragch's Alternative to "Remove element of unknown index":
There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.
If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.
if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
carsArray.removeAtIndex(validIndex)
}
Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.
To configure Sublime to always use tabs try the adding the following to preferences->settings-user:
{
"tab_size": 4,
"translate_tabs_to_spaces": false
}
More information here: http://www.sublimetext.com/docs/2/indentation.html
In Linux, there is different escape sequences for control terminal. For example, there is special escape sequence for erase whole line: \33[2K
and for move cursor to previous line: \33[1A
. So all you need is to print this every time you need to refresh the line. Here is the code which prints Line 1 (second variant)
:
System.out.println("Line 1 (first variant)");
System.out.print("\33[1A\33[2K");
System.out.println("Line 1 (second variant)");
There are codes for cursor navigation, clearing screen and so on.
I think there are some libraries which helps with it (ncurses
?).
Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.
Pause("Press Enter to continue")
Sub Pause(strPause)
WScript.Echo (strPause)
z = WScript.StdIn.Read(1)
End Sub
Add try this code .. Its working grt.......
<body>_x000D_
<?php_x000D_
if (isset($_POST['nav'])) {_x000D_
header("Location: $_POST[nav]");_x000D_
}_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
<select name="nav">_x000D_
<option value="">Go to page...</option>_x000D_
<option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
<option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
<option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
</select>_x000D_
<input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
$("#submit").hide();_x000D_
_x000D_
$("#page-changer select").change(function() {_x000D_
window.location = $("#page-changer select option:selected").val();_x000D_
})_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
The results of the test and source code are below (you can set the number of iterations in the app). The time is in milliseconds, and each entry is an average result of running the test 5-10 times. I found that generally it is accurate to 2-3 significant digits and after that it would vary with each run. That gives a margin of error of less than 1%. The test was running on an iPhone 3G as that's the target platform I was interested in.
numberOfItems NSArray (ms) C Array (ms) Ratio
100 0.39 0.0025 156
191 0.61 0.0028 218
3,256 12.5 0.026 481
4,789 16 0.037 432
6,794 21 0.050 420
10,919 36 0.081 444
19,731 64 0.15 427
22,030 75 0.162 463
32,758 109 0.24 454
77,969 258 0.57 453
100,000 390 0.73 534
The classes provided by Cocoa for handling data sets (NSDictionary, NSArray, NSSet etc.) provide a very nice interface for managing information, without having to worry about the bureaucracy of memory management, reallocation etc. Of course this does come at a cost though. I think it's pretty obvious that say using an NSArray of NSNumbers is going to be slower than a C Array of floats for simple iterations, so I decided to do some tests, and the results were pretty shocking! I wasn't expecting it to be this bad. Note: these tests are conducted on an iPhone 3G as that's the target platform I was interested in.
In this test I do a very simple random access performance comparison between a C float* and NSArray of NSNumbers
I create a simple loop to sum up the contents of each array and time them using mach_absolute_time(). The NSMutableArray takes on average 400 times longer!! (not 400 percent, just 400 times longer! thats 40,000% longer!).
Header:
// Array_Speed_TestViewController.h
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import <UIKit/UIKit.h>
@interface Array_Speed_TestViewController : UIViewController {
int numberOfItems; // number of items in array
float *cArray; // normal c array
NSMutableArray *nsArray; // ns array
double machTimerMillisMult; // multiplier to convert mach_absolute_time() to milliseconds
IBOutlet UISlider *sliderCount;
IBOutlet UILabel *labelCount;
IBOutlet UILabel *labelResults;
}
-(IBAction) doNSArray:(id)sender;
-(IBAction) doCArray:(id)sender;
-(IBAction) sliderChanged:(id)sender;
@end
Implementation:
// Array_Speed_TestViewController.m
// Array Speed Test
// Created by Mehmet Akten on 05/02/2009.
// Copyright MSA Visuals Ltd. 2009. All rights reserved.
#import "Array_Speed_TestViewController.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation Array_Speed_TestViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
NSLog(@"viewDidLoad");
[super viewDidLoad];
cArray = NULL;
nsArray = NULL;
// read initial slider value setup accordingly
[self sliderChanged:sliderCount];
// get mach timer unit size and calculater millisecond factor
mach_timebase_info_data_t info;
mach_timebase_info(&info);
machTimerMillisMult = (double)info.numer / ((double)info.denom * 1000000.0);
NSLog(@"machTimerMillisMult = %f", machTimerMillisMult);
}
// pass in results of mach_absolute_time()
// this converts to milliseconds and outputs to the label
-(void)displayResult:(uint64_t)duration {
double millis = duration * machTimerMillisMult;
NSLog(@"displayResult: %f milliseconds", millis);
NSString *str = [[NSString alloc] initWithFormat:@"%f milliseconds", millis];
[labelResults setText:str];
[str release];
}
// process using NSArray
-(IBAction) doNSArray:(id)sender {
NSLog(@"doNSArray: %@", sender);
uint64_t startTime = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += [[nsArray objectAtIndex:i] floatValue];
}
[self displayResult:mach_absolute_time() - startTime];
}
// process using C Array
-(IBAction) doCArray:(id)sender {
NSLog(@"doCArray: %@", sender);
uint64_t start = mach_absolute_time();
float total = 0;
for(int i=0; i<numberOfItems; i++) {
total += cArray[i];
}
[self displayResult:mach_absolute_time() - start];
}
// allocate NSArray and C Array
-(void) allocateArrays {
NSLog(@"allocateArrays");
// allocate c array
if(cArray) delete cArray;
cArray = new float[numberOfItems];
// allocate NSArray
[nsArray release];
nsArray = [[NSMutableArray alloc] initWithCapacity:numberOfItems];
// fill with random values
for(int i=0; i<numberOfItems; i++) {
// add number to c array
cArray[i] = random() * 1.0f/(RAND_MAX+1);
// add number to NSArray
NSNumber *number = [[NSNumber alloc] initWithFloat:cArray[i]];
[nsArray addObject:number];
[number release];
}
}
// callback for when slider is changed
-(IBAction) sliderChanged:(id)sender {
numberOfItems = sliderCount.value;
NSLog(@"sliderChanged: %@, %i", sender, numberOfItems);
NSString *str = [[NSString alloc] initWithFormat:@"%i items", numberOfItems];
[labelCount setText:str];
[str release];
[self allocateArrays];
}
//cleanup
- (void)dealloc {
[nsArray release];
if(cArray) delete cArray;
[super dealloc];
}
@end
From : memo.tv
////////////////////
Available since the introduction of blocks, this allows to iterate an array with blocks. Its syntax isn't as nice as fast enumeration, but there is one very interesting feature: concurrent enumeration. If enumeration order is not important and the jobs can be done in parallel without locking, this can provide a considerable speedup on a multi-core system. More about that in the concurrent enumeration section.
[myArray enumerateObjectsUsingBlock:^(id object, NSUInteger index, BOOL *stop) {
[self doSomethingWith:object];
}];
[myArray enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWith:object];
}];
/////////// NSFastEnumerator
The idea behind fast enumeration is to use fast C array access to optimize iteration. Not only is it supposed to be faster than traditional NSEnumerator, but Objective-C 2.0 also provides a very concise syntax.
id object;
for (object in myArray) {
[self doSomethingWith:object];
}
/////////////////
NSEnumerator
This is a form of external iteration: [myArray objectEnumerator] returns an object. This object has a method nextObject that we can call in a loop until it returns nil
NSEnumerator *enumerator = [myArray objectEnumerator];
id object;
while (object = [enumerator nextObject]) {
[self doSomethingWith:object];
}
/////////////////
objectAtIndex: enumeration
Using a for loop which increases an integer and querying the object using [myArray objectAtIndex:index] is the most basic form of enumeration.
NSUInteger count = [myArray count];
for (NSUInteger index = 0; index < count ; index++) {
[self doSomethingWith:[myArray objectAtIndex:index]];
}
////////////// From : darkdust.net
You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.
MyType result;
SimpleUsing.DoUsing(db =>
{
result = db.SomeQuery(); //whatever returns the MyType result
});
//do something with result
You may do as follows. one line of code will be enough
let array = $('ul>li').toArray().map(item => $(item).html());
Get the interested element
get children
get the array from toArray() method
filter out the results you want
let array = $('ul>li').toArray().map(item => $(item).html());_x000D_
console.log(array);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<ul>_x000D_
<li>text1</li>_x000D_
<li>text2</li>_x000D_
<li>text3</li>_x000D_
</ul>
_x000D_
JavaScript is case-sensitive. The b
in getElementbyId
should be capitalized.
var content = document.getElementById("edit").innerHTML;
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
I've tried to summarize the various answers here, updated for PowerShell 5:
If you're only using PowerShell 3 or higher, use $PSCommandPath
If want compatibility with older versions, insert the shim:
if ($PSCommandPath -eq $null) { function GetPSCommandPath() { return $MyInvocation.PSCommandPath; } $PSCommandPath = GetPSCommandPath; }
This adds $PSCommandPath
if it doesn't already exist.
The shim code can be executed anywhere (top-level or inside a function), though $PSCommandPath
variable is subject to normal scoping rules (eg, if you put the shim in a function, the variable is scoped to that function only).
There's 4 different methods used in various answers, so I wrote this script to demonstrate each (plus $PSCommandPath
):
function PSCommandPath() { return $PSCommandPath; }
function ScriptName() { return $MyInvocation.ScriptName; }
function MyCommandName() { return $MyInvocation.MyCommand.Name; }
function MyCommandDefinition() {
# Begin of MyCommandDefinition()
# Note: ouput of this script shows the contents of this function, not the execution result
return $MyInvocation.MyCommand.Definition;
# End of MyCommandDefinition()
}
function MyInvocationPSCommandPath() { return $MyInvocation.PSCommandPath; }
Write-Host "";
Write-Host "PSVersion: $($PSVersionTable.PSVersion)";
Write-Host "";
Write-Host "`$PSCommandPath:";
Write-Host " * Direct: $PSCommandPath";
Write-Host " * Function: $(PSCommandPath)";
Write-Host "";
Write-Host "`$MyInvocation.ScriptName:";
Write-Host " * Direct: $($MyInvocation.ScriptName)";
Write-Host " * Function: $(ScriptName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Name:";
Write-Host " * Direct: $($MyInvocation.MyCommand.Name)";
Write-Host " * Function: $(MyCommandName)";
Write-Host "";
Write-Host "`$MyInvocation.MyCommand.Definition:";
Write-Host " * Direct: $($MyInvocation.MyCommand.Definition)";
Write-Host " * Function: $(MyCommandDefinition)";
Write-Host "";
Write-Host "`$MyInvocation.PSCommandPath:";
Write-Host " * Direct: $($MyInvocation.PSCommandPath)";
Write-Host " * Function: $(MyInvocationPSCommandPath)";
Write-Host "";
Output:
PS C:\> .\Test\test.ps1
PSVersion: 5.1.19035.1
$PSCommandPath:
* Direct: C:\Test\test.ps1
* Function: C:\Test\test.ps1
$MyInvocation.ScriptName:
* Direct:
* Function: C:\Test\test.ps1
$MyInvocation.MyCommand.Name:
* Direct: test.ps1
* Function: MyCommandName
$MyInvocation.MyCommand.Definition:
* Direct: C:\Test\test.ps1
* Function:
# Begin of MyCommandDefinition()
# Note this is the contents of the MyCommandDefinition() function, not the execution results
return $MyInvocation.MyCommand.Definition;
# End of MyCommandDefinition()
$MyInvocation.PSCommandPath:
* Direct:
* Function: C:\Test\test.ps1
C:\
, but actual script is C:\Test\test.ps1
..\Test\test.ps1
)$PSCommandPath
is the only reliable way, but was introduced in PowerShell 3.NET core now has EF.Functions.Like
var isMatch = EF.Functions.Like(stringThatMightMatch, pattern);
You can use the clear method
List<string> test = new List<string>();
test.Clear();
Besides CMAKE_GENERATOR_PLATFORM
variable, there is also the -A
switch
cmake -G "Visual Studio 16 2019" -A Win32
cmake -G "Visual Studio 16 2019" -A x64
https://cmake.org/cmake/help/v3.16/generator/Visual%20Studio%2016%202019.html#platform-selection
-A <platform-name> = Specify platform name if supported by
generator.
According to Docker documentation
To use a different shell, other than ‘/bin/sh’, use the exec form passing in the desired shell. For example,
RUN ["/bin/bash", "-c", "echo hello"]
Try this,
public static Double[][] multiplicar(Double A[][],Double B[][]){
Double[][] C= new Double[2][2];
int i,j,k;
for (i = 0; i < 2; i++) {
for (j = 0; j < 2; j++) {
C[i][j] = 0.00000;
}
}
for(i=0;i<2;i++){
for(j=0;j<2;j++){
for (k=0;k<2;k++){
C[i][j]+=(A[i][k]*B[k][j]);
}
}
}
return C;
}
Just solved this problem for my personal project (thanks to Dries for that). For me it was because the project path was too long. After saving the .sln to a shorter path (C:/MyProjects) and compiling from there it ran without the error.
Suddenly, without any major change in my project, I too got this error.
All the above did not work for me, since I needed both the support libs V4 and V7.
At the end, because 2 hours ago the project compiled with no problems, I simply told Android Studio to REBUILD the project, and the error was gone.
I found this blog site: Adam Kahtava
I also found this question: send-mail-via-gmail-with-powershell-v2s-send-mailmessage
The problem is, neither of them addressed both your needs (Attachment with a password), so I did some combination of the two and came up with this:
$EmailTo = "[email protected]"
$EmailFrom = "[email protected]"
$Subject = "Test"
$Body = "Test Body"
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "C:\CDF.pdf"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$SMTPClient.Send($SMTPMessage)
Since I love to make functions for things, and I need all the practice I can get, I went ahead and wrote this:
Function Send-EMail {
Param (
[Parameter(`
Mandatory=$true)]
[String]$EmailTo,
[Parameter(`
Mandatory=$true)]
[String]$Subject,
[Parameter(`
Mandatory=$true)]
[String]$Body,
[Parameter(`
Mandatory=$true)]
[String]$EmailFrom="[email protected]", #This gives a default value to the $EmailFrom command
[Parameter(`
mandatory=$false)]
[String]$attachment,
[Parameter(`
mandatory=$true)]
[String]$Password
)
$SMTPServer = "smtp.gmail.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
if ($attachment -ne $null) {
$SMTPattachment = New-Object System.Net.Mail.Attachment($attachment)
$SMTPMessage.Attachments.Add($SMTPattachment)
}
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($EmailFrom.Split("@")[0], $Password);
$SMTPClient.Send($SMTPMessage)
Remove-Variable -Name SMTPClient
Remove-Variable -Name Password
} #End Function Send-EMail
To call it, just use this command:
Send-EMail -EmailTo "[email protected]" -Body "Test Body" -Subject "Test Subject" -attachment "C:\cdf.pdf" -password "Passowrd"
I know it's not secure putting the password in plainly like that. I'll see if I can come up with something more secure and update later, but at least this should get you what you need to get started. Have a great week!
Edit: Added $EmailFrom
based on JuanPablo's comment
Edit: SMTP was spelled STMP in the attachments.
I think you are looking for this?
var correctAnswer = Answers.First(a => a.Correct);
You can use single by typing :
var correctAnswer = Answers.Single(a => a.Correct);
The result is correct based on the SQL statement. Left join returns all values from the right table, and only matching values from the left table.
ID and NAME columns are from the right side table, so are returned.
Score is from the left table, and 30 is returned, as this value relates to Name "Flow". The other Names are NULL as they do not relate to Name "Flow".
The below would return the result you were expecting:
SELECT a.*, b.Score
FROM @Table1 a
LEFT JOIN @Table2 b
ON a.ID = b.T1_ID
WHERE 1=1
AND a.Name = 'Flow'
The SQL applies a filter on the right hand table.
I have made something like this, loading a dropdown item via Ajax. The response above is also acceptable, but it is always good to have as little DOM modification as as possible for better performance.
So rather than add each item inside a loop it is better to collect items within a loop and append it once it's completed.
$(data).each(function(){
... Collect items
})
Append it,
$('#select_id').append(items);
or even better
$('#select_id').html(items);
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
int size=5;
int ar[size ]={O};
/* This operation gives an error -
variable sized array may not be
initialised. Then just try this.
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
ar[i]=0;
}
Change <?php echo $proxy ?>
to ' . $proxy . '
.
You use <?php
when you're outputting HTML by leaving PHP mode with ?>
. When you using echo
, you have to use concatenation, or wrap your string in double quotes and use interpolation.
For Example
string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
rootPath += "MTN";
if (!(File.Exists(rootPath)))
{
File.CreateText(rootPath);
}
user this full solution to convert gridview to datatable
public DataTable gridviewToDataTable(GridView gv)
{
DataTable dtCalculate = new DataTable("TableCalculator");
// Create Column 1: Date
DataColumn dateColumn = new DataColumn();
dateColumn.DataType = Type.GetType("System.DateTime");
dateColumn.ColumnName = "date";
// Create Column 3: TotalSales
DataColumn loanBalanceColumn = new DataColumn();
loanBalanceColumn.DataType = Type.GetType("System.Double");
loanBalanceColumn.ColumnName = "loanbalance";
DataColumn offsetBalanceColumn = new DataColumn();
offsetBalanceColumn.DataType = Type.GetType("System.Double");
offsetBalanceColumn.ColumnName = "offsetbalance";
DataColumn netloanColumn = new DataColumn();
netloanColumn.DataType = Type.GetType("System.Double");
netloanColumn.ColumnName = "netloan";
DataColumn interestratecolumn = new DataColumn();
interestratecolumn.DataType = Type.GetType("System.Double");
interestratecolumn.ColumnName = "interestrate";
DataColumn interestrateperdaycolumn = new DataColumn();
interestrateperdaycolumn.DataType = Type.GetType("System.Double");
interestrateperdaycolumn.ColumnName = "interestrateperday";
// Add the columns to the ProductSalesData DataTable
dtCalculate.Columns.Add(dateColumn);
dtCalculate.Columns.Add(loanBalanceColumn);
dtCalculate.Columns.Add(offsetBalanceColumn);
dtCalculate.Columns.Add(netloanColumn);
dtCalculate.Columns.Add(interestratecolumn);
dtCalculate.Columns.Add(interestrateperdaycolumn);
foreach (GridViewRow row in gv.Rows)
{
DataRow dr;
dr = dtCalculate.NewRow();
dr["date"] = DateTime.Parse(row.Cells[0].Text);
dr["loanbalance"] = double.Parse(row.Cells[1].Text);
dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
dr["netloan"] = double.Parse(row.Cells[3].Text);
dr["interestrate"] = double.Parse(row.Cells[4].Text);
dr["interestrateperday"] = double.Parse(row.Cells[5].Text);
dtCalculate.Rows.Add(dr);
}
return dtCalculate;
}
I had a similar problem. I had installed JDK7 update 1 but couldn't use it (probably because I found a JRE6 that I deleted after installing JDK7). Uninstalling JDK7 was impossible. The solution was to add the JRE registry entries by hand.
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment]
"CurrentVersion"="1.7"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7]
"JavaHome"="C:\\Program Files\\Java\\jre7"
"RuntimeLib"="C:\\Program Files\\Java\\jre7\\bin\\client\\jvm.dll"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7.0_01]
"JavaHome"="C:\\Program Files\\Java\\jre7"
"RuntimeLib"="C:\\Program Files\\Java\\jre7\\bin\\client\\jvm.dll"
You'll have to adjust the above to your own directories and version.
If this doesn't help, there's still JavaRa http://raproducts.org/wordpress/ .
You can detect when window.print() is finished simply by putting it in another function
//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}
//print command
onPrintFinished(window.print());
tested in Firefox,Google chrome,IE
Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/
.footer
{
/* default styles applied first */
}
@media screen and (min-height: 820px) /* height >= 820 px */
{
.footer {
position: absolute;
bottom: 3px;
left: 0px;
/* more styles */
}
}
window.onresize = function() {
if (window.innerHeight >= 820) { /* ... */ }
if (window.innerWidth <= 1280) { /* ... */ }
}
$(window).on('resize', function(){
var win = $(this); //this = window
if (win.height() >= 820) { /* ... */ }
if (win.width() >= 1280) { /* ... */ }
});
This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.
To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.
debounce
will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.throttle
will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?
I tried many ways but this works.
Sample code is availalbe in DBCC SHRINKFILE
USE DBName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DBName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DBName_log, 1); --File name SELECT * FROM sys.database_files; query to get the file name
GO
-- Reset the database recovery model.
ALTER DATABASE DBName
SET RECOVERY FULL;
GO
If you are On Windows, and you are trying to setup MongoDB, run cmd as Admnistrator is the way forward as Enrique suggested above see it here
The easiest way to accomplish this is to package the desired font(s) with your application. To do this, simply create an assets/ folder in the project root, and put your fonts (in TrueType, or TTF, form) in the assets. You might, for example, create assets/fonts/ and put your TTF files in there.
Then, you need to tell your widgets to use that font. Unfortunately, you can no longer use layout XML for this, since the XML does not know about any fonts you may have tucked away as an application asset. Instead, you need to make the change in Java code, by calling Typeface.createFromAsset(getAssets(), “fonts/HandmadeTypewriter.ttf”), then taking the created Typeface object and passing it to your TextView via setTypeface().
For more reference here is the tutorial where I got this:
You can write in this way
<string name="you_me">You & Me<string>
Output: You & Me
First of all, you're testing fp
twice. so printf("Error Reading File\n");
never gets executed.
Then, the output of fscanf
should be equal to 2
since you're reading two values.
foreach (var element in instanceOfAClassThatImplelemntIEnumerable)
{
}
A very simple solution, just pass in input: mkdir dirname
void execute_command_mkdir(char *input)
{
char rec_dir[500];
int s;
if(strcmp(input,"mkdir") == 0)
printf("mkdir: operand required");
else
{
char *split = strtok(input," \t");
while(split)
{
if(strcmp(split,"create_dir") != 0)
strcpy(rec_dir,split);
split = strtok(NULL, " \t");
}
char *split2 = strtok(rec_dir,"/");
char dir[500];
strcpy(dir, "");
while(split2)
{
strcat(dir,split2);
strcat(dir,"/");
printf("%s %s\n",split2,dir);
s = mkdir(dir,0700);
split2 = strtok(NULL,"/");
}
strcpy(output,"ok");
}
if(s < 0)
printf(output,"Error!! Cannot Create Directory!!");
}
Formats like
date9.
or
mmddyy10.
are not valid for input command while converting text to a sas date. You can use
Date = input( cdate , ANYDTDTE11.);
or
Date = input( cdate , ANYDTDTE10.);
for conversion.
Updated to use the more modern Luxon instead of MomentJS.
Don't reinvent the wheel. Use a tried and tested library do this for you, Luxon for example: https://moment.github.io/luxon/index.html
From their site:
//=> 'Thu, Apr 20, 11:27 AM'
DateTime.local().toLocaleString({ weekday: 'short', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
You can also add a CALayer to the button - you can do lots of things with these including a color overlay, this example uses a plain color layer you can also easily graduate the colour. Be aware though added layers obscure those underneath
+(void)makeButtonColored:(UIButton*)button color1:(UIColor*) color
{
CALayer *layer = button.layer;
layer.cornerRadius = 8.0f;
layer.masksToBounds = YES;
layer.borderWidth = 4.0f;
layer.opacity = .3;//
layer.borderColor = [UIColor colorWithWhite:0.4f alpha:0.2f].CGColor;
CAGradientLayer *colorLayer = [CAGradientLayer layer];
colorLayer.cornerRadius = 8.0f;
colorLayer.frame = button.layer.bounds;
//set gradient colors
colorLayer.colors = [NSArray arrayWithObjects:
(id) color.CGColor,
(id) color.CGColor,
nil];
//set gradient locations
colorLayer.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:1.0f],
nil];
[button.layer addSublayer:colorLayer];
}
If you in any doubt, have a look at JDK source code
ArrayList.clear()
source code:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
You will see that size
is set to 0 so you start from 0 position.
Please note that when adding elements to ArrayList
, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear()
you only remove references to array elements and sets size
to 0, however, capacity
stays as it was.
Try this: B = A ( : )
, or try the reshape
function.
http://www.mathworks.com/access/helpdesk/help/techdoc/ref/reshape.html
Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.
Firefox and other programs allow you to increase and decrease the font size with C-+ and C--. I set up my .emacs so that I have that same ability by adding these lines of code:
(global-set-key [C-kp-add] 'text-scale-increase)
(global-set-key [C-kp-subtract] 'text-scale-decrease)
It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript
what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.
You can use line-height: 50px;
, you won't need vertical-align: middle;
there.
The above will fail if you've multiple lines, so in that case you can wrap your text using span
and than use display: table-cell;
and display: table;
along with vertical-align: middle;
, also don't forget to use width: 100%;
for #abc
#abc{
font:Verdana, Geneva, sans-serif;
font-size:18px;
text-align:left;
background-color:#0F0;
height:50px;
display: table;
width: 100%;
}
#abc span {
vertical-align:middle;
display: table-cell;
}
Another solution I can think of here is to use transform
property with translateY()
where Y
obviously stands for Y Axis. It's pretty straight forward... All you need to do is set the elements position to absolute
and later position 50%
from the top
and translate from it's axis with negative -50%
div {
height: 100px;
width: 100px;
background-color: tomato;
position: relative;
}
p {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
Note that this won't be supported on older browsers, for example IE8, but you can make IE9 and other older browser versions of Chrome and Firefox by using -ms, -moz
and -webkit
prefixes respectively.
For more information on transform
, you can refer here.
MAX_FILE_SIZE
is in KB not bytes. You were right, it is in bytes. So, for a limit of 4MB convert 4MB in bytes {1024 * (1024 * 4)}
try:
<input type="hidden" name="MAX_FILE_SIZE" value="4194304" />
As explained by others, you will never get a warning for this. It's there just to impose a soft limit on server side.
To answer your sub-question. Yes, there is a difference, you NEVER trust the user input. If you want to always impose a limit, you always must check its size. Don't trust what MAX_FILE_SIZE
does, because it can be changed by a user. So, yes, you should check to make sure it's always up to or above the size you want it to be.
The difference is that if you have imposed a MAX_FILE_SIZE
of 2MB and the user tries to upload a 4MB file, once they reach roughly the first 2MB of upload, the transfer will terminate and the PHP will stop accepting more data for that file. It will report the error on the files array.
Windows doesn't ignore anything. This is an issue with your setup; Windows just uses what you provide. It has no special knowledge of JAVA_HOME
.
CLASSPATH
has nothing to do with Windows, either. To Windows it's only an environmental variable that gets expanded to a folder location.
Check your %PATH%
environmental variable. It's what's making Windows find one before the other. The path (as the post you linked to said) should point to %JAVA_HOME%\bin;<remainder of path>
. Again, the post you linked to gave you a way to set this using a batch file.
(For others who might not know this: The easiest way to inspect the %PATH% is to open a command prompt and type echo %PATH%
. You can also get there by right-clicking on Computer
in the right pane of the Start Menu and choosing Properties
, then Advanced System Settings
, and the tne Environmental Variables
button.)
Using
dependencies:
connectivity: ^0.4.2
what we got from resouces is
import 'package:connectivity/connectivity.dart';
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
Future is little problematic for me, we have to implement it every single time like :
check().then((intenet) {
if (intenet != null && intenet) {
// Internet Present Case
}
// No-Internet Case
});
So to solve this problem i have created a class Which accept a function with boolean isNetworkPresent parameter like this
methodName(bool isNetworkPresent){}
And the Utility Class is
import 'package:connectivity/connectivity.dart'; class NetworkCheck { Future<bool> check() async { var connectivityResult = await (Connectivity().checkConnectivity()); if (connectivityResult == ConnectivityResult.mobile) { return true; } else if (connectivityResult == ConnectivityResult.wifi) { return true; } return false; } dynamic checkInternet(Function func) { check().then((intenet) { if (intenet != null && intenet) { func(true); } else{ func(false); } }); } }
And to use connectivity-check utilty
fetchPrefrence(bool isNetworkPresent) {
if(isNetworkPresent){
}else{
}
}
i will use this syntax
NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)
For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1)
geometrical lines, there is the below minimal solution (uses the shapely
module, but can be easily modified not to):
from shapely.geometry import LineString
import numpy as np
ninety_degrees_rad = 90.0 * np.pi / 180.0
def angle_between(line1, line2):
coords_1 = line1.coords
coords_2 = line2.coords
line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0
# Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
if line1_vertical and line2_vertical:
# Perpendicular vertical lines
return 0.0
if line1_vertical or line2_vertical:
# 90° - angle of non-vertical line
non_vertical_line = line2 if line1_vertical else line1
return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))
m1 = slope(line1)
m2 = slope(line2)
return np.arctan((m1 - m2)/(1 + m1*m2))
def slope(line):
# Assignments made purely for readability. One could opt to just one-line return them
x0 = line.coords[0][0]
y0 = line.coords[0][1]
x1 = line.coords[1][0]
y1 = line.coords[1][1]
return (y1 - y0) / (x1 - x0)
And the use would be
>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0
Check some typo ','
<?php
//file_get_content(url);
$jsonD = '{
"bpath":"http://www.sampledomain.com/",
"clist":[{
"cid":"11",
"display_type":"grid",
"ctitle":"abc",
"acount":"71",
"alist":[{
"aid":"6865",
"adate":"2 Hours ago",
"atitle":"test",
"adesc":"test desc",
"aimg":"",
"aurl":"?nid=6865",
"weburl":"news.php?nid=6865",
"cmtcount":"0"
},
{
"aid":"6857",
"adate":"20 Hours ago",
"atitle":"test1",
"adesc":"test desc1",
"aimg":"",
"aurl":"?nid=6857",
"weburl":"news.php?nid=6857",
"cmtcount":"0"
}
]
},
{
"cid":"1",
"display_type":"grid",
"ctitle":"test1",
"acount":"2354",
"alist":[{
"aid":"6851",
"adate":"1 Days ago",
"atitle":"test123",
"adesc":"test123 desc",
"aimg":"",
"aurl":"?nid=6851",
"weburl":"news.php?nid=6851",
"cmtcount":"7"
},
{
"aid":"6847",
"adate":"2 Days ago",
"atitle":"test12345",
"adesc":"test12345 desc",
"aimg":"",
"aurl":"?nid=6847",
"weburl":"news.php?nid=6847",
"cmtcount":"7"
}
]
}
]
}
';
$parseJ = json_decode($jsonD,true);
print_r($parseJ);
?>
Not in a JavaScript file, no.
Your JavaScript file could contains a class and you could instantiate a new instance of that class in the View, then you can pass ViewBag
values in the class constructor.
Or if it's not a class, your only other alternative, is to use data
attributes in your HTML elements, assign them to properties in your View and retrieve them in the JS file.
Assuming you had this input:
<input type="text" id="myInput" data-myValue="@ViewBag.MyValue" />
Then in your JS file you could get it by using:
var myVal = $("#myInput").data("myValue");
Give this a try:
perl -e 'use Date::Calc qw(Delta_Days); printf "%d\n", Delta_Days(2002,10,20,2003,11,22);'
To answer the question more generally, the answer is:
select: function( event , ui ) {
alert( "You selected: " + ui.item.label );
}
Complete example :
$('#test').each(function(i, el) {_x000D_
var that = $(el);_x000D_
that.autocomplete({_x000D_
source: ['apple','banana','orange'],_x000D_
select: function( event , ui ) {_x000D_
alert( "You selected: " + ui.item.label );_x000D_
}_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:
Run the script in your PowerShell ISE:
Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking
BUild list of Servers manually (this builds an array list):
$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
## - Add Code block:
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto
## - End of Code block
}
The following will solve your problem:
td.last {
width: 1px;
white-space: nowrap;
}
And a more flexible solution is creating a .fitwidth
class and applying that to any columns you want to ensure their contents are fit on one line:
td.fitwidth {
width: 1px;
white-space: nowrap;
}
And then in your HTML:
<tr>
<td class="fitwidth">ID</td>
<td>Description</td>
<td class="fitwidth">Status</td>
<td>Notes</td>
</tr>
Providing credentials on the command line is not a good idea. The above answers are great, but neglect to mention
mysql --defaults-extra-file=etc/myhost.cnf database_name < file.sql
Where etc/myhost.cnf is a file that contains host, user, password, and you avoid exposing the password on the command line. Here is a sample,
[client]
host=hostname.domainname
user=dbusername
password=dbpassword
I'm not exactly sure what it is that you want. Do you want a TimeStamp? Then you can do something simple like:
TimeStamp ts = TimeStamp.FromTicks(value.ToUniversalTime().Ticks);
Since you named a variable epoch, do you want the Unix time equivalent of your date?
DateTime unixStart = DateTime.SpecifyKind(new DateTime(1970, 1, 1), DateTimeKind.Utc);
long epoch = (long)Math.Floor((value.ToUniversalTime() - unixStart).TotalSeconds);
Have both the buttons inside a div as shown below and add the given CSS for that div
#button1, #button2{_x000D_
width: 200px;_x000D_
height: 40px;_x000D_
}_x000D_
_x000D_
#butn{_x000D_
margin: 0 auto;_x000D_
display: block;_x000D_
}
_x000D_
<div id="butn">_x000D_
<button type="button home-button" id="button1" >Home</button>_x000D_
<button type="button contact-button" id="button2">Contact Us</button>_x000D_
<div>
_x000D_
Here is another way I figured it out:
const x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
I know this is an old question, but I was struggling to do this with a time period over 2 hours, so this might help someone. Also, several of the answers don't actually plot against time, giving equal space whatever the duration.
Firstly, as @jameswarren says, use a scatter graph. Then right-click the horizontal axis and choose Format Axis.
Under Number, select Time, and at this point you may find your scale goes a bit crazy, because it chooses to scale the axis by days. So go back to Axis Options and select Fixed for the Minimum, Maximum and Major unit scales.
To set the unit to hours, type in 1/24 = 0.0416667 (I used half that to get half-hourly increments). To make this start at a round number, multiply it by your preferred number of hours and type that into the Minimum box. In my case 08:00 = 0.333333
If choice
is available, use this:
choice /C X /T 10 /D X > nul
where /T 10
is the number of seconds to delay.
Note the syntax can vary depending on your Windows version, so use CHOICE /?
to be sure.
to check input and get confirm by check box ,use this script...
$(document).on("change", ".inputClass", function () {
if($(this).is(':checked')){
confirm_message = $(this).data('confirm');
var confirm_status = confirm(confirm_message);
if (confirm_status == true) {
//doing somethings...
}
}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label> check action </lable>
<input class="inputClass" type="checkbox" data-confirm="are u sure to do ...?" >
_x000D_
The first c++ compiler actually was a preprocessor which translated the C++ code into C.
So it's very possible to have classes in C. You might try and dig up an old C++ preprocessor and see what kind of solutions it creates.
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
As of June 2020, adding role='button'
to any HTML tag would add cursor: "pointer"
to the element styling.
<span role="button">Non-button element button</span>
Official discussion on this feature - https://github.com/twbs/bootstrap/issues/23709
Documentation link - https://getbootstrap.com/docs/4.5/content/reboot/#pointers-on-buttons
It's missing an 'int'. It should be:
const static int foo = 42;
In C and C++, it declares an integer constant with local file scope of value 42.
Why 42? If you don't already know (and it's hard to believe you don't), it's a refernce to the Answer to Life, the Universe, and Everything.
There is another option that does not introduce global gotchas when trying to initialize multiple variables to the same value. Whether or not it is preferable to the long way is a judgement call. It will likely be slower and may or may not be more readable. In your specific case, I think that the long way is probably more readable and maintainable as well as being faster.
The other way utilizes Destructuring assignment.
let [moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown] = Array(6).fill(false);_x000D_
_x000D_
console.log(JSON.stringify({_x000D_
moveUp, moveDown,_x000D_
moveLeft, moveRight,_x000D_
mouseDown, touchDown_x000D_
}, null, ' '));_x000D_
_x000D_
// NOTE: If you want to do this with objects, you would be safer doing this_x000D_
let [obj1, obj2, obj3] = Array(3).fill(null).map(() => ({}));_x000D_
console.log(JSON.stringify({_x000D_
obj1, obj2, obj3_x000D_
}, null, ' '));_x000D_
// So that each array element is a unique object_x000D_
_x000D_
// Or another cool trick would be to use an infinite generator_x000D_
let [a, b, c, d] = (function*() { while (true) yield {x: 0, y: 0} })();_x000D_
console.log(JSON.stringify({_x000D_
a, b, c, d_x000D_
}, null, ' '));_x000D_
_x000D_
// Or generic fixed generator function_x000D_
function* nTimes(n, f) {_x000D_
for(let i = 0; i < n; i++) {_x000D_
yield f();_x000D_
}_x000D_
}_x000D_
let [p1, p2, p3] = [...nTimes(3, () => ({ x: 0, y: 0 }))];_x000D_
console.log(JSON.stringify({_x000D_
p1, p2, p3_x000D_
}, null, ' '));
_x000D_
This allows you to initialize a set of var
, let
, or const
variables to the same value on a single line all with the same expected scope.
References:
MDN: Array Global Object
MDN: Array.fill
if [ ! -d directory ]; then
mkdir directory
fi
or
mkdir -p directory
-p
ensures creation if directory
does not exist
Going off of tbradley22's answer, but using .map
instead:
var a = ["car", "bike", "scooter"];
a.map(function(entry) {
var singleObj = {};
singleObj['type'] = 'vehicle';
singleObj['value'] = entry;
return singleObj;
});
Yes, there is awesome simple bash script I found, which allows you to update the Postman Linux app, straight from the terminal, called postman-updater-linux.
Just install it using NPM:
npm install -g postman-updater-linux
Then check for updates:
sudo postman-updater check
Then install:
sudo postman-updater install
Or update:
sudo postman-updater update
All three last commands can be used with custom location by adding -l /your/custom/path
to end of this command.
Command:
node <path-to-jest> -i <you-test-file> -c <jest-config> -t "<test-block-name>"
<path-to-jest>
:
node_modules\jest\bin\jest.js
node_modules/.bin/jest
-i <you-test-file>
: path to the file with tests (js
or ts
)-c <jest-config>
: path to a separate Jest config file (JSON), if you keep your Jest configuration in package.json
, you don't have to specify this parameter (Jest will find it without your help)-t <the-name-of-test-block>
: actually it's a name (the first parameter) of describe(...)
, it(...)
, or test(...)
block.Example:
describe("math tests", () => {
it("1 + 1 = 2", () => {
expect(1 + 1).toBe(2);
});
it("-1 * -1 !== -1", () => {
expect(-1 * -1).not.toBe(-1);
});
});
So, the command
node node_modules/jest/bin/jest.js -i test/math-tests.js -c test/tests-config.json -t "1 + 1 = 2"
will test it("1 + 1 = 2", ...)
, but if you change the -t
parameter to "math tests"
then it will run both tests from the describe("math tests",...)
block.
Remarks:
node_modules/.bin/jest
with node_modules\jest\bin\jest.js
.'--inspect-brk'
parameter to the command.Having Jest installed, you can simplify the syntax of this command (above) by using NPM scripts. In "package.json"
add a new script to the "scripts"
section:
"scripts": {
"test:math": "jest -i test/my-tests.js -t \"math tests\"",
}
In this case, we use an alias 'jest'
instead of writing the full path to it. Also, we don't specify the configuration file path since we can place it in "package.json"
as well and Jest will look into it by default. Now you can run the command:
npm run test:math
And the "math tests"
block with two tests will be executed. Or, of course, you can specify one particular test by its name.
Another option would be to pull the <the-name-of-test-block>
parameter outside the "test:math"
script and pass it from the NPM command:
package.json:
"scripts": {
"test:math": "jest -i test/my-tests.js -t",
}
Command:
npm run test:math "math tests"
Now you can manage the name of the run test(s) with a much shorter command.
Remarks:
'jest'
command will work with NPM scripts becausenpm makes
"./node_modules/.bin"
the first entry in thePATH
environment variable when running any lifecycle scripts, so this will work fine, even if your program is not globally installed (NPM blog) 2. This approach doesn't seem to allow debugging because Jest is run via its binary/CLI, not vianode
.
If you are using Visual Studio Code you can take advantage of it and run the currently selected test (in the code editor) by pressing the F5 button. To do this, we will need to create a new launch configuration block in the ".vscode/launch.json"
file. In that configuration, we will use predefined variables which are substituted with the appropriate (unfortunately not always) values when running. Of all available we are only interested in these:
${relativeFile}
- the current opened file relative to
${workspaceFolder}
${selectedText}
- the current selected text in the active fileBut before writing out the launch configuration we should add the 'test'
script in our 'package.json'
(if we haven't done it yet).
File package.json:
"scripts": {
"test": "jest"
}
Then we can use it in our launch configuration.
Launch configuration:
{
"type": "node",
"request": "launch",
"name": "Run selected Jest test",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run-script",
"test"
],
"args": [
"--",
"-i",
"${relativeFile}",
"-t",
"${selectedText}"
],
"console": "integratedTerminal",
}
It actually does the same as the commands described earlier in this answer. Now that everything is ready, we can run any test we want without having to rewrite the command parameters manually.
Here's all you need to do:
Select currently created launch config in the debug panel:
Open the file with tests in the code editor and select the name of the test you want to test (without quotation marks):
Press F5 button.
And voilà!
Now to run any test you want. Just open it in the editor, select its name, and press F5.
Unfortunately, it won't be "voilà" on a Windows machines because they substitute (who knows why) the ${relativeFile}
variable with the path having reversed slashes and Jest wouldn't understand such a path.
Remarks:
'--inspect-brk'
parameter.'package.json'
.I've created a library that uses multipart uploads in the background to avoid buffering everything in memory and also doesn't write to disk: https://github.com/alexmojaki/s3-stream-upload
You have to do two steps:
url({{ URL::asset('images/slides/2.jpg') }})
where images/slides/2.jpg
is path of your content.Similarly you can call js, css etc.
you can call INSERTED
, SQL Server uses these tables to capture the data of the modified row before and after the event occurs.I assume in your table the name of the key is Id
I think the following code can help you
CREATE TRIGGER [dbo].[after_update]
ON [dbo].[MYTABLE]
AFTER UPDATE
AS
BEGIN
UPDATE dbo.[MYTABLE]
SET dbo.[MYTABLE].CHANGED_ON = GETDATE(),
dbo.[MYTABLE].CHANGED_BY = USER_NAME(USER_ID())
FROM INSERTED
WHERE INSERTED.Id = dbo.[MYTABLE].[Id]
END
PostAsJsonAsync
is no longer in the System.Net.Http.dll
(.NET 4.5.2). You can add a reference to System.Net.Http.Formatting.dll
, but this actually belongs to an older version. I ran into problems with this on our TeamCity build server, these two wouldn't cooperate together.
Alternatively, you can replace PostAsJsonAsync
with a PostAsync
call, which is just part of new dll.
Replace
var response = client.PostAsJsonAsync("api/AgentCollection", user).Result;
With:
var response = client.PostAsync("api/AgentCollection", new StringContent(
new JavaScriptSerializer().Serialize(user), Encoding.UTF8, "application/json")).Result;
Note that JavaScriptSerializer
is in the namespace: System.Web.Script.Serialization
.
You will have to add an assembly reference in your csproj: System.Web.Extensions.dll
See https://code.msdn.microsoft.com/windowsapps/How-to-use-HttpClient-to-b9289836
Simply doing
sudo gem uninstall cocoapods
worked for me.
You can use both PHP and javascript. Perform your php codes in the backend and redirect to a php page. On the php page you redirected to add the code below:
<?php if(condition_to_check_for){ ?>
<script type="text/javascript">
window.open('url_goes_here', '_blank');
</script>
<? } ?>
Say in the example that you are unable to change the HTML source code but only provide a stylesheet. Some thoughtless person has slapped on a style directly on the element (boo!)
div { background-color: green !important }
_x000D_
<div style="background-color:red">_x000D_
<p>Take that!</p>_x000D_
</div>
_x000D_
Here, !important can override inline CSS.
JpaRepository
extends PagingAndSortingRepository
which in turn extends CrudRepository
.
Their main functions are:
CrudRepository
mainly provides CRUD functions.PagingAndSortingRepository
provides methods to do pagination and sorting records.JpaRepository
provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.Because of the inheritance mentioned above, JpaRepository
will have all the functions of CrudRepository
and PagingAndSortingRepository
. So if you don't need the repository to have the functions provided by JpaRepository
and PagingAndSortingRepository
, use CrudRepository
.
I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.
I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!
Generate 2048-bit RSA private key:
openssl genrsa -out key.pem 2048
Generate a Certificate Signing Request:
openssl req -new -sha256 -key key.pem -out csr.csr
Generate a self-signed x509 certificate suitable for use on web servers.
openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem
Create SSL identity file in PKCS12 as mentioned here
openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem
I had this problem, the solution was to look at the commit graph (using gitk) and see that I had the following:
* commit I want to cherry-pick (x)
|\
| * branch I want to cherry-pick to (y)
* |
|/
* common parent (x)
I understand now that I want to do
git cherry-pick -m 2 mycommitsha
This is because -m 1
would merge based on the common parent where as -m 2
merges based on branch y, that is the one I want to cherry-pick to.
You would have to define operator+() for every data type you would want to concenate to the string, yet since operator<< is defined for most types, you should use std::stringstream.
Damn, beat by 50 seconds...
The
toFixed()
method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError
, RangeError
Here is the full detail and compatibility in the browser.
Suppose you have 2 lists
A = [1,2,3,4]
B = [3,4,5,6]
so you can find A
Union B
as follow
union = set(A).union(set(B))
also if you want to find intersection and non-intersection you do that as follow
intersection = set(A).intersection(set(B))
non_intersection = union - intersection
Position your <div>
absolutely at the bottom and don't forget to give div.A
a position: relative
- http://jsfiddle.net/TTaMx/
.A {
position: relative;
margin: 40px 0;
height: 40px;
width: 200px;
background: #eee;
}
.A:after {
content: " ";
display: block;
background: #c00;
height: 29px;
width: 100%;
position: absolute;
bottom: -29px;
}?
As you are not trying to move the files around in the tree, you should be able to just checkout the directory:
git checkout master -- dirname
Probably the simplest way is to use curl
for this, there is no need to install any additional packages and it can be configured directly in a request.
Here is an example using gmail smtp server:
curl --url 'smtps://smtp.gmail.com:465' --ssl-reqd \
--mail-from '[email protected]' \
--mail-rcpt '[email protected]' \
--user '[email protected]:YourPassword' \
-T <(echo -e 'From: [email protected]\nTo: [email protected]\nSubject: Curl Test\n\nHello')
http://www.bootply.com/3iSOTAyumP in this example the button for collapse was not clickable because the .navbar-brand was in front.
http://www.bootply.com/RfnEgu45qR there is an updated version where the collapse buttons is actually clickable.
This is another regex which I have learned to love/hate over the last week so usually import as (in this case yes) something that reflects how im feeling! make a normal function.... ask for input, then use ....something = re.compile(r'foo*|spam*', yes.I)...... re.I (yes.I below) is the same as IGNORECASE but you cant make as many mistakes writing it!
You then search your message using regex's but honestly that should be a few pages in its own , but the point is that foo or spam are piped together and case is ignored. Then if either are found then lost_n_found would display one of them. if neither then lost_n_found is equal to None. If its not equal to none return the user_input in lower case using "return lost_n_found.lower()"
This allows you to much more easily match up anything thats going to be case sensitive. Lastly (NCS) stands for "no one cares seriously...!" or not case sensitive....whichever
if anyone has any questions get me on this..
import re as yes
def bar_or_spam():
message = raw_input("\nEnter FoO for BaR or SpaM for EgGs (NCS): ")
message_in_coconut = yes.compile(r'foo*|spam*', yes.I)
lost_n_found = message_in_coconut.search(message).group()
if lost_n_found != None:
return lost_n_found.lower()
else:
print ("Make tea not love")
return
whatz_for_breakfast = bar_or_spam()
if whatz_for_breakfast == foo:
print ("BaR")
elif whatz_for_breakfast == spam:
print ("EgGs")
Try putting double quotes in your filepath variable
"\"E:/ABC/SEM 2/testfiles/all.txt\""
Check the permissions of the file or in any case consider renaming the folder to remove the space
try these too if just autocomplete="off"
doesn't work:
autocorrect="off" autocapitalize="off" autocomplete="off"
419 error happens when you don`t post csrf_token. in your post method you must add this token along other variables.
Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.
Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.
Using List<String> list = new LinkedList()
will get you rawtype warnings.
Completely nothing worked out for me from these answers. Had to create the project again by running cordova platform add ios
. What I've noticed, even freshly generated project with (in my case) Firebase pods caused the error message over and over again. In my opinion looks like a bug for some (Firebase, RestKit) pods in Xcode
or CocoaPods
. To have the pods included I could simply edit my config.xml
and run cordova platform add iOS
, which did everything for me automatically. Not sure if it will work in all scenarios though.
Edit: I had a Podfile
from previous iOS
/Xcode
, but the newest as of today have # DO NOT MODIFY -- auto-generated by Apache Cordova
in the Podfile
. This turned on a light in my head to try the approach. Looks a bit trivial, but works and my Firebase
features worked out.