You will need to install this plugin before the options mentioned above will appear
This plugin add the check box to all job configs to allow you to delete the whole workspace before any steps (inc source control) are run
This is useful to make sure you always start from a known point to guarantee how you build will run
You could replace something in there by getting the index along with the item.
>>> foo = ['a', 'b', 'c', 'A', 'B', 'C']
>>> for index, item in enumerate(foo):
... print(index, item)
...
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'A')
(4, 'B')
(5, 'C')
>>> for index, item in enumerate(foo):
... if item in ('a', 'A'):
... foo[index] = 'replaced!'
...
>>> foo
['replaced!', 'b', 'c', 'replaced!', 'B', 'C']
Note that if you want to remove something from the list you have to iterate over a copy of the list, else you will get errors since you're trying to change the size of something you are iterating over. This can be done quite easily with slices.
Wrong:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c', 2]
The 2 is still in there because we modified the size of the list as we iterated over it. The correct way would be:
>>> foo = ['a', 'b', 'c', 1, 2, 3]
>>> for item in foo[:]:
... if isinstance(item, int):
... foo.remove(item)
...
>>> foo
['a', 'b', 'c']
On my Ubuntu machine, I can see the output at /var/log/syslog
.
On a RHEL/CentOS machine, the output is found in /var/log/messages
.
This is controlled by the rsyslog
service, so if this is disabled for some reason you may need to start it with systemctl start rsyslog
.
As noted by others, your syslog()
output would be logged by the /var/log/syslog
file.
You can see system, user, and other logs at /var/log
.
For more details: here's an interesting link.
Try Emmet plug-in command Go To Matching Pair:
http://docs.emmet.io/actions/go-to-pair/
Shortcut (Mac): Shift + Control + T
Shortcut (PC): Control + Alt + J
USE THIS ONLY IF YOU HAVE LIMITED NUMBER OF ITEMS IN YOUR RECYCLER VIEW.
I tried using boolean value in model and keep the checkbox status, but it did not help in my case.
What worked for me is this.setIsRecyclable(false);
public class ComponentViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView) {
super(itemView);
....
this.setIsRecyclable(false);
}
More explanation on this can be found here https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#isRecyclable()
NOTE: This is a workaround. To use it properly you can refer the document which states "Calls to setIsRecyclable() should always be paired (one call to setIsRecyclabe(false) should always be matched with a later call to setIsRecyclable(true)). Pairs of calls may be nested, as the state is internally reference-counted." I don't know how to do this in code, if someone can provide more code on this.
Basic Availability: The database appears to work most of the time.
Soft State: Stores don’t have to be write-consistent or mutually consistent all the time.
Eventual consistency: Data should always be consistent, with regards how any number of changes are performed.
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
And for a spinner like iOs I use this:
html:
<div class='spinner'>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
Css:
.spinner {
font-size: 30px;
position: relative;
display: inline-block;
width: 1em;
height: 1em;
}
.spinner div {
position: absolute;
left: 0.4629em;
bottom: 0;
width: 0.074em;
height: 0.2777em;
border-radius: 0.5em;
background-color: transparent;
-webkit-transform-origin: center -0.2222em;
-ms-transform-origin: center -0.2222em;
transform-origin: center -0.2222em;
-webkit-animation: spinner-fade 1s infinite linear;
animation: spinner-fade 1s infinite linear;
}
.spinner div:nth-child(1) {
-webkit-animation-delay: 0s;
animation-delay: 0s;
-webkit-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
}
.spinner div:nth-child(2) {
-webkit-animation-delay: 0.083s;
animation-delay: 0.083s;
-webkit-transform: rotate(30deg);
-ms-transform: rotate(30deg);
transform: rotate(30deg);
}
.spinner div:nth-child(3) {
-webkit-animation-delay: 0.166s;
animation-delay: 0.166s;
-webkit-transform: rotate(60deg);
-ms-transform: rotate(60deg);
transform: rotate(60deg);
}
.spinner div:nth-child(4) {
-webkit-animation-delay: 0.249s;
animation-delay: 0.249s;
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.spinner div:nth-child(5) {
-webkit-animation-delay: 0.332s;
animation-delay: 0.332s;
-webkit-transform: rotate(120deg);
-ms-transform: rotate(120deg);
transform: rotate(120deg);
}
.spinner div:nth-child(6) {
-webkit-animation-delay: 0.415s;
animation-delay: 0.415s;
-webkit-transform: rotate(150deg);
-ms-transform: rotate(150deg);
transform: rotate(150deg);
}
.spinner div:nth-child(7) {
-webkit-animation-delay: 0.498s;
animation-delay: 0.498s;
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
.spinner div:nth-child(8) {
-webkit-animation-delay: 0.581s;
animation-delay: 0.581s;
-webkit-transform: rotate(210deg);
-ms-transform: rotate(210deg);
transform: rotate(210deg);
}
.spinner div:nth-child(9) {
-webkit-animation-delay: 0.664s;
animation-delay: 0.664s;
-webkit-transform: rotate(240deg);
-ms-transform: rotate(240deg);
transform: rotate(240deg);
}
.spinner div:nth-child(10) {
-webkit-animation-delay: 0.747s;
animation-delay: 0.747s;
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
.spinner div:nth-child(11) {
-webkit-animation-delay: 0.83s;
animation-delay: 0.83s;
-webkit-transform: rotate(300deg);
-ms-transform: rotate(300deg);
transform: rotate(300deg);
}
.spinner div:nth-child(12) {
-webkit-animation-delay: 0.913s;
animation-delay: 0.913s;
-webkit-transform: rotate(330deg);
-ms-transform: rotate(330deg);
transform: rotate(330deg);
}
@-webkit-keyframes spinner-fade {
0% {
background-color: #69717d;
}
100% {
background-color: transparent;
}
}
@keyframes spinner-fade {
0% {
background-color: #69717d;
}
100% {
background-color: transparent;
}
}
get from this website : https://365webresources.com/10-best-pure-css-loading-spinners-front-end-developers/
If you want to run the script in a linux kickstart you have to run as below .
sh /tmp/script.sh > /dev/null 2>&1 < /dev/null &
You can use case-sensitive or case-insensitive comparison, depending what you need. Case-sensitive is like this:
if ([category isEqualToString:@"Some String"])
{
// Both strings are equal without respect to their case.
}
Case-insensitive is like this:
if ([category compare:@"Some String" options:NSCaseInsensitiveSearch] == NSOrderedSame)
{
// Both strings are equal with respect to their case.
}
I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc
Option 1
Create Procedure [Test] AS
DECLARE @StartDate varchar(10)
DECLARE @EndDate varchar(10)
Set @StartDate = '201620' --Define start YearWeek
Set @EndDate = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Option 2
Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS
SELECT
*
FROM
(SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)
Then run exec test '2016-01-01','2016-01-25'
My solution. String must be changeable. The advantage above some of the other solutions that it moves the non-space part to the beginning so you can keep using the old pointer, in case you have to free() it later.
void trim(char * s) {
char * p = s;
int l = strlen(p);
while(isspace(p[l - 1])) p[--l] = 0;
while(* p && isspace(* p)) ++p, --l;
memmove(s, p, l + 1);
}
This version creates a copy of the string with strndup() instead of editing it in place. strndup() requires _GNU_SOURCE, so maybe you need to make your own strndup() with malloc() and strncpy().
char * trim(char * s) {
int l = strlen(s);
while(isspace(s[l - 1])) --l;
while(* s && isspace(* s)) ++s, --l;
return strndup(s, l);
}
Given you're on a rails 3 project with rspec 2, From the rails root directory:
bundle exec rspec spec/controllers/groups_controller_spec.rb
should definitely work. i got tired of typing that so i created an alias to shorten 'bundle exec rspec' to 'bersp'
'bundle exec' is so that it loads the exact gem environment specified in your gem file: http://gembundler.com/
Rspec2 switched from the 'spec' command to the 'rspec' command.
I think print()
is slower than echo
.
I like to use print()
only for situations like:
echo 'Doing some stuff... ';
foo() and print("ok.\n") or print("error: " . getError() . ".\n");
There are many way to get application context in Spring application. Those are given bellow:
Via ApplicationContextAware:
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class AppContextProvider implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
Here setApplicationContext(ApplicationContext applicationContext)
method you will get the applicationContext
ApplicationContextAware:
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in. Implementing this interface makes sense for example when an object requires access to a set of collaborating beans.
Via Autowired:
@Autowired
private ApplicationContext applicationContext;
Here @Autowired
keyword will provide the applicationContext. Autowired has some problem. It will create problem during unit-testing.
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
You can use Generic Webhook Trigger Plugin for this.
With a variable like changed_files
and expression $.commits[*].['modified','added','removed'][*]
.
You can have a filter text like $changed_files
and filter regexp like "folder/subfolder/[^"]+?"
if folder/subfolder
is the folder that should trigger builds.
You can also use map:
a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))
It gives:
[2, 2, 2, 2, 2]
A one line solution would be:
item['key'] if 'key' in item else None
This is useful when trying to add dictionary values to a new list and want to provide a default:
eg.
row = [item['key'] if 'key' in item else 'default_value']
path.extname
will do the trick in most cases. However, it will include everything after the last .
, including the query string and hash fragment of an http request:
var path = require('path')
var extname = path.extname('index.html?username=asdf')
// extname contains '.html?username=asdf'
In such instances, you'll want to try something like this:
var regex = /[#\\?]/g; // regex of illegal extension characters
var extname = path.extname('index.html?username=asdf');
var endOfExt = extname.search(regex);
if (endOfExt > -1) {
extname = extname.substring(0, endOfExt);
}
// extname contains '.html'
Note that extensions with multiple periods (such as .tar.gz
), will not work at all with path.extname
.
I work with gcc 7.2. I specifically needed a function to be non-inlined, because it had to be instantiated in a library. I tried the __attribute__((noinline))
answer, as well as the asm("")
answer. Neither one solved the problem.
Finally, I figured that defining a static variable inside the function will force the compiler to allocate space for it in the static variable block, and to issue an initialization for it when the function is first called.
This is sort of a dirty trick, but it works.
That's it works so fine in any browser (I'm using asp.net core)
function onDownload() {_x000D_
_x000D_
const api = '@Url.Action("myaction", "mycontroller")'; _x000D_
var form = new FormData(document.getElementById('form1'));_x000D_
_x000D_
fetch(api, { body: form, method: "POST"})_x000D_
.then(resp => resp.blob())_x000D_
.then(blob => {_x000D_
const url = window.URL.createObjectURL(blob);_x000D_
$('#linkdownload').attr('download', 'Attachement.zip');_x000D_
$('#linkdownload').attr("href", url);_x000D_
$('#linkdownload')_x000D_
.fadeIn(3000,_x000D_
function() { });_x000D_
_x000D_
})_x000D_
.catch(() => alert('An error occurred'));_x000D_
_x000D_
_x000D_
_x000D_
}
_x000D_
_x000D_
<button type="button" onclick="onDownload()" class="btn btn-primary btn-sm">Click to Process Files</button>_x000D_
_x000D_
_x000D_
_x000D_
<a role="button" href="#" style="display: none" class="btn btn-sm btn-secondary" id="linkdownload">Click to download Attachments</a>_x000D_
_x000D_
_x000D_
<form asp-controller="mycontroller" asp-action="myaction" id="form1"></form>_x000D_
_x000D_
_x000D_
function onDownload() {
const api = '@Url.Action("myaction", "mycontroller")';
//form1 is your id form, and to get data content of form
var form = new FormData(document.getElementById('form1'));
fetch(api, { body: form, method: "POST"})
.then(resp => resp.blob())
.then(blob => {
const url = window.URL.createObjectURL(blob);
$('#linkdownload').attr('download', 'Attachments.zip');
$('#linkdownload').attr("href", url);
$('#linkdownload')
.fadeIn(3000,
function() {
});
})
.catch(() => alert('An error occurred'));
}
try this
var express = require('express');
var mysql = require('mysql');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
console.log(app);
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin123",
database: "sitepoint"
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
module.exports = app;
I solved this problem by doing the "subselect" like it:
string newQuery = "select * from (" + query + ") as temp";
When do it on mysql, all collunms properties (unique, non-null ...) will be cleared.
I had this issue and what I did and solved the problem was that I used AsEnumerable()
just before my Join clause.
here is my query:
List<AccountViewModel> selectedAccounts;
using (ctx = SmallContext.GetInstance()) {
var data = ctx.Transactions.
Include(x => x.Source).
Include(x => x.Relation).
AsEnumerable().
Join(selectedAccounts, x => x.Source.Id, y => y.Id, (x, y) => x).
GroupBy(x => new { Id = x.Relation.Id, Name = x.Relation.Name }).
ToList();
}
I was wondering why this issue happens, and now I think It is because after you make a query via LINQ, the result will be in memory and not loaded into objects, I don't know what that state is but they are in in some transitional state I think. Then when you use AsEnumerable()
or ToList()
, etc, you are placing them into physical memory objects and the issue is resolving.
Try This...
Go to your notification area in the taskbar.
Right click on Bluestacks Agent>Rotate Portrait Apps>Enabled.
There are several options available..
a. Automatic - Selected By Default - It will rotate the app player in portrait mode for portrait apps.
b. Disabled - It will force the portrait apps to work in landscape mode.
c. Enabled - It will force the portrait apps to work in portrait mode only.
This May help you..
Here you go with modified data.json
file:
{
"maps": [
{
"id": "blabla",
"iscategorical": "0"
},
{
"id": "blabla",
"iscategorical": "0"
}
],
"masks": [{
"id": "valore"
}],
"om_points": "value",
"parameters": [{
"id": "valore"
}]
}
You can call or print data on console by using below lines:
import json
from pprint import pprint
with open('data.json') as data_file:
data_item = json.load(data_file)
pprint(data_item)
Expected output for print(data_item['parameters'][0]['id'])
:
{'maps': [{'id': 'blabla', 'iscategorical': '0'},
{'id': 'blabla', 'iscategorical': '0'}],
'masks': [{'id': 'valore'}],
'om_points': 'value',
'parameters': [{'id': 'valore'}]}
Expected output for print(data_item['parameters'][0]['id'])
:
valore
There are several mechanisms to avoid a link to reach its destination. The one from the question is not much intuitive.
A cleaner option is to use href="#no"
where #no
is a non-defined anchor in the document.
You can use a more semantic name such as #disable, or #action to increase readability.
Benefits of the approach:
Drawbacks:
Since the <a>
element is not acting as a link, the best option in these cases is not using an <a>
element but a <div>
and provide the desired link-like style.
If you don't mind introducing a dependency, CliWrap can simplify this for you:
using CliWrap;
using CliWrap.Buffered;
var result = await Cli.Wrap("target.exe")
.WithArguments("arguments")
.ExecuteBufferedAsync();
var stdout = result.StandardOutput;
Python docstrings can be written following several formats as the other posts showed. However the default Sphinx docstring format was not mentioned and is based on reStructuredText (reST). You can get some information about the main formats in this blog post.
Note that the reST is recommended by the PEP 287
There follows the main used formats for docstrings.
Historically a javadoc like style was prevalent, so it was taken as a base for Epydoc (with the called Epytext
format) to generate documentation.
Example:
"""
This is a javadoc style.
@param param1: this is a first param
@param param2: this is a second param
@return: this is a description of what is returned
@raise keyError: raises an exception
"""
Nowadays, the probably more prevalent format is the reStructuredText (reST) format that is used by Sphinx to generate documentation. Note: it is used by default in JetBrains PyCharm (type triple quotes after defining a method and hit enter). It is also used by default as output format in Pyment.
Example:
"""
This is a reST style.
:param param1: this is a first param
:param param2: this is a second param
:returns: this is a description of what is returned
:raises keyError: raises an exception
"""
Google has their own format that is often used. It also can be interpreted by Sphinx (ie. using Napoleon plugin).
Example:
"""
This is an example of Google style.
Args:
param1: This is the first param.
param2: This is a second param.
Returns:
This is a description of what is returned.
Raises:
KeyError: Raises an exception.
"""
Even more examples
Note that Numpy recommend to follow their own numpydoc based on Google format and usable by Sphinx.
"""
My numpydoc description of a kind
of very exhautive numpydoc format docstring.
Parameters
----------
first : array_like
the 1st param name `first`
second :
the 2nd param
third : {'value', 'other'}, optional
the 3rd param, by default 'value'
Returns
-------
string
a value in a string
Raises
------
KeyError
when a key error
OtherError
when an other error
"""
It is possible to use a tool like Pyment to automatically generate docstrings to a Python project not yet documented, or to convert existing docstrings (can be mixing several formats) from a format to an other one.
Note: The examples are taken from the Pyment documentation
If performance is important to you, and your compiler supports lambdas, the stdev calculation can be made faster and simpler: In tests with VS 2012 I've found that the following code is over 10 X quicker than the Boost code given in the chosen answer; it's also 5 X quicker than the safer version of the answer using standard libraries given by musiphil.
Note I'm using sample standard deviation, so the below code gives slightly different results (Why there is a Minus One in Standard Deviations)
double sum = std::accumulate(std::begin(v), std::end(v), 0.0);
double m = sum / v.size();
double accum = 0.0;
std::for_each (std::begin(v), std::end(v), [&](const double d) {
accum += (d - m) * (d - m);
});
double stdev = sqrt(accum / (v.size()-1));
I just delete my application temp data from this path
C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files
Problem resolve
Just modify one of the returned entities:
Customer c = (from x in dataBase.Customers
where x.Name == "Test"
select x).First();
c.Name = "New Name";
dataBase.SaveChanges();
Note, you can only update an entity (something that extends EntityObject, not something that you have projected using something like select new CustomObject{Name = x.Name}
INSERT INTO wp_bp_activity
(
user_id,
component,
`type`,
`action`,
content,
primary_link,
item_id,
secondary_item_id,
date_recorded,
hide_sitewide,
mptt_left,
mptt_right
)
VALUES(
1,'activity','activity_update','<a title="admin" href="http://brandnewmusicreleases.com/social-network/members/admin/">admin</a> posted an update','<a title="242925_1" href="http://brandnewmusicreleases.com/social-network/wp-content/uploads/242925_1.jpg" class="buddyboss-pics-picture-link">242925_1</a>','http://brandnewmusicreleases.com/social-network/members/admin/',' ',' ','2012-06-22 12:39:07',0,0,0
)
You might take a look at JavaScience's source for OpenSSLKey
There's code in there that does exactly what you want to do.
In fact, they have a lot of crypto source code available here.
Source code snippet:
//------- Parses binary ans.1 RSA private key; returns RSACryptoServiceProvider ---
public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
{
byte[] MODULUS, E, D, P, Q, DP, DQ, IQ ;
// --------- Set up stream to decode the asn.1 encoded RSA private key ------
MemoryStream mem = new MemoryStream(privkey) ;
BinaryReader binr = new BinaryReader(mem) ; //wrap Memory Stream with BinaryReader for easy reading
byte bt = 0;
ushort twobytes = 0;
int elems = 0;
try {
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102) //version number
return null;
bt = binr.ReadByte();
if (bt !=0x00)
return null;
//------ all private key components are Integer sequences ----
elems = GetIntegerSize(binr);
MODULUS = binr.ReadBytes(elems);
elems = GetIntegerSize(binr);
E = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
D = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
P = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
Q = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DP = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
DQ = binr.ReadBytes(elems) ;
elems = GetIntegerSize(binr);
IQ = binr.ReadBytes(elems) ;
Console.WriteLine("showing components ..");
if (verbose) {
showBytes("\nModulus", MODULUS) ;
showBytes("\nExponent", E);
showBytes("\nD", D);
showBytes("\nP", P);
showBytes("\nQ", Q);
showBytes("\nDP", DP);
showBytes("\nDQ", DQ);
showBytes("\nIQ", IQ);
}
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAparams = new RSAParameters();
RSAparams.Modulus =MODULUS;
RSAparams.Exponent = E;
RSAparams.D = D;
RSAparams.P = P;
RSAparams.Q = Q;
RSAparams.DP = DP;
RSAparams.DQ = DQ;
RSAparams.InverseQ = IQ;
RSA.ImportParameters(RSAparams);
return RSA;
}
catch (Exception) {
return null;
}
finally {
binr.Close();
}
}
If you are dealing with older versions of .NET Framework, then support for TLS 1.2 is available in our SecureBlackbox product in both client and server components. SecureBlackbox contains its own implementation of all algorithms, so it doesn't matter which version of .NET-based framework you use (including .NET CF) - you'll have TLS 1.2 with the latest additions in all cases.
Please note that SecureBlackbox wont magically add TLS 1.2 to framework classes - instead you need to use SecureBlackbox classes and components explicitly.
I think the issue would be fixed just making the html fill 100% also, might be body fills the 100% of the html but html doesn't fill 100% of the screen.
Try with:
html, body {
height: 100%;
}
I presume it is referring to Tools > Android > "Sync Project with Gradle Files" from the Android Studio main menu.
I ran into this situation and creating an extra div was impractical.
I ended up just setting the full-height
div to height: 10000%; overflow: hidden;
Clearly not the cleanest solution, but it works really fast.
You could write a jQuery function which allowed you to add hidden fields to a form:
// This must be applied to a form (or an object inside a form).
jQuery.fn.addHidden = function (name, value) {
return this.each(function () {
var input = $("<input>").attr("type", "hidden").attr("name", name).val(value);
$(this).append($(input));
});
};
And then add the hidden field before you submit:
var frm = $("#form").addHidden('SaveAndReturn', 'Save and Return')
.submit();
I will answer the question especially about ArrayList as an example in order to help you understand better..
public interface Iterable { ... abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T. ... }
public interface Iterator { ... abstract boolean hasNext(); //Returns true if the iteration has more elements. abstract E next(); //Returns the next element in the iteration. ... }
'Iterable <- Collection <- List <- ArrayList'
. And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.
'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.
public class ArrayList<E> ... implements List<E>, ... { ... public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { ... public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } ... } }
Here is a simple example.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
Now, is it clear? :)
Note: Due to reputation I cannot comment on bdeem's post. I'm posting my findings as an answer instead.
Following bdeem's post, I did the following (in order):
1. I modified the [project].csproj
file. Added the <Content Include="" />
tags to the ItemGroup
for the different config
files and made them dependent on the original config
file.
Note: Using <None Include="" />
will not work with the transformation.
<!-- App.config Settings -->
<!-- Create App.($Configuration).config files here. -->
<Content Include="App.config" />
<Content Include="App.Debug.config">
<DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config">
<DependentUpon>App.config</DependentUpon>
</Content>
2. At the bottom of the [project].csproj
file (before the closing </Project>
tag), I imported the ${MSBuildToolsPath\Microsoft.CSharp.targets
file, added the UsingTask
to transform the XML and added the Target
to copy the transformed App.config
file to the output location.
Note: The Target
will also overwrite the App.Config
in the local directory to see immediate changes working locally. The Target
also uses the Name="Afterbuild"
property to ensure the config files can be transformed after the executables are generated. For reasons I do not understand, when using WCF endpoints, if I use Name="CoreCompile"
, I will get warnings about the service attributes. Name="Afterbuild"
resolved this.
<!-- Task to transform the App.config using the App.($Configuration).config file. -->
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<!-- Only compile the App.config if the App.($Configuration).config file exists. -->
<!-- Make sure to use the AfterBuild name instead of CoreCompile to avoid first time build errors and WCF endpoint errors. -->
<Target Name="AfterBuild" Condition="exists('App.$(Configuration).config')">
<!-- Generate transformed App.config in the intermediate output directory -->
<TransformXml Source="App.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="App.$(Configuration).config" />
<!-- Modify the original App.config file with the transformed version. -->
<TransformXml Source="App.config" Destination="App.config" Transform="App.$(Configuration).config" />
<!-- Force build process to use the transformed configuration file from now on. -->
<ItemGroup>
<AppConfigWithTargetPath Remove="App.config" />
<AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
<TargetPath>$(TargetFileName).config</TargetPath>
</AppConfigWithTargetPath>
</ItemGroup>
</Target>
</Project>
3. Went back into Visual Studio and reloaded the modified files.
4. Manually added the App.*.config
files to the project. This allowed them to group under the original App.config
file.
Note: Make sure the App.*.config
files have the proper XML structure.
<?xml version="1.0" encoding="utf-8"?>
<!-- For more information on using web.config transformation visit https://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="myConn" connectionString=""; Initial Catalog=; User ID=; Password=;" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
</connectionStrings>
</configuration>
5. Re-built the project.
You can create your own custom auth schemas that use the Authorization:
header - for example, this is how OAuth works.
As a general rule, if servers or proxies don't understand the values of standard headers, they will leave them alone and ignore them. It is creating your own header keys that can often produce unexpected results - many proxies will strip headers with names they don't recognise.
Having said that, it is possibly a better idea to use cookies to transmit the token, rather than the Authorization:
header, for the simple reason that cookies were explicitly designed to carry custom values, whereas the specification for HTTP's built in auth methods does not really say either way - if you want to see exactly what it does say, have a look here.
The other point about this is that many HTTP client libraries have built-in support for Digest and Basic auth but may make life more difficult when trying to set a raw value in the header field, whereas they will all provide easy support for cookies and will allow more or less any value within them.
This works for me:
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
cout << M_PI << endl;
return 0;
}
Compiles and prints pi
like is should: cl /O2 main.cpp /link /out:test.exe
.
There must be a mismatch in the code you have posted and the one you're trying to compile.
Be sure there are no precompiled headers being pulled in before your #define
.
Use HTML5 Local Storage. you can store and use the data anytime you please.
<script>
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
var data = localStorage.getItem("lastname");
</script>
<!-- ToolBar -->
<style name="ToolBarTheme.ToolBarStyle" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:textColor">@color/white</item>
<item name="android:textColorPrimaryInverse">@color/white</item>
</style>
Too late to post, this worked for me to change the color of the back button
You need to cast the array - the returned array is actually of the requested type, i.e. myEnum[]
if you ask for typeof(myEnum)
:
myEnum[] values = (myEnum[]) Enum.GetValues(typeof(myEnum));
Then values[0]
etc
def longestWord(some_list):
count = 0 #You set the count to 0
for i in some_list: # Go through the whole list
if len(i) > count: #Checking for the longest word(string)
count = len(i)
word = i
return ("the longest string is " + word)
or much easier:
max(some_list , key = len)
plug: sshj is the only sane choice! See these examples to get started: download, upload.
Sub SelectAllCellsInSheet(SheetName As String)
lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub
To use with ActiveSheet:
Call SelectAllCellsInSheet(ActiveSheet.Name)
You have to create __init__.py
on the Models
subfolder. The file may be empty. It defines a package.
Then you can do:
from Models.user import User
Read all about it in python tutorial, here.
There is also a good article about file organization of python projects here.
Here is an explanation of the crontab format.
# 1. Entry: Minute when the process will be started [0-60]
# 2. Entry: Hour when the process will be started [0-23]
# 3. Entry: Day of the month when the process will be started [1-28/29/30/31]
# 4. Entry: Month of the year when the process will be started [1-12]
# 5. Entry: Weekday when the process will be started [0-6] [0 is Sunday]
#
# all x min = */x
So according to this your 5 8 * * 0
would run 8:05 every Sunday.
From the error, I infer that referenceElement
is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).
>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'
You probably meant either for element in referenceElement.keys()
or for element in json['referenceElement'].keys()
. With more context on what types json
and referenceElement
are and what they contain, we will be able to better help you if neither solution works.
The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*
. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*
.
So if you want to remove all the privileges and start totally from scratch do the following:
Revoke all privileges on database level:
REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';
Drop the user 'phpmyadmin'@'localhost'
DROP USER 'phpmyadmin'@'localhost';
Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.
To give you a bit background on what described above: as soon as you create a user the mysql.user
table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'
. If you do a show grants for 'phpmyadmin'@'localhost';
you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL
to this user on database level, this will be stored in the table mysql.db
. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb';
you will see a 'Y'
on every priv.
Above described shows the scenario you have on your db at the present. So having a user that only has USAGE
privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS;
he has no other privileges.
Have a look at the start up scripts a Java heap size is set there, it looks like you're not setting this before running Spark worker.
# Set SPARK_MEM if it isn't already set since we also use it for this process
SPARK_MEM=${SPARK_MEM:-512m}
export SPARK_MEM
# Set JAVA_OPTS to be able to load native libraries and to set heap size
JAVA_OPTS="$OUR_JAVA_OPTS"
JAVA_OPTS="$JAVA_OPTS -Djava.library.path=$SPARK_LIBRARY_PATH"
JAVA_OPTS="$JAVA_OPTS -Xms$SPARK_MEM -Xmx$SPARK_MEM"
You can find the documentation to deploy scripts here.
Yes, just override the printMe()
method:
class Son extends Dad {
public static final String me = "son";
@Override
public void printMe() {
System.out.println(me);
}
}
You asked this question almost a year ago and I don't know if you still are looking for another way of benchmarking your website. However since this question is still not marked as solved I would like to suggest the free webservice LoadImpact (btw. not affiliated). Just got this link via twitter and would like to share this find. They create a reasonable good overview and for a few bucks more you get the "full impact mode". This probably sounds strange, but good luck pushing and braking your service :)
This is not really a pure answer to the question, but an intelligent way to work around such problems:
instead of writing a complex file, simply delegate control to for instance a bash script like: makefile
foo : bar.cpp baz.h
bash script.sh
and script.sh looks like:
for number in 1 2 3 4
do
./a.out $number
done
http://wordnet.princeton.edu/man/morph.3WN
For a lot of my projects, I prefer the lexicon-based WordNet lemmatizer over the more aggressive porter stemming.
http://wordnet.princeton.edu/links#PHP has a link to a PHP interface to the WN APIs.
I got this error while pod update
. I solved it by deleting the index.lock
file in cocoapods
's .git
directory.
rm -f /Users/my_user_name/.cocoapods/repos/master/.git/index.lock
It might help someone.
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);
SQL Server 2008 has a type called datetimeoffset
. It's really useful for this type of stuff.
http://msdn.microsoft.com/en-us/library/bb630289.aspx
Then you can use the function SWITCHOFFSET
to move it from one timezone to another, but still keeping the same UTC value.
http://msdn.microsoft.com/en-us/library/bb677244.aspx
Rob
I tried to make the code more readable. This works for numbers within integer range
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
public class Solution2 {
static Map<Integer, String> numberMap = new HashMap<Integer, String>();
static Map<Integer, String> tensMap = new HashMap<Integer, String>();
static Map<Integer, String> exponentsMap = new HashMap<Integer, String>();
public static void main(String[] args) {
LinkedList<String> wordList = new LinkedList<String>();
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
scan.close();
exponentsMap.put(3, "thousand");
exponentsMap.put(6, "million");
exponentsMap.put(9, "billion");
tensMap.put(2, "twenty");
tensMap.put(3, "thirty");
tensMap.put(4, "forty");
tensMap.put(5, "fifty");
tensMap.put(6, "sixty");
tensMap.put(7, "seventy");
tensMap.put(8, "eighty");
tensMap.put(9, "ninety");
numberMap.put(1, "one");
numberMap.put(2, "two");
numberMap.put(3, "three");
numberMap.put(4, "four");
numberMap.put(5, "five");
numberMap.put(6, "six");
numberMap.put(7, "seven");
numberMap.put(8, "eight");
numberMap.put(9, "nine");
numberMap.put(10, "ten");
numberMap.put(11, "eleven");
numberMap.put(12, "twelve");
numberMap.put(13, "thirteen");
numberMap.put(14, "fourteen");
numberMap.put(15, "fifteen");
numberMap.put(16, "sixteen");
numberMap.put(17, "seventeen");
numberMap.put(18, "eighteen");
numberMap.put(19, "nineteen");
int temp = input;
int exponentCounter =0;
while(temp>0) {
// words from 1 to 99
addLastTwo(temp%100,wordList);
temp=temp/100;
// add hundreds before exponents
if(temp!=0) {
wordList.addFirst("hundred");
wordList.addFirst(numberMap.getOrDefault(temp%10,""));
temp = temp/10;
}
// words for exponents
if(temp!=0) {
exponentCounter+=3;
wordList.addFirst(exponentsMap.getOrDefault(exponentCounter,""));
}
}
wordList.stream().filter(word -> !word.contentEquals("")).forEach(word -> System.out.print(word + " "));
}
private static void addLastTwo(int num, LinkedList<String> wordList) {
if (num > 19) {
wordList.addFirst(numberMap.getOrDefault(num % 10,""));
wordList.addFirst(tensMap.getOrDefault(num / 10,""));
} else {
wordList.addFirst(numberMap.getOrDefault(num,""));
}
}
}
You don't have g++ installed, simple way to have all the needed build tools is to install the package build-essential:
sudo apt-get install build-essential
, or just the g++ package:
sudo apt-get install g++
You can do it in pgadmin3. Drop the schema(s) that your dump contains. Then right-click on the database and choose Restore. Then you can browse for the dump file.
Just used version 2 of the AWS CLI. For the s3 option, there is also a --dryrun option now to show you what will happen:
aws s3 --dryrun cp s3://bucket/filename /path/to/dest/folder --recursive
If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)
Check this out, it should get you started,
http://www.codeproject.com/KB/office/package.aspx
And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.
Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;
if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}
You can also do
Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;
if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}
And if you need to insert rows/columns
// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );
select
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
You can get the raw data by calling ReadAsStringAsAsync
on the Request.Content
property.
string result = await Request.Content.ReadAsStringAsync();
There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:
public async Task<IHttpActionResult> GetSomething()
{
var rawMessage = await Request.Content.ReadAsStringAsync();
// ...
return Ok();
}
EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:
public IHttpActionResult GetSomething()
{
var reader = new StreamReader(Request.Body);
reader.BaseStream.Seek(0, SeekOrigin.Begin);
var rawMessage = reader.ReadToEnd();
return Ok();
}
In this case, your endpoint doesn't need to be async (unless you have other async-methods)
This works in SQL 2008 and 2012 to produce datetime2:
declare @date date = current_timestamp;
declare @time time = current_timestamp;
select
@date as date
,@time as time
,cast(@date as datetime) + cast(@time as datetime) as datetime
,cast(@time as datetime2) as timeAsDateTime2
,dateadd(dayofyear,datepart(dayofyear,@date) - 1,dateadd(year,datepart(year,@date) - 1900,cast(@time as datetime2))) as datetime2;
Well, You can do it like this.
https://developer.android.com/reference/android/view/View#post(java.lang.Runnable)
A simple approach
currentTime.post(new Runnable(){
@Override
public void run() {
currentTime.setText(time);
}
}
it also provides delay
https://developer.android.com/reference/android/view/View#postDelayed(java.lang.Runnable,%20long)
Use double quotes:
$i = 1;
echo "
<p class=\"paragraph$i\">
</p>
";
++i;
An alternative is to change the order in which the views are drawn by the parent. You can enable this feature from ViewGroup by calling setChildrenDrawingOrderEnabled(true) and overriding getChildDrawingOrder(int childCount, int i).
/**
* Example Layout that changes draw order of a FrameLayout
*/
public class OrderLayout extends FrameLayout {
private static final int[][] DRAW_ORDERS = new int[][]{
{0, 1, 2},
{2, 1, 0},
{1, 2, 0}
};
private int currentOrder;
public OrderLayout(Context context) {
super(context);
setChildrenDrawingOrderEnabled(true);
}
public void setDrawOrder(int order) {
currentOrder = order;
invalidate();
}
@Override
protected int getChildDrawingOrder(int childCount, int i) {
return DRAW_ORDERS[currentOrder][i];
}
}
Calling OrderLayout#setDrawOrder(int)
with 0-1-2 results in:
You could use the refcodes-console
artifact at refcodes-console on REFCODES.ORG:
Option<String> r = new StringOptionImpl( "-r", null, "opt1", "..." );
Option<String> s = new StringOptionImpl( "-S", null, "opt2", "..." );
Operand<String> arg1 = new StringOperandImpl( "arg1", "..." );
Operand<String> arg2 = new StringOperandImpl( "arg2", "..." );
Operand<String> arg3 = new StringOperandImpl( "arg3", "..." );
Operand<String> arg4 = new StringOperandImpl( "arg4", "..." );
Switch test = new SwitchImpl( null, "--test", "..." );
Option<String> a = new StringOptionImpl( "-A", null, "opt3", "..." );
Condition theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4,
test );
Create your arguments parser ArgsParserImpl
with your root condition:
ArgsParser theArgsParser = new ArgsParserImpl( theRoot );
theArgsParser.setName( "MyProgramm" );
theArgsParser.setSyntaxNotation( SyntaxNotation.GNU_POSIX );
Above you define your syntax, below you invoke the parser:
theArgsParser.printUsage();
theArgsParser.printSeparatorLn();
theArgsParser.printOptions();
theArgsParser.evalArgs( new String[] {
"-r", "RRRRR", "-S", "SSSSS", "11111", "22222", "33333", "44444",
"--test", "-A", "AAAAA"
} );
In case you provided some good descriptions, theArgsParser.printUsage()
will even show you the pretty printed usage:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 --test
In the above example all defined arguments must be passed by the user, else the parser will detect a wrong usage. In case the
--test
switch is to be optional (or any other argument), assigntheRoot
as follows:
theRoot = new AndConditionImpl( r, s, a, arg1, arg2, arg3, arg4, new OptionalImpl( test ) );
Then your syntax looks as follows:
Usage: MyProgramm -r <opt1> -S <opt2> -A <opt3> arg1 arg2 arg3 arg4 [--test]
The full example for your case you find in the StackOverFlowExamle. You can use AND, OR, XOR conditions and any kind of nesting ... hope this helps.
Evaluate the parsed arguments as follows:
r.getValue() );
orif (test.getValue() == true) ...
:
LOGGER.info( "r :=" + r.getValue() );
LOGGER.info( "S :=" + s.getValue() );
LOGGER.info( "arg1 :=" + arg1.getValue() );
LOGGER.info( "arg2 :=" + arg2.getValue() );
LOGGER.info( "arg3 :=" + arg3.getValue() );
LOGGER.info( "arg4 :=" + arg4.getValue() );
LOGGER.info( "test :=" + test.getValue() + "" );
LOGGER.info( "A :=" + a.getValue() );
All the answers above are great. Only one thing is missing, be sure to drag the grey buttons to see the table (step number 2):
SET STATISTICS TIME ON
SELECT *
FROM Production.ProductCostHistory
WHERE StandardCost < 500.00;
SET STATISTICS TIME OFF;
And see the message tab it will look like this:
SQL Server Execution Times:
CPU time = 0 ms, elapsed time = 10 ms.
(778 row(s) affected)
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 0 ms.
There isn't so much a 'correct' way for the language. It's more personal preference or what the standard is for your team. I usually use the myFunction() when I'm doing my own code. Also, a style you didn't mention that you will often see in C++ is my_function() - no caps, underscores instead of spaces.
Really it is just dictated by the code your working in. Or, if it's your own project, your own personal preference then.
Executing seq(1, 10, 1)
does what 1:10
does. You can change the last parameter of seq
, i.e. by
, to be the step of whatever size you like.
> #a vector of even numbers
> seq(0, 10, by=2) # Explicitly specifying "by" only to increase readability
> [1] 0 2 4 6 8 10
Thanks for the great answer @user3136169, here is an example of how that might be done also removing NoneType values.
def regex_filter(val):
if val:
mo = re.search(regex,val)
if mo:
return True
else:
return False
else:
return False
df_filtered = df[df['col'].apply(regex_filter)]
Also you can also add regex as an arg:
def regex_filter(val,myregex):
...
df_filtered = df[df['col'].apply(res_regex_filter,regex=myregex)]
There are a few answers mentioning the functions dplyr::rename_with
and rlang::set_names
already. By they are separate. this answer illustrates the differences between the two and the use of functions and formulas to rename columns.
rename_with
from the dplyr
package can use either a function or a formula
to rename a selection of columns given as the .cols
argument. For example passing the function name toupper
:
library(dplyr)
rename_with(head(iris), toupper, starts_with("Petal"))
Is equivalent to passing the formula ~ toupper(.x)
:
rename_with(head(iris), ~ toupper(.x), starts_with("Petal"))
When renaming all columns, you can also use set_names
from the rlang package. To make a different example, let's use paste0
as a renaming function. pasteO
takes 2 arguments, as a result there are different ways to pass the second argument depending on whether we use a function or a formula.
rlang::set_names(head(iris), paste0, "_hi")
rlang::set_names(head(iris), ~ paste0(.x, "_hi"))
The same can be achieved with rename_with
by passing the data frame as first
argument .data
, the function as second argument .fn
, all columns as third
argument .cols=everything()
and the function parameters as the fourth
argument ...
. Alternatively you can place the second, third and fourth
arguments in a formula given as the second argument.
rename_with(head(iris), paste0, everything(), "_hi")
rename_with(head(iris), ~ paste0(.x, "_hi"))
rename_with
only works with data frames. set_names
is more generic and can
also perform vector renaming
rlang::set_names(1:4, c("a", "b", "c", "d"))
The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.
I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".
Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.
So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).
The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
This solution leaves the working directory under the control of the user.
No Javascript, no absolute positioning and no fixed heights are required for this one.
Here's an all CSS / CSS only method which doesn't require fixed heights or absolute positioning:
CSS
.container {
display: table;
}
.content {
display: table-row;
height: 100%;
}
.content-body {
display: table-cell;
}
HTML
<div class="container">
<header class="header">
<p>This is the header</p>
</header>
<section class="content">
<div class="content-body">
<p>This is the content.</p>
</div>
</section>
<footer class="footer">
<p>This is the footer.</p>
</footer>
</div>
See it in action here: http://jsfiddle.net/AzLQY/
The benefit of this method is that the footer and header can grow to match their content and the body will automatically adjust itself. You can also choose to limit their height with css.
In a single line you could do:
private static File[] bar(){
return new File[]{};
}
Here's a simple class that will accomplish what you want
import java.util.HashMap;
public class QuickHash extends HashMap<String,String> {
public QuickHash(String...KeyValuePairs) {
super(KeyValuePairs.length/2);
for(int i=0;i<KeyValuePairs.length;i+=2)
put(KeyValuePairs[i], KeyValuePairs[i+1]);
}
}
And then to use it
Map<String, String> Foo=QuickHash(
"a", "1",
"b", "2"
);
This yields {a:1, b:2}
Why not just
$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");
EDIT: You can also use the Expr class (Doctrine2).
This assumes the exe is somewhere you know on the user's computer:
<a href="javascript:LaunchApp()">Launch the executable</a>
<script>
function LaunchApp() {
if (!document.all) {
alert ("Available only with Internet Explorer.");
return;
}
var ws = new ActiveXObject("WScript.Shell");
ws.Exec("C:\\Windows\\notepad.exe");
}
</script>
Documentation: ActiveXObject, Exec Method (Windows Script Host).
The OP answered this question to change the default timezone for a single instance of a running JVM, set the user.timezone
system property:
java -Duser.timezone=GMT ... <main-class>
If you need to set specific time zones when retrieving Date/Time/Timestamp objects from a database ResultSet
, use the second form of the getXXX
methods that takes a Calendar
object:
Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
ResultSet rs = ...;
while (rs.next()) {
Date dateValue = rs.getDate("DateColumn", tzCal);
// Other fields and calculations
}
Or, setting the date in a PreparedStatement:
Calendar tzCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
PreparedStatement ps = conn.createPreparedStatement("update ...");
ps.setDate("DateColumn", dateValue, tzCal);
// Other assignments
ps.executeUpdate();
These will ensure that the value stored in the database is consistent when the database column does not keep timezone information.
The java.util.Date
and java.sql.Date
classes store the actual time (milliseconds) in UTC. To format these on output to another timezone, use SimpleDateFormat
. You can also associate a timezone with the value using a Calendar object:
TimeZone tz = TimeZone.getTimeZone("<local-time-zone>");
//...
Date dateValue = rs.getDate("DateColumn");
Calendar calValue = Calendar.getInstance(tz);
calValue.setTime(dateValue);
Usefull Reference
https://docs.oracle.com/javase/9/troubleshoot/time-zone-settings-jre.htm#JSTGD377
https://confluence.atlassian.com/kb/setting-the-timezone-for-the-java-environment-841187402.html
In Kotlin
private fun removeLastChar(str: String?): String? {
return if (str == null || str.isEmpty()) str else str.substring(0, str.length - 1)
}
According to this, you need to assign a height to the element in which the div is contained in order for 100% height to work. Does that work for you?
You can take advatange of the css property Box Sizing.
#content {
height: 100%;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
padding-top: 50px;
margin-top: -50px;
padding-bottom: 50px;
margin-bottom: -50px;
}
See the JsFiddle.
You have a <script>
element that is trying to load some external JavaScript.
The URL you have given it points to a JSON file and not a JavaScript program.
The server is correctly reporting that it is JSON so the browser is aborting with that error message instead of trying to execute the JSON as JavaScript (which would throw an error).
Odds are that the underlying reason for this is that you are trying to make an Ajax request, have hit a cross origin error and have tried to fix it by telling jQuery that you are using JSONP. This only works if the URL provides JSONP (which is a different subset of JavaScript), which this one doesn't.
The same URL with the additional query string parameter callback=the_name_of_your_callback_function
does return JavaScript though.
Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec
.
If you're still here, the following discussion should hopefully reveal why. When you run, say,
sh -c 'command'
you run a sh
instance, then start command
as a child of that sh
instance. When command
finishes, the sh
instance also finishes.
sh -c 'exec command'
runs a sh
instance, then replaces that sh
instance with the command
binary, and runs that instead.
Of course, both of these are useless in this limited context; you simply want
command
There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command
. This is pretty much the sole situation where exec command
is useful.
#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command
This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh
instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh
instance with the command
process, rather than have sh
run it as a child process and wait for it, then exit as soon as it finishes.
Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec
that command as an optimization.
If something forces you to run sh
but you really wanted to run something else, exec something else
is of course a workaround to replace the undesired sh
instance (like for example if you really wanted to run your own spiffy gosh
instead of sh
but yours isn't listed in /etc/shells
so you can't specify it as your login shell).
The second use of exec
to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec
is followed by a redirect instead of a command name.
$status = "";
$new_array = array();
if(!empty($new_array)){
$status = "1"; // not a blank array
}
else{
$status = "0"; // blank array
}
The problem is pyaudio does not have wheels for python 3.7 just try some lower version like 3.6
then install pyaudio
It works
As said @Jack, when mouseup
happens outside of browser window, we are not aware of it...
window.addEventListener('mouseup', mouseUpHandler, false);
window.addEventListener('mousedown', mouseDownHandler, false);
mouseup
event in one of those cases:Html code:
Change Title:
<input type="text" id="changeTitle" placeholder="Enter title tag">
<button id="changeTitle1">Click!</button>
Jquery code:
$(document).ready(function(){
$("#changeTitle1").click(function() {
$(document).prop('title',$("#changeTitle").val());
});
});
To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING
and CHAR_LENGTH
functions together:
SELECT col
, /* ANSI Syntax */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
, /* MySQL Syntax */ SUBSTRING(col, 1, CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl
To remove a specific substring from the end of string, use the TRIM
function:
SELECT col
, TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt
Here's another 'non-conventional' way.
An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).
// 1: define the array of switching classes:
var types = ['web','email'];
// 2: get the active class:
var type = $(mybutton).prop('class');
// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);
I have written a quick example to demonstrate how to create a layout programmatically.
public class CodeLayout extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Creating a new RelativeLayout
RelativeLayout relativeLayout = new RelativeLayout(this);
// Defining the RelativeLayout layout parameters.
// In this case I want to fill its parent
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT);
// Creating a new TextView
TextView tv = new TextView(this);
tv.setText("Test");
// Defining the layout parameters of the TextView
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT);
// Setting the parameters on the TextView
tv.setLayoutParams(lp);
// Adding the TextView to the RelativeLayout as a child
relativeLayout.addView(tv);
// Setting the RelativeLayout as our content view
setContentView(relativeLayout, rlp);
}
}
In theory everything should be clear as it is commented. If you don't understand something just tell me.
You can use .attr() as a part of however you plan to toggle it:
$("button").attr("aria-expanded","true");
You can use this to work cmd in C#:
ProcessStartInfo proStart = new ProcessStartInfo();
Process pro = new Process();
proStart.FileName = "cmd.exe";
proStart.WorkingDirectory = @"D:\...";
string arg = "/c your_argument";
proStart.Arguments = arg;
proStart.WindowStyle = ProcessWindowStyle.Hidden;
pro.StartInfo = pro;
pro.Start();
Don't forget to write /c before your argument !!
You can use the Free version of HTTP Debugger.
It is not a proxy and you needn't make any changes in web.config.
Also, it can show both; incoming and outgoing HTTP requests. HTTP Debugger Free
The following code works
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function AddRow()
{
$('#myTable').append('<tr><td>test 2</td></tr>')
}
</script>
<title></title>
</head>
<body>
<input type="button" id="btnAdd" onclick="AddRow()"/>
<a href="">test</a>
<table id="myTable">
<tbody >
<tr>
<td>
test
</td>
</tr>
</tbody>
</table>
</body>
</html>
Note this will work as of jQuery 1.4 even if the table includes a <tbody>
element:
jQuery since version 1.4(?) automatically detects if the element you are trying to insert (using any of the append(), prepend(), before(), or after() methods) is a
<tr>
and inserts it into the first<tbody>
in your table or wraps it into a new<tbody>
if one doesn't exist.
for k, m in self.materials.items():
example:
miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
print("%s: %s" % (k, v))
npm fund [<pkg>]
This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund
CSS?
td {
padding-top: 2px;
padding-bottom: 2px;
}
To get checkbox work you should follow all these steps:
FormsModule
in your moduleform
tagyour input should be like this:
<input name="mpf" type="checkbox" [(ngModel)]="value" />
Note: do not forget to put name in your input.
if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}
You didn't say on which event.Just use below on your event listener.Or in your page load
$('#models').empty()
Then to repopulate
$.getJSON('@Url.Action("YourAction","YourController")',function(data){
var dropdown=$('#models');
dropdown.empty();
$.each(data, function (index, item) {
dropdown.append(
$('<option>', {
value: item.valueField,
text: item.DisplayField
}, '</option>'))
}
)});
toISOString()
will give current UTC Date. So to get the current local time we have to get getTimezoneOffset()
and subtract it from current time
document.getElementById('dt').max = new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString().split("T")[0];
_x000D_
<input type="date" min='1899-01-01' id="dt" />
_x000D_
How about:
00 00 * * * every 3 days && echo test
Where every
is a script:
#!/bin/sh
case $2 in
days)
expr `date +%j` % $1 = 0 > /dev/null
;;
weeks)
expr `date +%V` % $1 = 0 > /dev/null
;;
months)
expr `date +%m` % $1 = 0 > /dev/null
;;
esac
So it runs every day.
Using */3
runs on the 3rd, 6th, ... 27th, 30th of the month, but is then wrong after a month has a 31st day. The every
script is only wrong after the end of the year.
simple google search turned up this:
If the data is actually an HTML page and has NOT been created by ASP, PHP, or some other scripting language, and you are using Internet Explorer 6, and you have Excel installed on your computer, simply right-click on the page and look through the menu. You should see "Export to Microsoft Excel." If all these conditions are true, click on the menu item and after a few prompts it will be imported to Excel.
if you can't do that, he gives an alternate "drag-and-drop" method:
Use changelists. The advantage over specifying files is that you can visualize and confirm everything you wanted is actually included before you commit.
$ svn changelist fix-issue-237 foo.c
Path 'foo.c' is now a member of changelist 'fix-issue-237'.
That done, svn now keeps things separate for you. This helps when you're juggling multiple changes
$ svn status
A bar.c
A baz.c
--- Changelist 'fix-issue-237':
A foo.c
Finally, tell it to commit what you wanted changed.
$ svn commit --changelist fix-issue-237 -m "Issue 237"
You have 9 fields listed, but only 8 values. Try adding the method.
Here is an example that should give you some idea..
=IIF(First(Fields!Gender.Value,"vw_BrgyClearanceNew")="Female" and
(First(Fields!CivilStatus.Value,"vw_BrgyClearanceNew")="Married"),false,true)
I think you have to identify the datasource name or the table name where your data is coming from.
How about
Select I.Fee
From Item I
WHERE (days(GETDATE()) - days(I.DateCreated) < 365)
Combining the solutions proposed by Daren and Thanos we have a good .vimrc file.
-----_x000D_
" configure expanding of tabs for various file types_x000D_
au BufRead,BufNewFile *.py set expandtab_x000D_
au BufRead,BufNewFile *.c set noexpandtab_x000D_
au BufRead,BufNewFile *.h set noexpandtab_x000D_
au BufRead,BufNewFile Makefile* set noexpandtab_x000D_
_x000D_
" --------------------------------------------------------------------------------_x000D_
" configure editor with tabs and nice stuff..._x000D_
" --------------------------------------------------------------------------------_x000D_
set expandtab " enter spaces when tab is pressed_x000D_
set textwidth=120 " break lines when line length increases_x000D_
set tabstop=4 " use 4 spaces to represent tab_x000D_
set softtabstop=4_x000D_
set shiftwidth=4 " number of spaces to use for auto indent_x000D_
set autoindent " copy indent from current line when starting a new line_x000D_
set smartindent_x000D_
set smarttab_x000D_
set expandtab_x000D_
set number_x000D_
_x000D_
" make backspaces more powerfull_x000D_
set backspace=indent,eol,start_x000D_
_x000D_
set ruler " show line and column number_x000D_
syntax on " syntax highlighting_x000D_
set showcmd " show (partial) command in status line
_x000D_
edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation
How would it break encapsulation?
You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:
class c1 {
public:
int x;
};
class c2 {
public:
int foo();
private:
int x;
};
class c3 {
friend int foo();
private:
int x;
};
c1
is obviously not encapsulated. Anyone can read and modify x
in it. We have no way to enforce any kind of access control.
c2
is obviously encapsulated. There is no public access to x
. All you can do is call the foo
function, which performs some meaningful operation on the class.
c3
? Is that less encapsulated? Does it allow unrestricted access to x
? Does it allow unknown functions access?
No. It allows precisely one function to access the private members of the class. Just like c2
did. And just like c2
, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2
, we can see, just by looking at the class definitions, a complete list of who has access.
So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.
friend
does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.
First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.
Second, it is not restrictive enough. Consider a fourth class:
class c4 {
public:
int getx();
void setx(int x);
private:
int x;
};
This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)
Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.
The better and correct solution is to have a directive. The scope is the same, whether in the controller of the directive or the main controller. Use $element
to do DOM operations. The method defined in the directive controller is accessible in the main controller.
Example, finding a child element:
var app = angular.module('myapp', []);
app.directive("testDir", function () {
function link(scope, element) {
}
return {
restrict: "AE",
link: link,
controller:function($scope,$element){
$scope.name2 = 'this is second name';
var barGridSection = $element.find('#barGridSection'); //helps to find the child element.
}
};
})
app.controller('mainController', function ($scope) {
$scope.name='this is first name'
});
Create a WebViewClient, and override the shouldOverrideUrlLoading method.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
Edit: thought of something else.
You say you're creating a form dynamically - do you really mean a <form> and its contents 'cause asp.net takes issue with multiple forms on a page and it's already creating one uberform for you.
This works for me:
File file = ...;
byte[] data = new byte[(int) file.length()];
try {
new FileInputStream(file).read(data);
} catch (Exception e) {
e.printStackTrace();
}
Vi or Vim?
Anyway, the following command works for Vim in 'nocompatible' mode. That is, I suppose, almost pure vi.
:join!
If you want to do it from normal command use
gJ
With 'gJ' you join lines as is -- without adding or removing whitespaces:
S<Switch_ID>_F<File type>
_ID<ID number>_T<date+time>_O<Original File name>.DAT
Result:
S<Switch_ID>_F<File type>_ID<ID number>_T<date+time>_O<Original File name>.DAT
With 'J' command you will have:
S<Switch_ID>_F<File type> _ID<ID number>_T<date+time>_O<Original File name>.DAT
Note space between type>
and _ID
.
The year()
function just retrieves the year component of the underlying Date
object, so it returns a number.
Calling format('YYYY')
will invoke moment's string formatting functions, which will parse the format string supplied, and build a new string containing the appropriate data. Since you only are passing YYYY
, then the result will be a string containing the year.
If all you need is the year, then use the year()
function. It will be faster, as there is less work to do.
Do note that while years are the same in this regard, months are not! Calling format('M')
will return months in the range 1-12. Calling month()
will return months in the range 0-11. This is due to the same behavior of the underlying Date
object.
Following are the steps to push Docker Image to Private Repository of DockerHub
1- First check Docker Images using command
docker images
2- Check Docker Tag command Help
docker tag help
3- Now Tag a name to your created Image
docker tag localImgName:tagName DockerHubUser\Private-repoName:tagName(tag name is optional. Default name is latest)
4- Before pushing Image to DockerHub Private Repo, first login to DockerHub using command
docker login [provide dockerHub username and Password to login]
5- Now push Docker Image to your private Repo using command
docker push [options] ImgName[:tag] e.g docker push DockerHubUser\Private-repoName:tagName
6- Now navigate to the DockerHub Private Repo and you will see Docker image is pushed on your private Repository with name written as TagName in previous steps
You are modifying the list book_shop.values()[i]
, which is not getting updated in the dictionary. Whenever you call the values()
method, it will give you the values available in dictionary, and here you are not modifying the data of the dictionary.
Even if you do the following steps you COULD get the same error message.
1. login as SA user (SSMS)
2. Edit the file permissions to say "everyone" full access (windows folder)
3. Delete the Log file (Windows Exploring (this was what I had done per advise from some msdn forum)
I still GOT the permission error, but then I noticed that in the Attach screen, the bottom section STILL showed the LOG file, and the error message remained the same.
Hope this helps someone who did the same thing.
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
I would suggest using a binary webservice protocol similar to Hessian. It works very well and they do have a android implementation. It might be a little heavy but depends on the application you are building. Hope this helps.
code bit should read:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
});
Found this to be a practical implementation:
[^@\s]+@[^@\s]+\.[^@\s]+
getMonthDiff(d1, d2) {
var year1 = dt1.getFullYear();
var year2 = dt2.getFullYear();
var month1 = dt1.getMonth();
var month2 = dt2.getMonth();
var day1 = dt1.getDate();
var day2 = dt2.getDate();
var months = month2 - month1;
var years = year2 -year1
days = day2 - day1;
if (days < 0) {
months -= 1;
}
if (months < 0) {
months += 12;
}
return months + years*!2;
}
This code creates a nice vertical scrollbar for me in Firefox and Chrome:
#answerform {
position: absolute;
border: 5px solid gray;
padding: 5px;
background: white;
width: 300px;
height: 400px;
overflow-y: scroll;
}
_x000D_
<div id='answerform'>
badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
<br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
Here is a JS fiddle demo proving the above works.
Add**/.DS_Store
into .gitignore
for the sub directory
If .DS_Store
already committed:
find . -name .DS_Store -print0 | xargs -0 git rm --ignore-unmatch
To ignore them in all repository: (sometimes it named ._.DS_Store
)
echo ".DS_Store" >> ~/.gitignore_global
echo "._.DS_Store" >> ~/.gitignore_global
echo "**/.DS_Store" >> ~/.gitignore_global
echo "**/._.DS_Store" >> ~/.gitignore_global
git config --global core.excludesfile ~/.gitignore_global
It might be happening that you have the old keys exported via env variables (bash_profile) and since the env variables have higher precedence over credential files it is giving the error "the access key id does not exists".
Remove the old keys from the bash_profile and you would be good to go.
Happened with me once earlier when I forgot I have credentials in bash_profile and gave me headache for quite some time :)
package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number: ");
int y = scan.nextInt();
boolean isEven = (y % 2 == 0) ? true : false;
String x = (isEven) ? "even" : "odd";
System.out.println("Your number is " + x);
}
}
function isInteger(argument) { return argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // true<br>
isInteger("0.1"); // false<br>
or:
function isInteger(argument) { return argument == argument + 0 && argument == ~~argument; }
Usage:
isInteger(1); // true<br>
isInteger(0.1); // false<br>
isInteger("1"); // false<br>
isInteger("0.1"); // false<br>
Angular doesn't know about that change. For this you should call $scope.$digest()
or make the change inside of $scope.$apply()
:
$scope.$apply(function() {
// every changes goes here
$('#selectedDueDate').val(dateText);
});
See this to better understand dirty-checking
UPDATE: Here is an example
Almost, we can say Python is interpreted language. But we are using some part of one time compilation process in python to convert complete source code into byte-code like java language.
Awk approach:
awk '/pattern/{print; count++; if (count==10) exit}' file
Generally speaking:
F5 may give you the same page even if the content is changed, because it may load the page from cache. But Ctrl-F5 forces a cache refresh, and will guarantee that if the content is changed, you will get the new content.
Putting this here in case I forget it later and Google it again.
In my case I wanted the extra column to have the same data for each row
Where $syncData is an array of IDs:
$syncData = array_map(fn($locationSysid) => ['other_column' => 'foo'], array_flip($syncData));
or without arrow
$syncData = array_map(function($locationSysid) {
return ['ENTITY' => 'dbo.Cli_Core'];
}, array_flip($syncData));
(array_flip means we're using the IDs as the index for the array)
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
Yes, you can indeed. There are three ways of achieving this that I can think of.
Notes:
instead of using jsonObject try using CsvSchema its way easier and directly converts object to csv
CsvSchema schema = csvMapper.schemaFor(MyClass.class).withHeader();
csvMapper.writer(schema).writeValueAsString(myClassList);
and it mentains the order id your pojo has @JsonPropertyOrder in it
A new answer to reflect the most current practices: as of version 1.0.1, neither astype('str')
nor astype(str)
work.
As per the documentation, a Series can be converted to the string datatype in the following ways:
df['id'] = df['id'].astype("string")
df['id'] = pandas.Series(df['id'], dtype="string")
df['id'] = pandas.Series(df['id'], dtype=pandas.StringDtype)
#similar {
float:left;
width:200px;
background:#000;
clear:both;
}
lst = ["a", "b", "a", "c", "c", "a", "c"]
temp=set(lst)
result={}
for i in temp:
result[i]=lst.count(i)
print result
Output:
{'a': 3, 'c': 3, 'b': 1}
DOUBLE columns are not the same as DECIMAL columns, and you will get in trouble if you use DOUBLE columns for financial data.
DOUBLE is actually just a double precision (64 bit instead of 32 bit) version of FLOAT. Floating point numbers are approximate representations of real numbers and they are not exact. In fact, simple numbers like 0.01 do not have an exact representation in FLOAT or DOUBLE types.
DECIMAL columns are exact representations, but they take up a lot more space for a much smaller range of possible numbers. To create a column capable of holding values from 0.0001 to 99.9999 like you asked you would need the following statement
CREATE TABLE your_table
(
your_column DECIMAL(6,4) NOT NULL
);
The column definition follows the format DECIMAL(M, D) where M is the maximum number of digits (the precision) and D is the number of digits to the right of the decimal point (the scale).
This means that the previous command creates a column that accepts values from -99.9999 to 99.9999. You may also create an UNSIGNED DECIMAL column, ranging from 0.0000 to 99.9999.
For more information on MySQL DECIMAL the official docs are always a great resource.
Bear in mind that all of this information is true for versions of MySQL 5.0.3 and greater. If you are using previous versions, you really should upgrade.
Try
margin: 0 auto;
display:table
Hope that helps somebody out.
I think you need this ..
Dim n as Integer
For n = 5 to 17
msgbox cells(n,3) '--> sched waste
msgbox cells(n,4) '--> type of treatm
msgbox format(cells(n,5),"dd/MM/yyyy") '--> Lic exp
msgbox cells(n,6) '--> email col
Next
In your local system right,
go to this url : http://localhost/phpmyadmin/
In this click mysql default db, after that browser user table to get existing username and password.
wp_trim_words
This function trims text to a certain number of words and returns the trimmed text.
echo wp_trim_words( get_the_content(), 40, '...' );
I had searched a lot and found nothing, until I got this:
<?php echo get_the_post_thumbnail_url( null, 'full' ); ?>
Which simply give you the full image URL without the entire <img>
tag.
Hope that can help you.
This kind of this is always a pain in Excel, you have to convert the values using a function because once Excel converts the cells to Time they are stored internally as numbers. Here is the best way I know how to do it:
I'll assume that your times are in column A starting at row 1. In cell B1 enter this formula: =TEXT(A1,"hh:mm:ss AM/PM")
, drag the formula down column B to the end of your data in column A. Select the values from column B, copy, go to column C and select "Paste Special", then select "Values". Select the cells you just copied into column C and format the cells as "Text".
In Juptyer notebook, a very simple way is
!pip install <package_name> --upgrade
So, you just need to replace with the actual package name.
I faced this issue Many time from different scenarios
one of them when I tryed Connecting to team foundation server for different Logged User
so the solution is easy Just Click Switch User
hope this help you
I think it's possible in Java 9:
animalMap.entrySet().stream()
.forEach(
pair -> Optional.ofNullable(pair.getValue())
.ifPresentOrElse(v -> myMap.put(pair.getKey(), v), v -> myList.add(pair.getKey())))
);
Need the ifPresentOrElse for it to work though. (I think a for loop looks better.)
I too got similar error when i misplaced the code
text=(TextView)findViewById(R.id.text);// this line has to be below setcontentview
setContentView(R.layout.activity_my_otype);
//this is the correct place
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
I got it working on placing the code in right order as shown below
setContentView(R.layout.activity_my_otype);
text=(TextView)findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
}
});
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.*;
/* Write an application that prompts the user for a String that contains at least
* five letters and at least five digits. Continuously re-prompt the user until a
* valid String is entered. Display a message indicating whether the user was
* successful or did not enter enough digits, letters, or both.
*/
public class FiveLettersAndDigits {
private static String readIn() { // read input from stdin
StringBuilder sb = new StringBuilder();
int c = 0;
try { // do not use try-with-resources. We don't want to close the stdin stream
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while ((c = reader.read()) != 0) { // read all characters until null
// We don't want new lines, although we must consume them.
if (c != 13 && c != 10) {
sb.append((char) c);
} else {
break; // break on new line (or else the loop won't terminate)
}
}
// reader.readLine(); // get the trailing new line
} catch (IOException ex) {
System.err.println("Failed to read user input!");
ex.printStackTrace(System.err);
}
return sb.toString().trim();
}
/**
* Check the given input against a pattern
*
* @return the number of matches
*/
private static int getitemCount(String input, String pattern) {
int count = 0;
try {
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(input);
while (m.find()) { // count the number of times the pattern matches
count++;
}
} catch (PatternSyntaxException ex) {
System.err.println("Failed to test input String \"" + input + "\" for matches to pattern \"" + pattern + "\"!");
ex.printStackTrace(System.err);
}
return count;
}
private static String reprompt() {
System.out.print("Entered input is invalid! Please enter five letters and five digits in any order: ");
String in = readIn();
return in;
}
public static void main(String[] args) {
int letters = 0, digits = 0;
String in = null;
System.out.print("Please enter five letters and five digits in any order: ");
in = readIn();
while (letters < 5 || digits < 5) { // will keep occuring until the user enters sufficient input
if (null != in && in.length() > 9) { // must be at least 10 chars long in order to contain both
// count the letters and numbers. If there are enough, this loop won't happen again.
letters = getitemCount(in, "[A-Za-z]");
digits = getitemCount(in, "[0-9]");
if (letters < 5 || digits < 5) {
in = reprompt(); // reset in case we need to go around again.
}
} else {
in = reprompt();
}
}
}
}
I've used this little utility whenever the need arises: http://www.analogx.com/contents/download/network/pmapper/freeware.htm
The last time this utility was updated was in 2009. I noticed on my Win10 machine, it hangs for a few seconds when opening new windows sometimes. Other then that UI glitch, it still does its job fine.
Instead of any Array
you can load your data in DataTable
like:
using System.Data;
DataTable dt = new DataTable();
using (var con = new SqlConnection("Data Source=local;Initial Catalog=Test;Integrated Security=True"))
{
using (var command = new SqlCommand("SELECT col1,col2" +
{
con.Open();
using (SqlDataReader dr = command.ExecuteReader())
{
dt.Load(dr);
}
}
}
You can also use SqlDataAdapater
to fill your DataTable like
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
Later you can iterate each row and compare like:
foreach (DataRow dr in dt.Rows)
{
if (dr.Field<string>("col1") == "yourvalue") //your condition
{
}
}
Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.
Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.
class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
}
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };
return query.ToList();
}
}
myprocess.out &
would run the process in background using a subshell. If the current shell is terminated (say by logout), all subshells are also terminated so the background process would also be terminated. The nohup command ignores the HUP
signal and thus even if the current shell is terminated, the subshell and myprocess.out
would continue to run in the background. Another difference is that &
alone doesn't redirect the stdout/stderr so if there are any output or error, those are displayed on the terminal. nohup on the other hand redirect the stdout/stderr to nohup.out
or $HOME/nohup.out
.
To check if a float value is a whole number, use the float.is_integer()
method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float
type in Python 2.6.
Take into account that in Python 2, 1/3
is 0
(floor division for integer operands!), and that floating point arithmetic can be imprecise (a float
is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float()
to find your number. Like rounding down the cube root of 12000
:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose()
function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
On Windows, search for Anaconda PowerShell Prompt. Right click the program and select Run as administrator. In the command prompt, execute the following command:
conda update -n base -c defaults conda
Your Anaconda should now update without admin related errors.
It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.
The closest support for java object to csv is stringutils provided by spring utils project
arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.
Here is a simple utility which uses reflection to serialize value objects
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
Here is an example value object
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
and the code to run the util
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
Output:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
I have created this JQuery function
/**
* Draw a table from json array
* @param {array} json_data_array Data array as JSON multi dimension array
* @param {array} head_array Table Headings as an array (Array items must me correspond to JSON array)
* @param {array} item_array JSON array's sub element list as an array
* @param {string} destinaion_element '#id' or '.class': html output will be rendered to this element
* @returns {string} HTML output will be rendered to 'destinaion_element'
*/
function draw_a_table_from_json(json_data_array, head_array, item_array, destinaion_element) {
var table = '<table>';
//TH Loop
table += '<tr>';
$.each(head_array, function (head_array_key, head_array_value) {
table += '<th>' + head_array_value + '</th>';
});
table += '</tr>';
//TR loop
$.each(json_data_array, function (key, value) {
table += '<tr>';
//TD loop
$.each(item_array, function (item_key, item_value) {
table += '<td>' + value[item_value] + '</td>';
});
table += '</tr>';
});
table += '</table>';
$(destinaion_element).append(table);
}
;
I know this is a bit of an older question, but it is one I had as well, and while the accepted answers work, there is a way to do something similar without using additional packages like ggplot or lattice. It isn't quite as nice in that the boxplots overlap rather than showing side by side but:
boxplot(data1[,1:4])
boxplot(data2[,1:4],add=TRUE,border="red")
This puts in two sets of boxplots, with the second having an outline (no fill) in red, and also puts the outliers in red. The nice thing is, it works for two different dataframes rather than trying to reshape them. Quick and dirty way.
More recent and much cleaner: use event.key
. No more arbitrary number codes!
NOTE: The old properties (
.keyCode
and.which
) are Deprecated.
const node = document.getElementsByClassName("input")[0];
node.addEventListener("keyup", function(event) {
if (event.key === "Enter") {
// Do work
}
});
Modern style, with lambda and destructuring
node.addEventListener('keyup', ({key}) => {
if (key === "Enter") return false
})
If you must use jQuery:
$(document).keyup(function(event) {
if ($(".input1").is(":focus") && event.key == "Enter") {
// Do work
}
});
You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.
class cDefaultDict(dict):
# dictionary that returns zero for missing keys
# keys with zero values are not stored
def __missing__(self,key):
return 0
def __setitem__(self, key, value):
if value==0:
if key in self: # returns zero anyway, so no need to store it
del self[key]
else:
dict.__setitem__(self, key, value)
request.get_host()
will give you the domain.
I would recommend Ulrich Drepper's SHA-256/SHA-512 based crypt implementation.
We ported these algorithms to Java, and you can find a freely licensed version of them at ftp://ftp.arlut.utexas.edu/java_hashes/.
Note that most modern (L)Unices support Drepper's algorithm in their /etc/shadow files.
When using the header function, php does not trigger a close on the current session. You must use session_write_close
to close the session and remove the file lock from the session file.
ob_start();
@session_start();
//some display stuff
$_SESSION['id'] = $id; //$id has a value
session_write_close();
header('location: test.php');
Another way to push items into array using Mongoose is- $addToSet, if you want only unique items to be pushed into array. $push operator simply adds the object to array whether or not the object is already present, while $addToSet does that only if the object is not present in the array so as not to incorporate duplicacy.
PersonModel.update(
{ _id: person._id },
{ $addToSet: { friends: friend } }
);
This will look for the object you are adding to array. If found, does nothing. If not, adds it to the array.
References:
You can use jQuery .getJSON()
function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});
If you don't want to use jQuery you should look at this answer for pure JS solution: https://stackoverflow.com/a/2499647/1361042
http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html
Depends on how specific you want the test to be. You could maybe get away with
if(page_name){ string += "&page_name=" + page_name; }
I did this (Ubuntu latest as of March 2013 [ I think :) ]):
sudo gem install bundler
Credit goes to Ray Baxter.
If you need gem, I installed Ruby this way (though this is chronically taxing):
mkdir /tmp/ruby && cd /tmp/ruby
wget http://ftp.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p327.tar.gz
tar xfvz ruby-1.9.3-p327.tar.gz
cd ruby-1.9.3-p327
./configure
make
sudo make install
For what purpose?
IF EXISTS (SELECT * FROM Table)...
SELECT TOP 1 1 FROM Table
returns either zero or one rowsSELECT COUNT(*) FROM Table
You can load the text file into a textfile Hive table and then insert the data from this table into your sequencefile.
Start with a tab delimited file:
% cat /tmp/input.txt
a b
a2 b2
create a sequence file
hive> create table test_sq(k string, v string) stored as sequencefile;
try to load; as expected, this will fail:
hive> load data local inpath '/tmp/input.txt' into table test_sq;
But with this table:
hive> create table test_t(k string, v string) row format delimited fields terminated by '\t' stored as textfile;
The load works just fine:
hive> load data local inpath '/tmp/input.txt' into table test_t;
OK
hive> select * from test_t;
OK
a b
a2 b2
Now load into the sequence table from the text table:
insert into table test_sq select * from test_t;
Can also do load/insert with overwrite to replace all.
You could use the .not function like the following examples to remove items that have an exact id, id containing a specific word, id starting with a word, etc... see http://www.w3schools.com/jquery/jquery_ref_selectors.asp for more information on jQuery selectors.
Ignore by Exact ID:
$(".thisClass").not('[id="thisId"]').doAction();
Ignore ID's that contains the word "Id"
$(".thisClass").not('[id*="Id"]').doAction();
Ignore ID's that start with "my"
$(".thisClass").not('[id^="my"]').doAction();
As mentioned by T.J., There is no assert
in JavaScript.
However, there is a node module named assert, which is used mostly for testing. so, you might see code like:
const assert = require('assert');
assert(5 > 7);
I had to create Interface
public interface ScrollViewListener {
void onScrollChanged(ScrollViewExt scrollView,
int x, int y, int oldx, int oldy);
}
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ScrollView;
public class CustomScrollView extends ScrollView {
private ScrollViewListener scrollViewListener = null;
public ScrollViewExt(Context context) {
super(context);
}
public CustomScrollView (Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomScrollView (Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setScrollViewListener(ScrollViewListener scrollViewListener) {
this.scrollViewListener = scrollViewListener;
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (scrollViewListener != null) {
scrollViewListener.onScrollChanged(this, l, t, oldl, oldt);
}
}
}
<"Your Package name ".CustomScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/scrollView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true"
android:scrollbars="vertical">
private CustomScrollView scrollView;
scrollView = (CustomScrollView)mView.findViewById(R.id.scrollView);
scrollView.setScrollViewListener(this);
@Override
public void onScrollChanged(ScrollViewExt scrollView, int x, int y, int oldx, int oldy) {
// We take the last son in the scrollview
View view = (View) scrollView.getChildAt(scrollView.getChildCount() - 1);
int diff = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY()));
// if diff is zero, then the bottom has been reached
if (diff == 0) {
// do stuff
//TODO keshav gers
pausePlayer();
videoFullScreenPlayer.setVisibility(View.GONE);
}
}
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
@ooboo:
It takes the one "closest" to the point of reference in the source code. This is called "Lexical Scoping" and is standard for >40 years now.
Python's class members are really in a dictionary called __dict__
and will never be reached by lexical scoping.
If you don't specify nonlocal
but do x = 7
, it will create a new local variable "x".
If you do specify nonlocal
, it will find the "closest" "x" and assign to that.
If you specify nonlocal
and there is no "x", it will give you an error message.
The keyword global
has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. Weird.
When you have more complex structures, you might need to convert to JSON before printing:
// Convert structs to JSON.
data, err := json.Marshal(myComplexStruct)
fmt.Printf("%s\n", data)
visualize the rolling averages to see if it makes sense. I don't understand why sum was used when the rolling average was requested.
df=pd.read_csv('poll.csv',parse_dates=['enddate'],dtype={'favorable':np.float,'unfavorable':np.float,'other':np.float})
df.set_index('enddate')
df=df.fillna(0)
fig, axs = plt.subplots(figsize=(5,10))
df.plot(x='enddate', ax=axs)
plt.show()
df.rolling(window=3,min_periods=3).mean().plot()
plt.show()
print("The larger the window coefficient the smoother the line will appear")
print('The min_periods is the minimum number of observations in the window required to have a value')
df.rolling(window=6,min_periods=3).mean().plot()
plt.show()
You do not need to use ORDER BY
in inner query after WHERE
clause because you have already used it in ROW_NUMBER() OVER (ORDER BY VRDATE DESC)
.
SELECT
*
FROM (
SELECT
Stockmain.VRNOA,
item.description as item_description,
party.name as party_name,
stockmain.vrdate,
stockdetail.qty,
stockdetail.rate,
stockdetail.amount,
ROW_NUMBER() OVER (ORDER BY VRDATE DESC) AS RowNum --< ORDER BY
FROM StockMain
INNER JOIN StockDetail
ON StockMain.stid = StockDetail.stid
INNER JOIN party
ON party.party_id = stockmain.party_id
INNER JOIN item
ON item.item_id = stockdetail.item_id
WHERE stockmain.etype='purchase'
) AS MyDerivedTable
WHERE
MyDerivedTable.RowNum BETWEEN 1 and 5
Clear:both gives you that space between them.
For example your code:
<div style="float:left">Hello</div>
<div style="float:right">Howdy dere pardner</div>
Will currently display as :
Hello ................... Howdy dere pardner
If you add the following to above snippet,
<div style="clear:both"></div>
In between them it will display as:
Hello ................
Howdy dere pardner
giving you that space between hello and Howdy dere pardner.
Js fiiddle http://jsfiddle.net/Qk5vR/1/
To be more precise the shebang #!
, when it is the first two bytes of an executable (x
mode) file, is interpreted by the execve(2) system call (which execute programs). But POSIX specification for execve
don't mention the shebang.
It must be followed by a file path of an interpreter executable (which BTW could even be relative, but most often is absolute).
A nice trick (or perhaps not so nice one) to find an interpreter (e.g. python
) in the user's $PATH
is to use the env
program (always at /usr/bin/env
on all Linux) like e.g.
#!/usr/bin/env python
Any ELF executable can be an interpreter. You could even use #!/bin/cat
or #!/bin/true
if you wanted to! (but that would be often useless)
To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.
In you command line. Use
java -cp "path/to/your/jar:." main
rather than just
java main
The option tells Java where to search for libraries.
Use an image
type input:
<input type="image" src="/Button1.jpg" border="0" alt="Submit" />
The full HTML:
<form id='formName' name='formName' onsubmit='redirect();return false;'>_x000D_
<div class="style7">_x000D_
<input type='text' id='userInput' name='userInput' value=''>_x000D_
<input type="image" name="submit" src="https://jekyllcodex.org/uploads/grumpycat.jpg" border="0" alt="Submit" style="width: 50px;" />_x000D_
</div>_x000D_
</form>
_x000D_