Remove the z-index value.
I would also recommend this approach.
HTML:
<header class="main-header" role="banner">
<img src="mybannerimage.gif" alt="Banner Image"/>
</header>
CSS:
.main-header {
text-align: center;
}
This will center your image with out stretching it out. You can adjust the padding as needed to give it some space around your image. Since this is at the top of your page you don't need to force it there with position absolute unless you want your other elements to go underneath it. In that case you'd probably want position:fixed; anyway.
You can add this to your _Layout.cshtml:
@using MyProj.ViewModels;
...
@if (TempData["UserMessage"] != null)
{
var message = (MessageViewModel)TempData["UserMessage"];
<div class="alert @message.CssClassName" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>@message.Title</strong>
@message.Message
</div>
}
Then if you want to throw an error message in your controller:
TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger alert-dismissible", Title = "Error", Message = "This is an error message" };
MessageViewModel.cs:
public class MessageViewModel
{
public string CssClassName { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
Note: Using Bootstrap 4 classes.
In SQL Management Studio you can expand the columns in Object Explorer, then drag the Columns
tree item into a query window to get a comma separated list of columns.
I have following idea how you can deal with such Access Device ID (ADID):
Gen ADID
Use device
In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.
You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.
In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.
Simpler approach based on links:
In Chrome 48+ use this solution:
Put fake fields before real fields:
<form autocomplete="off">
<input name="fake_email" class="visually-hidden" type="text">
<input name="fake_password" class="visually-hidden" type="password">
<input autocomplete="off" name="email" type="text">
<input autocomplete="off" name="password" type="password">
</form>
Hide fake fields:
.visually-hidden {
margin: -1px;
padding: 0;
width: 1px;
height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
clip: rect(0, 0, 0, 0);
position: absolute;
}
You did it!
Also this will work for older versions.
To achieve this you can use a Regular Expression to remove all the whitespace in the string. If the length of the resulting string is 0
, then you can be sure the original only contained whitespace. Try this:
var str = " ";_x000D_
if (!str.replace(/\s/g, '').length) {_x000D_
console.log('string only contains whitespace (ie. spaces, tabs or line breaks)');_x000D_
}
_x000D_
Let's say you have two models, one named Person and another one named Companies.
By definition, one person can create more than one company.
Considering a company can have one and only one person, we want that when a person is deleted that all the companies associated with that person also be deleted.
So, we start by creating a Person model, like this
class Person(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=20)
def __str__(self):
return self.id+self.name
Then, the Companies model can look like this
class Companies(models.Model):
title = models.CharField(max_length=20)
description=models.CharField(max_length=10)
person= models.ForeignKey(Person,related_name='persons',on_delete=models.CASCADE)
Notice the usage of on_delete=models.CASCADE
in the model Companies. That is to delete all companies when the person that owns it (instance of class Person) is deleted.
AFAIK, Windows doesn't have a built-in commandline tool to download a file. But you can do it from a VBScript, and you can generate the VBScript file from batch using echo and output redirection:
@echo off
rem Windows has no built-in wget or curl, so generate a VBS script to do it:
rem -------------------------------------------------------------------------
set DLOAD_SCRIPT=download.vbs
echo Option Explicit > %DLOAD_SCRIPT%
echo Dim args, http, fileSystem, adoStream, url, target, status >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
echo Set args = Wscript.Arguments >> %DLOAD_SCRIPT%
echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> %DLOAD_SCRIPT%
echo url = args(0) >> %DLOAD_SCRIPT%
echo target = args(1) >> %DLOAD_SCRIPT%
echo WScript.Echo "Getting '" ^& target ^& "' from '" ^& url ^& "'..." >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
echo http.Open "GET", url, False >> %DLOAD_SCRIPT%
echo http.Send >> %DLOAD_SCRIPT%
echo status = http.Status >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
echo If status ^<^> 200 Then >> %DLOAD_SCRIPT%
echo WScript.Echo "FAILED to download: HTTP Status " ^& status >> %DLOAD_SCRIPT%
echo WScript.Quit 1 >> %DLOAD_SCRIPT%
echo End If >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
echo Set adoStream = CreateObject("ADODB.Stream") >> %DLOAD_SCRIPT%
echo adoStream.Open >> %DLOAD_SCRIPT%
echo adoStream.Type = 1 >> %DLOAD_SCRIPT%
echo adoStream.Write http.ResponseBody >> %DLOAD_SCRIPT%
echo adoStream.Position = 0 >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
echo Set fileSystem = CreateObject("Scripting.FileSystemObject") >> %DLOAD_SCRIPT%
echo If fileSystem.FileExists(target) Then fileSystem.DeleteFile target >> %DLOAD_SCRIPT%
echo adoStream.SaveToFile target >> %DLOAD_SCRIPT%
echo adoStream.Close >> %DLOAD_SCRIPT%
echo. >> %DLOAD_SCRIPT%
rem -------------------------------------------------------------------------
cscript //Nologo %DLOAD_SCRIPT% http://example.com targetPathAndFile.html
More explanation here
Just wrap your WebElement into Select Object as shown below
Select dropdown = new Select(driver.findElement(By.id("identifier")));
Once this is done you can select the required value in 3 ways. Consider an HTML file like this
<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>
Now to identify dropdown do
Select dropdown = new Select(driver.findElement(By.id("designation")));
To select its option say 'Programmer' you can do
dropdown.selectByVisibleText("Programmer ");
or
dropdown.selectByIndex(1);
or
dropdown.selectByValue("prog");
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
I know this is older but the correct way to do this now is
string Domain = HttpContext.Current.Request.Url.Authority
That will get the DNS or ip address with port for a server.
Try this, but I don't think it will work because you're not supposed to be able to change this
Put this line in an htaccess file in the directory you want the setting to be enabled:
php_value allow_url_fopen On
Note that this setting will only apply to PHP file's in the same directory as the htaccess file.
As an alternative to using url_fopen, try using curl.
You shouldn't overload the templates with complex logic, it's a bad practice. Remember to always keep it simple!
The better approach would be to extract this logic into reusable function on your $rootScope
:
.run(function ($rootScope) {
$rootScope.inArray = function (item, array) {
return (-1 !== array.indexOf(item));
};
})
Then, use it in your template:
<li ng-class="{approved: inArray(jobSet, selectedForApproval)}"></li>
I think everyone will agree that this example is much more readable and maintainable.
In perl:
if($testString =~ /\d/)
{
print "This string contains at least one digit"
}
where \d
matches to a digit.
With my method you can completely remove duplicate values, leaving you with values from the array that only had a count of 1. It was not clear if this is what the OP actually wanted however I was unable to find an example of this solution online so here it is.
$array=@'
Bananna
Apple
Carrot
Pear
Apricot
Pear
Bananna
'@ -split '\r\n'
($array | Group-Object -NoElement | ?{$_.count -eq 1}).Name
Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.
To do so:
Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):
select myintfield + 0.0 as myfloatfield from mytable
While @Heximal's answer works, I don't personally recommend it.
This is because it uses implicit casting. Although you didn't type CAST
, either the SUM()
or the 0.0
need to be cast to be the same data-types, before the +
can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +
. But SUM(aFloatField) + 0
does not yield an INT, because the 0
is being implicitly cast to a FLOAT.
I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.
If you want to be explicit, I would use the following.
CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT requires 8.0
You can try the following to see what happens...
CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))
If you're in netbeans you can right click in the test method and click "Run Focused Test Method".
To extend to more dimensions, just add []
's and dimension parameters to newInstance()
(T
is a type parameter, cls
is a Class<T>
, d1
through d5
are integers):
T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);
See Array.newInstance()
for details.
For some reason I kept having this full page width problem with IE7 so I made this hack:
var tag = $("<div></div>");
//IE7 workaround
var w;
if (navigator.appVersion.indexOf("MSIE 7.") != -1)
w = 400;
else
w = "auto";
tag.html('My message').dialog({
width: w,
maxWidth: 600,
...
This button post to the current page while at the same time opens OtherPage.aspx
in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />
Read Ricardo's response first. This worked for me.
However, there exists a scenario where this won't work if the running container was kicked off using docker-compose. This is because docker-compose (I'm running docker 1.17) creates a new network. The way to address this scenario would be
docker network ls
Then append the following
docker run -d --name sqlplus --link db:db -p 1521:1521 sqlplus --net network_name
to disable
document.getElementById("btnPlaceOrder").disabled = true;
to enable
document.getElementById("btnPlaceOrder").disabled = false;
The with
function will let you use shorthand column references and sum
will count TRUE
results from the expression(s).
sum(with(aaa, sex==1 & group1==2))
## [1] 3
sum(with(aaa, sex==1 & group2=="A"))
## [1] 2
As @mnel pointed out, you can also do:
nrow(aaa[aaa$sex==1 & aaa$group1==2,])
## [1] 3
nrow(aaa[aaa$sex==1 & aaa$group2=="A",])
## [1] 2
The benefit of that is that you can do:
nrow(aaa)
## [1] 6
And, the behaviour matches Stata's count
almost exactly (syntax notwithstanding).
$array = data();
print_r($array);
This is a bit late, but this is the best solution I found. You make a look-up dictionary for the form name and its class, you also have to add an attribute to identify the form, and in your views you have to add it as a hidden field, with the form.formlabel
.
# form holder
form_holder = {
'majeur': {
'class': FormClass1,
},
'majsoft': {
'class': FormClass2,
},
'tiers1': {
'class': FormClass3,
},
'tiers2': {
'class': FormClass4,
},
'tiers3': {
'class': FormClass5,
},
'tiers4': {
'class': FormClass6,
},
}
for key in form_holder.keys():
# If the key is the same as the formlabel, we should use the posted data
if request.POST.get('formlabel', None) == key:
# Get the form and initate it with the sent data
form = form_holder.get(key).get('class')(
data=request.POST
)
# Validate the form
if form.is_valid():
# Correct data entries
messages.info(request, _(u"Configuration validée."))
if form.save():
# Save succeeded
messages.success(
request,
_(u"Données enregistrées avec succès.")
)
else:
# Save failed
messages.warning(
request,
_(u"Un problème est survenu pendant l'enregistrement "
u"des données, merci de réessayer plus tard.")
)
else:
# Form is not valid, show feedback to the user
messages.error(
request,
_(u"Merci de corriger les erreurs suivantes.")
)
else:
# Just initiate the form without data
form = form_holder.get(key).get('class')(key)()
# Add the attribute for the name
setattr(form, 'formlabel', key)
# Append it to the tempalte variable that will hold all the forms
forms.append(form)
I hope this will help in the future.
As the question and user3490026's answer are a top search hit, I have made a reproducible example and a brief illustration of the suggestions made so far, together with a solution that explicitly addresses the OP's question.
One of the things that ggplot2
does and which can be confusing is that it automatically blends certain legends when they are associated with the same variable. For instance, factor(gear)
appears twice, once for linetype
and once for fill
, resulting in a combined legend. By contrast, gear
has its own legend entry as it is not treated as the same as factor(gear)
. The solutions offered so far usually work well. But occasionally, you may need to override the guides. See my last example at the bottom.
# reproducible example:
library(ggplot2)
p <- ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs)) +
geom_point(aes(shape = factor(cyl))) +
geom_line(aes(linetype = factor(gear))) +
geom_smooth(aes(fill = factor(gear), color = gear)) +
theme_bw()
Remove all legends: @user3490026
p + theme(legend.position = "none")
Remove all legends: @duhaime
p + guides(fill = FALSE, color = FALSE, linetype = FALSE, shape = FALSE)
Turn off legends: @Tjebo
ggplot(data = mtcars, aes(x = mpg, y = disp, group = gear)) +
geom_point(aes(color = vs), show.legend = FALSE) +
geom_point(aes(shape = factor(cyl)), show.legend = FALSE) +
geom_line(aes(linetype = factor(gear)), show.legend = FALSE) +
geom_smooth(aes(fill = factor(gear), color = gear), show.legend = FALSE) +
theme_bw()
Remove fill so that linetype becomes visible
p + guides(fill = FALSE)
Same as above via the scale_fill_ function:
p + scale_fill_discrete(guide = FALSE)
And now one possible answer to the OP's request
"to keep the legend of one layer (smooth) and remove the legend of the other (point)"
Turn some on some off ad-hoc post-hoc
p + guides(fill = guide_legend(override.aes = list(color = NA)),
color = FALSE,
shape = FALSE)
This is pretty vague. Do you mean like in SQL:
DELETE FROM myTable
WHERE dateColumn < '2007'
After testing all workarounds, i suggest you to take a look at Settings -> Project -> project dependencies
and re-arrange them.
You are looking for the update method
dic0.update( dic1 )
print( dic0 )
gives
{'dic0': 0, 'dic1': 1}
By default, unlike an exception, a warning doesn't interrupt.
After import warnings
, it is possible to specify a Warnings class when generating a warning. If one is not specified, it is literally UserWarning
by default.
>>> warnings.warn('This is a default warning.')
<string>:1: UserWarning: This is a default warning.
To simply use a preexisting class instead, e.g. DeprecationWarning
:
>>> warnings.warn('This is a particular warning.', DeprecationWarning)
<string>:1: DeprecationWarning: This is a particular warning.
Creating a custom warning class is similar to creating a custom exception class:
>>> class MyCustomWarning(UserWarning):
... pass
...
... warnings.warn('This is my custom warning.', MyCustomWarning)
<string>:1: MyCustomWarning: This is my custom warning.
For testing, consider assertWarns
or assertWarnsRegex
.
As an alternative, especially for standalone applications, consider the logging
module. It can log messages having a level of debug, info, warning, error, etc. Log messages having a level of warning or higher are by default printed to stderr.
I found this page while looking for a solution that would help me select results from a prior calendar year. Most of the results shown above seems return items from the past 365 days, which didn't work for me.
At the same time, it did give me enough direction to solve my needs in the following code - which I'm posting here for any others who have the same need as mine and who may come across this page in searching for a solution.
SELECT .... FROM .... WHERE year(*your date column*) = year(DATEADD(year,-1,getdate()))
Thanks to those above whose solutions helped me arrive at what I needed.
After the installation of the new SDK, there is a new folder, "Android Dependencies", under your project file. If you right click and remove it from the build path, you will again be able to build your project.
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
alert (product.UnitName + " " + product.UnitPrice + " " + product.Stock)
or else create a toString() method on your object and call
alert(product.toString())
But I have to agree with other posters - if it is debugging you're going for then firebug or F12 on IE9 or chrome and using console.log is the way to go
Often, wild cards operate with two type of jokers:
? - any character (one and only one)
* - any characters (zero or more)
so you can easily convert these rules into appropriate regular expression:
// If you want to implement both "*" and "?"
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$";
}
// If you want to implement "*" only
private static String WildCardToRegular(String value) {
return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$";
}
And then you can use Regex as usual:
String test = "Some Data X";
Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));
// Starts with S, ends with X, contains "me" and "a" (in that order)
Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));
A workaround if you don't care about the strange view after an option is selected (i.e. Select to jump to a new page):
<!-- Limit width of the wrapping div instead of the select and use 'overflow: hidden' to hide the right part of it. -->
<div style='width: 145px; overflow: hidden; border-right: 1px solid #aaa;'>
<select onchange='jump();'>
<!-- '▼(?)' produces a fake dropdown indicator -->
<option value=''>Jump to ... ▼</option>
<option value='1'>http://stackoverflow.com/questions/682764/select-dropdown-with-fixed-width-cutting-off-content-in-ie</option>
...
</select>
</div>
cURL is disabled for most hosting control panels for security reasons, but it's required for a lot of php applications. It's not unusual for a client to request it. Since the risk of enabling cURL is minimal, you are probably better off enabling it than losing a customer. It's simply a utility that helps php scripts fetch things using standard Internet URLs.
To enable cURL, you will remove curl_exec from the "disabled list" in the control panel php advanced settings. You will also find a disabled list in the various php.ini files; look in /etc/php.ini and other paths that might exist for your control panel. You will need to restart Apache to make the change take effect.
To confirm whether cURL is enabled or disabled, create a file somewhere in your system and paste the following contents.
<?php
echo '<pre>';
var_dump(curl_version());
echo '</pre>';
?>
Save the file as testcurl.php and then run it as a php script.
testcurl.php
If cURL is disabled you will see this error.
Fatal error: Call to undefined function curl_version() in testcurl.php on line 2
If cURL is enabled you will see a long list of attributes, like this.
array(9) {
["version_number"]=>
int(461570)
["age"]=>
int(1)
["features"]=>
int(540)
["ssl_version_number"]=>
int(9465919)
["version"]=>
string(6) "7.11.2"
["host"]=>
string(13) "i386-pc-win32"
["ssl_version"]=>
string(15) " OpenSSL/0.9.7c"
["libz_version"]=>
string(5) "1.1.4"
["protocols"]=>
array(9) {
[0]=>
string(3) "ftp"
[1]=>
string(6) "gopher"
[2]=>
string(6) "telnet"
[3]=>
string(4) "dict"
[4]=>
string(4) "ldap"
[5]=>
string(4) "http"
[6]=>
string(4) "file"
[7]=>
string(5) "https"
[8]=>
string(4) "ftps"
}
}
I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket>
connection settings.
I set the headers object on my client-side script with the following options:
/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
method: 'OPTIONS',
credentials: "include",
body: JSON.stringify(data),
cors: 'cors',
headers: head, //could be object literal too
cache: 'default'
})
.then(response=>{
....
}).catch(err=>{...});
And on my express server I setup my router as follows:
router.head('absolute or regex', (request, response, next)=>{
req.setTimeout(1000*60*5, ()=>{
console.info("socket timed out");
});
console.info("Proceeding down the middleware chain link...\n\n");
next();
});
/*Keep the socket alive by enabling it on the server, with an optional
delay on the last packet sent
*/
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))
WARNING
Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.
I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.
@Adrian Cornish's answer is correct. However, there is another caveat to dropping an existing primary key. If that primary key is being used as a foreign key by another table you will get an error when trying to drop it. In some versions of mysql the error message there was malformed (as of 5.5.17, this error message is still
alter table parent drop column id;
ERROR 1025 (HY000): Error on rename of
'./test/#sql-a04_b' to './test/parent' (errno: 150).
If you want to drop a primary key that's being referenced by another table, you will have to drop the foreign key in that other table first. You can recreate that foreign key if you still want it after you recreate the primary key.
Also, when using composite keys, order is important. These
1) ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);
and
2) ALTER TABLE provider ADD PRIMARY KEY(person,thing,place);
are not the the same thing. They both enforce uniqueness on that set of three fields, however from an indexing standpoint there is a difference. The fields are indexed from left to right. For example, consider the following queries:
A) SELECT person, place, thing FROM provider WHERE person = 'foo' AND thing = 'bar';
B) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz';
C) SELECT person, place, thing FROM provider WHERE person = 'foo' AND place = 'baz' AND thing = 'bar';
D) SELECT person, place, thing FROM provider WHERE place = 'baz' AND thing = 'bar';
B can use the primary key index in ALTER statement 1
A can use the primary key index in ALTER statement 2
C can use either index
D can't use either index
A uses the first two fields in index 2 as a partial index. A can't use index 1 because it doesn't know the intermediate place portion of the index. It might still be able to use a partial index on just person though.
D can't use either index because it doesn't know person.
See the mysql docs here for more information.
I found this...
http://jsfiddle.net/Mottie/xcqpF/1/light/
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
Here is what I do. Using my editParams() function, you can add, remove, or change any parameter, then use the built in replaceState() function to update the URL:
window.history.replaceState('object or string', 'Title', 'page.html' + editParams('enable', 'true'));
// background functions below:
// add/change/remove URL parameter
// use a value of false to remove parameter
// returns a url-style string
function editParams (key, value) {
key = encodeURI(key);
var params = getSearchParameters();
if (Object.keys(params).length === 0) {
if (value !== false)
return '?' + key + '=' + encodeURI(value);
else
return '';
}
if (value !== false)
params[key] = encodeURI(value);
else
delete params[key];
if (Object.keys(params).length === 0)
return '';
return '?' + $.map(params, function (value, key) {
return key + '=' + value;
}).join('&');
}
// Get object/associative array of URL parameters
function getSearchParameters () {
var prmstr = window.location.search.substr(1);
return prmstr !== null && prmstr !== "" ? transformToAssocArray(prmstr) : {};
}
// convert parameters from url-style string to associative array
function transformToAssocArray (prmstr) {
var params = {},
prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
params[tmparr[0]] = tmparr[1];
}
return params;
}
Although I'm sure @Ben Jackson's asnwer with Option(getObject).foreach
is the preferred way of doing it, I like to use an AnyRef
pimp that allows me to write:
getObject ifNotNull ( QueueManager.add(_) )
I find it reads better.
And, in a more general way, I sometimes write
val returnVal = getObject ifNotNull { obj =>
returnSomethingFrom(obj)
} otherwise {
returnSomethingElse
}
... replacing ifNotNull with ifSome if I'm dealing with an Option
. I find it clearer than first wrapping in an option and then pattern-matching it.
(For the implementation, see Implementing ifTrue, ifFalse, ifSome, ifNone, etc. in Scala to avoid if(...) and simple pattern matching and the Otherwise0
/Otherwise1
classes.)
The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented
def isclass(object):
"""Return true if the object is a class.
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, (type, types.ClassType))
Angular 2.0.0 Final:
I have found that using a ViewChild
setter is most reliable way to set the initial form control focus:
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => {
this._renderer.invokeElementMethod(_input.nativeElement, "focus");
}, 0);
}
}
The setter is first called with an undefined
value followed by a call with an initialized ElementRef
.
Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview
Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).
UPDATE for Angular 4+
Renderer
has been deprecated in favor of Renderer2
, but Renderer2
does not have the invokeElementMethod
. You will need to access the DOM directly to set the focus as in input.nativeElement.focus()
.
I'm still finding that the ViewChild setter approach works best. When using AfterViewInit
I sometimes get read property 'nativeElement' of undefined
error.
@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
if (_input !== undefined) {
setTimeout(() => { //This setTimeout call may not be necessary anymore.
_input.nativeElement.focus();
}, 0);
}
}
In case that anyone still has this need (I have), I have written a library myself to deal with this problem. See here. It isn't completely automatic in that you have to describe all the fields in your classes, but it is as close as what we can get as C++ lacks reflection.
Since MySQL 5.6.X you can do this:
ALTER TABLE `schema`.`users`
CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
That way your column will be updated with the current timestamp when a new row is inserted, or updated.
If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
in the DEFAULT value field, like so:
http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html
restorecon
command works as below :
restorecon -v -R /var/www/html/
I was facing the same issue in bitbucket, and this worked for me:
line1
##<2 white spaces><enter>
line2
To solve this problem, github recommends Connecting over HTTPS.
Git's documentation discuss how to how to do exactly that using gitcredentials.
Solution 1
Static configuration of usernames for a given authentication context.
https://username:<personal-access-tokens>@repository-url.com
You will find the details in the documentation.
Solution 2
Use credential helpers to cache password (in memory for a short period of time).
git config --global credential.helper cache
Solution 3
Use credential helpers to store password (indefinitely on disk).
git config --global credential.helper 'store --file ~/.my-credentials'
You can find where the credential will be saved (If not set explicitly with --file) in the documentation.
If not set explicitly with --file, there are two files where git-credential-store will search for credentials in order of precedence:
~/.git-credentials
User-specific credentials file. $XDG_CONFIG_HOME/git/credentials Second user-specific credentials file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/credentials will be used. Any
credentials stored in this file will not be used if ~/.git-credentials has a matching credential as well. It is a good idea not to create this file if you sometimes use older versions of Git that do not support it.
P.S.
To address the concern:
your password is going to be stored completely unencrypted ("as is") at ~/.git-credentials.
You can always encrypt the file and decrypt it before using.
For no particular reason, arrays cannot be assigned to one another. Use std::copy
instead:
#include <algorithm>
// ...
int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);
This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays.
std::copy
is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy
performs better. If in doubt, measure.
Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.
Arrays cannot be passed by value. You can either pass them by pointer or by reference.
Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):
#include <numeric>
#include <cstddef>
int sum(const int* p, std::size_t n)
{
return std::accumulate(p, p + n, 0);
}
int sum(const int* p, const int* q)
{
return std::accumulate(p, q, 0);
}
As a syntactic alternative, you can also declare parameters as T p[]
, and it means the exact same thing as T* p
in the context of parameter lists only:
int sum(const int p[], std::size_t n)
{
return std::accumulate(p, p + n, 0);
}
You can think of the compiler as rewriting T p[]
to T *p
in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.
Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:
int sum(const int* p, std::size_t n)
// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)
// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n) // the 8 has no meaning here
Arrays can also be passed by reference:
int sum(const int (&a)[8])
{
return std::accumulate(a + 0, a + 8, 0);
}
In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:
template <std::size_t n>
int sum(const int (&a)[n])
{
return std::accumulate(a + 0, a + n, 0);
}
Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n
, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.
Go to Google Cloud Console, select the project then IAM and Admin and Settings
now SHUT DOWN
Then you have to wait for the project deletion.
It can be done like this:
import numpy as np
# create a random matrix:
A = np.random.normal(size=(5,2))
# add a column of zeros to it:
print(np.hstack((A,np.zeros((A.shape[0],1)))))
In general, if A is an m*n matrix, and you need to add a column, you have to create an n*1 matrix of zeros, then use "hstack" to add the matrix of zeros to the right of the matrix A.
if you have multiple parameters use the syntax as below. I have a bat file with script as below:
start "dummyTitle" [/options] D:\path\ProgramName.exe Param1 Param2 Param3
start "dummyTitle" [/options] D:\path\ProgramName.exe Param4 Param5 Param6
This will open multiple consoles.
final String s = "123456789";
final char[] word = s.toCharArray();
final int l = s.length() - 2;
final int ll = s.length() - 1;
for (int i = 0; i < l; i++) {
char x = word[i];
word[i] = word[ll - i];
word[ll - i] = x;
}
System.out.println(s);
System.out.println(new String(word));
You can do it either recursively or iteratively (looping).
Iteratively:
static String reverseMe(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length() - 1; i >= 0; --i)
sb.append(s.charAt(i));
return sb.toString();
}
Recursively:
static String reverseMe(String s) {
if (s.length() == 0)
return "";
return s.charAt(s.length() - 1) + reverseMe(s.substring(1));
}
Integer i = new Integer(15);
test(i);
System.out.println(i);
test(i);
System.out.println(i);
public static void test (Integer i) {
i = (Integer)i + 10;
}
You should check for (args == null || args.length == 0)
. Although the null
check isn't really needed, it is a good practice.
find . -type d > list.txt
Will list all directories and subdirectories under the current path. If you want to list all of the directories under a path other than the current one, change the .
to that other path.
If you want to exclude certain directories, you can filter them out with a negative condition:
find . -type d ! -name "~snapshot" > list.txt
You cannot check window.history.length
as it contains the amount of pages in you visited in total in a given session:
window.history.length
(Integer)Read-only. Returns the number of elements in the session history, including the currently loaded page. For example, for a page loaded in a new tab this property returns 1. Cite 1
Lets say a user visits your page, clicks on some links and goes back:
www.mysite.com/index.html <-- first page and now current page <----+ www.mysite.com/about.html | www.mysite.com/about.html#privacy | www.mysite.com/terms.html <-- user uses backbutton or your provided solution to go back
Now window.history.length
is 4. You cannot traverse through the history items due to security reasons. Otherwise on could could read the user's history and get his online banking session id or other sensitive information.
You can set a timeout, that will enable you to act if the previous page isn't loaded in a given time. However, if the user has a slow Internet connection and the timeout is to short, this method will redirect him to your default location all the time:
window.goBack = function (e){
var defaultLocation = "http://www.mysite.com";
var oldHash = window.location.hash;
history.back(); // Try to go back
var newHash = window.location.hash;
/* If the previous page hasn't been loaded in a given time (in this case
* 1000ms) the user is redirected to the default location given above.
* This enables you to redirect the user to another page.
*
* However, you should check whether there was a referrer to the current
* site. This is a good indicator for a previous entry in the history
* session.
*
* Also you should check whether the old location differs only in the hash,
* e.g. /index.html#top --> /index.html# shouldn't redirect to the default
* location.
*/
if(
newHash === oldHash &&
(typeof(document.referrer) !== "string" || document.referrer === "")
){
window.setTimeout(function(){
// redirect to default location
window.location.href = defaultLocation;
},1000); // set timeout in ms
}
if(e){
if(e.preventDefault)
e.preventDefault();
if(e.preventPropagation)
e.preventPropagation();
}
return false; // stop event propagation and browser default event
}
<span class="goback" onclick="goBack();">Go back!</span>
Note that typeof(document.referrer) !== "string"
is important, as browser vendors can disable the referrer due to security reasons (session hashes, custom GET URLs). But if we detect a referrer and it's empty, it's probaly save to say that there's no previous page (see note below). Still there could be some strange browser quirk going on, so it's safer to use the timeout than to use a simple redirection.
EDIT: Don't use <a href='#'>...</a>
, as this will add another entry to the session history. It's better to use a <span>
or some other element. Note that typeof document.referrer
is always "string"
and not empty if your page is inside of a (i)frame.
See also:
NAs also appear if there are attributes with zero variance (with all elements equal); see for instance:
cor(cbind(a=runif(10),b=rep(1,10)))
which returns:
a b
a 1 NA
b NA 1
Warning message:
In cor(cbind(a = runif(10), b = rep(1, 10))) :
the standard deviation is zero
Windows:
system("cls");
Unix:
system("clear");
You could instead, insert newline chars until everything gets scrolled, take a look here.
With that, you achieve portability easily.
You can also have this simple GoogleDoc approach.
<a style="color: green;" href="http://docs.google.com/gview?url=http://domain//docs/<?php echo $row['docname'] ;?>" target="_blank">View</a>
This would create a new page for you to view the doc without distorting your flow.
Since the release of HTML5 one can now simply do:
<div hidden>This div is hidden</div>
Note: This is not supported by some old browsers, most notably IE < 11.
Another variant to POST this content type and which does not use a dictionary would be:
StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
string resultJson = result.Content.ReadAsStringAsync().Result;
}
r = list(qs[:1])
if r:
return r[0]
return None
Use bin folder and exe instead. Path will be C:\Program Files (x86)\Git\bin\git.exe
Also sometimes it doesn't work if there are blank spaces in path name as in your program files directory name.
In that case, copy the whole git folder to root of partition and then link studio to it
i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:
your jQuery script needs to be after the elements you are referring to !
so your script needs to be after the html-code you want to access!
seems like jQuery can't access it otherwise.
For static import select the field and press Ctrl+Shift+M
You are correct in your understanding of the DOM based model. The XML file will be loaded as a whole and all its contents will be built as an in-memory representation of the tree the document represents. This can be time- and memory-consuming, depending on how large the input file is. The benefit of this approach is that you can easily query any part of the document, and freely manipulate all the nodes in the tree.
The DOM approach is typically used for small XML structures (where small depends on how much horsepower and memory your platform has) that may need to be modified and queried in different ways once they have been loaded.
SAX on the other hand is designed to handle XML input of virtually any size. Instead of the XML framework doing the hard work for you in figuring out the structure of the document and preparing potentially lots of objects for all the nodes, attributes etc., SAX completely leaves that to you.
What it basically does is read the input from the top and invoke callback methods you provide when certain "events" occur. An event might be hitting an opening tag, an attribute in the tag, finding text inside an element or coming across an end-tag.
SAX stubbornly reads the input and tells you what it sees in this fashion. It is up to you to maintain all state-information you require. Usually this means you will build up some sort of state-machine.
While this approach to XML processing is a lot more tedious, it can be very powerful, too. Imagine you want to just extract the titles of news articles from a blog feed. If you read this XML using DOM it would load all the article contents, all the images etc. that are contained in the XML into memory, even though you are not even interested in it.
With SAX you can just check if the element name is (e. g.) "title" whenever your "startTag" event method is called. If so, you know that you needs to add whatever the next "elementText" event offers you. When you receive the "endTag" event call, you check again if this is the closing element of the "title". After that, you just ignore all further elements, until either the input ends, or another "startTag" with a name of "title" comes along. And so on...
You could read through megabytes and megabytes of XML this way, just extracting the tiny amount of data you need.
The negative side of this approach is of course, that you need to do a lot more book-keeping yourself, depending on what data you need to extract and how complicated the XML structure is. Furthermore, you naturally cannot modify the structure of the XML tree, because you never have it in hand as a whole.
So in general, SAX is suitable for combing through potentially large amounts of data you receive with a specific "query" in mind, but need not modify, while DOM is more aimed at giving you full flexibility in changing structure and contents, at the expense of higher resource demand.
I am running Postgres 9.6 where I had to export a particular schema along with data.
I used the following command:
pg_dump.exe -U username -d databasename -n schemaname > C:\mylocation\mydumpfilename.dmp
If you want only the schema without data, use the switch s
instead of n
Below is the pg_dump switch list:
C:\Program Files\PostgreSQL\9.6\bin>pg_dump --help
pg_dump dumps a database as a text file or to other formats.
Usage:
pg_dump [OPTION]... [DBNAME]
General options:
-f, --file=FILENAME output file or directory name
-F, --format=c|d|t|p output file format (custom, directory, tar,
plain text (default))
-j, --jobs=NUM use this many parallel jobs to dump
-v, --verbose verbose mode
-V, --version output version information, then exit
-Z, --compress=0-9 compression level for compressed formats
--lock-wait-timeout=TIMEOUT fail after waiting TIMEOUT for a table lock
-?, --help show this help, then exit
Options controlling the output content:
-a, --data-only dump only the data, not the schema
-b, --blobs include large objects in dump
-c, --clean clean (drop) database objects before recreating
-C, --create include commands to create database in dump
-E, --encoding=ENCODING dump the data in encoding ENCODING
-n, --schema=SCHEMA dump the named schema(s) only
-N, --exclude-schema=SCHEMA do NOT dump the named schema(s)
-o, --oids include OIDs in dump
-O, --no-owner skip restoration of object ownership in
plain-text format
-s, --schema-only dump only the schema, no data
-S, --superuser=NAME superuser user name to use in plain-text format
-t, --table=TABLE dump the named table(s) only
-T, --exclude-table=TABLE do NOT dump the named table(s)
-x, --no-privileges do not dump privileges (grant/revoke)
--binary-upgrade for use by upgrade utilities only
--column-inserts dump data as INSERT commands with column names
--disable-dollar-quoting disable dollar quoting, use SQL standard quoting
--disable-triggers disable triggers during data-only restore
--enable-row-security enable row security (dump only content user has
access to)
--exclude-table-data=TABLE do NOT dump data for the named table(s)
--if-exists use IF EXISTS when dropping objects
--inserts dump data as INSERT commands, rather than COPY
--no-security-labels do not dump security label assignments
--no-synchronized-snapshots do not use synchronized snapshots in parallel jobs
--no-tablespaces do not dump tablespace assignments
--no-unlogged-table-data do not dump unlogged table data
--quote-all-identifiers quote all identifiers, even if not key words
--section=SECTION dump named section (pre-data, data, or post-data)
--serializable-deferrable wait until the dump can run without anomalies
--snapshot=SNAPSHOT use given snapshot for the dump
--strict-names require table and/or schema include patterns to
match at least one entity each
--use-set-session-authorization
use SET SESSION AUTHORIZATION commands instead of
ALTER OWNER commands to set ownership
Connection options:
-d, --dbname=DBNAME database to dump
-h, --host=HOSTNAME database server host or socket directory
-p, --port=PORT database server port number
-U, --username=NAME connect as specified database user
-w, --no-password never prompt for password
-W, --password force password prompt (should happen automatically)
--role=ROLENAME do SET ROLE before dump
If no database name is supplied, then the PGDATABASE environment
variable value is used.
Report bugs to <[email protected]>.
Express is basically a wrapper of http module that is created for the ease of the developers in such a way that..
Assuming you are using Eclipse, on a MAC you can:
Eclipse.app
Eclipse -> Preferences
Java -> Installed JREs
Add...
buttonMacOS X VM
as the JRE type. Press Next./Library/Java/JavaVirtualMachines/1.7.0.jdk/Contents/Home
JDK 1.7
. Click Finish.File -> New -> Java Project
.Use default JRE (currently JDK 1.7)
Hope this helps
from itertools import count, izip
def enumerate(L, n=0):
return izip( count(n), L)
# if 2.5 has no count
def count(n=0):
while True:
yield n
n+=1
Now h = list(enumerate(xrange(2000, 2005), 1))
works.
The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.
So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?
You're trying to cherry pick fd9f578
, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m
option. For example, git cherry-pick -m 1 fd9f578
to use parent 1 as the base.
I can't say for sure for your particular situation, but using git merge
instead of git cherry-pick
is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m
into that one commit. You lose all their history, and glom together all their diffs. Your call.
Another solution using recursion:
def subsets(nums: List[int]) -> List[List[int]]:
n = len(nums)
output = [[]]
for num in nums:
output += [curr + [num] for curr in output]
return output
Starting from empty subset in output list. At each step we take a new integer into consideration and generates new subsets from the existing ones.
Add any file in the documentation which will include your content, for example toc.h:
@ mainpage Manual SDK
<hr/>
@ section pageTOC Content
-# @ref Description
-# @ref License
-# @ref Item
...
And in your Doxyfile
:
INPUT = toc.h \
Example (in Russian):
WebRequest request = WebRequest.Create("http://www.google.com");
try
{
request.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
MessageBox.Show("The URL is incorrect");`
}
(Addendum to existing answers)
... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.
Citing [dcl.fct.def.delete]/4:
A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:
struct sometype { sometype(); }; sometype::sometype() = delete; // ill-formed; not first declaration
— end example )
Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.
Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.
#include <iostream>
#include <string>
template< typename T >
void use_only_explicit_specializations(T t);
template<>
void use_only_explicit_specializations<int>(int t) {
std::cout << "int: " << t;
}
int main()
{
const int num = 42;
const std::string str = "foo";
use_only_explicit_specializations(num); // int: 42
//use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}
However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:
#include <iostream>
#include <string>
template< typename T >
void use_only_explicit_specializations(T t) = delete;
template<>
void use_only_explicit_specializations<int>(int t) {
std::cout << "int: " << t;
}
int main()
{
const int num = 42;
const std::string str = "foo";
use_only_explicit_specializations(num); // int: 42
use_only_explicit_specializations(str);
/* error: call to deleted function 'use_only_explicit_specializations'
note: candidate function [with T = std::__1::basic_string<char>] has
been explicitly deleted
void use_only_explicit_specializations(T t) = delete; */
}
Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).
Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.
#include <cstdint>
#include <iostream>
void warning_at_best(int8_t num) {
std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}
template< typename T >
void only_for_signed(T t) = delete;
template<>
void only_for_signed<int8_t>(int8_t t) {
std::cout << "UB safe! 1 byte, " << +t << "\n";
}
template<>
void only_for_signed<int16_t>(int16_t t) {
std::cout << "UB safe! 2 bytes, " << +t << "\n";
}
int main()
{
const int8_t a = 42;
const uint8_t b = 255U;
const int16_t c = 255;
const float d = 200.F;
warning_at_best(a); // 42
warning_at_best(b); // implementation-defined behaviour, no diagnostic required
warning_at_best(c); // narrowing, -Wconstant-conversion warning
warning_at_best(d); // undefined behaviour!
only_for_signed(a);
only_for_signed(c);
//only_for_signed(b);
/* error: call to deleted function 'only_for_signed'
note: candidate function [with T = unsigned char]
has been explicitly deleted
void only_for_signed(T t) = delete; */
//only_for_signed(d);
/* error: call to deleted function 'only_for_signed'
note: candidate function [with T = float]
has been explicitly deleted
void only_for_signed(T t) = delete; */
}
Use onkeyup on the text box and check the keycode of the key pressed, if its between 65 and 90, allow else empty the text box.
The following code is basic on @DTing‘s answer and what I learn from class, which uses a while loop to insert (indicated in the code).
class Node:
def __init__(self, val):
self.l_child = None
self.r_child = None
self.data = val
def binary_insert(root, node):
y = None
x = root
z = node
#while loop here
while x is not None:
y = x
if z.data < x.data:
x = x.l_child
else:
x = x.r_child
z.parent = y
if y == None:
root = z
elif z.data < y.data:
y.l_child = z
else:
y.r_child = z
def in_order_print(root):
if not root:
return
in_order_print(root.l_child)
print(root.data)
in_order_print(root.r_child)
r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))
in_order_print(r)
An excerpt from an apple technical note (Thanks to matthias-bauch)
Xcode includes all your command-line tools. If it is installed on your system, remove it to uninstall your tools.
If your tools were downloaded separately from Xcode, then they are located at
/Library/Developer/CommandLineTools
on your system. Delete the CommandLineTools folder to uninstall them.
you could easily delete using terminal:
Here is an article that explains how to remove the command line tools but do it at your own risk.Try this only if any of the above doesn't work.
These data types are synonyms.
Single line version
git submodule foreach "(git checkout master; git pull; cd ..; git add '$path'; git commit -m 'Submodule Sync')"
this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.
public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
var dt = new DataTable();
var joinTable = from t1 in dataTable1.AsEnumerable()
join t2 in dataTable2.AsEnumerable()
on t1[joinField] equals t2[joinField]
select new { t1, t2 };
foreach (DataColumn col in dataTable1.Columns)
dt.Columns.Add(col.ColumnName, typeof(string));
dt.Columns.Remove(joinField);
foreach (DataColumn col in dataTable2.Columns)
dt.Columns.Add(col.ColumnName, typeof(string));
foreach (var row in joinTable)
{
var newRow = dt.NewRow();
newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
dt.Rows.Add(newRow);
}
return dt;
}
Overall
SELECT
COUNT(DISTINCT `site_id`) as distinct_sites
FROM `cp_visits`
WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
Or per site
SELECT
`site_id` as site,
COUNT(DISTINCT `user_id`) as distinct_users_per_site
FROM `cp_visits`
WHERE ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
GROUP BY `site_id`
Having the time
column in the result doesn't make sense - since you are aggregating the rows, showing one particular time
is irrelevant, unless it is the min
or max
you are after.
Have a look at the respective sitepoint reference pages for background-image and URIs
Apache Commons Collection class.
StringUtils.equalsAny(CharSequence string, CharSequence... searchStrings)
So in your case, it would be
StringUtils.equalsAny(str, "val1", "val2", "val3");
Just expanding the answers:
Spacer
is an option no one mentioned yet; it is used in case you prefer not to use Positioned
/ Align
.Align
works if you want to specify the alignment of a child inside a parent. Use it anywhere but directly inside Stack
Positioned
is similar to Align, but works only under Stack
directly.If you want multiple messages from a queue, say 10 messages, the command to use is:
rabbitmqadmin get queue=<QueueName> ackmode=ack_requeue_true count=10
If you don't want the messages requeued, just change ackmode
to ack_requeue_false
.
The problem with Threading.Thread.SLeep(2000)
is that it executes first in my VB.Net program. This
Imports VB = Microsoft.VisualBasic
Public Sub wait(ByVal seconds As Single)
Static start As Single
start = VB.Timer()
Do While VB.Timer() < start + seconds
System.Windows.Forms.Application.DoEvents()
Loop
End Sub
worked flawlessly.
You can easily add a second legend by adding the line:
ax2.legend(loc=0)
You'll get this:
But if you want all labels on one legend then you should do something like this:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10
fig = plt.figure()
ax = fig.add_subplot(111)
lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
Which will give you this:
Try using BindingExpression.UpdateTarget()
Information provided by @Gord
As of September 2019 pywin32
is now available from PyPI and installs the latest version (currently version 224). This is done via the pip
command
pip install pywin32
If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx
is the version you require, e.g. 224
pip install pywin32==xxx
This differs to the pip
command below as that one uses pypiwin32
which currently installs an older (namely 223)
Browsing the docs I see no reason for these commands to work for all python3.x
versions, I am unsure on python2.7
and below so you would have to try them and if they do not work then the solutions below will work.
Probably now undesirable solutions but certainly still valid as of September 2019
There is no version of specific version ofwin32api
. You have to get the pywin32
module which currently cannot be installed via pip
. It is only available from this link at the moment.
https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/
The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python
version :)
EDIT
Since I posted my answer there are other alternatives to downloading the win32api
module.
It is now available to download through pip
using this command;
pip install pypiwin32
Also it can be installed from this GitHub repository as provided in comments by @Heath
Here is what I use:
import Foundation
import CoreLocation
import UIKit
class BackgroundLocationManager :NSObject, CLLocationManagerDelegate {
static let instance = BackgroundLocationManager()
static let BACKGROUND_TIMER = 150.0 // restart location manager every 150 seconds
static let UPDATE_SERVER_INTERVAL = 60 * 60 // 1 hour - once every 1 hour send location to server
let locationManager = CLLocationManager()
var timer:NSTimer?
var currentBgTaskId : UIBackgroundTaskIdentifier?
var lastLocationDate : NSDate = NSDate()
private override init(){
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.activityType = .Other;
locationManager.distanceFilter = kCLDistanceFilterNone;
if #available(iOS 9, *){
locationManager.allowsBackgroundLocationUpdates = true
}
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.applicationEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
func applicationEnterBackground(){
FileLogger.log("applicationEnterBackground")
start()
}
func start(){
if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedAlways){
if #available(iOS 9, *){
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
} else {
locationManager.requestAlwaysAuthorization()
}
}
func restart (){
timer?.invalidate()
timer = nil
start()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
//log("Restricted Access to location")
case CLAuthorizationStatus.Denied:
//log("User denied access to location")
case CLAuthorizationStatus.NotDetermined:
//log("Status not determined")
default:
//log("startUpdatintLocation")
if #available(iOS 9, *){
locationManager.requestLocation()
} else {
locationManager.startUpdatingLocation()
}
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if(timer==nil){
// The locations array is sorted in chronologically ascending order, so the
// last element is the most recent
guard let location = locations.last else {return}
beginNewBackgroundTask()
locationManager.stopUpdatingLocation()
let now = NSDate()
if(isItTime(now)){
//TODO: Every n minutes do whatever you want with the new location. Like for example sendLocationToServer(location, now:now)
}
}
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
CrashReporter.recordError(error)
beginNewBackgroundTask()
locationManager.stopUpdatingLocation()
}
func isItTime(now:NSDate) -> Bool {
let timePast = now.timeIntervalSinceDate(lastLocationDate)
let intervalExceeded = Int(timePast) > BackgroundLocationManager.UPDATE_SERVER_INTERVAL
return intervalExceeded;
}
func sendLocationToServer(location:CLLocation, now:NSDate){
//TODO
}
func beginNewBackgroundTask(){
var previousTaskId = currentBgTaskId;
currentBgTaskId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
FileLogger.log("task expired: ")
})
if let taskId = previousTaskId{
UIApplication.sharedApplication().endBackgroundTask(taskId)
previousTaskId = UIBackgroundTaskInvalid
}
timer = NSTimer.scheduledTimerWithTimeInterval(BackgroundLocationManager.BACKGROUND_TIMER, target: self, selector: #selector(self.restart),userInfo: nil, repeats: false)
}
}
I start the tracking in AppDelegate like that:
BackgroundLocationManager.instance.start()
I agree with the above comments about overriding toString()
on your own classes (and about automating that process as much as possible).
For classes you didn't define, you could write a ToStringHelper
class with an overloaded method for each library class you want to have handled to your own tastes:
public class ToStringHelper {
//... instance configuration here (e.g. punctuation, etc.)
public toString(List m) {
// presentation of List content to your liking
}
public toString(Map m) {
// presentation of Map content to your liking
}
public toString(Set m) {
// presentation of Set content to your liking
}
//... etc.
}
EDIT: Responding to the comment by xukxpvfzflbbld, here's a possible implementation for the cases mentioned previously.
package com.so.demos;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class ToStringHelper {
private String separator;
private String arrow;
public ToStringHelper(String separator, String arrow) {
this.separator = separator;
this.arrow = arrow;
}
public String toString(List<?> l) {
StringBuilder sb = new StringBuilder("(");
String sep = "";
for (Object object : l) {
sb.append(sep).append(object.toString());
sep = separator;
}
return sb.append(")").toString();
}
public String toString(Map<?,?> m) {
StringBuilder sb = new StringBuilder("[");
String sep = "";
for (Object object : m.keySet()) {
sb.append(sep)
.append(object.toString())
.append(arrow)
.append(m.get(object).toString());
sep = separator;
}
return sb.append("]").toString();
}
public String toString(Set<?> s) {
StringBuilder sb = new StringBuilder("{");
String sep = "";
for (Object object : s) {
sb.append(sep).append(object.toString());
sep = separator;
}
return sb.append("}").toString();
}
}
This isn't a full-blown implementation, but just a starter.
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
English definition:
In HTML context:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
Let's take the following HTML document:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
class
is reserved keyword in JS). But actually 2 properties, classList
and className
.Hi I'm using the SQLAzureMW tool for SQLAzure DB migration and management. Very useful one. It was downloaded from codeplex, but currently it's not available the codeplex will be going to shutdown, the same application tool is now available in GttHub. This below link is explain how to use this tool and also available the Application for download.
Did you try: Settings -> Security -> Install from SD Card? – Alexander Egger Dec 20 '10 at 20:11
I'm not sure why is this not an answer already, but I just followed this advice and it worked.
I do some quick tests and have the following findings:
1) if using SynchronousQueue:
After the threads reach the maximum size, any new work will be rejected with the exception like below.
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task java.util.concurrent.FutureTask@3fee733d rejected from java.util.concurrent.ThreadPoolExecutor@5acf9800[Running, pool size = 3, active threads = 3, queued tasks = 0, completed tasks = 0]
at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2047)
2) if using LinkedBlockingQueue:
The threads never increase from minimum size to maximum size, meaning the thread pool is fixed size as the minimum size.
I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.
Check your current php version in terminal with the following command,
$ php -v
You see current php version in terminal, and next command run in terminal if you want to upgrade your php version with php concat with version liked as,
$ brew install homebrew/php/php71
Please restart terminal if you finished php version upgrade installed and run the command.
$ php -v
Now you see the current php version in terminal....thank
If you are adding the option with javascript
function AddNewOption(userRoutes, text, id)
{
var option = document.createElement("option");
option.text = text;
option.value = id;
option.selected = "selected";
userdRoutes.add(option);
}
Try the packaged pecl version instead (the advantage of the packaged installs is that they're easier to upgrade):
apt-get install php5-dev
pecl install pdo
pecl install pdo_pgsql
or, if you just need a driver for PHP, but that it doesn't have to be the PDO one:
apt-get install php5-pgsql
Otherwise, that message most likely means you need to install a more recent libpq package. You can check which version you have by running:
dpkg -s libpq-dev
I had the same issue for my angular project, then I make it work in Chrome by changing the setting. Go to Chrome setting -->site setting -->Insecure content --> click add button of allow, then add your domain name [*.]XXXX.biz
Now problem will be solved.
You can use stat
with a file glob and a decorate-sort-undecorate with the file time added on the front:
$ stat -f "%m%t%N" b2* | sort -rn | head -1 | cut -f2-
def x(a):
print(a)
return a
def y(func_to_run, a):
return func_to_run(a)
y(x, 1)
That I think would be a more proper sample. Now what I wonder is if there is a way to code the function to use within the argument submission to another function. I believe there is in C++, but in Python I am not sure.
Perhaps the best lightweight approach would be
module MyConstants
ABC = Class.new
DEF = Class.new
GHI = Class.new
end
This way values have associated names, as in Java/C#:
MyConstants::ABC
=> MyConstants::ABC
To get all values, you can do
MyConstants.constants
=> [:ABC, :DEF, :GHI]
If you want an enum's ordinal value, you can do
MyConstants.constants.index :GHI
=> 2
By using Image.alpha_composite
, the solution by Yuji 'Tomita' Tomita become simpler. This code can avoid a tuple index out of range
error if png has no alpha channel.
from PIL import Image
png = Image.open(img_path).convert('RGBA')
background = Image.new('RGBA', png.size, (255,255,255))
alpha_composite = Image.alpha_composite(background, png)
alpha_composite.save('foo.jpg', 'JPEG', quality=80)
None of the solution above worked for me. But following did :
Nick's answer would work for an NxM array too with only a small modification (as opposed to an NxN).
string[,] orig = new string[n, m];
string[,] rot = new string[m, n];
...
for ( int i=0; i < n; i++ )
for ( int j=0; j < m; j++ )
rot[j, n - i - 1] = orig[i, j];
One way to think about this is that you have moved the center of the axis (0,0) from the top left corner to the top right corner. You're simply transposing from one to the other.
i have never done this, but it would be done like this:
var script = $('#google').attr("onclick")
There are two ways to write case statements, you seem to be using a combination of the two
case a.updatedDate
when 1760 then 'Entered on' + a.updatedDate
when 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
or
case
when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
else 'Last Updated on' + a.updateDate
end
are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.
The following regex extract anything between the parenthesis:
PS> $prog = [regex]::match($s,'\(([^\)]+)\)').Groups[1].Value
PS> $prog
SUB RAD MSD 50R III
Explanation (created with RegexBuddy)
Match the character '(' literally «\(»
Match the regular expression below and capture its match into backreference number 1 «([^\)]+)»
Match any character that is NOT a ) character «[^\)]+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character ')' literally «\)»
Check these links:
Since id is an attribute don't create an id element, just do this:
myPara.setAttribute("id", "id_you_like");
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),
The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
That is all the language has to say, as far as C++03 is concerned.
I claimed 3.5gb space in ubuntu AWS through this.
clean docker
docker stop $(docker ps -qa) && docker system prune -af --volumes
build again
docker build .
docker-compose build
docker-compose up
Here is the answer of my question. I've asked that again with some remarks. How to add support libraries?
This command helped me on linux mint when i had exact same problem
gcc filename.c -L/usr/include -lreadline -o filename
You could use alias if you compile it many times Forexample:
alias compilefilename='gcc filename.c -L/usr/include -lreadline -o filename'
You need to have org/name
dirs at /usr/share/stuff
and place your org.name
package sources at this dir.
You usually use padding to add distance between a border and a content.However, background are spread on padding.
You can still do it with nested element.
html :
<div id="outter">
<div id="inner">
test
</div>
</div>
outter div :
border-style: ridge;
border-color: #567498;
border-spacing:10px;
min-width: 100px;
min-height: 100px;
float:left;
inner div :
width: 100px;
min-height: 100px;
margin: 10px;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, rgb(39,54,73)),
color-stop(1, rgb(30,42,54))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(39,54,73) 0%,
rgb(30,42,54) 100%
);}
stdio is part of the standard C library which, by default, gcc will link against.
The math function implementations are in a separate libm file that is not linked to by default so you have to specify it -lm. By the way, there is no relation between those header files and library files.
you can define the variable global , but when using this variable must to write in script block .
def foo="foo"
pipeline {
agent none
stages {
stage("first") {
script{
sh "echo ${foo}"
}
}
}
}
Just wanted to mention, that you also may have to set the https_proxy
OS environment variable in case https URLs need to be accessed.
In my case it was not obvious to me and I tried for hours to discover this.
My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py
<!DOCTYPE html>
<html>
<head>
<title>float object center</title>
<style type="text/css">
#warp{
width:500px;
margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
width: 120px;
margin-left: 40px;
}
</style>
</head>
<body>
<div id="warp">
<div class="ser">
<img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
<div class="ser">
<img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
</div>
</body>
</html>
create two or more div's you want and give them a definite width like 100px for each then float it left or right
then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.
How to add single item. This is not very effective but follows what you are asking for:
x = p.Series()
N = 4
for i in xrange(N):
x = x.set_value(i, i**2)
produces x:
0 0
1 1
2 4
3 9
Obviously there are better ways to generate this series in only one shot.
For your second question check answer and references of SO question add one row in a pandas.DataFrame.
i didnt see it mentioned, This example will show you the (-) decimal operation for 2 bit values: A-B (only if A contains B)
this operation is needed when we hold an verb in our program that represent bits. sometimes we need to add bits (like above) and sometimes we need to remove bits (if the verb contains then)
111 #decimal 7
-
100 #decimal 4
--------------
011 #decimal 3
with python: 7 & ~4 = 3 (remove from 7 the bits that represent 4)
001 #decimal 1
-
100 #decimal 4
--------------
001 #decimal 1
with python: 1 & ~4 = 1 (remove from 1 the bits that represent 4 - in this case 1 is not 'contains' 4)..
I know this post is older, but haven't seen a solution that provides the actual information, so I want to share what I use for SQL Server 2012 and above. the link below leads to the screenshot showing the information.
First (so no time is wasted):
SQL Server 2000:
SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')
SQL Server 2005+
The "SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')" is not in use anymore. You can see more details on MSFT documentation: https://docs.microsoft.com/en-us/sql/t-sql/functions/serverproperty-transact-sql?view=sql-server-2017
SQL Server 2005 - 2008R2 you would have to:
Using PowerShell: https://www.ryadel.com/en/sql-server-retrieve-product-key-from-an-existing-installation/
Using TSQL (you would need to know the registry key path off hand): https://docs.microsoft.com/en-us/sql/relational-databases/system-dynamic-management-views/sys-dm-server-registry-transact-sql?view=sql-server-2017
SQL Server 2012+
Now, you can extract SQL Server Licensing information from the SQL Server Error Log, granted it may not be formatted the way you want, but the information is there and can be parsed, along with more descriptive information that you probably didn't expect.
EXEC sp_readerrorlog @p1 = 0
,@p2 = 1
,@p3 = N'licensing'
NOTE: I tried pasting the image directly, but since I am new at stakoverflow we have to follow the link below.
Character.getNumericValue(c)
The java.lang.Character.getNumericValue(char ch)
returns the int
value that the specified Unicode character represents. For example, the character '\u216C'
(the roman numeral fifty) will return an int with a value of 50.
The letters A-Z in their uppercase ('\u0041' through '\u005A')
, lowercase ('\u0061' through '\u007A')
, and full width variant ('\uFF21' through '\uFF3A' and '\uFF41' through '\uFF5A')
forms have numeric values from 10 through 35. This is independent of the Unicode specification, which does not assign numeric values to these char values.
This method returns the numeric value of the character, as a nonnegative int value;
-2 if the character has a numeric value that is not a nonnegative integer;
-1 if the character has no numeric value.
And here is the link.
One common example for using volatile
is to use a volatile boolean
variable as a flag to terminate a thread. If you've started a thread, and you want to be able to safely interrupt it from a different thread, you can have the thread periodically check a flag. To stop it, set the flag to true. By making the flag volatile
, you can ensure that the thread that is checking it will see it has been set the next time it checks it without having to even use a synchronized
block.
You don't need to override onBackPressed()
- it's already defined as the action that your activity will do by default when the user pressed the back button. So just call onBackPressed()
whenever you want to "programatically press" the back button.
That would only result to finish()
being called, though ;)
I think you're confused with what the back button does. By default, it's just a call to finish()
, so it just exits the current activity. If you have something behind that activity, that screen will show.
What you can do is when launching your activity from the Login, add a CLEAR_TOP flag so the login activity won't be there when you exit yours.
You don't mention the API version, but since API 11 there's the method WebViewClient.shouldInterceptRequest
Maybe this could help?
I have the same error only on the production build. In development was all right, no warning.
The problem was a comment line
ERROR
return ( // comment
<div>foo</div>
)
OK
// comment
return (
<div>foo</div>
)
you can have an interface hierarchy and then extend your classes from selected interfaces :
public interface IAnimal {
}
public interface IBird implements IAnimal {
}
public interface IHorse implements IAnimal {
}
public interface IPegasus implements IBird,IHorse{
}
and then define your classes as needed, by extending a specific interface :
public class Bird implements IBird {
}
public class Horse implements IHorse{
}
public class Pegasus implements IPegasus {
}
set scan off; Above command also works.
In addition to protonpack, jOO?'s Seq provides this functionality (and by extension libraries that build on it like cyclops-react, I am the author of this library).
Seq.seq(Stream.of(names)).zipWithIndex()
.filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
.toList();
Seq also supports just Seq.of(names) and will build a JDK Stream under the covers.
The simple-react equivalent would similarly look like
LazyFutureStream.of(names)
.zipWithIndex()
.filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
.toList();
The simple-react version is more tailored for asynchronous / concurrent processing.
Use FileMode.Truncate
everytime you create the file. Also place the File.Create
inside a try
catch
.
I recommend using .htaccess
. You only need to add:
DirectoryIndex home.php
or whatever page name you want to have for it.
EDIT: basic htaccess tutorial.
1) Create .htaccess
file in the directory where you want to change the index file.
.
in front, to ensure it is a "hidden" fileEnter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.
2) Set server to allow reading of .htaccess
files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)
Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default
for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:
<Directory /var/www/>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:
sudo service apache2 restart
Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.
Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess
file in that sub-site's root and it will overwrite the declaration in the parent.
The formula is
minSdkVersion <= targetSdkVersion <= compileSdkVersion
minSdkVersion - is a marker that defines a minimum Android version on which application will be able to install. Also it is used by Lint to prevent calling API that doesn’t exist. Also it has impact on Build Time. So you can use build flavors to override minSdkVersion to maximum during the development. It will help to make build faster using all improvements that the Android team provides for us. For example some features Java 8 are available only from specific version of minSdkVersion.
targetSdkVersion - If AndroidOS version is >=
targetSdkVersion
it says Android system to turn on specific(new) behavior
changes. *Please note that some of new behaviors will be turned on by default even if thought targetSdkVersion
is <
, you should read official doc.
For example:
Starting in Android 6.0 (API level 23) Runtime Permissions
were introduced. If you set targetSdkVersion
to 22 or lower your application does not ask a user for some permission in run time.
Starting in Android 8.0 (API level 26), all notifications
must be assigned to a channel or it will not appear. On devices running Android 7.1 (API level 25) and lower, users can manage notifications on a per-app basis only (effectively each app only has one channel on Android 7.1 and lower).
Starting in Android 9 (API level 28), Web-based data directories separated by process
. If targetSdkVersion
is 28+ and you create several WebView
in different processes you will get java.lang.RuntimeException
compileSdkVersion - actually it is SDK Platform version and tells Gradle which Android SDK use to compile. When you want to use new features or debug .java
files from Android SDK you should take care of compileSdkVersion. One more example is using AndroidX that forces to use compileSdkVersion
- level 28. compileSdkVersion
is not included in your APK: it is purely used at compile time
. Changing your compileSdkVersion does not change runtime behavior. It can generate for example new compiler warnings/errors. Therefore it is strongly recommended that you always compile with the latest SDK. You’ll get all the benefits of new compilation checks on existing code, avoid newly deprecated APIs, and be ready to use new APIs. One more fact is compileSdkVersion >= Support Library version
You can read more about it here. Also I would recommend you to take a look at the example of migration to Android 8.0.
Martin Porter's official page contains a Porter Stemmer in PHP as well as other languages.
If you're really serious about good stemming though you're going to need to start with something like the Porter Algorithm, refine it by adding rules to fix incorrect cases common to your dataset, and then finally add a lot of exceptions to the rules. This can be easily implemented with key/value pairs (dbm/hash/dictionaries) where the key is the word to look up and the value is the stemmed word to replace the original. A commercial search engine I worked on once ended up with 800 some exceptions to a modified Porter algorithm.
For me, the next worked well:
I wrapped the header and the content on a div
<div class="main-wrapper">
<div class="header">
</div>
<div class="content">
</div>
</div>
I used this reference to fill the height with flexbox. The CSS goes like this:
.main-wrapper {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header {
flex: 1;
}
.content {
flex: 1;
}
For more info about the flexbox technique, visit the reference
Find parameters
The parameters find function takes are as follows:
«Object»
.«Object|String»
optional fields to return, see Query.prototype.select()«Object»
optional see Query.prototype.setOptions()«Function»
How to limit
const Post = require('./models/Post');
Post.find(
{ published: true },
null,
{ sort: { 'date': 'asc' }, limit: 20 },
function(error, posts) {
if (error) return `${error} while finding from post collection`;
return posts; // posts with sorted length of 20
}
);
Extra Info
Mongoose allows you to query your collections in different ways like: Official Documentation
// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});
// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })
// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })
// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});
// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});
// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});
It's all a matter of style. It's useful for debugging but otherwise it shouldn't be used in the final version of the program. It really doesn't matter on the memory issue because I'm sure that those guys who invented the system("pause") were anticipating that it'd be used often. In another perspective, computers get throttled on their memory for everything else we use on the computer anyways and it doesn't pose a direct threat like dynamic memory allocation, so I'd recommend it for debugging code, but nothing else.
Merge squash merges a tree (a sequence of commits) into a single commit. That is, it squashes all changes made in n commits into a single commit.
Rebasing is re-basing, that is, choosing a new base (parent commit) for a tree. Maybe the mercurial term for this is more clear: they call it transplant because it's just that: picking a new ground (parent commit, root) for a tree.
When doing an interactive rebase, you're given the option to either squash, pick, edit or skip the commits you are going to rebase.
Hope that was clear!
Call the TreeView.OnAfterSelect()
protected method after you programatically select the node.
You can use the line below which goes into a closure (viewDidLoad
, didLayOutSubViews
, etc):
self.view.backgroundColor = .redColor()
EDIT Swift 3:
view.backgroundColor = .red
What image do you want to hide? Assuming all images, the following should work:
$("img").hide();
Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.
However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page
While the accepted answer is correct, it is missing the explanation why it works.
First of all, your code should reflect the fact that this is not an array:
var myObject = new Object();
myObject["firstname"] = "Bob";
myObject["lastname"] = "Smith";
myObject["age"] = 25;
Note that all objects (including Array
s) can be used this way. However, do not expect for standard JavaScript array functions (pop, push, etc.) to work on objects!
As said in accepted answer, you can then use delete
to remove the entries from objects:
delete myObject["lastname"]
You should decide which route you wish to take - either use objects (associative arrays / dictionaries) or use arrays (maps). Never mix the two of them.
Yes my dear friends said correctly.
Layer is a logical partition of application whereas tier is physical partition of system
tier partition is depends on layer partition. Just like an application execute on single machine but it follows 3 layered architecture, so we can say that layer architecture could be exist in a tier architecture.
In simple term 3 layer architecture can implement in single machine then we can say that its is 1 tier architecture. If we implement each layer on separate machine then its called
3 tier architecture. A layer may also able to run several tier.
In layer architecture related component to communicate to each other easily.
Just like we follow given below architecture
A client could interact to "presentation layer", but they access public component of below layer's (like business logic layer's public component) to "business logic layer" due to security reason.
Q * why we use layer architecture ?
because if we implement layer architecture then we increase our applications efficiency like
==>security
==>manageability
==>scalability
other need like after developing application we need to change dbms or modify business logic etc. then it is necessary to all.
Q * why we use tier architecture?
because physically implementation of each layer gives a better efficiency ,without layer architecture we can not implement tier architecture. separate machine to implement separate
tier and separate tier is implement one or more layer that's why we use it.
it uses for the purposes of fault tolerance.
==>easy to maintain.
Simple example
Just like a bank open in a chamber, in which categories the employee:
they all are the related components of system.
If we going to bank for loan purpose then first a gate keeper open the door with smile after that we goes to near a person that introduce to all scheme of loan after that we goes to manager cabin and pass the loan. After that finally we goes to cashier's counter take loan. These are layer architecture of bank.
What about tier? A bank's branch open in a town, after that in another town, after that in another but what is the basic requirement of each branch
exactly the same concept of layer and tier.
Here's an idea. Load all of your audio for a certain class of sounds into a single individual audio element where the src data is all of your samples in a contiguous audio file (probably want some silence between so you can catch and cut the samples with a timeout with less risk of bleeding to the next sample). Then, seek to the sample and play it when needed.
If you need more than one of these to play you can create an additional audio element with the same src so that it is cached. Now, you effectively have multiple "tracks". You can utilize groups of tracks with your favorite resource allocation scheme like Round Robin etc.
You could also specify other options like queuing sounds into a track to play when that resource becomes available or cutting a currently playing sample.
Here's your expected snippet which gives you the array of all the matched values -
var windowArray = new Array ("item","thing","id-3-text","class");_x000D_
_x000D_
var result = [];_x000D_
windowArray.forEach(val => {_x000D_
if(val && val.includes('id-')) {_x000D_
result.push(val);_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(result);
_x000D_
Here are some examples for:
1) Simple
2) Fork
3) Threads
based server:
I want to try to break down the answer from @DerMike to explain:
First, type erasure does not mean that the JDK eliminates type information at runtime. It's a method for allowing compile-time type checking and runtime type compatibility to coexist in the same language. As this block of code implies, the JDK retains the erased type information--it's just not associated with checked casts and stuff.
Second, this provides generic type information to a generic class exactly one level up the heirarchy from the concrete type being checked--i.e. an abstract parent class with generic type parameters can find the concrete types corresponding to its type parameters for a concrete implementation of itself that directly inherits from it. If this class were non-abstract and instantiated, or the concrete implementation were two levels down, this wouldn't work (although a little bit of jimmying could make it apply to any predetermined number of levels beyond one, or up to the lowest class with X generic type parameters, et cetera).
Anyway, on to the explanation. Here's the code again, separated into lines for ease of reference:
1# Class genericParameter0OfThisClass = 2# (Class) 3# ((ParameterizedType) 4# getClass() 5# .getGenericSuperclass()) 6# .getActualTypeArguments()[0];
Let 'us' be the abstract class with generic types that contains this code. Reading this roughly inside out:
...and that's pretty much it. So we push type info from our own concrete implementation back into ourselves, and use it to access a class handle. we could double up getGenericSuperclass() and go two levels, or eliminate getGenericSuperclass() and get values for ourselves as a concrete type (caveat: I haven't tested these scenarios, they haven't come up for me yet).
It gets tricky if your concrete children are be an arbitrary number of hops away, or if you're concrete and not final, and especially tricky if you expect any of your (variably deep) children to have their own generics. But you can usually design around those considerations, so this gets you most of the way.
Hope this helped someone! I recognize this post is ancient. I'll probably snip this explanation and keep it for other questions.
One solution would be to divide your table into 20 columns of 5% width each, then use colspan on each real column to get the desired width, like this:
<html>_x000D_
<body bgcolor="#14B3D9">_x000D_
<table width="100%" border="1" bgcolor="#ffffff">_x000D_
<colgroup>_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
<col width="5%"><col width="5%">_x000D_
</colgroup>_x000D_
<tr>_x000D_
<td colspan=5>25</td>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=5>25</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td colspan=10>50</td>_x000D_
<td colspan=6>30</td>_x000D_
<td colspan=4>20</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
If you wanna use a URL just you can use this code.
<link rel="shortcut icon" type="image/x-icon" href="https://..." />
Select id,name,age
from
(
Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like "%a%"
) results
order by name
var fs = require("fs");
function readFileLineByLine(filename, processline) {
var stream = fs.createReadStream(filename);
var s = "";
stream.on("data", function(data) {
s += data.toString('utf8');
var lines = s.split("\n");
for (var i = 0; i < lines.length - 1; i++)
processline(lines[i]);
s = lines[lines.length - 1];
});
stream.on("end",function() {
var lines = s.split("\n");
for (var i = 0; i < lines.length; i++)
processline(lines[i]);
});
}
var linenumber = 0;
readFileLineByLine(filename, function(line) {
console.log(++linenumber + " -- " + line);
});
Turing-completeness is not only about "defining functions" or "have ifs/loops/etc". For example, Haskell doesn't have "loop", lambda-calculus don't have "ifs", etc...
For example, this site: http://experthuman.com/programming-with-nothing. The author uses Ruby and create a "FizzBuzz" program with only closures (no strings, numbers, or anything like that)...
There are examples when people compute some arithmetical functions on Scala using only the type system
So, yes, in my opinion, CSS3+HTML is turing-complete (even if you can't exactly do any real computation with then without becoming crazy)
Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.
So, to get around this, I've employed a solution that mixes the best of both worlds.
void IDisposable.Dispose()
{
bool success = false;
try
{
if (State != CommunicationState.Faulted)
{
Close();
success = true;
}
}
finally
{
if (!success)
Abort();
}
}
Ruby 2.6.0 enables casting to an integer without raising an exception, and will return nil
if the cast fails. And since nil
mostly behaves like false
in Ruby, you can easily check for an integer like so:
if Integer(my_var, exception: false)
# do something if my_var can be cast to an integer
end
nltk have its pre-trained tokenizer models. Model is downloading from internally predefined web sources and stored at path of installed nltk package while executing following possible function calls.
E.g. 1 tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
E.g. 2 nltk.download('punkt')
If you call above sentence in your code, Make sure you have internet connection without any firewall protections.
I would like to share some more better alter-net way to resolve above issue with more better deep understandings.
Please follow following steps and enjoy english word tokenization using nltk.
Step 1: First download the "english.pickle" model following web path.
Goto link "http://www.nltk.org/nltk_data/" and click on "download" at option "107. Punkt Tokenizer Models"
Step 2: Extract the downloaded "punkt.zip" file and find the "english.pickle" file from it and place in C drive.
Step 3: copy paste following code and execute.
from nltk.data import load
from nltk.tokenize.treebank import TreebankWordTokenizer
sentences = [
"Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
"Professor Plum has a green plant in his study.",
"Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
]
tokenizer = load('file:C:/english.pickle')
treebank_word_tokenize = TreebankWordTokenizer().tokenize
wordToken = []
for sent in sentences:
subSentToken = []
for subSent in tokenizer.tokenize(sent):
subSentToken.extend([token for token in treebank_word_tokenize(subSent)])
wordToken.append(subSentToken)
for token in wordToken:
print token
Let me know, if you face any problem
I like ranges for this:
def first_half(list)
list[0...(list.length / 2)]
end
def last_half(list)
list[(list.length / 2)..list.length]
end
However, be very careful about whether the endpoint is included in your range. This becomes critical on an odd-length list where you need to choose where you're going to break the middle. Otherwise you'll end up double-counting the middle element.
The above example will consistently put the middle element in the last half.
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
I have the same issue, when I close the chrome window popup browser inspector its working fine for me.
new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.
@fooMonster article worked for me
# git ls-tree HEAD
100644 blob 55c0287d4ef21f15b97eb1f107451b88b479bffe script.sh
As you can see the file has 644 permission (ignoring the 100). We would like to change it to 755:
# git update-index --chmod=+x script.sh
commit the changes
# git commit -m "Changing file permissions"
[master 77b171e] Changing file permissions
0 files changed, 0 insertions(+), 0 deletions(-)
mode change 100644 => 100755 script.sh
If you want to display an image file on the phone, you can do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageBitmap(BitmapFactory.decodeFile("pathToImageFile"));
If you want to display an image from your drawable resources, do this:
private ImageView mImageView;
mImageView = (ImageView) findViewById(R.id.imageViewId);
mImageView.setImageResource(R.drawable.imageFileId);
You'll find the drawable
folder(s) in the project res
folder. You can put your image files there.
That number indicates Date and Time Styles
You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.
Styles with century (e.g. 100, 101 etc) means year will come in yyyy
format. While styles without century (e.g. 1,7,10) means year will come in yy
format.
You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.
I believe this would be most correct.
printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);
printf()
is a variadic function and must be passed arguments of the right types. The standard says %p
takes void *
.
A variation of https://stackoverflow.com/a/12430764/589165 is
> nchar(gsub("[^a]", "", q.data$string))
[1] 2 1 0
mklement0's answer is great, but I have some small tweaks.
It seems like a good idea to explicitly specify bash
's encoding when using iconv
. Also, we should prepend a byte-order mark (even though the unicode standard doesn't recommend it) because there can be legitimate confusions between UTF-8 and ASCII without a byte-order mark. Unfortunately, iconv
doesn't prepend a byte-order mark when you explicitly specify an endianness (UTF-16BE
or UTF-16LE
), so we need to use UTF-16
, which uses platform-specific endianness, and then use file --mime-encoding
to discover the true endianness iconv
used.
(I uppercase all my encodings because when you list all of iconv
's supported encodings with iconv -l
they are all uppercase.)
# Find out MY_FILE's encoding
# We'll convert back to this at the end
FILE_ENCODING="$( file --brief --mime-encoding MY_FILE )"
# Find out bash's encoding, with which we should encode
# MY_FILE so sed doesn't fail with
# sed: RE error: illegal byte sequence
BASH_ENCODING="$( locale charmap | tr [:lower:] [:upper:] )"
# Convert to UTF-16 (unknown endianness) so iconv ensures
# we have a byte-order mark
iconv -f "$FILE_ENCODING" -t UTF-16 MY_FILE > MY_FILE.utf16_encoding
# Whether we're using UTF-16BE or UTF-16LE
UTF16_ENCODING="$( file --brief --mime-encoding MY_FILE.utf16_encoding )"
# Now we can use MY_FILE.bash_encoding with sed
iconv -f "$UTF16_ENCODING" -t "$BASH_ENCODING" MY_FILE.utf16_encoding > MY_FILE.bash_encoding
# sed!
sed 's/.*/&/' MY_FILE.bash_encoding > MY_FILE_SEDDED.bash_encoding
# now convert MY_FILE_SEDDED.bash_encoding back to its original encoding
iconv -f "$BASH_ENCODING" -t "$FILE_ENCODING" MY_FILE_SEDDED.bash_encoding > MY_FILE_SEDDED
# Now MY_FILE_SEDDED has been processed by sed, and is in the same encoding as MY_FILE
You can use the code from this minimal plugin. https://www.npmjs.com/package/paginator-js
Array.prototype.paginate = function(pageNumber, itemsPerPage){
pageNumber = Number(pageNumber)
itemsPerPage = Number(itemsPerPage)
pageNumber = (pageNumber < 1 || isNaN(pageNumber)) ? 1 : pageNumber
itemsPerPage = (itemsPerPage < 1 || isNaN(itemsPerPage)) ? 1 : itemsPerPage
var start = ((pageNumber - 1) * itemsPerPage)
var end = start + itemsPerPage
var loopCount = 0
var result = {
data: [],
end: false
}
for(loopCount = start; loopCount < end; loopCount++){
this[loopCount] && result.data.push(this[loopCount]);
}
if(loopCount == this.length){
result.end = true
}
return result
}
I think a better answer here is simply this:
mike@sleepycat:~? kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
As for the "significance" of 9... I would say there is probably none. According to The Linux Programming Interface(p 388):
Each signal is defined as a unique (small) integer, starting sequentially from 1. These integers are defined in with symbolic names of the form SIGxxxx . Since the actual numbers used for each signal vary across implementations, it is these symbolic names that are always used in programs.
Use:
git checkout -b serverfix origin/serverfix
This is a common enough operation that Git provides the --track
shorthand:
git checkout --track origin/serverfix
In fact, this is so common that there’s even a shortcut for that shortcut. If the branch name you’re trying to checkout (a) doesn’t exist and (b) exactly matches a name on only one remote, Git will create a tracking branch for you:
git checkout serverfix
To set up a local branch with a different name than the remote branch, you can easily use the first version with a different local branch name:
git checkout -b sf origin/serverfix
Now, your local branch sf
will automatically pull from origin/serverfix
.
Source: Pro Git, 2nd Edition, written by Scott Chacon and Ben Straub (cut for readability)
As the OP said, TLS v1.1 and v1.2 protocols are supported in API level 16+, but are not enabled by default, we just need to enable it.
Example here uses HttpsUrlConnection
, not HttpUrlConnection
. Follow https://blog.dev-area.net/2015/08/13/android-4-1-enable-tls-1-1-and-tls-1-2/, we can create a factory
class MyFactory extends SSLSocketFactory {
private javax.net.ssl.SSLSocketFactory internalSSLSocketFactory;
public MyFactory() throws KeyManagementException, NoSuchAlgorithmException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
internalSSLSocketFactory = context.getSocketFactory();
}
@Override
public String[] getDefaultCipherSuites() {
return internalSSLSocketFactory.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return internalSSLSocketFactory.getSupportedCipherSuites();
}
@Override
public Socket createSocket() throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket());
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(s, host, port, autoClose));
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port, localHost, localPort));
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(host, port));
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
return enableTLSOnSocket(internalSSLSocketFactory.createSocket(address, port, localAddress, localPort));
}
private Socket enableTLSOnSocket(Socket socket) {
if(socket != null && (socket instanceof SSLSocket)) {
((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
}
return socket;
}
}
No matter which Networking library you use, make sure ((SSLSocket)socket).setEnabledProtocols(new String[] {"TLSv1.1", "TLSv1.2"});
gets called so the Socket has enabled TLS protocols.
Now, you can use that in HttpsUrlConnection
class MyHttpRequestTask extends AsyncTask<String,Integer,String> {
@Override
protected String doInBackground(String... params) {
String my_url = params[0];
try {
URL url = new URL(my_url);
HttpsURLConnection httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setSSLSocketFactory(new MyFactory());
// setting the Request Method Type
httpURLConnection.setRequestMethod("GET");
// adding the headers for request
httpURLConnection.setRequestProperty("Content-Type", "application/json");
String result = readStream(httpURLConnection.getInputStream());
Log.e("My Networking", "We have data" + result.toString());
}catch (Exception e){
e.printStackTrace();
Log.e("My Networking", "Oh no, error occurred " + e.toString());
}
return null;
}
private static String readStream(InputStream is) throws IOException {
final BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("US-ASCII")));
StringBuilder total = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
total.append(line);
}
if (reader != null) {
reader.close();
}
return total.toString();
}
}
For example
new MyHttpRequestTask().execute(myUrl);
Also, remember to bump minSdkVersion
in build.gradle to 16
minSdkVersion 16
Unlike the C#/.NET class library (and most other sensible languages), when you pass a String
in as the string-to-match argument to the string.replace
method, it doesn't do a string replace. It converts the string to a RegExp
and does a regex substitution. As Gumbo explains, a regex substitution requires the g
?lobal flag, which is not on by default, to replace all matches in one go.
If you want a real string-based replace — for example because the match-string is dynamic and might contain characters that have a special meaning in regexen — the JavaScript idiom for that is:
var id= 'c_'+date.split('/').join('');
Use a negative lookahead and a negative lookbehind:
> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']
In other words, you always split by \s
(whitespace), and only split by commas and periods if they are not followed (?!\d)
or preceded (?<!\d)
by a digit.
DEMO.
EDIT: As per @verdesmarald comment, you may want to use the following instead:
> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']
This will split "1.2,a,5"
into ["1.2", "a", "5"]
.
DEMO.
Simply using
<option value="" selected disabled>Please select an option...</option>
will work anywhere without script and allow you to instruct the user at the same time.
In android pre Lollipop devices you can do it from SystemBarTintManager If you are using android studio just add Systembartint lib in your gradle file.
dependencies {
compile 'com.readystatesoftware.systembartint:systembartint:1.0.3'
...
}
Then in your activity
// create manager instance after the content view is set
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
// enable status bar tint
mTintManager.setStatusBarTintEnabled(true);
mTintManager.setTintColor(getResources().getColor(R.color.blue));
var data = {
"items": [{
"id": 1,
"category": "cat1"
}, {
"id": 2,
"category": "cat2"
}, {
"id": 3,
"category": "cat1"
}]
};
var returnedData = $.grep(data.items, function (element, index) {
return element.id == 1;
});
alert(returnedData[0].id + " " + returnedData[0].category);
The returnedData is returning an array of objects, so you can access it by array index.
Try using in
like this:
>>> x = 'hello'
>>> y = 'll'
>>> y in x
True
This is how I currently store a reference to the previous path in the $rootScope
:
run(['$rootScope', function($rootScope) {
$rootScope.$on('$locationChangeStart', function() {
$rootScope.previousPage = location.pathname;
});
}]);
If there is no randomstate provided the system will use a randomstate that is generated internally. So, when you run the program multiple times you might see different train/test data points and the behavior will be unpredictable. In case, you have an issue with your model you will not be able to recreate it as you do not know the random number that was generated when you ran the program.
If you see the Tree Classifiers - either DT or RF, they try to build a try using an optimal plan. Though most of the times this plan might be the same there could be instances where the tree might be different and so the predictions. When you try to debug your model you may not be able to recreate the same instance for which a Tree was built. So, to avoid all this hassle we use a random_state while building a DecisionTreeClassifier or RandomForestClassifier.
PS: You can go a bit in depth on how the Tree is built in DecisionTree to understand this better.
randomstate is basically used for reproducing your problem the same every time it is run. If you do not use a randomstate in traintestsplit, every time you make the split you might get a different set of train and test data points and will not help you in debugging in case you get an issue.
From Doc:
If int, randomstate is the seed used by the random number generator; If RandomState instance, randomstate is the random number generator; If None, the random number generator is the RandomState instance used by np.random.
Try tail:
tail -n +2 "$FILE"
-n x
: Just print the last x
lines. tail -n 5
would give you the last 5 lines of the input. The +
sign kind of inverts the argument and make tail
print anything but the first x-1
lines. tail -n +1
would print the whole file, tail -n +2
everything but the first line, etc.
GNU tail
is much faster than sed
. tail
is also available on BSD and the -n +2
flag is consistent across both tools. Check the FreeBSD or OS X man pages for more.
The BSD version can be much slower than sed
, though. I wonder how they managed that; tail
should just read a file line by line while sed
does pretty complex operations involving interpreting a script, applying regular expressions and the like.
Note: You may be tempted to use
# THIS WILL GIVE YOU AN EMPTY FILE!
tail -n +2 "$FILE" > "$FILE"
but this will give you an empty file. The reason is that the redirection (>
) happens before tail
is invoked by the shell:
$FILE
tail
tail
process to $FILE
tail
reads from the now empty $FILE
If you want to remove the first line inside the file, you should use:
tail -n +2 "$FILE" > "$FILE.tmp" && mv "$FILE.tmp" "$FILE"
The &&
will make sure that the file doesn't get overwritten when there is a problem.
Give it a try to the jQuery Audit extension (https://chrome.google.com/webstore/detail/jquery-audit/dhhnpbajdcgdmbbcoakfhmfgmemlncjg), after installing follow these steps:
Best solution for me, paste your class
@Override
public void onResume() {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
super.onResume();
}
@Override
public void onStart() {
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
super.onStart();
}
Attaching a Simple Snippet for renaming your current branch (local and on origin):
git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>
Explanation from git docs:
git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.
The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.
--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.
My opinion from my experience saying, that it is always better to use
event.preventDefault()
Practically
to stop or prevent submit event, whenever we required rather than return false
event.preventDefault()
works fine.
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});
After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.
* The arguments which may be supplied in the recovery.command file:
* --send_intent=anystring - write the text out to recovery.intent
* --update_package=path - verify install an OTA package file
* --wipe_data - erase user data (and cache), then reboot
* --wipe_cache - wipe cache (but not user data), then reboot
* --set_encrypted_filesystem=on|off - enables / diasables encrypted fs
Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:
adb shell
recovery --wipe_data
Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.
EDIT:
For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command
For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c
CLOB are like Files, you can read parts of it easily like this
// read the first 1024 characters
String str = myClob.getSubString(0, 1024);
and you can overwrite to it like this
// overwrite first 1024 chars with first 1024 chars in str
myClob.setString(0, str,0,1024);
I don't suggest using StringBuilder and fill it until you get an Exception, almost like adding numbers blindly until you get an overflow. Clob is like a text file and the best way to read it is using a buffer, in case you need to process it, otherwise you can stream it into a local file like this
int s = 0;
File f = new File("out.txt");
FileWriter fw new FileWriter(f);
while (s < myClob.length())
{
fw.write(myClob.getSubString(0, 1024));
s += 1024;
}
fw.flush();
fw.close();
Dictionaries have a built in function called iterkeys()
.
Try:
for team in league.iterkeys():
runs_scored = float(league[team][0])
runs_allowed = float(league[team][1])
win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
print win_percentage
From ioS 7 onwards, there are newer ways for apps to run in background. Apple now recognizes that apps have to constantly download and process data constantly.
- Apps that play audible content to the user while in the background, such as a music player app
- Apps that record audio content while in the background.
- Apps that keep users informed of their location at all times, such as a navigation app
- Apps that support Voice over Internet Protocol (VoIP)
- Apps that need to download and process new content regularly
- Apps that receive regular updates from external accessories
You can declare app's supported background tasks in Info.plist using X Code 5+. For eg. adding UIBackgroundModes key to your app’s Info.plist file and adding a value of 'fetch' to the array allows your app to regularly download and processes small amounts of content from the network. You can do the same in the 'capabilities' tab of Application properties in XCode 5 (attaching a snapshot)
You can find more about this in Apple documentation
If you want to exit from a simple if else
statement but still stays within a particular context (not by returning to the calling context), you can just set the block condition to false:
if(condition){
//do stuff
if(something happens)
condition = false;
}
This will guarantee that there is no further execution, the way I think you want it..You can only use break in a loop
or switch case
you can get this working with js:
<script>
$(document).ready(function() {
var height = Math.max($("#left").height(), $("#right").height());
$("#left").height(height);
$("#right").height(height);
});
</script>
So use the short cut keys , Press ctrl + shift + I and then Click on Magnifying Option on Left side and Then Hover the mouse cursor and you will be navigate to proper way