Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
You could do this, where td
is your series of timedeltas. The division converts the nanosecond deltas into day deltas, and the conversion to int drops to whole days.
import numpy as np
(td / np.timedelta64(1, 'D')).astype(int)
Both prior answers are definitely good solutions. If you're amenable to a library, I like moment.js - it does a lot more than just getting/formatting the date.
public static boolean BFS(ListNode n, int x){
if(n==null){
return false;
}
Queue<ListNode<Integer>> q = new Queue<ListNode<Integer>>();
ListNode<Integer> tmp = new ListNode<Integer>();
q.enqueue(n);
tmp = q.dequeue();
if(tmp.val == x){
return true;
}
while(tmp != null){
for(ListNode<Integer> child: n.getChildren()){
if(child.val == x){
return true;
}
q.enqueue(child);
}
tmp = q.dequeue();
}
return false;
}
First we can make use of git stash list to get all stash items:
$git stash list
stash@{0}: WIP on ...
stash@{1}: WIP on ....
stash@{2}: WIP on ...
Then we can make use of git stash show stash@{N}
to check the files under a specific stash N
. If we fire it then we may get:
$ git stash show stash@{2}
fatal: ambiguous argument 'stash@2': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'
The reason for this may be that the shell is eating up curly braces and git sees stash@2
and not stash@{2}
. And to fix this we need to make use of single quotes for braces as:
git stash show stash@'{2'}
com/java/myproject/my-xml-impl.xml | 16 ++++++++--------
com/java/myproject/MyJavaClass.java | 16 ++++++++--------
etc.
Router
Route::get('search/{id}', ['as' => 'search', 'uses' => 'SearchController@search']);
Controller
class SearchController extends BaseController {
public function search(Request $request){
$id= $request->id ; // or any params
...
}
}
In case if someone interests to pass data to dialog:
app.controller('ModalCtrl', function($scope, $modal) {
$scope.name = 'theNameHasBeenPassed';
$scope.showModal = function() {
$scope.opts = {
backdrop: true,
backdropClick: true,
dialogFade: false,
keyboard: true,
templateUrl : 'modalContent.html',
controller : ModalInstanceCtrl,
resolve: {} // empty storage
};
$scope.opts.resolve.item = function() {
return angular.copy(
{name: $scope.name}
); // pass name to resolve storage
}
var modalInstance = $modal.open($scope.opts);
modalInstance.result.then(function(){
//on ok button press
},function(){
//on cancel button press
console.log("Modal Closed");
});
};
})
var ModalInstanceCtrl = function($scope, $modalInstance, $modal, item) {
$scope.item = item;
$scope.ok = function () {
$modalInstance.close();
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
Demo Plunker
This message digital envelope routines: EVP_DecryptFInal_ex: bad decrypt
can also occur when you encrypt and decrypt with an incompatible versions of openssl.
The issue I was having was that I was encrypting on Windows which had version 1.1.0 and then decrypting on a generic Linux system which had 1.0.2g.
It is not a very helpful error message!
A possible solution from @AndrewSavinykh that worked for many (see the comments):
Default digest has changed between those versions from md5 to sha256. One can specify the default digest on the command line as
-md sha256
or-md md5
respectively
A ListView
let you define a set of views
for it and gives you a native way (WPF
binding
support) to control the display of ListView
by using defined views
.
Example:
XAML
<ListView ItemsSource="{Binding list}" Name="listv" MouseEnter="listv_MouseEnter" MouseLeave="listv_MouseLeave">
<ListView.Resources>
<GridView x:Key="one">
<GridViewColumn Header="ID" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding id}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
<GridView x:Key="two">
<GridViewColumn Header="Name" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.Resources>
<ListView.Style>
<Style TargetType="ListView">
<Style.Triggers>
<DataTrigger Binding="{Binding ViewType}" Value="1">
<Setter Property="View" Value="{StaticResource one}" />
</DataTrigger>
</Style.Triggers>
<Setter Property="View" Value="{StaticResource two}" />
</Style>
</ListView.Style>
Code Behind:
private int viewType;
public int ViewType
{
get { return viewType; }
set
{
viewType = value;
UpdateProperty("ViewType");
}
}
private void listv_MouseEnter(object sender, MouseEventArgs e)
{
ViewType = 1;
}
private void listv_MouseLeave(object sender, MouseEventArgs e)
{
ViewType = 2;
}
OUTPUT:
Normal View: View 2 in above XAML
MouseOver View: View 1 in above XAML
If you try to achieve above in a
ListBox
, probably you'll end up writing a lot more code forControlTempalate
/ItemTemplate
ofListBox
.
Try
ALLOWED_HOSTS = ['*']
Less secure if you're not firewalled off or on a public LAN, but it's what I use and it works.
EDIT: Interestingly enough I've been needing to add this to a few of my 1.8 projects even when DEBUG = True
. Very unsure why.
EDIT: This is due to a Django security update as mentioned in my comment.
For Angular version 6+
from @docs
Represents options to configure the router.
interface ExtraOptions {
enableTracing?: boolean
useHash?: boolean
initialNavigation?: InitialNavigation
errorHandler?: ErrorHandler
preloadingStrategy?: any
onSameUrlNavigation?: 'reload' | 'ignore'
scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
anchorScrolling?: 'disabled' | 'enabled'
scrollOffset?: [number, number] | (() => [number, number])
paramsInheritanceStrategy?: 'emptyOnly' | 'always'
malformedUriErrorHandler?: (error: URIError, urlSerializer: UrlSerializer, url: string) => UrlTree
urlUpdateStrategy?: 'deferred' | 'eager'
relativeLinkResolution?: 'legacy' | 'corrected'
}
One can use scrollPositionRestoration?: 'disabled' | 'enabled' | 'top'
in
Example:
RouterModule.forRoot(routes, {
scrollPositionRestoration: 'enabled'|'top'
});
And if one requires to manually control the scrolling, No need to use window.scroll(0,0)
Instead from Angular V6 common package has introduced ViewPortScoller
.
abstract class ViewportScroller {
static ngInjectableDef: defineInjectable({ providedIn: 'root', factory: () => new BrowserViewportScroller(inject(DOCUMENT), window) })
abstract setOffset(offset: [number, number] | (() => [number, number])): void
abstract getScrollPosition(): [number, number]
abstract scrollToPosition(position: [number, number]): void
abstract scrollToAnchor(anchor: string): void
abstract setHistoryScrollRestoration(scrollRestoration: 'auto' | 'manual'): void
}
Usage is pretty Straightforward Example:
import { Router } from '@angular/router';
import { ViewportScroller } from '@angular/common'; //import
export class RouteService {
private applicationInitialRoutes: Routes;
constructor(
private router: Router;
private viewPortScroller: ViewportScroller//inject
)
{
this.router.events.pipe(
filter(event => event instanceof NavigationEnd))
.subscribe(() => this.viewPortScroller.scrollToPosition([0, 0]));
}
Try this out:
grep -i 'killed process' /var/log/messages
For Python 3.x, use input()
. For Python 2.x, use raw_input()
. Don't forget you can add a prompt string in your input()
call to create one less print statement. input("GUESS THAT NUMBER!")
.
You probably want to use a regex like the one described here to check the format. When the form's submitted, run the following test on each field:
var userinput = $(this).val();
var pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
if(!pattern.test(userinput))
{
alert('not a valid e-mail address');
}?
Here is how to use UIVibrancyEffect and UIBlurEffect with UIVisualEffectView
Objective-C:
// Blur effect
UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
[blurEffectView setFrame:self.view.bounds];
[self.view addSubview:blurEffectView];
// Vibrancy effect
UIVibrancyEffect *vibrancyEffect = [UIVibrancyEffect effectForBlurEffect:blurEffect];
UIVisualEffectView *vibrancyEffectView = [[UIVisualEffectView alloc] initWithEffect:vibrancyEffect];
[vibrancyEffectView setFrame:self.view.bounds];
// Label for vibrant text
UILabel *vibrantLabel = [[UILabel alloc] init];
[vibrantLabel setText:@"Vibrant"];
[vibrantLabel setFont:[UIFont systemFontOfSize:72.0f]];
[vibrantLabel sizeToFit];
[vibrantLabel setCenter: self.view.center];
// Add label to the vibrancy view
[[vibrancyEffectView contentView] addSubview:vibrantLabel];
// Add the vibrancy view to the blur view
[[blurEffectView contentView] addSubview:vibrancyEffectView];
Swift 4:
// Blur Effect
let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
let blurEffectView = UIVisualEffectView(effect: blurEffect)
blurEffectView.frame = view.bounds
view.addSubview(blurEffectView)
// Vibrancy Effect
let vibrancyEffect = UIVibrancyEffect(blurEffect: blurEffect)
let vibrancyEffectView = UIVisualEffectView(effect: vibrancyEffect)
vibrancyEffectView.frame = view.bounds
// Label for vibrant text
let vibrantLabel = UILabel()
vibrantLabel.text = "Vibrant"
vibrantLabel.font = UIFont.systemFont(ofSize: 72.0)
vibrantLabel.sizeToFit()
vibrantLabel.center = view.center
// Add label to the vibrancy view
vibrancyEffectView.contentView.addSubview(vibrantLabel)
// Add the vibrancy view to the blur view
blurEffectView.contentView.addSubview(vibrancyEffectView)
I have had a similar problem.
Under "problems" tab I have found an error saying "Error generating final archive: Debug Certificate expired on 2/22/12 1:49 PM
"
So my advice is to look in the problems tab to get some more info.
Bye
"abcdefgh..".IndexOf("d")
returns 3
In general returns first occurrence index, if not present returns -1
EasyPHP is very good :
WAMP or UWAMP are good choices if you need to test with multiples versions of PHP and Apache.
But you can also use multiple versions of PHP with EasyPHP (by downloading the PHP version you need on php.net, and loading this version by editing httpd.conf) :
LoadModule php4_module "${path}/php4/php4apache2_2.dll"
As something of an aside, MAXDOP can apparently be used as a workaround to a potentially nasty bug:
After reading many resources regarding this topic, including StackOverFlow, I find that not all solutions are working properly. Below is our attempt to fix this.
Basically, We take the friendly name of an Enum from a DescriptionAttribute if it exists.
If it does not We use RegEx to determine the words within the Enum name and add spaces.
Next version, we will use another Attribute to flag whether we can/should take the friendly name from a localizable resource file.
Below are the test cases. Please report if you have another test case that do not pass.
public static class EnumHelper
{
public static string ToDescription(Enum value)
{
if (value == null)
{
return string.Empty;
}
if (!Enum.IsDefined(value.GetType(), value))
{
return string.Empty;
}
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
if (fieldInfo != null)
{
DescriptionAttribute[] attributes =
fieldInfo.GetCustomAttributes(typeof (DescriptionAttribute), false) as DescriptionAttribute[];
if (attributes != null && attributes.Length > 0)
{
return attributes[0].Description;
}
}
return StringHelper.ToFriendlyName(value.ToString());
}
}
public static class StringHelper
{
public static bool IsNullOrWhiteSpace(string value)
{
return value == null || string.IsNullOrEmpty(value.Trim());
}
public static string ToFriendlyName(string value)
{
if (value == null) return string.Empty;
if (value.Trim().Length == 0) return string.Empty;
string result = value;
result = string.Concat(result.Substring(0, 1).ToUpperInvariant(), result.Substring(1, result.Length - 1));
const string pattern = @"([A-Z]+(?![a-z])|\d+|[A-Z][a-z]+|(?![A-Z])[a-z]+)+";
List<string> words = new List<string>();
Match match = Regex.Match(result, pattern);
if (match.Success)
{
Group group = match.Groups[1];
foreach (Capture capture in group.Captures)
{
words.Add(capture.Value);
}
}
return string.Join(" ", words.ToArray());
}
}
[TestMethod]
public void TestFriendlyName()
{
string[][] cases =
{
new string[] {null, string.Empty},
new string[] {string.Empty, string.Empty},
new string[] {" ", string.Empty},
new string[] {"A", "A"},
new string[] {"z", "Z"},
new string[] {"Pascal", "Pascal"},
new string[] {"camel", "Camel"},
new string[] {"PascalCase", "Pascal Case"},
new string[] {"ABCPascal", "ABC Pascal"},
new string[] {"PascalABC", "Pascal ABC"},
new string[] {"Pascal123", "Pascal 123"},
new string[] {"Pascal123ABC", "Pascal 123 ABC"},
new string[] {"PascalABC123", "Pascal ABC 123"},
new string[] {"123Pascal", "123 Pascal"},
new string[] {"123ABCPascal", "123 ABC Pascal"},
new string[] {"ABC123Pascal", "ABC 123 Pascal"},
new string[] {"camelCase", "Camel Case"},
new string[] {"camelABC", "Camel ABC"},
new string[] {"camel123", "Camel 123"},
};
foreach (string[] givens in cases)
{
string input = givens[0];
string expected = givens[1];
string output = StringHelper.ToFriendlyName(input);
Assert.AreEqual(expected, output);
}
}
}
I would argue that there is a better method, by setting the scope of the variable $MyInvocation.MyCommand.Path:
ex> $script:MyInvocation.MyCommand.Name
This method works in all circumstances of invocation:
EX: Somescript.ps1
function printme () {
"In function:"
( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
}
"Main:"
( "MyInvocation.ScriptName: " + [string]($MyInvocation.ScriptName) )
( "script:MyInvocation.MyCommand.Name: " + [string]($script:MyInvocation.MyCommand.Name) )
( "MyInvocation.MyCommand.Name: " + [string]($MyInvocation.MyCommand.Name) )
" "
printme
exit
OUTPUT:
PS> powershell C:\temp\test.ps1
Main:
MyInvocation.ScriptName:
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: test.ps1
In function:
MyInvocation.ScriptName: C:\temp\test.ps1
script:MyInvocation.MyCommand.Name: test.ps1
MyInvocation.MyCommand.Name: printme
Notice how the above accepted answer does NOT return a value when called from Main. Also, note that the above accepted answer returns the full path when the question requested the script name only. The scoped variable works in all places.
Also, if you did want the full path, then you would just call:
$script:MyInvocation.MyCommand.Path
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
Why would you want length in this case?
If you do want to check for length, have the server return a JSON array with key-value pairs like this:
[
{key:value},
{key:value}
]
In JSON, [ and ] represents an array (with a length property), { and } represents a object (without a length property). You can iterate through the members of a object, but you will get functions as well, making a length check of the numbers of members useless except for iterating over them.
The scalar product between (c-a) and (b-a) must be equal to the product of their lengths (this means that the vectors (c-a) and (b-a) are aligned and with the same direction). Moreover, the length of (c-a) must be less than or equal to that of (b-a). Pseudocode:
# epsilon = small constant
def isBetween(a, b, c):
lengthca2 = (c.x - a.x)*(c.x - a.x) + (c.y - a.y)*(c.y - a.y)
lengthba2 = (b.x - a.x)*(b.x - a.x) + (b.y - a.y)*(b.y - a.y)
if lengthca2 > lengthba2: return False
dotproduct = (c.x - a.x)*(b.x - a.x) + (c.y - a.y)*(b.y - a.y)
if dotproduct < 0.0: return False
if abs(dotproduct*dotproduct - lengthca2*lengthba2) > epsilon: return False
return True
Say it like this: struct xyx a;
The point is semantics. In assertTrue, you are asserting that the expression is true. If it is not, then it will display the message and the assertion will fail. In assertFalse, you are asserting that an expression evaluates to false. If it is not, then the message is displayed and the assertion fails.
assertTrue (message, value == false) == assertFalse (message, value);
These are functionally the same, but if you are expecting a value to be false then use assertFalse
. If you are expecting a value to be true, then use assertTrue
.
This library calculates the difference of months, considering all parts of DateTime:
// ----------------------------------------------------------------------
public void DateDiffSample()
{
DateTime date1 = new DateTime( 2009, 11, 8, 7, 13, 59 );
Console.WriteLine( "Date1: {0}", date1 );
// > Date1: 08.11.2009 07:13:59
DateTime date2 = new DateTime( 2011, 3, 20, 19, 55, 28 );
Console.WriteLine( "Date2: {0}", date2 );
// > Date2: 20.03.2011 19:55:28
DateDiff dateDiff = new DateDiff( date1, date2 );
// differences
Console.WriteLine( "DateDiff.Years: {0}", dateDiff.Years );
// > DateDiff.Years: 1
Console.WriteLine( "DateDiff.Quarters: {0}", dateDiff.Quarters );
// > DateDiff.Quarters: 5
Console.WriteLine( "DateDiff.Months: {0}", dateDiff.Months );
// > DateDiff.Months: 16
Console.WriteLine( "DateDiff.Weeks: {0}", dateDiff.Weeks );
// > DateDiff.Weeks: 70
Console.WriteLine( "DateDiff.Days: {0}", dateDiff.Days );
// > DateDiff.Days: 497
Console.WriteLine( "DateDiff.Weekdays: {0}", dateDiff.Weekdays );
// > DateDiff.Weekdays: 71
Console.WriteLine( "DateDiff.Hours: {0}", dateDiff.Hours );
// > DateDiff.Hours: 11940
Console.WriteLine( "DateDiff.Minutes: {0}", dateDiff.Minutes );
// > DateDiff.Minutes: 716441
Console.WriteLine( "DateDiff.Seconds: {0}", dateDiff.Seconds );
// > DateDiff.Seconds: 42986489
// elapsed
Console.WriteLine( "DateDiff.ElapsedYears: {0}", dateDiff.ElapsedYears );
// > DateDiff.ElapsedYears: 1
Console.WriteLine( "DateDiff.ElapsedMonths: {0}", dateDiff.ElapsedMonths );
// > DateDiff.ElapsedMonths: 4
Console.WriteLine( "DateDiff.ElapsedDays: {0}", dateDiff.ElapsedDays );
// > DateDiff.ElapsedDays: 12
Console.WriteLine( "DateDiff.ElapsedHours: {0}", dateDiff.ElapsedHours );
// > DateDiff.ElapsedHours: 12
Console.WriteLine( "DateDiff.ElapsedMinutes: {0}", dateDiff.ElapsedMinutes );
// > DateDiff.ElapsedMinutes: 41
Console.WriteLine( "DateDiff.ElapsedSeconds: {0}", dateDiff.ElapsedSeconds );
// > DateDiff.ElapsedSeconds: 29
} // DateDiffSample
An optional way if you want to use pure Python:
ElementTree is good for most cases, but it can't CData and pretty print.
So, if you need CData and pretty print you should use minidom:
minidom_example.py:
from xml.dom import minidom
doc = minidom.Document()
root = doc.createElement('root')
doc.appendChild(root)
leaf = doc.createElement('leaf')
text = doc.createTextNode('Text element with attributes')
leaf.appendChild(text)
leaf.setAttribute('color', 'white')
root.appendChild(leaf)
leaf_cdata = doc.createElement('leaf_cdata')
cdata = doc.createCDATASection('<em>CData</em> can contain <strong>HTML tags</strong> without encoding')
leaf_cdata.appendChild(cdata)
root.appendChild(leaf_cdata)
branch = doc.createElement('branch')
branch.appendChild(leaf.cloneNode(True))
root.appendChild(branch)
mixed = doc.createElement('mixed')
mixed_leaf = leaf.cloneNode(True)
mixed_leaf.setAttribute('color', 'black')
mixed_leaf.setAttribute('state', 'modified')
mixed.appendChild(mixed_leaf)
mixed_text = doc.createTextNode('Do not use mixed elements if it possible.')
mixed.appendChild(mixed_text)
root.appendChild(mixed)
xml_str = doc.toprettyxml(indent=" ")
with open("minidom_example.xml", "w") as f:
f.write(xml_str)
minidom_example.xml:
<?xml version="1.0" ?>
<root>
<leaf color="white">Text element with attributes</leaf>
<leaf_cdata>
<![CDATA[<em>CData</em> can contain <strong>HTML tags</strong> without encoding]]> </leaf_cdata>
<branch>
<leaf color="white">Text element with attributes</leaf>
</branch>
<mixed>
<leaf color="black" state="modified">Text element with attributes</leaf>
Do not use mixed elements if it possible.
</mixed>
</root>
Try this:
<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<a href="#">About</a>
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<img src="image.png" />
</div>
<div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
<a href="#myModal1" data-toggle="modal">SHARE</a>
</div>
</div>
</div>
First a disclaimer beforehand: the posted code snippets are all basic examples. You'll need to handle trivial IOException
s and RuntimeException
s like NullPointerException
, ArrayIndexOutOfBoundsException
and consorts yourself.
We first need to know at least the URL and the charset. The parameters are optional and depend on the functional requirements.
String url = "http://example.com";
String charset = "UTF-8"; // Or in Java 7 and later, use the constant: java.nio.charset.StandardCharsets.UTF_8.name()
String param1 = "value1";
String param2 = "value2";
// ...
String query = String.format("param1=%s¶m2=%s",
URLEncoder.encode(param1, charset),
URLEncoder.encode(param2, charset));
The query parameters must be in name=value
format and be concatenated by &
. You would normally also URL-encode the query parameters with the specified charset using URLEncoder#encode()
.
The String#format()
is just for convenience. I prefer it when I would need the String concatenation operator +
more than twice.
It's a trivial task. It's the default request method.
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
// ...
Any query string should be concatenated to the URL using ?
. The Accept-Charset
header may hint the server what encoding the parameters are in. If you don't send any query string, then you can leave the Accept-Charset
header away. If you don't need to set any headers, then you can even use the URL#openStream()
shortcut method.
InputStream response = new URL(url).openStream();
// ...
Either way, if the other side is an HttpServlet
, then its doGet()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
For testing purposes, you can print the response body to stdout as below:
try (Scanner scanner = new Scanner(response)) {
String responseBody = scanner.useDelimiter("\\A").next();
System.out.println(responseBody);
}
Setting the URLConnection#setDoOutput()
to true
implicitly sets the request method to POST. The standard HTTP POST as web forms do is of type application/x-www-form-urlencoded
wherein the query string is written to the request body.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
// ...
Note: whenever you'd like to submit a HTML form programmatically, don't forget to take the name=value
pairs of any <input type="hidden">
elements into the query string and of course also the name=value
pair of the <input type="submit">
element which you'd like to "press" programmatically (because that's usually been used in the server side to distinguish if a button was pressed and if so, which one).
You can also cast the obtained URLConnection
to HttpURLConnection
and use its HttpURLConnection#setRequestMethod()
instead. But if you're trying to use the connection for output you still need to set URLConnection#setDoOutput()
to true
.
HttpURLConnection httpConnection = (HttpURLConnection) new URL(url).openConnection();
httpConnection.setRequestMethod("POST");
// ...
Either way, if the other side is an HttpServlet
, then its doPost()
method will be called and the parameters will be available by HttpServletRequest#getParameter()
.
You can fire the HTTP request explicitly with URLConnection#connect()
, but the request will automatically be fired on demand when you want to get any information about the HTTP response, such as the response body using URLConnection#getInputStream()
and so on. The above examples does exactly that, so the connect()
call is in fact superfluous.
You need an HttpURLConnection
here. Cast it first if necessary.
int status = httpConnection.getResponseCode();
for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
System.out.println(header.getKey() + "=" + header.getValue());
}
When the Content-Type
contains a charset
parameter, then the response body is likely text based and we'd like to process the response body with the server-side specified character encoding then.
String contentType = connection.getHeaderField("Content-Type");
String charset = null;
for (String param : contentType.replace(" ", "").split(";")) {
if (param.startsWith("charset=")) {
charset = param.split("=", 2)[1];
break;
}
}
if (charset != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(response, charset))) {
for (String line; (line = reader.readLine()) != null;) {
// ... System.out.println(line) ?
}
}
} else {
// It's likely binary content, use InputStream/OutputStream.
}
The server side session is usually backed by a cookie. Some web forms require that you're logged in and/or are tracked by a session. You can use the CookieHandler
API to maintain cookies. You need to prepare a CookieManager
with a CookiePolicy
of ACCEPT_ALL
before sending all HTTP requests.
// First set the default cookie manager.
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
// All the following subsequent URLConnections will use the same cookie manager.
URLConnection connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
connection = new URL(url).openConnection();
// ...
Note that this is known to not always work properly in all circumstances. If it fails for you, then best is to manually gather and set the cookie headers. You basically need to grab all Set-Cookie
headers from the response of the login or the first GET
request and then pass this through the subsequent requests.
// Gather all cookies on the first request.
URLConnection connection = new URL(url).openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
// ...
// Then use the same cookies on all subsequent requests.
connection = new URL(url).openConnection();
for (String cookie : cookies) {
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
// ...
The split(";", 2)[0]
is there to get rid of cookie attributes which are irrelevant for the server side like expires
, path
, etc. Alternatively, you could also use cookie.substring(0, cookie.indexOf(';'))
instead of split()
.
The HttpURLConnection
will by default buffer the entire request body before actually sending it, regardless of whether you've set a fixed content length yourself using connection.setRequestProperty("Content-Length", contentLength);
. This may cause OutOfMemoryException
s whenever you concurrently send large POST requests (e.g. uploading files). To avoid this, you would like to set the HttpURLConnection#setFixedLengthStreamingMode()
.
httpConnection.setFixedLengthStreamingMode(contentLength);
But if the content length is really not known beforehand, then you can make use of chunked streaming mode by setting the HttpURLConnection#setChunkedStreamingMode()
accordingly. This will set the HTTP Transfer-Encoding
header to chunked
which will force the request body being sent in chunks. The below example will send the body in chunks of 1KB.
httpConnection.setChunkedStreamingMode(1024);
It can happen that a request returns an unexpected response, while it works fine with a real web browser. The server side is probably blocking requests based on the User-Agent
request header. The URLConnection
will by default set it to Java/1.6.0_19
where the last part is obviously the JRE version. You can override this as follows:
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"); // Do as if you're using Chrome 41 on Windows 7.
Use the User-Agent string from a recent browser.
If the HTTP response code is 4nn
(Client Error) or 5nn
(Server Error), then you may want to read the HttpURLConnection#getErrorStream()
to see if the server has sent any useful error information.
InputStream error = ((HttpURLConnection) connection).getErrorStream();
If the HTTP response code is -1, then something went wrong with connection and response handling. The HttpURLConnection
implementation is in older JREs somewhat buggy with keeping connections alive. You may want to turn it off by setting the http.keepAlive
system property to false
. You can do this programmatically in the beginning of your application by:
System.setProperty("http.keepAlive", "false");
You'd normally use multipart/form-data
encoding for mixed POST content (binary and character data). The encoding is in more detail described in RFC2388.
String param = "value";
File textFile = new File("/path/to/file.txt");
File binaryFile = new File("/path/to/file.bin");
String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
String CRLF = "\r\n"; // Line separator required by multipart/form-data.
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
) {
// Send normal param.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
writer.append(CRLF).append(param).append(CRLF).flush();
// Send text file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset!
writer.append(CRLF).flush();
Files.copy(textFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// Send binary file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: binary").append(CRLF);
writer.append(CRLF).flush();
Files.copy(binaryFile.toPath(), output);
output.flush(); // Important before continuing with writer!
writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
}
If the other side is an HttpServlet
, then its doPost()
method will be called and the parts will be available by HttpServletRequest#getPart()
(note, thus not getParameter()
and so on!). The getPart()
method is however relatively new, it's introduced in Servlet 3.0 (Glassfish 3, Tomcat 7, etc). Prior to Servlet 3.0, your best choice is using Apache Commons FileUpload to parse a multipart/form-data
request. Also see this answer for examples of both the FileUpload and the Servelt 3.0 approaches.
Sometimes you need to connect an HTTPS URL, perhaps because you're writing a web scraper. In that case, you may likely face a javax.net.ssl.SSLException: Not trusted server certificate
on some HTTPS sites who doesn't keep their SSL certificates up to date, or a java.security.cert.CertificateException: No subject alternative DNS name matching [hostname] found
or javax.net.ssl.SSLProtocolException: handshake alert: unrecognized_name
on some misconfigured HTTPS sites.
The following one-time-run static
initializer in your web scraper class should make HttpsURLConnection
more lenient as to those HTTPS sites and thus not throw those exceptions anymore.
static {
TrustManager[] trustAllCertificates = new TrustManager[] {
new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null; // Not relevant.
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {
// Do nothing. Just allow them all.
}
}
};
HostnameVerifier trustAllHostnames = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true; // Just allow them all.
}
};
try {
System.setProperty("jsse.enableSNIExtension", "false");
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
}
catch (GeneralSecurityException e) {
throw new ExceptionInInitializerError(e);
}
}
The Apache HttpComponents HttpClient is much more convenient in this all :)
If all you want is parsing and extracting data from HTML, then better use a HTML parser like Jsoup
That's because you missed ELSE.
"Returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part." (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case)
You must use 'gem uninstall gem_name' to uninstall a gem.
Note that if you installed the gem system-wide (ie. sudo bundle install) then you may need to specify the binary directory using the -n option, to ensure binaries belonging to the gem are removed. For example
sudo gem uninstall gem_name -n /usr/lib/ruby/gems/1.9.1/bin
if you are receiving data from a serial port, make sure you are using the right baudrate (and the other configs ) : decoding using (utf-8) but the wrong config will generate the same error
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
to check your serial port config on linux use : stty -F /dev/ttyUSBX -a
It's not firing because the value hasn't "changed". It's the same value. Unfortunately, you can't achieve the desired behaviour using the change
event.
You can handle the blur
event and do whatever processing you need when the user leaves the select box. That way you can run the code you need even if the user selects the same value.
Very late to the party but I found an answer for MVC (5) I disabled the CheckBox and added a HiddenFor BEFORE the checkbox, so when it is posting if finds the Hidden field first and uses that value. This does work.
<div class="form-group">
@Html.LabelFor(model => model.Carrier.Exists, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(model => model.Carrier.Exists)
@Html.CheckBoxFor(model => model.Carrier.Exists, new { @disabled = "disabled" })
@Html.ValidationMessageFor(model => model.Carrier.Exists)
</div>
</div>
Think about what a pinch
event is: two fingers on an element, moving toward or away from each other.
Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:
(ontouchstart
event)
if (e.touches.length === 2) {
scaling = true;
pinchStart(e);
}
(ontouchmove
event)
if (scaling) {
pinchMove(e);
}
(ontouchend
event)
if (scaling) {
pinchEnd(e);
scaling = false;
}
To get the distance between the two fingers, use the hypot
function:
var dist = Math.hypot(
e.touches[0].pageX - e.touches[1].pageX,
e.touches[0].pageY - e.touches[1].pageY);
Probably because of optimizations. Excel 2007 can have a maximum of 16 384 columns and 1 048 576 rows. Strange numbers?
14 bits = 16 384, 20 bits = 1 048 576
14 + 20 = 34 bits = more than one 32 bit register can hold.
But they also need to store the format of the cell (text, number etc) and formatting (colors, borders etc). Assuming they use two 32-bit words (64 bit) they use 34 bits for the cell number and have 30 bits for other things.
Why is that important? In memory they don't need to allocate all the memory needed for the whole spreadsheet but only the memory necessary for your data, and every data is tagged with in what cell it is supposed to be in.
Update 2016:
Found a link to Microsoft's specification for Excel 2013 & 2016
in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:
copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.
since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.
This simple solution worked for me:
<?php
$sq = new SQLite3( 'sqlite3.db' );
$tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type="table"' );
while ( $table = $tables->fetchArray() ) {
$table = current( $table );
$result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );
if ( strpos( $table, 'sqlite' ) !== false )
continue;
printf( "-- %s\n", $table );
while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {
$values = array_map( function( $value ) {
return sprintf( "'%s'", mysql_real_escape_string( $value ) );
}, array_values( $row ) );
printf( "INSERT INTO `%s` VALUES( %s );\n", $table, implode( ', ', $values ) );
}
}
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command specified by string and then terminates
/k Carries out the command specified by string but remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Let's say you have a Dictionary called fooDictionary
fooDictionary.Values.ToList().IndexOf(someValue);
Values.ToList() converts your dictionary values into a List of someValue objects.
IndexOf(someValue) searches your new List looking for the someValue object in question and returns the Index which would match the index of the Key/Value pair in the dictionary.
This method does not care about the dictionary keys, it simply returns the index of the value that you are looking for.
This does not however account for the issue that there may be several matching "someValue" objects.
RecyclerView doesn't provide straightforward interface for drawing dividers of lists. But actually it provides us a much more flexible way to draw dividers. We use RecyclerView.ItemDecoration to decorate RecyclerView's tiles with dividers or anything you want. That is also why it is called ItemDecoration.
As described in Meterial Design Guidelines:
The divider sits within the baseline of the tile.
So if you want to follow the Material Design Guidelines, you don't need extra space to draw the dividers. Just draw them on the tiles. However, you have the right to do whatever you want to do. So I implemented one which gives you the ability to set insets as well as draw on/underneath the tiles.
public class InsetDivider extends RecyclerView.ItemDecoration {
public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;
public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;
private Paint mPaint;
// in pixel
private int mDividerHeight;
// left inset for vertical list, top inset for horizontal list
private int mFirstInset;
// right inset for vertical list, bottom inset for horizontal list
private int mSecondInset;
private int mColor;
private int mOrientation;
// set it to true to draw divider on the tile, or false to draw beside the tile.
// if you set it to false and have inset at the same time, you may see the background of
// the parent of RecyclerView.
private boolean mOverlay;
private InsetDivider() {
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setStyle(Paint.Style.FILL);
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setDividerHeight(int dividerHeight) {
this.mDividerHeight = dividerHeight;
}
public int getFirstInset() {
return mFirstInset;
}
public void setFirstInset(int firstInset) {
this.mFirstInset = firstInset;
}
public int getSecondInset() {
return mSecondInset;
}
public void setSecondInset(int secondInset) {
this.mSecondInset = secondInset;
}
public int getColor() {
return mColor;
}
public void setColor(int color) {
this.mColor = color;
mPaint.setColor(color);
}
public int getOrientation() {
return mOrientation;
}
public void setOrientation(int orientation) {
this.mOrientation = orientation;
}
public boolean getOverlay() {
return mOverlay;
}
public void setOverlay(boolean overlay) {
this.mOverlay = overlay;
}
@Override
public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == VERTICAL_LIST) {
drawVertical(c, parent);
} else {
drawHorizontal(c, parent);
}
}
protected void drawVertical(Canvas c, RecyclerView parent) {
final int left = parent.getPaddingLeft() + mFirstInset;
final int right = parent.getWidth() - parent.getPaddingRight() - mSecondInset;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if (parent.getChildAdapterPosition(child) == (parent.getAdapter().getItemCount() - 1)) {
continue;
}
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
final int bottom;
final int top;
if (mOverlay) {
bottom = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
top = bottom - mDividerHeight;
} else {
top = child.getBottom() + params.bottomMargin + Math.round(ViewCompat.getTranslationY(child));
bottom = top + mDividerHeight;
}
c.drawRect(left, top, right, bottom, mPaint);
}
}
protected void drawHorizontal(Canvas c, RecyclerView parent) {
final int top = parent.getPaddingTop() + mFirstInset;
final int bottom = parent.getHeight() - parent.getPaddingBottom() - mSecondInset;
final int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = parent.getChildAt(i);
if (parent.getChildAdapterPosition(child) == (parent.getAdapter().getItemCount() - 1)) {
continue;
}
final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
.getLayoutParams();
final int right;
final int left;
if (mOverlay) {
right = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
left = right - mDividerHeight;
} else {
left = child.getRight() + params.rightMargin + Math.round(ViewCompat.getTranslationX(child));
right = left + mDividerHeight;
}
c.drawRect(left, top, right, bottom, mPaint);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOverlay) {
super.getItemOffsets(outRect, view, parent, state);
return;
}
if (mOrientation == VERTICAL_LIST) {
outRect.set(0, 0, 0, mDividerHeight);
} else {
outRect.set(0, 0, mDividerHeight, 0);
}
}
/**
* Handy builder for creating {@link InsetDivider} instance.
*/
public static class Builder {
private Context mContext;
private int mDividerHeight;
private int mFirstInset;
private int mSecondInset;
private int mColor;
private int mOrientation;
private boolean mOverlay = true; // set default to true to follow Material Design Guidelines
public Builder(Context context) {
mContext = context;
}
public Builder dividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
return this;
}
public Builder insets(int firstInset, int secondInset) {
mFirstInset = firstInset;
mSecondInset = secondInset;
return this;
}
public Builder color(@ColorInt int color) {
mColor = color;
return this;
}
public Builder orientation(int orientation) {
mOrientation = orientation;
return this;
}
public Builder overlay(boolean overlay) {
mOverlay = overlay;
return this;
}
public InsetDivider build() {
InsetDivider insetDivider = new InsetDivider();
if (mDividerHeight == 0) {
// Set default divider height to 1dp.
insetDivider.setDividerHeight(mContext.getResources().getDimensionPixelSize(R.dimen.divider_height));
} else if (mDividerHeight > 0) {
insetDivider.setDividerHeight(mDividerHeight);
} else {
throw new IllegalArgumentException("Divider's height can't be negative.");
}
insetDivider.setFirstInset(mFirstInset < 0 ? 0 : mFirstInset);
insetDivider.setSecondInset(mSecondInset < 0 ? 0 : mSecondInset);
if (mColor == 0) {
throw new IllegalArgumentException("Don't forget to set color");
} else {
insetDivider.setColor(mColor);
}
if (mOrientation != InsetDivider.HORIZONTAL_LIST && mOrientation != InsetDivider.VERTICAL_LIST) {
throw new IllegalArgumentException("Invalid orientation");
} else {
insetDivider.setOrientation(mOrientation);
}
insetDivider.setOverlay(mOverlay);
return insetDivider;
}
}
}
And you can use it like this:
ItemDecoration divider = new InsetDivider.Builder(this)
.orientation(InsetDivider.VERTICAL_LIST)
.dividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height))
.color(getResources().getColor(R.color.colorAccent))
.insets(getResources().getDimensionPixelSize(R.dimen.divider_inset), 0)
.overlay(true)
.build();
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.addItemDecoration(divider);
I also wrote a demo App about how to implement ItemDecoration and how to use them. You can check out my GitHub repo Dividers-For-RecyclerView. There are three implementations in it:
Empty array for empty collections and null
for everything else.
You can mark folders or files so that they don't have read access (any of the main web servers support this). This allows you to store them on the server without any level of access to the outside world. You may want to do this if you have a service that generates images for someone else to download later, or if you use your web account for FTP access, but don't want anyone to view the files. (i.e. upload a .bak file to the server for someone else to FTP down again).
However, as others have said, getting into copyright areas where people can view the image or video but not save them locally is not fully possibly, although there are tools to discourage illegal usage.
Since ES7 theres a better way to await a loop:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
When the engine reaches the await
part, it sets a timeout and halts the execution of the async function
. Then when the timeout completes, execution continues at that point. That's quite useful as you can delay (1) nested loops, (2) conditionally, (3) nested functions:
async function task(i) { // 3
await timer(1000);
console.log(`Task ${i} done!`);
}
async function main() {
for(let i = 0; i < 100; i+= 10) {
for(let j = 0; j < 10; j++) { // 1
if(j % 2) { // 2
await task(i + j);
}
}
}
}
main();
function timer(ms) { return new Promise(res => setTimeout(res, ms)); }
_x000D_
While ES7 is now supported by NodeJS and modern browsers, you might want to transpile it with BabelJS so that it runs everywhere.
If john were an optional var (declared thusly)
var john: Person?
then it would be possible for john to have no value (in ObjC parlance, nil value)
The exclamation point basically tells the compiler "I know this has a value, you don't need to test for it". If you didn't want to use it, you could conditionally test for it:
if let otherPerson = john {
otherPerson.apartment = number73
}
The interior of this will only evaluate if john has a value.
You will need an intermediate class which will buffer between. Each time InputStream.read(byte[]...)
is called, the buffering class will fill the passed in byte array with the next chunk passed in from OutputStream.write(byte[]...)
. Since the sizes of the chunks may not be the same, the adapter class will need to store a certain amount until it has enough to fill the read buffer and/or be able to store up any buffer overflow.
This article has a nice breakdown of a few different approaches to this problem:
http://blog.ostermiller.org/convert-java-outputstream-inputstream
If you have a rooted device, you can use a Magisk Module to move User Certs to System so it will be Trusted Certificate
If you want to print all the columns in your select clause you can go with the autoprint command.
CREATE OR REPLACE PROCEDURE sps_detail_dtest(v_refcur OUT sys_refcursor)
AS
BEGIN
OPEN v_refcur FOR 'select * from dummy_table';
END;
SET autoprint on;
--calling the procedure
VAR vcur refcursor;
DECLARE
BEGIN
sps_detail_dtest(vrefcur=>:vcur);
END;
Hope this gives you an alternate solution
None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):
var clicker = null;
$('a').click(function(e){
clicker=$(this); // capture the clicked dom object
/* ... do something ... */
e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.
You can use pandas.Dataframe.isin
.
pandas.Dateframe.isin
will return boolean values depending on whether each element is inside the list a
or not. You then invert this with the ~
to convert True
to False
and vice versa.
import pandas as pd
a = ['2015-01-01' , '2015-02-01']
df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})
print(df)
# date
#0 2015-01-01
#1 2015-02-01
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
df = df[~df['date'].isin(a)]
print(df)
# date
#2 2015-03-01
#3 2015-04-01
#4 2015-05-01
#5 2015-06-01
It's legit and very handy!
Try this:
<script id="hello" type="text/template">
Hello world
</script>
<script>
alert($('#hello').html());
</script>
Several Javascript templating libraries use this technique. Handlebars.js is a good example.
The rvest
along with xml2
is another popular package for parsing html web pages.
library(rvest)
theurl <- "http://en.wikipedia.org/wiki/Brazil_national_football_team"
file<-read_html(theurl)
tables<-html_nodes(file, "table")
table1 <- html_table(tables[4], fill = TRUE)
The syntax is easier to use than the xml
package and for most web pages the package provides all of the options ones needs.
If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.
Source Code for Remote for VLC - VLC Remote
Using one of the subsets method in this question
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 0),
new KeyValuePair<string, int>("C", 0),
new KeyValuePair<string, int>("D", 2),
new KeyValuePair<string, int>("E", 8),
};
int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);
EDIT
a full console application:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var list = new List<KeyValuePair<string, int>>() {
new KeyValuePair<string, int>("A", 1),
new KeyValuePair<string, int>("B", 2),
new KeyValuePair<string, int>("C", 3),
new KeyValuePair<string, int>("D", 4),
new KeyValuePair<string, int>("E", 5),
new KeyValuePair<string, int>("F", 6),
};
int input = 12;
var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);
foreach (var res in alternatives)
{
Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
}
Console.WriteLine("END");
Console.ReadLine();
}
}
public static class Extenions
{
public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
{
List<T> list = enumerable.ToList();
ulong upper = (ulong)1 << list.Count;
for (ulong i = 0; i < upper; i++)
{
List<T> l = new List<T>(list.Count);
for (int j = 0; j < sizeof(ulong) * 8; j++)
{
if (((ulong)1 << j) >= upper) break;
if (((i >> j) & 1) == 1)
{
l.Add(list[j]);
}
}
yield return l;
}
}
}
}
It's generally considered a bad idea to ignore exceptions. Usually, if it's appropriate, you want to either notify the user of the issue (if they would care) or at the very least, log the exception, or print the stack trace to the console.
However, if that's truly not necessary (you're the one making the decision) then no, there's no other way to ignore an exception that forces you to catch it. The only revision, in that case, that I would suggest is explicitly listing the the class of the Exceptions you're ignoring, and some comment as to why you're ignoring them, rather than simply ignoring any exception, as you've done in your example.
Lazy loading images by attaching listener to scroll events or by making use of setInterval is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.
Use Lozad.js (just 569 bytes with no dependencies), which uses IntersectionObserver to lazy load images performantly.
What worked for me was excluding the hamcrest group from the junit test compile.
Here is the code from my build.gradle:
testCompile ('junit:junit:4.11') {
exclude group: 'org.hamcrest'
}
If you're running IntelliJ you may need to run gradle cleanIdea idea clean build
to detect the dependencies again.
According to the swift docs global variables are declared in file scope.
Global variables are variables that are defined outside of any function, method, closure, or type context
Just create a swift file (E.g: Constnats.swift) and declare your constants there:
// Constants.swift
let SOME_NOTIF = "aaaaNotification"
and call it from anywhere in your project without the need to mention struct,enum or class name.
// MyViewController.swift
NotificationCenter.default.post(name: SOME_NOTIF, object: nil)
I think this is much better for code readability.
You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html
Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.
A more recent solution is using the The PerformanceNavigation interface:
if(!!window.performance && window.performance.navigation.type === 2)
{
console.log('Reloading');
window.location.reload();
}
Where the value 2 means "The page was accessed by navigating into the history".
View browser support here: http://caniuse.com/#search=Navigation%20Timing%20API
A list
keeps order, dict
and set
don't: when you care about order, therefore, you must use list
(if your choice of containers is limited to these three, of course;-).
dict
associates with each key a value, while list
and set
just contain values: very different use cases, obviously.
set
requires items to be hashable, list
doesn't: if you have non-hashable items, therefore, you cannot use set
and must instead use list
.
set
forbids duplicates, list
does not: also a crucial distinction. (A "multiset", which maps duplicates into a different count for items present more than once, can be found in collections.Counter
-- you could build one as a dict
, if for some weird reason you couldn't import collections
, or, in pre-2.7 Python as a collections.defaultdict(int)
, using the items as keys and the associated value as the count).
Checking for membership of a value in a set
(or dict
, for keys) is blazingly fast (taking about a constant, short time), while in a list it takes time proportional to the list's length in the average and worst cases. So, if you have hashable items, don't care either way about order or duplicates, and want speedy membership checking, set
is better than list
.
Based on your edit and comments.. would this be what you're after?
byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));
This is how I did it:
curl -v \
--key ./admin-key.pem \
--cert ./admin.pem \
https://xxxx/api/v1/
I found a reason why this would happen. The user had the appropriate permissions, but the stored procedure included a TRUNCATE
statement:
TRUNCATE TableName
Since TRUNCATE
deletes items without logging, you (apparently) need elevated permissions to execute a stored procedure that contains it. We changed the statement to:
DELETE FROM TableName
...and the error went away!
For that you just need write to some lines
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.setDrawerIndicatorEnabled(true);
toggle.syncState();
toggle.setDrawerIndicatorEnabled(true); if this is false make it true or remove this line
Just a note for people who may have found this later (and want java way of achieving this); FirefoxOptions
is also capable of enabling the headless mode:
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setHeadless(true);
Take a look at Datejs for all those petty date related issues.. You could solve this by parseDate function too
The best approach in this case is to use extension_loaded() or function_exists() they are equally as fast.
You can see evidence here:
https://github.com/dragoonis/ppi-framework/blob/master/Cache/Memcached.php#L140
Bear in mind that some PHP extensions such as APC have php.ini settings that can disable them even though the extension may be loaded. Here is an example of how to check against that also:
https://github.com/dragoonis/ppi-framework/blob/master/Cache/Apc.php#L79
Hope this helps.
I was having a problem where setting element.Visible = true in my code behind wasn't having any effect on the actual screen. The solution for me was to wrap the area of my page where I wanted to show the div in an ASP UpdatePanel, which is used to cause partial screen updates.
http://msdn.microsoft.com/en-us/library/bb399001.aspx
Having the element runat=server gave me access to it from the codebehind, and placing it in the UpdatePanel let it actually be updated on the screen.
If all you are trying to do is get the value out of the hashmap itself, you can do something like the following:
for (Object key : map.keySet()) {
Object value = map.get(key);
//TODO: this
}
Or, you can iterate over the entries of a map, if that is what you are interested in:
for (Map.Entry<Object, Object> entry : map.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
//TODO: other cool stuff
}
As a community, we might be able to give you better/more appropriate answers if we had some idea why you needed the indexes or what you thought the indexes could do for you.
I know this post is old, sorry for that.
You can also type 10x
for cols and x2
for rows, if you want to have only one attribute.
[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->
In my case there was a static variable which was not initialized. When I initialized it, the error was removed. I don't know the logic behind it but worked for me. I know its a little late but other people with similar problem might get some help.
As @DSM points out, you can do this more directly using the vectorised string methods:
df['Date'].str[-4:].astype(int)
Or using extract (assuming there is only one set of digits of length 4 somewhere in each string):
df['Date'].str.extract('(?P<year>\d{4})').astype(int)
An alternative slightly more flexible way, might be to use apply
(or equivalently map
) to do this:
df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
# converts the last 4 characters of the string to an integer
The lambda function, is taking the input from the Date
and converting it to a year.
You could (and perhaps should) write this more verbosely as:
def convert_to_year(date_in_some_format):
date_as_string = str(date_in_some_format) # cast to string
year_as_string = date_in_some_format[-4:] # last four characters
return int(year_as_string)
df['Date'] = df['Date'].apply(convert_to_year)
Perhaps 'Year' is a better name for this column...
Form data (for GET or POST) is usually encoded as application/x-www-form-urlencoded
: this specifies +
for spaces.
URLs are encoded as RFC 1738 which specifies %20
.
In theory I think you should have %20 before the ?
and + after:
example.com/foo%20bar?foo+bar
Some others not mentioned here -
Mono Cecil: With Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.
Kaliro: This is a tool for exploring the content of applications built using the Microsoft.Net framework.
Dotnet IL Editor (DILE): Dotnet IL Editor (DILE) allows disassembling and debugging .NET 1.0/1.1/2.0/3.0/3.5 applications without source code or .pdb files. It can debug even itself or the assemblies of the .NET Framework on IL level.
Common Compiler Infrastructure: Microsoft Research Common Compiler Infrastructure (CCI) is a set of libraries and an application programming interface (API) that supports some of the functionality that is common to compilers and related programming tools. CCI is used primarily by applications that create, modify or analyze .NET portable executable (PE) and debug (PDB) files.
I think your question is, "why am I getting one more line than there is in the file?"
Imagine a file:
line 1
line 2
line 3
The file may be represented in ASCII like this:
line 1\nline 2\nline 3\n
(Where \n
is byte 0x10
.)
Now let's see what happens before and after each getline
call:
Before 1: line 1\nline 2\nline 3\n
Stream: ^
After 1: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Before 2: line 1\nline 2\nline 3\n
Stream: ^
After 2: line 1\nline 2\nline 3\n
Stream: ^
Now, you'd think the stream would mark eof
to indicate the end of the file, right? Nope! This is because getline
sets eof
if the end-of-file marker is reached "during it's operation". Because getline
terminates when it reaches \n
, the end-of-file marker isn't read, and eof
isn't flagged. Thus, myfile.eof()
returns false, and the loop goes through another iteration:
Before 3: line 1\nline 2\nline 3\n
Stream: ^
After 3: line 1\nline 2\nline 3\n
Stream: ^ EOF
How do you fix this? Instead of checking for eof()
, see if .peek()
returns EOF
:
while(myfile.peek() != EOF){
getline ...
You can also check the return value of getline
(implicitly casting to bool):
while(getline(myfile,line)){
cout<< ...
This is my way to do it!
public static byte[] concatByteArrays(byte[]... inputs) {
int i = inputs.length - 1, len = 0;
for (; i >= 0; i--) {
len += inputs[i].length;
}
byte[] r = new byte[len];
for (i = inputs.length - 1; i >= 0; i--) {
System.arraycopy(inputs[i], 0, r, len -= inputs[i].length, inputs[i].length);
}
return r;
}
Features:
...
) to be called with any number of byte[].System.arraycopy()
that is implemented with machine specific native code, to ensure high speed operation.int
variables by reusing the i
and len
variables.Keep in mind:
The better way to do this, is by copy the @Jonathan code. The issue comes from the native variable arrays, because Java create new variables when this data type is passed to another function.
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
In Apache commons lang, DateUtils class we have a method called parseDate. We can use this for parsing the date.
Also another library Joda-time also have the method to parse the date.
In my case Xcode was not accessing certificates from the keychain, I followed these steps:
Try Microsoft's NEWT, it worked perfect for me. It supplies customized latency, packet drop techniques and more :)
http://blog.mrpol.nl/2010/01/14/network-emulator-toolkit/
Update 1:
Here is a good video tutorial for NEWT - Network Emulator For Windows Toolkit Tutorial (Credits to Jimmery)
Try
SELECT EXTRACTVALUE(xmltype(testclob), '/DCResponse/ContextData/Field[@key="Decision"]')
FROM traptabclob;
Here is a sqlfiddle demo
Just define the variable as a variant, and make them equal:
Dim DirArray As Variant
DirArray = Range("a1:a5").Value
No need for the Array command.
When you use a blade echo {{ $data }}
it will automatically escape the output. It can only escape strings. In your data $data->ac
is an array and $data
is an object, neither of which can be echoed as is. You need to be more specific of how the data should be outputted. What exactly that looks like entirely depends on what you're trying to accomplish. For example to display the link you would need to do {{ $data->ac[0][0]['url'] }}
(not sure why you have two nested arrays but I'm just following your data structure).
@foreach($data->ac['0'] as $link)
<a href="{{ $link['url'] }}">This is a link</a>
@endforeach
Use:
set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );
Or possibly:
SET TIMING ON;
-- do stuff
SET TIMING OFF;
...to get the hundredths of seconds that elapsed.
In either case, time elapsed can be impacted by server load/etc.
Reference:
http://phpjs.org/functions/ucwords:569 has a good example
function ucwords (str) {
return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
return $1.toUpperCase();
});
}
(omitted function comment from source for brevity. please see linked source for details)
EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)
Try using this code:
var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
year: 'numeric', month: 'numeric', day: 'numeric',
};
var result = date.toLocaleDateString('en', options); // 10/29/2013
Multiline strings are a current part of JavaScript (since ES6) and are supported in node.js v4.0.0 and newer.
var text = `Lorem ipsum dolor
sit amet, consectetur
adipisicing
elit. `;
console.log(text);
You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.
ArrayList
and Vector
both implements List interface and maintains insertion order.But there are many differences between ArrayList
and Vector
classes...
ArrayList
is not synchronized.ArrayList
increments 50% of current array size if number of element exceeds from its capacity.ArrayList
is not a legacy class, it is introduced in JDK 1.2.ArrayList
is fast because it is non-synchronized.ArrayList
uses Iterator interface to traverse the elements.Vector -
Vector
is synchronized.Vector
increments 100% means doubles the array size if total number of element exceeds than its capacity.Vector
is a legacy class.
Vector
is slow because it is synchronized i.e. in multithreading environment, it will hold the other threads in runnable or non-runnable state until current thread releases the lock of object.
Vector
uses Enumeration interface to traverse the elements. But it can use Iterator also.
See Also : https://www.javatpoint.com/difference-between-arraylist-and-vector
It's quite feasible to generate labeled icons server-side, if you have some programming skills. You'll need the GD library at the server, in addition to PHP. Been working well for me for several years now, but admittedly tricky to get the icon images in synch.
I do that via AJAX by sending the few parameters to define the blank icon and the text and color as well as bgcolor to be applied. Here's my PHP:
header("Content-type: image/png");
//$img_url = "./icons/gen_icon5.php?blank=7&text=BB";
function do_icon ($icon, $text, $color) {
$im = imagecreatefrompng($icon);
imageAlphaBlending($im, true);
imageSaveAlpha($im, true);
$len = strlen($text);
$p1 = ($len <= 2)? 1:2 ;
$p2 = ($len <= 2)? 3:2 ;
$px = (imagesx($im) - 7 * $len) / 2 + $p1;
$font = 'arial.ttf';
$contrast = ($color)? imagecolorallocate($im, 255, 255, 255): imagecolorallocate($im, 0, 0, 0); // white on dark?
imagestring($im, $p2, $px, 3, $text, $contrast); // imagestring ( $image, $font, $x, $y, $string, $color)
imagepng($im);
imagedestroy($im);
}
$icons = array("black.png", "blue.png", "green.png", "red.png", "white.png", "yellow.png", "gray.png", "lt_blue.png", "orange.png"); // 1/9/09
$light = array( TRUE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE); // white text?
$the_icon = $icons[$_GET['blank']]; // 0 thru 8 (note: total 9)
$the_text = substr($_GET['text'], 0, 3); // enforce 2-char limit
do_icon ($the_icon, $the_text,$light[$_GET['blank']] );
It's invoked client-side via something like the following: var image_file = "./our_icons/gen_icon.php?blank=" + escape(icons[color]) + "&text=" + iconStr;
^[0-9]{1,2}[:.,-]?po$
Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.
Resolved - to the original ask:
I've seen this before. Easiest way to fix (don't need all those data conversion steps as ALL of the meta data is available from the source connection):
Delete the OLE DB Source & OLE DB Destinations Make sure Delayed Validation is FALSE (you can set it to True later) Recreate the OLE DB Source with your query, etc. Verify in the Advanced Editor that all of the output data column types are correct Recreate your OLE DB Destination, map, create new table (or remap to existing) and you'll see that SSIS got all the data types correct (same as source).
So much easier that the stuff above.
Since you're using PHP, you will probably need to use the CURLOPT_PORT
option, like so:
curl_setopt($ch, CURLOPT_PORT, 11740);
Bear in mind, you may face problems with SELinux:
The method I use is to import the ch.qos.logback modules and then type-cast the slf4j Logger instance to a ch.qos.logback.classic.Logger. This instance includes a setLevel() method.
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
Logger levelSet = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
// Now you can set the desired logging-level
levelSet.setLevel( Level.OFF );
To find out the possible Logging-levels, you can explode the ch.qos.logback class to see all the possible values for Level:
prompt$ javap -cp logback-classic-1.2.3.jar ch.qos.logback.classic.Level
The results are the following:
{
// ...skipping
public static final ch.qos.logback.classic.Level OFF;
public static final ch.qos.logback.classic.Level ERROR;
public static final ch.qos.logback.classic.Level WARN;
public static final ch.qos.logback.classic.Level INFO;
public static final ch.qos.logback.classic.Level DEBUG;
public static final ch.qos.logback.classic.Level TRACE;
public static final ch.qos.logback.classic.Level ALL;
}
My async function
const getAllRedis = async (key) => {
let obj = [];
await client.hgetall(key, (err, object) => {
console.log(object);
_.map(object, (ob)=>{
obj.push(JSON.parse(ob));
})
return obj;
// res.send(obj);
});
}
from __future__ import with_statement
with open('file.txt','r+') as f:
counter = str(int(f.read().strip())+1)
f.seek(0)
f.write(counter)
Try
$(document).ready(
instead of
$('document').ready(
or you can use a shorthand form
$(function(){
});
Try this one for current selection:
Sub A_SelectAllMakeTable2()
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
or equivalent of your macro (for Ctrl+Shift+End range selection):
Sub A_SelectAllMakeTable()
Dim tbl As ListObject
Dim rng As Range
Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End Sub
If you are using JQuery Google map plug-in then below code will work for you -
var markers = $('#map_canvas').gmap('get','markers');
None of the answers satisfied me, several don't work or are just shallow clones, answers from @clint-harris and using JSON.parse/stringify are good but quite slow. I found a module that does deep cloning fast: https://github.com/AlexeyKupershtokh/node-v8-clone
For Unix based systems (Linux, Mac OS X, Solaris), you can use the getrusage()
function from the standard library module resource
. The resulting object has the attribute ru_maxrss
, which gives the peak memory usage for the calling process:
>>> resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
2656 # peak memory usage (kilobytes on Linux, bytes on OS X)
The Python docs don't make note of the units. Refer to your specific system's man getrusage.2
page to check the unit for the value. On Ubuntu 18.04, the unit is noted as kilobytes. On Mac OS X, it's bytes.
The getrusage()
function can also be given resource.RUSAGE_CHILDREN
to get the usage for child processes, and (on some systems) resource.RUSAGE_BOTH
for total (self and child) process usage.
If you care only about Linux, you can alternatively read the /proc/self/status
or /proc/self/statm
file as described in other answers for this question and this one too.
Private Sub cmdInsertRow_Click()
Dim lRow As Long
Dim lRsp As Long
On Error Resume Next
lRow = Selection.Row()
lRsp = MsgBox("Insert New row above " & lRow & "?", _
vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Rows(lRow).Select
Selection.Copy
Rows(lRow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
'Paste formulas and conditional formatting in new row created
Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
End Sub
This is what I use. Tested and working,
Thanks,
The linefeed character \n
is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n
instead, then it'll both see the line-break with only \n
and \r\n
, I've never had any problems using it.
Also, you should look into using a StringBuilder
instead of concatenating the String
in the while-loop at BookCatalog.toString()
, it is a lot more effective. For instance:
public String toString() {
BookNode current = front;
StringBuilder sb = new StringBuilder();
while (current!=null){
sb.append(current.getData().toString()+"\r\n ");
current = current.getNext();
}
return sb.toString();
}
I found Visual Binary Diff was what I was looking for, available on:
Ubuntu:
sudo apt install vbindiff
Arch Linux:
sudo pacman -S vbindiff
Mac OS X via MacPorts:
port install vbindiff
Mac OS X via Homebrew:
brew install vbindiff
This issue maybe due to common user do not have privilege to access packages py file.
1. root user can run 'pip list'
2. other common user cannot run 'pip list'
[~]$ pip list
Traceback (most recent call last):
File "/usr/bin/pip", line 7, in <module>
from pip._internal import main
ImportError: No module named pip._internal
Check pip py file privilege.
[root@]# ll /usr/lib/python2.7/site-packages/pip/
?? 24
-rw------- 1 root root 24 6? 7 16:57 __init__.py
-rw------- 1 root root 163 6? 7 16:57 __init__.pyc
-rw------- 1 root root 629 6? 7 16:57 __main__.py
-rw------- 1 root root 510 6? 7 16:57 __main__.pyc
drwx------ 8 root root 4096 6? 7 16:57 _internal
drwx------ 18 root root 4096 6? 7 16:57 _vendor
solution : root user login and run
chmod -R 755 /usr/lib/python2.7
fix this issue.
AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.
Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "pluggable look and feel" that can make it look more or less like how the native windows and widgets would look).
These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:
AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those toolkits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.
Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.
Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.
Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.
I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV
, then opened the .CSV
in Excel. This has its own problems, but I've found this the quickest method.
First, convert the .CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
Then, export it to Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
You'll have to install some stuff, too...
Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel
It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.
In case I forgot anything, here's my 'using' statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
Try Linq:
Result = string.Join("", input.ToCharArray().Where(x=> ((int)x) < 127));
This will filter out all non ascii characters. Now if you want an equivalent, try the following:
Result = string.Join("", System.Text.Encoding.ASCII.GetChars(System.Text.Encoding.ASCII.GetBytes(input.ToCharArray())));
I think you had not yet import the private key as the message error said, To import public/private key from gnupg:
gpg --import mypub_key
gpg --allow-secret-key-import --import myprv_key
Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:
let value = GoalProgressMeasurements.Not_Measured;
console.log(GoalProgressMeasurements[value]);
// => Not_Measured
Based on that you can use the following code:
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
let map: {id: number; name: string}[] = [];
for(var n in GoalProgressMeasurements) {
if (typeof GoalProgressMeasurements[n] === 'number') {
map.push({id: <any>GoalProgressMeasurements[n], name: n});
}
}
console.log(map);
Reference: https://www.typescriptlang.org/docs/handbook/enums.html
You do not need to use an anonymous function with setTimeout
. You can do something like this:
setTimeout(doSomething, 3000);
function doSomething() {
//do whatever you want here
}
Jeremy Ruten's idea of using a symlink triggered a thought that hasn't crossed any other answer. Use:
CDPATH=:$HOME/projects
The leading colon is important; it means that if there is a directory 'dir' in the current directory, then 'cd dir
' will change to that, rather than hopping off somewhere else. With the value set as shown, you can do:
cd java
and, if there is no sub-directory called java in the current directory, then it will take you directly to $HOME/projects/java - no aliases, no scripts, no dubious execs or dot commands.
My $HOME is /Users/jleffler; my $CDPATH is:
:/Users/jleffler:/Users/jleffler/mail:/Users/jleffler/src:/Users/jleffler/src/perl:/Users/jleffler/src/sqltools:/Users/jleffler/lib:/Users/jleffler/doc:/Users/jleffler/work
In Asp.net Core 3+ Vesrion
Controller: If wants to return anything related to IActionResult & Data also, go for Controllercontroller
ApiController: Used as attribute/notation in API controller. That inherits ControllerBase Class
ControllerBase: If wants to return data only go for ControllerBase class
Another way using regular expressions
int length = text.replaceAll("[^ ]", "").length();
SQL Server Express editions are limited in some ways - one way is that they don't have the SQL Agent that allows you to schedule jobs.
There are a few third-party extensions that provide that capability - check out e.g.:
You could try attaching handlers to various events of BitmapImage:
They might tell you a little about what's going on, as far as the image is concerned.
I had a similar issue and this is how I was able to address it.
Step 1 - Loaded the data from hive table into another table as follows
DROP TABLE IF EXISTS TestHiveTableCSV; CREATE TABLE TestHiveTableCSV ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' AS SELECT Column List FROM TestHiveTable;
Step 2 - Copied the blob from hive warehouse to the new location with appropriate extension
Start-AzureStorageBlobCopy
-DestContext $destContext
-SrcContainer "Source Container"-SrcBlob "hive/warehouse/TestHiveTableCSV/000000_0"
-DestContainer "Destination Container" ` -DestBlob "CSV/TestHiveTable.csv"
Hope this helps!
Best Regards, Dattatrey Sindol (Datta) http://dattatreysindol.com
METHOD 1 : Either you can directly convert to bitmap like this
Bitmap myLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.my_drawable);
METHOD 2 : You can even convert the resource into the drawable and from that you can get bitmap like this
Bitmap myLogo = ((BitmapDrawable)getResources().getDrawable(R.drawable.logo)).getBitmap();
For API > 22 getDrawable
method moved to the ResourcesCompat
class so for that you do something like this
Bitmap myLogo = ((BitmapDrawable) ResourcesCompat.getDrawable(context.getResources(), R.drawable.logo, null)).getBitmap();
Here you wanna make a pointer to the first element of the array
uint8_t (*matrix_ptr)[20] = l_matrix;
With typedef, this looks cleaner
typedef uint8_t array_of_20_uint8_t[20];
array_of_20_uint8_t *matrix_ptr = l_matrix;
Then you can enjoy life again :)
matrix_ptr[0][1] = ...;
Beware of the pointer/array world in C, much confusion is around this.
Reviewing some of the other answers here, because the comment fields are too short to do there. Multiple alternatives were proposed, but it wasn't shown how they behave. Here is how they do
uint8_t (*matrix_ptr)[][20] = l_matrix;
If you fix the error and add the address-of operator &
like in the following snippet
uint8_t (*matrix_ptr)[][20] = &l_matrix;
Then that one creates a pointer to an incomplete array type of elements of type array of 20 uint8_t. Because the pointer is to an array of arrays, you have to access it with
(*matrix_ptr)[0][1] = ...;
And because it's a pointer to an incomplete array, you cannot do as a shortcut
matrix_ptr[0][0][1] = ...;
Because indexing requires the element type's size to be known (indexing implies an addition of an integer to the pointer, so it won't work with incomplete types). Note that this only works in C
, because T[]
and T[N]
are compatible types. C++ does not have a concept of compatible types, and so it will reject that code, because T[]
and T[10]
are different types.
The following alternative doesn't work at all, because the element type of the array, when you view it as a one-dimensional array, is not uint8_t
, but uint8_t[20]
uint8_t *matrix_ptr = l_matrix; // fail
The following is a good alternative
uint8_t (*matrix_ptr)[10][20] = &l_matrix;
You access it with
(*matrix_ptr)[0][1] = ...;
matrix_ptr[0][0][1] = ...; // also possible now
It has the benefit that it preserves the outer dimension's size. So you can apply sizeof on it
sizeof (*matrix_ptr) == sizeof(uint8_t) * 10 * 20
There is one other answer that makes use of the fact that items in an array are contiguously stored
uint8_t *matrix_ptr = l_matrix[0];
Now, that formally only allows you to access the elements of the first element of the two dimensional array. That is, the following condition hold
matrix_ptr[0] = ...; // valid
matrix_ptr[19] = ...; // valid
matrix_ptr[20] = ...; // undefined behavior
matrix_ptr[10*20-1] = ...; // undefined behavior
You will notice it probably works up to 10*20-1
, but if you throw on alias analysis and other aggressive optimizations, some compiler could make an assumption that may break that code. Having said that, i've never encountered a compiler that fails on it (but then again, i've not used that technique in real code), and even the C FAQ has that technique contained (with a warning about its UB'ness), and if you cannot change the array type, this is a last option to save you :)
<b>
and <i>
should be avoided because they describe the style of the text. Instead, use <strong>
and <em>
because that describes the semantics (the meaning) of the text.
As with all things in HTML, you should be thinking not about how you want it to look, but what you actually mean. Sure, it might just be bold and italics to you, but not to a screen reader.
Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:
Example:
export const loginForm = ({ commit }, data) => {
return axios
.post('http://localhost:8000/api/login', data)
.then((response) => {
commit('logUserIn', response.data);
})
.catch((error) => {
commit('unAuthorisedUser', { error:error.response.data });
})
}
Another example:
addEmployee({ commit, state }) {
return insertEmployee(state.employee)
.then(result => {
commit('setEmployee', result.data);
return result.data; // resolve
})
.catch(err => {
throw err.response.data; // reject
})
}
Another example with async-await
async getUser({ commit }) {
try {
const currentUser = await axios.get('/user/current')
commit('setUser', currentUser)
return currentUser
} catch (err) {
commit('setUser', null)
throw 'Unable to fetch current user'
}
},
This is old topic but on my last test on one my API, cURL is faster and more stable. Sometimes file_get_contents on larger request need over 5 seconds when cURL need only from 1.4 to 1.9 seconds what is double faster.
I need to add one note on this that I just send GET and recive JSON content. If you setup cURL properly, you will have a great response. Just "tell" to cURL what you need to send and what you need to recive and that's it.
On your exampe I would like to do this setup:
$ch = curl_init('http://api.bitly.com/v3/shorten?login=user&apiKey=key&longUrl=url');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 3);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
$result = curl_exec($ch);
This request will return data in 0.10 second max
def reverse(text):
reversed = ''
for i in range(len(text)-1, -1, -1):
reversed += text[i]
return reversed
print("reverse({}): {}".format("abcd", reverse("abcd")))
The parametric equation for a circle is
x = cx + r * cos(a)
y = cy + r * sin(a)
Where r is the radius, cx,cy the origin, and a the angle.
That's pretty easy to adapt into any language with basic trig functions. Note that most languages will use radians for the angle in trig functions, so rather than cycling through 0..360 degrees, you're cycling through 0..2PI radians.
Thanks to @Birchlabs' comment, now it is tons easier with this special Mac-only DNS name available:
docker run -e DB_PORT=5432 -e DB_HOST=docker.for.mac.host.internal
From 17.12.0-cd-mac46, docker.for.mac.host.internal
should be used instead of docker.for.mac.localhost
. See release note for details.
@helmbert's answer well explains the issue. But Docker for Mac does not expose the bridge network, so I had to do this trick to workaround the limitation:
$ sudo ifconfig lo0 alias 10.200.10.1/24
Open /usr/local/var/postgres/pg_hba.conf
and add this line:
host all all 10.200.10.1/24 trust
Open /usr/local/var/postgres/postgresql.conf
and edit change listen_addresses
:
listen_addresses = '*'
Reload service and launch your container:
$ PGDATA=/usr/local/var/postgres pg_ctl reload
$ docker run -e DB_PORT=5432 -e DB_HOST=10.200.10.1 my_app
What this workaround does is basically same with @helmbert's answer, but uses an IP address that is attached to lo0
instead of docker0
network interface.
if you are able to access node on ubuntu terminal using nodejs command,then this problem can be simply solved using -creating a symbolic link of nodejs and node using
ln -s /usr/bin/nodejs /usr/bin/node
and this may solve the problem
...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?
If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:
Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.
For those who uses Git Bash and having issues with npm run <script>
,
Just set npm to use Git Bash to run scripts
npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe"
(change the path according to your installation)
And then npm will run scripts with Git Bash, so such usages like NODE_ENV=
will work properly.
Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:
private void myCustomControl_Click(object sender, EventArgs e)
{
((MyCustomControl)sender).DoWhatever();
}
The 'sender' is just the object that was actioned (eg clicked).
The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.
I have same error. Problem was that branch was deleted, released. But in PhpStorm I still could see it in remote branches. I could checkout as local branch. And then doing git pull was giving this error.
So need to check if this brnach really exists remotely.
If anyone is trying to use event.target in React and finding a null value, it is because a SyntheticEvent has replaced the event.target. The SyntheticEvent now holds 'currentTarget', such as in event.currentTarget.getAttribute('data-username').
https://facebook.github.io/react/docs/events.html
It looks like React does this so that it works across more browsers. You can access the old properties through a nativeEvent attribute.
To remove one or more columns by name, when the column names are known (as opposed to being determined at run-time), I like the subset()
syntax. E.g. for the data-frame
df <- data.frame(a=1:3, d=2:4, c=3:5, b=4:6)
to remove just the a
column you could do
Data <- subset( Data, select = -a )
and to remove the b
and d
columns you could do
Data <- subset( Data, select = -c(d, b ) )
You can remove all columns between d
and b
with:
Data <- subset( Data, select = -c( d : b )
As I said above, this syntax works only when the column names are known. It won't work when say the column names are determined programmatically (i.e. assigned to a variable). I'll reproduce this Warning from the ?subset
documentation:
Warning:
This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like '[', and in particular the non-standard evaluation of argument 'subset' can have unanticipated consequences.
The CSS selector for the direct first-child in your case is:
.section > :first-child
The direct selector is > and the first child selector is :first-child
No need for an asterisk before the : as others suggest. You could speed up the DOM searching by modifying this solution by prepending the tag:
div.section > :first-child
Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1 or p. So we'll use .contents() instead, and use this instead of $(this) since we're creating a method on a jQuery object.
$.fn.textWidth = function(){
var contents = this.contents(),
wrapper = '<span style="display: inline-block;" />',
width = '';
contents.wrapAll(wrapper);
width = contents.parent().width(); // parent is now the wrapper
contents.unwrap();
return width;
};
There is none. Either use a java.util.List
*, or you can write your own indexOf()
:
public static <T> int indexOf(T needle, T[] haystack)
{
for (int i=0; i<haystack.length; i++)
{
if (haystack[i] != null && haystack[i].equals(needle)
|| needle == null && haystack[i] == null) return i;
}
return -1;
}
*you can make one from your array using Arrays#asList()
Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();
exitcode = data.wait()
. The child process will be blocked If it writes to standard output/error, and/or reads from standard input, and there are no peers.
You mention you are using Pandas (in your title). If so, there is no need to use an external library, you can just use to_datetime
>>> pandas.to_datetime('today').normalize()
Timestamp('2015-10-14 00:00:00')
This will always return today's date at midnight, irrespective of the actual time, and can be directly used in pandas to do comparisons etc. Pandas always includes 00:00:00 in its datetimes.
Replacing today
with now
would give you the date in UTC instead of local time; note that in neither case is the tzinfo (timezone) added.
In pandas versions prior to 0.23.x, normalize
may not have been necessary to remove the non-midnight timestamp.
php\php.ini
set your loadable php extensions path (eg. extension_dir = "C:\php\ext"
)
(https://drive.google.com/open?id=1DDZd06SLHSmoFrdmWkmZuXt4DMOPIi_A)php\php.ini
) check if extension=php_mysqli.dll
is uncommented
(https://drive.google.com/open?id=17DUt1oECwOdol8K5GaW3tdPWlVRSYfQ9)"C:\php"
) and php\ext folder (eg."C:\php\ext"
) as your runtime environment variable path
(https://drive.google.com/open?id=1zCRRjh1Jem_LymGsgMmYxFc8Z9dUamKK)It's impossible for both servers to listen on the same port at the same IP address: since a single socket can only be opened by a single process, only the first server configured for a certain IP/port combination will successfully bind, and the second one will fail.
You will thus need a workaround to achieve what you want. Easiest is probably to run Apache on your primary IP/port combination, and have it route requests for IIS (which should be configured for a different IP and/or port) to it using mod_rewrite.
Keep in mind that the alternative IP and port IIS runs on should be reachable to the clients connecting to your server: if you only have a single IP address available, you should take care to pick an IIS port that isn't generally blocked by firewalls (8080 might be a good option, or 443, even though you're running regular HTTP and not SSL)
P.S. Also, please note that you do need to modify the IIS default configuration using httpcfg before it will allow other servers to run on port 80 on any IP address on the same server: see Micky McQuade's answer for the procedure to do that...
If you have Windows 10 you can use Bash on Ubuntu on Windows to install subversion.
The problem is in the line before the one that throws the warning. When you create df_2 that's where you're creating a copy of a slice of a dataframe. Instead, when you create df_2, use .copy() and you won't get that warning later on.
df_2 = df[df['B'] == 'b.2'].copy()
I have simplified it : I have edited jackjoe's answer. The height auto etc not required I think.
CSS:
#container {
position: relative;
margin:0 auto;
width: 1000px;
background: #C63;
padding: 10px;
}
#leftCol {
background: #e8f6fe;
width: auto;
}
#rightCol {
float:right;
width:30%;
background: #aafed6;
}
.box {
position:relative;
clear:both;
background:#F39;
}
</style>
HTML:
<div id="container">
<div id="rightCol">
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>
<div id="leftCol">
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.
</div>
</div>
<div class="box">
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
<p>Lorem ipsum dolor sit amet,consectetuer adipiscing elit. Phasellus varius eleifend. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Phasellus varius eleifend.</p>
</div>
This works for me (I'm using mac). Run this command
lsof -PiTCP -sTCP:LISTEN
This's going to display a list of ports that your syetem is using. Find the PID
that your node is running
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
node 17269 hientrq 16u IPv6 0xc42959c6fa30c3b9 0t0 TCP *:51524 (LISTEN)
node 17269 hientrq 19u IPv4 0xc42959c71ae86fc1 0t0 TCP localhost:1337 (LISTEN)
and run kill -9 [YOUR_PID]
From Qt5 onwards we can also use
Static Public Members of QThread
void msleep(unsigned long msecs)
void sleep(unsigned long secs)
void usleep(unsigned long usecs)
The fastest way to get date formatting thats any good is to use datejs.
The lib is really easy to use and does give you very pretty formatting.
as far as your code snippet, dont use document.write if you can help it. try
document.getElementById("date").value = new Date().toUTCString();
UPDATE
T1
SET
T1.Inci = T2.Inci
FROM
T1
INNER JOIN
T2
ON
T1.Brands = T2.Brands
AND
T1.Category= T2.Category
AND
T1.Date = T2.Date
You can use string.scan(your_regex).flatten
. If your regex contains groups, it will return in a single plain array.
string = "A 54mpl3 string w1th 7 numbers scatter3r ar0und"
your_regex = /(\d+)[m-t]/
string.scan(your_regex).flatten
=> ["54", "1", "3"]
Regex can be a named group as well.
string = 'group_photo.jpg'
regex = /\A(?<name>.*)\.(?<ext>.*)\z/
string.scan(regex).flatten
You can also use gsub
, it's just one more way if you want MatchData.
str.gsub(/\d/).map{ Regexp.last_match }
This 'just works' for me using jQuery, provided you don't try to append a subset the XHR-returned HTML to the document. (See this bug report showing the problem with jQuery.)
Here is an example showing it working:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test_1.4</title>
<script type="text/javascript" charset="utf-8" src="jquery.1.4.2.js"></script>
<script type="text/javascript" charset="utf-8">
var snippet = "<div><span id='a'>JS did not run<\/span><script type='text/javascript'>" +
"$('#a').html('Hooray! JS ran!');" +
"<\/script><\/div>";
$(function(){
$('#replaceable').replaceWith($(snippet));
});
</script>
</head>
<body>
<div id="replaceable">I'm going away.</div>
</body>
</html>
Here is the equivalent of the above: http://jsfiddle.net/2CTLH/
Here's a simpler method to add multiple classes via classList
(supported by all modern browsers, as noted in other answers here):
div.classList.add('foo', 'bar'); // add multiple classes
From: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList#Examples
If you have an array of class names to add to an element, you can use the ES6 spread operator to pass them all into classList.add()
via this one-liner:
let classesToAdd = [ 'foo', 'bar', 'baz' ];
div.classList.add(...classesToAdd);
Note that not all browsers support ES6 natively yet, so as with any other ES6 answer you'll probably want to use a transpiler like Babel, or just stick with ES5 and use a solution like @LayZee's above.
You're getting None
because list.sort()
it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort()
without assigning it to a
again.
There is a built in function sorted()
, which returns a sorted version of the list - a = sorted(a)
will do what you want as well.
That's not possible. but you can use an Object Mapper like AutoMapper
Example:
class A
{
public int IntProp { get; set; }
}
class B
{
public int IntProp { get; set; }
public string StrProp { get; set; }
}
In global.asax or application startup:
AutoMapper.Mapper.CreateMap<A, B>();
Usage:
var b = AutoMapper.Mapper.Map<B>(a);
It's easily configurable via a fluent API.
A simpler answer.
function ($quantity) use ($tax, &$total) { .. };
$tax
inside the closure has no external effect, unless it is a pointer, like an object is.&$total
. This way, modifying the value of $total
DOES HAVE an external effect, the original variable's value changes.As @Mytskine pointed out probably the best in-depth explanation is the RFC for closures. (Upvote him for this.)
I agree with Charles Duffy that a proper XML parser is the right way to go.
But as to what's wrong with your sed
command (or did you do it on purpose?).
$data
was not quoted, so $data
is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.So given your specific XML structure, this modified sed
command should work
title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")
Basically for the line that contains title
, extract the text between the tags, then quit (so you don't extract the 2nd <title>
)
My solution was to put same value (path to JDK bin folder) in JAVA_HOME
and Path
The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.
When working to create Cross Browser Favicons (including touch icons) there are several things to consider.
The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon"
for IE to recognize the icon it needs the word shortcut
which is not standard. Also we wrap the .ico
favicon in a IE conditional comment because Chrome and Safari will use the .ico
file if it is present, despite other options available, not what we would like.
The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.
For the rest of the browsers we are going to use the standard way to cite a favicon:
<link rel="icon" href="path/to/favicon.png">
This icon should be 196x196 pixels in size to cover all devices that may use this icon.
To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
Using rel="apple-touch-icon-precomposed"
will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon"
. This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed"
.
As a note: Chrome for Android states:
The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).
Custom Tiles for IE 11+ on Windows 8.1+
IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.
Microsoft recommends creating a few tiles at the following size:
Small: 128 x 128
Medium: 270 x 270
Wide: 558 x 270
Large: 558 x 558
These should be transparent images as we will define a color background next.
Once these images are created you should create an xml file called browserconfig.xml
with the following code:
<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
<msapplication>
<tile>
<square70x70logo src="images/smalltile.png"/>
<square150x150logo src="images/mediumtile.png"/>
<wide310x150logo src="images/widetile.png"/>
<square310x310logo src="images/largetile.png"/>
<TileColor>#009900</TileColor>
</tile>
</msapplication>
</browserconfig>
Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head
:
<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />
For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.
Putting it all together:
To put it all together the above code would look like this:
<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->
<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. -->
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">
<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">
Windows Phone Live Tiles
If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:
Here are detailed instructions from Microsoft but here is a synopsis:
Step 1
Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.
Step 2
Add a hidden overlay of this image. Here is example code from Microsoft:
<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
<img src="customtile.png" width="320" height="320" />
<div style='margin-top: 40px'>
Add text/graphic asking user to pin to start using the menu...
</div>
</div>
Step 3
You then can add thew following line to add a pin to start link:
<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>
Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.
Step 4
Next you add some JS to toggle the overlay visibility
<script>
function ToggleTileOverlay() {
var newVisibility = (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
document.getElementById('TileOverlay').style.visibility = newVisibility;
}
</script>
Note on Sizes
I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.
Further Reading
For those who would like more details see the links below:
You can use the AddOrUpdate
method:
db.Books.AddOrUpdate(book); //requires using System.Data.Entity.Migrations;
db.SaveChanges();
%pip install fedex #fedex = package name
in 2019.
In older versions of conda:
import sys
!{sys.executable} -m pip install fedex #fedex = package name
*note - you do need to import sys
#!/bin/bash
prog1 & 2> .errorprog1.log; prog2 & 2> .errorprog2.log
Redirect errors to separate logs.
Unrelated to the OP's problem, but my issue was that I'm a noob shell scripter. All the other languages I've used require parentheses to invoke methods, whereas shell doesn't seem to like that.
function do_something() {
# do stuff here
}
# bad
do_something()
# works
do_something
way one :
you can use bin icon in logcat
way two: you can clear logcat after per lunch Edit Configuration > Miscellaneous
check Clear log before lunch
$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIMESTAMP(), '$comments')";
You can use this Query. CURRENT_TIMESTAMP
Remember to use the parenthesis CURRENT_TIMESTAMP()
Or you can send a page break (ASCII form feed) by pressing Ctrl + L.
While this technically just starts a new page, this has the same net effect as all the other methods, while being a lot faster (except for the Apple + K solution, of course).
And because this is an ASCII control command, and it works in all shells.
The root of the problem are often outdated scripts in the bin
(Linux) or Scripts
(Windows) subdirectory. I'll explain this using problem I encountered myself as an example.
I had virtualenv version 1.10 installed in my user site-packages (the fact it's in user site-packages not sytem site-packages is irrelevant here)
pdobrogost@host:~$ which virtualenv
/home/users/pdobrogost/.local/bin/virtualenv
pdobrogost@host:~$ virtualenv --version
1.10
After I upgraded it to version 1.11 I got the following error:
pdobrogost@host:~$ virtualenv --version
Traceback (most recent call last):
File "/home/users/pdobrogost/.local/bin/virtualenv", line 5, in <module>
from pkg_resources import load_entry_point
File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 2701, in <module>
return self.__dep_map
File "build/bdist.linux-x86_64/egg/pkg_resources.py", line 572, in resolve
if insert:
pkg_resources.DistributionNotFound: virtualenv==1.10
File /home/users/pdobrogost/.local/bin/virtualenv
mentioned in the error message looked like this:
#!/opt/python/2.7.5/bin/python2.7
# EASY-INSTALL-ENTRY-SCRIPT: 'virtualenv==1.10','console_scripts','virtualenv'
__requires__ = 'virtualenv==1.10'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('virtualenv==1.10', 'console_scripts', 'virtualenv')()
)
There, we see that virtualenv
script was not updated and still requires previously installed version 1.10 of virtualenv.
Now, reinstalling virtualenv like this
pdobrogost@host:~$ pip install --user --upgrade virtualenv
Downloading/unpacking virtualenv from https://pypi.python.org/packages/py27/v/virtualenv/virtualenv-1.11.1-py27-none-any.whl#md5=265770b61de41d34d2e9fdfddcdf034c
Using download cache from /home/users/pdobrogost/.pip_download_cache/https%3A%2F%2Fpypi.python.org%2Fpackages%2Fpy27%2Fv%2Fvirtualenv%2Fvirtualenv-1.11.1-py27-none-any.whl
Installing collected packages: virtualenv
Successfully installed virtualenv
Cleaning up...
does not help (neither pip install --user --upgrade --force-reinstall virtualenv
) because script /home/users/pdobrogost/.local/bin/virtualenv
is left unchanged.
The only way I could fix this was by manually removing virtualenv* scripts from /home/users/pdobrogost/.local/bin/
folder and installing virtualenv again. After this, newly generated scripts refer to the proper version of the package:
pdobrogost@host:~$ virtualenv --version
1.11
Character U+201C Left Double Quotation Mark is not present in the Latin-1 (ISO-8859-1) encoding.
It is present in code page 1252 (Western European). This is a Windows-specific encoding that is based on ISO-8859-1 but which puts extra characters into the range 0x80-0x9F. Code page 1252 is often confused with ISO-8859-1, and it's an annoying but now-standard web browser behaviour that if you serve your pages as ISO-8859-1, the browser will treat them as cp1252 instead. However, they really are two distinct encodings:
>>> u'He said \u201CHello\u201D'.encode('iso-8859-1')
UnicodeEncodeError
>>> u'He said \u201CHello\u201D'.encode('cp1252')
'He said \x93Hello\x94'
If you are using your database only as a byte store, you can use cp1252 to encode “
and other characters present in the Windows Western code page. But still other Unicode characters which are not present in cp1252 will cause errors.
You can use encode(..., 'ignore')
to suppress the errors by getting rid of the characters, but really in this century you should be using UTF-8 in both your database and your pages. This encoding allows any character to be used. You should also ideally tell MySQL you are using UTF-8 strings (by setting the database connection and the collation on string columns), so it can get case-insensitive comparison and sorting right.
for safety we should not use self signed certificates in our implementation. However, when it comes to development often we have to use trial environments which got self-signed certs. I tried to fix this issue programmatically in my code and I fail. However, by adding the cert to the jre trust-store fixed my issue. Please find below steps,
Download the site cert,
Copy the certificate(ex:cert_file.cer) into the directory $JAVA_HOME\Jre\Lib\Security
Open CMD in Administrator and change the directory to $JAVA_HOME\Jre\Lib\Security
Import the certificate to a trust store using below command,
keytool -import -alias ca -file cert_file.cer -keystore cacerts -storepass changeit
If you got a error saying keytool is not recognizable please refer this.
Type yes like below
Trust this certificate: [Yes]
Update
If your app server is jboss try adding below system property
System.setProperty("org.jboss.security.ignoreHttpsHost","true");
Hope this helps!
How about this:
function array_keys_exist($searchForKeys = array(), $searchableArray) {
$searchableArrayKeys = array_keys($searchableArray);
return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys);
}
You cannot read text strings with csvread. Here is another solution:
fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
line = fgets(fid1); %# read line by line
A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
if A(2)<4.185 %# test the values
fprintf(fid2,'%s',line); %# write the line to the new file
end
end
fclose(fid1);
fclose(fid2);
You can do it with a separate UPDATE statement
UPDATE report.TEST target
SET is Deleted = 'Y'
WHERE NOT EXISTS (SELECT 1
FROM main.TEST source
WHERE source.ID = target.ID);
I don't know of any way to integrate this into your MERGE statement.
In C, \0
denotes a character with value zero. The following are identical:
char a = 0;
char b = '\0';
The utility of this escape sequence is greater inside string literals, which are arrays of characters:
char arr[] = "abc\0def\0ghi\0";
(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)
With the expression API, which based on the comments is what this question is asking for, you can use the in_
method of the relevant column.
To query
SELECT id, name FROM user WHERE id in (123,456)
use
myList = [123, 456]
select = sqlalchemy.sql.select([user_table.c.id, user_table.c.name], user_table.c.id.in_(myList))
result = conn.execute(select)
for row in result:
process(row)
This assumes that user_table
and conn
have been defined appropriately.
There's no reliable way to do this, as there are strings which stay the same through the encoding process, i.e. is "abc" encoded or not? There's no clear answer. Also, as you've encountered, some characters have multiple encodings... But...
Your decode-check-encode-check scheme fails due to the fact that some characters may be encoded in more than one way. However, a slight modification to your function should be fairly reliable, just check if the decode modifies the string, if it does, it was encoded.
It won't be fool proof of course, as "10+20=30" will return true (+ gets converted to space), but we're actually just doing arithmetic. I suppose this is what you're scheme is attempting to counter, I'm sorry to say that I don't think there's a perfect solution.
HTH.
Edit:
As I entioned in my own comment (just reiterating here for clarity), a good compromise would probably be to check for invalid characters in your url (e.g. space), and if there are some it's not encoded. If there are none, try to decode and see if the string changes. This still won't handle the arithmetic above (which is impossible), but it'll hopefully be sufficient.
use this
when: "{{ 'value' in variable1}}"
instead of
when: "'value' in {{variable1}}"
Also for string comparison you can use
when: "{{ variable1 == 'value' }}"
public static class SqlParameterExtensions
{
public static T GetValueOrDefault<T>(this SqlParameter sqlParameter)
{
if (sqlParameter.Value == DBNull.Value
|| sqlParameter.Value == null)
{
if (typeof(T).IsValueType)
return (T)Activator.CreateInstance(typeof(T));
return (default(T));
}
return (T)sqlParameter.Value;
}
}
// Usage
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("storedProcedure", conn))
{
SqlParameter outputIdParam = new SqlParameter("@ID", SqlDbType.Int)
{
Direction = ParameterDirection.Output
};
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(outputIdParam);
conn.Open();
cmd.ExecuteNonQuery();
int result = outputIdParam.GetValueOrDefault<int>();
}
Why not just load the frame off screen or hidden and then display it once it has finished loading. You could show a loading icon in its place to begin with to give the user immediate feedback that it's loading.
No need to apologize for asking a question! Try using the RIGHT
function. It returns the last n characters of a string.
=RIGHT(A1, 1)
There is also the static HostingEnvironment.MapPath
Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:
Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.
I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.
If you're dead set on taking this approach, Pim Jager's solution is good.
A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.
You could do this with jquery:
$('a[href^="http://"]').each(function() {
$('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)
});
An interesting solution is to make this declarative: you just give every div that should be shown an attribute automaticallyVisibleIfIdChecked
with the id of the checkbox or radio button on which it depends. That is, your form looks like this:
<form name="form1" id="my_form" method="post" action="">
<div><label><input type="radio" name="group1" id="rdio1" value="opt1">opt1</label></div>
<div><label><input type="radio" name="group1" id="rdio2" value="opt2">opt2</label></div>
</form>
....
<div id="opt1" automaticallyVisibleIfIdChecked="rdio1">lorem ipsum dolor</div>
<div id="opt2" automaticallyVisibleIfIdChecked="rdio2">consectetur adipisicing</div>
and have some page independent JavaScript that nicely uses functional programming:
function executeAutomaticVisibility(name) {
$("[name="+name+"]:checked").each(function() {
$("[automaticallyVisibleIfIdChecked=" + this.id+"]").show();
});
$("[name="+name+"]:not(:checked)").each(function() {
$("[automaticallyVisibleIfIdChecked=" + this.id+"]").hide();
});
}
$(document).ready( function() {
triggers = $("[automaticallyVisibleIfIdChecked]")
.map(function(){ return $("#" + $(this).attr("automaticallyVisibleIfIdChecked")).get() })
$.unique(triggers);
triggers.each( function() {
executeAutomaticVisibility(this.name);
$(this).change( function(){ executeAutomaticVisibility(this.name); } );
});
});
Similarily you could automatically enable / disable form fields with an attribute automaticallyEnabledIfChecked
.
I think this method is nice since it avoids having to create specific JavaScript for your page - you just insert some attributes that say what should be done.
You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.
The github repo will be created as a new project in android studio.
Ive modifiet Lukas Knuth's solution a little:
1) There's no need to subclass the webview,
2) the code will crash during bytecode verification on some Android 1.6 devices if you don't put nonexistant methods in seperate classes
3) Zoom controls will still appear if the user scrolls up/down a page. I simply set the zoom controller container to visibility GONE
wv.getSettings().setSupportZoom(true);
wv.getSettings().setBuiltInZoomControls(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
// Use the API 11+ calls to disable the controls
// Use a seperate class to obtain 1.6 compatibility
new Runnable() {
public void run() {
wv.getSettings().setDisplayZoomControls(false);
}
}.run();
} else {
final ZoomButtonsController zoom_controll =
(ZoomButtonsController) wv.getClass().getMethod("getZoomButtonsController").invoke(wv, null);
zoom_controll.getContainer().setVisibility(View.GONE);
}
I have created FolderLayout
which may help you.
This link helped me
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/path" android:text="Path"
android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
<ListView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:id="@+id/list"></ListView>
</LinearLayout>
package com.testsample.activity;
public class FolderLayout extends LinearLayout implements OnItemClickListener {
Context context;
IFolderItemListener folderListener;
private List<String> item = null;
private List<String> path = null;
private String root = "/";
private TextView myPath;
private ListView lstView;
public FolderLayout(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
this.context = context;
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.folderview, this);
myPath = (TextView) findViewById(R.id.path);
lstView = (ListView) findViewById(R.id.list);
Log.i("FolderView", "Constructed");
getDir(root, lstView);
}
public void setIFolderItemListener(IFolderItemListener folderItemListener) {
this.folderListener = folderItemListener;
}
//Set Directory for view at anytime
public void setDir(String dirPath){
getDir(dirPath, lstView);
}
private void getDir(String dirPath, ListView v) {
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if (!dirPath.equals(root)) {
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for (int i = 0; i < files.length; i++) {
File file = files[i];
path.add(file.getPath());
if (file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
Log.i("Folders", files.length + "");
setItemList(item);
}
//can manually set Item to display, if u want
public void setItemList(List<String> item){
ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
R.layout.row, item);
lstView.setAdapter(fileList);
lstView.setOnItemClickListener(this);
}
public void onListItemClick(ListView l, View v, int position, long id) {
File file = new File(path.get(position));
if (file.isDirectory()) {
if (file.canRead())
getDir(path.get(position), l);
else {
//what to do when folder is unreadable
if (folderListener != null) {
folderListener.OnCannotFileRead(file);
}
}
} else {
//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
if (folderListener != null) {
folderListener.OnFileClicked(file);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
onListItemClick((ListView) arg0, arg0, arg2, arg3);
}
}
And an Interface IFolderItemListener
to add what to do when a fileItem
is clicked
public interface IFolderItemListener {
void OnCannotFileRead(File file);//implement what to do folder is Unreadable
void OnFileClicked(File file);//What to do When a file is clicked
}
Also an xml to define the row
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowtext" android:layout_width="fill_parent"
android:textSize="23sp" android:layout_height="match_parent"/>
In your xml,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="horizontal" android:weightSum="1">
<com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
android:layout_weight="0.35"
android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>
In Your Activity,
public class SampleFolderActivity extends Activity implements IFolderItemListener {
FolderLayout localFolders;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
localFolders = (FolderLayout)findViewById(R.id.localfolders);
localFolders.setIFolderItemListener(this);
localFolders.setDir("./sys");//change directory if u want,default is root
}
//Your stuff here for Cannot open Folder
public void OnCannotFileRead(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle(
"[" + file.getName()
+ "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
//Your stuff here for file Click
public void OnFileClicked(File file) {
// TODO Auto-generated method stub
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "]")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
}).show();
}
}
Import the libraries needed. Hope these help you...
If you look at the docs [1], you see that the load()
method can take a URL:
load(URL location)
So if you're running Java 7 or newer, you can load the FXML file like this:
URL url = Paths.get("./src/main/resources/fxml/Fxml.fxml").toUri().toURL();
Parent root = FXMLLoder.load(url);
This example is from a Maven project, which is why the FXML file is in the resources folder.
[1] https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.htm
Find out how to fix this here:
https://github.com/blog/1614-two-factor-authentication#how-does-it-work-for-command-line-git
How does it work for command-line Git?
If you are using SSH for Git authentication, rest easy: you don't need to do anything. If you are using HTTPS Git, instead of entering your password, enter a personal access token. These can be created by going to your personal access tokens page.
You have to convert the response to JSON using Gson.toJson(object)
.
For example:
return Response.status(Status.OK).entity(new Gson().toJson(Student)).build();
I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):
mention permissions in Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
e.g.
File file=new File(path);
long=file.length();//in Bytes
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
I am pretty sure this is a duplicate. Anyway, have a look at the following piece of code
x <- seq(5, 15, length=1000)
y <- dnorm(x, mean=10, sd=3)
plot(x, y, type="l", lwd=1)
I'm sure you can work the rest out yourself, for the title you might want to look for something called main=
and y-axis
labels are also up to you.
If you want to see more of the tails of the distribution, why don't you try playing with the seq(5, 15, )
section? Finally, if you want to know more about what dnorm
is doing I suggest you look here
In the build.gradle file, It was by default compile 'com.android.support:support-v4:+' so when you build the gradle projecit would consider, com.android.support:support-v4:21.0.0-rc1 because of the recent L developer preview release.
Make changes in the following line and it will resolve the issue. Change
compile 'com.android.support:support-v4:+'
to
compile 'com.android.support:support-v4:20.+'
Similarly when using v7-appcompat support library, make the change from
compile 'com.android.support:appcompat-v7:+'
to
compile 'com.android.support:appcompat-v7:20.+'.
you must have aligned it to left or right of parent view
don't use any of these when using android:centerInParent="true"
codes:-
android:layout_alignParentLeft="true"
android:layout_alignParentLeft="true"
android:layout_alignRight=""
etc.
if you would use octave you could do it like this - but sadly matlab does not support this possibility
function hello (who = "World")
printf ("Hello, %s!\n", who);
endfunction
(taken from the doc)
A more general answer would be to import java.util.Date
, then when you need to set a timestamp
equal to the current date, simply set it equal to new Date()
.
[ ]{2,}
SPACE (2 or more)
You could also check that before and after those spaces words follow. (not other whitespace like tabs or new lines)
\w[ ]{2,}\w
the same, but you can also pick (capture) only the spaces for tasks like replacement
\w([ ]{2,})\w
or see that before and after spaces there is anything, not only word characters (except whitespace)
[^\s]([ ]{2,})[^\s]
If you find boost::assign::map_list_of
useful, but can't use it for some reason, you could write your own:
template<class K, class V>
struct map_list_of_type {
typedef std::map<K, V> Map;
Map data;
map_list_of_type(K k, V v) { data[k] = v; }
map_list_of_type& operator()(K k, V v) { data[k] = v; return *this; }
operator Map const&() const { return data; }
};
template<class K, class V>
map_list_of_type<K, V> my_map_list_of(K k, V v) {
return map_list_of_type<K, V>(k, v);
}
int main() {
std::map<int, char> example =
my_map_list_of(1, 'a') (2, 'b') (3, 'c');
cout << example << '\n';
}
It's useful to know how such things work, especially when they're so short, but in this case I'd use a function:
struct A {
static map<int, int> const m;
};
namespace {
map<int,int> create_map() {
map<int, int> m;
m[1] = 2; // etc.
return m;
}
}
map<int, int> const A::m = create_map();
If you want to export all JAR-files of a Java web-project, open the latest generated WAR-file with a ZIP-tool (e.g. 7-Zip), navigate to the /WEB-INF/lib/ folder. Here you will find all JAR-files you need for this project (as listed in "Referenced Libraries").
Check in the folder structure of the project the files within the /gradle/wrapper/ The gradle-wrapper.jar version should be the one specified in the gradle-wrapper.properties
Most browsers don't fully support the numerical values for font-weight
. Here's a good article about the problem, and even tough it's a little old, it does seem to be correct.
If you need something bolder then you might want to try using a different font that's bolder than your existing one. Naturally, you could probably adjust the font size for a similar effect.