I am using the following code in such cases:
obj, created = Model.objects.get_or_create(id=some_id)
if not created:
resp= "It was created"
else:
resp= "OK"
obj.save()
-webkit-padding-start: 0;
will remove padding added by webkit engine
AFNetworking for Android:
Fast Android Networking is here
Fast Android Networking Library supports all types of HTTP/HTTPS request like GET, POST, DELETE, HEAD, PUT, PATCH
Fast Android Networking Library supports downloading any type of file
Fast Android Networking Library supports uploading any type of file (supports multipart upload)
Fast Android Networking Library supports cancelling a request
Fast Android Networking Library supports setting priority to any request (LOW, MEDIUM, HIGH, IMMEDIATE)
Fast Android Networking Library supports RxJava
As it uses OkHttp as a networking layer, it supports:
Fast Android Networking Library supports HTTP/2 support allows all requests to the same host to share a socket
Fast Android Networking Library uses connection pooling which reduces request latency (if HTTP/2 isn’t available)
Transparent GZIP shrinks download sizes
Fast Android Networking Library supports response caching which avoids the network completely for repeat requests
Thanks: The library is created by me
You can use this google service free IP geolocation webservice
update
the link is broken, I put here other link that include @NickSweeting in the comments:
and you can get the data in json format:
The C# Replace method usually works for me:
foo = "http://maps.google.com/?q=" + address.Text.Replace(" ","+");
Converting Jason Coco's answer to Swift for the profoundly lazy :)
if ("Some String" .caseInsensitiveCompare("some string") == .OrderedSame)
{
// Strings are equal.
}
The .title()
method can't work well,
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"
Try string.capwords()
method,
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
From the Python documentation on capwords:
Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.
Swift 3, Swift 4:
Change first line to
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool
the rest is same.
Swift 5+:
Instantiate root view controller from storyboard:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// this line is important
self.window = UIWindow(frame: UIScreen.main.bounds)
// In project directory storyboard looks like Main.storyboard,
// you should use only part before ".storyboard" as its name,
// so in this example name is "Main".
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
// controller identifier sets up in storyboard utilities
// panel (on the right), it is called 'Storyboard ID'
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
self.window?.rootViewController = viewController
self.window?.makeKeyAndVisible()
return true
}
If you want to use UINavigationController
as root:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// this line is important
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
let navigationController = UINavigationController.init(rootViewController: viewController)
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
Instantiate root view controller from xib:
It is almost the same, but instead of lines
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "YourViewControllerIdentifier") as! YourViewController
you'll have to write
let viewController = YourViewController(nibName: "YourViewController", bundle: nil)
Please use the following
ddlCity.Items.Clear();
function del_confirm(msg,url)
{
if(confirm(msg))
{
window.location.href=url
}
else
{
false;
}
}
<a onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>
You can use the onsubmit function.
If you return false the form won't get submitted. Read up about it here.
$('#myform').submit(function() {
// your code here
});
I have done it two different ways,
1.) make a Map
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i=0; i<settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
2.) make a JSONArray of names
JSONArray names = json.names();
JSONArray values = json.toJSONArray(names);
for(int i=0; i<values.length(); i++){
if (names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if (names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if (names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if (names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if (names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
You can't do it directly, you should provide your own way to check this. Eg.
class MyClass {
Object attr1, attr2, attr3;
public boolean isValid() {
return attr1 != null && attr2 != null && attr3 != null;
}
}
Or make all fields final and initialize them in constructors so that you can be sure that everything is initialized.
This masks the password with a red square, then reverts back to the original colours once the password has been entered.
It doesn't stop the user from using copy/paste to get the password, but if it's more just about stopping someone looking over your shoulder, this is a good quick solution.
Console.Write("Password ");
ConsoleColor origBG = Console.BackgroundColor; // Store original values
ConsoleColor origFG = Console.ForegroundColor;
Console.BackgroundColor = ConsoleColor.Red; // Set the block colour (could be anything)
Console.ForegroundColor = ConsoleColor.Red;
string Password = Console.ReadLine(); // read the password
Console.BackgroundColor= origBG; // revert back to original
Console.ForegroundColor= origFG;
If you've already got the figure created you can quickly do this:
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)
To propagate the size change to an existing gui window add forward=True
fig.set_size_inches(18.5, 10.5, forward=True)
Both the regex and included files are good methods, and I frequently use those. But another alternative is to use a "named location", which is a useful approach in many situations — especially more complicated ones. The official "If is Evil" page shows essentially the following as a good way to do things:
error_page 418 = @common_location;
location /first/location/ {
return 418;
}
location /second/location/ {
return 418;
}
location @common_location {
# The common configuration...
}
There are advantages and disadvantages to these various approaches. One big advantage to a regex is that you can capture parts of the match and use them to modify the response. Of course, you can usually achieve similar results with the other approaches by either setting a variable in the original block or using map
. The downside of the regex approach is that it can get unwieldy if you want to match a variety of locations, plus the low precedence of a regex might just not fit with how you want to match locations — not to mention that there are apparently performance impacts from regexes in some cases.
The main advantage of including files (as far as I can tell) is that it is a little more flexible about exactly what you can include — it doesn't have to be a full location block, for example. But it's also just subjectively a bit clunkier than named locations.
Also note that there is a related solution that you may be able to use in similar situations: nested locations. The idea is that you would start with a very general location, apply some configuration common to several of the possible matches, and then have separate nested locations for the different types of paths that you want to match. For example, it might be useful to do something like this:
location /specialpages/ {
# some config
location /specialpages/static/ {
try_files $uri $uri/ =404;
}
location /specialpages/dynamic/ {
proxy_pass http://127.0.0.1;
}
}
I came across this question when I was looking for a way to pass a Date object. In my case, as was suggested among the answers, I used Bundle.putSerializable() but that wouldn't work for a complex thing as the described DataManager in the original post.
My suggestion that will give a very similar result to putting said DataManager in the Application or make it a Singleton is to use Dependency Injection and bind the DataManager to a Singleton scope and inject the DataManager wherever it is needed. Not only do you get the benefit of increased testability but you'll also get cleaner code without all of the boiler plate "passing dependencies around between classes and activities" code. (Robo)Guice is very easy to work with and the new Dagger framework looks promising as well.
I faced the same issue, and I found out the problem was the location of my images.
Instead of saving them into the src
folder, you should store them in the public
directory and have direct access.
Kudos.
How i solved
# yum update
# yum install -y https://centos7.iuscommunity.org/ius-release.rpm
# yum install -y python36u python36u-libs python36u-devel python36u-pip
# pip3.6 install pipenv
I hope it will help Someone to resolve "gcc" issue.
You can try with this code
Image.Save("myfile.png", ImageFormat.Png)
Link : http://msdn.microsoft.com/en-us/library/ms142147.aspx
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
Using both jquery Load and Ready neither seemed to really match when the iframe was TRULY ready.
I ended up doing something like this
$('#iframe').ready(function () {
$("#loader").fadeOut(2500, function (sender) {
$(sender).remove();
});
});
Where #loader is an absolutely positioned div over top the iframe with a spinner gif.
imagesLoaded Plugin is way to go ,if you need a crossbrowser solution
$("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
if($broken.length > 0){
//Error CallBack
console.log('Error');
}
else{
// Load CallBack
console.log('Load');
}
});
If You Just Need a IE WorkAround,This Will Do
var img = $("<img>", {
error: function() {console.log('error'); },
load: function() {console.log('load');}
});
img.attr('src','image.jpg');
My PHP framework uses
SET LOCAL time_zone='Whatever'
on after connect, where 'Whatever' == date_default_timezone_get()
Not my solution, but this ensures SYSTEM
timezone of MySQL server is always the same as PHP's one
So, yes, PHP is strongly envolved and can affect it
Try ceiling...
SELECT Ceiling(45.01), Ceiling(45.49), Ceiling(45.99)
(Angular 2 - Angular 7)
Component can be declared in a single module only. In order to use a component from another module, you need to do two simple tasks:
1st Module:
Have a component (lets call it: "ImportantCopmonent"), we want to re-use in the 2nd Module's page.
@NgModule({
declarations: [
FirstPage,
ImportantCopmonent // <-- Enable using the component html tag in current module
],
imports: [
IonicPageModule.forChild(NotImportantPage),
TranslateModule.forChild(),
],
exports: [
FirstPage,
ImportantCopmonent // <--- Enable using the component in other modules
]
})
export class FirstPageModule { }
2nd Module:
Reuses the "ImportantCopmonent", by importing the FirstPageModule
@NgModule({
declarations: [
SecondPage,
Example2ndComponent,
Example3rdComponent
],
imports: [
IonicPageModule.forChild(SecondPage),
TranslateModule.forChild(),
FirstPageModule // <--- this Imports the source module, with its exports
],
exports: [
SecondPage,
]
})
export class SecondPageModule { }
Ok, I solved it. Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.
@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
//Content goes here
}
Yes, it's simple. Just add the DateTimeFormat annotation.
You probably want to use some Unicode character encoding, for example UTF-8, and htmlspecialchars. Because there isn't any need to generate "HTML entities" for "all [the] applicable characters" (that is what htmlentities does according to the documentation) if it's already in your character set.
Try this:
import matplotlib
matplotlib.use('TkAgg')
BEFORE import pylab
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedAfter losing hours trying to find my error, the problem is your formula:
sigma = sum(y*(x-mean)**2)/n
This previous formula is wrong, the correct formula is the square root of this!;
sqrt(sum(y*(x-mean)**2)/n)
Hope this helps
It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.
A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.
SELECT
vars.BalanceDue
FROM
Entity e
OUTER APPLY (
SELECT
-- variables
BalanceDue = e.EntityTypeId,
Variable2 = ...some..long..complex..expression..etc...
) vars
WHERE
vars.BalanceDue > 0
Kudos to Syed Mehroz Alam.
There are two features of null we should understand:
You can assign null to a variable to denote that currently that variable does not have any value but it will have later on. A null means absence of a value.
example:-
let a = null;
console.log(a); //null
File f = new File(fileName);
byte[] fileContent = msg.getByteSequenceContent();
Path path = Paths.get(f.getAbsolutePath());
try {
Files.write(path, fileContent);
} catch (IOException ex) {
Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}
I know this is an old question, but here is a solution that doesn't use any extra data structures or libraries. It is linear in the number of elements of the input list and I cannot think of any other way to make it more efficient (actually if anyone knows of a better way to allocate the result, please let me know).
NOTE: this would be much faster using a numpy array instead of a list, but I wanted to eliminate all dependencies. It would also be possible to improve performance by multi-threaded execution
The function assumes that the input list is one dimensional, so be careful.
### Running mean/Moving average
def running_mean(l, N):
sum = 0
result = list( 0 for x in l)
for i in range( 0, N ):
sum = sum + l[i]
result[i] = sum / (i+1)
for i in range( N, len(l) ):
sum = sum - l[i-N] + l[i]
result[i] = sum / N
return result
Example
Assume that we have a list data = [ 1, 2, 3, 4, 5, 6 ]
on which we want to compute a rolling mean with period of 3, and that you also want a output list that is the same size of the input one (that's most often the case).
The first element has index 0, so the rolling mean should be computed on elements of index -2, -1 and 0. Obviously we don't have data[-2] and data[-1] (unless you want to use special boundary conditions), so we assume that those elements are 0. This is equivalent to zero-padding the list, except we don't actually pad it, just keep track of the indices that require padding (from 0 to N-1).
So, for the first N elements we just keep adding up the elements in an accumulator.
result[0] = (0 + 0 + 1) / 3 = 0.333 == (sum + 1) / 3
result[1] = (0 + 1 + 2) / 3 = 1 == (sum + 2) / 3
result[2] = (1 + 2 + 3) / 3 = 2 == (sum + 3) / 3
From elements N+1 forwards simple accumulation doesn't work. we expect result[3] = (2 + 3 + 4)/3 = 3
but this is different from (sum + 4)/3 = 3.333
.
The way to compute the correct value is to subtract data[0] = 1
from sum+4
, thus giving sum + 4 - 1 = 9
.
This happens because currently sum = data[0] + data[1] + data[2]
, but it is also true for every i >= N
because, before the subtraction, sum
is data[i-N] + ... + data[i-2] + data[i-1]
.
use jquery
$("#item").change(function({
var x=$(this).val();
});
Your value will be in x
variable, use this variable value in your jsp, like this {x}
this statement will give the value
Or this will work too the same way but without a save as choice:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
(function () {
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.getElementById('downloadlink');
link.href = makeTextFile(textbox.value);
link.style.display = 'block';
}, false);
})();
}//]]>
</script>
</head>
<body>
<textarea id="textbox">Type something here</textarea> <button id="create">Create file</button> <a download="info.txt" id="downloadlink" style="display: none">Download</a>
<script>
// tell the embed parent frame the height of the content
if (window.parent && window.parent.parent){
window.parent.parent.postMessage(["resultsFrame", {
height: document.body.getBoundingClientRect().height,
slug: "qm5AG"
}], "*")
}
</script>
</body>
</html>
Your __init__.py
should have a docstring.
Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email
package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.
For any other content, see the excellent answers by firecrow and Alex Martelli.
i was looking for changing second row html and you can do cascading selector
$('#tbox1 tr:nth-child(2) td').html(11111)
"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.
The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.
Below can be the required mapping,
<class name="com.example.CompanyEntity" table="COMPANY">
<id name="id" column="COMPANY_ID"/>
<set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
<key column="COMPANY_ID" not-null="true"/>
<one-to-many entity-name="vendorName"/>
</set>
</class>
Here is the right way to do imports in Java.
import Dan.Vik;
class Kab
{
public static void main(String args[])
{
Vik Sam = new Vik();
Sam.disp();
}
}
You don't import methods in java. There is an advanced usage of static imports but basically you just import packages and classes. If the function you are importing is a static function you can do a static import, but I don't think you are looking for static imports here.
Or you can try CGI.unescapeHTML method.
CGI.unescapeHTML "<p>This is a Paragraph.</p>"
=> "<p>This is a Paragraph.</p>"
To expound more on @vrian's answer
To view the bootstrap version of a website in your web browser, do the following:
First Method:
boostrap.min.js
or boostrap.min.css
. It should look like this <link href="assets/css/bootstrap.min.css" rel="stylesheet" />
Bootstrap v4.4.1 (https://getbootstrap.com/)
Second Method:
boostrap.min.css
Bootstrap v4.4.1 (https://getbootstrap.com/)
That's all
I hope this helps
it occured when I changed the applicationId in app gradle file. It works for me after I sync gradle.
If you application depends on 3d-party code (in Xsl-scripts) then you have to decide first do you want to defend from bugs in them or not. If you really want to defend then I think you should execute your logic which prone to external errors in separate AppDomains. Catching StackOverflowException is not good.
Check also this question.
You are comparing two objects for equality. The snippet:
if (obj == this) { return true; }
is a quick test that can be read
"If the object I'm comparing myself to is me, return true"
. You usually see this happen in equals
methods so they can exit early and avoid other costly comparisons.
If you are willing to use your own custom output format, you would be able to get the desired behaviour with RDD as well.
Have a look at the following classes: FileOutputFormat, FileOutputCommitter
In file output format you have a method named checkOutputSpecs, which is checking whether the output directory exists. In FileOutputCommitter you have the commitJob which is usually transferring data from the temporary directory to its final place.
I wasn't able to verify it yet (would do it, as soon as I have few free minutes) but theoretically: If I extend FileOutputFormat and override checkOutputSpecs to a method that doesn't throw exception on directory already exists, and adjust the commitJob method of my custom output committer to perform which ever logic that I want (e.g. Override some of the files, append others) than I may be able to achieve the desired behaviour with RDDs as well.
The output format is passed to: saveAsNewAPIHadoopFile (which is the method saveAsTextFile called as well to actually save the files). And the Output committer is configured at the application level.
I've just attempted this - I needed to test some development code on my localhost Apache on Windows. This was WAAAY more difficult than it should be. But here are the steps that managed to work after much hairpulling...
I found that my Apache install comes with openssl.exe
which is helpful. If you don't have a copy, you'll need to download it. My copy was in Apache2\bin
folder which is how I reference it below.
Steps:
Apache2\conf
folder..\bin\openssl req -config openssl.cnf -new -out blarg.csr -keyout blarg.pem
You can leave all questions blank except:
When that completes, type
..\bin\openssl rsa -in blarg.pem -out blarg.key
Generate your self-signed certificate by typing:
..\bin\openssl x509 -in blarg.csr -out blarg.cert -req -signkey blarg.key -days 365
Open Apache's conf\httpd.conf
file and ensure SSL module is enabled - there should be no hash at the start of this line:
LoadModule ssl_module modules/mod_ssl.so
Some Apache installations place the SSL config in a separate file. If so, ensure that the SSL conf file is being included. In my case I had to uncomment this line:
Include conf/extra/httpd-ssl.conf
In the SSL config httpd-ssl.conf
I had to update the following lines:
SSLSessionCache "shmcb:C:\Program Files (x86)\Zend\Apache2/logs/ssl_scache(512000)"
SSLSessionCache "shmcb:C:/Progra\~2/Zend/Apache2/logs/ssl_scache(512000)"
DocumentRoot
- set this to the folder for your web filesServerName
- the server's hostnameSSLCertificateFile "conf/blarg.cert"
SSLCertificateKeyFile "conf/blarg.key"
Restart Apache.
https://localhost/
in your browser.Hopefully you made it this far. Feel free to update this post with any other helpful info.
(Screenshots courtesy of Neil Obremski and his helpful article - although now quite out-of-date.)
This means that you must declare strict mode by writing "use strict"
at the beginning of the file or the function to use block-scope declarations.
EX:
function test(){
"use strict";
let a = 1;
}
This works for me on the webpack.config.js
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
}),
in another javascript or into HTML add:
global.jQuery = require('jquery');
If you really need to be sure that now()
has the same value you can run two queries (that will answer to your second question too, in that case you are asking to update last_monitor = to last_update
but last_update
hasn't been updated yet)
you could do something like:
mysql> update table set last_update=now() where id=1;
mysql> update table set last_monitor = last_update where id=1;
anyway I think that mysql is clever enough to ask for now()
only once per query.
I solved the issue by adding this import
More info
from past.builtins import xrange
You can use math.ceil()
to round up, and then multiply by 10
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
To use just do
>>roundup(45)
50
I think you can almost do exactly what you thought would be ideal, using the statsmodels package which was one of pandas
' optional dependencies before pandas
' version 0.20.0 (it was used for a few things in pandas.stats
.)
>>> import pandas as pd
>>> import statsmodels.formula.api as sm
>>> df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]})
>>> result = sm.ols(formula="A ~ B + C", data=df).fit()
>>> print(result.params)
Intercept 14.952480
B 0.401182
C 0.000352
dtype: float64
>>> print(result.summary())
OLS Regression Results
==============================================================================
Dep. Variable: A R-squared: 0.579
Model: OLS Adj. R-squared: 0.158
Method: Least Squares F-statistic: 1.375
Date: Thu, 14 Nov 2013 Prob (F-statistic): 0.421
Time: 20:04:30 Log-Likelihood: -18.178
No. Observations: 5 AIC: 42.36
Df Residuals: 2 BIC: 41.19
Df Model: 2
==============================================================================
coef std err t P>|t| [95.0% Conf. Int.]
------------------------------------------------------------------------------
Intercept 14.9525 17.764 0.842 0.489 -61.481 91.386
B 0.4012 0.650 0.617 0.600 -2.394 3.197
C 0.0004 0.001 0.650 0.583 -0.002 0.003
==============================================================================
Omnibus: nan Durbin-Watson: 1.061
Prob(Omnibus): nan Jarque-Bera (JB): 0.498
Skew: -0.123 Prob(JB): 0.780
Kurtosis: 1.474 Cond. No. 5.21e+04
==============================================================================
Warnings:
[1] The condition number is large, 5.21e+04. This might indicate that there are
strong multicollinearity or other numerical problems.
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
As said, to follow redirects you can use the flag -L
or --location
:
curl -L http://www.example.com
But, if you want limit the number of redirects, add the parameter --max-redirs
--max-redirs <num>
Set maximum number of redirection-followings allowed. If
-L
,--location
is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.
To redirect to another page, you can use:
window.location = "http://www.yoururl.com";
if you are using SQL Server use convert
e.g. select convert(varchar(10), DeliveryDate, 103) as ShortDate
more information here: http://msdn.microsoft.com/en-us/library/aa226054(v=sql.80).aspx
sleep()
causes the thread to definitely stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle (and probably enter a power saving mode).
yield()
basically means that the thread is not doing anything particularly important and if any other threads or processes need to be run, they should. Otherwise, the current thread will continue to run.
document.getElementById("elementID").scrollIntoView();
Same thing, but wrapping it in a function:
function scrollIntoView(eleID) {
var e = document.getElementById(eleID);
if (!!e && e.scrollIntoView) {
e.scrollIntoView();
}
}
This even works in an IFrame on an iPhone.
Example of using getElementById: http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_document_getelementbyid
I had the same issue, and it turned out to be that MariaDB was set to allow only root to log in locally via the unix_socket plug-in, so clearing that setting allowed successfully logging in with the user specified on the command line, provided a correct password is entered, of course. See this answer on Ask Ubuntu
The fragments onResume()
or onPause()
will be called only when the Activities onResume()
or onPause()
is called.
They are tightly coupled to the Activity
.
Read the Handling the Fragment Lifecycle section of this article.
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.
The number of sessions the database was configured to allow
SELECT name, value
FROM v$parameter
WHERE name = 'sessions'
The number of sessions currently active
SELECT COUNT(*)
FROM v$session
As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
There are a number of dictionary files available online - if you're on linux, a lot of (all?) distros come with an /etc/dictionaries-common/words file, which you can easily parse (words = open('/etc/dictionaries-common/words').readlines()
, eg) for use.
this might be a solution, i have done something similar but this one does not seem to work for example if the necessary function requires administrator privileges it should ask you to restart it as admin.
@echo off
mkdir C:\Users\cmdfolder
if echo=="Access is denied." (goto :1A) else (goto :A4)
:A1
cls
color 0d
echo restart this program as administator
:A4
pause
Is objects
a Linq-To-SQL database context? In which case, you can only use simple expressions to the right of the => operator. The reason is, these expressions are not executed, but are converted to SQL to be executed against the database.
Try this
Arr[] myArray = objects.Select(o => new Obj() {
Var1 = o.someVar,
Var2 = o.var2
}).ToArray();
If it is only one file, you can use following procedure (in putty):
Edit file permission with next command: chmod u+x filename.extension
Off the top of my head, it needs a width
. You need to specify the width of the container you are centering (not the parent width).
The IF statement has these forms in PL/SQL
:
IF THEN
IF THEN ELSE
IF THEN ELSIF
You have used elseif
which in terms of PL/SQL is wrong. That need to be replaced with ELSIF
.
DECLARE
mark NUMBER :=50;
BEGIN
mark :=& mark;
IF (mark BETWEEN 85 AND 100) THEN
dbms_output.put_line('mark is A ');
elsif (mark BETWEEN 50 AND 65) THEN
dbms_output.put_line('mark is D ');
elsif (mark BETWEEN 66 AND 75) THEN
dbms_output.put_line('mark is C ');
elsif (mark BETWEEN 76 AND 84) THEN
dbms_output.put_line('mark is B');
ELSE
dbms_output.put_line('mark is F');
END IF;
END;
/
I tried this using Lambda expression, and it worked.
List<MyList>.Any (x => (String.Equals(x.Name, name, StringComparison.OrdinalIgnoreCase)) && (x.Type == qbType) );
If I get you right, you need ..\..\src
Your call to MessageBox.Show
needs to pass MessageBoxButtons.YesNo
to get the Yes/No buttons instead of the OK button.
Compare the result of that call (which will block execution until the dialog returns) to DialogResult.Yes
....
if (MessageBox.Show("Are you sure?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
// user clicked yes
}
else
{
// user clicked no
}
If you aren't averse to third-party modules, you could check out the fastnumbers module. It provides a function called fast_real that does exactly what this question is asking for and does it faster than a pure-Python implementation:
>>> from fastnumbers import fast_real
>>> fast_real("545.2222")
545.2222
>>> type(fast_real("545.2222"))
float
>>> fast_real("31")
31
>>> type(fast_real("31"))
int
If you read the help file for ?boxplot
, you'll see there is a names=
parameter.
boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))
If you don't have a 'real' certificate (and thus using a self-signed one), in Firefox you can go to:
Options > Privacy & Security > (scroll to the bottom) View Certificates > Servers > Add Exception...
There, fill in the location, eg: https://www.myserver:myport
I would'nt do this with PHP. A database should know, what day is today.( use MySQL->NOW() for example ), so it will be very easy to compare within the Query and return the result, without any problems depending on the used Date-Types
SELECT IF(expireDate < NOW(),TRUE,FALSE) as isExpired FROM tableName
I had the same problem too, but I found a solution.
from tkinter import *
# must add
root = Tk()
root.title("Calculator")
root.iconbitmap(r"image/icon.ico")
root.mainloop()
In the example, what python needed is an icon file, so when you dowload an icon as .png
it won't work cause it needs an .ico
file. So you need to find converters to convert your icon from png
to ico
.
Differences:
{a: &b [*b]}
, which will loop infinitely in some converters. Even with circular detection, a "yaml bomb" is still possible (see xml bomb).Observations:
The following are some of the reasons for the hibernate.dialect
not set issue.
Most of these exceptions are shown in the startup log which is finally followed by the mentioned issue.
Example: In Spring boot app with Postgres DB
org.postgresql.util.PSQLException: FATAL: database "foo" does not exist
In application.properties
file,
spring.datasource.url = jdbc:postgresql://localhost:5432/foo
but foo
didn't exist.
So I created the database from pgAdmin for postgres
CREATE DATABASE foo;
org.postgresql.util.PSQLException: FATAL: password authentication failed for user "postgres"
spring.datasource.username= {DB USERNAME HERE}
spring.datasource.password= {DB PASSWORD HERE}
read
will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:
import boto3
s3 = boto3.resource('s3')
obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8')
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
You can use the text editing controller to manipulate the value inside a textfield.
var textController = new TextEditingController();
Now, create a new textfield and set textController
as the controller for the textfield as shown below.
new TextField(controller: textController)
Now, create a RaisedButton
anywhere in your code and set the desired text in the onPressed
method of the RaisedButton
.
new RaisedButton(
onPressed: () {
textController.text = "New text";
}
),
The statement about CMake being a "build generator" is a common misconception.
It's not technically wrong; it just describes HOW it works, but not WHAT it does.
In the context of the question, they do the same thing: take a bunch of C/C++ files and turn them into a binary.
So, what is the real difference?
CMake is much more high-level. It's tailored to compile C++, for which you write much less build code, but can be also used for general purpose build. make
has some built-in C/C++ rules as well, but they are useless at best.
CMake
does a two-step build: it generates a low-level build script in ninja
or make
or many other generators, and then you run it. All the shell script pieces that are normally piled into Makefile
are only executed at the generation stage. Thus, CMake
build can be orders of magnitude faster.
The grammar of CMake
is much easier to support for external tools than make's.
Once make
builds an artifact, it forgets how it was built. What sources it was built from, what compiler flags? CMake
tracks it, make
leaves it up to you. If one of library sources was removed since the previous version of Makefile
, make
won't rebuild it.
Modern CMake
(starting with version 3.something) works in terms of dependencies between "targets". A target is still a single output file, but it can have transitive ("public"/"interface" in CMake terms) dependencies.
These transitive dependencies can be exposed to or hidden from the dependent packages. CMake
will manage directories for you. With make
, you're stuck on a file-by-file and manage-directories-by-hand level.
You could code up something in make
using intermediate files to cover the last two gaps, but you're on your own. make
does contain a Turing complete language (even two, sometimes three counting Guile); the first two are horrible and the Guile is practically never used.
To be honest, this is what CMake
and make
have in common -- their languages are pretty horrible. Here's what comes to mind:
CMake
has three data types: string, list, and a target with properties. make
has one: string;set_property(TARGET helloworld APPEND PROPERTY INCLUDE_DIRECTORIES "${CMAKE_CURRENT_SOURCE_DIR}")
;You can create a method like
public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}
This method will return the number of days between the 2 days.
Both answers to this question so far are incorrect.
For Linux the correct command is:
gcc -pthread -o term term.c
In general, libraries should follow sources and objects on command line, and -lpthread
is not an "option", it's a library specification. On a system with only libpthread.a
installed,
gcc -lpthread ...
will fail to link.
You're multipling your "1 + 0.01" times the growthRate list, not the item in the list you're iterating through. I've renamed i
to rate
and using that instead. See the updated code below:
def nestEgVariable(salary, save, growthRates):
SavingsRecord = []
fund = 0
depositPerYear = salary * save * 0.01
# V-- rate is a clearer name than i here, since you're iterating through the rates contained in the growthRates list
for rate in growthRates:
# V-- Use the `rate` item in the growthRate list you're iterating through rather than multiplying by the `growthRate` list itself.
fund = fund * (1 + 0.01 * rate) + depositPerYear
SavingsRecord += [fund,]
return SavingsRecord
print nestEgVariable(10000,10,[3,4,5,0,3])
For me the issue is resolved by adding domain name in user name as follow:
string userName="yourUserName";
string password="passowrd";
string hostName="LdapServerHostName";
string domain="yourDomain";
System.DirectoryServices.AuthenticationTypes option = System.DirectoryServices.AuthenticationTypes.SecureSocketsLayer;
string userNameWithDomain = string.Format("{0}@{1}",userName , domain);
DirectoryEntry directoryOU = new DirectoryEntry("LDAP://" + hostName, userNameWithDomain, password, option);
Use SqlCommand.ExecuteScalar() and cast it to an int
:
cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();
In Addition to @Dev Blanked answer, if you want to use an existing bean that was created by Spring the code can be modified to:
@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
@Inject
private ApplicationContext ctx;
@Spy
private SomeService service;
@InjectMocks
private Demo demo;
@Before
public void setUp(){
service = ctx.getBean(SomeService.class);
}
/* ... */
}
This way you don't need to change your code (add another constructor) just to make the tests work.
This worked for me:
Do
$ git status
And check if you have Unmerged paths
# Unmerged paths:
# (use "git reset HEAD <file>..." to unstage)
# (use "git add <file>..." to mark resolution)
#
# both modified: app/assets/images/logo.png
# both modified: app/models/laundry.rb
Fix them with git add
to each of them and try git stash
again.
git add app/assets/images/logo.png
TL;DR Remember, all git branches are themselves used for tracking the history of a set of files. Therefore, isn't every branch actually a "tracking branch", because that's what these branches are used for: to track the history of files over time. Thus we should probably be calling normal git "branches", "tracking-branches", but we don't. Instead we shorten their name to just "branches".
So that's partly why the term "tracking-branches" is so terribly confusing: to the uninitiated it can easily mean 2 different things.
In git the term "Tracking-branch" is a short name for the more complete term: "Remote-tracking-branch".
It's probably better at first if you substitute the more formal terms until you get more comfortable with these concepts.
Let's rephrase your question to this:
The key word here is 'Remote', so skip down to where you get confused and I'll describe what a Remote Tracking branch is and how it's used.
To better understand git terminology, including branches and tracking, which can initially be very confusing, I think it's easiest if you first get crystal clear on what git is and the basic structure of how it works. Without a solid understand like this I promise you'll get lost in the many details, as git has lots of complexity; (translation: lots of people use it for very important things).
The following is an introduction/overview, but you might find this excellent article also informative.
WHAT GIT IS, AND WHAT IT'S FOR
A git repository is like a family photo album: It holds historical snapshots showing how things were in past times. A "snapshot" being a recording of something, at a given moment in time.
A git repository is not limited to holding human family photos. It, rather can be used to record and organize anything that is evolving or changing over time.
The basic idea is to create a book so we can easily look backwards in time,
When you get mired down in the complexity and terminology, try to remember that a git repository is first and foremost, a repository of snapshots, and just like a photo album, it's used to both store and organize these snapshots.
SNAPSHOTS AND TRACKING
tracked - to follow a person or animal by looking for proof that they have been somewhere (dictionary.cambridge.org)
In git, "your project" refers to a directory tree of files (one or more, possibly organized into a tree structure using sub-directories), which you wish to keep a history of.
Git, via a 3 step process, records a "snapshot" of your project's directory tree at a given moment in time.
Each git snapshot of your project, is then organized by "links" pointing to previous snapshots of your project.
One by one, link-by-link, we can look backwards in time to find any previous snapshot of you, or your heritage.
For example, we can start with today's most recent snapshot of you, and then using a link, seek backwards in time, for a photo of you taken perhaps yesterday or last week, or when you were a baby, or even who your mother was, etc.
This is refereed to as "tracking; in this example it is tracking your life, or seeing where you have left a footprint, and where you have come from.
COMMITS
A commit is similar to one page in your photo album with a single snapshot, in that its not just the snapshot contained there, but also has the associated meta information about that snapshot. It includes:
A commit is the most important part of a well organized photo album.
THE FAMILY TREE OVER TIME, WITH BRANCHES AND MERGES
Disambiguation: "Tree" here refers not to a file directory tree, as used above, but rather to a family tree of related parent and child commits over time.
The git family tree structure is modeled on our own, human family trees.
In what follows to help understand links in a simple way, I'll refer to:
You should understand this instinctively, as it is based on the tree of life:
Thus all commits except brand new commits, (you could say "juvenile commits"), have one or more children pointing back at them.
With no children are pointing to a parent, then this commit is only a "growing tip", or where the next child will be born from.
With just one child pointing at a parent, this is just a simple, single parent <-- child relationship.
Line diagram of a simple, single parent chain linking backwards in time:
(older) ... <--link1-- Commit1 <--link2-- Commit2 <--link3-- Commit3 (newest)
BRANCHES
branch - A "branch" is an active line of development. The most recent commit on a branch is referred to as the tip of that branch. The tip of the branch is referenced by a branch head, which moves forward as additional development is done on the branch. A single Git repository can track an arbitrary number of branches, but your working tree is associated with just one of them (the "current" or "checked out" branch), and HEAD points to that branch. (gitglossary)
A git branch also refers to two things:
More than one child pointing --at a--> parent, is what git calls "branching".
NOTE: In reality any child, of any parent, weather first, second, or third, etc., can be seen as their own little branch, with their own growing tip. So a branch is not necessarily a long thing with many nodes, rather it is a little thing, created with just one or more commits from a given parent.
The first child of a parent might be said to be part of that same branch, whereas the successive children of that parent are what are normally called "branches".
In actuality, all children (not just the first) branch from it's parent, or you could say link, but I would argue that each link is actually the core part of a branch.
Formally, a git "branch" is just a name, like 'foo' for example, given to a specific growing tip of a family hierarchy. It's one type of what they call a "ref". (Tags and remotes which I'll explain later are also refs.)
ref - A name that begins with refs/ (e.g. refs/heads/master) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches). There are a few special-purpose refs that do not begin with refs/. The most notable example is HEAD. (gitglossary)
(You should take a look at the file tree inside your .git directory. It's where the structure of git is saved.)
So for example, if your name is Tom, then commits linked together that only include snapshots of you, might be the branch we name "Tom".
So while you might think of a tree branch as all of it's wood, in git a branch is just a name given to it's growing tips, not to the whole stick of wood leading up to it.
The special growing tip and it's branch which an arborist (a guy who prunes fruit trees) would call the "central leader" is what git calls "master".
The master branch always exists.
Line diagram of: Commit1 with 2 children (or what we call a git "branch"):
parent children
+-- Commit <-- Commit <-- Commit (Branch named 'Tom')
/
v
(older) ... <-- Commit1 <-- Commit (Branch named 'master')
Remember, a link only points from child to parent. There is no link pointing the other way, i.e. from old to new, that is from parent to child.
So a parent-commit has no direct way to list it's children-commits, or in other words, what was derived from it.
MERGING
Children have one or more parents.
With just one parent this is just a simple parent <-- child commit.
With more than one parent this is what git calls "merging". Each child can point back to more than one parent at the same time, just as in having both a mother AND father, not just a mother.
Line diagram of: Commit2 with 2 parents (or what we call a git "merge", i.e. Procreation from multiple parents):
parents child
... <-- Commit
v
\
(older) ... <-- Commit1 <-- Commit2
REMOTE
This word is also used to mean 2 different things:
remote repository - A repository which is used to track the same project but resides somewhere else. To communicate with remotes, see fetch or push. (gitglossary)
(The remote repository can even be another git repository on our own computer.) Actually there are two URLS for each remote name, one for pushing (i.e. uploading commits) and one for pulling (i.e. downloading commits) from that remote git repository.
A "remote" is a name (an identifier) which has an associated URL which points to a remote git repository. (It's been described as an alias for a URL, although it's more than that.)
You can setup multiple remotes if you want to pull or push to multiple remote repositories.
Though often you have just one, and it's default name is "origin" (meaning the upstream origin from where you cloned).
origin - The default upstream repository. Most projects have at least one upstream project which they track. By default origin is used for that purpose. New upstream updates will be fetched into remote-tracking branches named origin/name-of-upstream-branch, which you can see using git branch -r. (gitglossary)
Origin represents where you cloned the repository from.
That remote repository is called the "upstream" repository, and your cloned repository is called the "downstream" repository.
upstream - In software development, upstream refers to a direction toward the original authors or maintainers of software that is distributed as source code wikipedia
upstream branch - The default branch that is merged into the branch in question (or the branch in question is rebased onto). It is configured via branch..remote and branch..merge. If the upstream branch of A is origin/B sometimes we say "A is tracking origin/B". (gitglossary)
This is because most of the water generally flows down to you.
From time to time you might push some software back up to the upstream repository, so it can then flow down to all who have cloned it.
REMOTE TRACKING BRANCH
A remote-tracking-branch is first, just a branch name, like any other branch name.
It points at a local growing tip, i.e. a recent commit in your local git repository.
But note that it effectively also points to the same commit in the remote repository that you cloned the commit from.
remote-tracking branch - A ref that is used to follow changes from another repository. It typically looks like refs/remotes/foo/bar (indicating that it tracks a branch named bar in a remote named foo), and matches the right-hand-side of a configured fetch refspec. A remote-tracking branch should not contain direct modifications or have local commits made to it. (gitglossary)
Say the remote you cloned just has 2 commits, like this: parent42 <== child-of-4, and you clone it and now your local git repository has the same exact two commits: parent4 <== child-of-4.
Your remote tracking branch named origin now points to child-of-4.
Now say that a commit is added to the remote, so it looks like this: parent42 <== child-of-4 <== new-baby. To update your local, downstream repository you'll need to fetch new-baby, and add it to your local git repository. Now your local remote-tracking-branch points to new-baby. You get the idea, the concept of a remote-tracking-branch is simply to keep track of what had previously been the tip of a remote branch that you care about.
TRACKING IN ACTION
First we begin tracking a file with git.
Here are the basic commands involved with file tracking:
$ mkdir mydir && cd mydir && git init # create a new git repository
$ git branch # this initially reports no branches
# (IMHO this is a bug!)
$ git status -bs # -b = branch; -s = short # master branch is empty
## No commits yet on master
# ...
$ touch foo # create a new file
$ vim foo # modify it (OPTIONAL)
$ git add foo; commit -m 'your description' # start tracking foo
$ git rm --index foo; commit -m 'your description' # stop tracking foo
$ git rm foo; commit -m 'your description' # stop tracking foo & also delete foo
REMOTE TRACKING IN ACTION
$ git pull # Essentially does: get fetch; git merge # to update our clone
There is much more to learn about fetch, merge, etc, but this should get you off in the right direction I hope.
1. About onCreate() and onUpgrade()
onCreate(..)
is called whenever the app is freshly installed. onUpgrade
is called whenever the app is upgraded and launched and the database version is not the same.
2. Incrementing the db version
You need a constructor like:
MyOpenHelper(Context context) {
super(context, "dbname", null, 2); // 2 is the database version
}
IMPORTANT: Incrementing the app version alone is not enough for onUpgrade
to be called!
3. Don't forget your new users!
Don't forget to add
database.execSQL(DATABASE_CREATE_color);
to your onCreate() method as well or newly installed apps will lack the table.
4. How to deal with multiple database changes over time
When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion
:
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
db.execSQL(DATABASE_CREATE_color);
// we want both updates, so no break statement here...
case 2:
db.execSQL(DATABASE_CREATE_someothertable);
}
}
This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)
5. Keeping your revision numbers under control while developing
And finally... calling
adb uninstall <yourpackagename>
totally uninstalls the app. When you install again, you are guaranteed to hit onCreate
which keeps you from having to keep incrementing the database version into the stratosphere as you develop...
Rule of thumb: Use -a
and -o
inside square brackets, &&
and ||
outside.
It's important to understand the difference between shell syntax and the syntax of the [
command.
&&
and ||
are shell operators. They are used to combine the results of two commands. Because they are shell syntax, they have special syntactical significance and cannot be used as arguments to commands.
[
is not special syntax. It's actually a command with the name [
, also known as test
. Since [
is just a regular command, it uses -a
and -o
for its and and or operators. It can't use &&
and ||
because those are shell syntax that commands don't get to see.
But wait! Bash has a fancier test syntax in the form of [[ ]]
. If you use double square brackets, you get access to things like regexes and wildcards. You can also use shell operators like &&
, ||
, <
, and >
freely inside the brackets because, unlike [
, the double bracketed form is special shell syntax. Bash parses [[
itself so you can write things like [[ $foo == 5 && $bar == 6 ]]
.
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
The simplest solution I have found is this:
Look for the line in the log that looks like this:
04-24 01:14:08.605: I/System.out(31395): invalid_key:Android key mismatch.
Your key "abcdefgHIJKLMN+OPqrstuvwzyz" does not match the allowed keys specified in your
application settings. Check your application settings at
http://www.facebook.com/developers
Copy "abcdefgHIJKLMN+OPqrstuvwzyz" and paste it into the Facebook Android Key Hash area.
Here is a cleaner way getting Year/Month/Day with template literals:
var date = new Date();_x000D_
var formattedDate = `${date.getFullYear()}/${(date.getMonth() + 1)}/${date.getDate()}`;_x000D_
console.log(formattedDate);
_x000D_
You could do the following:
var inputType = $('#inputid').attr('type');
The best and simpler setup with Nginx and Nodejs is to use Nginx as an HTTP and TCP load balancer with proxy_protocol enabled. In this context, Nginx will be able to proxy incoming requests to nodejs, and also terminate SSL connections to the backend Nginx server(s), and not to the proxy server itself. (SSL-PassThrough)
In my opinion, there is no point in giving non-SSL examples, since all web apps are (or should be) using secure environments.
Example config for the proxy server, in /etc/nginx/nginx.conf
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
upstream webserver-http {
server 192.168.1.4; #use a host port instead if using docker
server 192.168.1.5; #use a host port instead if using docker
}
upstream nodejs-http {
server 192.168.1.4:8080; #nodejs listening port
server 192.168.1.5:8080; #nodejs listening port
}
server {
server_name example.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Connection "";
add_header X-Upstream $upstream_addr;
proxy_redirect off;
proxy_connect_timeout 300;
proxy_http_version 1.1;
proxy_buffers 16 16k;
proxy_buffer_size 16k;
proxy_cache_background_update on;
proxy_pass http://webserver-http$request_uri;
}
}
server {
server_name node.example.com;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
add_header X-Upstream $upstream_addr;
proxy_redirect off;
proxy_connect_timeout 300;
proxy_http_version 1.1;
proxy_buffers 16 16k;
proxy_buffer_size 16k;
proxy_cache_background_update on;
proxy_pass http://nodejs-http$request_uri;
}
}
}
stream {
upstream webserver-https {
server 192.168.1.4:443; #use a host port instead if using docker
server 192.168.1.5:443; #use a host port instead if using docker
}
server {
proxy_protocol on;
tcp_nodelay on;
listen 443;
proxy_pass webserver-https;
}
log_format proxy 'Protocol: $protocol - $status $bytes_sent $bytes_received $session_time';
access_log /var/log/nginx/access.log proxy;
error_log /var/log/nginx/error.log debug;
}
Now, let's handle the backend webserver. /etc/nginx/nginx.conf:
user nginx;
worker_processes 1;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
load_module /etc/nginx/modules/ngx_http_geoip2_module.so; # GeoIP2
events {
worker_connections 1024;
}
http {
variables_hash_bucket_size 64;
variables_hash_max_size 2048;
server_tokens off;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
autoindex off;
keepalive_timeout 30;
types_hash_bucket_size 256;
client_max_body_size 100m;
server_names_hash_bucket_size 256;
include mime.types;
default_type application/octet-stream;
index index.php index.html index.htm;
# GeoIP2
log_format main 'Proxy Protocol Address: [$proxy_protocol_addr] '
'"$request" $remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# GeoIP2
log_format main_geo 'Original Client Address: [$realip_remote_addr]- Proxy Protocol Address: [$proxy_protocol_addr] '
'Proxy Protocol Server Address:$proxy_protocol_server_addr - '
'"$request" $remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'$geoip2_data_country_iso $geoip2_data_country_name';
access_log /var/log/nginx/access.log main_geo; # GeoIP2
#===================== GEOIP2 =====================#
geoip2 /usr/share/geoip/GeoLite2-Country.mmdb {
$geoip2_metadata_country_build metadata build_epoch;
$geoip2_data_country_geonameid country geoname_id;
$geoip2_data_country_iso country iso_code;
$geoip2_data_country_name country names en;
$geoip2_data_country_is_eu country is_in_european_union;
}
#geoip2 /usr/share/geoip/GeoLite2-City.mmdb {
# $geoip2_data_city_name city names en;
# $geoip2_data_city_geonameid city geoname_id;
# $geoip2_data_continent_code continent code;
# $geoip2_data_continent_geonameid continent geoname_id;
# $geoip2_data_continent_name continent names en;
# $geoip2_data_location_accuracyradius location accuracy_radius;
# $geoip2_data_location_latitude location latitude;
# $geoip2_data_location_longitude location longitude;
# $geoip2_data_location_metrocode location metro_code;
# $geoip2_data_location_timezone location time_zone;
# $geoip2_data_postal_code postal code;
# $geoip2_data_rcountry_geonameid registered_country geoname_id;
# $geoip2_data_rcountry_iso registered_country iso_code;
# $geoip2_data_rcountry_name registered_country names en;
# $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
# $geoip2_data_region_geonameid subdivisions 0 geoname_id;
# $geoip2_data_region_iso subdivisions 0 iso_code;
# $geoip2_data_region_name subdivisions 0 names en;
#}
#=================Basic Compression=================#
gzip on;
gzip_disable "msie6";
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types text/css text/xml text/plain application/javascript image/jpeg image/png image/gif image/x-icon image/svg+xml image/webp application/font-woff application/json application/vnd.ms-fontobject application/vnd.ms-powerpoint;
gzip_static on;
include /etc/nginx/sites-enabled/example.com-https.conf;
}
Now, let's configure the virtual host with this SSL and proxy_protocol enabled config at /etc/nginx/sites-available/example.com-https.conf:
server {
real_ip_header proxy_protocol;
set_real_ip_from 192.168.1.1; #proxy server ip address
#set_real_ip_from proxy; #proxy container hostname if you are using docker
server_name 192.168.1.4; #Your current server ip address. It will redirect to the domain name.
listen 80;
listen 443 ssl http2;
listen [::]:80;
listen [::]:443 ssl http2;
ssl_certificate /etc/nginx/certs/example.com.crt;
ssl_certificate_key /etc/nginx/certs/example.com.key;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
return 301 https://example.com$request_uri;
}
server {
real_ip_header proxy_protocol;
set_real_ip_from 192.168.1.1; #proxy server ip address
#set_real_ip_from proxy; #proxy container hostname if you are using docker
server_name example.com;
listen *:80;
return 301 https://example.com$request_uri;
}
server {
real_ip_header proxy_protocol;
set_real_ip_from 192.168.1.1; #proxy server ip address
#set_real_ip_from proxy; #proxy container hostname if you are using docker
server_name www.example.com;
listen 80;
listen 443 http2;
listen [::]:80;
listen [::]:443 ssl http2 ;
ssl_certificate /etc/nginx/certs/example.com.crt;
ssl_certificate_key /etc/nginx/certs/example.com.key;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
return 301 https://example.com$request_uri;
}
server {
real_ip_header proxy_protocol;
set_real_ip_from 192.168.1.1; #proxy server ip address
#set_real_ip_from proxy; #proxy container hostname if you are using docker
server_name example.com;
listen 443 proxy_protocol ssl http2;
listen [::]:443 proxy_protocol ssl http2;
root /var/www/html;
charset UTF-8;
add_header Strict-Transport-Security 'max-age=31536000; includeSubDomains; preload';
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy no-referrer;
ssl_prefer_server_ciphers on;
ssl_ciphers "EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH";
ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
keepalive_timeout 70;
ssl_buffer_size 1400;
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 8.8.4.4 valid=86400;
resolver_timeout 10;
ssl_certificate /etc/nginx/certs/example.com.crt;
ssl_certificate_key /etc/nginx/certs/example.com.key;
ssl_trusted_certificate /etc/nginx/certs/example.com.crt;
location ~* \.(jpg|jpe?g|gif|png|ico|cur|gz|svgz|mp4|ogg|ogv|webm|htc|css|js|otf|eot|svg|ttf|woff|woff2)(\?ver=[0-9.]+)?$ {
expires modified 1M;
add_header Access-Control-Allow-Origin '*';
add_header Pragma public;
add_header Cache-Control "public, must-revalidate, proxy-revalidate";
access_log off;
}
location ~ /.well-known { #For issuing LetsEncrypt Certificates
allow all;
}
location / {
index index.php;
try_files $uri $uri/ /index.php?$args;
}
error_page 404 /404.php;
location ~ \.php$ {
try_files $uri =404;
fastcgi_index index.php;
fastcgi_pass unix:/tmp/php7-fpm.sock;
#fastcgi_pass php-container-hostname:9000; (if using docker)
fastcgi_pass_request_headers on;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_intercept_errors on;
fastcgi_ignore_client_abort off;
fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_request_buffering on;
fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;
fastcgi_temp_file_write_size 256k;
include fastcgi_params;
}
location = /robots.txt {
access_log off;
log_not_found off;
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}
And lastly, a sample of 2 nodejs webservers: First server:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.4");
console.log('Server running at http://192.168.1.4:8080/');
Second server:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello From Nodejs\n');
}).listen(8080, "192.168.1.5");
console.log('Server running at http://192.168.1.5:8080/');
Now everything should be perfectly working and load-balanced.
A while back i wrote about How to set up Nginx as a TCP load balancer in Docker. Check it out if you are using Docker.
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
Just Simply paste this code you will get the desired output that you needed.
{{ Form::select ('myselect', ['1' => 'Item 1', '2' => 'Item 2'], 2 , ['id' =>'myselect']) }}` `
free
is not enough, free
just marks the memory as unused, the struct data will be there until overwriting. For safety, set the pointer to NULL
after free
.
Ex:
if (testPerson) {
free(testPerson);
testPerson = NULL;
}
struct
is similar like an array, it is a block of memory. You can access to struct member via its offset. The first struct's member is placed at offset 0
so the address of first struct's member is same as the address of struct.
I think you may be looking for Jagged Arrays, which are different from multi-dimensional arrays (as you are using in your example) in C#. Converting the arrays in your declarations to jagged arrays should make it work. However, you'll still need to use two loops to iterate over all the items in the 2D jagged array.
Within Databricks you can visualize the dataframe in a tabular format. With the command:
display(results)
It will look like
Combining two of the previous results, we have:
int(round(some_float))
This converts a float to an integer fairly dependably.
<T>
is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.
I don't know what a Pool
or PoolFactory
is, but you also mention ArrayList<T>
, which is a standard Java class, so I'll talk to that.
Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer>
for example, that means "An ArrayList
of Integer
s." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>
, which means "a map with String
keys and Integer
values."
Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String>
using your class definition. That would mean two things:
Pool<String>
would have an interface PoolFactory<String>
with a createObject
method that returns String
s.Pool<String>
would contain an ArrayList
of Strings.This is great news, because at another time, I could come along and create a Pool<Integer>
which would use the same code, but have Integer
wherever you see T
in the source.
<Button Content="Click" Width="200" Height="50">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Border" Background="{TemplateBinding Background}">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="LightGreen" TargetName="Border" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
NullPointerException
. That is a bad practice. It is better to ensure that the value is not null.Other users commenting that the Content-Type
is plain/text
when encoding. You have to set the Content-Type
first w.Header().Set
, then the HTTP response code w.WriteHeader
.
If you call w.WriteHeader
first then call w.Header().Set
after you will get plain/text
.
An example handler might look like this;
func SomeHandler(w http.ResponseWriter, r *http.Request) {
data := SomeStruct{}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(data)
}
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
Source: Kubernetes in Action.
You can get the element itself in .each()
, try this instead of using this
$('.Count').each(function (index, value) {
jQuery({ Counter: 0 }).animate({ Counter: value.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
value.text(Math.ceil(this.Counter));
}
});
});
Use String#next
as the counter.
>> n = "000"
>> 3.times { puts "file_#{n.next!}" }
file_001
file_002
file_003
next
is relatively 'clever', meaning you can even go for
>> n = "file_000"
>> 3.times { puts n.next! }
file_001
file_002
file_003
Regular expression is your answer.
$str = preg_replace('/[^a-z\d ]/i', '', $str);
i
stands for case insensitive. ^
means, does not start with. \d
matches any digit. a-z
matches all characters between a
and z
. Because of the i
parameter you don't have to specify a-z
and A-Z
. \d
there is a space, so spaces are allowed in this regex.This is a bit nasty, but:
from datetime import datetime, timedelta
now = datetime.now().time()
# Just use January the first, 2000
d1 = datetime(2000, 1, 1, now.hour, now.minute, now.second)
d2 = d1 + timedelta(hours=1, minutes=23)
print d2.time()
That's shorter.
function IsArrows (e) {
return (e.keyCode >= 37 && e.keyCode <= 40);
}
I ran into a same problem. I was running portable version of android studio so downloaded a package from https://developer.android.com/studio/#downloads and installed it, and like that, done!
If you have a directory open in VSCode, and want to search a subdirectory, then either:
files to include
field enter the path with a leading ./
,or
Find in Folder...
option.The code to compress/decompress a string
public static void CopyTo(Stream src, Stream dest) {
byte[] bytes = new byte[4096];
int cnt;
while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
dest.Write(bytes, 0, cnt);
}
}
public static byte[] Zip(string str) {
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
//msi.CopyTo(gs);
CopyTo(msi, gs);
}
return mso.ToArray();
}
}
public static string Unzip(byte[] bytes) {
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
//gs.CopyTo(mso);
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
}
static void Main(string[] args) {
byte[] r1 = Zip("StringStringStringStringStringStringStringStringStringStringStringStringStringString");
string r2 = Unzip(r1);
}
Remember that Zip
returns a byte[]
, while Unzip
returns a string
. If you want a string from Zip
you can Base64 encode it (for example by using Convert.ToBase64String(r1)
) (the result of Zip
is VERY binary! It isn't something you can print to the screen or write directly in an XML)
The version suggested is for .NET 2.0, for .NET 4.0 use the MemoryStream.CopyTo
.
IMPORTANT: The compressed contents cannot be written to the output stream until the GZipStream
knows that it has all of the input (i.e., to effectively compress it needs all of the data). You need to make sure that you Dispose()
of the GZipStream
before inspecting the output stream (e.g., mso.ToArray()
). This is done with the using() { }
block above. Note that the GZipStream
is the innermost block and the contents are accessed outside of it. The same goes for decompressing: Dispose()
of the GZipStream
before attempting to access the data.
If you are using cPanel you should just click the wee box that allows you to send to external servers by SMTP.
Login to CPanel > Tweak Settings > All> "Restrict outgoing SMTP to root, exim, and mailman (FKA SMTP Tweak)"
As answered here:
In Bourne shell(sh), use the . command to source a file
. filename
Not entirely sure what you are after but in PL/SQL you would simply
DECLARE
v_variable INTEGER;
BEGIN
SELECT mycolumn
INTO v_variable
FROM myTable;
END;
Ollie.
This keymap will duplicate the current line if nothing is selected or duplicate the selected words.
Access:
File/Preferences/Keyboard shortcuts
In the right top corner, click on Open Keyboard Shortcuts (JSON).
Insert this keymap:
{
"key": "shift+alt+d",
"command": "editor.action.duplicateSelection"
}
Use alt+arrows up/down to move the line (Default behaviour of VS Code).
MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.
https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns
The total columns in a row has to add up to 12. So you can do col-md-4 col-md-offset-4. So your breaking up your columns into 3 groups of 4 columns each. Right now you have a 4 column form with an offset by 6 so you are only getting 2 columns to the right side of your form. You can also do col-md-8 col-md-offset-2 which would give you a 8 column form with 2 columns each of space left and right or col-md-6 col-md-offset-3 (6 column form with 3 columns space on each side), etc.
Fileservice.cs
:
public class FileService : IFileService
{
private readonly IWebHostEnvironment env;
public FileService(IWebHostEnvironment env)
{
this.env = env;
}
public string Upload(IFormFile file)
{
var uploadDirecotroy = "uploads/";
var uploadPath = Path.Combine(env.WebRootPath, uploadDirecotroy);
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
var fileName = Guid.NewGuid() + Path.GetExtension(file.FileName);
var filePath = Path.Combine(uploadPath, fileName);
using (var strem = File.Create(filePath))
{
file.CopyTo(strem);
}
return fileName;
}
}
IFileService
:
namespace studentapps.Services
{
public interface IFileService
{
string Upload(IFormFile file);
}
}
StudentController
:
[HttpGet]
public IActionResult Create()
{
var student = new StudentCreateVM();
student.Colleges = dbContext.Colleges.ToList();
return View(student);
}
[HttpPost]
public IActionResult Create([FromForm] StudentCreateVM vm)
{
Student student = new Student()
{
DisplayImage = vm.DisplayImage.FileName,
Name = vm.Name,
Roll_no = vm.Roll_no,
CollegeId = vm.SelectedCollegeId,
};
if (ModelState.IsValid)
{
var fileName = fileService.Upload(vm.DisplayImage);
student.DisplayImage = fileName;
getpath = fileName;
dbContext.Add(student);
dbContext.SaveChanges();
TempData["message"] = "Successfully Added";
}
return RedirectToAction("Index");
}
Is the problem with SUM(billableDuration)
? To find out, try commenting out that line and see if it works.
It could be that the sum is exceeding the maximum int
. If so, try replacing it with SUM(CAST(billableDuration AS BIGINT))
.
for ST3
$language = "language u wish"
if exists,
go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings
else
create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings
and set
{ "extensions": [ "yourextension" ] }
This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )
But if you really want to add some animation while scrolling, you can try my simple plugin (AnimateScroll) which currently supports more than 30 easing styles
This will work in most browsers, even in IE8 , and no libraries of any sort are required. var i is your key.
var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
var keys=[];
for (var i in myJSONObject ) { keys.push(i); }
alert(keys);
Typically you'd define this toward the top of a class:
public static final String WELCOME_MESSAGE = "Hello, welcome to the server";
Of course, use the appropriate member visibility (public
/private
/protected
) based on where you use this constant.
Why not create a webfont with your svg image or images, import the webfont in the css and then just change the color of the glyph using the css color attribute? No javascript needed
For anyone else reading this (in 2019 onwards) unfortunately most JS RSS reading implementations don't now work. Firstly Google API has shut down so this is no longer an option and because of the CORS security policy you generally cannot now request RSS feeds cross-domains.
Using the example on https://www.raymondcamden.com/2015/12/08/parsing-rss-feeds-in-javascript-options (2015) I get the following:
Access to XMLHttpRequest at 'https://feeds.feedburner.com/raymondcamdensblog?format=xml' from origin 'MYSITE' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This is correct and is a security precaution by the end website but does now mean that the answers above are unlikely to work.
My workaround will probably be to parse the RSS feed through PHP and allow the javascript to access my PHP rather than trying to access the end-destination feed itself.
My experience with this was that when I had this in every execution it was fine using the provider as a string like this
Security.addProvider(new BounctCastleProvider());
new JcaPEMKeyConverter().setProvider("BC");
But when I optimized and put the following in the constructor:
if(bounctCastleProvider == null) {
bounctCastleProvider = new BouncyCastleProvider();
}
if(Security.getProvider(bouncyCastleProvider.getName()) == null) {
Security.addProvider(bouncyCastleProvider);
}
Then I had to use provider like this or I would get the above error:
new JcaPEMKeyConverter().setProvider(bouncyCastleProvider);
I am using bcpkix-jdk15on version 1.65
You can use the by()
function:
by(dataFrame, seq_len(nrow(dataFrame)), function(row) dostuff)
But iterating over the rows directly like this is rarely what you want to; you should try to vectorize instead. Can I ask what the actual work in the loop is doing?
I am working with Visual studio 2010, if you would like to split your files to .h and .cpp, include your cpp header at the end of the .h file
This is a "PHP Notice", so you could in theory ignore it. Change php.ini
:
error_reporting = E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
To
error_reporting = E_ALL & ~E_NOTICE
This show all errors, except for notices.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
From your question, you are running python2.7 and Cygwin.
Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.
Set the Python Environmental variables appropriately , for instance in my case:
PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib
In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows
/usr/bin/pydoc
Replace /usr/bin/pydoc with
#! /bin/bash
/cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat
Then add this to $PY_HOME/Scripts/pydoc.bat
rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*
Now when you type in the cygwin bash prompt you should see:
$ pydoc
pydoc - the Python documentation tool
pydoc.py <name> ...
Show text documentation on something. <name>
may be the name of a Python keyword, topic,
function, module, or package, or a dotted
reference to a class or function within a
module or module in a package.
...
If you need the construct for a quick example to play with, use the : operator.
But if you are creating a vector/range of numbers dynamically, then use seq() instead.
Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.
In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,
seq(a, b, -1)
will raise an error for a=2, b=6, because the coder expected a decreasing sequence.
MsSql Syntax : DATEDIFF ( datepart , startdate , enddate )
Oracle: This will returns number of days
select
round(Second_date - First_date) as Diff_InDays,round ((Second_date - First_date) / (30),1) as Diff_InMonths,round ((Second_date - First_date) * (60*24),2) as TimeIn_Minitues
from
(
select
to_date('01/01/2012 01:30:00 PM','mm/dd/yyyy hh:mi:ss am') as First_date
,to_date('05/02/2012 01:35:00 PM','mm/dd/yyyy HH:MI:SS AM') as Second_date
from
dual
) result;
Option 1: select the cell(s), under formatting/number/custom formatting, type in
"BOB" General
now you have a prefix "BOB" next to numbers, dates, booleans, but not next to TEXTs
Option2: As before, but use the following format
_ "BOB" @_
now you have a prefix BOB, this works even if the cell contained text
Cheers, Sudhi
If you don't want to or simply can't use Linq you can also use the static Array.Exists(...);
function:
https://msdn.microsoft.com/en-us/library/yw84x8be%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
var arr = new string[]{"bird","foo","cat","dog"};
var catInside = Array.Exists(
arr, // your Array
(s)=>{ return s == "cat"; } // the Predicate
);
When the Predicate do return true once catInside will be true as well.
I had the same exact isuue with the latest Android Studio 2.3.2 and Instant Run.
here what I did : (I'll give you two ways to achive that one disable for specefic project, and second for whole android studio):
on root of your projct open gradle-->gradle-wrapper.properties then change the value
distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip
and on your project build.gradle change the value
classpath 'com.android.tools.build:gradle:2.2.3'
in older version of AS settings for instant run is
File -> Other Settings -> Default Settings ->Build,Execution,Deployment
However In most recent version of Android Studio i.e 2.3.2 , instant run settings is:
Edited: If for any reason the Instant-run settings is greyed out do this :
Help-> Find Action...
and then type 'enable isntant run' and click (now you should be able to change the value in Preferences... or file->Settings... , if that was the case then this is an Android Studio bug :-)
Unity supports:
1. UnityScript(Is known as Javascript but includes more functionality for the Unity game engine. I think this could be very easy to learn)
2. Boo (No experience)
3. C# (I prefer this as it is useful to learn and you will be able to use this outside of unity as well. I also think it is easy to get used to)
You can use CountDownTimer
which is much more efficient than any other solution posted. You can also produce regular notifications on intervals along the way using its onTick(long)
method
Have a look at this example showing a 30seconds countdown
new CountDownTimer(30000, 1000) {
public void onFinish() {
// When timer is finished
// Execute your code here
}
public void onTick(long millisUntilFinished) {
// millisUntilFinished The amount of time until finished.
}
}.start();
you can use str.index
too:
>>> 'sdfasdf'.index('cc')
Traceback (most recent call last):
File "<pyshell#144>", line 1, in <module>
'sdfasdf'.index('cc')
ValueError: substring not found
>>> 'sdfasdf'.index('df')
1
This seems to be answered - #include <fstream>
.
The message means :-
incomplete type
- the class has not been defined with a full class. The compiler has seen statements such as class ifstream;
which allow it to understand that a class exists, but does not know how much memory the class takes up.
The forward declaration allows the compiler to make more sense of :-
void BindInput( ifstream & inputChannel );
It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.
The has initializer
seems a bit extraneous, but is saying that the incomplete object is being created.
You literally just pass them in std::thread(func1,a,b,c,d);
that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate
is called. You could std::join
or std::detach
it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach
.
This is how it should be done.
std::thread t(func1,a,b,c,d);
t.join();
You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.
You can do it the old fashioned way... with an SQL statement that looks something like this
ALTER TABLE table_name
ADD CONSTRAINT fk_foreign_key_name
FOREIGN KEY (foreign_key_name)
REFERENCES target_table(target_key_name);
This assumes the keys already exist in the relevant table
You have a couple of problems here.
First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.
Change:
<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/>
To:
<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/>
And:
Stock
Stock
So:
<xsd:element name="Stock">
<xsd:complexType>
To:
<xsd:complexType name="Stock">
Make sure you fix the xml closing tags.
The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:
INCORRECT: (the way you showed it)
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
CORRECT:
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />
</schema>
</types>
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.
It would be better if you go the WS-I way when it comes to WSDL authoring.
Other issues may be related to the use of relative vs. absolute URIs in locating external content.
You need to set the default timezone smth like this :
date_default_timezone_set('Europe/Bucharest');
More info about this in http://php.net/manual/en/function.date-default-timezone-set.php
Or you could use @
in front of date to suppress the warning however as the warning states it's not safe to rely on the servers default timezone
replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(string,'a',''),'b',''),'c',''),'d',''),'e',''),'f',''),'g',''),'h',''),'i',''),'j',''),'k',''),'l',''),'m',''),'n',''),'o',''),'p',''),'q',''),'r',''),'s',''),'t',''),'u',''),'v',''),'w',''),'x',''),'y',''),'z',''),'A',''),'B',''),'C',''),'D',''),'E',''),'F',''),'G',''),'H',''),'I',''),'J',''),'K',''),'L',''),'M',''),'N',''),'O',''),'P',''),'Q',''),'R',''),'S',''),'T',''),'U',''),'V',''),'W',''),'X',''),'Y',''),'Z','')*1 AS string
,
:)
Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command:
sudo apt-get install python-boto
Or you can download the boto code from their site and move into the unzipped directory to run
python setup.py install
SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.
In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.
In order to create the view, developer need an utility called createOrReplaceTempView
Just wanted to add that I used Microsoft.Interop libraries, specifically ExportAsFixedFormat function which I did not see used in this thread.
using Microsoft.Office.Interop.Word;
using System.Runtime.InteropServices;
using System.IO;
using Microsoft.Office.Core;
Application app;
public string CreatePDF(string path, string exportDir)
{
Application app = new Application();
app.DisplayAlerts = WdAlertLevel.wdAlertsNone;
app.Visible = true;
var objPresSet = app.Documents;
var objPres = objPresSet.Open(path, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
var pdfFileName = Path.ChangeExtension(path, ".pdf");
var pdfPath = Path.Combine(exportDir, pdfFileName);
try
{
objPres.ExportAsFixedFormat(
pdfPath,
WdExportFormat.wdExportFormatPDF,
false,
WdExportOptimizeFor.wdExportOptimizeForPrint,
WdExportRange.wdExportAllDocument
);
}
catch
{
pdfPath = null;
}
finally
{
objPres.Close();
}
return pdfPath;
}
You don't need use so many prefixes for full use, because if you choose prefix for old firefox, you don't need use prefix for new firefox.
So for full use, enough use this code:
img.grayscale {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#grayscale"); /* Firefox 10+, Firefox on Android */
filter: gray; /* IE6-9 */
-webkit-filter: grayscale(100%); /* Chrome 19+, Safari 6+, Safari 6+ iOS */
}
img.grayscale.disabled {
filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
filter: none;
-webkit-filter: grayscale(0%);
}
You can use multiple ordering on multiple condition,
ORDER BY
(CASE
WHEN @AlphabetBy = 2 THEN [Drug Name]
END) ASC,
CASE
WHEN @TopBy = 1 THEN [Rx Count]
WHEN @TopBy = 2 THEN [Cost]
WHEN @TopBy = 3 THEN [Revenue]
END DESC
In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:
$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>
Once you get >
symbol in the terminal, you have entered into the MongoDB shell.
Run dos2unix or similar utility on it to remove the carriage returns (^M).
This message indicates that your file has dos-style lineendings:
-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory
Utilities like dos2unix
will fix it:
dos2unix <backup.bash >improved-backup.sh
Or, if no such utility is installed, you can accomplish the same thing with translate:
tr -d "\015\032" <backup.bash >improved-backup.sh
As for how those characters got there in the first place, @MadPhysicist had some good comments.
Warning: Answers above only work most of the time!
In jQuery version 3.3.1 (haven't tested other versions)
$("#myList li").length;
works only if your list items don't wrap. If your items wrap in the list then this code counts the number of lines occupied not the number of <li> elements.
$("#myList").children().length;
gets the actual number of <li> elements in your list not the number of lines that are occupied.
Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:
function whywouldyoudothis() {
var n = document.getElementById("non-unique-id");
var a = [];
var i;
while(n) {
a.push(n);
n.id = "a-different-id";
n = document.getElementById("non-unique-id");
}
for(i = 0;i < a.length; ++i) {
a[i].id = "non-unique-id";
}
return a;
}
However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.
EDIT: Given a valid document, the same effect could be achieved thus:
function getElementsById(id) {
return [document.getElementById(id)];
}
That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.
Building off the above (great!) answer, we can also make a horizontal bar plot with just a few adjustments:
# Bring some raw data.
frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
freq_series = pd.Series(frequencies)
y_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='barh')
ax.set_title('Amount Frequency')
ax.set_xlabel('Frequency')
ax.set_ylabel('Amount ($)')
ax.set_yticklabels(y_labels)
ax.set_xlim(-40, 300) # expand xlim to make labels easier to read
rects = ax.patches
# For each bar: Place a label
for rect in rects:
# Get X and Y placement of label from rect.
x_value = rect.get_width()
y_value = rect.get_y() + rect.get_height() / 2
# Number of points between bar and label. Change to your liking.
space = 5
# Vertical alignment for positive values
ha = 'left'
# If value of bar is negative: Place label left of bar
if x_value < 0:
# Invert space to place label to the left
space *= -1
# Horizontally align label at right
ha = 'right'
# Use X value as label and format number with one decimal place
label = "{:.1f}".format(x_value)
# Create annotation
plt.annotate(
label, # Use `label` as label
(x_value, y_value), # Place label at end of the bar
xytext=(space, 0), # Horizontally shift label by `space`
textcoords="offset points", # Interpret `xytext` as offset in points
va='center', # Vertically center label
ha=ha) # Horizontally align label differently for
# positive and negative values.
plt.savefig("image.png")
The solution to avoid the unchecked warning:
class MyMap extends HashMap<String, String> {};
someMap = (MyMap)getApplicationContext().getBean("someMap");
I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...
Here's what I came up with:
python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"
That's the one-liner, here's it a little more readable:
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)
This worked for downloading a tarball. I was able to extract the package and download it after downloading.
EDIT:
To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint
package, but this was tested on my machine and works fine:
#!/usr/bin/env python
from clint.textui import progress
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
total_length = int(r.headers.get('content-length'))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1):
if chunk:
f.write(chunk)
f.flush()
Here's the code:
glPushMatrix();
glTranslatef(18,2,0);
glRotatef(angle, 0, 0, 0.7);
glColor3ub(0,255,255);
glutWireSphere(3,10,10);
glPopMatrix();
In addition to the nested scrolling NestedScrollView
added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener
. Adding a OnScrollChangeListener
to the original ScrollView
below API 23 required subclassing ScrollView
or messing around with the ViewTreeObserver
of the ScrollView
which often means even more work than subclassing. With NestedScrollView
it can be done using the build-in setter.
Change android:stretchColumns
value to *
.
Value 0
means stretch the first column. Value 1
means stretch the second column and so on.
Value *
means stretch all the columns.
You can use function colSums()
to calculate sum of all values. [,-1]
ensures that first column with names of people is excluded.
colSums(people[,-1])
Height Weight
199 425
Assuming there could be multiple columns that are not numeric, or that your column order is not fixed, a more general approach would be:
colSums(Filter(is.numeric, people))
If you are using windows 7 64-bit version, then the solution is found here: http://pypi.python.org/pypi/setuptools
namely, you need to download a python script, run it, and then easy_install will work normally from commandline.
P.S. I agree with the original poster saying that this should work out of the box.
Make sure u close all instances wcfSvcHost and try again. It worked for me!
Use the vector
constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:
int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);
or
test(std::vector<int>(x, x + sizeof x / sizeof x[0]));
where sizeof x / sizeof x[0]
is obviously 3
in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0]
points one element beyond the last element.
I use an immediately invoked lambda for these scenarios:
const config = (() => {
try {
return JSON.parse(fs.readFileSync('config.json'));
} catch (error) {
return {};
}
})();
async
version:
const config = await (async () => {
try {
return JSON.parse(await fs.readFileAsync('config.json'));
} catch (error) {
return {};
}
})();
in my case, i have a cdn,and i am going to place all my processed static files (js,imgs,fonts...) into my cdn,suppose the url is http://my.cdn.com/
so if there is a js file which is the orginal refer url in html is './js/my.js' it should became http://my.cdn.com/js/my.js in production environment
in that case,what i need to do is just set publicpath equals http://my.cdn.com/ and webpack will automatic add that prefix
You can quickly convert deeply nested objects to associative arrays by relying on the behavior of the JSON encode/decode functions:
$array = json_decode(json_encode($response->response->docs), true);
Use this function to regain the utf-8 characters
function decode_utf8(s) {
return decodeURIComponent(escape(s));
}
Example: var new_Str=decode_utf8(str);
Here is a more generic solution for any given weekday. Working demo on jsfiddle
var myIsoWeekDay = 2; // say our weeks start on tuesday, for monday you would type 1, etc.
var startOfPeriod = moment("2013-06-23T00:00:00"),
// how many days do we have to substract?
var daysToSubtract = moment(startOfPeriod).isoWeekday() >= myIsoWeekDay ?
moment(startOfPeriod).isoWeekday() - myIsoWeekDay :
7 + moment(startOfPeriod).isoWeekday() - myIsoWeekDay;
// subtract days from start of period
var begin = moment(startOfPeriod).subtract('d', daysToSubtract);
I got a little frustrated in not finding an online source, or Python documentation that describes precisely what slicing does.
I took Aaron Hall's suggestion, read the relevant parts of the CPython source code, and wrote some Python code that performs slicing similarly to how it's done in CPython. I've tested my code in Python 3 on millions of random tests on integer lists.
You may find the references in my code to the relevant functions in CPython helpful.
# Return the result of slicing list x
# See the part of list_subscript() in listobject.c that pertains
# to when the indexing item is a PySliceObject
def slicer(x, start=None, stop=None, step=None):
# Handle slicing index values of None, and a step value of 0.
# See PySlice_Unpack() in sliceobject.c, which
# extracts start, stop, step from a PySliceObject.
maxint = 10000000 # A hack to simulate PY_SSIZE_T_MAX
if step == None:
step = 1
elif step == 0:
raise ValueError('slice step cannot be zero')
if start == None:
start = maxint if step < 0 else 0
if stop == None:
stop = -maxint if step < 0 else maxint
# Handle negative slice indexes and bad slice indexes.
# Compute number of elements in the slice as slice_length.
# See PySlice_AdjustIndices() in sliceobject.c
length = len(x)
slice_length = 0
if start < 0:
start += length
if start < 0:
start = -1 if step < 0 else 0
elif start >= length:
start = length - 1 if step < 0 else length
if stop < 0:
stop += length
if stop < 0:
stop = -1 if step < 0 else 0
elif stop > length:
stop = length - 1 if step < 0 else length
if step < 0:
if stop < start:
slice_length = (start - stop - 1) // (-step) + 1
else:
if start < stop:
slice_length = (stop - start - 1) // step + 1
# Cases of step = 1 and step != 1 are treated separately
if slice_length <= 0:
return []
elif step == 1:
# See list_slice() in listobject.c
result = []
for i in range(stop - start):
result.append(x[i+start])
return result
else:
result = []
cur = start
for i in range(slice_length):
result.append(x[cur])
cur += step
return result
Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL
1) Enter MySQL
mysql -u your_user -p
2) Let's see the list of locked tables
mysql> show open tables where in_use>0;
3) Let's see the list of the current processes, one of them is locking your table(s)
mysql> show processlist;
4) Let's kill one of these processes
mysql> kill put_process_id_here;
Just get a handle to the root logger and add the StreamHandler
. The StreamHandler
writes to stderr. Not sure if you really need stdout over stderr, but this is what I use when I setup the Python logger and I also add the FileHandler
as well. Then all my logs go to both places (which is what it sounds like you want).
import logging
logging.getLogger().addHandler(logging.StreamHandler())
If you want to output to stdout
instead of stderr
, you just need to specify it to the StreamHandler
constructor.
import sys
# ...
logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))
You could also add a Formatter
to it so all your log lines have a common header.
ie:
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s] %(message)s")
rootLogger = logging.getLogger()
fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)
consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)
Prints to the format of:
2012-12-05 16:58:26,618 [MainThread ] [INFO ] my message
My variant:
const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )
document.getElementById('Id').value='new value';
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById
If you know the child element you're interested in is the first:
$('.second').children().first();
Or to find by index:
var index = 0
$('.second').children().eq(index);
The problem may be due to mixed build platforms DLLs in the project. i.e You build your project to Any CPU but have some DLLs in the project already built for x86 platform. These will cause random crashes because of different memory mapping of 32bit and 64bit architecture. If all the DLLs are built for one platform the problem can be solved. For safety try bulinding for 32bit x86 architecture because it is the most compatible.
Dir.pwd
seems to do the trick.
Try this:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
// comboBox1 is readonly
e.SuppressKeyPress = true;
}
Yes, it is. But using GET for sensitive data is a bad idea for several reasons:
Therefore, even though Querystring is secured it's not recommended to transfer sensitive data over querystring.
[1] Although I need to note that RFC states that browser should not send referrers from HTTPS to HTTP. But that doesn't mean a bad 3rd party browser toolbar or an external image/flash from an HTTPS site won't leak it.
I have a function that works well with only stdio.h
. I like it a lot and it works very well and is pretty concise:
size_t fsize(FILE *File) {
size_t FSZ;
fseek(File, 0, 2);
FSZ = ftell(File);
rewind(File);
return FSZ;
}
Tools - Android - Sdk manager - tab Sdk tools - install emulator 25.3.1
Tim Storer wrote a more flexible and nicer looking timeline.sty
(Internet Archive Wayback Machine link, as original is gone). In addition, the line is horizontal rather than vertical. So for instance:
\begin{timeline}{2008}{2010}{50}{250}
\MonthAndYearEvent{4}{2008}{First Podcast}
\MonthAndYearEvent{7}{2008}{Private Beta}
\MonthAndYearEvent{9}{2008}{Public Beta}
\YearEvent{2009}{IPO?}
\end{timeline}
produces a timeline that looks like this:
2008 2010
· · April, 2008 First Podcast ·
· July, 2008 Private Beta
· September, 2008 Public Beta
· 2009 IPO?
Personally, I find this a more pleasing solution than the other answers. But I also find myself modifying the code to get something closer to what I think a timeline should look like. So there's not definitive solution in my opinion.
2.51 * 100 = 250.999999999997
The int()
function simply truncates the number at the decimal point, giving 250. Use
int(round(2.51*100))
to get 251 as an integer. In general, floating point numbers cannot be represented exactly. One should therefore be careful of round-off errors. As mentioned, this is not a Python-specific problem. It's a recurring problem in all computer languages.
I prefer to upgrade all homebrew formulae and homebrew cask formulae.
I added a Bourne shell function to my environment for this one (I load a .bashrc)
function updatebrew() {
set -x;
brew update;
brew cleanup;
brew cask upgrade --greedy
)
}
set -x
for transparency: So that the terminal outputs whatever Homebrew is doing in the background.brew update
to update homebrew formulasbrew cleanup
to remove any change left over after installationsbrew cask upgrade --greedy
will install all casks; both those with versioning information and those withoutUse localStorage to store the fact that you opened the page :
$(document).ready(function() {
var yetVisited = localStorage['visited'];
if (!yetVisited) {
// open popup
localStorage['visited'] = "yes";
}
});
Try the following
var original = 'www.test.com';
var stripped = original.substring(4);