No, there is no way to comment a line in XML and have the comment end automatically on a linebreak.
XML has only one definition for a comment:
'<!--' ((Char - '-') | ('-' (Char - '-')))* '-->'
XML forbids --
in comments to maintain compatibility with SGML.
To generate an area where you can specify a description for the function and each parameter for the function, type the following on the line before your function and hit Enter:
C#: ///
VB: '''
See Recommended Tags for Documentation Comments (C# Programming Guide) for more info on the structured content you can include in these comments.
Try this instead:
(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
setTimeout
is not an async
function, so you can't use it with ES7 async-await. But you could implement your sleep
function using ES6 Promise:
function sleep (fn, par) {
return new Promise((resolve) => {
// wait 3s before calling fn(par)
setTimeout(() => resolve(fn(par)), 3000)
})
}
Then you'll be able to use this new sleep
function with ES7 async-await:
var fileList = await sleep(listFiles, nextPageToken)
Please, note that I'm only answering your question about combining ES7 async/await with setTimeout
, though it may not help solve your problem with sending too many requests per second.
Update: Modern node.js versions has a buid-in async timeout implementation, accessible via util.promisify helper:
const {promisify} = require('util');
const setTimeoutAsync = promisify(setTimeout);
With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?
The Uri
class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):
var uri = new Uri(absoluteUrl, relativeUrl);
If relativeUrl
is in fact an abolute URL, then the absoluteUrl
is ignored.
The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri
constructor does not translate these).
--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----
For this you will need to use a Service or a Factory.
The services are the BEST PRACTICE to share data between not nested controllers.
A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.
I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!
A $scope element should be created like this:
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// best practice, always use a model
$scope.someModel = {
someValue: 'hello computer'
});
And not like this:
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// anti-pattern, bare value
$scope.someBareValue = 'hello computer';
};
});
This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as
<div ng-model="someModel.someValue"></div> //NOTICE THE DOT.
This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....
But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.
Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.
If from your controller you want to GET the objectC into your scope, is a mistake to say:
$scope.neededObjectInController = Factory.objectA.objectB.objectC;
That wont work... Instead use only one dot.
$scope.neededObjectInController = Factory.ObjectA;
Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.
I'm using a custom view that I layout on top of the other ones and that just draws the 4 small corners in the same color as the background. This works whatever the view contents are and does not allocate much memory.
public class RoundedCornersView extends View {
private float mRadius;
private int mColor = Color.WHITE;
private Paint mPaint;
private Path mPath;
public RoundedCornersView(Context context) {
super(context);
init();
}
public RoundedCornersView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.RoundedCornersView,
0, 0);
try {
setRadius(a.getDimension(R.styleable.RoundedCornersView_radius, 0));
setColor(a.getColor(R.styleable.RoundedCornersView_cornersColor, Color.WHITE));
} finally {
a.recycle();
}
}
private void init() {
setColor(mColor);
setRadius(mRadius);
}
private void setColor(int color) {
mColor = color;
mPaint = new Paint();
mPaint.setColor(mColor);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
invalidate();
}
private void setRadius(float radius) {
mRadius = radius;
RectF r = new RectF(0, 0, 2 * mRadius, 2 * mRadius);
mPath = new Path();
mPath.moveTo(0,0);
mPath.lineTo(0, mRadius);
mPath.arcTo(r, 180, 90);
mPath.lineTo(0,0);
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
/*Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(0, 0, mRadius, mRadius, paint);*/
int w = getWidth();
int h = getHeight();
canvas.drawPath(mPath, mPaint);
canvas.save();
canvas.translate(w, 0);
canvas.rotate(90);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.save();
canvas.translate(w, h);
canvas.rotate(180);
canvas.drawPath(mPath, mPaint);
canvas.restore();
canvas.translate(0, h);
canvas.rotate(270);
canvas.drawPath(mPath, mPaint);
}
}
The earlier suggestion to use "yyyy-MM-dd HH:mm:ss" is fine, though I believe Excel has much finer time resolution than that. I find this post rather credible (follow the thread and you'll see lots of arithmetic and experimenting with Excel), and if it's correct, you'll have your milliseconds. You can just tack on decimal places at the end, i.e. "yyyy-mm-dd hh:mm:ss.000".
You should be aware that Excel may not necessarily format the data (without human intervention) in such a way that you will see all of that precision. On my computer at work, when I set up a CSV with "yyyy-mm-dd hh:mm:ss.000" data (by hand using Notepad), I get "mm:ss.0" in the cell and "m/d/yyyy hh:mm:ss AM/PM" in the formula bar.
For maximum information[1] conveyed in the cells without human intervention, you may want to split up your timestamp into a date portion and a time portion, with the time portion only to the second. It looks to me like Excel wants to give you at most three visible "levels" (where fractions of a second are their own level) in any given cell, and you want seven: years, months, days, hours, minutes, seconds, and fractions of a second.
Or, if you don't need the timestamp to be human-readable but you want it to be as accurate as possible, you might prefer just to store a big number (internally, Excel is just using the number of days, including fractional days, since an "epoch" date).
[1]That is, numeric information. If you want to see as much information as possible but don't care about doing calculations with it, you could make up some format which Excel will definitely parse as a string, and thus leave alone; e.g. "yyyymmdd.hhmmss.000".
If you use node.js 0.12 or above / typescript 1.4 or above, just add compiler options like:
tsc a.ts --target es6 --module commonjs
More info: https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
If you use tsconfig.json
, then like this:
{
"compilerOptions": {
"module": "commonjs",
"target": "es6"
}
}
More info: https://github.com/Microsoft/TypeScript/wiki/tsconfig.json
Even I got the same compilation error when I was cross compiling i686-cm-linux-gcc.
The below compilation option solved my problem
$ i686-cm-linux-gcc a.c --sysroot=/opt/toolchain/i686-cm-linux-gcc
Note: The sysroot should point to compiler directory where usr/include available
In my case the toolchain is installed at /opt/toolchain/i686-cm-linux-gcc directory and usr/include is also available in the same directory
Yes, you can make dynamic styles. You can pass values from Components.
First create StyleSheetFactory.js
import { StyleSheet } from "react-native";
export default class StyleSheetFactory {
static getSheet(backColor) {
return StyleSheet.create({
jewelStyle: {
borderRadius: 10,
backgroundColor: backColor,
width: 20,
height: 20,
}
})
}
}
then use it in your component following way
import React from "react";
import { View } from "react-native";
import StyleSheetFactory from './StyleSheetFactory'
class Main extends React.Component {
getRandomColor = () => {
var letters = "0123456789ABCDEF";
var color = "#";
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
};
render() {
return (
<View>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
<View
style={StyleSheetFactory.getSheet(this.getRandomColor()).jewelStyle}
/>
</View>
);
}
}
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) rar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "don't know '$1'..." ;;
esac
else
echo "'$1' is not a valid file!"
fi
}
In response to Aquarius Power in the comment above, We need to store the regex on a var
The variable BASH_REMATCH is set after you match the expression, and ${BASH_REMATCH[n]} will match the nth group wrapped in parentheses ie in the following ${BASH_REMATCH[1]} = "compressed"
and ${BASH_REMATCH[2]} = ".gz"
if [[ "compressed.gz" =~ ^(.*)(\.[a-z]{1,5})$ ]];
then
echo ${BASH_REMATCH[2]} ;
else
echo "Not proper format";
fi
(The regex above isn't meant to be a valid one for file naming and extensions, but it works for the example)
I suppose subqueries and PIVOT would qualify, as well as multiple joins, unions and the like.
You should not use your domain models
in your views. ViewModels
are the correct way to do it.
You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.
If you never heard of viewmodels, take a look at this.
May be use Filter.
const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
if (item.id === 1) {
item.id = 12345;
}
return item;
});
console.log(filteredDataSource);
Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]
If your sole purpose is to convert a 1d array X to a 2d array just do:
X = np.reshape(X,(1, X.size))
Also make sure that the name of the variable is not some kind of a language keyword. For instance, the following produces the same type of error:
var history = [];
history.push("what a mess");
replacing it for:
var history123 = [];
history123.push("pray for a better language");
works as expected.
There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplication as @Ant mentions. This is only going to work if each of your print
statements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20
works).
>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa
If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print
. Note that string concatenation using +=
is now linear in the size of the string you're concatenating so this will be fast.
>>> for i in xrange(20):
... s += 'a'
...
>>> print s
aaaaaaaaaaaaaaaaaaaa
Or you can do it more directly using sys.stdout.write(), which print
is a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 a
s.
>>> import sys
>>> for i in xrange(20):
... sys.stdout.write('a')
...
aaaaaaaaaaaaaaaaaaaa>>>
Python 3 changes the print
statement into a print() function, which allows you to set an end
parameter. You can use it in >=2.6 by importing from __future__
. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.
>>> from __future__ import print_function
>>> for i in xrange(20):
... print('a', end='')
...
aaaaaaaaaaaaaaaaaaaa>>>
With NodeJS is simple like that! And if you want to run this script at each boot of your server, you can have a look on the forever-service application!
var exec = require('child_process').exec;
exec('php main.php', function (error, stdOut, stdErr) {
// do what you want!
});
You can get the desired result with the code below. Two'H' in HH
is for 24-hour format.
return fechaHora.Value.ToString("HH:mm");
Best and super easy way to do this is:-
adb devices
adb tcpip 5555
adb connect 192.168.9.120:5555 ( Your phone ip xxx.xxx.x.xxx:5555 )
Place this file into your android sdk platform-tool folder. Example:- C:\Users\'user_name'\AppData\Local\Android\Sdk\platform-tools
Right click file > sendto > Desktop(create shortcut )
That's it....
Now you just need to connect your phone through USB , then open desktop shortcut and disconnect your phone...
I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.
Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.
Total Start End
829 29170 29998
815 38866 39680
710 41798 42507
681 43442 44122
661 46337 46997
643 35358 36000
609 36866 37474
596 38204 38799
592 33657 34248
571 30261 30831
563 41231 41793
542 21011 21552
528 28590 29117
521 14415 14935
510 26490 26999
Source (via the CSV download button):
http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-
https://atom.io/packages/atom-typescript#alternative-to-symbols-view
You can get html element tag name on whole page.
You could use:
$('body').contents().on("click",function () {
var string = this.tagName;
alert(string);
});
In v.2.x.x , we can use align
and justify
. We have below options for setup the horizontal and vertical alignment.
PROPS align
: 'start','center','end','baseline','stretch'
PRPS justify
: 'start','center','end','space-around','space-between'
<v-container fill-height fluid>
<v-row align="center"
justify="center">
<v-col></v-col>
</v-row>
</v-container>
For more details please refer this vuetify grid-system and you could check here with working codepen demo.
You could use align-center
for layout
and fill-height
for container.
Demo with v1.x.x
new Vue({
el: '#app'
})
_x000D_
.bg{
background: gray;
color: #fff;
font-size: 18px;
}
_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.js"></script>
<div id="app">
<v-app>
<v-container bg fill-height grid-list-md text-xs-center>
<v-layout row wrap align-center>
<v-flex>
Hello I am center to vertically using "align-center".
</v-flex>
</v-layout>
</v-container>
</v-app>
</div>
_x000D_
$(':checkbox').change(function(){
$('#delete').removeAttr('hidden');
});
Note, thanks to tip by A.Wolff
, you should use removeAttr
instead of setting to false. When set to false, the element will still be hidden. Therefore, removing is more effective.
If legend_out
is set to True
then legend is available thought g._legend
property and it is a part of a figure. Seaborn legend is standard matplotlib legend object. Therefore you may change legend texts like:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# title
new_title = 'My title'
g._legend.set_title(new_title)
# replace labels
new_labels = ['label 1', 'label 2']
for t, l in zip(g._legend.texts, new_labels): t.set_text(l)
sns.plt.show()
Another situation if legend_out
is set to False
. You have to define which axes has a legend (in below example this is axis number 0):
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = False)
# check axes and find which is have legend
leg = g.axes.flat[0].get_legend()
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
Moreover you may combine both situations and use this code:
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.lmplot(x="total_bill", y="tip", hue="smoker",
data=tips, markers=["o", "x"], legend_out = True)
# check axes and find which is have legend
for ax in g.axes.flat:
leg = g.axes.flat[0].get_legend()
if not leg is None: break
# or legend may be on a figure
if leg is None: leg = g._legend
# change legend texts
new_title = 'My title'
leg.set_title(new_title)
new_labels = ['label 1', 'label 2']
for t, l in zip(leg.texts, new_labels): t.set_text(l)
sns.plt.show()
This code works for any seaborn plot which is based on Grid
class.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
To convert any object or object list into JSON, we have to use the function JsonConvert.SerializeObject.
The below code demonstrates the use of JSON in an ASP.NET environment:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace JSONFromCS
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
List<Employee> eList = new List<Employee>();
Employee e = new Employee();
e.Name = "Minal";
e.Age = 24;
eList.Add(e);
e = new Employee();
e.Name = "Santosh";
e.Age = 24;
eList.Add(e);
string ans = JsonConvert.SerializeObject(eList, Formatting.Indented);
string script = "var employeeList = {\"Employee\": " + ans+"};";
script += "for(i = 0;i<employeeList.Employee.length;i++)";
script += "{";
script += "alert ('Name : ='+employeeList.Employee[i].Name+'
Age : = '+employeeList.Employee[i].Age);";
script += "}";
ClientScriptManager cs = Page.ClientScript;
cs.RegisterStartupScript(Page.GetType(), "JSON", script, true);
}
}
public class Employee
{
public string Name;
public int Age;
}
}
After running this program, you will get two alerts
In the above example, we have created a list of Employee object and passed it to function "JsonConvert.SerializeObject". This function (JSON library) will convert the object list into JSON format. The actual format of JSON can be viewed in the below code snippet:
{ "Maths" : [ {"Name" : "Minal", // First element
"Marks" : 84,
"age" : 23 },
{
"Name" : "Santosh", // Second element
"Marks" : 91,
"age" : 24 }
],
"Science" : [
{
"Name" : "Sahoo", // First Element
"Marks" : 74,
"age" : 27 },
{
"Name" : "Santosh", // Second Element
"Marks" : 78,
"age" : 41 }
]
}
Syntax:
{} - acts as 'containers'
[] - holds arrays
: - Names and values are separated by a colon
, - Array elements are separated by commas
This code is meant for intermediate programmers, who want to use C# 2.0 to create JSON and use in ASPX pages.
You can create JSON from JavaScript end, but what would you do to convert the list of object into equivalent JSON string from C#. That's why I have written this article.
In C# 3.5, there is an inbuilt class used to create JSON named JavaScriptSerializer.
The following code demonstrates how to use that class to convert into JSON in C#3.5.
JavaScriptSerializer serializer = new JavaScriptSerializer()
return serializer.Serialize(YOURLIST);
So, try to create a List of arrays with Questions and then serialize this list into JSON
The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:
For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:
Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.
Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.
Here's a real world example of why Closures kick ass... This is straight out of my Javascript code. Let me illustrate.
Function.prototype.delay = function(ms /*[, arg...]*/) {
var fn = this,
args = Array.prototype.slice.call(arguments, 1);
return window.setTimeout(function() {
return fn.apply(fn, args);
}, ms);
};
And here's how you would use it:
var startPlayback = function(track) {
Player.play(track);
};
startPlayback(someTrack);
Now imagine you want the playback to start delayed, like for example 5 seconds later after this code snippet runs. Well that's easy with delay
and it's closure:
startPlayback.delay(5000, someTrack);
// Keep going, do other things
When you call delay
with 5000
ms, the first snippet runs, and stores the passed in arguments in it's closure. Then 5 seconds later, when the setTimeout
callback happens, the closure still maintains those variables, so it can call the original function with the original parameters.
This is a type of currying, or function decoration.
Without closures, you would have to somehow maintain those variables state outside the function, thus littering code outside the function with something that logically belongs inside it. Using closures can greatly improve the quality and readability of your code.
Try this:
[https://lodash.com/docs/4.17.4#clone][1]
var objects = [{ 'a': 1 }, { 'b': 2 }];
var shallow = _.clone(objects);
console.log(shallow[0] === objects[0]);
// => true
ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:
For Swift 2.3
extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSUnderlineStyleAttributeName, value: NSUnderlineStyle.StyleSingle.rawValue, range: NSRange(location: 0, length: (self.titleLabel?.text!.characters.count)!))
self.setAttributedTitle(attributedString, forState: .Normal)
}
}
and in ViewController
@IBOutlet var yourButton: UIButton!
in ViewDidLoad
Method or in your function just write
yourButton.underline()
it will underline the title of your button
If you're not using auto-incrementing fields, you can achieve a similar result with something like the following:
insert into Customers (ID, FirstName, LastName)
select max(ID)+1, 'Barack', 'Obama' from Customers;
This will ensure there's no chance of a race condition which could be caused by someone else inserting into the table between your extraction of the maximum ID and your insertion of the new record.
This is using standard SQL, there are no doubt better ways to achieve it with specific DBMS' but they're not necessarily portable (something we take very seriously in our shop).
For Microsoft Access
UPDATE TableA A
INNER JOIN TableB B
ON A.ID = B.ID
SET A.Name = B.Name
You can also restrict keys to permissible commands (in the authorized_keys file).
I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")
Instead of
cmd = new OracleCommand("ProcName", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
You can also use this syntax:
cmd = new OracleCommand("BEGIN ProcName(:p0); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
Note, if you set cmd.BindByName = False
(which is the default) then you have to add the parameters in the same order as they are written in your command string, the actual names are not relevant. For cmd.BindByName = True
the parameter names have to match, the order does not matter.
In case of a function call the command string would be like this:
cmd = new OracleCommand("BEGIN :ret := ProcName(:ParName); END;", con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("ret", OracleDbType.RefCursor, ParameterDirection.ReturnValue);
cmd.Parameters.Add("ParName", OracleDbType.Varchar2, ParameterDirection.Input).Value = "foo";
// cmd.ExecuteNonQuery(); is not needed, otherwise the function is executed twice!
var da = new OracleDataAdapter(cmd);
da.Fill(dt);
The answers above are still using the old Python 3.4 style coroutines. Here is what you would write if you got Python 3.5+.
aiohttp
supports http proxy now
import aiohttp
import asyncio
async def fetch(session, url):
async with session.get(url) as response:
return await response.text()
async def main():
urls = [
'http://python.org',
'https://google.com',
'http://yifei.me'
]
tasks = []
async with aiohttp.ClientSession() as session:
for url in urls:
tasks.append(fetch(session, url))
htmls = await asyncio.gather(*tasks)
for html in htmls:
print(html[:100])
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
My problem was I was modifying the settings for the wrong version of my app.
I had "Debug" selected instead of "Release", so my bundle identifier was not accurate when it came time to Archive.
http://msdn.microsoft.com/en-us/library/system.convert.aspx
l1 = Convert.ToInt64(strValue)
Though the example you gave isn't an integer, so I'm not sure why you want it as a long.
$_
is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ...
so $_
represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:
write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH
Document
Document style messages can be validated against predefined schema.
In document style, SOAP message is sent as a single document.
Example of schema:
<types>
<xsd:schema> <xsd:import namespace="http://example.com/"
schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>
</xsd:schema>
</types>
Example of document style soap body message
<message name="getHelloWorldAsString">
<part name="parameters" element="tns:getHelloWorldAsString"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>
</message>
Document style message is loosely coupled.
RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.
<message name="getHelloWorldAsString">
<part name="arg0"> type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return"
> type="xsd:string"/>
</message>
Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters
Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.
<soap:body>
<myMethod>
<x>5</x>
<y>5.0</y>
</myMethod>
</soap:body>
Encoded Datatype specified in each parameter
<soap:body>
<myMethod>
<x xsi:type="xsd:int">5</x>
<y xsi:type="xsd:float">5.0</y>
</myMethod>
</soap:body>
Schema free
With my current reputation I have no ability to comment, so I choose answer referencing comments for sample code in reply by Prashant Gaur (thanks, Gaur - this was helpful!) - his sample is for python2, since python3 has no
unicodemethod.
The replacement below for function
get_prep_value(self, value):should work with Django running with python3 (I'll use this code soon - yet not tested). Note, though, that I'm passing
encoding='utf-8', errors='ignore'parameters to
decode()and
unicode() methods. Encoding should match your Django settings.py configuration and passing
errors='ignore'is optional (and may result in silent data loss instead of exception whith misconfigured django in rare cases).
import sys ... def get_prep_value(self, value): if value is None: return value if sys.version_info[0] >= 3: if isinstance(out_data, type(b'')): return value.decode(encoding='utf-8', errors='ignore') else: if isinstance(out_data, type(b'')): return unicode(value, encoding='utf-8', errors='ignore') return str(value) ...
This works perfectly fine
<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
<option style="display:none" value=""></option>
</select>
the way it works is, that this gives the first option to be displayed before selecting something and the display:none
removes it form the dropdown so if you want you can do
<select ng-model="contact.Title" ng-options="co for co in['Mr.','Ms.','Mrs.','Dr.','Prof.']">
<option style="display:none" value="">select an option...</option>
</select>
and this will give you the select and option
before selecting but once selected it will disappear, and it will not show up in the dropdown.
I made a small function,placed it from where I can use it globally & working fine with swift 2.1:
func getColorFromHex(rgbValue:UInt32)->UIColor{
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/255.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/255.0
let blue = CGFloat(rgbValue & 0xFF)/255.0
return UIColor(red:red, green:green, blue:blue, alpha:1.0)
}
usage:
getColorFromHex(0xffffff)
var arrCombo = function(arr1, arr2){
return arr1.concat(arr2).sort(function(x, y) {
return x - y;
});
};
This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.
Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.
In this case I'd ask why you're including both cstdlib
and stdlib.h
; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib
puts them in the namespace std
in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!
Anyway, your use of using namespace std
(which I would recommend against, in future) means that std::system
from cstdlib
now conflicts with system
from stdlib.h
. I can't explain what's going on with std::cout
and std::cin
.
Try removing #include <stdlib.h>
and see what happens.
If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.
pass
in Python basically does nothing, but unlike a comment it is not ignored by interpreter. So you can take advantage of it in a lot of places by making it a place holder:
1: Can be used in class
class TestClass:
pass
2: Can be use in loop and conditional statements:
if (something == true): # used in conditional statement
pass
while (some condition is true): # user is not sure about the body of the loop
pass
3: Can be used in function :
def testFunction(args): # programmer wants to implement the body of the function later
pass
pass
is mostly used when programmer does not want to give implementation at the moment but still wants to create a certain class/function/conditional statement which can be used later on. Since the Python interpreter does not allow for blank or unimplemented class/function/conditional statement it gives an error:
IndentationError: expected an indented block
pass
can be used in such scenarios.
in your css use white-space:nowrap;
Easiest method is
<TD>
<xsl:value-of select="concat(//author/first-name,' ',//author/last-name)"/>
</TD>
when the XML Structure is
<title>The Confidence Man</title>
<author>
<first-name>Herman</first-name>
<last-name>Melville</last-name>
</author>
<price>11.99</price>
This answer is similar to 17 but avoiding wrapper exception definition:
List test = new ArrayList();
try {
test.forEach(obj -> {
//let say some functionality throws an exception
try {
throw new IOException("test");
}
catch(Exception e) {
throw new RuntimeException(e);
}
});
}
catch (RuntimeException re) {
if(re.getCause() instanceof IOException) {
//do your logic for catching checked
}
else
throw re; // it might be that there is real runtime exception
}
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
I have combined all the previous answers:
public static string UrlPathCombine(string path1, string path2)
{
path1 = path1.TrimEnd('/') + "/";
path2 = path2.TrimStart('/');
return Path.Combine(path1, path2)
.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
}
[TestMethod]
public void TestUrl()
{
const string P1 = "http://msdn.microsoft.com/slash/library//";
Assert.AreEqual("http://msdn.microsoft.com/slash/library/site.aspx", UrlPathCombine(P1, "//site.aspx"));
var path = UrlPathCombine("Http://MyUrl.com/", "Images/Image.jpg");
Assert.AreEqual(
"Http://MyUrl.com/Images/Image.jpg",
path);
}
From my research and starting on this post, i think this is the best option:
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">This will stick at the botton no matter what :).</p>
_x000D_
This option allow resizes of the page and even if the page is blank it will stick at the bottom.
Might be useful to some : check for
pointer-events: none;
In the CSS. It prevents clicks from being caught by JS. I think it's relevant because the CSS might be the last place you'd look into in this kind of situation.
I used the following to filter out given values in a col:
def filter_rows_by_values(df, col, values):
return df[df[col].isin(values) == False]
Example:
In a DataFrame I want to remove rows which have values "b" and "c" in column "str"
df = pd.DataFrame({"str": ["a","a","a","a","b","b","c"], "other": [1,2,3,4,5,6,7]})
df
str other
0 a 1
1 a 2
2 a 3
3 a 4
4 b 5
5 b 6
6 c 7
filter_rows_by_values(d,"str", ["b","c"])
str other
0 a 1
1 a 2
2 a 3
3 a 4
For anyone experiencing this in angular 9+
This issue can also be experienced if you do not declare or import the component that declares your component.
Lets consider a situation where you intend to use ng-select
but you forget to import it Angular will throw the error 'No value accessor...'
I have reproduced this error in the Below stackblitz demo.
Maybe it help you. I use this in my app
https://github.com/rubyworks/facets
class String
# Create a random String of given length, using given character set
#
# Character set is an Array which can contain Ranges, Arrays, Characters
#
# Examples
#
# String.random
# => "D9DxFIaqR3dr8Ct1AfmFxHxqGsmA4Oz3"
#
# String.random(10)
# => "t8BIna341S"
#
# String.random(10, ['a'..'z'])
# => "nstpvixfri"
#
# String.random(10, ['0'..'9'] )
# => "0982541042"
#
# String.random(10, ['0'..'9','A'..'F'] )
# => "3EBF48AD3D"
#
# BASE64_CHAR_SET = ["A".."Z", "a".."z", "0".."9", '_', '-']
# String.random(10, BASE64_CHAR_SET)
# => "xM_1t3qcNn"
#
# SPECIAL_CHARS = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "=", "+", "|", "/", "?", ".", ",", ";", ":", "~", "`", "[", "]", "{", "}", "<", ">"]
# BASE91_CHAR_SET = ["A".."Z", "a".."z", "0".."9", SPECIAL_CHARS]
# String.random(10, BASE91_CHAR_SET)
# => "S(Z]z,J{v;"
#
# CREDIT: Tilo Sloboda
#
# SEE: https://gist.github.com/tilo/3ee8d94871d30416feba
#
# TODO: Move to random.rb in standard library?
def self.random(len=32, character_set = ["A".."Z", "a".."z", "0".."9"])
chars = character_set.map{|x| x.is_a?(Range) ? x.to_a : x }.flatten
Array.new(len){ chars.sample }.join
end
end
It works fine for me
You're thinking too complicated. It's actually just $('#'+openaddress)
.
If problem is coming on windows then remove the Credentials from the Windows history.
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
You cannot push anything that hasn't been committed yet. The order of operations is:
git add
- this stages your changes for committinggit commit
- this commits your staged changes locallygit push
- this pushes your committed changes to a remoteIf you push without committing, nothing gets pushed. If you commit without adding, nothing gets committed. If you add without committing, nothing at all happens, git merely remembers that the changes you added should be considered for the following commit.
The message you're seeing (your branch is ahead by 1 commit) means that your local repository has one commit that hasn't been pushed yet.
In other words: add
and commit
are local operations, push
, pull
and fetch
are operations that interact with a remote.
Since there seems to be an official source control workflow in place where you work, you should ask internally how this should be handled.
The URL should be a string:
import urllib
link = "http://www.somesite.com/details.pl?urn=2344"
f = urllib.urlopen(link)
myfile = f.readline()
print myfile
You can just use the normal setTimeout method in JavaScript.
ie...
setTimeout( function(){
// Do something after 1 second
} , 1000 );
In your example, you might want to use showStickySuccessToast
directly.
Use two view types in the your RVAdapter
. One for expanded layout and other for collapsed.
And the magic happens with setting android:animateLayoutChanges="true"
for RecyclerView
Checkout the effect achieved using this at 0:42 in this video
Use sys.getsizeof
to get the size of an object, in bytes.
>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>
Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.
SequenceEqual can be faster. Namely in the case where almost all of the time, both arrays have indeed the same length and are not the same object.
It's still not the same functionality as the OP's function, as it won't silently compare null values.
create table payment(
user_id int(11),
account int(11) not null,
zip int(11) not null,
dt date not null
);
insert into payment values
(1,123,55555,'2009-12-12'),
(1,123,66666,'2009-12-12'),
(1,123,77777,'2009-12-13'),
(2,456,77777,'2009-12-14'),
(2,456,77777,'2009-12-14'),
(2,789,77777,'2009-12-14'),
(2,789,77777,'2009-12-14');
select foo.user_id, foo.cnt from
(select user_id,count(account) as cnt, dt from payment group by account, dt) foo
where foo.cnt > 1;
Why would you want to do that?
If you want to return some other object when a class is called, then use the __new__()
method:
class MyClass(object):
def __init__(self):
print "never called in this case"
def __new__(cls):
return 42
obj = MyClass()
print obj
In Swift 2:
extension NSMutableURLRequest {
func setAuthorizationHeader(username username: String, password: String) -> Bool {
guard let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return false }
let base64 = data.base64EncodedStringWithOptions([])
setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
return true
}
}
Run this and it worked for me
adb reverse tcp:8081 tcp:8081
I have put something like this in my Controller class and it worked:
IdentityUser user = await userManager.FindByNameAsync(HttpContext.User.Identity.Name);
where userManager is an instance of Microsoft.AspNetCore.Identity.UserManager class (with all weird setup that goes with it).
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
You can try some positioning tricks. You can put the input in a div with position: relative
and a fixed height, then on the input have position: absolute; left: 0; right: 0;
, and any padding you like.
If you are in android studio 3.1, Verify if file->Project Structure -> Source compatibility is empty. it should not have 1.8 set.
then press ok, the project will sync and error will disappear.
The solution for this problem is actually quite simple and there are two ways to go about it. If you have control over the Content.html then simply change the div#ScrolledArea
width CSS to:
width: 1px;
min-width: 100%;
*width: 100%;
Basically the idea here is simple, you set the width
to something that is smaller than the viewport (iframe width in this case) and then overwrite it with min-width: 100%
to allow for actual width: 100%
which iOS Safari by default overwrites. The *width: 100%;
is there so the code would remain IE6 compatible, but if you do not care for IE6 you can omit it. Demo
As you can see now, the div#ScrolledArea
width is actually 100% and the overflow: scroll;
can do it's thing and hide the overflowing content. If you have access to the iframe content, then this is preferable.
However if you do not have access to the iframe content (for what ever reason) then you can actually use the same technique on the iframe itself. Simply use the same CSS on the iframe:
iframe {
width: 1px;
min-width: 100%;
*width: 100%;
}
However, there is one limitation with this, you need to turn off the scrollbars with scrolling="no"
on the iframe for this to work:
<iframe height="950" width="100%" scrolling="no" src="Content.html"></iframe>
If the scrollbars are allowed, then this wont work on the iframe anymore. That said, if you modify the Content.html instead then you can retain the scrolling in the iframe. Demo
use labelpad parameter:
pl.xlabel("...", labelpad=20)
or set it after:
ax.xaxis.labelpad = 20
I have created a tool to orchestrate and launch backup of data and mysql containers, simply called docker-backup. There is even a ready-to-use image on the docker hub.
It's mainly written in Bash as it is mainly orchestration. It uses duplicity
for the actual backup engine. You can currently backup to FTP(S) and Amazon S3.
The configuration is quite simple: write a config file in YAML describing what to backup and where, and here you go!
For data containers, it automatically mount the volumes shared by your container to backup and process it. For mysql containers, it links them and execute a mysqldump bundled with your container and process the result.
I wrote it because I use Docker-Cloud which is not up-to-date with recent docker-engine releases and because I wanted to embrace the Docker way by not including any process of backup inside my application containers.
If the file is in a public folder, you can use Google Drive website hosting.
mAgendaListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//view.setBackgroundColor(Color.RED);
for(int i=0; i<parent.getChildCount(); i++)
{
if(i == position)
{
parent.getChildAt(i).setBackgroundColor(Color.BLUE);
}
else
{
parent.getChildAt(i).setBackgroundColor(Color.BLACK);
}
}
This is shorter and works
<connectionStrings>
<add name="DBConnection"
connectionString="data source=SERVER\INSTANCE;
Initial Catalog=MyDB;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
Persist Security Info not needed
You need to create a Handler
in the UI thread and then use it to post or send a message from your other thread to update the UI
public Person SomeMethod(string fName)
{
var con = ConfigurationManager.ConnectionStrings["Yourconnection"].ToString();
Person matchingPerson = new Person();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from Employees where FirstName=@fName";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("@Fname", fName);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
matchingPerson.firstName = oReader["FirstName"].ToString();
matchingPerson.lastName = oReader["LastName"].ToString();
}
myConnection.Close();
}
}
return matchingPerson;
}
Few things to note here: I used a parametrized query, which makes your code safer. The way you are making the select statement with the "where x = "+ Textbox.Text +""
part opens you up to SQL injection.
I've changed this to:
"Select * from Employees where FirstName=@fName"
oCmd.Parameters.AddWithValue("@fname", fName);
So what this block of code is going to do is:
Execute an SQL statement against your database, to see if any there are any firstnames matching the one you provided.
If that is the case, that person will be stored in a Person object (see below in my answer for the class).
If there is no match, the properties of the Person object will be null
.
Obviously I don't exactly know what you are trying to do, so there's a few things to pay attention to: When there are more then 1 persons with a matching name, only the last one will be saved and returned to you.
If you want to be able to store this data, you can add them to a List<Person>
.
Person class to make it cleaner:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Now to call the method:
Person x = SomeMethod("John");
You can then fill your textboxes with values coming from the Person object like so:
txtLastName.Text = x.LastName;
This will do the object empty checking:
<div ng-if="isEmpty(card)">Object Empty!</div>
$scope.isEmpty = function(obj){
return Object.keys(obj).length == 0;
}
In your destination field you want to use VLOOKUP like so:
=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)
VLOOKUP Arguments:
Use Guava to normalize all your commas. Split the string up around the commas, throw out the empties, and connect it all back together. Two calls. No loops. Works the first time:
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
public class TestClass {
Splitter splitter = Splitter.on(',').omitEmptyStrings().trimResults();
Joiner joiner = Joiner.on(',').skipNulls();
public String cleanUpCommas(String string) {
return joiner.join(splitter.split(string));
}
}
public class TestMain {
public static void main(String[] args) {
TestClass testClass = new TestClass();
System.out.println(testClass.cleanUpCommas("a,b,c,d,e"));
System.out.println(testClass.cleanUpCommas("a,b,c,d,e,,,,,"));
System.out.println(testClass.cleanUpCommas("a,b,,, ,c,d, ,,e,,,,,"));
System.out.println(testClass.cleanUpCommas("a,b,c,d, e,,,,,"));
System.out.println(testClass.cleanUpCommas(",,, ,,,,a,b,c,d, e,,,,,"));
}
}
Output:
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
a,b,c,d,e
Personally, I hate futzing around with counting limits of substrings and all that nonsense.
HTML:
<body ng-app="App">
<div ng-controller="testController" >
<input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
</div>
{{ testInput }}
</body>
JS:
angular.module('App', []);
testController = function ($scope) {
console.log('test');
$scope.$watch('testInput', testShow, true);
function testShow() {
console.log($scope.testInput);
}
}
The DateTimeOffset structure was created for exactly this type of use.
See: http://msdn.microsoft.com/en-us/library/system.datetimeoffset.aspx
Here's an example of creating a DateTimeOffset object with a specific time zone:
DateTimeOffset do1 = new DateTimeOffset(2008, 8, 22, 1, 0, 0, new TimeSpan(-5, 0, 0));
Use Following.
For user input to search as it is, use escape, in that it will require following replacement for all special characters (below covers all of SQL Server).
Here single quote "'" is not taken as it does not affect like clause as It is a matter of string concatenation.
"-" & "^" & "]" replace is not required as we are escaping "[".
String FormattedString = "UserString".Replace("ð","ðð").Replace("_", "ð_").Replace("%", "ð%").Replace("[", "ð[");
Then, in SQL Query it should be as following. (In parameterised query, string can be added with patterns after above replacement).
To search exact string.
like 'FormattedString' ESCAPE 'ð'
To search start with string
like '%FormattedString' ESCAPE 'ð'
To search end with string
like 'FormattedString%' ESCAPE 'ð'
To search contain with string
like '%FormattedString%' ESCAPE 'ð'
and so on for other pattern matching. But direct user input needs to format as mentioned above.
Here we can use below query to the first date of the month and last date of the month.
SELECT DATEADD(DAY,1,EOMONTH(Getdate(),-1)) as 'FD',Cast(Getdate()-1 as Date)
as 'LD'
Pandas will recognise a value as null if it is a np.nan
object, which will print as NaN
in the DataFrame. Your missing values are probably empty strings, which Pandas doesn't recognise as null. To fix this, you can convert the empty stings (or whatever is in your empty cells) to np.nan
objects using replace()
, and then call dropna()
on your DataFrame to delete rows with null tenants.
To demonstrate, we create a DataFrame with some random values and some empty strings in a Tenants
column:
>>> import pandas as pd
>>> import numpy as np
>>>
>>> df = pd.DataFrame(np.random.randn(10, 2), columns=list('AB'))
>>> df['Tenant'] = np.random.choice(['Babar', 'Rataxes', ''], 10)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640
Now we replace any empty strings in the Tenants
column with np.nan
objects, like so:
>>> df['Tenant'].replace('', np.nan, inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
1 -0.008562 0.725239 NaN
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
4 0.805304 -0.834214 NaN
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
9 0.066946 0.375640 NaN
Now we can drop the null values:
>>> df.dropna(subset=['Tenant'], inplace=True)
>>> print df
A B Tenant
0 -0.588412 -1.179306 Babar
2 0.282146 0.421721 Rataxes
3 0.627611 -0.661126 Babar
5 -0.514568 1.890647 Babar
6 -1.188436 0.294792 Rataxes
7 1.471766 -0.267807 Babar
8 -1.730745 1.358165 Rataxes
mm
is minutes. You want MM
for months:
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");
Don't feel bad - this exact mistake comes up a lot.
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$postdata = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);
This code worked for me. You can try...
There's the Managed Script Plugin which provides an easy way of managing user scripts. It also adds a build step action which allows you to select which user script to execute.
The expression -z string
is true if the length of string is zero
.
useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false
If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:
If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:
this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);
It's very important that Calendar is null - so make sure you're using:
setTimestamp(int,Timestamp).
... NOT setTimestamp(int,Timestamp,Calendar).
It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).
To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.
Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.
Note:
It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";
You only need to do this if it complains.
Step 1: check your default authentication plugin
SHOW VARIABLES LIKE 'default_authentication_plugin';
Step 2: veryfing your password validation requirements
SHOW VARIABLES LIKE 'validate_password%';
Step 3: setting up your user with correct password requirements
CREATE USER '<your_user>'@'localhost' IDENTIFIED WITH '<your_default_auth_plugin>' BY 'password';
Bulk add new categories to Woo:
Insert category id, name, url key
INSERT INTO wp_terms
VALUES
(57, 'Apples', 'fruit-apples', '0'),
(58, 'Bananas', 'fruit-bananas', '0');
Set the term values as catergories
INSERT INTO wp_term_taxonomy
VALUES
(57, 57, 'product_cat', '', 17, 0),
(58, 58, 'product_cat', '', 17, 0)
17 - is parent category, if there is one
key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id
After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories
I built a general method for that with following features:
Here the code:
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Utils.class);
@GET
@Path("16x16")
@Produces("image/png")
public Response get16x16PNG(@HeaderParam("If-Modified-Since") String modified) {
File repositoryFile = new File("c:/temp/myfile.png");
return returnFile(repositoryFile, modified);
}
/**
*
* Sends the file if modified and "not modified" if not modified
* future work may put each file with a unique id in a separate folder in tomcat
* * use that static URL for each file
* * if file is modified, URL of file changes
* * -> client always fetches correct file
*
* method header for calling method public Response getXY(@HeaderParam("If-Modified-Since") String modified) {
*
* @param file to send
* @param modified - HeaderField "If-Modified-Since" - may be "null"
* @return Response to be sent to the client
*/
public static Response returnFile(File file, String modified) {
if (!file.exists()) {
return Response.status(Status.NOT_FOUND).build();
}
// do we really need to send the file or can send "not modified"?
if (modified != null) {
Date modifiedDate = null;
// we have to switch the locale to ENGLISH as parseDate parses in the default locale
Locale old = Locale.getDefault();
Locale.setDefault(Locale.ENGLISH);
try {
modifiedDate = DateUtils.parseDate(modified, org.apache.http.impl.cookie.DateUtils.DEFAULT_PATTERNS);
} catch (ParseException e) {
logger.error(e.getMessage(), e);
}
Locale.setDefault(old);
if (modifiedDate != null) {
// modifiedDate does not carry milliseconds, but fileDate does
// therefore we have to do a range-based comparison
// 1000 milliseconds = 1 second
if (file.lastModified()-modifiedDate.getTime() < DateUtils.MILLIS_PER_SECOND) {
return Response.status(Status.NOT_MODIFIED).build();
}
}
}
// we really need to send the file
try {
Date fileDate = new Date(file.lastModified());
return Response.ok(new FileInputStream(file)).lastModified(fileDate).build();
} catch (FileNotFoundException e) {
return Response.status(Status.NOT_FOUND).build();
}
}
/*** copied from org.apache.http.impl.cookie.DateUtils, Apache 2.0 License ***/
/**
* Date format pattern used to parse HTTP date headers in RFC 1123 format.
*/
public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in RFC 1036 format.
*/
public static final String PATTERN_RFC1036 = "EEEE, dd-MMM-yy HH:mm:ss zzz";
/**
* Date format pattern used to parse HTTP date headers in ANSI C
* <code>asctime()</code> format.
*/
public static final String PATTERN_ASCTIME = "EEE MMM d HH:mm:ss yyyy";
public static final String[] DEFAULT_PATTERNS = new String[] {
PATTERN_RFC1036,
PATTERN_RFC1123,
PATTERN_ASCTIME
};
Note that the Locale switching does not seem to be thread-safe. I think, it's better to switch the locale globally. I am not sure about the side-effects though...
If you are using docker service and you have switched to other network. You need to restart docker service.
service docker restart
This solved my problem in docker.
This is another way of enabling C++11 support,
ADD_DEFINITIONS(
-std=c++11 # Or -std=c++0x
# Other flags
)
I have encountered instances where only this method works and other methods fail. Maybe it has something to do with the latest version of CMake.
I didn't want to have to work around this problem for every dialog in my project, so I created a simple jQuery plugin. This plugin is merely for opening new dialogs and placing them within the ASP.NET form:
(function($) {
/**
* This is a simple jQuery plugin that works with the jQuery UI
* dialog. This plugin makes the jQuery UI dialog append to the
* first form on the page (i.e. the asp.net form) so that
* forms in the dialog will post back to the server.
*
* This plugin is merely used to open dialogs. Use the normal
* $.fn.dialog() function to close dialogs programatically.
*/
$.fn.aspdialog = function() {
if (typeof $.fn.dialog !== "function")
return;
var dlg = {};
if ( (arguments.length == 0)
|| (arguments[0] instanceof String) ) {
// If we just want to open it without any options
// we do it this way.
dlg = this.dialog({ "autoOpen": false });
dlg.parent().appendTo('form:first');
dlg.dialog('open');
}
else {
var options = arguments[0];
options.autoOpen = false;
options.bgiframe = true;
dlg = this.dialog(options);
dlg.parent().appendTo('form:first');
dlg.dialog('open');
}
};
})(jQuery);</code></pre>
So to use the plugin, you first load jQuery UI and then the plugin. Then you can do something like the following:
$('#myDialog1').aspdialog(); // Simple
$('#myDialog2').aspdialog('open'); // The same thing
$('#myDialog3').aspdialog({title: "My Dialog", width: 320, height: 240}); // With options!
To be clear, this plugin assumes you are ready to show the dialog when you call it.
None of the above worked out for me until I changed the Action as [HttpPost]
.
and made the ajax type as POST
.
[HttpPost]
public JsonResult GetSelectedSignalData(string signal1,...)
{
JsonResult result = new JsonResult();
var signalData = GetTheData();
try
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };
result.Data = serializer.Serialize(signalData);
return Json(result, JsonRequestBehavior.AllowGet);
..
..
...
}
And the ajax call as
$.ajax({
type: "POST",
url: some_url,
data: JSON.stringify({ signal1: signal1,.. }),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data !== null) {
setValue();
}
},
failure: function (data) {
$('#errMessage').text("Error...");
},
error: function (data) {
$('#errMessage').text("Error...");
}
});
If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.
You do not need the -p
option in order to expose ports from container to host. By default, all port are exposed. The -p
option allows you to expose a port from the container to the outside of the host.
So, my guess is that you do not need -p
at all and it should be working fine :)
Note: This is not a duplicate, because the OP is aware that the image from cv2.imread
is in BGR format (unlike the suggested duplicate question that assumed it was RGB hence the provided answers only address that issue)
To illustrate, I've opened up this same color JPEG image:
once using the conversion
img = cv2.imread(path)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
and another by loading it in gray scale mode
img_gray_mode = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
Like you've documented, the diff between the two images is not perfectly 0, I can see diff pixels in towards the left and the bottom
I've summed up the diff too to see
import numpy as np
np.sum(diff)
# I got 6143, on a 494 x 750 image
I tried all cv2.imread()
modes
Among all the IMREAD_
modes for cv2.imread()
, only IMREAD_COLOR
and IMREAD_ANYCOLOR
can be converted using COLOR_BGR2GRAY
, and both of them gave me the same diff against the image opened in IMREAD_GRAYSCALE
The difference doesn't seem that big. My guess is comes from the differences in the numeric calculations in the two methods (loading grayscale vs conversion to grayscale)
Naturally what you want to avoid is fine tuning your code on a particular version of the image just to find out it was suboptimal for images coming from a different source.
In brief, let's not mix the versions and types in the processing pipeline.
So I'd keep the image sources homogenous, e.g. if you have capturing the image from a video camera in BGR, then I'd use BGR as the source, and do the BGR to grayscale conversion cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Vice versa if my ultimate source is grayscale then I'd open the files and the video capture in gray scale cv2.imread(path, cv2.IMREAD_GRAYSCALE)
The session.save(object) returns the id of the object, or you could alternatively call the id getter method after performing a save.
Save() return value:
Serializable save(Object object) throws HibernateException
Returns:
the generated identifier
Getter method example:
UserDetails entity:
@Entity
public class UserDetails {
@Id
@GeneratedValue
private int id;
private String name;
// Constructor, Setters & Getters
}
Logic to test the id's :
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.getTransaction().begin();
UserDetails user1 = new UserDetails("user1");
UserDetails user2 = new UserDetails("user2");
//int userId = (Integer) session.save(user1); // if you want to save the id to some variable
System.out.println("before save : user id's = "+user1.getId() + " , " + user2.getId());
session.save(user1);
session.save(user2);
System.out.println("after save : user id's = "+user1.getId() + " , " + user2.getId());
session.getTransaction().commit();
Output of this code:
before save : user id's = 0 , 0
after save : user id's = 1 , 2
As per this output, you can see that the id's were not set before we save the UserDetails
entity, once you save the entities then Hibernate set's the id's for your objects - user1
and user2
You can also use svnsync. This only requires read-only access on the source repository
This program does not eliminate the duplicates, but I think it is one of the most efficient approaches:
s=raw_input("Enter a string: ")
print "Permutations :\n",s
size=len(s)
lis=list(range(0,size))
while(True):
k=-1
while(k>-size and lis[k-1]>lis[k]):
k-=1
if k>-size:
p=sorted(lis[k-1:])
e=p[p.index(lis[k-1])+1]
lis.insert(k-1,'A')
lis.remove(e)
lis[lis.index('A')]=e
lis[k:]=sorted(lis[k:])
list2=[]
for k in lis:
list2.append(s[k])
print "".join(list2)
else:
break
This one minifies but doesn't obfuscate. If you don't want to use command line Java you can paste your javascript into a webform.
Actually it is possible in JPA, although a little bit of a hack using the columnDefinition
property of the @Column
annotation, for example:
@Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")
To find it from Windows OS,
catalina.bat version
It should print jre version details along with other informative details.
Using CATALINA_BASE: "C:\User\software\enterprise-server-tome...
Using CATALINA_HOME: "C:\User\software\enterprise-server-tome...
Using CATALINA_TMPDIR: "C:\User\software\enterprise-server-tome...
Using JRE_HOME: "C:\Program Files\Java\jdk1.8.0_25"
Using CLASSPATH: "C:\User\software\enterprise-server-tome...
Server version: Apache Tomcat/8.5.11
Server built: Jan 10 2017 21:02:52 UTC
Server number: 8.5.11.0
OS Name: Windows 7
OS Version: 6.1
Architecture: amd64
JVM Version: 1.8.0_25-b18
JVM Vendor: Oracle Corporation
Here is a util function modified (another post on stack) for get and post both. Make Util.js file.
let cachedData = null;
let cachedPostData = null;
const postServiceData = (url, params) => {
console.log('cache status' + cachedPostData );
if (cachedPostData === null) {
console.log('post-data: requesting data');
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then(response => {
cachedPostData = response.json();
return cachedPostData;
});
} else {
console.log('post-data: returning cachedPostData data');
return Promise.resolve(cachedPostData);
}
}
const getServiceData = (url) => {
console.log('cache status' + cachedData );
if (cachedData === null) {
console.log('get-data: requesting data');
return fetch(url, {})
.then(response => {
cachedData = response.json();
return cachedData;
});
} else {
console.log('get-data: returning cached data');
return Promise.resolve(cachedData);
}
};
export { getServiceData, postServiceData };
Usage like below in another component
import { getServiceData, postServiceData } from './../Utils/Util';
constructor(props) {
super(props)
this.state = {
datastore : []
}
}
componentDidMount = () => {
let posturl = 'yoururl';
let getdataString = { name: "xys", date:"today"};
postServiceData(posturl, getdataString)
.then(items => {
this.setState({ datastore: items })
console.log(items);
});
}
Here's one sample: http://jsfiddle.net/CUUfb/1/
I've done it with two annotations for test class: @RunWith(SpringRunner.class)
and @SpringBootTest
.
Example:
@RunWith(SpringRunner.class )
@SpringBootTest
public class ProtocolTransactionServiceTest {
@Autowired
private ProtocolTransactionService protocolTransactionService;
}
@SpringBootTest
loads the whole context, which was OK in my case.
Not sure what your asking!
However
SELECT GETDATE()
Will get you the current date and time
SELECT DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
Will get you just the date with time set to 00:00:00
I had a similar problem with a request to a non-SSL service.
This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html
I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:
@http = Net::HTTP.new('domain.com')
@http = @http.start
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req)
Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call
You can also try: (I tried this and it worked for me)
SELECT ISNULL((SELECT SUM(columnA) FROM my_table WHERE columnB = 1),0)) INTO res;
I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.
.imgContainer {
overflow: hidden;
width: 200px;
height: 100px;
}
.imgContainer img {
width: 200px;
height: 120px;
}
<div class="imgContainer">
<img src="imageSrc" />
</div>
The containing div with essentially crop the image by hiding the overflow.
I've just had a particular problem where I had to count the number of true statements from a logical vector and this worked best for me...
length(grep(TRUE, (gene.rep.matrix[i,1:6] > 1))) > 5
So This takes a subset of the gene.rep.matrix object, and applies a logical test, returning a logical vector. This vector is put as an argument to grep, which returns the locations of any TRUE entries. Length then calculates how many entries grep finds, thus giving the number of TRUE entries.
Generate the scripts?
Generate a script to create the table then generate a script to insert the data.
check-out SP_ Genereate_Inserts for generating the data insert script.
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()
To answer the question directly:
let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");
for (var i = 0; i < codeLines.length; i++) {
const first = codeLines[i].split(' ').shift()
firstWords.push(first)
}
You can use XmlDocument. Also some XPath can be useful.
Just a simple example
XmlDocument doc = new XmlDocument();
doc.Load("sample.xml");
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here
foreach (XmlNode node in nodes)
{
// use node variable here for your beeds
}
untested:
using System;
using System.Management;
ManagementObject disk = new
ManagementObject("win32_logicaldisk.deviceid="c:"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.WriteLine("Logical Disk FreeSpace = " + disk["FreeSpace"] + "
bytes");
Btw what is the outcome of free diskspace on c:\temp ? you will get the space free of c:\
To get camelCase
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
To get CamelSentenceCase or PascalCase
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
Note :
For those language with accents. Do include À-ÖØ-öø-ÿ
with the regex as following
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g
Just comment all lines in first Directory. Or you can remove these lines, but better to keep in case later you want to add some restrictions, you will uncomment.
#<Directory /usr/share/phpMyAdmin/>
# <IfModule mod_authz_core.c>
# # Apache 2.4
# <RequireAny>
# Require ip 127.0.0.1
# Require ip ::1
# </RequireAny>
# </IfModule>
# <IfModule !mod_authz_core.c>
# # Apache 2.2
# Order Deny,Allow
# Deny from All
# Allow from 127.0.0.1
# Allow from ::1
# </IfModule>
#</Directory>
Alert: This answer is for MacOS only
Let suppose you have 2 versions of nodeJS inside your nvm, namely v13.10.1 & v15.4.0
And, v15.4.0 is default
> nvm list
v13.10.1
-> v15.4.0
system
default -> 15.4.0 (-> v15.4.0)
And, you want to switch the default to v13.10.1
Follow these steps on your Mac terminal:
Run the command:
nvm alias default 13.10.1
This will make the default point to v13.10.1 as...
default -> 13.10.1 (-> v13.10.1)
node -v
You will get...
v13.10.1
nvm list will also show the new default version.
nvm list
Just an info: The NodeJS versions taken as example above will have their different npm versions. You can cross-verify it in terminal by running npm -v
you can try this.Add the parameter as output direction and after executing the query get the output parameter value.
SqlParameter parmOUT = new SqlParameter("@return", SqlDbType.Int);
parmOUT.Direction = ParameterDirection.Output;
cmd.Parameters.Add(parmOUT);
cmd.ExecuteNonQuery();
int returnVALUE = (int)cmd.Parameters["@return"].Value;
The proposed answer (stored procedure) from BartoszX didn't work for me when using a view instead of a real table.
Credit for the idea and the code below (except for my fix) belongs to BartoszX.
In order that this works for tables as well as for views, use the following code:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[select_without]
@schema_name sysname = N'dbo',
@table_name sysname,
@list_of_columns_excluded nvarchar(max),
@separator nchar(1) = N','
AS
BEGIN
DECLARE
@SQL nvarchar(max),
@full_table_name nvarchar(max) = CONCAT(@schema_name, N'.', @table_name);
SELECT @SQL = COALESCE(@SQL + ', ', '') + QUOTENAME([Name])
FROM sys.columns sc
LEFT JOIN STRING_SPLIT(@list_of_columns_excluded, @separator) ss ON sc.[name] = ss.[value]
WHERE sc.OBJECT_ID = OBJECT_ID(@full_table_name)
AND ss.[value] IS NULL;
SELECT @SQL = N'SELECT ' + @SQL + N' FROM ' + @full_table_name;
EXEC(@SQL)
END
GO
In my opinion, this is the simplest way to join two tables with multiple fields:
from a in Table1 join b in Table2
on (a.Field1.ToString() + "&" + a.Field2.ToString())
equals (b.Field1.ToString() + "&" + b.Field2.ToString())
select a
This maybe helpful for MySql with AppArmor
stop mysql :
sudo /etc/init.d/mysql stop
Create directory called /somewhere/tmp
Edit Config:
sudo vim /etc/mysql/my.cnf
# or perhaps sudo vim /etc/mysql/mysql.conf.d/mysqld.cnf
change
tmpdir = /somewhere/tmp/
Then
sudo vim /etc/apparmor.d/usr.sbin.mysqld
Add
# Allow data dir access
/somewhere/ r,
/somewhere/** rwk,
sudo chown -R root:root /somewhere
sudo chmod -R 1777 /somewhere
Restart
sudo /etc/init.d/apparmor reload
sudo /etc/init.d/mysql restart
If no From: header is specified in the e-mail headers, the MTA uses the full name of the current user, in this case "Apache". You can edit full user names in /etc/passwd
The following compiles for me:
class E{
String s = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~#;:?/@&!\"'%*=¼.,-])(?=[^\\s]+$).{8,24}$";
}
See:
I think the only cookie you need is JSESSIONID=xxx..
Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.
There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.
I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.
As a small example, say you have a library with the header myclass.h:
#include<iostream>
class MyClass {
int myNumber;
public:
MyClass(int number): myNumber(number){}
void sayHello() {
std::cout << "Hello, my number is:"
<< myNumber <<std::endl;
}
};
In order to use this class in node, you simply write the following SWIG interface file (mylib.i):
%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"
Create the binding file binding.gyp:
{
"targets": [
{
"target_name": "mylib",
"sources": [ "mylib_wrap.cxx" ]
}
]
}
Run the following commands:
swig -c++ -javascript -node mylib.i
node-gyp build
Now, running node from the same folder, you can do:
> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5
Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass
constructor nor the sayHello
method anywhere, SWIG discovers these things, and automatically generates natural interfaces.
window.open('your_url', 'popup_name','height=' + screen.height + ',width=' + screen.width + ',resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes')
Use XSSFCellStyle.BORDER_MEDIUM
or XSSFBorderFormatting.BORDER_MEDIUM
(both enums refer to the same value):
XSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setBorderTop(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderRight(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_MEDIUM);
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_MEDIUM);
cell.setCellStyle(cellStyle);
Use setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, XSSFColor)
or setBottomBorderColor(XSSFColor)
(equivalent for top, left, right):
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFColor color = new XSSFColor(new java.awt.Color(128, 0, 128));
cellStyle.setTopBorderColor(color);
cellStyle.setRightBorderColor(color);
cellStyle.setBottomBorderColor(color);
cellStyle.setLeftBorderColor(color);
cell.setCellStyle(cellStyle);
The keyword extends
can be used for interfaces and classes only.
If you just want to declare a type that has additional properties, you can use intersection type:
type UserEvent = Event & {UserId: string}
UPDATE for TypeScript 2.2, it's now possible to have an interface that extends object-like type, if the type satisfies some restrictions:
type Event = {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
It does not work the other way round - UserEvent
must be declared as interface, not a type
if you want to use extends
syntax.
And it's still impossible to use extend
with arbitrary types - for example, it does not work if Event
is a type parameter without any constraints.
Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve
How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).
The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:
EXPORTS main=_main
Borland compilers add an underscore to function names, and this exports the main()
function the way a VST host expects it. For more information about .def files, see the C++Builder help files.
This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:
In the constructor of your effect class, write
_control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
That should do the trick.
Here are some more useful sites:
http://www.steinberg.net/en/company/developer.html
how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial
Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head>
and it will patch setInterval
and setTimeout
with ones that use WebWorker
.
There are already a lot of answers in this thread but none of them particularly helped me, I had to work it out myself, so I hope this one is a little more informative.
You just have to make sure you have parentheses at the end of your class, e.g:
print(class())
Here's an example of code from a project I was working on:
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol = symbol
self.number = number
def __str__(self):
return "{}: {}\nAtomic Number: {}\n".format(self.name, self.symbol, self.number
class Hydrogen(Element):
def __init__(self):
super().__init__(name = "Hydrogen", symbol = "H", number = "1")
To print my Hydrogen class, I used the following:
print(Hydrogen())
Please note, this will not work without the parentheses at the end of Hydrogen. They are necessary.
Hope this helps, let me know if you have anymore questions.
Examples for: https://(www.)example.com/subFolder/myfile.php?var=blabla#555
// ======= PATHINFO ====== //
$x = pathinfo($url);
$x['dirname'] https://example.com/subFolder
$x['basename'] myfile.php?var=blabla#555 // Unsecure!
$x['extension'] php?var=blabla#555 // Unsecure!
$x['filename'] myfile
// ======= PARSE_URL ====== //
$x = parse_url($url);
$x['scheme'] https
$x['host'] example.com
$x['path'] /subFolder/myfile.php
$x['query'] var=blabla
$x['fragment'] 555
//=================================================== //
//========== self-defined SERVER variables ========== //
//=================================================== //
$_SERVER["DOCUMENT_ROOT"] /home/user/public_html
$_SERVER["SERVER_ADDR"] 143.34.112.23
$_SERVER["SERVER_PORT"] 80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"] https //similar: $_SERVER["SERVER_PROTOCOL"]
$_SERVER['HTTP_HOST'] example.com (or with WWW) //similar: $_SERVER["SERVER_NAME"]
$_SERVER["REQUEST_URI"] /subFolder/myfile.php?var=blabla
$_SERVER["QUERY_STRING"] var=blabla
__FILE__ /home/user/public_html/subFolder/myfile.php
__DIR__ /home/user/public_html/subFolder //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"] /subFolder/myfile.php?var=blabla
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH) /subFolder/myfile.php
$_SERVER["PHP_SELF"] /subFolder/myfile.php
// ==================================================================//
//if "myfile.php" is included in "PARENTFILE.php" , and you visit "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"] /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"] /parentfile.php
$_SERVER["REQUEST_URI"] /parentfile.php?var=blabla
__FILE__ /home/user/public_html/subFolder/myfile.php
// =================================================== //
// ================= handy variables ================= //
// =================================================== //
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' ); //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO']) ...
//To trim values to filename, i.e.
basename($url) myfile.php
//excellent solution to find origin
$debug_files = debug_backtrace();
$caller_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;
Notice ! ! !
#
parts were manually used in the above example just for illustration purposes, however, server-side languages (including php
) can't natively detect them (Only Javascript can do that, as hashtag is only browser/client side
functionality ).DIRECTORY_SEPARATOR
returns \
for Windows-type hosting, instead of /
.//(let's say, if wordpress is installed in subdirectory: http://example.com/wpdir/)
home_url() http://example.com/wpdir/ //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri() http://example.com/wpdir/wp-content/themes/THEME_NAME [same: get_bloginfo('template_url') ]
get_stylesheet_directory() /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__) http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__) /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/
This seems a little bit like homework. So I'll give you some hints. The good news is that you're almost there! You've done most of the hard work already!
randomFill()
to the current location of the array.Note: Your array is double
, but you are returning int
s from randomFill
. So there's something you need to fix there.
Unable to resolve host “”; No address associated with hostname
I had this issue and I solved it by this way. change
http://hostname/abc/def/ghi/name.php
to
http://ipaddress/abc/def/ghi/name.php //http://97.68.XX.YY/abc/def/ghi/name.php
I solved this by this way...you have to give server ip address instead of hostname/servername.
Please try this and comment your feedback.
I just love getting information like BalusC gives here - and he is kind enough to help SO many people with such GOOD information that I regard his words as gospel, but I was not able to use that order of events to solve this same kind of timing issue in my project. Since BalusC put a great general reference here that I even bookmarked, I thought I would donate my solution for some advanced timing issues in the same place since it does solve the original poster's timing issues as well. I hope this code helps someone:
<p:pickList id="formPickList"
value="#{mediaDetail.availableMedia}"
converter="MediaPicklistConverter"
widgetVar="formsPicklistWidget"
var="mediaFiles"
itemLabel="#{mediaFiles.mediaTitle}"
itemValue="#{mediaFiles}" >
<f:facet name="sourceCaption">Available Media</f:facet>
<f:facet name="targetCaption">Chosen Media</f:facet>
</p:pickList>
<p:commandButton id="viewStream_btn"
value="Stream chosen media"
icon="fa fa-download"
ajax="true"
action="#{mediaDetail.prepareStreams}"
update=":streamDialogPanel"
oncomplete="PF('streamingDialog').show()"
styleClass="ui-priority-primary"
style="margin-top:5px" >
<p:ajax process="formPickList" />
</p:commandButton>
The dialog is at the top of the XHTML outside this form and it has a form of its own embedded in the dialog along with a datatable which holds additional commands for streaming the media that all needed to be primed and ready to go when the dialog is presented. You can use this same technique to do things like download customized documents that need to be prepared before they are streamed to the user's computer via fileDownload buttons in the dialog box as well.
As I said, this is a more complicated example, but it hits all the high points of your problem and mine. When the command button is clicked, the result is to first insure the backing bean is updated with the results of the pickList, then tell the backing bean to prepare streams for the user based on their selections in the pick list, then update the controls in the dynamic dialog with an update, then show the dialog box ready for the user to start streaming their content.
The trick to it was to use BalusC's order of events for the main commandButton and then to add the <p:ajax process="formPickList" />
bit to ensure it was executed first - because nothing happens correctly unless the pickList updated the backing bean first (something that was not happening for me before I added it). So, yea, that commandButton rocks because you can affect previous, pending and current components as well as the backing beans - but the timing to interrelate all of them is not easy to get a handle on sometimes.
Happy coding!
it's better to think in a practical context. In our team, we use rsync -aP
to replace a bad cassandra host in our cluster. We can't do this with scp (slow and no progress preservation).
Do you mean these hex values?
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...
You can find these in glyphicons.css
here:
http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
$('#notice_div').load('response.php');
}, 3000); // the "3000"
});
Try this instead:
=SUM(IF(MONTH($A$2:$A$6)=1,$B$2:$B$6,0))
It's an array formula, so you will need to enter it with the Control-Shift-Enter key combination.
Here's how the formula works.
{1, 1, 1, 2, 2}
.{1, 1, 1, 2, 2}= 1
produces the array {TRUE, TRUE, TRUE, FALSE, FALSE}
, which comprises the condition for the IF statement.{430, 96, 400..
for the values of the sum ranges where the month value equals 1 and ..0,0}
where the month value does not equal 1.{430, 96, 400, 0, 0}
is then summed to get the answer you are looking for.This is essentially equivalent to what the SUMIF and SUMIFs functions do. However, neither of those functions support the kind of calculation you tried to include in the conditional.
It's also possible to drop the IF completely. Since TRUE and FALSE can also be treated as 1 and 0, this formula--=SUM((MONTH($A$2:$A$6)=1)*$B$2:$B$6)
--also works.
Heads up: This does not work in Google Spreadsheets
I've just had a similar problem to this and finally figured out the cause: the application.properties file had the wrong ownership and rwx attributes. So when tomcat started up the application.properties file was in the right location, but owned by another user:
$ chmod 766 application.properties
$ chown tomcat application.properties
If you do not have Administrator access to the MySQL Server configuration (i.e. you are using a hosting service), then there are 2 options to get this to work:
1) Request that the old_passwords option be set to false on the MySQL server
2) Downgrade PHP to 5.2.2 until option 1 occurs.
From what I've been able to find, the issue seems to be with how the MySQL account passwords are stored and if the 'old_passwords' setting is set to true. This causes a compatibility issue between MySQL and newer versions of PHP (5.3+) where PHP attempts to connect using a 41-character hash but the MySQL server is still storing account passwords using a 16-character hash.
This incompatibility was brought about by the changing of the hashing method used in MySQL 4.1 which allows for both short and long hash lengths (Scenario 2 on this page from the MySQL site: http://dev.mysql.com/doc/refman/5.5/en/password-hashing.html) and the inclusion of the MySQL Native Driver in PHP 5.3 (backwards compatibility issue documented on bullet 7 of this page from the PHP documentation: http://www.php.net/manual/en/migration53.incompatible.php).
The easiest way is to use Android Debug Database library (7.7k stars on GitHub).
Advantages:
How to use:
debugImplementation 'com.amitshekhar.android:debug-db:1.0.6'
to build.gradle (module)
;D/DebugDB: Open http://192.168.232.2:8080 in your browser
, the link will be different) and open it in the browser;Important:
adb forward tcp:8080 tcp:8080
For more information go to the library page on GitHub.
Please Try this code margin-left:60px
instead of left:60px
please take a look: http://jsfiddle.net/hbirjand/2LtBh/2/
as @Shomz said,transition must be changed to transition:margin 1s linear;
instead of transition:all 1s linear;
If you want to check for a specific class then you can use
if([MyClass class] == [myClassObj class]) {
//your object is instance of MyClass
}
If you're looking for the path of a specific app, a quick and dirty solution is to just grep the bugreport:
$ adb bugreport | grep 'dir=/data/app'
I don't know that this will provide an exhaustive list, so it may help to run the app first.
I was using Markwon for markdown parsing in Android. The following worked great:
"My first line \nMy second line \nMy third line \nMy last line"
...two spaces followed by \n
at the end of each line.
If JDK installed but still not working.
In Eclipse follow below steps:- Window --> Preference --> Installed JREs -->Change path of JRE to JDK(add).
PowerShell interpolates, does it not?
In PHP
echo "filesizecounter: " . $filesizecounter
can also be written as:
echo "filesizecounter: $filesizecounter"
In PowerShell something like this should suit your needs:
Write-Host "filesizecounter: $filesizecounter"
For me
sudo apt-get install php5-mcrypt
solved the issue
Another thing to note with std::map
:
myMap[nonExistingKey];
will create a new entry in the map, keyed to nonExistingKey
initialized to a default value.
This scared the hell out of me the first time I saw it (while banging my head against a nastly legacy bug). Wouldn't have expected it. To me, that looks like a get operation, and I didn't expect the "side-effect." Prefer map.find()
when getting from your map.
Not all cultures use the same format for dates and decimal / currency values.
This will matter for you when you are converting input values (read) that are stored as strings to DateTime
, float
, double
or decimal
. It will also matter if you try to format the aforementioned data types to strings (write) for display or storage.
If you know what specific culture that your dates and decimal / currency values will be in ahead of time, you can use that specific CultureInfo
property (i.e. CultureInfo("en-GB")
). For example if you expect a user input.
The CultureInfo.InvariantCulture
property is used if you are formatting or parsing a string that should be parseable by a piece of software independent of the user's local settings.
The default value is CultureInfo.InstalledUICulture
so the default CultureInfo is depending on the executing OS's settings. This is why you should always make sure the culture info fits your intention (see Martin's answer for a good guideline).
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
Well, by IP is faster.
Basically, when you call by server name, it is converted to original IP.
But it would be difficult to memorize an IP, for this reason the domain name was created.
Personally I use http://localhost
instead of http://127.0.0.1
or http://username
.
Alternatively, you can install "SourceForge Notepad++ Compare Plugin 1.5.6". It provides compare functionality between two files and show the differences between two files.
Link to refer : https://sourceforge.net/projects/npp-compare/files/1.5.6/
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
Can you add a method to your class? If not, have you thought about using extension methods? You could create an extension method for your object type called GetPropC()
.
Example:
public static class MyExtensions
{
public static int GetPropC(this MyObjectType obj, int defaltValue)
{
if (obj != null && obj.PropertyA != null & obj.PropertyA.PropertyB != null)
return obj.PropertyA.PropertyB.PropertyC;
return defaltValue;
}
}
Usage:
int val = ObjectA.GetPropC(0); // will return PropC value, or 0 (defaltValue)
By the way, this assumes you are using .NET 3 or higher.
The question is correctly answered here Center a column using Twitter Bootstrap 3
For odd rows: i.e., col-md-7 or col-large-9 use this
Add col-centered to the column you want centered.
<div class="col-lg-11 col-centered">
And add this to your stylesheet:
.col-centered{
float: none;
margin: 0 auto;
}
For even rows: i.e., col-md-6 or col-large-10 use this
Simply use bootstrap 3's offset col class. i.e.,
<div class="col-lg-10 col-lg-offset-1">
myList.GroupBy(i => i.id).Select(group => group.First())
It's as easy as in your Visual studio.
No need to compile stuff. You can do the same with ssh-keygen
:
ssh-keygen -f pub1key.pub -i
will read the public key in openssl format from pub1key.pub
and output it in OpenSSH format.
Note: In some cases you will need to specify the input format:
ssh-keygen -f pub1key.pub -i -mPKCS8
From the ssh-keygen docs (From man ssh-keygen):
-m key_format Specify a key format for the -i (import) or -e (export) conversion options. The supported key formats are: “RFC4716” (RFC 4716/SSH2 public or private key), “PKCS8” (PEM PKCS8 public key) or “PEM” (PEM public key). The default conversion format is “RFC4716”.
You can use: $counter = count($datas);
I'm using rescu with Kotlin and resolved it by using @ConstructorProperties
data class MyResponse @ConstructorProperties("message", "count") constructor(
val message: String,
val count: Int
)
Jackson uses @ConstructorProperties. This should fix Lombok @Data as well.
You need use patches.
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, aspect='equal')
ax2.add_patch(
patches.Rectangle(
(0.1, 0.1),
0.5,
0.5,
fill=False # remove background
) )
fig2.savefig('rect2.png', dpi=90, bbox_inches='tight')
if permission issue and you have ssh access in root folder
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;
will resolve your error
Can you clarify your question? What is "ohHover" in this case and how does it correspond to a delay in hover time?
That said, I think what you probably want is...
var timeout;
element.onmouseover = function(e) {
timeout = setTimeout(function() {
// ...
}, delayTimeMs)
};
element.onmouseout = function(e) {
if(timeout) {
clearTimeout(timeout);
}
};
Or addEventListener
/attachEvent
or your favorite library's event abstraction method.
your_field DATETIME NULL DEFAULT NULL
INSERT INTO x(your_field)VALUES(NULL)
If you're on OpenWrt or using some old version of wget which doesn't gives you -i
option:
#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
wget $line
done < "$input"
Furthermore, if you don't have wget
, you can use curl
or whatever you use for downloading individual files.
What I do is I want the page to stay after submit when there are errors...So I want the page to be reloaded :
($_SERVER["PHP_SELF"])
While I include the sript from a seperate file e.g
include_once "test.php";
I also read somewhere that
if(isset($_POST['submit']))
Is a beginners old fasion way of posting a form, and
if ($_SERVER['REQUEST_METHOD'] == 'POST')
Should be used (Not my words, read it somewhere)
// Ready to run
import java.io.File;
public class Filewalker {
public void walk( String path ) {
File root = new File( path );
File[] list = root.listFiles();
if (list == null) return;
for ( File f : list ) {
if ( f.isDirectory() ) {
walk( f.getAbsolutePath() );
System.out.println( "Dir:" + f.getAbsoluteFile() );
}
else {
System.out.println( "File:" + f.getAbsoluteFile() );
}
}
}
public static void main(String[] args) {
Filewalker fw = new Filewalker();
fw.walk("c:\\" );
}
}
I had the same problem and wrote a class that seems to work for me. Basically, I used a static layout to draw the text in a separate canvas and remeasure until I find a font size that fits. You can see the class posted in the topic below. I hope it helps.
In Swift:
tableView.alwaysBounceVertical = false
Using the Func as mentioned above works but there are also delegates that do the same task and also define intent within the naming:
public delegate double MyFunction(double x);
public double Diff(double x, MyFunction f)
{
double h = 0.0000001;
return (f(x + h) - f(x)) / h;
}
public double MyFunctionMethod(double x)
{
// Can add more complicated logic here
return x + 10;
}
public void Client()
{
double result = Diff(1.234, x => x * 456.1234);
double secondResult = Diff(2.345, MyFunctionMethod);
}
Something like this:
var div = document.getElementById("result");_x000D_
_x000D_
var str = "{'a':1}";_x000D_
str = str.replace(/\'/g, '"');_x000D_
var parsed = JSON.parse(str);_x000D_
console.log(parsed);_x000D_
div.innerText = parsed.a;
_x000D_
<div id="result"></div>
_x000D_
I was getting this error when trying to run my test web page directly from "file:///C:/webtests/myfile.htm". To fix it, I didn't have to make any changes to my App Settings. Instead, I just had to host my HTML file on an actual server and then hit it like: "http://localhost/myfile.htm".
Hope that helps someone.
I solved the problem REF
Run
# For Yarn
yarn add eslint-plugin-jest -D
# For NPM
npm i eslint-plugin-jest -D
And then add in your .eslintrc
file
{
"extends": ["airbnb","plugin:jest/recommended"],
}
For Xamarin Developers, you can use:
intent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
Quick approach to this would be to set a booby/bot trap.
Make a page that if it's opened a certain amount of times or even opened at all, will collect certain information like the IP and whatnot (you can also consider irregularities or patterns but this page shouldn't have to be opened at all).
Make a link to this in your page that is hidden with CSS display:none; or left:-9999px; positon:absolute; try to place it in places that are less unlikely to be ignored like where your content falls under and not your footer as sometimes bots can choose to forget about certain parts of a page.
In your robots.txt file set a whole bunch of disallow rules to pages you don't want friendly bots (LOL, like they have happy faces!) to gather information on and set this page as one of them.
Now, If a friendly bot comes through it should ignore that page. Right but that still isn't good enough. Make a couple more of these pages or somehow re-route a page to accept differnt names. and then place more disallow rules to these trap pages in your robots.txt file alongside pages you want ignored.
Collect the IP of these bots or anyone that enters into these pages, don't ban them but make a function to display noodled text in your content like random numbers, copyright notices, specific text strings, display scary pictures, basically anything to hinder your good content. You can also set links that point to a page which will take forever to load ie. in php you can use the sleep() function. This will fight the crawler back if it has some sort of detection to bypass pages that take way too long to load as some well written bots are set to process X amount of links at a time.
If you have made specific text strings/sentences why not go to your favorite search engine and search for them, it might show you where your content is ending up.
Anyway, if you think tactically and creatively this could be a good starting point. The best thing to do would be to learn how a bot works.
I'd also think about scambling some ID's or the way attributes on the page element are displayed:
<a class="someclass" href="../xyz/abc" rel="nofollow" title="sometitle">
that changes its form every time as some bots might be set to be looking for specific patterns in your pages or targeted elements.
<a title="sometitle" href="../xyz/abc" rel="nofollow" class="someclass">
id="p-12802" > id="p-00392"
For some reason none of these solutions worked for me. I've had the best success using transforms.
transform: translateX(-5.8%) translateY(-5%) scale(0.884);
If you want to calculate your own location, then first set StartPosition
to FormStartPosition.Manual
:
Form Child = new Form();
Child.StartPosition = FormStartPosition.Manual;
Child.Location = new Point(Location.X + (Width - Child.Width) / 2, Location.Y + (Height - Child.Height) / 2);
Child.Show(this);
Where this is the main/parent form, just like Location.X.
Default value for StartPosition
is FormStartPosition.CenterParent
and therefore it changes the child's location after showing.
You can write like this:
CSS
span{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
left:-30px;
display:none;
padding:0 20px;
}
span:after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
margin:100px;
float:left;
position:relative;
cursor:pointer;
}
p:hover span{
display:block;
}
HTML
<p>Hover here<span>some text here ?</span></p>
Check this http://jsfiddle.net/UNs9J/1/
You can use "os.sep "
import os
pathfile=os.path.dirname(templateFile)
directory = str(pathfile)+os.sep+'output'+os.sep+'log.txt'
rootTree.write(directory)
Sometimes the Maven command line is sufficient when scripting something related to the project version, e.g. for artifact retrieval via URL from a repository:
mvn help:evaluate -Dexpression=project.version -q -DforceStdout
Usage example:
VERSION=$( mvn help:evaluate -Dexpression=project.version -q -DforceStdout )
ARTIFACT_ID=$( mvn help:evaluate -Dexpression=project.artifactId -q -DforceStdout )
GROUP_ID_URL=$( mvn help:evaluate -Dexpression=project.groupId -q -DforceStdout | sed -e 's#\.#/#g' )
curl -f -S -O http://REPO-URL/mvn-repos/${GROUP_ID_URL}/${ARTIFACT_ID}/${VERSION}/${ARTIFACT_ID}-${VERSION}.jar
you should change the type from submit
to button
:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me hope it helps.
Just to add on to what @Zaph says in the comments.
I have the same problem as you, as to know, the array of String
is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String]
neither of [AnyObject]
.
However an array of [NSString]
works for me.
So your code could look like that :
var key = "keySave"
var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")
//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()
//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
var readArray : [NSString] = testArray! as [NSString]
}
Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString]
to have it working.
EDIT
Re-reading your question and your title, you are talking of array of array
. I think that as long as you stay with NSString
, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.
If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."
<bindings>
<basicHttpBinding>
<binding name="MyBasicHttpBinding">
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyService">
<endpoint
binding="basicHttpBinding"
bindingConfiguration="MyBasicHttpBinding"
name="basicEndPoint"
contract="IMyService"
/>
</service>
Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access
You can use ImageView below two properties to show image based on your requirement :
android:adjustViewBounds : Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.
android:scaleType :Controls how the image should be resized or moved to match the size of this ImageView
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/ic_launcher"/>
Above two properties can be use either xml or java code.
As you need to decide at run time need to show image into full screen or not so will apply above two properties at java code as below :
public class MainActivity extends Activity {
ImageView imageView;
boolean isImageFitToScreen;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(isImageFitToScreen) {
isImageFitToScreen=false;
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
imageView.setAdjustViewBounds(true);
}else{
isImageFitToScreen=true;
imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
}
}
});
}
}
You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.
req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))