Here is the detailed answer to the question:
Pass data into the HTTP header from the Angular side (Please note I am using Angular4.0+ in the application).
There is more than one way we can pass data into the headers. The syntax is different but all means the same.
// Option 1
const httpOptions = {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'ID': emp.UserID,
})
};
// Option 2
let httpHeaders = new HttpHeaders();
httpHeaders = httpHeaders.append('Authorization', 'my-auth-token');
httpHeaders = httpHeaders.append('ID', '001');
httpHeaders.set('Content-Type', 'application/json');
let options = {headers:httpHeaders};
// Option 1
return this.http.post(this.url + 'testMethod', body,httpOptions)
// Option 2
return this.http.post(this.url + 'testMethod', body,options)
In the call you can find the field passed as a header as shown in the image below :
Still, if you are facing the issues like.. (You may need to change the backend/WebAPI side)
Response to preflight request doesn't pass access control check: No ''Access-Control-Allow-Origin'' header is present on the requested resource. Origin ''http://localhost:4200'' is therefore not allowed access
Response for preflight does not have HTTP ok status.
Find my detailed answer at https://stackoverflow.com/a/52620468/3454221
Building on what is mentioned in the comments, the simplest solution would be:
@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {
//whatever
}
class SomeDto {
private List<WhateverBudgerPerDateDTO> budgetPerDate;
//getters setters
}
The solution assumes that the HTTP request you are creating actually has
Content-Type:application/json
instead of text/plain
To do this task download.js library can be used. Here is an example from library docs:
download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");
Simple One-line Solution
As suggested in many of above answers, for example
Simply getting navigation bar height may not be enough. We need to consider whether 1. navigation bar exists, 2. is it on the bottom, or right or left, 3. is app open in multi-window mode.
Fortunately you can easily bypass all the long coding by simply setting android:fitsSystemWindows="true"
in your root layout. Android system will automatically take care of adding necessary padding to the root layout to make sure that the child views don't get into the navigation bar or statusbar regions.
There is a simple one line solution
android:fitsSystemWindows="true"
or programatically
findViewById(R.id.your_root_view).setFitsSystemWindows(true);
you may also get root view by
findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)
For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177
<!--something like this-->
<html>
<body>
<!-- i've used for loop...this pointer takes current element to apply a
particular change on it ...other elements take change by else condition
-->
<div class="classname" onclick="myFunction(this);">first</div>
<div class="classname" onclick="myFunction(this);">second</div>
<script>
function myFunction(p) {
var x = document.getElementsByClassName("classname");
var i;
for (i = 0; i < x.length; i++) {
if(x[i] == p)
{
x[i].style.background="blue";
}
else{
x[i].style.background="red";
}
}
}
</script>
<!--this script will only work for a class with onclick event but if u want
to use all class of same name then u can use querySelectorAll() ...-->
var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}
<!--if u like to divide it on some logic apply it inside this for loop
using your nodelist-->
</body>
</html>
Math.sqrt returns a double so you'll have to cast it to int as well
distance = (int)Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));
like this?
<?php
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];
header('Location: http://linkhere.com/'. $url_endpoint);
?>
This is PKCS#1 format of a private key. Try this code. It doesn't use Bouncy Castle or other third-party crypto providers. Just java.security and sun.security for DER sequece parsing. Also it supports parsing of a private key in PKCS#8 format (PEM file that has a header "-----BEGIN PRIVATE KEY-----").
import sun.security.util.DerInputStream;
import sun.security.util.DerValue;
import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPrivateCrtKeySpec;
import java.util.Base64;
public static PrivateKey pemFileLoadPrivateKeyPkcs1OrPkcs8Encoded(File pemFileName) throws GeneralSecurityException, IOException {
// PKCS#8 format
final String PEM_PRIVATE_START = "-----BEGIN PRIVATE KEY-----";
final String PEM_PRIVATE_END = "-----END PRIVATE KEY-----";
// PKCS#1 format
final String PEM_RSA_PRIVATE_START = "-----BEGIN RSA PRIVATE KEY-----";
final String PEM_RSA_PRIVATE_END = "-----END RSA PRIVATE KEY-----";
Path path = Paths.get(pemFileName.getAbsolutePath());
String privateKeyPem = new String(Files.readAllBytes(path));
if (privateKeyPem.indexOf(PEM_PRIVATE_START) != -1) { // PKCS#8 format
privateKeyPem = privateKeyPem.replace(PEM_PRIVATE_START, "").replace(PEM_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
byte[] pkcs8EncodedKey = Base64.getDecoder().decode(privateKeyPem);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(new PKCS8EncodedKeySpec(pkcs8EncodedKey));
} else if (privateKeyPem.indexOf(PEM_RSA_PRIVATE_START) != -1) { // PKCS#1 format
privateKeyPem = privateKeyPem.replace(PEM_RSA_PRIVATE_START, "").replace(PEM_RSA_PRIVATE_END, "");
privateKeyPem = privateKeyPem.replaceAll("\\s", "");
DerInputStream derReader = new DerInputStream(Base64.getDecoder().decode(privateKeyPem));
DerValue[] seq = derReader.getSequence(0);
if (seq.length < 9) {
throw new GeneralSecurityException("Could not parse a PKCS1 private key.");
}
// skip version seq[0];
BigInteger modulus = seq[1].getBigInteger();
BigInteger publicExp = seq[2].getBigInteger();
BigInteger privateExp = seq[3].getBigInteger();
BigInteger prime1 = seq[4].getBigInteger();
BigInteger prime2 = seq[5].getBigInteger();
BigInteger exp1 = seq[6].getBigInteger();
BigInteger exp2 = seq[7].getBigInteger();
BigInteger crtCoef = seq[8].getBigInteger();
RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(keySpec);
}
throw new GeneralSecurityException("Not supported format of a private key");
}
You will need to set the permissions every time you plug the converter in. I use PuTTY to connect. In order to do so, I have created a little Bash script to sort out the permissions and launch PuTTY:
#!/bin/bash
sudo chmod 666 /dev/ttyUSB0
putty
P.S. I would never recommend that permissions are set to 777.
First, go to the following URL and download the mobile_detect.php file:
http://code.google.com/p/php-mobile-detect/
Insert the following code on your index or home page:
<?php
@include("Mobile_Detect.php");
$detect = new Mobile_Detect();
if ($detect->isMobile() && isset($_COOKIE['mobile']))
{
$detect = "false";
}
elseif ($detect->isMobile())
{
header("Location:http://www.yourmobiledirectory.com");
}
?>
Converting it to integer worked for me:
int(sub_df.iloc[0])
There is another way of doing "random" ordered numbers with LFSR, take a look at:
http://en.wikipedia.org/wiki/Linear_feedback_shift_register
with this technique you can achieve the ordered random number by index and making sure the values are not duplicated.
But these are not TRUE random numbers because the random generation is deterministic.
But depending your case you can use this technique reducing the amount of processing on random number generation when using shuffling.
Here a LFSR algorithm in java, (I took it somewhere I don't remeber):
public final class LFSR {
private static final int M = 15;
// hard-coded for 15-bits
private static final int[] TAPS = {14, 15};
private final boolean[] bits = new boolean[M + 1];
public LFSR() {
this((int)System.currentTimeMillis());
}
public LFSR(int seed) {
for(int i = 0; i < M; i++) {
bits[i] = (((1 << i) & seed) >>> i) == 1;
}
}
/* generate a random int uniformly on the interval [-2^31 + 1, 2^31 - 1] */
public short nextShort() {
//printBits();
// calculate the integer value from the registers
short next = 0;
for(int i = 0; i < M; i++) {
next |= (bits[i] ? 1 : 0) << i;
}
// allow for zero without allowing for -2^31
if (next < 0) next++;
// calculate the last register from all the preceding
bits[M] = false;
for(int i = 0; i < TAPS.length; i++) {
bits[M] ^= bits[M - TAPS[i]];
}
// shift all the registers
for(int i = 0; i < M; i++) {
bits[i] = bits[i + 1];
}
return next;
}
/** returns random double uniformly over [0, 1) */
public double nextDouble() {
return ((nextShort() / (Integer.MAX_VALUE + 1.0)) + 1.0) / 2.0;
}
/** returns random boolean */
public boolean nextBoolean() {
return nextShort() >= 0;
}
public void printBits() {
System.out.print(bits[M] ? 1 : 0);
System.out.print(" -> ");
for(int i = M - 1; i >= 0; i--) {
System.out.print(bits[i] ? 1 : 0);
}
System.out.println();
}
public static void main(String[] args) {
LFSR rng = new LFSR();
Vector<Short> vec = new Vector<Short>();
for(int i = 0; i <= 32766; i++) {
short next = rng.nextShort();
// just testing/asserting to make
// sure the number doesn't repeat on a given list
if (vec.contains(next))
throw new RuntimeException("Index repeat: " + i);
vec.add(next);
System.out.println(next);
}
}
}
Here is a simplified version (the gist) of Mick Cullen's answer -- in part to prove that it needn't be very complex to implement this; in part to give a quick reference for anyone who isn't interested in reading pages and pages of code.
You have to make you app use connect-busboy:
var busboy = require("connect-busboy");
app.use(busboy());
This will not do anything until you trigger it. Within the call that handles uploading, do the following:
app.post("/upload", function(req, res) {
if(req.busboy) {
req.busboy.on("file", function(fieldName, fileStream, fileName, encoding, mimeType) {
//Handle file stream here
});
return req.pipe(req.busboy);
}
//Something went wrong -- busboy was not loaded
});
Let's break this down:
req.busboy
is set (the middleware was loaded correctly)"file"
listener on req.busboy
req
to req.busboy
Inside the file listener there are a couple of interesting things, but what really matters is the fileStream
: this is a Readable, that can then be written to a file, like you usually would.
Pitfall: You must handle this Readable, or express will never respond to the request, see the busboy API (file section).
echo "<span style = 'font-color: #ff0000'> Movie List for {$key} 2013 </span>";
Variables are only expanded inside double quotes, not single quotes. Since the above uses double quotes for the PHP string, I switched to single quotes for the embedded HTML, to avoid having to escape the quotes.
The other problem with your code is that <style>
tags are for entering CSS blocks, not for styling individual elements. To style an element, you need an element tag with a style
attribute; <span>
is the simplest element -- it doesn't have any formatting of its own, it just serves as a place to attach attributes.
Another popular way to write it is with string concatenation:
echo '<span style = "font-color: #ff0000"> Movie List for ' . $key . ' 2013 </span>';
like dwn said, Performance was one of its benefits during the rise of complex processors, MSDN blog Non-classical processor behavior: How doing something can be faster than not doing it gives an example which clearly says the difference between ternary (conditional) operator and if/else statement.
give the following code:
#include <windows.h>
#include <stdlib.h>
#include <stdlib.h>
#include <stdio.h>
int array[10000];
int countthem(int boundary)
{
int count = 0;
for (int i = 0; i < 10000; i++) {
if (array[i] < boundary) count++;
}
return count;
}
int __cdecl wmain(int, wchar_t **)
{
for (int i = 0; i < 10000; i++) array[i] = rand() % 10;
for (int boundary = 0; boundary <= 10; boundary++) {
LARGE_INTEGER liStart, liEnd;
QueryPerformanceCounter(&liStart);
int count = 0;
for (int iterations = 0; iterations < 100; iterations++) {
count += countthem(boundary);
}
QueryPerformanceCounter(&liEnd);
printf("count=%7d, time = %I64d\n",
count, liEnd.QuadPart - liStart.QuadPart);
}
return 0;
}
the cost for different boundary are much different and wierd (see the original material). while if change:
if (array[i] < boundary) count++;
to
count += (array[i] < boundary) ? 1 : 0;
The execution time is now independent of the boundary value, since:
the optimizer was able to remove the branch from the ternary expression.
but on my desktop intel i5 cpu/windows 10/vs2015, my test result is quite different with msdn blog.
when using debug mode, if/else cost:
count= 0, time = 6434
count= 100000, time = 7652
count= 200800, time = 10124
count= 300200, time = 12820
count= 403100, time = 15566
count= 497400, time = 16911
count= 602900, time = 15999
count= 700700, time = 12997
count= 797500, time = 11465
count= 902500, time = 7619
count=1000000, time = 6429
and ternary operator cost:
count= 0, time = 7045
count= 100000, time = 10194
count= 200800, time = 12080
count= 300200, time = 15007
count= 403100, time = 18519
count= 497400, time = 20957
count= 602900, time = 17851
count= 700700, time = 14593
count= 797500, time = 12390
count= 902500, time = 9283
count=1000000, time = 7020
when using release mode, if/else cost:
count= 0, time = 7
count= 100000, time = 9
count= 200800, time = 9
count= 300200, time = 9
count= 403100, time = 9
count= 497400, time = 8
count= 602900, time = 7
count= 700700, time = 7
count= 797500, time = 10
count= 902500, time = 7
count=1000000, time = 7
and ternary operator cost:
count= 0, time = 16
count= 100000, time = 17
count= 200800, time = 18
count= 300200, time = 16
count= 403100, time = 22
count= 497400, time = 16
count= 602900, time = 16
count= 700700, time = 15
count= 797500, time = 15
count= 902500, time = 16
count=1000000, time = 16
the ternary operator is slower than if/else statement on my machine!
so according to different compiler optimization techniques, ternal operator and if/else may behaves much different.
Escape the quotes with backslashes:
printf("She said \"time flies like an arrow, but fruit flies like a banana\".");
There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.
Store it in a cookie that only lasts for the current browsing session
as per @anaximander s answer but your signup action should look more like
[HttpPost]
public ActionResult SignUp(Account account)
{
if(ModelState.IsValid){
//do something with account
return RedirectToAction("Index");
}
return View("SignUp");
}
This works perfect for Python 3.5
, if the URL contains Query String / Parameter value,
Request URL = https://bah2.com/ws/rest/v1/concept/
Parameter value = 21f6bb43-98a1-419d-8f0c-8133669e40ca
import requests
url = 'https://bahbah2.com/ws/rest/v1/concept/21f6bb43-98a1-419d-8f0c-8133669e40ca'
data = {"name": "Value"}
r = requests.post(url, auth=('username', 'password'), verify=False, json=data)
print(r.status_code)
check with either:
ps -edaf | grep mongo | grep -v grep # "ps" flags may differ on your OS
or
/etc/init.d/mongodb status # for MongoDB version < 2.6
/etc/init.d/mongod status # for MongoDB version >= 2.6
or
service mongod status
to see if mongod is running (you need to be root to do this, or prefix everything with sudo
). Please note that the 'grep' command will always also show up as a separate process.
check the log file /var/log/mongo/mongo.log to see if there are any problems reported
You can't do it using environment variables directly. You need to use the set of "non standard" options that are passed to the java command. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)
Some products like Ant or Tomcat might come with a batch script that looks for the JAVA_OPTS environment variable, but it's not part of the Java runtime. If you are using one of those products, you may be able to set the variable like:
set JAVA_OPTS="-Xms128m -Xmx256m"
You can also take this approach with your own command line like:
set JAVA_OPTS="-Xms128m -Xmx256m"
java ${JAVA_OPTS} MyClass
You can’t modify much about the input[type=file]
control itself.
Since clicking a label
element correctly paired with an input will activate/focus it, we can use a label
to trigger the OS browse dialog.
Here is how you can do it…
label {_x000D_
cursor: pointer;_x000D_
/* Style as you please, it will become the visible UI component. */_x000D_
}_x000D_
_x000D_
#upload-photo {_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
z-index: -1;_x000D_
}
_x000D_
<label for="upload-photo">Browse...</label>_x000D_
<input type="file" name="photo" id="upload-photo" />
_x000D_
The CSS for the form control will make it appear invisible and not take up space in the document layout, but will still exist so it can be activated via the label
.
If you want to display the user’s chosen path after selection, you can listen for the change
event with JavaScript and then read the path that the browser makes available to you (for security reasons it can lie to you about the exact path). A way to make it pretty for the end user is to simply use the base name of the path that is returned (so the user simply sees the chosen filename).
There is a great guide by Tympanus for styling this.
Nothing built in, my solution would be as follows :
function tConvert (time) {
// Check correct time format and split into components
time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice (1); // Remove full string match value
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join (''); // return adjusted time or original string
}
tConvert ('18:00:00');
This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.
The return value is the adjusted time if a valid time was presented or the original string.
Working example
(function() {_x000D_
_x000D_
function tConvert(time) {_x000D_
// Check correct time format and split into components_x000D_
time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
_x000D_
if (time.length > 1) { // If time format correct_x000D_
time = time.slice(1); // Remove full string match value_x000D_
time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
}_x000D_
return time.join(''); // return adjusted time or original string_x000D_
}_x000D_
_x000D_
var tel = document.getElementById('tests');_x000D_
_x000D_
tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {_x000D_
return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;_x000D_
}).join('\n');_x000D_
})();
_x000D_
<h3>tConvert tests : </h3>_x000D_
<pre id="tests">_x000D_
18:00:00_x000D_
18:00_x000D_
00:00_x000D_
11:59:01_x000D_
12:00:00_x000D_
13:01:57_x000D_
24:00_x000D_
sdfsdf_x000D_
12:61:54_x000D_
</pre>
_x000D_
What about this:
var txt="";
var nyc = {
fullName: "New York City",
mayor: "Michael Bloomberg",
population: 8000000,
boroughs: 5
};
for (var x in nyc){
txt += nyc[x];
}
As well as adding the MySQL JDBC connector ensure the context.xml (if not unpacked in the Tomcat webapps folder) with your DB connection definitions are included within Tomcats conf directory.
All the answers provide sufficient details to the question. However, let me add something more.
Why are we using these Interfaces:
Which interface does what:
When to use which interface:
According to http://jtuts.com/2014/08/26/difference-between-crudrepository-and-jparepository-in-spring-data-jpa/
Generally the best idea is to use CrudRepository or PagingAndSortingRepository depending on whether you need sorting and paging or not.
The JpaRepository should be avoided if possible, because it ties you repositories to the JPA persistence technology, and in most cases you probably wouldn’t even use the extra methods provided by it.
You can rename your Conda env by just renaming the env folder. Here is the proof:
You can find your Conda env folder inside of C:\ProgramData\Anaconda3\envs
or you can enter conda env list
to see the list of conda envs and its location.
$('#id').find('option:selected').text();
See ?boxplot
for all the help you need.
outline: if ‘outline’ is not true, the outliers are not drawn (as
points whereas S+ uses lines).
boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)
And for extending the range of the whiskers and suppressing the outliers inside this range:
range: this determines how far the plot whiskers extend out from the
box. If ‘range’ is positive, the whiskers extend to the most
extreme data point which is no more than ‘range’ times the
interquartile range from the box. A value of zero causes the
whiskers to extend to the data extremes.
# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)
This question is 2 years old but it's still a good question and it was the first Google result ... but all of the existing answers recommend setting and removing the HTML attribute (removeAttr("disabled")) "disabled", which is not the right approach. There is a lot of confusion regarding attribute vs. property.
The "disabled" in <input type="button" disabled>
in the markup is called a boolean attribute by the W3C.
Quote:
A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.
https://stackoverflow.com/a/7572855/664132
Related:
Nevertheless, the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does. Therefore, the cross-browser-compatible way to determine if a checkbox is checked is to use the property...
Relevant:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
$( "input" ).prop( "disabled", false );
To [...] change DOM properties such as the [...] disabled state of form elements, use the .prop() method.
As for the disable on change part of the question: There is an event called "input", but browser support is limited and it's not a jQuery event, so jQuery won't make it work. The change event works reliably, but is fired when the element loses focus. So one might combine the two (some people also listen for keyup and paste).
Here's an untested piece of code to show what I mean:
$(document).ready(function() {
var $submit = $('input[type="submit"]');
$submit.prop('disabled', true);
$('input[type="text"]').on('input change', function() { //'input change keyup paste'
$submit.prop('disabled', !$(this).val().length);
});
});
This what helped me:
List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);
Taken from Java 8 Finding Specific Element in List with Lambda
Be sure to stringify
before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.
Works:
$.ajax({
url: _saveAllDevicesUrl
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(postData) //stringify is important
, success: _madeSave.bind(this)
});
I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.
One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
See this list of php image libraries. Basically it's GD or Imagemagick.
Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.
If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.
The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.
So the ultimate difference is:
In my case I had the same issue on running from eclipse. Just did the following to resolve it: Right Click the Project --> Mavan --> Update Project.
And it worked!
If you're able to use third-party libraries, You might be able to use something like sarge
(disclosure: I'm its maintainer). This library allows non-blocking access to output streams from subprocesses - it's layered over the subprocess
module.
One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
(do something lengthy)
[mySpinner stopAnimating];
}
will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.
- (void) handleDoSomethingButton{
[mySpinner startAnimating];
dispatch_async (dispatch_get_main_queue(), ^{
(do something lengthy)
[mySpinner stopAnimating];
});
}
will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.
An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.
Not sure I would recommend this for production software but for development it is quick and easy.
In my config/application.yml I have changed this
redis:
url: "redis://redis:6379/0"
to this
redis:
url: "redis://localhost:6379/0"
and it works for me
EDIT 2015-06-27: Minimum is actually 8, including country code. My bad.
Original post
The minimum phone number that I use is 10 digits. International users should always be putting their country code, and as far as I know there are no countries with fewer than ten digits if you count country code.
More info here: https://en.wikipedia.org/wiki/Telephone_numbering_plan
I believe this is the best solution:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
This will update your date by the offset appropriately since it is presented in minutes.
The canvas
DOM element has .height
and .width
properties that correspond to the height="…"
and width="…"
attributes. Set them to numeric values in JavaScript code to resize your canvas. For example:
var canvas = document.getElementsByTagName('canvas')[0];
canvas.width = 800;
canvas.height = 600;
Note that this clears the canvas, though you should follow with ctx.clearRect( 0, 0, ctx.canvas.width, ctx.canvas.height);
to handle those browsers that don't fully clear the canvas. You'll need to redraw of any content you wanted displayed after the size change.
Note further that the height and width are the logical canvas dimensions used for drawing and are different from the style.height
and style.width
CSS attributes. If you don't set the CSS attributes, the intrinsic size of the canvas will be used as its display size; if you do set the CSS attributes, and they differ from the canvas dimensions, your content will be scaled in the browser. For example:
// Make a canvas that has a blurry pixelated zoom-in
// with each canvas pixel drawn showing as roughly 2x2 on screen
canvas.width = 400;
canvas.height = 300;
canvas.style.width = '800px';
canvas.style.height = '600px';
See this live example of a canvas that is zoomed in by 4x.
var c = document.getElementsByTagName('canvas')[0];_x000D_
var ctx = c.getContext('2d');_x000D_
ctx.lineWidth = 1;_x000D_
ctx.strokeStyle = '#f00';_x000D_
ctx.fillStyle = '#eff';_x000D_
_x000D_
ctx.fillRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.fillRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.fillRect( 70, 10, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );_x000D_
_x000D_
ctx.strokeStyle = '#fff';_x000D_
ctx.strokeRect( 10.5, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 40, 10.5, 20, 20 );_x000D_
ctx.strokeRect( 70, 10, 20, 20 );
_x000D_
body { background:#eee; margin:1em; text-align:center }_x000D_
canvas { background:#fff; border:1px solid #ccc; width:400px; height:160px }
_x000D_
<canvas width="100" height="40"></canvas>_x000D_
<p>Showing that re-drawing the same antialiased lines does not obliterate old antialiased lines.</p>
_x000D_
I resolved this error today when it occurred trying to Commit to SVN. The error was genuine, TortoiseSVN could not access a file which I tried to Commit. This file had been saved while running a program "As Administrator" in Windows. This means the file has Administrator access but not access from my account (TortoiseSVN running as interactive user). I took ownership of the nominated file under my windows account and after that Cleanup was able to proceed.
To get the length of a string stored in a variable, say:
myvar="some string"
size=${#myvar}
To confirm it was properly saved, echo
it:
$ echo "$size"
11
The core team responsible for Postgres is gradually phasing out OIDs.
The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:
CREATE TABLE … WITH OIDS
commanddefault_with_oids (boolean)
compatibility settingThe data type OID
remains in Postgres 12. You can explicitly create a column of the type OID
.
After migrating to Postgres 12, any optionally-defined system column oid
will no longer be invisible by default. Performing a SELECT *
will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.
You first need to uninstall the ruby installed by Ubuntu with something like sudo apt-get remove ruby
.
Then reinstall ruby using rbenv and ruby-build according to their docs:
cd $HOME
sudo apt-get update
sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec $SHELL
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
exec $SHELL
rbenv install 2.3.1
rbenv global 2.3.1
ruby -v
The last step is to install Bundler:
gem install bundler
rbenv rehash
Then enjoy!
Derek
NOTE: Pure Swift 3 (Xcode 8) example:
Please try out the following sample code. It is the simple example of dataTask
function of URLSession
.
func simpleDataRequest() {
//Get the url from url string
let url:URL = URL(string: "YOUR URL STRING")!
//Get the session instance
let session = URLSession.shared
//Create Mutable url request
var request = URLRequest(url: url as URL)
//Set the http method type
request.httpMethod = "POST"
//Set the cache policy
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
//Post parameter
let paramString = "key=value"
//Set the post param as the request body
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(data, response, error) in
guard let _:Data = data as Data?, let _:URLResponse = response , error == nil else {
//Oops! Error occured.
print("error")
return
}
//Get the raw response string
let dataString = String(data: data!, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
//Print the response
print(dataString!)
}
//resume the task
task.resume()
}
My pseudocode example will be as follows:
JSONArray jsonArray = "[{id:\"1\", name:\"sql\"},{id:\"2\",name:\"android\"},{id:\"3\",name:\"mvc\"}]";
JSON newJson = new JSON();
for (each json in jsonArray) {
String id = json.get("id");
String name = json.get("name");
newJson.put(id, name);
}
return newJson;
With the help of regular expression also we can achieve.
(/keyword/i).test(source)
/i
is for ignore case. If not necessary we can ignore and test for NOT case sensitive match like
(/keyword/).test(source)
THE SOLUTION :
I created an icon from existing png file by simply changing the extension of the image from png to ico. I use drupal 7 bartik theme, so I uploaded the shortcut icon to the server and it WORKED for Chrome and Firefox but not IE. Also, the image icon was white-blank on the desktop.
Then I took the advice of some guys here and reduced the size of the image to 32x32 pixels using an image editor (gimp 2<<
I uploaded the icon in the same way as earlier, and it worked fine for all browsers.
I love you guys on stackoverflow, you helped me solve LOTS of problems. THANK YOU!
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
Getting overly clever with obscure-er HTTP error codes is a bad idea. Browsers sometimes react in unhelpful ways that obfuscate the situation. Stick with 404.
As per Swift 4.2 (Xcode 10 beta 6) "UIEdgeInsetsInsetRect" being deprecated. I've also declared the class public to make it more useful.
public class UIPaddedLabel: UILabel {
@IBInspectable var topInset: CGFloat = 5.0
@IBInspectable var bottomInset: CGFloat = 5.0
@IBInspectable var leftInset: CGFloat = 7.0
@IBInspectable var rightInset: CGFloat = 7.0
public override func drawText(in rect: CGRect) {
let insets = UIEdgeInsets.init(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
super.drawText(in: rect.inset(by: insets))
}
public override var intrinsicContentSize: CGSize {
let size = super.intrinsicContentSize
return CGSize(width: size.width + leftInset + rightInset,
height: size.height + topInset + bottomInset)
}
public override func sizeToFit() {
super.sizeThatFits(intrinsicContentSize)
}
}
If you want to denote an actual error in your code, you could raise a RuntimeError
exception:
raise RuntimeError, 'Message goes here'
This will print a stacktrace, the type of the exception being raised and the message that you provided. Depending on your users, a stacktrace might be too scary, and the actual message might get lost in the noise. On the other hand, if you die because of an actual error, a stacktrace will give you additional information for debugging.
i don't like the idea of using Reflection for that.
Not only dangerous for missing it in some refactoring, but it can also be denied by SecurityManager
.
FutureTask
is a good option as the other options from the java.util.concurrent package.
My favorite for simple tasks:
Executors.newSingleThreadExecutor().submit(task);
little bit shorter than creating a Thread (task is a Callable or a Runnable)
class list_benefits(object):
def __init__(self):
self.s1 = "More organized code"
self.s2 = "More readable code"
self.s3 = "Easier code reuse"
def build_sentence():
obj=list_benefits()
print obj.s1 + " is a benefit of functions!"
print obj.s2 + " is a benefit of functions!"
print obj.s3 + " is a benefit of functions!"
print build_sentence()
I know it is late answer, maybe some other folk can benefit If you still want to call by "attributes", you could use class with default constructor, and create an instance of the class as mentioned in other answers
Since using the @Value("new Long("myconfig")") with cast could throw error on startup if the config is not found or if not in the same expected number format
We used the following approach and is working as expected with fail safe check.
@Configuration()
public class MyConfiguration {
Long DEFAULT_MAX_IDLE_TIMEOUT = 5l;
@Value("db.timeoutInString")
private String timeout;
public Long getTimout() {
final Long timoutVal = StringUtil.parseLong(timeout);
if (null == timoutVal) {
return DEFAULT_MAX_IDLE_TIMEOUT;
}
return timoutVal;
}
}
Open up the .csproj file for your solution in wordpad or some text editor. Look for the ProjectTypeGuids. They indicate the required supported types for your solutions. Search the internet these GUIDs to find out what they require. For example E53F8FEA-EAE0-44A6-8774-FFD645390401 means it requires "MVC 3.0"
Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).
Instead, I used this method:
Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:
From the docs:
Modals have two optional sizes, available via modifier classes to be placed on a .modal-dialog
: modal-lg
and modal-sm
(as of 3.1).
Also the modal dialogue will scale itself on small screens (as of 3.1.1).
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
A simple readable version is
def find(lst, key, value):
for i, dic in enumerate(lst):
if dic[key] == value:
return i
return -1
Well, it appears that instead of creating a true multidimensional array, you've created an array of (almost) JavaScript Objects. Try defining your arrays like this ->
var array = [ [id,name,value], [id,name,value] ]
Hopefully that helps!
Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);
..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.
Bootstrap has a way of using media queries to define the different task for different sites. It uses four breakpoints.
we have extra small screen sizes which are less than 576 pixels that small in which I mean it's size from 576 to 768 pixels.
medium screen sizes take up screen size from 768 pixels up to 992 pixels large screen size from 992 pixels up to 1200 pixels.
E.g Small Text
This means that at the small screen between 576px and 768px, center the text For medium screen, change "sm" to "md" and same goes to large "lg"
It is a bit late, but you can find it (windows 10 chrome 83)
%USERPROFILE%\AppData\Local\Google\Chrome\User Data\<your profile>\Extensions
Chrome now store it per profile. If you only have one profile, it's in a folder called Default
Here's a C# example I just cooked up, loosely based on the answer using CSS selectors, hopefully of use to others for seeing how to setup a ReadOnlyCollection
of table rows and iterate over it in MS land at least. I'm looking through a collection of table rows to find a row with an OriginatorsRef
(just a string) and a TD
with an image that contains a title attribute with Overdue by
in it:
public ReadOnlyCollection<IWebElement> GetTableRows()
{
this.iwebElement = GetElement();
return this.iwebElement.FindElements(By.CssSelector("tbody tr"));
}
And within my main code:
...
ReadOnlyCollection<IWebElement> TableRows;
TableRows = f.Grid_Fault.GetTableRows();
foreach (IWebElement row in TableRows)
{
if (row.Text.Contains(CustomTestContext.Current.OriginatorsRef) &&
row.FindElements(By.CssSelector("td img[title*='Overdue by']")).Count > 0)
return true;
}
The way that I do this is with GroovyShell
.
GroovyShell shell = new GroovyShell()
def Util = shell.parse(new File('Util.groovy'))
def data = Util.fetchData()
I was getting the same problem using EasyPHP. Found that I had to specify AllowOverride All
in my <Directory>
block in httpd.conf
. Without this, Apache sometimes ignores your .htaccess
.
Mine ended up looking like this...
<Directory "D:/Dev">
Options FollowSymLinks Indexes
#### NEXT IS THE CRUCIAL LINE ####
AllowOverride All
Order deny,allow
Allow from 127.0.0.1
Deny from all
Require all granted
</Directory>
For SAPI: php-fpm
There is no need to create a php.info file (it is not a good policy to leave it for the world to read anyway). On the command line:
php-fpm -i | more
Somewhere in its output, it will show this line:
Configuration File (php.ini) Path => /etc
Here is a more complete explanation: https://www.cloudinsidr.com/content/how-to-figure-out-your-php-configuration-parameters-without-info-php/
Maybe I'm missing something here, but usually calling .SingleOrDefault()
is the way to go to return either the single element in the list, or a default value (null for reference or nullable types) if the list is empty.
It generates an exception if the list contains more than one element.
Use FirstOrDefault()
to cover the case where you could have more than one.
Additionally,
ggplot(dat, aes(x,y)) +
geom_point() +
scale_x_continuous(breaks = seq(min(dat$x), max(dat$x), by = 0.05))
Works for binned or discrete scaled x-axis data (I.e., rounding not necessary).
I was facing same problem but accidentlty I sorted this problem. 1) Login in github 2) Click on Fork Button at Top Right. 3) After above step you can see Clone or download in Green color under <> Code Tab.
There are many very feature rich and ingenious answers already. To provide some contrast, I could make do with a very simple line.
# Check return value to see if there are incoming updates.
if ! git diff --quiet remotes/origin/HEAD; then
# pull or whatever you want to do
fi
Here's how to setup a scrollview using Xcode 11
1 - Add scrollview and set top,bottom,leading and trailing constraints
2 - Add a Content View to the scrollview, drag a connection to the Content Layout Guide and select Leading, Top, Bottom and Trailing. Make sure to set its' values to 0 or the constants you want.
3 - Drag from the Content View to the Frame Layout Guide and select Equal Widths
4 - Set a height constraint constant to the Content View
The following example works on both ssl and non-ssl and is much faster as you use just one rule to manage http and https
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|offs()
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R]
[Tested]
This will redirect
http
to
https
to
<?php echo 'apple'; ?>
is pretty much literally all you need on the server.
as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have
success: function(data) {
alert(data); // apple
}
I had a similar issue, no videos would play in Chrome. Tried installing beta 64bit, going back to Chrome 32bit release.
The only thing that worked for me was updating my video drivers.
I have the NVIDIA GTS 240. Downloaded, installed the drivers and restarted and Chrome 38.0.2125.77 beta-m (64-bit) starting playing HTML5 videos again on youtube, vimeo and others. Hope this helps anyone else.
In Bootstrap 4, there are already separated files in their GitHub. You can find them here
https://github.com/twbs/bootstrap/tree/main/dist/css
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
I think this will help : In Controller get the list items and selected value
public ActionResult Edit(int id)
{
ItemsStore item = itemStoreRepository.FindById(id);
ViewBag.CategoryId = new SelectList(categoryRepository.Query().Get(),
"Id", "Name",item.CategoryId);
// ViewBag to pass values to View and SelectList
//(get list of items,valuefield,textfield,selectedValue)
return View(item);
}
and in View
@Html.DropDownList("CategoryId",String.Empty)
As noted in the answer provided by Tim Cooper, java.awt.Desktop
has provided this capability since Java version 6 (1.6), but with the following caveat:
For platforms which do not support or provide java.awt.Desktop
, look into the BrowserLauncher2 project. It is derived and somewhat updated from the BrowserLauncher class originally written and released by Eric Albert. I used the original BrowserLauncher class successfully in a multi-platform Java application which ran locally with a web browser interface in the early 2000s.
Note that BrowserLauncher2 is licensed under the GNU Lesser General Public License. If that license is unacceptable, look for a copy of the original BrowserLauncher which has a very liberal license:
This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be redistributed or modified in any form without restrictions as long as the portion of this comment from this paragraph through the end of the comment is not removed. The author requests that he be notified of any application, applet, or other binary that makes use of this code, but that's more out of curiosity than anything and is not required. This software includes no warranty. The author is not repsonsible for any loss of data or functionality or any adverse or unexpected effects of using this software.
Credits: Steven Spencer, JavaWorld magazine (Java Tip 66) Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
Projects other than BrowserLauncher2 may have also updated the original BrowserLauncher to account for changes in browser and default system security settings since 2001.
Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections
Example:
String foo;
...
if( StringUtils.isBlank( foo ) ) {
///do something
}
or (depending on what you need to check):
String foo;
...
if( StringUtils.isEmpty( foo ) ) {
///do something
}
The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.
Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)
public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
return read(new StringReader(xml), true, validationEventHandler);
}
And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)
Example on how to use this static classf from spring(org.springframework.util.Assert)
Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
Pretty old question so I figured I'll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important
.
Taking the OP's example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here's a working example https://codepen.io/ybentz/pen/RwPoeqb
A POD (plain old data) object has one of these data types--a fundamental type, pointer, union, struct, array, or class--with no constructor. Conversely, a non-POD object is one for which a constructor exists. A POD object begins its lifetime when it obtains storage with the proper size for its type and its lifetime ends when the storage for the object is either reused or deallocated.
PlainOldData types also must not have any of:
A looser definition of PlainOldData includes objects with constructors; but excludes those with virtual anything. The important issue with PlainOldData types is that they are non-polymorphic. Inheritance can be done with POD types, however it should only be done for ImplementationInheritance (code reuse) and not polymorphism/subtyping.
A common (though not strictly correct) definition is that a PlainOldData type is anything that doesn't have a VeeTable.
Use this CSS hack, it saved me lot of trouble and time.
I use it in every project.
While some of these solutions may work, none of them follow best practices. Many assign global variables and you may find yourself making calls to multiple parent variables or functions, leading to a cluttered, vulnerable namespace.
To avoid this, use a module pattern. In the parent window:
var myThing = {
var i = 0;
myFunction : function () {
// do something
}
};
var newThing = Object.create(myThing);
Then, in the iframe:
function myIframeFunction () {
parent.myThing.myFunction();
alert(parent.myThing.i);
};
This is similar to patterns described in the Inheritance chapter of Crockford's seminal text, "Javascript: The Good Parts." You can also learn more at w3's page for Javascript's best practices. https://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals
Hope it helps .
A slight modification to one of the previous ip route ...
solutions, which eliminates the need for a grep:
ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'
In my similar case, I had my own validation logic and just wanted to use jQuery validation to show the message. This was what I did.
//1) Enable jQuery validation_x000D_
var validator = $('#myForm').validate();_x000D_
_x000D_
$('#myButton').click(function(){_x000D_
//my own validation logic here_x000D_
//....._x000D_
//2) when validation failed, show the error message manually_x000D_
validator.showErrors({_x000D_
'myField': 'my custom error message'_x000D_
});_x000D_
});
_x000D_
Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).
I frequently write code like this:
Sub arrayBuilder()
myarray = Range("A1:D4")
'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned
For i = 1 To UBound(myarray)
For j = 1 To UBound(myarray, 2)
Debug.Print (myarray(i, j))
Next j
Next i
End Sub
Assigning ranges to variables is a very powerful way to manipulate data in VBA.
public class Organization {
@Id
@Column(name="org_id")
@GeneratedValue
private int id;
@Column(name="org_name")
private String name;
@Column(name="org_office_address1")
private String address1;
@Column(name="org_office_addres2")
private String address2;
@Column(name="city")
private String city;
@Column(name="state")
private String state;
@Column(name="country")
private String country;
@JsonIgnore
@OneToOne
@JoinColumn(name="pkg_id")
private int pkgId;
public int getPkgId() {
return pkgId;
}
public void setPkgId(int pkgId) {
this.pkgId = pkgId;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="pincode")
private String pincode;
@OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);
@Column(name="status")
private String status = "ACTIVE";
@Column(name="project_id")
private int redmineProjectId;
public int getRedmineProjectId() {
return redmineProjectId;
}
public void setRedmineProjectId(int redmineProjectId) {
this.redmineProjectId = redmineProjectId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Set<OrganizationBranch> getOrganizationBranch() {
return organizationBranch;
}
public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
this.organizationBranch = organizationBranch;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired
Give your anonymous function a name, then:
$(window).on("resize", doResize);
There is now (AutoMapper 2.0) an IgnoreMap
attribute, which I'm going to use rather than the fluent syntax which is a bit heavy IMHO.
Another way :
change BOT_USER_NAME before use
https://telegram.me/BOT_USER_NAME?startgroup=true
You should use string equals to compare two strings for equality, not operator == which just compares the references.
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
A HashMap
is to add, get, remove, ... objects indexed by a custom key of any type.
A HashSet
is to add elements, remove elements and check if elements are present by comparing their hashes.
So a HashMap contains the elements and a HashSet remembers their hashes.
You can simply try.
git reset --soft HEAD~1
and create a new commit.
However, there is an awesome software "gitkraken". which makes it easy to work with git.
For Microsoft SQL Server or PostgreSQL you may want to try this syntax
SELECT constants FROM (VALUES ('[email protected]'), ('[email protected]'), ('[email protected]')) AS MyTable(constants)
You can also view an SQL Fiddle here: http://www.sqlfiddle.com/#!17/9eecb/34703/0
sass --watch a.scss:a.css --style compressed
Consult the documentation for updates:
Thx Burhan Khalid, I overlooked your "You need to be root" quote, but found the way when you are not the root here.
At point 7 you need to use:
sudo env ORACLE_HOME=$ORACLE_HOME python setup.py install
Or
sudo env ORACLE_HOME=/path/to/instantclient python setup.py install
var link = $("#me").closest(":has(h3 span b)").find('h3 span b');
Example: http://jsfiddle.net/e27r8/
This uses the closest()
[docs] method to get the first ancestor that has a nested h3 span b
, then does a .find()
.
Of course you could have multiple matches.
Otherwise, you're looking at doing a more direct traversal.
var link = $("#me").closest("h3 + div").prev().find('span b');
edit: This one works with your updated HTML.
Example: http://jsfiddle.net/e27r8/2/
EDIT: Updated to deal with updated question.
var link = $("#me").closest("h3 + *").prev().find('span b');
This makes the targeted element for .closest()
generic, so that even if there is no parent, it will still work.
Example: http://jsfiddle.net/e27r8/4/
Assuming Python 3 (in Python 2, this difference is a little less well-defined) - a string is a sequence of characters, ie unicode codepoints; these are an abstract concept, and can't be directly stored on disk. A byte string is a sequence of, unsurprisingly, bytes - things that can be stored on disk. The mapping between them is an encoding - there are quite a lot of these (and infinitely many are possible) - and you need to know which applies in the particular case in order to do the conversion, since a different encoding may map the same bytes to a different string:
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-16')
'?????'
>>> b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'.decode('utf-8')
'to??o?'
Once you know which one to use, you can use the .decode()
method of the byte string to get the right character string from it as above. For completeness, the .encode()
method of a character string goes the opposite way:
>>> 'to??o?'.encode('utf-8')
b'\xcf\x84o\xcf\x81\xce\xbdo\xcf\x82'
When you install third-party extensions you need to make sure that all the compilation parameters match:
Common glitches includes:
php.ini
file (that's typical with bundles); the right path is shown in phpinfo()
.Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:
php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
If everything's right you should see sqlsrv
in the command output and/or phpinfo()
(depending on what SAPI you're configuring):
[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]
The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.
One possibility could be to use the 'pageshow' -event instead, as described in:
Try manually:
$ ftp www.domainhere.com
> useridhere
> passwordhere
> put test.txt
> bye
> pause
Because of the GDPR it makes no sense to use the iframe, you should rather use the object tag with the embed tag and also use the embed link.
<object width="100%" height="333">
<param name="movie" value="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw">
<embed src="https://www.youtube-nocookie.com/embed/Sdg0ef2PpBw" width="100%" height="333">
</object>
_x000D_
You should also activate the extended data protection mode function to receive the no cookie url.
type="application/x-shockwave-flash"
flash does not have to be used
Nocookie, however, means that data is still being transmitted, namely the thumbnail that is loaded from YouTube. But at least data is no longer passed on to advertising networks (as example DoubleClick). And no user data is stored on your website by youtube.
Use NUMPAD 7 and NUMPAD 9. It will help you.
Try this first, you may be passing a Null Model:
@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
<label for="Image">Change picture</label>
}
else
{
<label for="Image">Add picture</label>
}
Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.
<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>
Check out Pathname and in particular Pathname#exist?
.
File and its FileTest module are perhaps simpler/more direct, but I find Pathname
a nicer interface in general.
Just use Spring type ClassPathResource.
File file = new ClassPathResource("countries.xml").getFile();
As long as this file is somewhere on classpath Spring will find it. This can be src/main/resources
during development and testing. In production, it can be current running directory.
EDIT: This approach doesn't work if file is in fat JAR. In such case you need to use:
InputStream is = new ClassPathResource("countries.xml").getInputStream();
We can use map
function
print map(str, EmployeeList)
Just pass it in, like this:
Game(list_a, list_b, Rule1)
and then your Game function could look something like this (still pseudocode):
def Game(listA, listB, rules=None):
if rules:
# do something useful
# ...
result = rules(variable) # this is how you can call your rule
else:
# do something useful without rules
First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.
If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
'do something
End If
End If
import java.util.Scanner;
class Test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int num=sc.nextInt();
System.out.println("Enter a number (-1 to end):"+num);
int result=0;
int i=0;
while(true)
{
int n=num%10;
if(n==-1){
break;
}
i++;
System.out.println("Digit"+i+" = "+n);
result=result*10+n;
num=num/10;
if(num==0)
{
break;
}
}
}
}
Assuming you're referring to this plugin, your code should be:
// To Store
$(function() {
$.session.set("myVar", "value");
});
// To Read
$(function() {
alert($.session.get("myVar"));
});
Before using a plugin, remember to read its documentation in order to learn how to use it. In this case, an usage example can be found in the README.markdown
file, which is displayed on the project page.
You can use the command find
to do this. We can match files with -type f
, and match empty files using -size 0
. Then we can delete the matches with -delete
.
find . -type f -size 0 -delete
It's in the python docs.
import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1),
datetime.time(10, 23))
returns
datetime.datetime(2011, 1, 1, 10, 23)
pygame
is not distributed via pip
. See this link which provides windows binaries ready for installation.
Finally, use these commands to install pygame wheel with pip
Python 2 (usually called pip)
pip install file.whl
Python 3 (usually called pip3)
pip3 install file.whl
Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit
If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:
myTimer.Elapsed += PlayMusicEvent;
where
public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
music.player.Stop();
System.Timers.Timer myTimer = (System.Timers.Timer)sender;
myTimer.Stop();
}
But you need to think about where to store your note.
How about rev(x)[1:5]
?
x<-1:10
system.time(replicate(10e6,tail(x,5)))
user system elapsed
138.85 0.26 139.28
system.time(replicate(10e6,rev(x)[1:5]))
user system elapsed
61.97 0.25 62.23
FYI, the list of operators (containing like and all others) is in code:
/vendor/laravel/framework/src/Illuminate/Database/Query/Builder.php
protected $operators = array(
'=', '<', '>', '<=', '>=', '<>', '!=',
'like', 'not like', 'between', 'ilike',
'&', '|', '^', '<<', '>>',
'rlike', 'regexp', 'not regexp',
);
disclaimer:
Joel Larson's answer is correct. Got my upvote.
I'm hoping this answer sheds more light on what's available via the Eloquent ORM (points people in the right direct). Whilst a link to documentation would be far better, that link has proven itself elusive.
It is reasonable to expect that you cannot do any better than O(N log N) in running time.
However, the interesting part is to investigate whether you can sort it in-place, stably, its worst-case behavior and so on.
Simon Tatham, of Putty fame, explains how to sort a linked list with merge sort. He concludes with the following comments:
Like any self-respecting sort algorithm, this has running time O(N log N). Because this is Mergesort, the worst-case running time is still O(N log N); there are no pathological cases.
Auxiliary storage requirement is small and constant (i.e. a few variables within the sorting routine). Thanks to the inherently different behaviour of linked lists from arrays, this Mergesort implementation avoids the O(N) auxiliary storage cost normally associated with the algorithm.
There is also an example implementation in C that work for both singly and doubly linked lists.
As @Jørgen Fogh mentions below, big-O notation may hide some constant factors that can cause one algorithm to perform better because of memory locality, because of a low number of items, etc.
For larger s&r tasks it's better and faster to use grep and xargs, so, for example;
grep -rl 'apples' /dir_to_search_under | xargs sed -i 's/apples/oranges/g'
Others are correct in saying that setting button.enabled = false
doesn't prevent the button from triggering. However, I found that setting button.visible = false
does work. The button disappears and can't be clicked until you set visible
to true
again.
For Angular 4
Url:
http://example.com/company/100
Router Path :
const routes: Routes = [
{ path: 'company/:companyId', component: CompanyDetailsComponent},
]
Component:
@Component({
selector: 'company-details',
templateUrl: './company.details.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
companyId: string;
constructor(private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.companyId = params.companyId;
console.log('companyId :'+this.companyId);
});
}
}
Console Output:
companyId : 100
It may be the case that you have some ambiguity in your ViewData:
Take a look Here
SELECT count(*) FROM information_schema.`COLUMNS` C
WHERE table_name = 'your_table_name'
AND TABLE_SCHEMA = "your_db_name"
I think you want this syntax:
ALTER TABLE tb_TableName
add constraint cnt_Record_Status Default '' for Record_Status
Based on some of your comments, I am going to guess that you might already have null
values in your table which is causing the alter of the column to not null
to fail. If that is the case, then you should run an UPDATE
first. Your script will be:
update tb_TableName
set Record_Status = ''
where Record_Status is null
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL
ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status
Besides the solution of using an additional list and calling addAll to insert the new items after the iteration (as e.g. the solution by user Nat), you can also use concurrent collections like the CopyOnWriteArrayList.
The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException.
With this special collection (usually used for concurrent access) it is possible to manipulate the underlying list while iterating over it. However, the iterator will not reflect the changes.
Is this better than the other solution? Probably not, I don't know the overhead introduced by the Copy-On-Write approach.
From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.
I figured out such data design:
Main sheet: Column A: Pump codes (numbers)
Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'
=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)
Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.
Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B
=INDIRECT("Ruhrpumpen!A"&$B2)
Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:
=INDIRECT("Ruhrpumpen!B"&$B2)
Sheet 'Ruhrpumpen':
Column A: some data about a certain pump
Column B: some more data
Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.
Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls
There is one more way to solve this problem. 1)Go to Project Explorer. Go to the target folder of your project, right-click and delete the target folder. 2)Right-click on your project, select run as Maven Build. 3)After you get Build Success on the console; right click on the project folder and select refresh. After performing the above steps, try to run your project.Your problem should be solved now.
Function firstBlankRow() As Long
Dim emptyCells As Boolean
For Each rowinC In Sheet7.Range("A" & currentEmptyRow & ":A5000") ' (row,col)
If rowinC.Value = "" Then
currentEmptyRow = rowinC.row
'firstBlankRow = rowinC.row 'define class variable to simplify computing complexity for other functions i.e. no need to call function again
Exit Function
End If
Next
End Function
Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.
I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.
here is a copy of the script I made for your solution but have dos2unix installed.
#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"
this script has been tested on 3 machines with no errors.
By using the _MSC_VER
macro.
You can split and convert like
var strVale = "130,235,342,124 ";
var intValArray=strVale.split(',');
for(var i=0;i<intValArray.length;i++{
intValArray[i]=parseInt(intValArray[i]);
}
Now you can use intValArray in you logic.
When autocomplete changes a value, it fires a autocompletechange event, not the change event
$(document).ready(function () {
$('#tags').on('autocompletechange change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
});
Demo: Fiddle
Another solution is to use select event, because the change event is triggered only when the input is blurred
$(document).ready(function () {
$('#tags').on('change', function () {
$('#tagsname').html('You selected: ' + this.value);
}).change();
$('#tags').on('autocompleteselect', function (e, ui) {
$('#tagsname').html('You selected: ' + ui.item.value);
});
});
Demo: Fiddle
datetime.now()
is being evaluated once, when your class is instantiated. Try removing the parenthesis so that the function datetime.now
is returned and THEN evaluated. I had the same issue with setting default values for my DateTimeField
s and wrote up my solution here.
Windows
1- Find: CTRL + F
2- Select-in: Alt + Enter
Now you can change all the selection in one shot like "seen-on-tv" ST homepage Spot.
Credit goes to : https://superuser.com/a/921806/342825
Vectors and matrices can only be of a single type and cbind
and rbind
on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.
(Note that in your rbind
example, the promotion happens within the c
call:
> c(10, "[]", "[[1,2]]")
[1] "10" "[]" "[[1,2]]"
If you want a rectangular structure where the columns can be different types, you want a data.frame
. Any of the following should get you what you want:
> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
v1 v2 v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ v1: num 10 20
$ v2: Factor w/ 1 level "[]": 1 1
$ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using specifically the data.frame
version of cbind
)
> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c(10, 20) : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
or (using cbind
, but making the first a data.frame
so that it combines as data.frames do):
> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame': 2 obs. of 3 variables:
$ c.10..20. : num 10 20
$ c("[]", "[]") : Factor w/ 1 level "[]": 1 1
$ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2
I am not sure you can dynamically change profiles.
Why not just have an internal properties file with the spring.config.location property set to your desired outside location, and the properties file at that location (outside the jar) have the spring.profiles.active property set?
Better yet, have an internal properties file, specific to dev profile (has spring.profiles.active=dev) and leave it like that, and when you want to deploy in production, specify a new location for your properties file, which has spring.profiles.active=prod:
java -jar myjar.jar --spring.config.location=D:\wherever\application.properties
//for closeing the popover when user click outside it will close all popover
var hidePopover = function(element) {
var elementScope = angular.element($(element).siblings('.popover')).scope().$parent;
elementScope.isOpen = false;
elementScope.$apply();
//Remove the popover element from the DOM
$(element).siblings('.popover').remove();
};
$(document).ready(function(){
$('body').on('click', function (e) {
$("a").each(function () {
//Only do this for all popovers other than the current one that cause this event
if (!($(this).is(e.target) || $(this).has(e.target).length > 0)
&& $(this).siblings('.popover').length !== 0 && $(this).siblings('.popover').has(e.target).length === 0)
{
hidePopover(this);
}
});
});
});
Your server is imposing some resource limit that your site is hitting. This is usually RAM, CPU, or INODES.
Ask your server administrator what the limits are and what it is you are hitting to solve.
For fine tuning the position of an inline-block
item, use top and left:
position: relative;
top: 5px;
left: 5px;
Thanks CSS-Tricks!
For iOS 7 I use this,
-(void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
header.textLabel.font = [UIFont boldSystemFontOfSize:10.0f];
header.textLabel.textColor = [UIColor orangeColor];
}
Here is Swift 3.0 version with header resizing
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel!.font = UIFont.systemFont(ofSize: 24.0)
header.textLabel!.textColor = UIColor.orange
}
}
The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern
df[0::len(df)-1 if len(df) > 1 else 1]
works even for single row-dataframes.
Example: For the following dataframe this will not create a duplicate:
df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1 else 1]
print df2
a b
0 1 a
whereas this does:
df3 = df.iloc[[0, -1]]
print df3
a b
0 1 a
0 1 a
because the single row is the first AND last row at the same time.
You can't (and shouldn't) block processing with a sleep function. However, you can use setTimeout
to kick off a function after a delay:
setTimeout(function(){alert("hi")}, 1000);
Depending on your needs, setInterval
might be useful, too.
The best way is to use layers insted of views:
AVPlayer *player = [AVPlayer playerWithURL:[NSURL url...]]; //
AVPlayerLayer *layer = [AVPlayerLayer layer];
[layer setPlayer:player];
[layer setFrame:CGRectMake(10, 10, 300, 200)];
[layer setBackgroundColor:[UIColor redColor].CGColor];
[layer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
[self.view.layer addSublayer:layer];
[player play];
Don't forget to add frameworks:
#import <QuartzCore/QuartzCore.h>
#import "AVFoundation/AVFoundation.h"
Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )
"
"1" is a non-null expression so it's the same as COUNT(*)
.
The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK)
= COUNT(*)
This is a similar myth to EXISTS (SELECT * ...
or EXISTS (SELECT 1 ...
And see the ANSI 92 spec, section 6.5, General Rules, case 1
a) If COUNT(*) is specified, then the result is the cardinality
of T.
b) Otherwise, let TX be the single-column table that is the
result of applying the <value expression> to each row of T
and eliminating null values. If one or more null values are
eliminated, then a completion condition is raised: warning-
null value eliminated in set function.
-z
string is null, that is, has zero length
String='' # Zero-length ("null") string variable.
if [ -z "$String" ]
then
echo "\$String is null."
else
echo "\$String is NOT null."
fi # $String is null.
The t
indicates text mode, meaning that \n
characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.
Other than U
, those mode flags come directly from the standard C library's fopen()
function, a fact that is documented in the sixth paragraph of the python2 documentation for open()
.
As far as I know, t
is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.
I had to run Xcode.app and agree to the License Agreement
Setup: Brand new MacBook with Mavericks, then brew install and other c/l type things 'just work'.
Why not simply this?
resultString = Regex.Replace(subjectString, @"\\", "");
For databases:
SHOW CREATE DATABASE "DB_NAME_HERE";
In creating a Database (MySQL), default character set/collation is always LATIN, instead that you have selected a different one on initially creating your database
On windows, you will need to install drivers for the device for adb to recognize it. To see if the drivers are installed, check the device manager. If there is any "unrecognized device" in the device manager, the drivers are not installed. You can usually get the adb drivers from the manufacturers.
Try out below code snippet:
var list = [];
var text;
function update() {
console.log(list);
for (var i = 0; i < list.length; i++) {
console.log( i );
var letters;
var ul = document.getElementById("list");
var li = document.createElement("li");
li.appendChild(document.createTextNode(list[i]));
ul.appendChild(li);
letters += "<li>" + list[i] + "</li>";
}
document.getElementById("list").innerHTML = letters;
}
function myFunction() {
text = prompt("enter TODO");
list.push(text);
update();
}
All of the listed solutions give a mediocre user experience or cause issues if you want to re-enable the datepicker with it's settings in-tact. I used a method similar to making a select read-only, which is to disable it but add a hidden field with the same name. Check it:
Usage:
$("#datepicker").readonlyDatepicker(true); //makes the datepicker readonly
$("#datepicker").readonlyDatepicker(false); //makes the datepicker editable again
jQuery function:
$.fn.readonlyDatepicker = function (makeReadonly) {
$(this).each(function(){
//find corresponding hidden field
var name = $(this).attr('name');
var $hidden = $('input[name="' + name + '"][type="hidden"]');
//if it doesn't exist, create it
if ($hidden.length === 0){
$hidden = $('<input type="hidden" name="' + name + '"/>');
$hidden.insertAfter($(this));
}
if (makeReadonly){
$hidden.val($(this).val());
$(this).unbind('change.readonly');
$(this).attr('disabled', true);
}
else{
$(this).bind('change.readonly', function(){
$hidden.val($(this).val());
});
$(this).attr('disabled', false);
}
});
};
String.prototype.padZero= function(len, c){
var s= this, c= c || '0';
while(s.length< len) s= c+ s;
return s;
}
dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.
Assuming your "states" collection is like:
{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }
The query to find states with null cities would be:
db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});
It is a common mistake to query for nulls as:
db.states.find({"cities.name" : null});
because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.
It seems that you need to define formats for both date and time part or use String-based formatting. For example:
Gson gson = new GsonBuilder()
.setDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").create();
Gson gson = new GsonBuilder()
.setDateFormat(DateFormat.FULL, DateFormat.FULL).create();
or do it with serializers:
I believe that formatters cannot produce timestamps, but this serializer/deserializer-pair seems to work
JsonSerializer<Date> ser = new JsonSerializer<Date>() {
@Override
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext
context) {
return src == null ? null : new JsonPrimitive(src.getTime());
}
};
JsonDeserializer<Date> deser = new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return json == null ? null : new Date(json.getAsLong());
}
};
Gson gson = new GsonBuilder()
.registerTypeAdapter(Date.class, ser)
.registerTypeAdapter(Date.class, deser).create();
If using Java 8 or above you should use the above serializers/deserializers like so:
JsonSerializer<Date> ser = (src, typeOfSrc, context) -> src == null ? null
: new JsonPrimitive(src.getTime());
JsonDeserializer<Date> deser = (jSon, typeOfT, context) -> jSon == null ? null : new Date(jSon.getAsLong());
I have a hack that I think uses very little code and is quite reliable.
Put your site's files in a subdirectory. SSL into your server and create symlinks to that subdirectory where your files are stored that indicate your languages.
Something like this:
ln -s /var/www/yourhtml /var/www/en
ln -s /var/www/yourhtml /var/www/sp
ln -s /var/www/yourhtml /var/www/it
Use your web server to read HTTP_ACCEPT_LANGUAGE and redirect to these "different subdirectories" according to the language value it provides.
Now you can use Javascript's window.location.href to get your url and use it in conditionals to reliably identify the preferred language.
url_string = window.location.href;
if (url_string = "http://yoursite.com/it/index.html") {
document.getElementById("page-wrapper").className = "italian";
}
std::copy (b.begin(), b.end(), std::back_inserter(a));
This can be used in case the items in vector a have no assignment operator (e.g. const member).
In all other cases this solution is ineffiecent compared to the above insert solution.
Not sure why the question was down-voted, but I had the same issue and following the blog post recommended solve the issue. One thing I should add is that in my case, once I ran:
npm config set prefix /usr/local
I confirmed the npm root -g
was pointing to /usr/local/lib/node_modules/npm
, but in order to install gulp
in /usr/local/lib/node_modules
, I had to use sudo
:
sudo npm install gulp -g
I'm a relative novice compared to all the experts on Stack Overflow.
I have 2 versions of jupyter notebook running (one through a fresh Anaconda Navigator installation and one through ????). I think this is because Anaconda was installed as a local installation on my Mac (per Anaconda instructions).
I already had python 3.7 installed. After that, I used my terminal to open jupyter notebook and I think that it put another version globally onto my Mac.
However, I'm not sure because I'm just learning through trial and error!
I did the terminal command:
conda install -c anaconda certifi
(as directed above, but it didn't work.)
My python 3.7 is installed on OS Catalina10.15.3 in:
The certificate is at:
I tried to find the Install Certificate.command ... but couldn't find it through looking through the file structures...not in Applications...not in links above.
I finally installed it by finding it through Spotlight (as someone suggested above). And it double clicked automatically and installed ANOTHER certificate in the same folder as:
NONE of the above solved anything for me...I still got the same error.
So, I solved the problem by:
I can't tell you why this worked. But it solved the problem for me.
I just want to save someone the hassle next time. If someone can tell my why it worked, that would be terrific.
I didn't try the other terminal commands because of the 2 versions of jupyter notebook that I knew were a problem. I just don't know how to fix that.
Use screen: Start screen
, start your script, press Ctrl+A, D. Reattach with screen -r
.
Make a script that takes your "1" as a parameter, run nohup yourscript
:
#!/bin/bash
(time bash executeScript $1 input fileOutput $> scrOutput) &> timeUse.txt
WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh
None of the above worked for me but simply use this:
document.querySelector('.messageCheckbox').checked;
Happy coding.
I tried almost all of the mentioned answers but nothing worked for me. My gradle build was failing every time. Just found this solution:
Add annotationProcessor 'org.projectlombok:lombok'
in your build.gradle.
This worked for me.
It's quite easy and efficient to use Excel as a reporting tool for Access data.
A quick "non programming" approach is to set a List or a Pivot Table, linked to your External Data source. But that's out of scope for Stackoverflow.
A programmatic approach can be very simple:
strProv = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & SourceFile & ";"
Set cnn = New ADODB.Connection
cnn.Open strProv
Set rst = New ADODB.Recordset
rst.Open strSql, cnn
myDestRange.CopyFromRecordset rst
That's it !
Java enums are not like C or C++ enums, which are really just labels for integers.
Java enums are implemented more like classes - and they can even have multiple attributes.
public enum Ids {
OPEN(100), CLOSE(200);
private final int id;
Ids(int id) { this.id = id; }
public int getValue() { return id; }
}
The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.
See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.
I just unchecked all, applied, checked all again, applied and it worked :) hopefully helps others.
foreach (Foos foo in Enum.GetValues(typeof(Foos)))
{
...
}
In your script you can add the following to the lines that you know are going to give an output:
some_code 2>>/dev/null
Or else you can also try
some_code >>/dev/null
I had a call to cell.userInteractionEnabled buried in some customized table code.
Stupid, yet aren't most bugs?
Very very minified version of http://www.featureblend.com/javascript-flash-detection-library.html (only boolean flash detection)
var isFlashInstalled = (function(){
var b=new function(){var n=this;n.c=!1;var a="ShockwaveFlash.ShockwaveFlash",r=[{name:a+".7",version:function(n){return e(n)}},{name:a+".6",version:function(n){var a="6,0,21";try{n.AllowScriptAccess="always",a=e(n)}catch(r){}return a}},{name:a,version:function(n){return e(n)}}],e=function(n){var a=-1;try{a=n.GetVariable("$version")}catch(r){}return a},i=function(n){var a=-1;try{a=new ActiveXObject(n)}catch(r){a={activeXError:!0}}return a};n.b=function(){if(navigator.plugins&&navigator.plugins.length>0){var a="application/x-shockwave-flash",e=navigator.mimeTypes;e&&e[a]&&e[a].enabledPlugin&&e[a].enabledPlugin.description&&(n.c=!0)}else if(-1==navigator.appVersion.indexOf("Mac")&&window.execScript)for(var t=-1,c=0;c<r.length&&-1==t;c++){var o=i(r[c].name);o.activeXError||(n.c=!0)}}()};
return b.c;
})();
if(isFlashInstalled){
// Do something with flash
}else{
// Don't use flash
}
This should be fine:
const char* bool_cast(const bool b) {
return b ? "true" : "false";
}
But, if you want to do it more C++-ish:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string bool_cast(const bool b) {
ostringstream ss;
ss << boolalpha << b;
return ss.str();
}
int main() {
cout << bool_cast(true) << "\n";
cout << bool_cast(false) << "\n";
}
Files will be deleted from your app's document directory when the user uninstalls the app. Knowing this, all you have to do is check whether a file exists as the first thing that happens in application:didFinishLaunchingWithOptions:
. Afterwards, unconditionally create the file (even if it's just a dummy file).
If the file did not exist at time of check, you know this is the first run since the latest install. If you need to know later in the app, save the boolean result to your app delegate member.
Purely on the basis of inheritance, you would use an Abstract where you're defining clearly descendant, abstract relationships (i.e. animal->cat) and/or require inheritance of virtual or non-public properties, especially shared state (which Interfaces cannot support).
You should try and favour composition (via dependency injection) over inheritance where you can though, and note that Interfaces being contracts support unit-testing, separation of concerns and (language varying) multiple inheritance in a way Abstracts cannot.
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
See the section "5.1. Accessing Hibernate APIs from JPA" in the Hibernate ORM User Guide:
Session session = entityManager.unwrap(Session.class);
df.index[df.LastName == 'Smith']
Or
df.query('LastName == "Smith"').index
Will return all row indices where LastName
is Smith
Int64Index([1], dtype='int64')
I haven't played around with it much but eclipse/pydev feels nice.
I got the same problem when trying to create a database using Code First(without database approach). The problem is that EF doesn't have enough permissions to create a database for you.
So I worked my way up using the Code First(using an existing database approach).
Steps :
Now in the Context class, create a constructor for it and extend it from base class and pass the name of the connection string as a parameter. Just like,
public class DummyContext : DbContext
{
public DummyContext() : base("name=DefaultConnection")
{
}
}
5.And now run your code and see the tables getting added to the database provided.
check it useing loop for each index in comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
select age(timestamp_A, timestamp_B)
Answering to Igor's comment:
select age('2013-02-28 11:01:28'::timestamp, '2011-12-31 11:00'::timestamp);
age
-------------------------------
1 year 1 mon 28 days 00:01:28
I Did that and it works for redirecting to other view I think If you add the #sectionLink after It will work
<a class="btn yellow" href="/users/Create/@Model.Id" target="_blank">
Add As User
</a>
As no one has not provided an OO approach yet here is like it would be done.
class Person {
public $name = 'Alex Super Tramp';
public $age = 100;
private $property = 'property';
}
$r = new ReflectionClass(new Person);
print_r($r->getProperties());
//Outputs
Array
(
[0] => ReflectionProperty Object
(
[name] => name
[class] => Person
)
[1] => ReflectionProperty Object
(
[name] => age
[class] => Person
)
[2] => ReflectionProperty Object
(
[name] => property
[class] => Person
)
)
The advantage when using reflection is that you can filter by visibility of property, like this:
print_r($r->getProperties(ReflectionProperty::IS_PRIVATE));
Since Person::$property is private it's returned when filtering by IS_PRIVATE:
//Outputs
Array
(
[0] => ReflectionProperty Object
(
[name] => property
[class] => Person
)
)
Read the docs!
To create a new Date object in node.js
, or JavaScript
in general, just call it’s initializer
var d = new Date();
var d = new Date(dateString);
var d = new Date(jsonDate);
var d = new Date(year, month, day);
var d = new Date(year, month, day, hour, minute, second, millisecond);
Remember that Date objects can only be instantiated by calling Date
or using it as a constructor; unlike other JavaScript object types, Date objects have no literal syntax
You don't need to list ContactPhoneAreaCode1 and ContactPhoneNumber1
SELECT FirstName AS First_Name,
LastName AS Last_Name,
COALESCE(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone
FROM TABLE1
There is no do-while loop in Python.
This is a similar construct, taken from the link above.
while True:
do_something()
if condition():
break
For alphabetical order following nationalization, use Collator
.
//Get the Collator for US English and set its strength to PRIMARY
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
if( usCollator.compare("abc", "ABC") == 0 ) {
System.out.println("Strings are equivalent");
}
For a list of supported locales, see JDK 8 and JRE 8 Supported Locales.
That means sql group by 1st column in your select clause, we always use this GROUP BY 1
together with ORDER BY 1
, besides you can also use like this GROUP BY 1,2,3..
, of course it is convenient for us but you need to pay attention to that condition the result may be not what you want if some one has modified your select columns, and it's not visualized
This is a complete solution based on MadisonTrash answer, and benrwb and fredrivett tweaks for safari compatibility and vue 3 api changes.
The solution proposed below is still useful, and the how to use is still valid, but I changed it to use document.elementsFromPoint
instead of event.contains
because it doesn't recognise as children some elements like the <path>
tags inside svgs. So the right directive is this one:
export default {
beforeMount: (el, binding) => {
el.eventSetDrag = () => {
el.setAttribute("data-dragging", "yes");
};
el.eventClearDrag = () => {
el.removeAttribute("data-dragging");
};
el.eventOnClick = event => {
const dragging = el.getAttribute("data-dragging");
// Check that the click was outside the el and its children, and wasn't a drag
console.log(document.elementsFromPoint(event.clientX, event.clientY))
if (!document.elementsFromPoint(event.clientX, event.clientY).includes(el) && !dragging) {
// call method provided in attribute value
binding.value(event);
}
};
document.addEventListener("touchstart", el.eventClearDrag);
document.addEventListener("touchmove", el.eventSetDrag);
document.addEventListener("click", el.eventOnClick);
document.addEventListener("touchend", el.eventOnClick);
},
unmounted: el => {
document.removeEventListener("touchstart", el.eventClearDrag);
document.removeEventListener("touchmove", el.eventSetDrag);
document.removeEventListener("click", el.eventOnClick);
document.removeEventListener("touchend", el.eventOnClick);
el.removeAttribute("data-dragging");
},
};
const clickOutside = {
beforeMount: (el, binding) => {
el.eventSetDrag = () => {
el.setAttribute("data-dragging", "yes");
};
el.eventClearDrag = () => {
el.removeAttribute("data-dragging");
};
el.eventOnClick = event => {
const dragging = el.getAttribute("data-dragging");
// Check that the click was outside the el and its children, and wasn't a drag
if (!(el == event.target || el.contains(event.target)) && !dragging) {
// call method provided in attribute value
binding.value(event);
}
};
document.addEventListener("touchstart", el.eventClearDrag);
document.addEventListener("touchmove", el.eventSetDrag);
document.addEventListener("click", el.eventOnClick);
document.addEventListener("touchend", el.eventOnClick);
},
unmounted: el => {
document.removeEventListener("touchstart", el.eventClearDrag);
document.removeEventListener("touchmove", el.eventSetDrag);
document.removeEventListener("click", el.eventOnClick);
document.removeEventListener("touchend", el.eventOnClick);
el.removeAttribute("data-dragging");
},
}
createApp(App)
.directive("click-outside", clickOutside)
.mount("#app");
This solution watch the element and the element's children of the component where the directive is applied to check if the event.target
element is also a child. If that's the case it will not trigger, because it's inside the component.
You only have to use as any directive, with a method reference to handle the trigger:
<template>
<div v-click-outside="myMethod">
<div class="handle" @click="doAnotherThing($event)">
<div>Any content</div>
</div>
</div>
</template>
I heard of RTM (The RT FAQ Manager). Never used it, however.
If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
and client side JavaScript/jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.
I am writing application to API level 21, I tried all the above but didn't worked, Finally i deleted Values-v23 from appcompat_v7.It worked.
You can see the following example for the Form action on the same page
<form action="" method="post">
<table border="1px">
<tr><td>Name: <input type="text" name="user_name" ></td></tr>
<tr><td align="right"> <input type="submit" value="submit" name="btn">
</td></tr>
</table>
</form>
<?php
if(isset($_POST['btn'])){
$name=$_POST['user_name'];
echo 'Welcome '. $name;
}
?>
Use
git cherry-pick <commit>
to apply <commit>
to your current branch.
I myself would probably cross-check the commits I pick in gitk
and cherry-pick them with right-clicks on the commit entry there instead.
If you want to go more automatic (with all its dangers) and assuming all commits since yesterday happened on wss you could generate the list of commits using git log
(with --pretty
suggested by Jefromi)
git log --reverse --since=yesterday --pretty=%H
so everything together assuming you use bash
for commit in $(git log --reverse --since=yesterday --pretty=%H);
do
git cherry-pick $commit
done
If something goes wrong here (there is a lot of potential) you are in trouble since this works on the live checkout, so either do manual cherry-picks or use rebase like suggested by Jefromi.
I found it. Perl has multi-line comments:
#!/usr/bin/perl
use strict;
use warnings;
=for comment
Example of multiline comment.
Example of multiline comment.
=cut
print "Multi Line Comment Example \n";
Transient variables in Java are never serialized.
This should get you started: Using VBA in your own Excel workbook, have it prompt the user for the filename of their data file, then just copy that fixed range into your target workbook (that could be either the same workbook as your macro enabled one, or a third workbook). Here's a quick vba example of how that works:
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' assume range is A1 - C10 in sheet1
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
targetSheet.Range("A1", "C10").Value = sourceSheet.Range("A1", "C10").Value
' Close customer workbook
customerWorkbook.Close
You can achieve this using Lodash _.assign
function.
library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
"Gold Rush": {_x000D_
"foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
"backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
},_x000D_
"California": {_x000D_
"foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
"backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
}_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
// If title already exists, modify item_x000D_
if (library[title]) {_x000D_
_x000D_
// override one Object with the values of another (lodash)_x000D_
library[title] = _.assign({}, {_x000D_
'foregrounds': foregrounds_x000D_
}, {_x000D_
'backgrounds': backgrounds_x000D_
});_x000D_
console.log(library[title]);_x000D_
_x000D_
// Save to Database. Then on callback..._x000D_
// console.log('Changes Saved to <b>' + title + '</b>');_x000D_
}_x000D_
_x000D_
// If title does not exist, add new item_x000D_
else {_x000D_
// Format it for the JSON object_x000D_
var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
// THE PROBLEM SEEMS TO BE HERE??_x000D_
// Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
library.push(item);_x000D_
_x000D_
// Save to Database. Then on callback..._x000D_
console.log('Added: <b>' + title + '</b>');_x000D_
}_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_