There are few examples for using JSONP which include error handling.
However, please note that the error-event is not triggered when using JSONP! See: http://api.jquery.com/jQuery.ajax/ or jQuery ajax request using jsonp error
Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?
By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...
-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications
If you are running you should be able to access any of those system properties to see if they have been set:
if (System.getProperty("com.sun.management.jmxremote") == null) {
System.out.println("JMX remote is disabled");
} else [
String portString = System.getProperty("com.sun.management.jmxremote.port");
if (portString != null) {
System.out.println("JMX running on port "
+ Integer.parseInt(portString));
}
}
Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts
or if it is set to an incorrect interface address then you can override it with the following:
-Djava.rmi.server.hostname=<IP address>
As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port
is actually the RMI port. This tells the client what port the JMX server is running on.
Try double-clicking on the bottom right hand corner of the cell (ie on the box that you would otherwise drag).
I got du.exe
with my git distribution. Another place might be aforementioned Microsoft or Unxutils.
Once you got du.exe in your path. Here's your fileSizes.bat
:-)
@echo ___________
@echo DIRECTORIES
@for /D %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo FILES
@for %%i in (*) do @CALL du.exe -hs "%%i"
@echo _____
@echo TOTAL
@du.exe -sh "%CD%"
?
___________
DIRECTORIES
37M Alps-images
12M testfolder
_____
FILES
765K Dobbiaco.jpg
1.0K testfile.txt
_____
TOTAL
58M D:\pictures\sample
Consider this array:
$arr = array("key1" => "value1", "key2" => "value2", "key3" => "value3", "key4" => "value4");
To remove an element using the array key
:
// To unset an element from array using Key:
unset($arr["key2"]);
var_dump($arr);
// output: array(3) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
To remove element by value
:
// remove an element by value:
$arr = array_diff($arr, ["value1"]);
var_dump($arr);
// output: array(2) { ["key3"]=> string(6) "value3" ["key4"]=> string(6) "value4" }
read more about array_diff: http://php.net/manual/en/function.array-diff.php
To remove an element by using index
:
array_splice($arr, 1, 1);
var_dump($arr);
// array(1) { ["key3"]=> string(6) "value3" }
read more about array_splice: http://php.net/manual/en/function.array-splice.php
Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:
When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.
This is the procedure that seems simplest to me:
SharedPreferences sp = getSharedPreferences("MySharedPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = sp.edit();
if (sp.getString("sharedString", null).equals("true")
|| sp.getString("sharedString", null) == null) {
e.putString("sharedString", "false").commit();
// Do something
} else {
// Do something else
}
$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.
It "maps" a function to each item in an Enumerable
- in this case, a range. So it would call the block passed once for every integer from 0 to param_count
(exclusive - you're right about the dots) and return an array containing each return value.
Here's the documentation for Enumerable#map
. It also has an alias, collect
.
A very dummy mistake, but you can get this with a class too if you didn't instantiate it.
BankAccount account;
account.addMoney(5);
The above will produce the same error whereas:
class BankAccount
{
int balance = 0;
public void addMoney(int amount)
{
balance += amount;
}
}
Do the following to eliminate the error:
BankAccount account = new BankAccount();
account.addMoney(5);
This should work:
window.onload = function() {
document.getElementById('about').className = 'expand';
};
Or if you're using jQuery:
$(function() {
$('#about').addClass('expand');
});
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.
Synchronous Execution
My boss is a busy man. He tells me to write the code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?"
he's like: "No, I'm waiting right here until you finish." This is synchronous.
Asynchronous Execution
The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution.
(Take my advice: NEVER work with the boss behind you.)
Assuming you're using docker-compose, where your docker-compose.yml
file looks like:
version: '3.7'
services:
mysql_db_container:
image: mysql:latest
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_ROOT_PASSWORD: rootpassword
ports:
- 3307:3306
volumes:
- mysql_db_data_container:/var/lib/mysql
web:
image: ${DOCKER_IMAGE_NAME-eis}:latest
build:
context: .
links:
- mysql_db_container
ports:
- 4000:3000
command: ["./scripts/wait-for-it.sh", "mysql_db_container:3306", "--", "./scripts/start_web_server.sh"]
volumes:
- .:/opt/eis:cached
env_file:
- .env
volumes:
mysql_db_data_container:
Notice the ports
definition for mysql_db_container
ports:
- 3307:3306
<= That indicates that mysql will be accessible via port 3307 to the localhost workstation and via port 3306 within the docker net
Run the following to see your container names:
$ dc config --services
mysql_db_container
web
In this case, we have two containers.
If you connect to mysql_db_container
from your localhost workstation and try to access the mysql console there, you'll get that error:
docker-compose run mysql_db_container bash
root@8880ffe47962:/# mysql -u root -p
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
root@8880ffe47962:/# exit
Also, if you try to connect from your local workstation, you'll also get that error:
$ mysql -u root -p -P 3307
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
Just add the --protocol=tcp
parameter (otherwise mysql assumes you want to connect via the mysql socket):
$ mysql --protocol=tcp -u root -p -P 3307
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 11
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
Reference the docker hostname -h mysql_db_container
. Note that when you're running within the context of Docker that the TCP protocol is assumed.
$ dc run web bash
Starting eligibility-service_mysql_db_container_1_d625308b5a77 ... done
root@e7852ff02683:/opt/eis# mysql -h mysql_db_container -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 18
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [(none)]>
Assuming your mysql container name is eis_mysql_db_container_1_d625308b5a77
(that you can see when running docker ps
), the following should work:
$ docker exec -it eis_mysql_db_container_1_d625308b5a77 bash
root@3738cf6eb3e9:/# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.21 MySQL Community Server - GPL
Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
using (var serviceScope = host.Services.CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
context.Database.Migrate();
}
host.Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
In code level also, you could add your lib to the project using the compiler directives #pragma.
example:
#pragma comment( lib, "yourLibrary.lib" )
To solve this problem in IntelliJ...
1) Put your .fxml files into resources directory
2) In the Start method define the path to .fxml file in the following way:
Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
The /
seemed to solve this problem for me :)
In JavaScript strings can be either string primitive type or string objects. The following code shows the distinction:
var a: string = 'test'; // string literal
var b: String = new String('another test'); // string wrapper object
console.log(typeof a); // string
console.log(typeof b); // object
Your error:
Type 'String' is not assignable to type 'string'. 'string' is a primitive, but 'String' is a wrapper object. Prefer using 'string' when possible.
Is thrown by the TS compiler because you tried to assign the type string
to a string object type (created via new
keyword). The compiler is telling you that you should use the type string
only for strings primitive types and you can't use this type to describe string object types.
You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
Use foreach($fields as &$field){
- so you will work with the original array.
Here is more about passing by reference.
The solution is easy, you just need to download and install the Graphviz, from here.
Then set the path variable to the bin directory, in my case it was C:\Program Files (x86)\Graphviz2.38\bin
. Last, do the conda install python-graphviz
and it should work fine.
The accept attribute expects MIME types, not file masks. For example, to accept PNG images, you'd need accept="image/png". You may need to find out what MIME type the browser considers your file type to be, and use that accordingly. However, since a 'drp' file does not appear standard, you might have to accept a generic MIME type.
Additionally, it appears that most browsers may not honor this attribute.
The better way to filter file uploads is going to be on the server-side. This is inconvenient since the occasional user might waste time uploading a file only to learn they chose the wrong one, but at least you'll have some form of data integrity.
Alternatively you may choose to do a quick check with JavaScript before the form is submitted. Just check the extension of the file field's value to see if it is ".drp". This is probably going to be much more supported than the accept attribute.
Core java is a sun term.It mentions the USE,it means it contains only basics of java and some principles and also contain some packages details.
GOOGLEFINANCE can have a 20 minutes delay, so refreshing every minute would not really help.
Instead of GOOGLEFINANCE you can use different source. I'm using this RealTime stock prices(I tried a couple but this is the easiest by-far to implement. They have API that retuen JSON { Name: CurrentPrice }
Here's a little script you can use in Google Sheets(Tools->Script Editor)
function GetStocksPrice() {
var url = 'https://financialmodelingprep.com/api/v3/stock/real-time-
price/AVP,BAC,CHK,CY,GE,GPRO,HIMX,IMGN,MFG,NIO,NMR,SSSS,UCTT,UMC,ZNGA';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
// define an array of all the object keys
var headerRow = Object.keys(jsonSignal);
// define an array of all the object values
var values = headerRow.map(function(key){ return jsonSignal[key]});
var data = values[0];
// get sheet by ID -
// you can get the sheet unqiue ID from the your current sheet url
var jsonSheet = SpreadsheetApp.openById("Your Sheet UniqueID");
//var name = jsonSheet.getName();
var sheet = jsonSheet.getSheetByName('Sheet1');
// the column to put the data in -> Y
var letter = "F";
// start from line
var index = 4;
data.forEach(function( row, index2 ) {
var keys = Object.keys(row);
var value2 = row[keys[1]];
// set value loction
var cellXY = letter + index;
sheet.getRange(cellXY).setValue(value2);
index = index + 1;
});
}
Now you need to add a trigger that will execute every minute.
And your set :)
Try following command;
ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
JSONArray successObject=new JSONArray();
JSONObject dataObject=new JSONObject();
successObject.put(dataObject.toString());
This works for me.
When I know the string is going to be reasonably short then I use the following one liner... (remember to escape backslashes)
// if str is C:\windows\file system\path\picture name.jpg
alert( str.split('\\').pop() );
alert pops up with picture name.jpg
you can also do it like that :
$ver = $em->getRepository('GedDocumentBundle:version')->search($val);
$tail = sizeof($ver);
The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.
Examples:
// firstName has a hard-coded value of "hello world"
string firstName = "hello world";
// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();
A hard-coded constant[1]:
float areaOfCircle(int radius)
{
float area = 0;
area = 3.14*radius*radius; // 3.14 is a hard-coded value
return area;
}
Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.
- Hard Coding “Hard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.
The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.- Soft Coding
If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.
In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.
In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.
Sources and Citations:
1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid
Further Reading:
Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding
For anyone meaning to do this more reliably for different Minecraft versions, I have a Python script (adapted from parts of minecraft-launcher-lib) that does the job very nicely
Besides setting some basic variables near the top after the functions, it calls a get_classpath
that goes through for example ~/.minecraft/versions/1.16.5/1.16.5.json
, and loops over the libraries
array, checking to see if each object (within the array), is supposed to be added to the classpath (cp
variable). whether this library is added to the java classpath is governed by the should_use_library
function, deterministic based on the computer's architecture and operating system. finally, some jarfiles that are platform specific have extra things prepended to them (ex. natives-linux
in org/lwjgl/lwjgl/3.2.1/lwjgl-3.2.1-natives-linux.jar
). this extra prepended string is handled by get_natives_string
and is empty if it doesn't apply to the current library
tested on Linux, distribution Arch Linux
#!/usr/bin/env python
import json
import os
import platform
from pathlib import Path
import subprocess
"""Debug output
"""
def debug(str):
if os.getenv('DEBUG') != None:
print(str)
"""
[Gets the natives_string toprepend to the jar if it exists. If there is nothing native specific, returns and empty string]
"""
def get_natives_string(lib):
arch = ""
if platform.architecture()[0] == "64bit":
arch = "64"
elif platform.architecture()[0] == "32bit":
arch = "32"
else:
raise Exception("Architecture not supported")
nativesFile=""
if not "natives" in lib:
return nativesFile
# i've never seen ${arch}, but leave it in just in case
if "windows" in lib["natives"] and platform.system() == 'Windows':
nativesFile = lib["natives"]["windows"].replace("${arch}", arch)
elif "osx" in lib["natives"] and platform.system() == 'Darwin':
nativesFile = lib["natives"]["osx"].replace("${arch}", arch)
elif "linux" in lib["natives"] and platform.system() == "Linux":
nativesFile = lib["natives"]["linux"].replace("${arch}", arch)
else:
raise Exception("Platform not supported")
return nativesFile
"""[Parses "rule" subpropery of library object, testing to see if should be included]
"""
def should_use_library(lib):
def rule_says_yes(rule):
useLib = None
if rule["action"] == "allow":
useLib = False
elif rule["action"] == "disallow":
useLib = True
if "os" in rule:
for key, value in rule["os"].items():
os = platform.system()
if key == "name":
if value == "windows" and os != 'Windows':
return useLib
elif value == "osx" and os != 'Darwin':
return useLib
elif value == "linux" and os != 'Linux':
return useLib
elif key == "arch":
if value == "x86" and platform.architecture()[0] != "32bit":
return useLib
return not useLib
if not "rules" in lib:
return True
shouldUseLibrary = False
for i in lib["rules"]:
if rule_says_yes(i):
return True
return shouldUseLibrary
"""
[Get string of all libraries to add to java classpath]
"""
def get_classpath(lib, mcDir):
cp = []
for i in lib["libraries"]:
if not should_use_library(i):
continue
libDomain, libName, libVersion = i["name"].split(":")
jarPath = os.path.join(mcDir, "libraries", *
libDomain.split('.'), libName, libVersion)
native = get_natives_string(i)
jarFile = libName + "-" + libVersion + ".jar"
if native != "":
jarFile = libName + "-" + libVersion + "-" + native + ".jar"
cp.append(os.path.join(jarPath, jarFile))
cp.append(os.path.join(mcDir, "versions", lib["id"], f'{lib["id"]}.jar'))
return os.pathsep.join(cp)
version = '1.16.5'
username = '{username}'
uuid = '{uuid}'
accessToken = '{token}'
mcDir = os.path.join(os.getenv('HOME'), '.minecraft')
nativesDir = os.path.join(os.getenv('HOME'), 'versions', version, 'natives')
clientJson = json.loads(
Path(os.path.join(mcDir, 'versions', version, f'{version}.json')).read_text())
classPath = get_classpath(clientJson, mcDir)
mainClass = clientJson['mainClass']
versionType = clientJson['type']
assetIndex = clientJson['assetIndex']['id']
debug(classPath)
debug(mainClass)
debug(versionType)
debug(assetIndex)
subprocess.call([
'/usr/bin/java',
f'-Djava.library.path={nativesDir}',
'-Dminecraft.launcher.brand=custom-launcher',
'-Dminecraft.launcher.version=2.1',
'-cp',
classPath,
'net.minecraft.client.main.Main',
'--username',
username,
'--version',
version,
'--gameDir',
mcDir,
'--assetsDir',
os.path.join(mcDir, 'assets'),
'--assetIndex',
assetIndex,
'--uuid',
uuid,
'--accessToken',
accessToken,
'--userType',
'mojang',
'--versionType',
'release'
])
To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
You may want to do a careful use of the orient parameter.
For Spark 1.4.x "Pre built for Hadoop 2.6 and later":
I just copied needed S3, S3native packages from hadoop-aws-2.6.0.jar to spark-assembly-1.4.1-hadoop2.6.0.jar.
After that I restarted spark cluster and it works. Do not forget to check owner and mode of the assembly jar.
#!/bin/bash
git-remote-url() {
local rmt=$1; shift || { printf "Usage: git-remote-url [REMOTE]\n" >&2; return 1; }
local url
if ! git config --get remote.${rmt}.url &>/dev/null; then
printf "%s\n" "Error: not a valid remote name" && return 1
# Verify remote using 'git remote -v' command
fi
url=`git config --get remote.${rmt}.url`
# Parse remote if local clone used SSH checkout
[[ "$url" == git@* ]] \
&& { url="https://github.com/${url##*:}" >&2; }; \
{ url="${url%%.git}" >&2; };
printf "%s\n" "$url"
}
Usage:
# Either launch a new terminal and copy `git-remote-url` into the current shell process,
# or create a shell script and add it to the PATH to enable command invocation with bash.
# Create a local clone of your repo with SSH, or HTTPS
git clone [email protected]:your-username/your-repository.git
cd your-repository
git-remote-url origin
Output:
https://github.com/your-username/your-repository
The typical reason to set a SO_LINGER
timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT
state, tying up all the available resources on a server.
When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT
for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.
This isn't a good idea, though - TIME_WAIT
exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.
This query works for me:
SELECT DISTINCT
local_tcp_port
FROM sys.dm_exec_connections
WHERE local_tcp_port IS NOT NULL
This answer doesn't rely on external packages, I also think that most people just want a ready-made piece of code. The code below can be adapted to fit your needs by customizing: bar progress symbol '#'
, bar size
, text prefix
etc.
import sys
def progressbar(it, prefix="", size=60, file=sys.stdout):
count = len(it)
def show(j):
x = int(size*j/count)
file.write("%s[%s%s] %i/%i\r" % (prefix, "#"*x, "."*(size-x), j, count))
file.flush()
show(0)
for i, item in enumerate(it):
yield item
show(i+1)
file.write("\n")
file.flush()
Usage:
import time
for i in progressbar(range(15), "Computing: ", 40):
time.sleep(0.1) # any calculation you need
Output:
Computing: [################........................] 4/15
Doesn't require a second thread. Some solutions/packages above require.
Works with any iterable it means anything that len()
can be used on. A list
, a dict
of anything for example ['a', 'b', 'c' ... 'g']
Works with generators only have to wrap it with a list(). For example for i in progressbar(list(your_generator), "Computing: ", 40):
Unless the work is done in the generator. In that case you need another solution (like tqdm).
You can also change output by changing file to sys.stderr
for example
In my case, I also needed to reset the cached config files:
php artisan key:generate
php artisan config:cache
$value = ( array_key_exists($key, $array) && !empty($array[$key]) )
? $array[$key]
: 'non-existant or empty value key';
Testing for name pointing to None
and name existing are two semantically different operations.
To check if val
is None:
if val is None:
pass # val exists and is None
To check if name exists:
try:
val
except NameError:
pass # val does not exist at all
extension String {
/// EZSE: Trims white space and new line characters
public mutating func trim() {
self = self.trimmed()
}
/// EZSE: Trims white space and new line characters, returns a new string
public func trimmed() -> String {
return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
}
}
Taken from this repo of mine: https://github.com/goktugyil/EZSwiftExtensions/commit/609fce34a41f98733f97dfd7b4c23b5d16416206
Replaced the reader declaration with this one and now it works!
Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)
Encoding.Default represents the ANSI code page that is set under Windows Control Panel.
A very cool util is journalctl
.
For example, to show syslog to console: journalctl -t <syslog-ident>
, where <syslog-ident>
is identity you gave to function openlog
to initialize syslog.
I was getting this issue for instaling expo cli and I fixed by just following four steps mentioned in the npm documentation here.
Problem is some version of npm fail to locate folder for global installations of package. Following these steps we can create or modify the .profile file in Home directory of user and give it a proper PATH there so it works like a charm.
Try this it helped me and I spent around an hour for this issue. My node version was 6.0
Steps I follow
Back up your computer. On the command line, in your home directory, create a directory for global installations:
mkdir ~/.npm-global
Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'
In your preferred text editor, open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH
On the command line, update your system variables:
source ~/.profile
To test your new configuration, install a package globally without using sudo:
npm install -g jshint
You need to change from queue import Queue
to from multiprocessing import Queue
.
The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.
For details, you can read some source code or contact me!
setState
return a Promise
In addition to passing a callback
to setState()
method, you can wrap it around an async
function and use the then()
method -- which in some cases might produce a cleaner code:
(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
.then(() => { console.log('state:', this.state) });
And here you can take this one more step ahead and make a reusable setState
function that in my opinion is better than the above version:
const promiseState = async state =>
new Promise(resolve => this.setState(state, resolve));
promiseState({...})
.then(() => promiseState({...})
.then(() => {
... // other code
return promiseState({...});
})
.then(() => {...});
This works fine in React 16.4, but I haven't tested it in earlier versions of React yet.
Also worth mentioning that keeping your callback code in componentDidUpdate
method is a better practice in most -- probably all, cases.
All md-
prefixes are now mat-
prefixes as of time of writing this!
Put this in your html head:
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
Import in our module:
import { MatIconModule } from '@angular/material';
Use in your code:
<mat-icon>face</mat-icon>
Here is the latest documentation:
You can use a 'for in' loop for this:
for (var key in bar) {
var value = bar[key];
}
I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/
Ive refactored the code to make it simpler for this.
// In your controller
var w = angular.element($window);
$scope.$watch(
function () {
return $window.innerWidth;
},
function (value) {
$scope.windowWidth = value;
},
true
);
w.bind('resize', function(){
$scope.$apply();
});
You can then reference to windowWidth from the html
<span ng-bind="windowWidth"></span>
For example, to check if the DBI module is installed or not, use
perl -e 'use DBI;'
You will see error if not installed. (from http://www.linuxask.com)
You can use resize like this:
For n = 1 To 5
Columns(n).Resize(, 5).Select
'~~> rest of your code
Next
In any Range Manipulation that you do, always keep at the back of your mind Resize and Offset property.
In simple words:
For completeness (since this seems to be a high-traffic page), let's not forget the good old dir()
function:
$entries = [];
$d = dir("/"); // dir to scan
while (false !== ($entry = $d->read())) { // mind the strict bool check!
if ($entry[0] == '.') continue; // ignore anything starting with a dot
$entries[] = $entry;
}
$d->close();
sort($entries); // or whatever desired
print_r($entries);
I'm answering only the part of the question about zbar
installation.
I spent nearly half an hour a few hours to make it work on Windows + Python 2.7 64-bit, so here are additional notes to the accepted answer:
Install it with pip install zbar-0.10-cp27-none-win_amd64.whl
If Python reports an ImportError: DLL load failed: The specified module could not be found.
when doing import zbar
, then you will just need to install the Visual C++ Redistributable Packages for VS 2013 (I spent a lot of time here, trying to recompile unsuccessfully...)
Required too: libzbar64-0.dll must be in a folder which is in the PATH. In my case I copied it to "C:\Python27\libzbar64-0.dll" (which is in the PATH). If it still does not work, add this:
import os
os.environ['PATH'] += ';C:\\Python27'
import zbar
PS: Making it work with Python 3.x is even more difficult: Compile zbar for Python 3.x.
PS2: I just tested pyzbar with pip install pyzbar
and it's MUCH easier, it works out-of-the-box (the only thing is you need to have VC Redist 2013 files installed). It is also recommended to use this library in this pyimagesearch.com article.
To split your String by comma(,) use str.split(",")
and for tab use str.split("\\t")
try {
BufferedReader in = new BufferedReader(
new FileReader("G:\\RoutePPAdvant2.txt"));
String str;
while ((str = in.readLine())!= null) {
String[] ar=str.split(",");
...
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I know this already has a marked answer, but I feel I have an improvement to it.
The marked answer is a bit misleading. He set a width to the button, which is not necessary, and set widths are not "responsive". To his defense, he mentions in a comment below it, that the width is not necessary and just an example.
One thing not mentioned here, is that the words may break in the middle of a word and look messed up.
My solution, forces the break to happen between words, a nice word wrap.
.btn-responsive {
white-space: normal !important;
word-wrap: break-word;
}
<a href="#" class="btn btn-primary btn-responsive">Click Here</a>
ymin, ymax = axes.get_ylim()
If you are using the plt
api directly, you can avoid calls to axes
altogether:
def myplotfunction(title, values, errors, plot_file_name):
# plot errorbars
indices = range(0, len(values))
fig = plt.figure()
plt.errorbar(tuple(indices), tuple(values), tuple(errors), marker='.')
plt.ylim([-0.5, len(values) - 0.5])
plt.xlabel('My x-axis title')
plt.ylabel('My y-axis title')
# title
plt.title(title)
# save as file
plt.savefig(plot_file_name)
# close figure
plt.close(fig)
Once you have the flattened DataFrame
obtained by the accepted answer, you can make the columns a MultiIndex
("fancy multiline header") like this:
df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])
The answer provided by @aaronasterling looks good, however, it is not compatible with the default interface of list: x = MyList(1, 2, 3, 4)
vs x = MyList([1, 2, 3, 4])
. Thus, the below code can be used as a more python-list friendly:
class MyList(list):
def __init__(self, *args):
super(MyList, self).__init__(*args)
def __sub__(self, other):
return self.__class__([item for item in self if item not in other])
Example:
x = MyList([1, 2, 3, 4])
y = MyList([2, 5, 2])
z = x - y
Try this:
var div = document.getElementsByClassName('drill_cursor')[0];
div.addEventListener('click', function (event) {
alert('Hi!');
});
Reflection and dynamic value access are correct solutions to this question but are quite slow. If your want something faster then you can create dynamic method using expressions:
object value = GetValue();
string propertyName = "MyProperty";
var parameter = Expression.Parameter(typeof(object));
var cast = Expression.Convert(parameter, value.GetType());
var propertyGetter = Expression.Property(cast, propertyName);
var castResult = Expression.Convert(propertyGetter, typeof(object));//for boxing
var propertyRetriver = Expression.Lambda<Func<object, object>>(castResult, parameter).Compile();
var retrivedPropertyValue = propertyRetriver(value);
This way is faster if you cache created functions. For instance in dictionary where key would be the actual type of object assuming that property name is not changing or some combination of type and property name.
Some 2+ years after I asked this question I'd like to explain it the way I'd want it explained back when I was still a complete newb and would be most beneficial to people who want to understand the process.
First of all, forget the "11111111" example value, which is not really all that suited for the visual explanation of the process. So let the initial value be 10111011
(187 decimal) which will be a little more illustrative of the process.
1 - how to read a 3 bit value starting from the second bit:
___ <- those 3 bits
10111011
The value is 101, or 5 in decimal, there are 2 possible ways to get it:
In this approach, the needed bits are first masked with the value 00001110
(14 decimal) after which it is shifted in place:
___
10111011 AND
00001110 =
00001010 >> 1 =
___
00000101
The expression for this would be: (value & 14) >> 1
This approach is similar, but the order of operations is reversed, meaning the original value is shifted and then masked with 00000111
(7) to only leave the last 3 bits:
___
10111011 >> 1
___
01011101 AND
00000111
00000101
The expression for this would be: (value >> 1) & 7
Both approaches involve the same amount of complexity, and therefore will not differ in performance.
2 - how to write a 3 bit value starting from the second bit:
In this case, the initial value is known, and when this is the case in code, you may be able to come up with a way to set the known value to another known value which uses less operations, but in reality this is rarely the case, most of the time the code will know neither the initial value, nor the one which is to be written.
This means that in order for the new value to be successfully "spliced" into byte, the target bits must be set to zero, after which the shifted value is "spliced" in place, which is the first step:
___
10111011 AND
11110001 (241) =
10110001 (masked original value)
The second step is to shift the value we want to write in the 3 bits, say we want to change that from 101 (5) to 110 (6)
___
00000110 << 1 =
___
00001100 (shifted "splice" value)
The third and final step is to splice the masked original value with the shifted "splice" value:
10110001 OR
00001100 =
___
10111101
The expression for the whole process would be: (value & 241) | (6 << 1)
Bonus - how to generate the read and write masks:
Naturally, using a binary to decimal converter is far from elegant, especially in the case of 32 and 64 bit containers - decimal values get crazy big. It is possible to easily generate the masks with expressions, which the compiler can efficiently resolve during compilation:
((1 << fieldLength) - 1) << (fieldIndex - 1)
, assuming that the index at the first bit is 1 (not zero)(1 << fieldLength) - 1
(index does not play a role here since it is always shifted to the first bit~
operatorHow does it work (with the 3bit field beginning at the second bit from the examples above)?
00000001 << 3
00001000 - 1
00000111 << 1
00001110 ~ (read mask)
11110001 (write mask)
The same examples apply to wider integers and arbitrary bit width and position of the fields, with the shift and mask values varying accordingly.
Also note that the examples assume unsigned integer, which is what you want to use in order to use integers as portable bit-field alternative (regular bit-fields are in no way guaranteed by the standard to be portable), both left and right shift insert a padding 0, which is not the case with right shifting a signed integer.
Even easier:
Using this set of macros (but only in C++ since it relies on the generation of member functions):
#define GETMASK(index, size) ((((size_t)1 << (size)) - 1) << (index))
#define READFROM(data, index, size) (((data) & GETMASK((index), (size))) >> (index))
#define WRITETO(data, index, size, value) ((data) = (((data) & (~GETMASK((index), (size)))) | (((value) << (index)) & (GETMASK((index), (size))))))
#define FIELD(data, name, index, size) \
inline decltype(data) name() const { return READFROM(data, index, size); } \
inline void set_##name(decltype(data) value) { WRITETO(data, index, size, value); }
You could go for something as simple as:
struct A {
uint bitData;
FIELD(bitData, one, 0, 1)
FIELD(bitData, two, 1, 2)
};
And have the bit fields implemented as properties you can easily access:
A a;
a.set_two(3);
cout << a.two();
Replace decltype
with gcc's typeof
pre-C++11.
The Database is very flexible with multi-threading. My apps hit their DBs from many different threads simultaneously and it does just fine. In some cases I have multiple processes hitting the DB simultaneously and that works fine too.
Your async tasks - use the same connection when you can, but if you have to, its OK to access the DB from different tasks.
You can use client-side validation:
<asp:textbox onkeydown="return (!(event.keyCode>=65) && event.keyCode!=32);" />
Simply use super.alphaMethod1();
Got this example from cppreference. It works with:
GCC 10.1+ with flag -std=c++20
#include <ranges>
#include <iostream>
int main()
{
static constexpr auto il = {3, 1, 4, 1, 5, 9};
std::ranges::reverse_view rv {il};
for (int i : rv)
std::cout << i << ' ';
std::cout << '\n';
for(int i : il | std::views::reverse)
std::cout << i << ' ';
}
Perhaps another way to code conditional constructs in XML:
<rule>
<if>
<conditions>
<condition var="something" operator=">">400</condition>
<!-- more conditions possible -->
</conditions>
<statements>
<!-- do something -->
</statements>
</if>
<elseif>
<conditions></conditions>
<statements></statements>
</elseif>
<else>
<statements></statements>
</else>
</rule>
You can use the CSS property background-size
and set it to cover
or contain
, depending your preference. Cover will cover the window entirely, while contain will make one side fit the window thus not covering the entire page (unless the aspect ratio of the screen is equal to the image).
Please note that this is a CSS3 property. In older browsers, this property is ignored. Alternatively, you can use javascript to change the CSS settings depending on the window size, but this isn't preferred.
body {
background-image: url(image.jpg); /* image */
background-position: center; /* center the image */
background-size: cover; /* cover the entire window */
}
There is no universal command line that would fit to all cases (sometimes you need to blur and sharpen image). But you can give a try to TEXTCLEANER from Fred's ImageMagick Scripts.
If you are not fan of command line, maybe you can try to use opensource scantailor.sourceforge.net or commercial bookrestorer.
Many solution here with lot of upvotes didn't work for me, even the accepted answer. I solved it by setting the scaleY, but isn't a good solution if you need too much height because the drawable comes pixelated.
Programmatically:
progressBar.setScaleY(2f);
XML Layout:
android:scaleY="2"
if you have in your layout activity_main
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
you have to put
in your Activity this code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setBackgroundColor(Color.CYAN);
}
Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:
SELECT model, date
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model
Firebase is a suite of features .
I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .
When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .
Here is an example `
$(document).ready(function() {
var lastItem = null;
$(".our-work-group > p > a").click(function(e) {
e.preventDefault();
var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
if (item == lastItem) {
lastItem = null;
$('.our-work-single-page').show();
} else {
lastItem = item;
$('.our-work-single-page').each(function() {
var imgAlt = $(this).find('img').attr('alt'); //Here value of "this" is '.our-work-single-page'.
if (imgAlt != item) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});`
So you can see that value of this is two different values depending on the DOM element you target but when you add "that" to the code above you change the value of "this" you are targeting.
`$(document).ready(function() {
var lastItem = null;
$(".our-work-group > p > a").click(function(e) {
e.preventDefault();
var item = $(this).html(); //Here value of "this" is ".our-work-group > p > a"
if (item == lastItem) {
lastItem = null;
var that = this;
$('.our-work-single-page').show();
} else {
lastItem = item;
$('.our-work-single-page').each(function() {
***$(that).css("background-color", "#ffe700");*** //Here value of "that" is ".our-work-group > p > a"....
var imgAlt = $(this).find('img').attr('alt');
if (imgAlt != item) {
$(this).hide();
} else {
$(this).show();
}
});
}
});
});`
.....$(that).css("background-color", "#ffe700"); //Here value of "that" is ".our-work-group > p > a" because the value of var that = this; so even though we are at "this"= '.our-work-single-page', still we can use "that" to manipulate previous DOM element.
sudo apt install aptitude
Then
sudo aptitude install npm
What's the problem with using for
loop inside, just like outside?
for (int j = i + 1; j < list.size(); ++j) {
...
}
In general, since Java 5, I used iterators only once or twice.
Another simple way to exclude the auto configuration classes,
Add below similar configuration to your application.yml file,
---
spring:
profiles: test
autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration
That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the *
with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:
paths:
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:
# coding: utf-8
from __future__ import print_function
import ruamel.yaml as yaml
class Paths:
def __init__(self):
self.d = {}
def __repr__(self):
return repr(self.d).replace('ordereddict', 'Paths')
@staticmethod
def __yaml_in__(loader, data):
result = Paths()
loader.construct_mapping(data, result.d)
return result
@staticmethod
def __yaml_out__(dumper, self):
return dumper.represent_mapping('!Paths', self.d)
def __getitem__(self, key):
res = self.d[key]
return self.expand(res)
def expand(self, res):
try:
before, rest = res.split(u'?', 1)
kw, rest = rest.split(u'? +', 1)
rest = rest.lstrip() # strip any spaces after "+"
# the lookup will throw the correct keyerror if kw is not found
# recursive call expand() on the tail if there are multiple
# parts to replace
return before + self.d[kw] + self.expand(rest)
except ValueError:
return res
yaml_str = """\
paths: !Paths
root: /path/to/root/
patha: ?root? + a
pathb: ?root? + b
pathc: ?root? + c
"""
loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)
paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']
for k in ['root', 'pathc']:
print(u'{} -> {}'.format(k, paths[k]))
which will print:
root -> /path/to/root/
pathc -> /path/to/root/c
The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.
By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:
dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))
this will change the mapping key ordering. If that is a problem you have
to make self.d
a CommentedMap
(imported from ruamel.yaml.comments.py
)
You (still) can not choose the position of the column using ALTER TABLE: it can only be added to the end of the table. You can obviously select the columns in any order you want, so unless you are using SELECT * FROM column order shouldn't be a big deal.
If you really must have them in a particular order and you can't drop and recreate the table, then you might be able to drop and recreate columns instead:-
First copy the table
CREATE TABLE my_tab_temp AS SELECT * FROM my_tab;
Then drop columns that you want to be after the column you will insert
ALTER TABLE my_tab DROP COLUMN three;
Now add the new column (two in this example) and the ones you removed.
ALTER TABLE my_tab ADD (two NUMBER(2), three NUMBER(10));
Lastly add back the data for the re-created columns
UPDATE my_tab SET my_tab.three = (SELECT my_tab_temp.three FROM my_tab_temp WHERE my_tab.one = my_tab_temp.one);
Obviously your update will most likely be more complex and you'll have to handle indexes and constraints and won't be able to use this in some cases (LOB columns etc). Plus this is a pretty hideous way to do this - but the table will always exist and you'll end up with the columns in a order you want. But does column order really matter that much?
keras predict_classes (docs) outputs A numpy array of class predictions. Which in your model case, the index of neuron of highest activation from your last(softmax) layer. [[0]]
means that your model predicted that your test data is class 0. (usually you will be passing multiple image, and the result will look like [[0], [1], [1], [0]]
)
You must convert your actual label (e.g. 'cancer', 'not cancer'
) into binary encoding (0
for 'cancer', 1
for 'not cancer') for binary classification. Then you will interpret your sequence output of [[0]]
as having class label 'cancer'
Same thing happened to me just now. I set prettier as the Default Formatter in Settings and it started working again. My Default Formatter was null.
To set VSCODE Default Formatter
File -> Preferences -> Settings (for Windows) Code -> Preferences -> Settings (for Mac)
Search for "Default Formatter". In the dropdown, prettier will show as esbenp.prettier-vscode.
df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
does already return a dataframe, so you cannot loop over the groups anymore.
In general:
df.groupby(...)
returns a GroupBy
object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:
grouped = df.groupby('A')
for name, group in grouped:
...
When you apply a function on the groupby, in your example df.groupby(...).agg(...)
(but this can also be transform
, apply
, mean
, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).
Yes assuming you have this:
var WhatIsThe = AnswerToLife()
func AnswerToLife() int {
return 42
}
func init() {
WhatIsThe = 0
}
func main() {
if WhatIsThe == 0 {
fmt.Println("It's all a lie.")
}
}
AnswerToLife()
is guaranteed to run before init()
is called, and init()
is guaranteed to run before main()
is called.
Keep in mind that init()
is always called, regardless if there's main or not, so if you import a package that has an init
function, it will be executed.
Additionally, you can have multiple init()
functions per package; they will be executed in the order they show up in the file (after all variables are initialized of course). If they span multiple files, they will be executed in lexical file name order (as pointed out by @benc):
It seems that
init()
functions are executed in lexical file name order. The Go spec says "build systems are encouraged to present multiple files belonging to the same package in lexical file name order to a compiler". It seems thatgo build
works this way.
A lot of the internal Go packages use init()
to initialize tables and such, for example https://github.com/golang/go/blob/883bc6/src/compress/bzip2/bzip2.go#L480
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
This might look cheap but it's working for me
SELECT CONVERT(DATETIME,LEFT(CONVERT(VARCHAR,@dateFieldOrVariable,101),10)+' 00:00:00.000')
Use the CSS display values of table and table-cell:
HTML
<html>
<body>
<div class="valign bottom">
<div>
<div>my bottom aligned div 1</div>
<div>my bottom aligned div 2</div>
<div>my bottom aligned div 3</div>
</div>
</div>
</body>
</html>
CSS
html,body {
width: 100%;
height: 100%;
}
.valign {
display: table;
width: 100%;
height: 100%;
}
.valign > div {
display: table-cell;
width: 100%;
height: 100%;
}
.valign.bottom > div {
vertical-align: bottom;
}
I've created a JSBin demo here: http://jsbin.com/INOnAkuF/2/edit
The demo also has an example how to vertically center align using the same technique.
Works fine for me with one change - fourth line should be:
cell.Value = Trim(cell.Value)
Edit: If it appears to be stuck in a loop, I'd add
Debug.Print cell.Address
inside your For ... Next
loop to get a bit more info on what's happening.
I also suspect that Trim
only strips spaces - are you sure you haven't got some other kind of non-display character in there?
In Swift, you can overload existing operators:
func > (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
func < (lhs: NSDate, rhs: NSDate) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
Then, you can compare NSDates directly with <
, >
, and ==
(already supported).
Here is an easy example of how to kill all Word Processes.
Process[] procs = Process.GetProcessesByName("winword");
foreach (Process proc in procs)
proc.Kill();
You can validate group checkbox and radio button without extra js code, see below example.
Your JS should be look like:
$("#formid").validate();
You can play with HTML tag and attributes: eg. group checkbox [minlength=2 and maxlength=4]
<fieldset class="col-md-12">
<legend>Days</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="1" required="required" data-msg-required="This value is required." minlength="2" maxlength="4" data-msg-maxlength="Max should be 4">Monday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="2">Tuesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="3">Wednesday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="4">Thursday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="5">Friday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="6">Saturday
</label>
<label class="checkbox-inline">
<input type="checkbox" name="daysgroup[]" value="7">Sunday
</label>
<label for="daysgroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can see here first or any one input should have required, minlength="2" and maxlength="4" attributes. minlength/maxlength as per your requirement.
eg. group radio button:
<fieldset class="col-md-12">
<legend>Gender</legend>
<div class="form-row">
<div class="col-12 col-md-12 form-group">
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="m" required="required" data-msg-required="This value is required.">man
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="w">woman
</label>
<label class="form-check-inline">
<input type="radio" name="gendergroup[]" value="o">other
</label>
<label for="gendergroup[]" class="error">Your error message will be display here.</label>
</div>
</div>
</fieldset>
You can check working example here.
Try this one:
onsubmit="return f(this.'yourfieldname'.value);"
I hope this will help you.
It can be done with the regular JavaScript function replace()
.
value.replace(".", ":");
If you pass a string that is case-insensitive into LINQ-to-SQL it will get passed into the SQL unchanged and the comparison will happen in the database. If you want to do case-insensitive string comparisons in the database all you need to to do is create a lambda expression that does the comparison and the LINQ-to-SQL provider will translate that expression into a SQL query with your string intact.
For example this LINQ query:
from user in Users
where user.Email == "[email protected]"
select user
gets translated to the following SQL by the LINQ-to-SQL provider:
SELECT [t0].[Email]
FROM [User] AS [t0]
WHERE [t0].[Email] = @p0
-- note that "@p0" is defined as nvarchar(11)
-- and is passed my value of "[email protected]"
As you can see, the string parameter will be compared in SQL which means things ought to work just the way you would expect them to.
Try to use the fleqn
document class option.
\documentclass[fleqn]{article}
(See also http://en.wikibooks.org/wiki/LaTeX/Basics for a list of other options.)
Add following at this location C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\x64 FileName: sgen.exe.config(If you dont find this file, create and add one)
<?xml version ="1.0"?>_x000D_
_x000D_
<configuration>_x000D_
<runtime> _x000D_
<generatePublisherEvidence enabled="false"/> _x000D_
</runtime>_x000D_
_x000D_
<startup useLegacyV2RuntimeActivationPolicy="true">_x000D_
_x000D_
<supportedRuntime version="v4.0" />_x000D_
_x000D_
</startup> _x000D_
_x000D_
</configuration>
_x000D_
Doing this resolved the issue
I've worked it out.
Let's say you have a Python datetime object, d, created with datetime.now(). Its value is:
datetime.datetime(2011, 5, 25, 13, 34, 5, 787000)
You can serialize it to JSON as an ISO 8601 datetime string:
import json
json.dumps(d.isoformat())
The example datetime object would be serialized as:
'"2011-05-25T13:34:05.787000"'
This value, once received in the Javascript layer, can construct a Date object:
var d = new Date("2011-05-25T13:34:05.787000");
As of Javascript 1.8.5, Date objects have a toJSON method, which returns a string in a standard format. To serialize the above Javascript object back to JSON, therefore, the command would be:
d.toJSON()
Which would give you:
'2011-05-25T20:34:05.787Z'
This string, once received in Python, could be deserialized back to a datetime object:
datetime.strptime('2011-05-25T20:34:05.787Z', '%Y-%m-%dT%H:%M:%S.%fZ')
This results in the following datetime object, which is the same one you started with and therefore correct:
datetime.datetime(2011, 5, 25, 20, 34, 5, 787000)
I know this is an old question, but...
I was just noticing my instance of IISExpress wasn't serving woff files, so I wen't searching (Found this) and then found:
http://www.tomasmcguinness.com/2011/07/06/adding-support-for-svg-to-iis-express/
I suppose my install has support for SVG since I haven't had issue with that. But the instructions are trivially modifiable for woff:
Run the command:
appcmd set config /section:staticContent /+[fileExtension='woff',mimeType='application/x-woff']
Solved my problem, and I didn't have to mess with some crummy config (like I had to to add support for the PUT
and DELETE
verbs). Yay!
In XML
<androidx.appcompat.widget.Toolbar
android:id="@+id/main_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways">
</androidx.appcompat.widget.Toolbar>
Kotlin: In fragment.kt -> onCreateView()
setHasOptionsMenu(true)
val toolbar = view.findViewById<Toolbar>(R.id.main_toolbar)
(activity as? AppCompatActivity)?.setSupportActionBar(toolbar)
(activity as? AppCompatActivity)?.supportActionBar?.show()
-> onCreateOptionsMenu()
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.app_main_menu,menu)
super.onCreateOptionsMenu(menu, inflater)
}
->onOptionsItemSelected()
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.selected_id->{//to_do}
else -> super.onOptionsItemSelected(item)
}
}
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
for others scratching their heads, I came across this error because I had innapropriately const-qualified one of the arguments to a method in a base class, so the derived class member functions were not over-riding it. so make sure you don't have something like
class Base
{
public:
virtual void foo(int a, const int b) = 0;
}
class D: public Base
{
public:
void foo(int a, int b){};
}
Entity interface
public interface Entity<I> extends Serializable {
/**
* @return entity identity
*/
I getId();
/**
* @return HashCode of entity identity
*/
int identityHashCode();
/**
* @param other
* Other entity
* @return true if identities of entities are equal
*/
boolean identityEquals(Entity<?> other);
}
Basic implementation for all Entities, simplifies Equals/Hashcode implementations:
public abstract class AbstractEntity<I> implements Entity<I> {
@Override
public final boolean identityEquals(Entity<?> other) {
if (getId() == null) {
return false;
}
return getId().equals(other.getId());
}
@Override
public final int identityHashCode() {
return new HashCodeBuilder().append(this.getId()).toHashCode();
}
@Override
public final int hashCode() {
return identityHashCode();
}
@Override
public final boolean equals(final Object o) {
if (this == o) {
return true;
}
if ((o == null) || (getClass() != o.getClass())) {
return false;
}
return identityEquals((Entity<?>) o);
}
@Override
public String toString() {
return getClass().getSimpleName() + ": " + identity();
// OR
// return ReflectionToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
}
Room Entity impl:
@Entity
@Table(name = "ROOM")
public class Room extends AbstractEntity<Integer> {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;
@Column(name = "number")
private String number; //immutable
@Column(name = "capacity")
private Integer capacity;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "building_id")
private Building building; //immutable
Room() {
// default constructor
}
public Room(Building building, String number) {
// constructor with required field
notNull(building, "Method called with null parameter (application)");
notNull(number, "Method called with null parameter (name)");
this.building = building;
this.number = number;
}
public Integer getId(){
return id;
}
public Building getBuilding() {
return building;
}
public String getNumber() {
return number;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
//no setters for number, building nor id
}
I don't see a point of comparing equality of entities based on business fields in every case of JPA Entities. That might be more of a case if these JPA entities are thought of as Domain-Driven ValueObjects, instead of Domain-Driven Entities (which these code examples are for).
Try adding the following line at the top of your python script.
# _*_ coding:utf-8 _*_
The exact question is how to do it with pure JavaScript not with jQuery.
But I always use the solution that can be found in jQuery's source code. It's just one line of native JavaScript.
For me it's the best, easy readable and even afaik the shortest way to get the iframes content.
First get your iframe
var iframe = document.getElementById('id_description_iframe');
// or
var iframe = document.querySelector('#id_description_iframe');
And then use jQuery's solution
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
It works even in the Internet Explorer which does this trick during the
contentWindow
property of theiframe
object. Most other browsers uses thecontentDocument
property and that is the reason why we proof this property first in this OR condition. If it is not set trycontentWindow.document
.
Select elements in iframe
Then you can usually use getElementById()
or even querySelectorAll()
to select the DOM-Element from the iframeDocument
:
if (!iframeDocument) {
throw "iframe couldn't be found in DOM.";
}
var iframeContent = iframeDocument.getElementById('frameBody');
// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');
Call functions in the iframe
Get just the window
element from iframe
to call some global functions, variables or whole libraries (e.g. jQuery
):
var iframeWindow = iframe.contentWindow;
// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');
// or
iframeContent = iframeWindow.$('#frameBody');
// or even use any other global variable
iframeWindow.myVar = window.myVar;
// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);
Note
All this is possible if you observe the same-origin policy.
This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n
:
zip(*(l[start:] for start in range(0, n)))
Examples:
l = range(0, 4) # [0, 1, 2, 3]
list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []
Explanations:
l[start:]
generates a a list/generator starting from index start
*list
or *generator
: passes all elements to the enclosing function zip
as if it was written zip(elem1, elem2, ...)
Note:
AFAIK, this code is as lazy as it can be. Not tested.
The function below will take as input # of minutes and output time in the following format: Hours:minutes. I used Math.trunc(), which is a new method added in 2015. It returns the integral part of a number by removing any fractional digits.
function display(a){
var hours = Math.trunc(a/60);
var minutes = a % 60;
console.log(hours +":"+ minutes);
}
display(120); //"2:0"
display(60); //"1:0:
display(100); //"1:40"
display(126); //"2:6"
display(45); //"0:45"
In the device manager you can select View > Show hidden devices
I encountered this error and I think the issue was that I had 'run as admin' when I started Eclipse and created the files, therefore they were owned by Admin (noticed by running 'ls -la' on the folder). When I later tried to stash the files, it didn't let me ('unable to unlink files' and all that). Doing a chmod on the files was the fix for me.
x=3#rows
y=3#columns
a=[]#create an empty list first
for i in range(x):
a.append([0]*y)#And again append empty lists to original list
for j in range(y):
a[i][j]=input("Enter the value")
If you use a static key, encrypt and decrypt always give the same result;
public static final String CRYPTOR_KEY = "your static key here";
byte[] keyByte = Base64.getDecoder().decode(CRYPTOR_KEY);
key = new SecretKeySpec(keyByte, "AES");
Try this:
Alex Misuno@hp4530s ~
$ cat test.txt
1 OK
2 OK
3 NOTOK
4 OK
5 NOTOK
Alex Misuno@hp4530s ~
$ cat test.txt | grep ".* OK$"
1 OK
2 OK
4 OK
var intTried = Convert.ChangeType(myObject, typeof(int)) as int?;
About the Implicit Objects of the Unified Expression Language, the Java EE 5 Tutorial writes:
Implicit Objects
The JSP expression language defines a set of implicit objects:
pageContext
: The context for the JSP page. Provides access to various objects including:
servletContext
: The context for the JSP page’s servlet and any web components contained in the same application. See Accessing the Web Context.session
: The session object for the client. See Maintaining Client State.request
: The request triggering the execution of the JSP page. See Getting Information from Requests.response
: The response returned by the JSP page. See Constructing Responses.- In addition, several implicit objects are available that allow easy access to the following objects:
param
: Maps a request parameter name to a single valueparamValues
: Maps a request parameter name to an array of valuesheader
: Maps a request header name to a single valueheaderValues
: Maps a request header name to an array of valuescookie
: Maps a cookie name to a single cookieinitParam
: Maps a context initialization parameter name to a single value- Finally, there are objects that allow access to the various scoped variables described in Using Scope Objects.
pageScope
: Maps page-scoped variable names to their valuesrequestScope
: Maps request-scoped variable names to their valuessessionScope
: Maps session-scoped variable names to their valuesapplicationScope
: Maps application-scoped variable names to their values
The interesting parts are in bold :)
So, to answer your question, you should be able to access it like this (using EL):
${param.accountID}
Or, using JSP Scriptlets (not recommended):
<%
String accountId = request.getParameter("accountID");
%>
Try This
@Html.DropDownList("Id", null, new { @class = "ct-js-select ct-select-lg" })
This exact example is present on mozilla developers page:
As you can see it even allows you to create tooltips! :) Also, instead of embedding the actual text in your CSS, you may use content: attr(data-descr);
, and store it in data-descr="ADD"
attribute of your HTML tag (which is nice because you can e.g translate it)
CSS content
can only be usef with :after
and :before
pseudo-elements, so you can try to proceed with something like this:
.item a p.new-label span:after{
position: relative;
content: 'NEW'
}
.item:hover a p.new-label span:after {
content: 'ADD';
}
The CSS :after pseudo-element matches a virtual last child of the selected element. Typically used to add cosmetic content to an element, by using the content CSS property. This element is inline by default.
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.
The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.
without considering this to be a good idea...
select dbo.F_AddThousandSeparators(convert(varchar, convert(decimal(18, 4), 1234.1234567), 1))
Function
-- Author: bummi
-- Create date: 20121106
CREATE FUNCTION F_AddThousandSeparators(@NumStr varchar(50))
RETURNS Varchar(50)
AS
BEGIN
declare @OutStr varchar(50)
declare @i int
declare @run int
Select @i=CHARINDEX('.',@NumStr)
if @i=0
begin
set @i=LEN(@NumStr)
Set @Outstr=''
end
else
begin
Set @Outstr=SUBSTRING(@NUmStr,@i,50)
Set @i=@i -1
end
Set @run=0
While @i>0
begin
if @Run=3
begin
Set @Outstr=','+@Outstr
Set @run=0
end
Set @Outstr=SUBSTRING(@NumStr,@i,1) +@Outstr
Set @i=@i-1
Set @run=@run + 1
end
RETURN @OutStr
END
GO
Here's my solution. If your cells will contain only dates or blanks, just compare it to another date. If the cell can be converted to date, it will be counted.
=COUNTIF(C:C,">1/1/1900")
## Counts all the dates in column C
Caution, cells with numbers will be counted.
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
Activities are the full screen components in the app with the toolbar, everything else are preferably Fragments. One full screen parent activity with a toolbar can have multiple panes, scrollable pages, dialogs, etc. (all fragments), all of which can be accessed from the parent and communicate via the parent.
Example:
Activity A, Activity B, Activity C:
vs
Activity A, Fragment 1, Fragment 2, Fragment 3:
You can use the new Bootstrap cards:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
<div class="card">_x000D_
<img class="card-img-top" src="..." alt="Card image cap">_x000D_
<div class="card-block">_x000D_
<h4 class="card-title">Card title</h4>_x000D_
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
</div>_x000D_
<div class="card-footer">_x000D_
<small class="text-muted">Last updated 3 mins ago</small>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Link: Click here
regards,
Make
Make is the program that’s used to install the program that’s compiled from the source code. It’s not the Linux package manager so it doesn’t keep track of the files it installs. This makes it difficult to uninstall the files afterward.
The Make Install command copies the built program and packages into the library directory and specified locations from the makefile. These locations can vary based on the examination that’s performed by the configure script.
CheckInstall
CheckInstall is the program that’s used to install or uninstall programs that are compiled from the source code. It monitors and copies the files that are installed using the make program. It also installs the files using the Linux package manager which allows it to be uninstalled like any regular package.
The CheckInstall command is used to call the Make Install command. It monitors the files that are installed and creates a binary package from them. It also installs the binary package with the Linux package manager.
Replace "source_location.deb" and "name" with your information from the Screenshot.
Execute the following commands in the source package directory:
sudo apt-get install checkinstall
sudo ./configure
sudo make
sudo checkinstall
sudo dpkg --install --force-overwrite source_location.deb
sudo apt remove name
Here's an article article I wrote that covers the whole process with explanations.
The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.
Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.
<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
<div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
<iframe src="otherpage.html" width="400px"></iframe>
</div>
</div>
I answered a very similar question, and here is a way of doing this :
First, create a file where you would define your animations and export them. Just to make it more clear in your app.component.ts
In the following example, I used a max-height of the div that goes from 0px (when it's hidden), to 500px, but you would change that according to what you need.
This animation uses states (in and out), that will be toggle when we click on the button, which will run the animtion.
animations.ts
import { trigger, state, style, transition,
animate, group, query, stagger, keyframes
} from '@angular/animations';
export const SlideInOutAnimation = [
trigger('slideInOut', [
state('in', style({
'max-height': '500px', 'opacity': '1', 'visibility': 'visible'
})),
state('out', style({
'max-height': '0px', 'opacity': '0', 'visibility': 'hidden'
})),
transition('in => out', [group([
animate('400ms ease-in-out', style({
'opacity': '0'
})),
animate('600ms ease-in-out', style({
'max-height': '0px'
})),
animate('700ms ease-in-out', style({
'visibility': 'hidden'
}))
]
)]),
transition('out => in', [group([
animate('1ms ease-in-out', style({
'visibility': 'visible'
})),
animate('600ms ease-in-out', style({
'max-height': '500px'
})),
animate('800ms ease-in-out', style({
'opacity': '1'
}))
]
)])
]),
]
Then in your app.component, we import the animation and create the method that will toggle the animation state.
app.component.ts
import { SlideInOutAnimation } from './animations';
@Component({
...
animations: [SlideInOutAnimation]
})
export class AppComponent {
animationState = 'in';
...
toggleShowDiv(divName: string) {
if (divName === 'divA') {
console.log(this.animationState);
this.animationState = this.animationState === 'out' ? 'in' : 'out';
console.log(this.animationState);
}
}
}
And here is how your app.component.html would look like :
<div class="wrapper">
<button (click)="toggleShowDiv('divA')">TOGGLE DIV</button>
<div [@slideInOut]="animationState" style="height: 100px; background-color: red;">
THIS DIV IS ANIMATED</div>
<div class="content">THIS IS CONTENT DIV</div>
</div>
slideInOut refers to the animation trigger defined in animations.ts
Here is a StackBlitz example I have created : https://angular-muvaqu.stackblitz.io/
Side note : If an error ever occurs and asks you to add BrowserAnimationsModule, just import it in your app.module.ts:
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
imports: [ ..., BrowserAnimationsModule ],
...
})
As an extension to @VinaySajip answer. There are additional nargs
worth mentioning.
parser.add_argument('dir', nargs=1, default=os.getcwd())
N (an integer). N arguments from the command line will be gathered together into a list
parser.add_argument('dir', nargs='*', default=os.getcwd())
'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*'
, but multiple optional arguments with nargs='*'
is possible.
parser.add_argument('dir', nargs='+', default=os.getcwd())
'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.
parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())
argparse.REMAINDER
. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities
If the nargs
keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.
Edit (copied from a comment by @Acumenus) nargs='?'
The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.
If you want to go with the add-open option, here's a command to find which module provides which package ->
java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d
the name of the module will be shown with the @ while the name of the packages without it
NOTE: tested with JDK 11
IMPORTANT: obviously is better than the provider of the package does not do the illegal access
I don't think so. Just use two IFs and GOTO the same label:
IF cond1 GOTO foundit
IF cond2 GOTO foundit
ECHO Didn't found it
GOTO end
:foundit
ECHO Found it!
:end
Hey this is pretty simple to solve this error.Just follow this steps:
First uninstall any existing installation:
pip uninstall scikit-image
or, on conda-based systems:
conda uninstall scikit-image
Now, clone scikit-image on your local computer, and install:
git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .
To update the installation:
git pull # Grab latest source
pip install -e . # Reinstall
For other os and manual process please check this Link.
Actually it depends on your use case.
1) You want to protect your route from unauthorized users
If that is the case you can use the component called <Redirect />
and can implement the following logic:
import React from 'react'
import { Redirect } from 'react-router-dom'
const ProtectedComponent = () => {
if (authFails)
return <Redirect to='/login' />
}
return <div> My Protected Component </div>
}
Keep in mind that if you want <Redirect />
to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.
2) You want to redirect after a certain action (let's say after creating an item)
In that case you can use history:
myFunction() {
addSomeStuff(data).then(() => {
this.props.history.push('/path')
}).catch((error) => {
console.log(error)
})
or
myFunction() {
addSomeStuff()
this.props.history.push('/path')
}
In order to have access to history, you can wrap your component with an HOC called withRouter
. When you wrap your component with it, it passes match
location
and history
props. For more detail please have a look at the official documentation for withRouter.
If your component is a child of a <Route />
component, i.e. if it is something like <Route path='/path' component={myComponent} />
, you don't have to wrap your component with withRouter
, because <Route />
passes match
, location
, and history
to its child.
3) Redirect after clicking some element
There are two options here. You can use history.push()
by passing it to an onClick
event:
<div onClick={this.props.history.push('/path')}> some stuff </div>
or you can use a <Link />
component:
<Link to='/path' > some stuff </Link>
I think the rule of thumb with this case is to try to use <Link />
first, I suppose especially because of performance.
Designing You Model:
Public class ModelName
{
...// Properties
public IEnumerable<SelectListItem> ListName { get; set; }
}
Prepare and bind List to Model in Controller :
public ActionResult Index(ModelName model)
{
var items = // Your List of data
model.ListName = items.Select(x=> new SelectListItem() {
Text = x.prop,
Value = x.prop2
});
}
In You View :
@Html.DropDownListFor(m => Model.prop2,Model.ListName)
You can build DFA using simple modular arithmetics.
We can interpret w
which is a string of k-ary numbers using a following rule
V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])
V[|w|]
is a number that w
is representing. If modify this rule to find w mod N
, the rule becomes this.
V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N
and each V[i]
is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.
See an example.
k = 2, N = 5
| V | (V*2 + 0) mod 5 | (V*2 + 1) mod 5 |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |
k = 3, N = 5
| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |
Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.
i suggest in Javascript:
var item=1387843200000;
var date1=new Date(item);
and then date1 is a Date.
Find element with id in row using jquery
$(document).ready(function () {
$("button").click(function() {
//find content of different elements inside a row.
var nameTxt = $(this).closest('tr').find('.name').text();
var emailTxt = $(this).closest('tr').find('.email').text();
//assign above variables text1,text2 values to other elements.
$("#name").val( nameTxt );
$("#email").val( emailTxt );
});
});
(this answer is not useful, but leaving it here since some of the comments may be)
docker images
will show the 'virtual size', i.e. how much in total including all the lower layers. So some double-counting if you have containers that share the same base image.
The answer depends on what is in your hash. If you have a simple hash a simple
print map { "$_ $h{$_}\n" } keys %h;
or
print "$_ $h{$_}\n" for keys %h;
will do, but if you have a hash that is populated with references you will something that can walk those references and produce a sensible output. This walking of the references is normally called serialization. There are many modules that implement different styles, some of the more popular ones are:
Due to the fact that Data::Dumper
is part of the core Perl library, it is probably the most popular; however, some of the other modules have very good things to offer.
sudo service mysql start
This should serve you just fine. There could be a possibility that you changed some commands that affected the mysql configurations.
Above error is because of the space in between two words.
Eg: Java located in C:\Program Files\Java --> Space in between Program and files would cause the above problem. If you remove the space, it would not show any error.
Here is a check list for you:
1) Is your app published? (Production APK is not required for publishing)
2) Did your alpha/beta testers "Accept invitation" to Google+ community or Google group?
3) Are your alpha/beta testers logged in their Google+ account?
4) Are your alpha/beta testers using your link from Google Play developer console? It has format like this: https://play.google.com/apps/testing/com.yourdomain.package
I use the following:
lastrow = ActiveSheet.Columns("A").Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
It'll find the last row in a specific column. If you want the last used row for any column then:
lastrow = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, LookIn:=xlValues, SearchDirection:=xlPrevious).Row
You need to read the Python Unicode HOWTO. This error is the very first example.
Basically, stop using str
to convert from unicode to encoded text / bytes.
Instead, properly use .encode()
to encode the string:
p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip()
or work entirely in unicode.
By far the easiest way to create DOC files on Linux, using PHP is with the Zend Framework component phpLiveDocx.
From the project web site:
"phpLiveDocx allows developers to generate documents by combining structured data from PHP with a template, created in a word processor. The resulting document can be saved as a PDF, DOCX, DOC or RTF file. The concept is the same as with mail-merge."
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
According to the documentation.
If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.
You can check what all devices are used by tensorflow by -
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Also as suggested in this answer
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.
If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.
pip install tensorflow-gpu
Yes, you can. Based on knowledge from colleagues here and researching on web, here you have the best solution for styling a checkbox without any third-party plugin:
input[type='checkbox']{
width: 14px !important;
height: 14px !important;
margin: 5px;
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance: none;
outline: 1px solid gray;
box-shadow: none;
font-size: 0.8em;
text-align: center;
line-height: 1em;
background: red;
}
input[type='checkbox']:checked:after {
content: '?';
color: white;
}
_x000D_
<input type='checkbox'>
_x000D_
It's fine just to cast your int to Foo:
int i = 1;
Foo f = (Foo)i;
If you try to cast a value that's not defined it will still work. The only harm that may come from this is in how you use the value later on.
If you really want to make sure your value is defined in the enum, you can use Enum.IsDefined:
int i = 1;
if (Enum.IsDefined(typeof(Foo), i))
{
Foo f = (Foo)i;
}
else
{
// Throw exception, etc.
}
However, using IsDefined costs more than just casting. Which you use depends on your implemenation. You might consider restricting user input, or handling a default case when you use the enum.
Also note that you don't have to specify that your enum inherits from int; this is the default behavior.
This also works if you are looping over an object.
unset($object->$key);
No need to use brackets.
To run Selenium WebDriver test cases in Chrome, follow these steps:
First of all, set the property and Chrome driver path:
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver");
Initialize the Chrome Driver's object:
WebDriver driver = new ChromeDriver();
Pass the URL into the get
method of WebDriver:
driver.get("http://www.google.com");
I second Harmen's div suggestion. Alternatively, you can wrap the table in a form, and use javascript to capture the row focus and adjust the form action via javascript before submit.
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
For users that are using VB.Net
Imports System.IO
Imports System.Reflection
Dim reader As StreamReader
Dim ass As Assembly = Assembly.GetExecutingAssembly()
Dim sFileName = "MyApplicationName.JavaScript.js"
Dim reader = New StreamReader(ass.GetManifestResourceStream(sFileName))
Dim sScriptText = reader.ReadToEnd()
reader.Close()
where MyApplicationName
is namespace of my application.
It is not the assembly name.
This name is define in project's properties (Application tab).
If you don't find correct resource name, you can use GetManifestResourceNames()
function
Dim resourceName() As String = ass.GetManifestResourceNames()
or
Dim sName As String
= ass.GetManifestResourceNames()
.Single(Function(x) x.EndsWith("JavaScript.js"))
or
Dim sNameList
= ass.GetManifestResourceNames()
.Where(Function(x As String) x.EndsWith(".js"))
You can do it more simply, guaranteeing that your .gitconfig
is left in a meaningful state:
git push -u hub master
when pushing, or:
git branch -u hub/master
(This will set the remote for the currently checked-out branch to hub/master
)
git branch --set-upstream-to hub/master
(This will set the remote for the branch named branch_name
to hub/master
)
git branch branch_name --set-upstream-to hub/master
v1.7.x
or earlieryou must use --set-upstream
:
git branch --set-upstream master hub/master
Removed below lines in .csproj file
<Import Project="$(SolutionDir)\.nuget\NuGet.targets"
Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer.
Enable NuGet Package Restore to download them. For more information, see
http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')"
Text="$([System.String]::Format('$(ErrorText)',
'$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
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 can use the LocalForward
directive in your host yam
section of ~/.ssh/config
:
LocalForward 5901 computer.myHost.edu:5901
From the manual:
SET NAMES indicates what character set the client will use to send SQL statements to the server.
More elaborately, (and once again, gratuitously lifted from the manual):
SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)
Approach 1
File > Settings... > Build, Execution, Deployment > Build Tools > Maven > Importing > check Import Maven projects automatically
Approach 2
Approach 1
Approach 2
I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet according to their nature and format.
For example, using the Content-type
header value defined in a HTTP response, the browser can open the file with the proper extension/plugin.
Internet Media Type (also Content-type) is the same as a MIME type. MIME types were originally created for emails sent using the SMTP protocol. Nowadays, this standard is used in a lot of other protocols, hence the new naming convention "Internet Media Type".
A MIME type is a string identifier composed of two parts: a type
and a subtype
.
The x-
prefix of a MIME subtype simply means that it's non-standard.
The vnd
prefix means that the MIME value is vendor specific.
I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:
16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.
So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?
That would be very sweet. Sadly, I don't think such a thing exists.
There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.
You can easily do this using node-fetch if you are pulling from http(s) URIs.
From the readme:
fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png')
.then(res => res.buffer())
.then(buffer => console.log)
Try this
rails destroy model Rating
It will remove model, migration, tests and fixtures
string theString = "The String";
int index = theString.NthIndexOf("THEVALUE", 3, true);
NOTE: You must have the Team Agent or Admin role in App Store Connect to perform any of these tasks. If you are not part of a Team in App Store Connect this probably does not affect you.
Sending push notifications to an iOS application requires creating encyption keys. In the past this was a cumbersome process that used SSL keys and certificates. Each SSL certificate was specific to a single iOS application. In 2016 Apple introduced a new authentication key mechanism that is more reliable and easier to use. The new authentication keys are more flexible, simple to maintain and apply to more than on iOS app.
Even though it has been years since authentication keys were introduced not every service supports them. FireBase and Amazon Pinpoint support authentication keys. Amazon SNS, Urban Airship, Twilio, and LeanPlum do not. Many open source software packages do not yet support authentication keys.
To create the required SSL certificate and export it as PEM file containing public and private keys:
If you already have the SSL certificate set up for the app in the Apple Developer Center website you can skip ahead to Convert the certificate to PEM format. Keep in mind that you will run into problems if you do not also have the private key that was generated on the Mac that created the signing request that was uploaded to Apple.
Read on to see how to avoid losing track of that private key.
Xcode does not control certificates or keys for push notifications. To create keys and enable push notifications for an app you must go to the Apple Developer Center website. The Certificates, Identifiers & Profiles section of your account controls App IDs and certificates.
To access certificates and profiles you must either have a paid Apple Developer Program membership or be part of a Team that does.
Apps that use push notifications can not use wildcard App IDs or provisioning profiles. Each app requires you to set up an App ID record in the Apple Developer Center portal to enable push notifications.
Creating SSL certificates for push notifications is a process of several tasks. Each task has several steps. All of these are necessary to export the keys in P12 or PEM format. Review the steps before proceeding.
To create a certificate you will need to make a Certificate Signing Request (CSR) on a Mac and upload it to Apple.
Later if you need to export this certificate as a pkcs12 (aka p12) file you will need to use the keychain from the same Mac. When the signing request is created Keychain Access generates a set of keys in the default keychain. These keys are necessary for working with the certificate Apple will create from the signing request.
It is a good practice to have a separate keychain specifically for credentials used for development. If you do this make sure this keychain is set to be the default before using Certificate Assistant.
When creating the Certificate Signing Request the Certificate Assistant generates two encryption keys in the default keychain. It is important to make the development keychain the default so the keys are in the right keychain.
Creating the signing request generated a pair of keys. Before the signing request is uploaded verify that the development keychain has the keys. Their names will be the same as the Common Name used in the signing request.
Once the Certicate Signing Request is created upload it to the Apple Developer Center. Apple will create the push notification certificate from the signing request.
Your development keychain should now show the push certificate with a private key under My Certificates in Keychain Access:
At this point the development keychain should be backed up. Many teams keep their push certificates on secure USB drives, commit to internal version control or use a backup solution like Time Machine. The development keychain can be shared between different team members because it does not contain any personal code signing credentials.
Keychain files are located in
~/Library/Keychains
.
Some third party push services require certificates in Privacy Enhanced Mail (PEM) format, while others require Public-Key Cryptography Standards #12 (PKCS12 or P12). The certificate downloaded from Apple can be used to export certificates in these formats - but only if you have kept the private key.
You can throw your own custom errors by extending the Exception class.
class CustomException : Exception {
[string] $additionalData
CustomException($Message, $additionalData) : base($Message) {
$this.additionalData = $additionalData
}
}
try {
throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
# NOTE: To access your custom exception you must use $_.Exception
Write-Output $_.Exception.additionalData
# This will produce the error message: Didn't catch it the second time
throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}
As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget
in this way.
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
I then can declare the event as KonvaMouseEvent
in my onclick MouseEventHandler function.
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.
It is the container of the Grid
that is imposing on its width. In this case, that's a ListBoxItem
, which is left-aligned by default. You can set it to stretch as follows:
<ListBox>
<!-- other XAML omitted, you just need to add the following bit -->
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
Take Matt Solnit example, imagine that you define an association between Car and Wheels as LAZY and you need some Wheels fields. This means that after the first select, hibernate is going to do "Select * from Wheels where car_id = :id" FOR EACH Car.
This makes the first select and more 1 select by each N car, that's why it's called n+1 problem.
To avoid this, make the association fetch as eager, so that hibernate loads data with a join.
But attention, if many times you don't access associated Wheels, it's better to keep it LAZY or change fetch type with Criteria.
The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.
Here's a simple example. In both trapz
and simps
, the argument dx=5
indicates that the spacing of the data along the x axis is 5 units.
from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from numpy import trapz
# The y values. A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)
Output:
area = 452.5
area = 460.0
My personal opinion is that you should avoid using JSP/ASP/PHP/etc pages. Instead output to an API similar to SAX (only designed for calling rather than handling). That way there is a single layer that has to create well formed output.
The solution:
$("#element-id").val('the value of the option');
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
If you have access to Underscore.js, you can use the _.values
function like this:
_.values({one : 1, two : 2, three : 3}); // return [1, 2, 3]
The first part consists of creating a new package under java
folder and selecting then dragging all your source files from the old package
to this new package
. After that you need to remane
the package name in android manifest
to the name of the new package.
In step 2, here is what you need to do.You need to change the old package name in applicationId
under the module build.gradle
in your android studio in addition to changing the package name in the manifest
. So in summary, click on build.gradle
which is below the "AndroidManifest.xml" and modify the value of applicationId
to your new package name.
Then, at the very top, under build
. clean
your project, then rebuild
. It should be fine from here.
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
This is what I did to achieve image rendering in DEBUG = False mode in Python 3.6 with Django 1.11
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,{'document_root': settings.MEDIA_ROOT}),
# other paths
]
I would consider using something like https://www.bouncycastle.org/ It is a prebuilt library that allows you to encrypt whatever you like with a number of different Ciphers I understand that you only want to protect from snooping, but if you really want to protect the information, using Base64 won't actually protect you.
We encountered a very similar situation.
Activity 1 (Opening) -> Activity 2 (Preview) -> Activity 3 (Detail)
Incorrect "on back press" Response
I have checked all answers posted above and none of them worked. Java syntax for transition between Activity 2 and Activity 3 was reviewed to be correct.
Fresh from coding on calling out a 3rd party app. by an Activity. We decided to investigate the configuration angle - eventually enabling us to identify the root cause of the problem.
Scope: Configuration of Activity 2 (caller).
Root Cause:
android:launchMode="singleInstance"
Solution:
android:launchMode="singleTask"
Apparently on this "on back press" issue singleInstance considers invoked Activities in one instance with the calling Activity, whereas singleTask will allow for invoked Activities having their own identity enough for the intended on back press to function to work as it should to.
Function LastRow(rng As Range) As Long
Dim iRowN As Long
Dim iRowI As Long
Dim iColN As Integer
Dim iColI As Integer
iRowN = 0
iColN = rng.Columns.count
For iColI = 1 To iColN
iRowI = rng.Columns(iColI).Offset(65536 - rng.Row, 0).End(xlUp).Row
If iRowI > iRowN Then iRowN = iRowI
Next
LastRow = iRowN
End Function
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
This is the perfect code for uploading and displaying image through MySQL database.
<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
if(isset($_POST['submit']))
{
if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
{
echo " error ";
}
else
{
$image = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($image));
saveimage($image);
}
}
function saveimage($image)
{
$dbcon=mysqli_connect('localhost','root','','dbname');
$qry="insert into tablename (name) values ('$image')";
$result=mysqli_query($dbcon,$qry);
if($result)
{
echo " <br/>Image uploaded.";
header('location:urlofpage.php');
}
else
{
echo " error ";
}
}
?>
</body>
</html>
You can use rsplit
string.rsplit('delimeter',1)[1]
To get the string from reverse.
In case the data is not in the same character set you might consider this snippet from http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html
If the column has a nonbinary data type (CHAR, VARCHAR, TEXT), its contents should be encoded in the column character set, not some other character set. If the contents are encoded in a different character set, you can convert the column to use a binary data type first, and then to a nonbinary column with the desired character set.
Here is an example:
ALTER TABLE t1 CHANGE c1 c1 BLOB;
ALTER TABLE t1 CHANGE c1 c1 VARCHAR(100) CHARACTER SET utf8;
Make sure to choose the right collation, or you might get unique key conflicts. e.g. Éleanore and Eleanore might be considered the same in some collations.
Aside:
I had a situation where certain characters "broke" in emails even though they were stored as UTF-8 in the database. If you are sending emails using utf8 data, you might want to also convert your emails to send in UTF8.
In PHPMailer, just update this line: public $CharSet = 'utf-8';
The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)
A & B (A and B are evaluated)
A && B (B is only evaluated if A is true)
You can only delete with your time field, which is a number.
Delete from <measurement> where time=123456
will work. Remember not to give single quotes or double quotes. Its a number.
To solve this problem, simply run:
bundle update
It will update the version of your bundler. Then run:
bundle install
Your problem will get solve. Solution is well explained here.
It's easy way to use .match()
method to string.
var re = /(AND|OR|MAYBE)/;
var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING";
console.log('Do we found something?', Boolean(str.match(re)));
Wish you a nice day, sir!
You can use the following method inside the catch block:
response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")
Notice that you can use any HttpStatus code and a custom message.
Another simple way is to use the pivot
function to format the data as you need first.
df.plot()
does the rest
df = pd.DataFrame([
['red', 0, 0],
['red', 1, 1],
['red', 2, 2],
['red', 3, 3],
['red', 4, 4],
['red', 5, 5],
['red', 6, 6],
['red', 7, 7],
['red', 8, 8],
['red', 9, 9],
['blue', 0, 0],
['blue', 1, 1],
['blue', 2, 4],
['blue', 3, 9],
['blue', 4, 16],
['blue', 5, 25],
['blue', 6, 36],
['blue', 7, 49],
['blue', 8, 64],
['blue', 9, 81],
], columns=['color', 'x', 'y'])
df = df.pivot(index='x', columns='color', values='y')
df.plot()
pivot effectively turns the data into:
You can use a Multiset (from guava). It will give you the count for each object. For example:
Multiset<Character> chars = HashMultiset.create();
for (int i = 0; i < string.length(); i++) {
chars.add(string.charAt(i));
}
Then for each character you can call chars.count('a')
and it returns the number of occurrences
Use the change
events on the inputs to update the component's state and access it in handleLogin
:
handleEmailChange: function(e) {
this.setState({email: e.target.value});
},
handlePasswordChange: function(e) {
this.setState({password: e.target.value});
},
render : function() {
return (
<form>
<input type="text" name="email" placeholder="Email" value={this.state.email} onChange={this.handleEmailChange} />
<input type="password" name="password" placeholder="Password" value={this.state.password} onChange={this.handlePasswordChange}/>
<button type="button" onClick={this.handleLogin}>Login</button>
</form>);
},
handleLogin: function() {
console.log("EMail: " + this.state.email);
console.log("Password: " + this.state.password);
}
Working fiddle.
Also, read the docs, there is a whole section dedicated to form handling: Forms
Previously you could also use React's two-way databinding helper mixin to achieve the same thing, but now it's deprecated in favor of setting the value and change handler (as above):
var ExampleForm = React.createClass({
mixins: [React.addons.LinkedStateMixin],
getInitialState: function() {
return {email: '', password: ''};
},
handleLogin: function() {
console.log("EMail: " + this.state.email);
console.log("Password: " + this.state.password);
},
render: function() {
return (
<form>
<input type="text" valueLink={this.linkState('email')} />
<input type="password" valueLink={this.linkState('password')} />
<button type="button" onClick={this.handleLogin}>Login</button>
</form>
);
}
});
Documentation is here: Two-way Binding Helpers.
If using .NET Core or .NET Standard
use:
Manage NuGet Packages..
instead of:
Add Reference...
You can USE PyPDF2 package
#install pyDF2
pip install PyPDF2
# importing all the required modules
import PyPDF2
# creating an object
file = open('example.pdf', 'rb')
# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)
# print the number of pages in pdf file
print(fileReader.numPages)
Follow this Documentation http://pythonhosted.org/PyPDF2/
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
Try this:
MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;
Add text-align: center;
to the parent tag of <canvas>
. That's it.
Example:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</canvas>
</div>
Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.
Consider this function in action:
Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min
e.g. the value 1.1 truly falls in the left bin:
Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.