You want to do $arrayOfString[0].Title -eq $myPbiject.item(0).Title
-match
is for regex matching ( the second argument is a regex )
Is there a way to limit a regex to 100 characters WITH regex?
Your example suggests that you'd like to grab a number from inside the regex and then use this number to place a maximum length on another part that is matched later in the regex. This usually isn't possible in a single pass. Your best bet is to have two separate regular expressions:
If you just want to limit the number of characters matched by an expression, most regular expressions support bounds by using braces. For instance,
\d{3}-\d{3}-\d{4}
will match (US) phone numbers: exactly three digits, then a hyphen, then exactly three digits, then another hyphen, then exactly four digits.
Likewise, you can set upper or lower limits:
\d{5,10}
means "at least 5, but not more than 10 digits".
Update: The OP clarified that he's trying to limit the value, not the length. My new answer is don't use regular expressions for that. Extract the value, then compare it against the maximum you extracted from the size parameter. It's much less error-prone.
if you want to write in column:
for x in np.nditer(a.T, order='C'):
file.write(str(x))
file.write("\n")
Here 'a' is the name of numpy array and 'file' is the variable to write in a file.
If you want to write in row:
writer= csv.writer(file, delimiter=',')
for x in np.nditer(a.T, order='C'):
row.append(str(x))
writer.writerow(row)
var rotator = function(){
widget.Rotator.rotate();
setTimeout(rotator,5000);
};
rotator();
Or:
setInterval(
function(){ widget.Rotator.rotate() },
5000
);
Or:
setInterval(
widget.Rotator.rotate.bind(widget.Rotator),
5000
);
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
It seems that this can't be done, not at least with current versions of IE (6 and 7).
IE supports form attribute accept-charset, but only if its value is 'utf-8'.
The solution is to modify server A to produce encoding 'ISO-8859-1' for page that contains the form.
The selected answer apparently does not work anymore in 2019 (at least for me).
I was trying to export a certificate using openssl (version 1.1.0) and the parameter -password
doesn't work.
According to that link in the original answer (the same info is in man openssl
), openssl has two parameter for passwords and they are -passin
for the input parts and -passout
for output files.
For the -export
command, I used -passin
for the password of my key file and -passout
to create a new password for my P12 file.
So the complete command without any prompt was like below:
openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass:keypassphrase -passout pass:certificatepassword
If you does not want a password, you can use pass:
like below:
openssl pkcs12 -export -in /tmp/MyCert.crt -inkey /tmp/MyKey.key -out /tmp/MyP12.p12 -name alias -passin pass: -passout pass:
It will works fine with a key without password and the output certificate will be created without password too.
Not sure if you have resolved it (and if I understand correctly), but here's my idea:
If parent receives myProp, and you want it to pass to child and watch it in child, then parent has to have copy of myProp (not reference).
Try this:
new Vue({
el: '#app',
data: {
text: 'Hello'
},
components: {
'parent': {
props: ['myProp'],
computed: {
myInnerProp() { return myProp.clone(); } //eg. myProp.slice() for array
}
},
'child': {
props: ['myProp'],
watch: {
myProp(val, oldval) { now val will differ from oldval }
}
}
}
}
and in html:
<child :my-prop="myInnerProp"></child>
actually you have to be very careful when working on complex collections in such situations (passing down few times)
I found the answer!
I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).
The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS
#ActionBox {
position: relative;
float: right;
}
Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)
I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.
You can set the fontsize directly in the call to set_xticklabels
and set_yticklabels
(as noted in previous answers). This will only affect one Axes
at a time.
ax.set_xticklabels(x_ticks, rotation=0, fontsize=8)
ax.set_yticklabels(y_ticks, rotation=0, fontsize=8)
You can also set the ticklabel
font size globally (i.e. for all figures/subplots in a script) using rcParams
:
import matplotlib.pyplot as plt
plt.rc('xtick',labelsize=8)
plt.rc('ytick',labelsize=8)
Or, equivalently:
plt.rcParams['xtick.labelsize']=8
plt.rcParams['ytick.labelsize']=8
Finally, if this is a setting that you would like to be set for all your matplotlib plots, you could also set these two rcParams
in your matplotlibrc
file:
xtick.labelsize : 8 # fontsize of the x tick labels
ytick.labelsize : 8 # fontsize of the y tick labels
According to Jenkins documentation for declarative pipeline:
sh 'printenv'
For Jenkins scripted pipeline:
echo sh(script: 'env|sort', returnStdout: true)
The above also sorts your env vars for convenience.
well after a few modification of the code provided by mace,i ended up building a stopwatch. https://codepen.io/truestbyheart/pen/EGELmv
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Stopwatch</title>
<style>
#center {
margin: 30% 30%;
font-family: tahoma;
}
.stopwatch {
border:1px solid #000;
background-color: #eee;
text-align: center;
width:656px;
height: 230px;
overflow: hidden;
}
.stopwatch span{
display: block;
font-size: 100px;
}
.stopwatch p{
display: inline-block;
font-size: 40px;
}
.stopwatch a{
font-size:45px;
}
a:link,
a:visited{
color :#000;
text-decoration: none;
padding: 12px 14px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="center">
<div class="timer stopwatch"></div>
</div>
<script>
const Stopwatch = function(elem, options) {
let timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval,
hrs = 0,
min = 0;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
if (action !== "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
} else if (action === "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
clean();
event.preventDefault();
});
return a;
}
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function clean() {
min = 0;
hrs = 0;
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
if (Math.floor(clock / 1000) === 60) {
min++;
reset();
if (min === 60) {
min = 0;
hrs++;
}
}
timer.innerHTML =
hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
};
// Initiating the Stopwatch
var elems = document.getElementsByClassName("timer");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
</script>
</body>
</html>
You can't add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.
There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can't edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.
Check out: Unique ID in SharePoint list
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.
How to get the last N rows of a pandas DataFrame?
If you are slicing by position, __getitem__
(i.e., slicing with[]
) works well, and is the most succinct solution I've found for this problem.
pd.__version__
# '0.24.2'
df = pd.DataFrame({'A': list('aaabbbbc'), 'B': np.arange(1, 9)})
df
A B
0 a 1
1 a 2
2 a 3
3 b 4
4 b 5
5 b 6
6 b 7
7 c 8
df[-3:]
A B
5 b 6
6 b 7
7 c 8
This is the same as calling df.iloc[-3:]
, for instance (iloc
internally delegates to __getitem__
).
As an aside, if you want to find the last N rows for each group, use groupby
and GroupBy.tail
:
df.groupby('A').tail(2)
A B
1 a 2
2 a 3
5 b 6
6 b 7
7 c 8
You can use the terms aggregation.
{
"size": 0,
"aggs" : {
"langs" : {
"terms" : { "field" : "language", "size" : 500 }
}
}}
The size
parameter within the aggregation specifies the maximum number of terms to include in the aggregation result. If you need all results, set this to a value that is larger than the number of unique terms in your data.
A search will return something like:
{
"took" : 16,
"timed_out" : false,
"_shards" : {
"total" : 2,
"successful" : 2,
"failed" : 0
},
"hits" : {
"total" : 1000000,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"langs" : {
"buckets" : [ {
"key" : "10",
"doc_count" : 244812
}, {
"key" : "11",
"doc_count" : 136794
}, {
"key" : "12",
"doc_count" : 32312
} ]
}
}
}
this is the easiest way that you could print the String by using array!!!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace arraypracticeforstring
{
class Program
{
static void Main(string[] args)
{
string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };
foreach (string item in arr)
{
Console.WriteLine(item.ToString());
}
Console.ReadLine();
}
}
}
I resolved this by installing System.Data.SQLite with Nuget extension. This extension can use for Visual Studio 2010 or higher. First, you have to install Nuget extension. You can follow here:
Second, now, you can install SQLite:
And now, you can use System.Data.SQLite.
In the case, you see two folder x64 and, x86, these folders contain SQLite.Interop.dll. Now go to the properties windows of those dlls and set build action is content and Copy to output directory is Copy always.
So, that is my way.
Thanks. Kim Tho Pham, HoChiMinh City, Vietnam. Email: [email protected]
I think this is only partially true. Changing the format seems to switch the date to a string object which then has no methods like AddDays to manipulate it. So to make this work, you have to switch it back to a date. For example:
Get-Date (Get-Date).AddDays(-1) -format D
alternative commands that does same job
tr -d ",$" < infile
awk 'gsub(",$","")' infile
It is a bad practice to involve any exception throwing/handling into such a typical scenario.
Therefore a parseInt() is not nice, but a regex is an elegant solution for this, but take care of the following:
-fractions
-negative numbers
-decimal separator might differ in contries (e.g. ',' or '.')
-sometimes it is allowed to have a so called thousand separator, like a space or a comma e.g. 12,324,1000.355
To handle all the necessary cases in your application you have to be careful, but this regex covers the typical scenarios (positive/negative and fractional, separated by a dot): ^[-+]?\d*.?\d+$
For testing, I recommend regexr.com.
It's fairly easy to use label
, You can break the outer loop from inner loop using the label, Consider the example below,
public class Breaking{
public static void main(String[] args) {
outerscope:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
break outerscope;
}
}
}
}
}
Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.
public class Breaking{
public static void main(String[] args) {
boolean isBreaking = false;
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
isBreaking = true;
break;
}
}
if(isBreaking){
break;
}
}
}
}
However, I prefer using the first approach.
If superkey is a big set than candidate key is some smaller set inside big set and primary key any one element(one at a time or for a table) in candidate key set.
Messing around with the same answers:
$ git config --global alias.find '!git log --color -p -S '
Now you can do
$ git find <whatever>
or
$ git find <whatever> --all
$ git find <whatever> master develop
Yes, you could append ;Connection Timeout=30
to your connection string and specify the value you wish.
The timeout value set in the Connection Timeout
property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).
Moreover, setting the timeout value to 0
, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.
Shows the file names and amount/nubmer of lines that changed in each file between now and the specified commit:
git diff --stat <commit-hash>
For me, using expo, I just had to restart expo. ctrl + c
and yarn start
or expo start
and the run on ios simulator or your device, whichever you're testing with.
I deleted folders build
inside a project. After cleaned and rebuilt it in Android Studio. Then corrected errors in build.gradle and AndroidManifest.
You call both event listeners using .on()
then use a if
inside the function:
$(function(){
$('#searchButton').on('keypress click', function(e){
var search = $('#usersSearch').val();
if (e.which === 13 || e.type === 'click') {
$.post('../searchusers.php', {search: search}, function (response) {
$('#userSearchResultsTable').html(response);
});
}
});
});
Swift 4
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let selectedCell = tableView.cellForRow(at: indexPath)! as! LeftMenuCell
selectedCell.contentView.backgroundColor = UIColor.blue
}
If you want to unselect the previous cell, also you can use the different logic for this
var tempcheck = 9999
var lastrow = IndexPath()
var lastcolor = UIColor()
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
if tempcheck == 9999
{
tempcheck = 0
let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
lastcolor = selectedCell.contentView.backgroundColor!
selectedCell.contentView.backgroundColor = UIColor.blue
lastrow = indexPath
}
else
{
let selectedCelllasttime = tableView.cellForRow(at: lastrow)! as! HealthTipsCell
selectedCelllasttime.contentView.backgroundColor = lastcolor
let selectedCell = tableView.cellForRow(at: indexPath)! as! HealthTipsCell
lastcolor = selectedCell.contentView.backgroundColor!
selectedCell.contentView.backgroundColor = UIColor.blue
lastrow = indexPath
}
}
To return a value from a VBScript function, assign the value to the name of the function, like this:
Function getNumber
getNumber = "423"
End Function
I think the simplest way it's to use library ContentManager. This library for getting photo or video from a device gallery, cloud or camera. With asynchronous load from the cloud and fixed bugs for some problem devices.
Download via Gradle:
compile 'com.github.stfalcon:contentmanager:0.4.3'
You can find documentation at https://github.com/stfalcon-studio/ContentManager
If you don't like nested list comprehensions, you can make use of the map function as well,
>>> from pprint import pprint
>>> l = l = [['40', '20', '10', '30'], ['20', '20', '20', '20', '20', '30', '20'], ['30', '20', '30', '50', '10', '30', '20', '20', '20'], ['100', '100'], ['100', '100', '100', '100', '100'], ['100', '100', '100', '100']]
>>> pprint(l)
[['40', '20', '10', '30'],
['20', '20', '20', '20', '20', '30', '20'],
['30', '20', '30', '50', '10', '30', '20', '20', '20'],
['100', '100'],
['100', '100', '100', '100', '100'],
['100', '100', '100', '100']]
>>> float_l = [map(float, nested_list) for nested_list in l]
>>> pprint(float_l)
[[40.0, 20.0, 10.0, 30.0],
[20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0],
[30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0],
[100.0, 100.0],
[100.0, 100.0, 100.0, 100.0, 100.0],
[100.0, 100.0, 100.0, 100.0]]
Dim numberOfButtons As Integer
Dim buttons() as Button
Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Redim buttons(numberOfbuttons)
for counter as integer = 0 to numberOfbuttons
With buttons(counter)
.Size = (10, 10)
.Visible = False
.Location = (55, 33 + counter*13)
.Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
'any other property
End With
'
next
End Sub
If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.
If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:
AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked
then create
Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub
when you call: objectYouCall.numberOfButtons = initial_value_from_main_program
response_yes_or_no_or_other = objectYouCall.ShowDialog()
For radio buttons, textboxes, same story, different ending.
In getting started with require.js I ran into the issue and as a beginner the docs may as well been written in greek.
The issue I ran into was that most of the beginner examples use "anonymous defines" when you should be using a "string id".
anonymous defines
define(function() {
return { helloWorld: function() { console.log('hello world!') } };
})
define(function() {
return { helloWorld2: function() { console.log('hello world again!') } };
})
define with string id
define('moduleOne',function() {
return { helloWorld: function() { console.log('hello world!') } };
})
define('moduleTwo', function() {
return { helloWorld2: function() { console.log('hello world again!') } };
})
When you use define with a string id then you will avoid this error when you try to use the modules like so:
require([ "moduleOne", "moduleTwo" ], function(moduleOne, moduleTwo) {
moduleOne.helloWorld();
moduleTwo.helloWorld2();
});
You can use sort.Slice()
plus sort.Search()
type Person struct {
Name string
}
func main() {
crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}
sort.Slice(crowd, func(i, j int) bool {
return crowd[i].Name <= crowd[j].Name
})
needle := "Benni"
idx := sort.Search(len(crowd), func(i int) bool {
return string(crowd[i].Name) >= needle
})
if crowd[idx].Name == needle {
fmt.Println("Found:", idx, crowd[idx])
} else {
fmt.Println("Found noting: ", idx)
}
}
make a class for that button lets say :
`<input type="button" value="+" class="b1" onclick="addRow()">`
your js should look like this :
$(document).ready(function(){
$('.b1').click(function(){
$('div').append('<input type="text"..etc ');
});
});
Just like any other environment variable, with SET
:
SET PATH=%PATH%;c:\whatever\else
If you want to have a little safety check built in first, check to see if the new path exists first:
IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else
If you want that to be local to that batch file, use setlocal
:
setlocal
set PATH=...
set OTHERTHING=...
@REM Rest of your script
Read the docs carefully for setlocal
/endlocal
, and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.
The Syntax page should get you started with the basics.
Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.
As pointed out, you can use getElementById
instead, but you can also still achieve the same with a querySelector
:
document.querySelector("[id='22']")
If this is a Windows app, try checking for a duplicate in the Global Assembly Cache (GAC). Something is overriding your bin / debug version.
If this is a web app, you may need to delete on server and re-upload. If you are publishing you may want to check the Delete all existing files prior to publish check box. Depending on Visual Studio version it should be located in Publish > Settings > File Publish Options
public string GetCreditCardType(string CreditCardNumber)
{
Regex regVisa = new Regex("^4[0-9]{12}(?:[0-9]{3})?$");
Regex regMaster = new Regex("^5[1-5][0-9]{14}$");
Regex regExpress = new Regex("^3[47][0-9]{13}$");
Regex regDiners = new Regex("^3(?:0[0-5]|[68][0-9])[0-9]{11}$");
Regex regDiscover = new Regex("^6(?:011|5[0-9]{2})[0-9]{12}$");
Regex regJCB = new Regex("^(?:2131|1800|35\\d{3})\\d{11}$");
if (regVisa.IsMatch(CreditCardNumber))
return "VISA";
else if (regMaster.IsMatch(CreditCardNumber))
return "MASTER";
else if (regExpress.IsMatch(CreditCardNumber))
return "AEXPRESS";
else if (regDiners.IsMatch(CreditCardNumber))
return "DINERS";
else if (regDiscover.IsMatch(CreditCardNumber))
return "DISCOVERS";
else if (regJCB.IsMatch(CreditCardNumber))
return "JCB";
else
return "invalid";
}
Here is the function to check Credit card type using Regex , c#
So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.
One way I solved this problem was by making the beginning of the path relative. For your case:
gulp.src([
'index.php',
'*css/**/*',
'*js/**/*',
'*src/**/*',
])
.pipe(gulp.dest('/var/www/'));
The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)
This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/
at the same level as js
, you would end up matching both.
This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.
A static variable inside a function has a lifespan as long as your program runs. It won't be allocated every time your function is called and deallocated when your function returns.
You're not far; you need to do something like this:
[WebMethod]
public static string GetProducts()
{
// instantiate a serializer
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
//optional: you can create your own custom converter
TheSerializer.RegisterConverters(new JavaScriptConverter[] {new MyCustomJson()});
var products = context.GetProducts().ToList();
var TheJson = TheSerializer.Serialize(products);
return TheJson;
}
You can reduce this code further but I left it like that for clarity. In fact, you could even write this:
return context.GetProducts().ToList();
and this would return a json string. I prefer to be more explicit because I use custom converters. There's also Json.net but the framework's JavaScriptSerializer
works just fine out of the box.
Preferences can either be set in code or can be found in res/xml/preferences.xml. You can read more about preferences on the Android SDK website.
There is also someone who managed to modify CR for VS.NET 2010 to install on 2012, using MS ORCA
in this thread: http://scn.sap.com/thread/3235515 . I couldn't get it to work myself, though.
Quick answer:
Doing list()
around a generator expression is (almost) exactly equivalent to having []
brackets around it. So yeah, you can do
>>> list((x for x in string.letters if x in (y for y in "BigMan on campus")))
But you can just as well do
>>> [x for x in string.letters if x in (y for y in "BigMan on campus")]
Yes, that will turn the generator expression into a list comprehension. It's the same thing and calling list() on it. So the way to make a generator expression into a list is to put brackets around it.
Detailed explanation:
A generator expression is a "naked" for
expression. Like so:
x*x for x in range(10)
Now, you can't stick that on a line by itself, you'll get a syntax error. But you can put parenthesis around it.
>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7485464>
This is sometimes called a generator comprehension, although I think the official name still is generator expression, there isn't really any difference, the parenthesis are only there to make the syntax valid. You do not need them if you are passing it in as the only parameter to a function for example:
>>> sorted(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Basically all the other comprehensions available in Python 3 and Python 2.7 is just syntactic sugar around a generator expression. Set comprehensions:
>>> {x*x for x in range(10)}
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
>>> set(x*x for x in range(10))
{0, 1, 4, 81, 64, 9, 16, 49, 25, 36}
Dict comprehensions:
>>> dict((x, x*x) for x in range(10))
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {x: x*x for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
And list comprehensions under Python 3:
>>> list(x*x for x in range(10))
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Under Python 2, list comprehensions is not just syntactic sugar. But the only difference is that x will under Python 2 leak into the namespace.
>>> x
9
While under Python 3 you'll get
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
This means that the best way to get a nice printout of the content of your generator expression in Python is to make a list comprehension out of it! However, this will obviously not work if you already have a generator object. Doing that will just make a list of one generator:
>>> foo = (x*x for x in range(10))
>>> [foo]
[<generator object <genexpr> at 0xb7559504>]
In that case you will need to call list()
:
>>> list(foo)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Although this works, but is kinda stupid:
>>> [x for x in foo]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
To get a more precise (and user friendly) information about connection type. You can use this code (derived from a @hide method in TelephonyManager.java).
This method returns a String describing the current connection type.
i.e. one of : "WIFI" , "2G" , "3G" , "4G" , "5G" , "-" (not connected) or "?" (unknown)
Remark: This code requires API 25+, but you can easily support older versions by using int instead of const. (See comments in code).
public static String getNetworkClass(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info == null || !info.isConnected())
return "-"; // not connected
if (info.getType() == ConnectivityManager.TYPE_WIFI)
return "WIFI";
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
int networkType = info.getSubtype();
switch (networkType) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN: // api< 8: replace by 11
case TelephonyManager.NETWORK_TYPE_GSM: // api<25: replace by 16
return "2G";
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B: // api< 9: replace by 12
case TelephonyManager.NETWORK_TYPE_EHRPD: // api<11: replace by 14
case TelephonyManager.NETWORK_TYPE_HSPAP: // api<13: replace by 15
case TelephonyManager.NETWORK_TYPE_TD_SCDMA: // api<25: replace by 17
return "3G";
case TelephonyManager.NETWORK_TYPE_LTE: // api<11: replace by 13
case TelephonyManager.NETWORK_TYPE_IWLAN: // api<25: replace by 18
case 19: // LTE_CA
return "4G";
case TelephonyManager.NETWORK_TYPE_NR: // api<29: replace by 20
return "5G";
default:
return "?";
}
}
return "?";
}
If you are aiming for maximum browser support, modern approach is to place button in a div with display:flex;
and flex-direction:row;
The same trick will work for height with flex-direction:column;
or both height and width(will require 2 divs)
You can write: [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]
It also takes care of not serializing properties with default values (not only null). It can be useful for enums for example.
Date
is a container for the number of milliseconds since the Unix epoch ( 00:00:00 UTC on 1 January 1970).
It has no concept of format.
LocalDateTime ldt = LocalDateTime.now();
System.out.println(DateTimeFormatter.ofPattern("MM-dd-yyyy", Locale.ENGLISH).format(ldt));
System.out.println(DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH).format(ldt));
System.out.println(ldt);
Outputs...
05-11-2018
2018-05-11
2018-05-11T17:24:42.980
You should be making use of the ThreeTen Backport
For example...
Date myDate = new Date();
System.out.println(myDate);
System.out.println(new SimpleDateFormat("MM-dd-yyyy").format(myDate));
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(myDate));
System.out.println(myDate);
Outputs...
Wed Aug 28 16:20:39 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 16:20:39 EST 2013
None of the formatting has changed the underlying Date
value. This is the purpose of the DateFormatter
s
Updated with additional example
Just in case the first example didn't make sense...
This example uses two formatters to format the same date. I then use these same formatters to parse the String
values back to Date
s. The resulting parse does not alter the way Date
reports it's value.
Date#toString
is just a dump of it's contents. You can't change this, but you can format the Date
object any way you like
try {
Date myDate = new Date();
System.out.println(myDate);
SimpleDateFormat mdyFormat = new SimpleDateFormat("MM-dd-yyyy");
SimpleDateFormat dmyFormat = new SimpleDateFormat("yyyy-MM-dd");
// Format the date to Strings
String mdy = mdyFormat.format(myDate);
String dmy = dmyFormat.format(myDate);
// Results...
System.out.println(mdy);
System.out.println(dmy);
// Parse the Strings back to dates
// Note, the formats don't "stick" with the Date value
System.out.println(mdyFormat.parse(mdy));
System.out.println(dmyFormat.parse(dmy));
} catch (ParseException exp) {
exp.printStackTrace();
}
Which outputs...
Wed Aug 28 16:24:54 EST 2013
08-28-2013
2013-08-28
Wed Aug 28 00:00:00 EST 2013
Wed Aug 28 00:00:00 EST 2013
Also, be careful of the format patterns. Take a closer look at SimpleDateFormat
to make sure you're not using the wrong patterns ;)
Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.
Just been doing that myself today... here is code I have working for me...
$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
$response = curl_exec($ch);
if (!$response)
{
return false;
}
src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl
var appBanners = document.getElementsByClassName('appBanner');
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
DecimalFormat df=new DecimalFormat("0.00");
Use this code to get exact two decimal points. Even if the value is 0.0 it will give u 0.00 as output.
Instead if you use:
DecimalFormat df=new DecimalFormat("#.00");
It wont convert 0.2659 into 0.27. You will get an answer like .27.
Your regex does not work because [] defines a character class, but what you want is a lookahead:
(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)
So try: (?!bush)
Define a function like this:
getUserName() {
echo $1 | cut -d : -f 1 | xargs basename
}
And pass the string as a parameter:
userName=$(getUserName "/var/cpanel/users/joebloggs:DNS9=domain.com")
echo $userName
This line is causing problems:
(-b+math.sqrt(b**2-4*a*c))/2*a
x/2*a
is interpreted as (x/2)*a
. You need more parentheses:
(-b + math.sqrt(b**2 - 4*a*c)) / (2 * a)
Also, if you're already storing d
, why not use it?
x = (-b + math.sqrt(d)) / (2 * a)
I had the very same issue, not being able to instantiate the type of a class which I was absolutely sure was not abstract. Turns out I was implementing an abstract class from Java.util
instead of implementing my own class.
So if the previous answers did not help you, please check that you import
the class you actually wanted to import, and not something else with the same name that you IDE might have hinted you.
For example, if you were trying to instantiate the class Queue from the package myCollections which you coded yourself :
import java.util.*; // replace this line
import myCollections.Queue; // by this line
Queue<Edge> theQueue = new Queue<Edge>();
If you are coming from Microsoft Excel, the following functions will be similar to LEFT()
, RIGHT()
, and MID()
functions.
# This counts from the left and then extract n characters
str_left <- function(string, n) {
substr(string, 1, n)
}
# This counts from the right and then extract n characters
str_right <- function(string, n) {
substr(string, nchar(string) - (n - 1), nchar(string))
}
# This extract characters from the middle
str_mid <- function(string, from = 2, to = 5){
substr(string, from, to)
}
Examples:
x <- "some text in a string"
str_left(x, 4)
[1] "some"
str_right(x, 6)
[1] "string"
str_mid(x, 6, 9)
[1] "text"
As per my usage above v.4 this gonna work
$('#selectID').on("select2:select", function(e) {
//var value = e.params.data; Using {id,text format}
});
And for less then v.4 this gonna work:
$('#selectID').on("change", function(e) {
//var value = e.params.data; Using {id,text} format
});
Here is the Power Shell script which I used by taking the reference of:
https://stackoverflow.com/a/3495491/148657
$Lookup = @{
378389 = [version]'4.5'
378675 = [version]'4.5.1'
378758 = [version]'4.5.1'
379893 = [version]'4.5.2'
393295 = [version]'4.6'
393297 = [version]'4.6'
394254 = [version]'4.6.1'
394271 = [version]'4.6.1'
394802 = [version]'4.6.2'
394806 = [version]'4.6.2'
460798 = [version]'4.7'
460805 = [version]'4.7'
461308 = [version]'4.7.1'
461310 = [version]'4.7.1'
461808 = [version]'4.7.2'
461814 = [version]'4.7.2'
528040 = [version]'4.8'
528049 = [version]'4.8'
}
# For One True framework (latest .NET 4x), change the Where-Oject match
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -name Version, Release -EA 0 |
Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}},
@{name = "Product"; expression = {$Lookup[$_.Release]}},
Version, Release
The above script makes use of the registry and gives us the Windows update number along with .Net Framework installed on a machine.
Here are the results for the same when running that script on two different machines
List<string> animals= new List<string>();
animals.Add("dog");
animals.Add("tiger");
I am late for this but i want put some more solution relevant to this.
@GetMapping
public ResponseEntity<List<JSONObject>> getRole() {
return ResponseEntity.ok(service.getRole());
}
Let me please update the acdcjunior's answer about using HttpInterceptor with the latest RxJs features(v.6).
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpRequest,
HttpErrorResponse,
HttpHandler,
HttpEvent,
HttpResponse
} from '@angular/common/http';
import { Observable, EMPTY, throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError((error: HttpErrorResponse) => {
if (error.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(`Backend returned code ${error.status}, body was: ${error.error}`);
}
// If you want to return a new response:
//return of(new HttpResponse({body: [{name: "Default value..."}]}));
// If you want to return the error on the upper level:
//return throwError(error);
// or just return nothing:
return EMPTY;
})
);
}
}
The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.
Do you need any other information except the date? If not:
SELECT DISTINCT start_date FROM table;
From http://matplotlib.sourceforge.net/examples/event_handling/pick_event_demo.html :
from matplotlib.pyplot import figure, show
import numpy as npy
from numpy.random import rand
if 1: # picking on a scatter plot (matplotlib.collections.RegularPolyCollection)
x, y, c, s = rand(4, 100)
def onpick3(event):
ind = event.ind
print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))
fig = figure()
ax1 = fig.add_subplot(111)
col = ax1.scatter(x, y, 100*s, c, picker=True)
#fig.savefig('pscoll.eps')
fig.canvas.mpl_connect('pick_event', onpick3)
show()
Can anyone give me a brief explanation...
Sure.
ORM stands for "Object to Relational Mapping" where
The Object part is the one you use with your programming language ( python in this case )
The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )
And finally the Mapping part is where you do a bridge between your objects and your tables.
In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.
So let's say you have this object.
class Employee:
def __init__( self, name ):
self.__name = name
def getName( self ):
return self.__name
#etc.
and the table
create table employee(
name varcar(10),
-- etc
)
Using an ORM framework would allow you to map that object with a db record automagically and write something like:
emp = Employee("Ryan")
orm.save( emp )
And have the employee inserted into the DB.
Oops it was not that brief but I hope it is simple enough to catch other articles you read.
First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U
And, in my case, I mistakenly define my two different columns as identities on DbContext configurations like below,
builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.Id).UseSqlServerIdentityColumn(); //History Id should use identity column in this example
When I correct it like below,
builder.HasKey(e => e.HistoryId).HasName("HistoryId");
builder.Property(e => e.HistoryId).UseSqlServerIdentityColumn();
I have also got rid of this error.
You want to iterate backwards through using a counter instead of foreach. If you iterate forwards you have to adjust the counter as you delete items.
for(int i=listBox1.Items.Count - 1; i > -1; i--) {
{
if(listBox1.Items[i].Contains("OBJECT"))
{
listBox1.Items.RemoveAt(i);
}
}
If you add:
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
in the head of the document it will start working as expected:
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
<script type="text/javascript">_x000D_
function get_param(param) {_x000D_
var search = window.location.search.substring(1);_x000D_
var compareKeyValuePair = function(pair) {_x000D_
var key_value = pair.split('=');_x000D_
var decodedKey = decodeURIComponent(key_value[0]);_x000D_
var decodedValue = decodeURIComponent(key_value[1]);_x000D_
if(decodedKey == param) return decodedValue;_x000D_
return null;_x000D_
};_x000D_
_x000D_
var comparisonResult = null;_x000D_
_x000D_
if(search.indexOf('&') > -1) {_x000D_
var params = search.split('&');_x000D_
for(var i = 0; i < params.length; i++) {_x000D_
comparisonResult = compareKeyValuePair(params[i]); _x000D_
if(comparisonResult !== null) {_x000D_
break;_x000D_
}_x000D_
}_x000D_
} else {_x000D_
comparisonResult = compareKeyValuePair(search);_x000D_
}_x000D_
_x000D_
return comparisonResult;_x000D_
}_x000D_
_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_
_x000D_
_x000D_
</script>
_x000D_
then in the page i call the values like so:
<td class="tinfodd"> <script type="text/javascript">_x000D_
document.write(registrySectionId)_x000D_
</script></td>
_x000D_
I know this is an old question and the correct answer, use _blank
, has been mentioned several times, but using <a target="somesite.com" target="_blank">Link</a>
is a security risk.
It is recommended (performance benefits) to use:
<a href="somesite.com" target="_blank" rel="noopener noreferrer">Link</a>
You can use input type="reset"
<form action="/action_page.php">
text: <input type="text" name="email" /><br />
<input type="reset" defaultValue="Reset" />
</form>
Use GETDATE()
Returns the current database system timestamp as a datetime value without the database time zone offset. This value is derived from the operating system of the computer on which the instance of SQL Server is running.
UPDATE table SET date = GETDATE()
You can reference those remote tracking branches ~(listed with git branch -r
) with the name of their remote.
You need to fetch the remote branch:
git fetch origin aRemoteBranch
If you want to merge one of those remote branches on your local branch:
git checkout master
git merge origin/aRemoteBranch
Note 1: For a large repo with a long history, you will want to add the --depth=1
option when you use git fetch
.
Note 2: These commands also work with other remote repos so you can setup an origin
and an upstream
if you are working on a fork.
Note 3: user3265569 suggests the following alias in the comments:
From
aLocalBranch
, rungit combine remoteBranch
Alias:combine = !git fetch origin ${1} && git merge origin/${1}
Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:
git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch
The idea here, is to merge "one of your local branch" (here anotherLocalBranch
) to a remote branch (origin/aBranch
).
For that, you create first "myBranch
" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch
part.
And then you can merge anotherLocalBranch
to it (to myBranch
).
Do a cross-domain AJAX call
Your web-service must support method injection in order to do JSONP.
Your code seems fine and it should work if your web services and your web application hosted in the same domain.
When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.
For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do
then jQuery will add ?callback={some_random_dynamically_generated_method}.
This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:
window.some_random_dynamically_generated_method = function(actualJsonpData) {
//here actually has reference to the success function mentioned with $.ajax
//so it just calls the success method like this:
successCallback(actualJsonData);
}
Check the following for more information
I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
color: #000; /*Sets the text hover color on navbar*/
}
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
a:hover, .navbar-default .navbar-nav > .active > a:focus {
color: white; /*BACKGROUND color for active*/
background-color: #030033;
}
.navbar-default {
background-color: #0f006f;
border-color: #030033;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
color: #262626;
text-decoration: none;
background-color: #66CCFF; /*change color of links in drop down here*/
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: silver; /*Change rollover cell color here*/
}
.navbar-default .navbar-nav > li > a {
color: white; /*Change active text color here*/
}
I know it's already answered but couldn't you just synchronize the settings in the settings designer to move back to your default settings?
typeof(IMyInterface).IsAssignableFrom(typeof(MyType));
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:
[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
var value1 = model.SimpleProp1;
var value2 = model.SimpleProp2;
var value3 = model.ComplexProp1.SimpleProp1;
...
... return something ...
}
Another (obviously uglier) way is:
[HttpPost]
public ActionResult SubmitAction()
{
var value1 = Request["SimpleProp1"];
var value2 = Request["SimpleProp2"];
var value3 = Request["ComplexProp1.SimpleProp1"];
...
... return something ...
}
html
<input type="hidden" #fondovalor value="valores">
<button (click)="getFotoFondo()">Obtener</button>
ts
@ViewChild('fondovalor') fondovalor:ElementRef;
getFotoFondo(){
const valueInput = this.fondovalor.nativeElement.value
}
I happened to encounter this similar SSL problem a few days ago. The problem is your npm does not set root certificate for the certificate used by https://registry.npmjs.org.
Solutions:
wget https://registry.npmjs.org/coffee-script --ca-certificate=./DigiCertHighAssuranceEVRootCA.crt
to fix wget problemnpm config set cafile /path/to/DigiCertHighAssuranceEVRootCA.crt
to set root certificate for your npm program.you can download root certificate from : https://www.digicert.com/CACerts/DigiCertHighAssuranceEVRootCA.crt
Notice: Different program may use different way of managing root certificate, so do not mix browser's with others.
let's fix your wget https://registry.npmjs.org/coffee-script
problem first. your snippet says:
ERROR: cannot verify registry.npmjs.org's certificate, issued by /C=US/ST=CA/L=Oakland/O=npm/OU=npm Certificate Authority/CN=npmCA/[email protected]: Unable to locally verify the issuer's authority.
This means that your wget program cannot verify https://registry.npmjs.org
's certificate. There are two reasons that may cause this problem:
So the solution is explicitly set root certificate for https://registry.npmjs.org
. We can use openssl to make sure that the reason bellow is the problem.
Try openssl s_client -host registry.npmjs.org -port 443
on the command line and we will get this message (first several lines):
CONNECTED(00000003) depth=1 /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 verify error:num=20:unable to get local issuer certificate verify return:0 --- Certificate chain 0 s:/C=US/ST=California/L=San Francisco/O=Fastly, Inc./CN=a.sni.fastly.net i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 1 s:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance CA-3 i:/C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert High Assurance EV Root CA ---
This line verify error:num=20:unable to get local issuer certificate
makes sure that https://registry.npmjs.org
does not pack root certificate. So we Google DigiCert High Assurance EV Root CA
root Certificate.
Similar to other syntax above but for learning - can you sort by column names?
sort(colnames(test[1:ncol(test)] ))
If you don't want to use an external library, or store an array of month names, or if the ECMAScript Internationalization API is not good enough because of browser compatibility you can always do it the old-fashioned way by extracting the info from the date output:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
This would give you the abbreviated month name, e.g. Oct. I believe the date will come in all sorts of formats depending on the initialization and your locale so take a look at what toDateString()
returns and recalculate your substring()
values based on that.
Here is a new solution based on Bennett McElwee answer in the same question as mentioned below.
Tested with IE 9 & 10, Opera 12.01, Google Chrome 22 and Firefox 15.0.
jsFiddle example
@media screen {
#printSection {
display: none;
}
}
@media print {
body * {
visibility:hidden;
}
#printSection, #printSection * {
visibility:visible;
}
#printSection {
position:absolute;
left:0;
top:0;
}
}
function printElement(elem, append, delimiter) {
var domClone = elem.cloneNode(true);
var $printSection = document.getElementById("printSection");
if (!$printSection) {
$printSection = document.createElement("div");
$printSection.id = "printSection";
document.body.appendChild($printSection);
}
if (append !== true) {
$printSection.innerHTML = "";
}
else if (append === true) {
if (typeof (delimiter) === "string") {
$printSection.innerHTML += delimiter;
}
else if (typeof (delimiter) === "object") {
$printSection.appendChild(delimiter);
}
}
$printSection.appendChild(domClone);
}?
You're ready to print any element on your site!
Just call printElement()
with your element(s) and execute window.print()
when you're finished.
Note: If you want to modify the content before it is printed (and only in the print version), checkout this example (provided by waspina in the comments): http://jsfiddle.net/95ezN/121/
One could also use CSS in order to show the additional content in the print version (and only there).
I think, you have to hide all other parts of the site via CSS.
It would be the best, to move all non-printable content into a separate DIV
:
<body>
<div class="non-printable">
<!-- ... -->
</div>
<div class="printable">
<!-- Modal dialog comes here -->
</div>
</body>
And then in your CSS:
.printable { display: none; }
@media print
{
.non-printable { display: none; }
.printable { display: block; }
}
Credits go to Greg who has already answered a similar question: Print <div id="printarea"></div> only?
There is one problem in using JavaScript: the user cannot see a preview - at least in Internet Explorer!
try
<div style='overflow:auto; width:400px;height:400px;'>here is some text</div>
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Bootstrap 3 I achieved a nice responsive form layout using the following:
<div class="row">
<div class="form-group col-sm-4">
<label for=""> Date</label>
<input type="date" class="form-control" id="date" name="date" placeholder=" date">
</div>
<div class="form-group col-sm-4">
<label for="hours">Hours</label>
<input type="" class="form-control" id="hours" name="hours" placeholder="Total hours">
</div>
</div>
The reason for your confusion is probably that the Visitor is a fatal misnomer. Many (prominent1!) programmers have stumbled over this problem. What it actually does is implement double dispatching in languages that don't support it natively (most of them don't).
1) My favourite example is Scott Meyers, acclaimed author of “Effective C++”, who called this one of his most important C++ aha! moments ever.
It is pretty easy to add a collaborator to a free plan.
The added user should now be able to push to your repository on GitHub.
On a LAMP environment the php errors are default directed to this below file.
/var/log/httpd/error_log
All access logs come under:
/var/log/httpd/access_log
Add this function in your js file. It will work on every browser
$(function() {_x000D_
$(document).on("click", '#mydiv', function() {_x000D_
alert("You have just clicked on ");_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id='mydiv'>Div</div>
_x000D_
You could use:
Dim MyForm As New Form1
MyForm.Show()
or rather:
MyForm.ShowDialog()
to open the form as a dialog box to ensure that user interacts with the new form or closes it.
You will also get this if git doesn't have permissions to read the config files. It will just go up in the hierarchy tree until it needs to cross file systems.
The difference between 'exec' and 'system' is that exec replaces your current program with 'command' and NEVER returns to your program. system, on the other hand, forks and runs 'command' and returns you the exit status of 'command' when it is done running. The back tick runs 'command' and then returns a string representing its standard out (whatever it would have printed to the screen)
You can also use popen to run shell commands and I think that there is a shell module - 'use shell' that gives you transparent access to typical shell commands.
Hope that clarifies it for you.
You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:
"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html
You should either write or download a little tool that will allow you to generate config files from placeholder config files.
Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.
e.g. my nginx source config file looks like this:
location / {
try_files $uri /routing.php?$args;
fastcgi_pass unix:%phpfpm.socket%/php-fpm-www.sock;
include %mysite.root.directory%/conf/fastcgi.conf;
}
And then I have a config file with the variables defined:
phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite
And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:
<?php
require_once('path.php');
$filesToGenerate = array(
'conf/nginx.conf' => 'autogen/nginx.conf',
'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
'conf/my.cnf' => 'autogen/my.cnf',
);
$environment = 'amazonec2';
if ($argc >= 2){
$environmentRequired = $argv[1];
$allowedVars = array(
'amazonec2',
'macports',
);
if (in_array($environmentRequired, $allowedVars) == true){
$environment = $environmentRequired;
}
}
else{
echo "Defaulting to [".$environment."] environment";
}
$config = getConfigForEnvironment($environment);
foreach($filesToGenerate as $inputFilename => $outputFilename){
generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}
function getConfigForEnvironment($environment){
$config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
$configWithMarkers = array();
foreach($config[$environment] as $key => $value){
$configWithMarkers['%'.$key.'%'] = $value;
}
return $configWithMarkers;
}
function generateConfigFile($inputFilename, $outputFilename, $config){
$lines = file($inputFilename);
if($lines === FALSE){
echo "Failed to read [".$inputFilename."] for reading.";
exit(-1);
}
$fileHandle = fopen($outputFilename, "w");
if($fileHandle === FALSE){
echo "Failed to read [".$outputFilename."] for writing.";
exit(-1);
}
$search = array_keys($config);
$replace = array_values($config);
foreach($lines as $line){
$line = str_replace($search, $replace, $line);
fwrite($fileHandle, $line);
}
fclose($fileHandle);
}
?>
And then deployConfig.ini looks something like:
[global]
;global variables go here.
[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory = /var/run
nginx.user = nginx
[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory = /opt/local/var/run
nginx.user = _www
Use empty
(it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"
If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:
styleClass="#{empty obj.validationErrorMap ? ' ' :
(obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"
Update: as per the comments, the Map
turns out to actually be a List
(please work on your naming conventions). To check if a List
contains an item the "normal" EL way, use JSTL fn:contains
(although not explicitly documented, it works for List
as well).
styleClass="#{empty obj.validationErrorMap ? ' ' :
(fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"
Before MySQL 5.6 Full-Text Search is supported only with MyISAM Engine.
Therefore either change the engine for your table to MyISAM
CREATE TABLE gamemech_chat (
id bigint(20) unsigned NOT NULL auto_increment,
from_userid varchar(50) NOT NULL default '0',
to_userid varchar(50) NOT NULL default '0',
text text NOT NULL,
systemtext text NOT NULL,
timestamp datetime NOT NULL default '0000-00-00 00:00:00',
chatroom bigint(20) NOT NULL default '0',
PRIMARY KEY (id),
KEY from_userid (from_userid),
FULLTEXT KEY from_userid_2 (from_userid),
KEY chatroom (chatroom),
KEY timestamp (timestamp)
) ENGINE=MyISAM;
Here is SQLFiddle demo
or upgrade to 5.6 and use InnoDB Full-Text Search.
The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.
Do not do it. I might want to run my car on monkey blood. I have my reasons, but sometimes it's better to stick with using things the way they were designed even if it doesn't "absolutely perfectly" match the exact look you are driving for.
To back up my argument I submit the following.
onclick="location.href"
model. (This is a real-life production example from my predecessor) This can make users hesitant to click on the link, since they have no idea where it is taking them, for starters.You are also making Search engine optimization more difficult IMO as well as making the debugging and reading of your code/HTML more complex. A submit button should submit a form. Why should you(the development community) try to create a non-standard UI?
Edit: As in a comment rightly requested here some more information. Use the include
tag
<include
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/yourlayout" />
to include the layout you want to reuse.
Check this link out...
<uses-permission android:name="android.permission.INTERNET"/>
add this tag above into AndroidManifest.xml of your Android project
,and it will be ok.
You can find the full list here.
\t
Insert a tab in the text at this point.\b
Insert a backspace in the text at this point.\n
Insert a newline in the text at this point.\r
Insert a carriage return in the text at this point.\f
Insert a formfeed in the text at this point.\'
Insert a single quote character in the text at this point.\"
Insert a double quote character in the text at this point.\\
Insert a backslash character in the text at this point.Use HTTP Basic Auth to authenticate clients, but treat username/password only as temporary session token.
The session token is just a header attached to every HTTP request, eg: Authorization: Basic Ym9ic2Vzc2lvbjE6czNjcmV0
The string Ym9ic2Vzc2lvbjE6czNjcmV0 above is just the string "bobsession1:s3cret" (which is a username/password) encoded in Base64.
To obtain the temporary session token above, provide an API function (eg: http://mycompany.com/apiv1/login
) which takes master-username and master-password as an input, creates a temporary HTTP Basic Auth username / password on the server side, and returns the token (eg: Ym9ic2Vzc2lvbjE6czNjcmV0). This username / password should be temporary, it should expire after 20min or so.
For added security ensure your REST service are served over HTTPS so that information are not transferred plaintext
If you're on Java, Spring Security library provides good support to implement above method
This is a simple example of what I used for a recent test. You need to make sure that your security settings are the same on the server and client.
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.None;
var myEndpointAddress = new EndpointAddress("http://servername:8732/TestService/");
client = new ClientTest(myBinding, myEndpointAddress);
client.someCall();
select
relname as table
from
pg_stat_user_tables
where schemaname = 'public'
select
tablename as table
from
pg_tables
where schemaname = 'public'
For PySpark, you can also set the log level in your scripts with sc.setLogLevel("FATAL")
. From the docs:
Control our logLevel. This overrides any user-defined log settings. Valid log levels include: ALL, DEBUG, ERROR, FATAL, INFO, OFF, TRACE, WARN
@jmnas, I liked your answer, but it didn't find floats. I'm working on a script to parse code going to a CNC mill and needed to find both X and Y dimensions that can be integers or floats, so I adapted your code to the following. This finds int, float with positive and negative vals. Still doesn't find hex formatted values but you could add "x" and "A" through "F" to the num_char
tuple and I think it would parse things like '0x23AC'.
s = 'hello X42 I\'m a Y-32.35 string Z30'
xy = ("X", "Y")
num_char = (".", "+", "-")
l = []
tokens = s.split()
for token in tokens:
if token.startswith(xy):
num = ""
for char in token:
# print(char)
if char.isdigit() or (char in num_char):
num = num + char
try:
l.append(float(num))
except ValueError:
pass
print(l)
There is one little catch with the third approach. Since aggregate POMs (myproject/pom.xml) usually don't have parent at all, they do not share configuration. That means all those aggregate POMs will have only default repositories.
That is not a problem if you only use plugins from Central, however, this will fail if you run plugin using the plugin:goal format from your internal repository. For example, you can have foo-maven-plugin
with the groupId of org.example
providing goal generate-foo
. If you try to run it from the project root using command like mvn org.example:foo-maven-plugin:generate-foo
, it will fail to run on the aggregate modules (see compatibility note).
Several solutions are possible:
I have written a program to iterate all Threads
created and printing getState()
of each Thread
import java.util.Set;
public class ThreadStatus {
public static void main(String args[]) throws Exception{
for ( int i=0; i< 5; i++){
Thread t = new Thread(new MyThread());
t.setName("MyThread:"+i);
t.start();
}
int threadCount = 0;
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
for ( Thread t : threadSet){
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup()){
System.out.println("Thread :"+t+":"+"state:"+t.getState());
++threadCount;
}
}
System.out.println("Thread count started by Main thread:"+threadCount);
}
}
class MyThread implements Runnable{
public void run(){
try{
Thread.sleep(2000);
}catch(Exception err){
err.printStackTrace();
}
}
}
Output:
java ThreadStatus
Thread :Thread[MyThread:0,5,main]:state:TIMED_WAITING
Thread :Thread[main,5,main]:state:RUNNABLE
Thread :Thread[MyThread:1,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:4,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:2,5,main]:state:TIMED_WAITING
Thread :Thread[MyThread:3,5,main]:state:TIMED_WAITING
Thread count started by Main thread:6
If you remove below condition
if ( t.getThreadGroup() == Thread.currentThread().getThreadGroup())
You will get below threads in output too, which have been started by system.
Reference Handler, Signal Dispatcher,Attach Listener and Finalizer
.
If constraint on column STATUS was created without a name during creating a table, Oracle will assign a random name for it. Unfortunately, we cannot modify the constraint directly.
Steps involved of dropping unnamed constraint linked to column STATUS
Rename STATUS2 to STATUS
ALTER TABLE MY_TABLE ADD STATUS2 NVARCHAR2(10) DEFAULT 'OPEN';
ALTER TABLE MY_TABLE ADD CONSTRAINT MY_TABLE_CHECK_STATUS CHECK (STATUS2 IN ('OPEN', 'CLOSED'));
UPDATE MY_TABLE SET STATUS2 = STATUS;
ALTER TABLE MY_TABLE DROP COLUMN STATUS;
ALTER TABLE MY_TABLE RENAME COLUMN STATUS2 TO STATUS;
Ran into the diagram while looking at key-value coding, thought it might help someone. It helps with understanding of what IBOutlet is.
By looking at the flow, one could see that IBOutlets are only there to match the property name with a control name in the Nib file.
This will cause Lint to ignore the missing translation error for ALL strings in the file, yet other string resource files can be verified if needed.
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation">
Accessing dynamically multi levels object.
var obj = {
name: "john doe",
subobj: {
subsubobj: {
names: "I am sub sub obj"
}
}
};
var level = "subobj.subsubobj.names";
level = level.split(".");
var currentObjState = obj;
for (var i = 0; i < level.length; i++) {
currentObjState = currentObjState[level[i]];
}
console.log(currentObjState);
Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/
Swift 2.0
extension Dictionary {
mutating func unionInPlace(dictionary: Dictionary) {
dictionary.forEach { self.updateValue($1, forKey: $0) }
}
func union(var dictionary: Dictionary) -> Dictionary {
dictionary.unionInPlace(self)
return dictionary
}
}
Try this one, I assure you that it will work perfectly.
import scipy.optimize as opt
from numpy import exp
import timeit
st1 = timeit.default_timer()
def f(variables) :
(x,y) = variables
first_eq = x + y**2 -4
second_eq = exp(x) + x*y - 3
return [first_eq, second_eq]
solution = opt.fsolve(f, (0.1,1) )
print(solution)
st2 = timeit.default_timer()
print("RUN TIME : {0}".format(st2-st1))
->
[ 0.62034452 1.83838393]
RUN TIME : 0.0009331008900937708
FYI. as mentioned above, you can also use 'Broyden's approximation' by replacing 'fsolve' with 'broyden1'. It works. I did it.
I don't know exactly how Broyden's approximation works, but it took 0.02 s.
And I recommend you do not use Sympy's functions <- convenient indeed, but in terms of speed, it's quite slow. You will see.
system
The system
method calls a system program. You have to provide the command as a string argument to this method. For example:
>> system("date")
Wed Sep 4 22:03:44 CEST 2013
=> true
The invoked program will use the current STDIN
, STDOUT
and STDERR
objects of your Ruby program. In fact, the actual return value is either true
, false
or nil
. In the example the date was printed through the IO object of STDIN
. The method will return true
if the process exited with a zero status, false
if the process exited with a non-zero status and nil
if the execution failed.
As of Ruby 2.6, passing exception: true
will raise an exception instead of returning false
or nil
:
>> system('invalid')
=> nil
>> system('invalid', exception: true)
Traceback (most recent call last):
...
Errno::ENOENT (No such file or directory - invalid)
Another side effect is that the global variable $?
is set to a Process::Status
object. This object will contain information about the call itself, including the process identifier (PID) of the invoked process and the exit status.
>> system("date")
Wed Sep 4 22:11:02 CEST 2013
=> true
>> $?
=> #<Process::Status: pid 15470 exit 0>
Backticks
Backticks (``) call a system program and return its output. As opposed to the first approach, the command is not provided through a string, but by putting it inside a backticks pair.
>> `date`
=> Wed Sep 4 22:22:51 CEST 2013
The global variable $?
is set through the backticks, too. With backticks you can also make use string interpolation.
%x()
Using %x
is an alternative to the backticks style. It will return the output, too. Like its relatives %w
and %q
(among others), any delimiter will suffice as long as bracket-style delimiters match. This means %x(date)
, %x{date}
and %x-date-
are all synonyms. Like backticks %x
can make use of string interpolation.
exec
By using Kernel#exec
the current process (your Ruby script) is replaced with the process invoked through exec
. The method can take a string as argument. In this case the string will be subject to shell expansion. When using more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.
Open3.popen3
Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here Open3.popen3
comes in handy:
require 'open3'
Open3.popen3("curl http://example.com") do |stdin, stdout, stderr, thread|
pid = thread.pid
puts stdout.read.chomp
end
Just clear the clipboard before closing.
Application.CutCopyMode=False
ActiveWindow.Close
First of all you should stop using mysql_*. MySQL supports multiple inserting like
INSERT INTO example
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You just have to build one string in your foreach loop which looks like that
$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";
and then insert it after the loop
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;
Another way would be Prepared Statements, which are even more suited for your situation.
Try to clean and rebuild the project. I had the absolutely same question, this solved it.
Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.
# make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))
# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)
# Make a vector of thresholds 'Brks' to colour code z
Brks <- c(seq(0,18,3),Inf)
# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')
# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")
# Make up lookup dataframe 'LkUp' of the lables and colours
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)
# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))
# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')
# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
Grd$Var2,
xlim = c(0,400),
ylim = c(0,400),
cex = 1.0,
col = Grd$Clrs,
pch = 20,
xlab = 'mX',
ylab = 'mY',
main = 'My Grid',
axes = FALSE,
labels = FALSE,
las = 1
)
axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')
legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')
Try using string.Contains () combined with EndsWith.
var results = from c in db.Customers
where c.FullName.Contains (FirstName) && c.FullName.EndsWith (LastName)
select c;
lista = list.sort(lista)
This should be
lista.sort()
The .sort()
method is in-place, and returns None. If you want something not in-place, which returns a value, you could use
sorted_list = sorted(lista)
Aside #1: please don't call your lists list
. That clobbers the builtin list type.
Aside #2: I'm not sure what this line is meant to do:
print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")
is it simply
print "value 1a + value 2 = value 3a value 4"
? In other words, I don't know why you're calling str on things which are already str.
Aside #3: sometimes you use print("something")
(Python 3 syntax) and sometimes you use print "something"
(Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..
The exception TypeError: 'NoneType' object is not subscriptable
happens because the value of lista
is actually None
. You can reproduce TypeError
that you get in your code if you try this at the Python command line:
None[0]
The reason that lista
gets set to None is because the return value of list.sort()
is None
... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).
If you do not want to alter the original version you can use
other_list = sorted(lista)
Even though it's too late, I'd like to give my input on this as it might clarify why the solution given by JB Nizet works. I stumbled upon this little problem working on a byte parser and to string conversion myself. When you copy from a bigger size integral type to a smaller size integral type as this java doc says this happens:
https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.3 A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.
You can be sure that a byte is an integral type as this java doc says https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html byte: The byte data type is an 8-bit signed two's complement integer.
So in the case of casting an integer(32 bits) to a byte(8 bits), you just copy the last (least significant 8 bits) of that integer to the given byte variable.
int a = 128;
byte b = (byte)a; // Last 8 bits gets copied
System.out.println(b); // -128
Second part of the story involves how Java unary and binary operators promote operands. https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2 Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:
If either operand is of type double, the other is converted to double.
Otherwise, if either operand is of type float, the other is converted to float.
Otherwise, if either operand is of type long, the other is converted to long.
Otherwise, both operands are converted to type int.
Rest assured, if you are working with integral type int and/or lower it'll be promoted to an int.
// byte b(0x80) gets promoted to int (0xFF80) by the & operator and then
// 0xFF80 & 0xFF (0xFF translates to 0x00FF) bitwise operation yields
// 0x0080
a = b & 0xFF;
System.out.println(a); // 128
I scratched my head around this too :). There is a good answer for this here by rgettman. Bitwise operators in java only for integer and long?
I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.
$(function() {
$('.datetimepicker').datetimepicker({
format: 'MM-DD-YYYY HH:mm '
});
});
In GitHub markdown <ins>
text</ins>
works just fine.
The Decimal value type represents decimal numbers ranging from positive 79,228,162,514,264,337,593,543,950,335 to negative 79,228,162,514,264,337,593,543,950,335. The Decimal value type is appropriate for financial calculations requiring large numbers of significant integral and fractional digits and no round-off errors. The Decimal type does not eliminate the need for rounding. Rather, it minimizes errors due to rounding.
I'd like to point to this excellent answer by zneak on why double shouldn't be used.
The tool that richardtz suggests is excellent.
Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.
You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge
Here is what I used to fade in/out Views, hope this helps someone.
private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
AnimatorSet mAnimationSet = new AnimatorSet();
ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA, 1f, 0f);
fadeOut.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
fadeOutTarget.setVisibility(View.GONE);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
fadeOut.setInterpolator(new LinearInterpolator());
ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
fadeIn.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
fadeInTarget.setVisibility(View.VISIBLE);
}
@Override
public void onAnimationEnd(Animator animation) {}
@Override
public void onAnimationCancel(Animator animation) {}
@Override
public void onAnimationRepeat(Animator animation) {}
});
fadeIn.setInterpolator(new LinearInterpolator());
mAnimationSet.setDuration(duration);
mAnimationSet.playTogether(fadeOut, fadeIn);
mAnimationSet.start();
}
Just added ignore: []
in the specific page for the specific form, this solution worked for me.
$("#form_name").validate({
ignore: [],
onkeyup: false,
rules: {
},
highlight:false,
});
An important difference between numpy array and list is that array slices are views on the original array. This means that the data is not copied, and any modifications to the view will be reflected in the source array.
Answer has been updated
count
is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:
$wordCount = count($wordlist);
If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count
method. Example:
$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();
There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478
However as of now, the query builder always returns an array.
Edit: As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:
$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
$wordCount = $wordlist->count();
However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:
// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->count();
// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();
The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.
int[,] list = new int[4,4] {
{1,2,3,4},
{5,6,7,8},
{1,3,2,1},
{5,4,3,2}};
You could also do
int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };
int[,] lists = new int[4,4] {
{list1[0],list1[1],list1[2],list1[3]},
{list2[0],list2[1],list2[2],list2[3]},
etc...};
Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters
JUST THIS WORKS!!
take care about your file name uppercase in tag and put PNG file inroot, and link to the filename without any path:
![Screenshot](screenshot.png)
You can use date filter to convert in date and display in specific format.
In .ts file (typescript):
let dateString = '1968-11-16T00:00:00'
let newDate = new Date(dateString);
In HTML:
{{dateString | date:'MM/dd/yyyy'}}
Below are some formats which you can implement :
Backend:
public todayDate = new Date();
HTML :
<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option>
</select>
I was getting the same error, even after following Google's guide at https://developers.google.com/drive/api/v3/quickstart/python, then I realized I had to invoke like this:
python3 quickstart.py
Instead of:
python quickstart.py <-- WRONG
(Note the "3
")
Worked flawlessly.
I'm using Ubuntu 18.04.4 LTS
.
This is an old post, but I had a similar need and this is the solution I came up with. It is a bit of a hack, but it works and could be refined.
require 'erb'
require 'yaml'
doc = <<-EOF
theme:
name: default
css_path: compiled/themes/<%= data['theme']['name'] %>
layout_path: themes/<%= data['theme']['name'] %>
image_path: <%= data['theme']['css_path'] %>/images
recursive_path: <%= data['theme']['image_path'] %>/plus/one/more
EOF
data = YAML::load("---" + doc)
template = ERB.new(data.to_yaml);
str = template.result(binding)
while /<%=.*%>/.match(str) != nil
str = ERB.new(str).result(binding)
end
puts str
A big downside is that it builds into the yaml document a variable name (in this case, "data") that may or may not exist. Perhaps a better solution would be to use $ and then substitute it with the variable name in Ruby prior to ERB. Also, just tested using hashes2ostruct which allows data.theme.name type notation which is much easier on the eyes. All that is required is to wrap the YAML::load with this
data = hashes2ostruct(YAML::load("---" + doc))
Then your YAML document can look like this
doc = <<-EOF
theme:
name: default
css_path: compiled/themes/<%= data.theme.name %>
layout_path: themes/<%= data.theme.name %>
image_path: <%= data.theme.css_path %>/images
recursive_path: <%= data.theme.image_path %>/plus/one/more
EOF
If you are using visual studio 2005 then
public void sumAverageElements(int[] arr)
{
int size =arr.Length;
int sum = 0;
int average = 0;
for (int i = 0; i < size; i++)
{
sum += arr[i];
}
average = sum / size; // sum divided by total elements in array
Console.WriteLine("The Sum Of Array Elements Is : " + sum);
Console.WriteLine("The Average Of Array Elements Is : " + average);
}
One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.
private boolean switchComponents;
public boolean isSwitchComponents() {
return switchComponents;
}
public void setSwitchComponents(boolean switchComponents) {
this.switchComponents = switchComponents;
}
When the switch is true, one set of components will be shown and when it is false the other set will be shown.
<h:selectOneRadio value="#{backbean.switchValue}">
<f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
<f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
<f:ajax event="change" execute="@this" render="componentsRoot"/>
</h:selectOneRadio>
<H:panelGroup id="componentsRoot">
<h:panelGroup rendered="#{backbean.switchValue}">
<!--switchValue to be shown on switch value == true-->
</h:panelGroup>
<h:panelGroup rendered="#{!backbean.switchValue}">
<!--switchValue to be shown on switch value == false-->
</h:panelGroup>
</H:panelGroup>
Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.
Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).
Add-on software packages.
See http://www.pathname.com/fhs/2.2/fhs-3.12.html for details.
Also described at Wikipedia.
Its use dates back at least to the late 1980s, when it was a standard part of System V UNIX. These days, it's also seen in Linux, Solaris (which is SysV), OSX Cygwin, etc. Other BSD unixes (FreeBSD, NetBSD, etc) tend to follow other rules, so you don't usually see BSD systems with an /opt unless they're administered by someone who is more comfortable in other environments.
I solved the issue by removing "type": "module"
field from package.json
.
Please do right click on the project and go to properties. Then go to Build and Packaging. You can see the JAR file location that is produced by defualt setting of netbean in the dist directory.
You can do it with initializer list:
std::vector<unsigned int> array;
// First argument is an iterator to the element BEFORE which you will insert:
// In this case, you will insert before the end() iterator, which means appending value
// at the end of the vector.
array.insert(array.end(), { 1, 2, 3, 4, 5, 6 });
(Additional step from solution above for if you are missing the AutoReconnect or Offline registry value)
For Visual Studio 2015, Version 14
Additional info: blog MSDN - When and how does my solution go offline?
Or:
SELECT SUM(foo), DATE(mydate) mydate FROM a_table GROUP BY mydate;
More efficient (I think.) Because you don't have to cast mydate twice per row.
You have the color you just need to convert it into the format you want.
Here's a script that should do the trick: http://www.phpied.com/rgb-color-parser-in-javascript/
OK some answers about malloc were already posted.
The more interesting part is how free works (and in this direction, malloc too can be understood better).
In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).
So returning 40 Bytes to the OS will just not work. So what does free do?
Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.
The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.
There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.
Why does your code crash:
The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.
This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!
Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.
What kind of query do you perform? Using ExecuteNonQuery
is intended for UPDATE
, INSERT
and DELETE
queries. As per the documentation:
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.
You need to commit at least one time on master before creating a new branch.
@Drew Baker gave a great solution to solve the problem. The code works properly. However, those who uses AngularJs may find lots of dependency on jQuery. Consequently, I thought it is a good idea to paste for AngularJS users, a code following @Drew Baker's solution.
AngularJs way of the same code
1. Html: use the bellow tag in you html file:
<svg-image src="/icons/my.svg" class="any-class-you-wish"></svg-image>
2. Directive: this will be the directive that you will need to recognise the tag:
'use strict';
angular.module('myApp')
.directive('svgImage', ['$http', function($http) {
return {
restrict: 'E',
link: function(scope, element) {
var imgURL = element.attr('src');
// if you want to use ng-include, then
// instead of the above line write the bellow:
// var imgURL = element.attr('ng-include');
var request = $http.get(
imgURL,
{'Content-Type': 'application/xml'}
);
scope.manipulateImgNode = function(data, elem){
var $svg = angular.element(data)[4];
var imgClass = elem.attr('class');
if(typeof(imgClass) !== 'undefined') {
var classes = imgClass.split(' ');
for(var i = 0; i < classes.length; ++i){
$svg.classList.add(classes[i]);
}
}
$svg.removeAttribute('xmlns:a');
return $svg;
};
request.success(function(data){
element.replaceWith(scope.manipulateImgNode(data, element));
});
}
};
}]);
3. CSS:
.any-class-you-wish{
border: 1px solid red;
height: 300px;
width: 120px
}
4. Unit-test with karma-jasmine:
'use strict';
describe('Directive: svgImage', function() {
var $rootScope, $compile, element, scope, $httpBackend, apiUrl, data;
beforeEach(function() {
module('myApp');
inject(function($injector) {
$rootScope = $injector.get('$rootScope');
$compile = $injector.get('$compile');
$httpBackend = $injector.get('$httpBackend');
apiUrl = $injector.get('apiUrl');
});
scope = $rootScope.$new();
element = angular.element('<svg-image src="/icons/icon-man.svg" class="svg"></svg-image>');
element = $compile(element)(scope);
spyOn(scope, 'manipulateImgNode').andCallThrough();
$httpBackend.whenGET(apiUrl + 'me').respond(200, {});
data = '<?xml version="1.0" encoding="utf-8"?>' +
'<!-- Generator: Adobe Illustrator 17.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->' +
'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
'<!-- Obj -->' +
'<!-- Obj -->' +
'<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"' +
'width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve">' +
'<g>' +
'<path fill="#F4A902" d=""/>' +
'<path fill="#F4A902" d=""/>' +
'</g>' +
'</svg>';
$httpBackend.expectGET('/icons/icon-man.svg').respond(200, data);
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should call manipulateImgNode atleast once', function () {
$httpBackend.flush();
expect(scope.manipulateImgNode.callCount).toBe(1);
});
it('should return correct result', function () {
$httpBackend.flush();
var result = scope.manipulateImgNode(data, element);
expect(result).toBeDefined();
});
it('should define classes', function () {
$httpBackend.flush();
var result = scope.manipulateImgNode(data, element);
var classList = ["svg"];
expect(result.classList[0]).toBe(classList[0]);
});
});
Just to clarify a few things, System.Web.Optimization
(aka Bundling/Minification) will work against 4.0. It is not depending on anything in 4.5, so there should be no problems there.
If script bundling is working, and its only an issue with CSS, perhaps the issue is with relative URLs?
I'd first look at the rendered page and see if you are getting references to the CSS bundle, i.e. something like:
<link href="/app/Content/css?v=oI5uNwN5NWmYrn8EXEybCI" rel="stylesheet"/>
If you are, then bundling is working, but something inside your CSS bundle is messed up. Usually this is due to relative URLs inside your CSS bundle being incorrect, i.e. if your images live under ~/Content, but you name your bundle ~/bundles/css
, the browser will incorrectly look for images under ~/bundles
.
Also, the default behavior is to disable bundling and minification when debug=true
. So, if you do want optimizations enabled even when debug=true
, you will need to force:
BundleTable.EnableOptimizations = true
Updated: With the new info that v=""
, that means the bundle was empty, you should verify that you are adding files to the bundle correctly, and that it found them. How are you including files to the bundle?
This is the correct way to do it
In trying to avoid experimental and frankly fed up with the NDK and all its hackery I am happy that 2.2.x of the Gradle Build Tools came out and now it just works. The key is the externalNativeBuild
and pointing ndkBuild
path argument at an Android.mk
or change ndkBuild
to cmake
and point the path argument at a CMakeLists.txt
build script.
android {
compileSdkVersion 19
buildToolsVersion "25.0.2"
defaultConfig {
minSdkVersion 19
targetSdkVersion 19
ndk {
abiFilters 'armeabi', 'armeabi-v7a', 'x86'
}
externalNativeBuild {
cmake {
cppFlags '-std=c++11'
arguments '-DANDROID_TOOLCHAIN=clang',
'-DANDROID_PLATFORM=android-19',
'-DANDROID_STL=gnustl_static',
'-DANDROID_ARM_NEON=TRUE',
'-DANDROID_CPP_FEATURES=exceptions rtti'
}
}
}
externalNativeBuild {
cmake {
path 'src/main/jni/CMakeLists.txt'
}
//ndkBuild {
// path 'src/main/jni/Android.mk'
//}
}
}
For much more detail check Google's page on adding native code.
After this is setup correctly you can ./gradlew installDebug
and off you go. You will also need to be aware that the NDK is moving to clang since gcc is now deprecated in the Android NDK.
You could also use jOOL library - https://github.com/jOOQ/jOOL
It has already prepared function interfaces with different number of parameters. For instance, you could use org.jooq.lambda.function.Function3
, etc from Function0
up to Function16
.
Try this:
printf '\n%s\n' 'I want this on a new line!'
That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.
quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f %s\n' "$quantity" "$price" "$description"
38 142.15 advanced widget
The regex you need is /(.)\1{9,}/
.
Test:
#!perl
use warnings;
use strict;
my $regex = qr/(.)\1{9,}/;
print "NO" if "abcdefghijklmno" =~ $regex;
print "YES" if "------------------------" =~ $regex;
print "YES" if "========================" =~ $regex;
Here the \1
is called a backreference. It references what is captured by the dot .
between the brackets (.)
and then the {9,}
asks for nine or more of the same character. Thus this matches ten or more of any single character.
Although the above test script is in Perl, this is very standard regex syntax and should work in any language. In some variants you might need to use more backslashes, e.g. Emacs would make you write \(.\)\1\{9,\}
here.
If a whole string should consist of 9 or more identical characters, add anchors around the pattern:
my $regex = qr/^(.)\1{9,}$/;
IntelliJ has no option to click on a file and choose "Add to .gitignore" like Eclipse has.
The quickest way to add a file or folder to .gitignore without typos is:
Additional info: There is a .ignore plugin available for IntelliJ which adds a "Add to .gitignore" item to the popup menu when you right-click a file. It works like a charm.
We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:
var fs = require('fs');
var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();
\r\n
is used for the new Line.
\n
won't help. Please refer this
Here is one implementation of ArraySize
from Google Protobuf.
#define GOOGLE_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
// test codes...
char* ptr[] = { "you", "are", "here" };
int testarr[] = {1, 2, 3, 4};
cout << GOOGLE_ARRAYSIZE(testarr) << endl;
cout << GOOGLE_ARRAYSIZE(ptr) << endl;
ARRAYSIZE(arr) works by inspecting sizeof(arr) (the # of bytes in the array) and sizeof(*(arr)) (the # of bytes in one array element). If the former is divisible by the latter, perhaps arr is indeed an array, in which case the division result is the # of elements in the array. Otherwise, arr cannot possibly be an array, and we generate a compiler error to prevent the code from compiling.
Since the size of bool is implementation-defined, we need to cast !(sizeof(a) & sizeof(*(a))) to size_t in order to ensure the final result has type size_t.
This macro is not perfect as it wrongfully accepts certain pointers, namely where the pointer size is divisible by the pointee size. Since all our code has to go through a 32-bit compiler, where a pointer is 4 bytes, this means all pointers to a type whose size is 3 or greater than 4 will be (righteously) rejected.
You can also use it in named_scope if You want to put there others conditions
for example include some other model:
named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }
public class ListOfLists<T> : List<List<T>>
{
}
var myList = new ListOfLists<string>();
Can I include GPL licensed code in a MIT licensed product?
You can. GPL is free software as well as MIT is, both licenses do not restrict you to bring together the code where as "include" is always two-way.
In copyright for a combined work (that is two or more works form together a work), it does not make much of a difference if the one work is "larger" than the other or not.
So if you include GPL licensed code in a MIT licensed product you will at the same time include a MIT licensed product in GPL licensed code as well.
As a second opinion, the OSI listed the following criteria (in more detail) for both licenses (MIT and GPL):
Both allow the creation of combined works, which is what you've been asking for.
If combining the two works is considered being a derivate, then this is not restricted as well by both licenses.
And both licenses do not restrict to distribute the software.
It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.
The GPL doesn't require you to release your modifications only because you made them. That's not precise.
You might mix this with distribiution of software under GPL which is not what you've asked about directly.
Is that correct - is the GPL is more restrictive than the MIT license?
This is how I understand it:
As far as distribution counts, you need to put the whole package under GPL. MIT code inside of the package will still be available under MIT whereas the GPL applies to the package as a whole if not limited by higher rights.
"Restrictive" or "more restrictive" / "less restrictive" depends a lot on the point of view. For a software-user the MIT might result in software that is more restricted than the one available under GPL even some call the GPL more restrictive nowadays. That user in specific will call the MIT more restrictive. It's just subjective to say so and different people will give you different answers to that.
As it's just subjective to talk about restrictions of different licenses, you should think about what you would like to achieve instead:
As long as you're the author it's you who can decide.
So the most restrictive person ever is the author, regardless of which license anybody is opting for ;)
[attr.disabled]="valid == true ? true : null"
You have to use null
to remove attr from html element.
This code works well :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
var options = {};
$("#c").hide();
$("#d").hide();
$("#a").click(function(){
$("#c").toggle( "slide", options, 500 );
$("#d").hide();
});
$("#b").click(function(){
$("#d").toggle( "slide", options, 500 );
$("#c").hide();
});
});
</script>
<style>
nav{
float:left;
max-width:300px;
width:300px;
margin-top:100px;
}
article{
margin-top:100px;
height:100px;
}
#c,#d{
padding:10px;
border:1px solid olive;
margin-left:100px;
margin-top:100px;
background-color:blue;
}
button{
border:2px solid blue;
background-color:white;
color:black;
padding:10px;
}
</style>
</head>
<body>
<header>
<center>hi</center>
</header>
<nav>
<button id="a">Register 1</button>
<br>
<br>
<br>
<br>
<button id="b">Register 2</button>
</nav>
<article id="c">
<form>
<label>User name:</label>
<input type="text" name="123" value="something"/>
<br>
<br>
<label>Password:</label>
<input type="text" name="456" value="something"/>
</form>
</article>
<article id="d">
<p>Hi</p>
</article>
</body>
</html>
Reference:W3schools.com and jqueryui.com
Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.
aws s3 cp s3://source_folder/ s3://destination_folder/ --recursive
aws s3 rm s3://source_folder --recursive
function getTime(offset)
{
var d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
// obtain UTC time in msec
utc = localTime + localOffset;
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
//nd = 3600000 + nd;
utc = new Date(utc);
// return time as a string
$("#local").html(nd.toLocaleString());
$("#utc").html(utc.toLocaleString());
}
You can't. With inline styles you are targeting the element directly. You can't use other selectors there.
What you can do however is define different classes in your stylesheet that define different colours and then add the class to the element.
as you can see on the answer to this question: Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
I would use serialize()
or json_encode()
.
While it won't give your the exact result string you want, it would be much easier to encode/store/retrieve/decode later on.
I believe the way to do this is $location.url('/RouteTo/Login');
Edit for Clarity
Say my route for my login view was /Login
, I would say $location.url('/Login')
to navigate to that route.
For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:
window.location = "http://www.my-domain.com/login"
The model presents a placeholder to hold the information you want to display on the view. It could be a string, which is in your above example, or it could be an object containing bunch of properties.
Example 1
If you have...
return new ModelAndView("welcomePage","WelcomeMessage","Welcome!");
... then in your jsp, to display the message, you will do:-
Hello Stranger! ${WelcomeMessage} // displays Hello Stranger! Welcome!
Example 2
If you have...
MyBean bean = new MyBean();
bean.setName("Mike!");
bean.setMessage("Meow!");
return new ModelAndView("welcomePage","model",bean);
... then in your jsp, you can do:-
Hello ${model.name}! {model.message} // displays Hello Mike! Meow!
Rank and Dense rank gives the rank in the partitioned dataset.
Rank() : It doesn't give you consecutive integer numbers.
Dense_rank() : It gives you consecutive integer numbers.
In above picture , the rank of 10008 zip is 2 by dense_rank() function and 24 by rank() function as it considers the row_number.
In Prefix expression operators comes first then operands : +ab[ oprator ab ]
Infix : (a–b)/c*(d + e – f / g)
Step 1: (a - b) = (- ab)
[ '(' has highest priority ]
step 2: (d + e - f / g) = (d + e - / fg)
[ '/' has highest priority ]
= (+ de - / fg )
['+','-' has same priority but left to right associativity]
= (- + de / fg)
Step 3: (-ab )/ c * (- + de / fg)
= / - abc * (- + de / fg)
= * / - abc - + de / fg
Prefix : * / - abc - + de / fg
char members[255] = {0};
Please check if you have already close the database connection or not. In my case i was getting the error because the connection was close in upper line.
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
In your css file add following.
ul{
list-style-type: none;
}
Not a direct answer, but here is a function to insert a row with column-value pairs into sqlite table:
def sqlite_insert(conn, table, row):
cols = ', '.join('"{}"'.format(col) for col in row.keys())
vals = ', '.join(':{}'.format(col) for col in row.keys())
sql = 'INSERT INTO "{0}" ({1}) VALUES ({2})'.format(table, cols, vals)
conn.cursor().execute(sql, row)
conn.commit()
Example of use:
sqlite_insert(conn, 'stocks', {
'created_at': '2016-04-17',
'type': 'BUY',
'amount': 500,
'price': 45.00})
Note, that table name and column names should be validated beforehand.
(Maybe helpful for others with a similar requirement)
I had a similar requirement to use AES-256-CBC
encrypt and decrypt in Java.
To achieve (or specify) the 256-byte encryption/decryption, Java Cryptography Extension (JCE)
policy should set to "Unlimited"
It can be set in the java.security
file under $JAVA_HOME/jre/lib/security
(for JDK) or $JAVA_HOME/lib/security
(for JRE)
crypto.policy=unlimited
Or in the code as
Security.setProperty("crypto.policy", "unlimited");
Java 9 and later versions have this enabled by default.
Note that :
typeof $(this)
is JQuery object.
and
typeof $(this)[0]
is HTMLElement object
then :
if you want to apply .val()
on HTMLElement , you can add this extension .
HTMLElement.prototype.val=function(v){
if(typeof v!=='undefined'){this.value=v;return this;}
else{return this.value}
}
Then :
document.getElementById('myDiv').val() ==== $('#myDiv').val()
And
document.getElementById('myDiv').val('newVal') ==== $('#myDiv').val('newVal')
?????
INVERSE :Conversely? if you want to add value property to jQuery object , follow those steps :
Download the full source code (not minified) i.e: example http://code.jquery.com/jquery-1.11.1.js .
Insert Line after L96 , add this code value:""
to init this new prop
Search on jQuery.fn.init
, it will be almost Line 2747
value
prop : (Before return statment add this.value=jQuery(selector).val()
)
Here is a simple solution inside python using a decorator:
import os, time
def daemon(func):
def wrapper(*args, **kwargs):
if os.fork(): return
func(*args, **kwargs)
os._exit(os.EX_OK)
return wrapper
@daemon
def my_func(count=10):
for i in range(0,count):
print('parent pid: %d' % os.getppid())
time.sleep(1)
my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own
You can of course replace the content of your bgservice.py
file in place of my_func
.
This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.
ul {_x000D_
display: flex;_x000D_
flex-direction: column-reverse;_x000D_
}_x000D_
_x000D_
/* Apply desired style to all matching elements. */_x000D_
ul > li.list {_x000D_
background-color: #888;_x000D_
}_x000D_
_x000D_
/* Using a more specific selector, "unstyle" elements which are not the first. */_x000D_
ul > li.list ~ li.list {_x000D_
background-color: inherit;_x000D_
}
_x000D_
<ul>_x000D_
<li class="list">0</li>_x000D_
<li>1</li>_x000D_
<li class="list">2</li>_x000D_
</ul>_x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li class="list">1</li>_x000D_
<li class="list">2</li>_x000D_
<li>3</li>_x000D_
</ul>
_x000D_
The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.
It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a
and b
in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse
method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.
You could try direction:rtl;
in your css. Then reset the text direction in the inner div
#scroll{
direction:rtl;
overflow:auto;
height:50px;
width:50px;}
#scroll div{
direction:ltr;
}
Untested.
You can read data direct from some file and plot
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from sys import argv
x,y,z = np.loadtxt('your_file', unpack=True)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.savefig('teste.pdf')
plt.show()
If necessary you can pass vmin and vmax to define the colorbar range, e.g.
surf = ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.1, vmin=0, vmax=2000)
I was wondering how to do some interactive plots, in this case with artificial data
from __future__ import print_function
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
from IPython.display import Image
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits import mplot3d
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
def plot(i):
fig = plt.figure()
ax = plt.axes(projection='3d')
theta = 2 * np.pi * np.random.random(1000)
r = i * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax.plot_trisurf(x, y, z, cmap='viridis', edgecolor='none')
fig.tight_layout()
interactive_plot = interactive(plot, i=(2, 10))
interactive_plot
PHP 7 improved query.........
$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'");
if (mysqli_num_rows($sql) > 0) {
echo 'Username taken.';
}
student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user,
'request':request, 'enrolled_subjects': enrolled_subjects})
In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.
Subject and Student User model is a Foreign Key to the SubjectGrade Model.
In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user
PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much
If you want to clean up Solr index -
you can fire http url -
http://host:port/solr/[core name]/update?stream.body=<delete><query>*:*</query></delete>&commit=true
(replace [core name]
with the name of the core you want to delete from). Or use this if posting data xml data:
<delete><query>*:*</query></delete>
Be sure you use commit=true
to commit the changes
Don't have much idea with clearing hbase data though.
Offering another potential solution to this error.
If you have a frontend application that makes API calls to the backend, make sure you reference the domain name that the certificate has been issued to.
e.g.
https://example.com/api/etc
and not
https://123.4.5.6/api/etc
In my case, I was making API calls to a secure server with a certificate, but using the IP instead of the domain name. This threw a Failed to load resource: net::ERR_INSECURE_RESPONSE
.
In kibana 4.0.2 there is no --log-file option. If I start kibana as a service with systemctl start kibana
I find log in /var/log/messages