myImageView.isUserInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(imageTapped))
tapGestureRecognizer.numberOfTapsRequired = 1
myImageView.addGestureRecognizer(tapGestureRecognizer)
and when tapped:
@objc func imageTapped(_ sender: UITapGestureRecognizer) {
// do something when image tapped
print("image tapped")
}
func tabGesture_Call
{
let tapRec = UITapGestureRecognizer(target: self, action: "handleTap:")
tapRec.delegate = self
self.view.addGestureRecognizer(tapRec)
//where we want to gesture like: view, label etc
}
func handleTap(sender: UITapGestureRecognizer)
{
NSLog("Touch..");
//handling code
}
For anyone who is looking for Swift 3 solution
let tap = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
view.addGestureRecognizer(tap)
view.isUserInteractionEnabled = true
self.view.addSubview(view)
// function which is triggered when handleTap is called
func handleTap(_ sender: UITapGestureRecognizer) {
print("Hello World")
}
//----firstly you have to alloc the double and single tap gesture-------//
UITapGestureRecognizer* doubleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleDoubleTap:)];
UITapGestureRecognizer* singleTap = [[UITapGestureRecognizer alloc] initWithTarget : self action : @selector (handleSingleTap:)];
[singleTap requireGestureRecognizerToFail : doubleTap];
[doubleTap setDelaysTouchesBegan : YES];
[singleTap setDelaysTouchesBegan : YES];
//-----------------------number of tap----------------//
[doubleTap setNumberOfTapsRequired : 2];
[singleTap setNumberOfTapsRequired : 1];
//------- add double tap and single tap gesture on the view or button--------//
[self.view addGestureRecognizer : doubleTap];
[self.view addGestureRecognizer : singleTap];
As of iOS 8 the accepted answer no longer works. I needed to stop the swipping to dismiss gesture on my main game screen so implemented this:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = self;
}
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
self.navigationController.interactivePopGestureRecognizer.delegate = nil;
}
}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
return NO;
}
I solved a lot of issues by using the following code. Issues were : -
const sequelize = new Sequelize("test", "root", "root", {
host: "127.0.0.1",
dialect: "mysql",
port: "8889",
connectionLimit: 10,
socketPath: "/Applications/MAMP/tmp/mysql/mysql.sock",
// It will disable logging
logging: false
});
To add search button on navigation bar use this code:
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(toggleSearch:)];
self.navigationController.navigationBar.topItem.rightBarButtonItem = searchButton;
and implement following method:
- (IBAction)toggleSearch:(id)sender
{
// do something or handle Search Button Action.
}
version for data.table based on code from dmanuge :
convNumValues<-function(ds){
ds<-data.table(ds)
dsnum<-data.table(data.matrix(ds))
num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
nds <- data.table( dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}
im attach my vb.net code based on brian reference
Imports System.ComponentModel
Imports System.Runtime.InteropServices
Public Class PinvokeWindowsNetworking
Const NO_ERROR As Integer = 0
Private Structure ErrorClass
Public num As Integer
Public message As String
Public Sub New(ByVal num As Integer, ByVal message As String)
Me.num = num
Me.message = message
End Sub
End Structure
Private Shared ERROR_LIST As ErrorClass() = New ErrorClass() {
New ErrorClass(5, "Error: Access Denied"),
New ErrorClass(85, "Error: Already Assigned"),
New ErrorClass(1200, "Error: Bad Device"),
New ErrorClass(67, "Error: Bad Net Name"),
New ErrorClass(1204, "Error: Bad Provider"),
New ErrorClass(1223, "Error: Cancelled"),
New ErrorClass(1208, "Error: Extended Error"),
New ErrorClass(487, "Error: Invalid Address"),
New ErrorClass(87, "Error: Invalid Parameter"),
New ErrorClass(1216, "Error: Invalid Password"),
New ErrorClass(234, "Error: More Data"),
New ErrorClass(259, "Error: No More Items"),
New ErrorClass(1203, "Error: No Net Or Bad Path"),
New ErrorClass(1222, "Error: No Network"),
New ErrorClass(1206, "Error: Bad Profile"),
New ErrorClass(1205, "Error: Cannot Open Profile"),
New ErrorClass(2404, "Error: Device In Use"),
New ErrorClass(2250, "Error: Not Connected"),
New ErrorClass(2401, "Error: Open Files")}
Private Shared Function getErrorForNumber(ByVal errNum As Integer) As String
For Each er As ErrorClass In ERROR_LIST
If er.num = errNum Then Return er.message
Next
Try
Throw New Win32Exception(errNum)
Catch ex As Exception
Return "Error: Unknown, " & errNum & " " & ex.Message
End Try
Return "Error: Unknown, " & errNum
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetUseConnection(ByVal hwndOwner As IntPtr, ByVal lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserID As String, ByVal dwFlags As Integer, ByVal lpAccessName As String, ByVal lpBufferSize As String, ByVal lpResult As String) As Integer
End Function
<DllImport("Mpr.dll")>
Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Boolean) As Integer
End Function
<StructLayout(LayoutKind.Sequential)>
Private Class NETRESOURCE
Public dwScope As Integer = 0
Public dwType As Integer = 0
Public dwDisplayType As Integer = 0
Public dwUsage As Integer = 0
Public lpLocalName As String = ""
Public lpRemoteName As String = ""
Public lpComment As String = ""
Public lpProvider As String = ""
End Class
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String) As String
Return connectToRemote(remoteUNC, username, password, False)
End Function
Public Shared Function connectToRemote(ByVal remoteUNC As String, ByVal username As String, ByVal password As String, ByVal promptUser As Boolean) As String
Dim nr As NETRESOURCE = New NETRESOURCE()
nr.dwType = ResourceTypes.Disk
nr.lpRemoteName = remoteUNC
Dim ret As Integer
If promptUser Then
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", Connects.Interactive Or Connects.Prompt, Nothing, Nothing, Nothing)
Else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, Nothing, Nothing, Nothing)
End If
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Public Shared Function disconnectRemote(ByVal remoteUNC As String) As String
Dim ret As Integer = WNetCancelConnection2(remoteUNC, Connects.UpdateProfile, False)
If ret = NO_ERROR Then Return Nothing
Return getErrorForNumber(ret)
End Function
Enum Resources As Integer
Connected = &H1
GlobalNet = &H2
Remembered = &H3
End Enum
Enum ResourceTypes As Integer
Any = &H0
Disk = &H1
Print = &H2
End Enum
Enum ResourceDisplayTypes As Integer
Generic = &H0
Domain = &H1
Server = &H2
Share = &H3
File = &H4
Group = &H5
End Enum
Enum ResourceUsages As Integer
Connectable = &H1
Container = &H2
End Enum
Enum Connects As Integer
Interactive = &H8
Prompt = &H10
Redirect = &H80
UpdateProfile = &H1
CommandLine = &H800
CmdSaveCred = &H1000
LocalDrive = &H100
End Enum
End Class
how to use it
Dim login = PinvokeWindowsNetworking.connectToRemote("\\ComputerName", "ComputerName\UserName", "Password")
If IsNothing(login) Then
'do your thing on the shared folder
PinvokeWindowsNetworking.disconnectRemote("\\ComputerName")
End If
With the unobtrusive way:
Jquery Validate Example:
<input type="text" name="email" class="required">
<script>
$(function () {
$("form").validate();
});
</script>
Jquery Validate Unobtrusive Example:
<input type="text" name="email" data-val="true"
data-val-required="This field is required.">
<div class="validation-summary-valid" data-valmsg-summary="true">
<ul><li style="display:none"></li></ul>
</div>
In MySQL you can do this:
INSERT IGNORE INTO Table2(Id, Name) SELECT Id, Name FROM Table1
Does SQL Server have anything similar?
They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.
you should return three different values from this method and get these three in a single variable like this.
func getTime()-> (hour:Int,min:Int,sec:Int){
//your code
return (hour,min,sec)
}
get the value in single variable
let getTime = getTime()
now you can access the hour,min and seconds simply by "." ie.
print("hour:\(getTime.hour) min:\(getTime.min) sec:\(getTime.sec)")
You can do this easily with the KoGrid plugin for KnockoutJS.
<script type="text/javascript">
$(function () {
window.viewModel = {
myObsArray: ko.observableArray([
{ id: 1, firstName: 'John', lastName: 'Doe', createdOn: '1/1/2012', birthday: '1/1/1977', salary: 40000 },
{ id: 1, firstName: 'Jane', lastName: 'Harper', createdOn: '1/2/2012', birthday: '2/1/1976', salary: 45000 },
{ id: 1, firstName: 'Jim', lastName: 'Carrey', createdOn: '1/3/2012', birthday: '3/1/1985', salary: 60000 },
{ id: 1, firstName: 'Joe', lastName: 'DiMaggio', createdOn: '1/4/2012', birthday: '4/1/1991', salary: 70000 }
])
};
ko.applyBindings(viewModel);
});
</script>
<div data-bind="koGrid: { data: myObsArray }">
git clone --depth 1 --branch <tag_name> <repo_url>
Example
git clone --depth 1 --branch 0.37.2 https://github.com/apache/incubator-superset.git
<tag_name> : 0.37.2
<repo_url> : https://github.com/apache/incubator-superset.git
In HTML:
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />
In PHP:
if (isset($_POST["btnSubmit"])){
// "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
// "Delete" clicked
}
There are nice libraries which will handle everything and reduce your pain. For using it, just add two dependencies in gradle:
implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
After that, use dimens
like this:
android:layout_marginTop="@dimen/_80sdp"
I use the below mentioned process to convert equations to markdown. This works very well for me. Its very simple!!
Let's say, I want to represent matrix multiplication equation
Get the script for your formulae from here - https://csrgxtu.github.io/2015/03/20/Writing-Mathematic-Fomulars-in-Markdown/
My example: I wanted to represent Z(i,j)=X(i,k) * Y(k, j); k=1 to n
into a summation formulae.
Referencing the website, the script needed was => Z_i_j=\sum_{k=1}^{10} X_i_k * Y_k_j
Use URL encoder - https://www.urlencoder.org/ to convert the script to a valid url
My example:
Use this website to generate the image by copy-pasting the output from Step 2 in the "eq" request parameter - http://www.sciweavers.org/tex2img.php?eq=<b><i>paste-output-here</i></b>&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=
- My example:
http://www.sciweavers.org/tex2img.php?eq=Z_i_j=\sum_{k=1}^{10}%20X_i_k%20*%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=
Reference image using markdown syntax - ![alt text](enter url here)
- Copy this in your markdown and you are good to go:
![Z(i,j)=X(i,k) * Y(k, j); k=1 to n](http://www.sciweavers.org/tex2img.php?eq=Z_i_j%3D%5Csum_%7Bi%3D1%7D%5E%7B10%7D%20X_i_k%20%2A%20Y_k_j&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)
No need to use any tool for that
Shift + Tab = Shift text right to left
As rcar says, you can't without losing some quality, the best you can do in c# is:
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
You can pass new value like this
setExampleState({...exampleState, masterField2: {
fieldOne: "c",
fieldTwo: {
fieldTwoOne: "d",
fieldTwoTwo: "e"
}
},
}})
You can use also:
Collections.singletonList(Something.values())
public class MyException extends Exception {
// special exception code goes here
}
Throw it as:
throw new MyException ("Something happened")
Catch as:
catch (MyException e)
{
// something
}
There is an easy way to get Jobs' Owners info from multiple instances by PowerShell:
Run the script in your PowerShell ISE:
Loads SQL Powerhell SMO and commands:
Import-Module SQLPS -disablenamechecking
BUild list of Servers manually (this builds an array list):
$SQLServers = "SERVERNAME\INSTANCE01","SERVERNAME\INSTANCE02","SERVERNAME\INSTANCE03";
$SysAdmins = $null;
foreach($SQLSvr in $SQLServers)
{
## - Add Code block:
$MySQL = new-object Microsoft.SqlServer.Management.Smo.Server $SQLSvr;
DIR SQLSERVER:\SQL\$SQLSvr\JobServer\Jobs| FT $SQLSvr, NAME, OWNERLOGINNAME -Auto
## - End of Code block
}
Just write
System.Diagnostics.Process.Start(@"file path");
example
System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...
And shell will run associated program reading it from the registry, like usual double click does.
Use extend to add a list comprehension to the end.
l.extend([x for i in range(100)])
See the Python docs for more information.
It's not possible with CSS3. There is a proposed CSS4 selector, $
, to do just that, which could look like this (Selecting the li
element):
ul $li ul.sub { ... }
See the list of CSS4 Selectors here.
As an alternative, with jQuery, a one-liner you could make use of would be this:
$('ul li:has(ul.sub)').addClass('has_sub');
You could then go ahead and style the li.has_sub
in your CSS.
You can use http://pingdom.com/ to check your app; if done every minute or so, heroku won't idle your app and won't need to spin-up.
Updated for Swift 3
Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController
and the storyboard ID to secondVC
.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Source:
Try fixing the capitalization. onclick
instead of onClick
Reference: Mozilla Developer Docs
First, close all instances of Google Chrome. There should be no instances of chrome.exe
running in the Windows Task Manager. Then
%LOCALAPPDATA%\Google\Chrome\User Data\Default\
..txt
). This will serve as a backup, should something go wrong.window_placement
. Under window_placement
you will see things like "bottom", "left", "right", etc. with numbers after them.You will need to play around with these numbers to get your desired window size and placement. When finished, save this file with the name "Preferences" again with no extension. This will overwrite the existing Preferences file. Open Chrome and see how you did. If you're not satisfied with the size and placement, close Chrome and change the numbers in the Preferences file until you get what you want.
To inspect your localStorage items you may type console.log(localStorage);
in your javascript console (firebug for example or in new FF versions the shipped js console).
You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:
localStorage.clear();
I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:$('#selectorid').val()
You can do this using jQuery.offset()
and jQuery.animate()
.
Check out the jsFiddle Demonstration.
function scrollToAnchor(aid){
var aTag = $("a[name='"+ aid +"']");
$('html,body').animate({scrollTop: aTag.offset().top},'slow');
}
scrollToAnchor('id3');
Step: 1 Your Html, First Store the value in your localstorage using javascript then add the line like below ,this is where you going to display the value in your html, my example is based on boostrap :
<label for="stringName" class="cols-sm-2 control-
label">@Html.Hidden("stringName", "")</label>
Step:2 Javascript
$('#stringName').replaceWith(localStorage.getItem("itemName"));
You can use Newtonsoft.Json
just add Newtonsoft.dll
to your project and use below script
using System;
using Newtonsoft.Json;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
[Serializable]
public class Person
{
public string id;
public string name;
}
public Person[] person;
private void Start()
{
var myjson = JsonConvert.SerializeObject(person);
print(myjson);
}
}
another solution is using JsonHelper
using System;
using Newtonsoft.Json;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
[Serializable]
public class Person
{
public string id;
public string name;
}
public Person[] person;
private void Start()
{
var myjson = JsonHelper.ToJson(person);
print(myjson);
}
}
For completeness sake, here is the pathlib
solution for python 3.2+:
>>> from pathlib import PureWindowsPath
>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c',
... 'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [PureWindowsPath(path).name for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']
This works on both Windows and Linux.
another.obj = [obj copyWithZone: zone];
I think, that this line causes memory leak, because you access to obj
through property which is (I assume) declared as retain
. So, retain count will be increased by property and copyWithZone
.
I believe it should be:
another.obj = [[obj copyWithZone: zone] autorelease];
or:
SomeOtherObject *temp = [obj copyWithZone: zone];
another.obj = temp;
[temp release];
This may be prove helpful to few people -
// MARK: - KVO
var observedPaths: [String] = []
func observeKVO(keyPath: String) {
observedPaths.append(keyPath)
addObserver(self, forKeyPath: keyPath, options: [.old, .new], context: nil)
}
func unObserveKVO(keyPath: String) {
if let index = observedPaths.index(of: keyPath) {
observedPaths.remove(at: index)
}
removeObserver(self, forKeyPath: keyPath)
}
func unObserveAllKVO() {
for keyPath in observedPaths {
removeObserver(self, forKeyPath: keyPath)
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if let keyPath = keyPath {
switch keyPath {
case #keyPath(camera.iso):
slider.value = camera.iso
default:
break
}
}
}
I had used KVO in this way in Swift 3. You can use this code with few changes.
Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
Try to add empty View
inside horizontal LinearLayout
before element that you want to see right, e.g.:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<View
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
To explain the two concepts by example, imagine you have an order entry system for a bookstore. The mapping of orders to items is many to many (n:m) because each order can have multiple items, and each item can be ordered by multiple orders. On the other hand, a lookup between customers and order is one to many (1:n) because a customer can place more than one order, but an order is never for more than one customer.
Why would you want to clone? Creating a new list usually makes more sense.
List<String> strs;
...
List<String> newStrs = new ArrayList<>(strs);
Job done.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]
Only correct and W3C compatible answer is: <html>
object and rem. transformation doesn't work correctly if you scale down (for example scale(0.5).
Use:
html
{
font-size: 1mm; /* or your favorite unit */
}
and use in your code "rem" unit (including styles for <body>
) instead metric units. "%"s without changes. For all backgrounds set background-size. Define font-size for body, that is inherited by other elements.
if any condition occurs that shall fire zoom other than 1.0 change the font-size for tag (via CSS or JS).
for example:
@media screen and (max-width:320pt)
{
html
{
font-size: 0.5mm;
}
}
This makes equivalent of zoom:0.5 without problems in JS with clientX and positioning during drag-drop events.
Don't use "rem" in media queries.
You really doesn't need zoom, but in some cases it can faster method for existing sites.
To directly answer your question if you want to return a view that belongs to another controller you simply have to specify the name of the view and its folder name.
public class CommentsController : Controller
{
public ActionResult Index()
{
return View("../Articles/Index", model );
}
}
and
public class ArticlesController : Controller
{
public ActionResult Index()
{
return View();
}
}
Also, you're talking about using a read and write method from one controller in another. I think you should directly access those methods through a model rather than calling into another controller as the other controller probably returns html.
<ng-container>
to the rescueThe Angular
<ng-container>
is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.(...)
The
<ng-container>
is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block:if (someCondition) { statement1; statement2; statement3; }
Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The
<ng-container>
satisfies a similar need in Angular templates.
According to this pull request :
<ng-container>
is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node.
<ng-container>
is rendered as an HTML comment.
so this angular template :
<div>
<ng-container>foo</ng-container>
<div>
will produce this kind of output :
<div>
<!--template bindings={}-->foo
<div>
So ng-container
is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo"
) in your application but don't want to wrap them with another element.
<div>
<ng-container *ngIf="true">
<h2>Title</h2>
<div>Content</div>
</ng-container>
</div>
will then produce :
<div>
<h2>Title</h2>
<div>Content</div>
</div>
To check whether select box has any values:
if( $('#fruit_name').has('option').length > 0 ) {
To check whether selected value is empty:
if( !$('#fruit_name').val() ) {
I got similar error while using in-app-purchase in android. My mistake is I used wrong purchase id while instantiating the purchases.
public static final String PRODUCT_ID_ASTRO_Match = "android.test.product";//wrong id not in play store dev console
Replaced it with:
public static final String PRODUCT_ID_ASTRO_Match = "android.test.purchased";
and it worked.
You can find keyboard shortcuts from
File > Preferences > Keyboard Shortcuts
Default Keyboard Shortcuts are,
Copy Lines Down Action : shift+alt+down
Copy Lines Up Action : shift+alt+up
Move Lines Up Action : alt+up
Move Lines Down Action : alt+down
Or you can override the keyboard shortcuts from
File > Preferences > Keyboard Shortcuts
And editing the keybindings.json
Example:
[
{
"key": "ctrl+d",
"command": "editor.action.copyLinesDownAction",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+up",
"command": "editor.action.moveLinesUpAction",
"when": "editorTextFocus"
},
{
"key": "ctrl+shift+down",
"command": "editor.action.moveLinesDownAction",
"when": "editorTextFocus"
}
]
You may be forgetting something. Before #include <iostream>
, write #include <stdafx.h>
and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."
If you're using Apache POI 4.x, you can do that with:
Cell c = row.getCell(3);
if (c == null || c.getCellType() == CellType.Blank) {
// This cell is empty
}
For older Apache POI 3.x versions, which predate the move to the CellType
enum, it's:
Cell c = row.getCell(3);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// This cell is empty
}
Don't forget to check if the Row
is null though - if the row has never been used with no cells ever used or styled, the row itself might be null!
To auto indent on Sublime text 3 with a key bind try going to
Preferences > Key Bindings - users
And adding this code between the square brackets
{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}
it sets shift + alt + f to be your full page auto indent.
Source here
Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.
As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:
Here is an example depicting both options:
Sub PrintArrayIn1Cell(myArr As Variant, cell As Range) cell = Join(myArr, ",") End Sub Sub PrintArrayAsRange(myArr As Variant, cell As Range) cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr End Sub Sub TestPrintArrayIntoSheet() '2dArrayToSheet Dim arr As Variant arr = Split("a b c", " ") 'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c): PrintArrayIn1Cell arr, [A1] 'Printing in SEPARATE-CELLS: To print array-elements in separate cells: Dim arr2D As Variant arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array PrintArrayAsRange arr2D, Range("B1:B3") End Sub
Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.
HTH
I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.
$(function () {
$('#whitelist_add').keyup(function () {
if ($(this).val() == '') { //Check to see if there is any text entered
//If there is no text within the input, disable the button
$('.whitelistCheck').attr('disabled', 'disabled');
} else {
// Domain name regular expression
var regex = new RegExp("^([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
if (regex.test($(this).val())) {
// Domain looks OK
//alert("Successful match");
$('.whitelistCheck').removeAttr('disabled');
} else {
// Domain is NOT OK
//alert("No match");
$('.whitelistCheck').attr('disabled', 'disabled');
}
}
});
});
HTML FORM:
<form action="domain_management.php" method="get">
<input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
<button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>
Please use !statusCheck.equals("success")
instead of !=
.
Here are more details.
As I wrote in my comment, the solution to your problem is to write the following:
Set hyperLinkText = hprlink.Range
Set
is needed because TextRange
is a class, so hyperLinkText
is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.
ECMAScript 6 introduced String.prototype.includes
:
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
includes
doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf
, which returns -1 when a substring cannot be found:
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
I have the same problem: I have to make a specific .txt file for bank payments out of an excel file. The .txt file must not be delimeted by any character, because the standard requires a certain number of commas after each mandatory field. The easiest way of doing it is to copy the contect of the excel file and paste it in notepad.
In Rails 3.1, you should use the query interface:
update and update_all are the operation you need.
See details here: http://m.onkey.org/active-record-query-interface
You can even set a separate right margin for HTML. Under the specified path:
File >> Settings >> Editor >> Code Style >> HTML >> Other Tab >> Right margin (columns)
This is very useful because generally HTML and JS may be usually long in one line than Python. :)
Try using Web API HttpClient
static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://domain.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP POST
var obj = new MyObject() { Str = "MyString"};
response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
if (response.IsSuccessStatusCode)
{
response.//.. Contains the returned content.
}
}
}
You can find more details here Web API Clients
Maybe you should try
^[#;].*$
^
matches the beggining, $
the end.
C# supports some inherited covariance for event delegates, so a method like this:
void LowestCommonHander( object sender, EventArgs e ) { ... }
Can be used to subscribe to your event, no explicit cast required
gcInt.MyEvent += LowestCommonHander;
You can even use lambda syntax and the intellisense will all be done for you:
gcInt.MyEvent += (sender, e) =>
{
e. //you'll get correct intellisense here
};
Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt
). You can check where you are spooling by issuing spool
command.
General form is:
var ids = []; <= this is your array/collection
var csv = ids.join(",");
For your case you will have to adapt a little bit
The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <
)
select *
from xxx
where dates >= '20121026'
and dates < '20121028'
If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.
select *
from xxx
where CAST(dates as DATE) between '20121026' and '20121027'
This explicitly tells SQL Server that you are only interested in the DATE portion of the dates
column for comparison against the BETWEEN range.
If you wanna do it in case-insensitive way, this is better:
System.out.println(test.matches("^(?i)(https?|ftp)://.*$"));
Backtick Operator Backtick on php manual
You can also get this error when you have an infinite loop. Make sure that you don't have any unending, recursive self references.
There are lots of free tools that can do this.
I use PDFTK (a open source cross-platform command-line tool) for things like that.
In C++ NULL expands to 0 or 0L. See this quote from Stroustrup's FAQ:
Should I use NULL or 0?
In C++, the definition of NULL is 0, so there is only an aesthetic difference. I prefer to avoid macros, so I use 0. Another problem with NULL is that people sometimes mistakenly believe that it is different from 0 and/or not an integer. In pre-standard code, NULL was/is sometimes defined to something unsuitable and therefore had/has to be avoided. That's less common these days.
If you have to name the null pointer, call it nullptr; that's what it's called in C++11. Then, "nullptr" will be a keyword.
there is a case statement, but i think the below is more accurate/efficient/easier to read for what you want.
select
product
,coalesce(t4.price,t2.price, t3.price) as price
from table1 t1
left join table1 t2 on t1.product = t2.product and t2.customer =2
left join table1 t3 on t1.product = t3.product and t3.company =3
left join table1 t4 on t1.product = t4.product and t4.project =1
In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197
It is very simple to make a variable global in a class:
a = 0
class b():
global a
a = 10
>>> a
10
catch (Exception ex)
{
if (!(
ex is FormatException ||
ex is OverflowException))
{
throw;
}
Console.WriteLine("Hello");
}
I think you have to write some extra code. For example:
if 'MICHAEL89' in map(lambda name: name.upper(), USERNAMES):
...
In this case we are forming a new list with all entries in USERNAMES
converted to upper case and then comparing against this new list.
Update
As @viraptor says, it is even better to use a generator instead of map
. See @Nathon's answer.
The best practice for this, in my opinion is:
TimeUnit.DAYS.toMillis(1); // 1 day to milliseconds.
TimeUnit.MINUTES.toMillis(23); // 23 minutes to milliseconds.
TimeUnit.HOURS.toMillis(4); // 4 hours to milliseconds.
TimeUnit.SECONDS.toMillis(96); // 96 seconds to milliseconds.
I had a slight different solution to this problem. my PATH and JAVA_HOME were pointing to JDK12 in
C:\Program Files\Java
but execution of the command:
Java -version
gave the error:
Error: could not open `C:\ProgramFiles\Java\jre1.8.0_212\lib\amd64\jvm.cfg'
I had to delete a folder of executables (Java.exe, javaw.exe etc.) in a different directory than System32, as other answers here and blog posts have suggested. Instead I found the problem lied with executables found in:
C:\Program Files\Common Files\Oracle
as there was nothing Java related in
C:\Windows\System32
If you're having this issue and nothing is in System32, check this "common files" directory mentioned above for an oracle directory and delete it.
After, your PATH references should work fine!
You need to use JSONObject
like below:
String mJsonString = downloadFileFromInternet(urls[0]);
JSONObject jObject = null;
try {
jObject = new JSONObject(mJsonString);
}
catch (JSONException e) {
e.printStackTrace();
return false;
}
...
private String downloadFileFromInternet(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
new IllegalArgumentException("url is empty/null");
StringBuilder sb = new StringBuilder();
InputStream inStream = null;
try
{
url = urlEncode(url);
URL link = new URL(url);
inStream = link.openStream();
int i;
int total = 0;
byte[] buffer = new byte[8 * 1024];
while((i=inStream.read(buffer)) != -1)
{
if(total >= (1024 * 1024))
{
return "";
}
total += i;
sb.append(new String(buffer,0,i));
}
}
catch(Exception e )
{
e.printStackTrace();
return null;
}catch(OutOfMemoryError e)
{
e.printStackTrace();
return null;
}
return sb.toString();
}
private String urlEncode(String url)
{
if(url == null /*|| url.isEmpty() == true*/)
return null;
url = url.replace("[","");
url = url.replace("]","");
url = url.replaceAll(" ","%20");
return url;
}
Hope this helps you..
I think @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"
should work.
You need to write it like
string email = txtemail.Text;
Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is correct");
else
Response.Write(email + " is incorrect");
Be warned that this will fail if:
There is a subdomain after the @
symbol.
You use a TLD with a length greater than 3, such as .info
Destroys the session and will unset the req.session property. Once complete, the callback will be invoked.
↓ Secure way ↓ ?
req.session.destroy((err) => {
res.redirect('/') // will always fire after session is destroyed
})
↓ Unsecure way ↓ ?
req.logout();
res.redirect('/') // can be called before logout is done
For hide keyboard use Keyboard.dismiss() inside TextInput.
lets put it in this way:
actually Modulus operator does the same division but it does not care about the answer , it DOES CARE ABOUT reminder for example if you divide 7 to 5 ,
so , lets me take you through a simple example:
think 5 is a block, then for example we going to have 3 blocks in 15 (WITH Nothing Left) , but when that loginc comes to this kinda numbers {1,3,5,7,9,11,...} , here is where the Modulus comes out , so take that logic that i said before and apply it for 7 , so the answer gonna be that we have 1 block of 5 in 7 => with 2 reminds in our hand! that is the modulus!!!
but you were asking about 5 % 7 , right ?
so take the logic that i said , how many 7 blocks do we have in 5 ???? 0
so the modulus returns 0...
that's it ...
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Note: You can use memset with any character.
Example:
int arr[20];
memset(arr, 'A', sizeof(arr));
Also could be partially filled
int arr[20];
memset(&arr[5], 0, 10);
But be carefull. It is not limited for the array size, you could easily cause severe damage to your program doing something like this:
int arr[20];
memset(arr, 0, 200);
It is going to work (under windows) and zero memory after your array. It might cause damage to other variables values.
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release
I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:
But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:
This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).
Here we go... just copy the code to a module, it's ready to use
Private Type hashtable
key As Variant
value As Variant
End Type
Private GetErrMsg As String
Private Function CreateHashTable(htable() As hashtable) As Boolean
GetErrMsg = ""
On Error GoTo CreateErr
ReDim htable(0)
CreateHashTable = True
Exit Function
CreateErr:
CreateHashTable = False
GetErrMsg = Err.Description
End Function
Private Function AddValue(htable() As hashtable, key As Variant, value As Variant) As Long
GetErrMsg = ""
On Error GoTo AddErr
Dim idx As Long
idx = UBound(htable) + 1
Dim htVal As hashtable
htVal.key = key
htVal.value = value
Dim i As Long
For i = 1 To UBound(htable)
If htable(i).key = key Then Err.Raise 9999, , "Key [" & CStr(key) & "] is not unique"
Next i
ReDim Preserve htable(idx)
htable(idx) = htVal
AddValue = idx
Exit Function
AddErr:
AddValue = 0
GetErrMsg = Err.Description
End Function
Private Function RemoveValue(htable() As hashtable, key As Variant) As Boolean
GetErrMsg = ""
On Error GoTo RemoveErr
Dim i As Long, idx As Long
Dim htTemp() As hashtable
idx = 0
For i = 1 To UBound(htable)
If htable(i).key <> key And IsEmpty(htable(i).key) = False Then
ReDim Preserve htTemp(idx)
AddValue htTemp, htable(i).key, htable(i).value
idx = idx + 1
End If
Next i
If UBound(htable) = UBound(htTemp) Then Err.Raise 9998, , "Key [" & CStr(key) & "] not found"
htable = htTemp
RemoveValue = True
Exit Function
RemoveErr:
RemoveValue = False
GetErrMsg = Err.Description
End Function
Private Function GetValue(htable() As hashtable, key As Variant) As Variant
GetErrMsg = ""
On Error GoTo GetValueErr
Dim found As Boolean
found = False
For i = 1 To UBound(htable)
If htable(i).key = key And IsEmpty(htable(i).key) = False Then
GetValue = htable(i).value
Exit Function
End If
Next i
Err.Raise 9997, , "Key [" & CStr(key) & "] not found"
Exit Function
GetValueErr:
GetValue = ""
GetErrMsg = Err.Description
End Function
Private Function GetValueCount(htable() As hashtable) As Long
GetErrMsg = ""
On Error GoTo GetValueCountErr
GetValueCount = UBound(htable)
Exit Function
GetValueCountErr:
GetValueCount = 0
GetErrMsg = Err.Description
End Function
To use in your VB(A) App:
Public Sub Test()
Dim hashtbl() As hashtable
Debug.Print "Create Hashtable: " & CreateHashTable(hashtbl)
Debug.Print ""
Debug.Print "ID Test Add V1: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test Add V2: " & AddValue(hashtbl, "Hallo_0", "Testwert 0")
Debug.Print "ID Test 1 Add V1: " & AddValue(hashtbl, "Hallo.1", "Testwert 1")
Debug.Print "ID Test 2 Add V1: " & AddValue(hashtbl, "Hallo-2", "Testwert 2")
Debug.Print "ID Test 3 Add V1: " & AddValue(hashtbl, "Hallo 3", "Testwert 3")
Debug.Print ""
Debug.Print "Test 1 Removed V1: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 1 Removed V2: " & RemoveValue(hashtbl, "Hallo_1")
Debug.Print "Test 2 Removed V1: " & RemoveValue(hashtbl, "Hallo-2")
Debug.Print ""
Debug.Print "Value Test 3: " & CStr(GetValue(hashtbl, "Hallo 3"))
Debug.Print "Value Test 1: " & CStr(GetValue(hashtbl, "Hallo_1"))
Debug.Print ""
Debug.Print "Hashtable Content:"
For i = 1 To UBound(hashtbl)
Debug.Print CStr(i) & ": " & CStr(hashtbl(i).key) & " - " & CStr(hashtbl(i).value)
Next i
Debug.Print ""
Debug.Print "Count: " & CStr(GetValueCount(hashtbl))
End Sub
In recent versions of major browsers you can use backdrop-filter property.
HTML
<div>backdrop blur</div>
CSS
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
}
or if you need different background color for browsers without support:
div {
background-color: rgba(255, 255, 255, 0.9);
}
@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
div {
-webkit-backdrop-filter: blur(10px);
backdrop-filter: blur(10px);
background-color: rgba(255, 255, 255, 0.5);
}
}
Demo: JSFiddle
Docs: Mozilla Developer: backdrop-filter
Is it for me?: CanIUse
Mac OS : Big Sur
First Priority
sudo xcode-select --reset
sudo xcodebuild -license
Second Priority
xcode-select --install
I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.
You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)
>>> for field, values in fields.iteritems():
... print field, values
...
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']
Your problem was that you were looping over fields, which returns the keys of the dictionary.
>>> for field in fields:
... print field
...
first_names
last_name
The best way to enable the production mode for an Angular 2 application, is to use angular-cli and build the application with ng build --prod
. This will build the application with production profile. Using angular-cli has the benefit of being able to use development mode using ng serve
or ng build
while developing without altering the code all the time.
This should work:
string url = "http://example.com/file?a=1&b=2&c=string%20param";
string querystring = url.Substring(url.IndexOf('?'));
System.Collections.Specialized.NameValueCollection parameters =
System.Web.HttpUtility.ParseQueryString(querystring);
According to MSDN. Not the exact collectiontype you are looking for, but nevertheless useful.
Edit: Apparently, if you supply the complete url to ParseQueryString
it will add 'http://example.com/file?a' as the first key of the collection. Since that is probably not what you want, I added the substring to get only the relevant part of the url.
Or Simply you Can add
protected void onPreExecute() {
mDialog = ProgressDialog.show(mContext, "", "Saving changes...", true, false);
}
which will make the ProgressDialog
to not cancel-able
Complete instruction is as follow:
openssl pkcs12 -in myfile.pfx -nocerts -out private-key.pem -nodes
openssl pkcs12 -in myfile.pfx -nokeys -out certificate.pem
yum install -y ca-certificates
,
cp your-cert.pem /etc/pki/ca-trust/source/anchors/your-cert.pem
,
update-ca-trust
,
update-ca-trust force-enable
Hope to be useful
Solution I have json object which has data
[{"name":"Ata","email":"[email protected]"}]
You can use following approach to iterate through ng-repeat and use table format instead of list.
<div class="container" ng-controller="fetchdataCtrl">
<ul ng-repeat="item in numbers">
<li>
{{item.name}}: {{item.email}}
</li>
</ul>
</div>
Your model is null
because the way you're supplying the inputs to your form means the model binder has no way to distinguish between the elements. Right now, this code:
@foreach (var planVM in Model)
{
@Html.Partial("_partialView", planVM)
}
is not supplying any kind of index to those items. So it would repeatedly generate HTML output like this:
<input type="hidden" name="yourmodelprefix.PlanID" />
<input type="hidden" name="yourmodelprefix.CurrentPlan" />
<input type="checkbox" name="yourmodelprefix.ShouldCompare" />
However, as you're wanting to bind to a collection, you need your form elements to be named with an index, such as:
<input type="hidden" name="yourmodelprefix[0].PlanID" />
<input type="hidden" name="yourmodelprefix[0].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[0].ShouldCompare" />
<input type="hidden" name="yourmodelprefix[1].PlanID" />
<input type="hidden" name="yourmodelprefix[1].CurrentPlan" />
<input type="checkbox" name="yourmodelprefix[1].ShouldCompare" />
That index is what enables the model binder to associate the separate pieces of data, allowing it to construct the correct model. So here's what I'd suggest you do to fix it. Rather than looping over your collection, using a partial view, leverage the power of templates instead. Here's the steps you'd need to follow:
EditorTemplates
folder inside your view's current folder (e.g. if your view is Home\Index.cshtml
, create the folder Home\EditorTemplates
).PlanCompareViewModel.cshtml
.Now, everything you have in your partial view wants to go in that template:
@model PlanCompareViewModel
<div>
@Html.HiddenFor(p => p.PlanID)
@Html.HiddenFor(p => p.CurrentPlan)
@Html.CheckBoxFor(p => p.ShouldCompare)
<input type="submit" value="Compare"/>
</div>
Finally, your parent view is simplified to this:
@model IEnumerable<PlanCompareViewModel>
@using (Html.BeginForm("ComparePlans", "Plans", FormMethod.Post, new { id = "compareForm" }))
{
<div>
@Html.EditorForModel()
</div>
}
DisplayTemplates
and EditorTemplates
are smart enough to know when they are handling collections. That means they will automatically generate the correct names, including indices, for your form elements so that you can correctly model bind to a collection.
In Unix systems the end of a line is represented with a line feed (LF). In windows a line is represented with a carriage return (CR) and a line feed (LF) thus (CRLF). when you get code from git that was uploaded from a unix system they will only have an LF.
If you are a single developer working on a windows machine, and you don't care that git automatically replaces LFs to CRLFs, you can turn this warning off by typing the following in the git command line
git config core.autocrlf true
If you want to make an intelligent decision how git should handle this, read the documentation
Here is a snippet
Formatting and Whitespace
Formatting and whitespace issues are some of the more frustrating and subtle problems that many developers encounter when collaborating, especially cross-platform. It’s very easy for patches or other collaborated work to introduce subtle whitespace changes because editors silently introduce them, and if your files ever touch a Windows system, their line endings might be replaced. Git has a few configuration options to help with these issues.
core.autocrlf
If you’re programming on Windows and working with people who are not (or vice-versa), you’ll probably run into line-ending issues at some point. This is because Windows uses both a carriage-return character and a linefeed character for newlines in its files, whereas Mac and Linux systems use only the linefeed character. This is a subtle but incredibly annoying fact of cross-platform work; many editors on Windows silently replace existing LF-style line endings with CRLF, or insert both line-ending characters when the user hits the enter key.
Git can handle this by auto-converting CRLF line endings into LF when you add a file to the index, and vice versa when it checks out code onto your filesystem. You can turn on this functionality with the core.autocrlf setting. If you’re on a Windows machine, set it to true – this converts LF endings into CRLF when you check out code:
$ git config --global core.autocrlf true
If you’re on a Linux or Mac system that uses LF line endings, then you don’t want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. You can tell Git to convert CRLF to LF on commit but not the other way around by setting core.autocrlf to input:
$ git config --global core.autocrlf input
This setup should leave you with CRLF endings in Windows checkouts, but LF endings on Mac and Linux systems and in the repository.
If you’re a Windows programmer doing a Windows-only project, then you can turn off this functionality, recording the carriage returns in the repository by setting the config value to false:
$ git config --global core.autocrlf false
public static void main(String[] args) {
int[][] matrix = {
{ 1, 2, 5 },
{ 3, 4, 6 },
{ 7, 8, 9 }
};
System.out.println(" ** Matrix ** ");
for (int rows = 0; rows < 3; rows++) {
System.out.println("\n");
for (int columns = 0; columns < matrix[rows].length; columns++) {
System.out.print(matrix[rows][columns] + "\t");
}
}
}
This works,add a new line in for loop of the row. When the first row will be done printing the code will jump in new line.
The List<>
class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
...List "Represents a strongly typed list of objects that can be accessed by index."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your Remove()
will move all of the other items down one place before the call to Insert()
.
Can you boil your code down to something small enough to post?
I've come up with a javascript-heavy way to achieve a readonly state for check boxes and radio buttons. It is tested against current versions of Firefox, Opera, Safari, Google Chrome, as well as current and previous versions of IE (down to IE7).
Why not simply use the disabled property you ask? When printing the page, disabled input elements come out in a gray color. The customer for which this was implemented wanted all elements to come out the same color.
I'm not sure if I'm allowed to post the source code here, as I developed this while working for a company, but I can surely share the concepts.
With onmousedown events, you can read the selection state before the click action changes it. So you store this information and then restore these states with an onclick event.
<input id="r1" type="radio" name="group1" value="r1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="r2" type="radio" name="group1" value="r2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="r3" type="radio" name="group1" value="r3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 3</input>
<input id="c1" type="checkbox" name="group2" value="c1" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 1</input>
<input id="c2" type="checkbox" name="group2" value="c2" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);">Option 2</input>
<input id="c3" type="checkbox" name="group2" value="c3" onmousedown="storeSelectedRadiosForThisGroup(this.name);" onclick="setSelectedStateForEachElementOfThisGroup(this.name);" checked="checked">Option 3</input>
The javascript portion of this would then work like this (again only the concepts):
var selectionStore = new Object(); // keep the currently selected items' ids in a store
function storeSelectedRadiosForThisGroup(elementName) {
// get all the elements for this group
var radioOrSelectGroup = document.getElementsByName(elementName);
// iterate over the group to find the selected values and store the selected ids in the selectionStore
// ((radioOrSelectGroup[i].checked == true) tells you that)
// remember checkbox groups can have multiple checked items, so you you might need an array for the ids
...
}
function setSelectedStateForEachElementOfThisGroup(elementName) {
// iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
...
// make sure you return false here
return false;
}
You can now enable/disable the radio buttons/checkboxes by changing the onclick and onmousedown properties of the input elements.
Answer in short: (search your situation)
The subversion book is an excellent source of information on strategies for laying out your repository, branching and tagging.
See also:
I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
As of now (Android Studio v0.8.6) it's quite simple. Here are the steps to create a "Hello world" type app:
Download the Android NDK and put the root folder somewhere sane -- in the same location as the SDK folder, perhaps.
Add the following to your local.properties
file:
ndk.dir=<path-to-ndk>
Add the following to your build.gradle file inside of the defaultConfig
closure, right after the versionName
line: ndk { moduleName="hello-world" }
In your app module's main
directory, create a new folder called jni
.
In that folder, create a file called hello-world.c
, which you'll see below.
See the example Activity
code below for an example of how to call a method (or is it a function?) in hello-world.c
.
hello-world.c
#include <string.h>
#include <jni.h>
jstring
Java_me_mattlogan_ndktest_MainActivity_stringFromJNI(JNIEnv* env, jobject thiz)
{
return (*env)->NewStringUTF(env, "Hello world!");
}
MainActivity.java
public class MainActivity extends Activity {
static {
System.loadLibrary("hello-world");
}
public native String stringFromJNI();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String testString = stringFromJNI();
TextView mainText = (TextView) findViewById(R.id.main_text);
mainText.setText(testString);
}
}
build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "me.mattlogan.ndktest"
minSdkVersion 15
targetSdkVersion 20
versionCode 1
versionName "1.0"
ndk {
moduleName "hello-world"
}
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
Find the full source code of a very similar app here (minus the NDK).
The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -
onclick
method on anchor tag which would actually do the real job.<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID',
oauth : true,
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'public_profile,email'
});
}
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.
Or if one want to use lambda
function in the apply
function:
data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
putting a background of @android:drawable/dialog_holo_light_frame
, gives shadow but you can't change background color nor border style, so it's better to benefit from the shadow of it, while still be able to put a background via layer-list
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!--the shadow comes from here-->
<item
android:bottom="0dp"
android:drawable="@android:drawable/dialog_holo_light_frame"
android:left="0dp"
android:right="0dp"
android:top="0dp">
</item>
<item
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp">
<!--whatever you want in the background, here i preferred solid white -->
<shape android:shape="rectangle">
<solid android:color="@android:color/white" />
</shape>
</item>
</layer-list>
save it in the drawable folder under say shadow.xml
to assign it to a view, in the xml layout file set the background of it
android:background="@drawable/shadow"
Thought I'd share this code snippet that I've used before, this adds multiple addresses via Geocode and adds these addresses as Markers...
var addressesArray = [_x000D_
'Address Str.No, Postal Area/city',_x000D_
//follow this structure_x000D_
]_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
center: {_x000D_
lat: 12.7826,_x000D_
lng: 105.0282_x000D_
},_x000D_
zoom: 6,_x000D_
gestureHandling: 'cooperative'_x000D_
});_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
for (i = 0; i < addressArray.length; i++) {_x000D_
var address = addressArray[i];_x000D_
geocoder.geocode({_x000D_
'address': address_x000D_
}, function(results, status) {_x000D_
if (status === 'OK') {_x000D_
var marker = new google.maps.Marker({_x000D_
map: map,_x000D_
position: results[0].geometry.location,_x000D_
center: {_x000D_
lat: 12.7826,_x000D_
lng: 105.0282_x000D_
},_x000D_
});_x000D_
} else {_x000D_
alert('Geocode was not successful for the following reason: ' + status);_x000D_
}_x000D_
});_x000D_
}
_x000D_
As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:
#content {
display: table;
}
#pageFooter {
display: table-footer-group;
}
#pageFooter:after {
counter-increment: page;
content: counter(page);
}
And the HTML code is:
<div id="content">
<div id="pageFooter">Page </div>
multi-page content here...
</div>
This way you can customize your page number by editing parametrs to #pageFooter. My example:
#pageFooter:after {
counter-increment: page;
content:"Page " counter(page);
left: 0;
top: 100%;
white-space: nowrap;
z-index: 20;
-moz-border-radius: 5px;
-moz-box-shadow: 0px 0px 4px #222;
background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);
}
This trick worked for me fine. Hope it will help you.
I had the duplicate definition of connection string in my Project Cms.And the Context class is named:CmsContext
In my case, the problem was solved, as I changed the connectionsting in Web.config as follow:in first one name is CmsContext and it's related to main project .in second one name is DefaultConnection and it's related to Identity
<add name="CmsContext" providerName="System.Data.SqlClient" connectionString="Data Source=DESKTOP-2NQSP1P\SQLEXPRESS; Initial Catalog=CmsDB;Integrated Security=True;" />
</connectionStrings>
Try this:
ioreg -p IOUSB -l -b | grep -E "@|PortNum|USB Serial Number"
To change your application to a different built-in theme, just add this line under application tag in your app's manifest.xml
file.
Example:
<application
android:theme="@android:style/Theme.Holo"/>
<application
android:theme="@android:style/Theme.Holo.Light"/>
<application
android:theme="@android:style/Theme.Black"/>
<application
android:theme="@android:style/Theme.DeviceDefault"/>
If you set style to DeviceDefault it will require min SDK version 14, but if you won't add a style, it will set to the device default anyway.
<uses-sdk
android:minSdkVersion="14"/>
The #define
is part of the preprocessor language for C and C++. When they're used in code, the compiler just replaces the #define
statement with what ever you want. For example, if you're sick of writing for (int i=0; i<=10; i++)
all the time, you can do the following:
#define fori10 for (int i=0; i<=10; i++)
// some code...
fori10 {
// do stuff to i
}
If you want something more generic, you can create preprocessor macros:
#define fori(x) for (int i=0; i<=x; i++)
// the x will be replaced by what ever is put into the parenthesis, such as
// 20 here
fori(20) {
// do more stuff to i
}
It's also very useful for conditional compilation (the other major use for #define
) if you only want certain code used in some particular build:
// compile the following if debugging is turned on and defined
#ifdef DEBUG
// some code
#endif
Most compilers will allow you to define a macro from the command line (e.g. g++ -DDEBUG something.cpp
), but you can also just put a define in your code like so:
#define DEBUG
Some resources:
When you call a function, a new "namespace" is allocated on the stack. That's how functions can have local variables. As functions call functions, which in turn call functions, we keep allocating more and more space on the stack to maintain this deep hierarchy of namespaces.
To curb programs using massive amounts of stack space, a limit is usually put in place via ulimit -s
. If we remove that limit via ulimit -s unlimited
, our programs will be able to keep gobbling up RAM for their evergrowing stack until eventually the system runs out of memory entirely.
int eat_stack_space(void) { return eat_stack_space(); }
// If we compile this with no optimization and run it, our computer could crash.
Usually, using a ton of stack space is accidental or a symptom of very deep recursion that probably should not be relying so much on the stack. Thus the stack limit.
Impact on performace is minor but does exist. Using the time
command, I found that eliminating the stack limit increased performance by a few fractions of a second (at least on 64bit Ubuntu).
Simple way:
directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)
You'll have to use JS to open the popup, though you can put it on the page conditionally with PHP, you're right that you'll have to use a JavaScript function.
This can be due to byte alignment and padding so that the structure comes out to an even number of bytes (or words) on your platform. For example in C on Linux, the following 3 structures:
#include "stdio.h"
struct oneInt {
int x;
};
struct twoInts {
int x;
int y;
};
struct someBits {
int x:2;
int y:6;
};
int main (int argc, char** argv) {
printf("oneInt=%zu\n",sizeof(struct oneInt));
printf("twoInts=%zu\n",sizeof(struct twoInts));
printf("someBits=%zu\n",sizeof(struct someBits));
return 0;
}
Have members who's sizes (in bytes) are 4 bytes (32 bits), 8 bytes (2x 32 bits) and 1 byte (2+6 bits) respectively. The above program (on Linux using gcc) prints the sizes as 4, 8, and 4 - where the last structure is padded so that it is a single word (4 x 8 bit bytes on my 32bit platform).
oneInt=4
twoInts=8
someBits=4
Found the solution after some searching.
You need to add a <meta>
tag in your <head>
containing name="theme-color"
, with your HEX code as the content value. For example:
<meta name="theme-color" content="#999999" />
If the android device has native dark-mode
enabled, then this meta
tag is ignored.
Chrome for Android does not use the color on devices with native
dark-mode
enabled.
We now have seamless integration to unity with Github to Unity extension... https://unity.github.com/
The new GitHub for Unity extension brings the GitHub workflow and more to Unity, providing support for large files with Git LFS and file locking.
At the time of writing the project is in alpha, but is still usable for personal projects.
This may help:
if (cbProhibitEditPW.isChecked()) { // disable editing password
editTextPassword.setFocusable(false);
editTextPassword.setFocusableInTouchMode(false); // user touches widget on phone with touch screen
editTextPassword.setClickable(false); // user navigates with wheel and selects widget
isProhibitEditPassword= true;
} else { // enable editing of password
editTextPassword.setFocusable(true);
editTextPassword.setFocusableInTouchMode(true);
editTextPassword.setClickable(true);
isProhibitEditPassword= false;
}
On MacOS 10.11 with Firefox and a German keyboard layout it is Ctrl + ?
I'll give a slightly advanced answer. In Python, functions are first-class objects. This means they can be "dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have."
Calling a function/class instance in Python means invoking the __call__
method of that object. For old-style classes, class instances are also callable but only if the object which creates them has a __call__
method. The same applies for new-style classes, except there is no notion of "instance" with new-style classes. Rather they are "types" and "objects".
As quoted from the Python 2 Data Model page, for function objects, class instances(old style classes), and class objects(new-style classes), "x(arg1, arg2, ...)
is a shorthand for x.__call__(arg1, arg2, ...)
".
Thus whenever you define a function with the shorthand def funcname(parameters):
you are really just creating an object with a method __call__
and the shorthand for __call__
is to just name the instance and follow it with parentheses containing the arguments to the call. Because functions are first class objects in Python, they can be created on the fly with dynamic parameters (and thus accept dynamic arguments). This comes into handy with decorator functions/classes which you will read about later.
For now I suggest reading the Official Python Tutorial.
ok so my solution for this was:
this.arrayWeNeed.DoWhatWeNeedWithThisArray();
const tempArray = [...arrayWeNeed];
this.arrayWeNeed = [];
this.arrayWeNeed = tempArray;
And this trigger me ngOnChanges
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
See below link : http://www.asciitable.com/
public static char randomSeriesForThreeCharacter() {
Random r = new Random();
char random_3_Char = (char) (48 + r.nextInt(47));
return random_3_Char;
}
Now you can generate a character at one time of calling.
PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>"
inside a <script>
tag is considered unsafe.
This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES
flag but most developers will not use this since the original result is already valid JSON.
You can better achieve it by using the DrawableCompat like this:
Drawable backgroundDrawable = view.getBackground();
DrawableCompat.setTint(backgroundDrawable, newColor);
**check this out**
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).keypress(function(e)
{
var keynum;
if(window.event)
{ // IE
keynum = e.keyCode;
}
else if(e.which)
{
// Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
var unicode=e.keyCode? e.keyCode : e.charCode;
alert(unicode);
});
});
</script>
</head>
<body>
<input type="text"></input>
</body>
</html>
The following code clear all the form and it's fields will be empty. If you want to clear only a particular form if the page is having more than one form, please mention the id or class of the form
$("body").find('form').find('input, textarea').val('');
So many answers, and not a single one explains the WHY? (which Giovanni explicitly asked)...
.NET generics do not act like C++ templates. In C++ templates, overload resolution occurs after the actual template parameters are known.
In .NET generics (including C#), overload resolution occurs without knowing the actual generic parameters. The only information the compiler can use to choose the function to call comes from type constraints on the generic parameters.
The absolute path to the directory where
./manage.py collectstatic
will collect static files for deployment. Example:STATIC_ROOT="/var/www/example.com/static/"
now the command ./manage.py collectstatic
will copy all the static files(ie in static folder in your apps, static files in all paths) to the directory /var/www/example.com/static/
. now you only need to serve this directory on apache or nginx..etc.
The
URL
of which the static files inSTATIC_ROOT
directory are served(by Apache or nginx..etc). Example:/static/
orhttp://static.example.com/
If you set STATIC_URL = 'http://static.example.com/'
, then you must serve the STATIC_ROOT
folder (ie "/var/www/example.com/static/"
) by apache or nginx at url 'http://static.example.com/'
(so that you can refer the static file '/var/www/example.com/static/jquery.js'
with 'http://static.example.com/jquery.js'
)
Now in your django-templates, you can refer it by:
{% load static %}
<script src="{% static "jquery.js" %}"></script>
which will render:
<script src="http://static.example.com/jquery.js"></script>
Some of the solutions here will not prevent a back event from occurring - they let a back event happen (and data held about the page in the browsers memory is lost) and then they play a forward event to try and hide the fact that a back event just happened. Which is unsuccessful if the page held transient state.
I wrote this solution for React (when react router is not being used), which is based on vrfvr's answer.
It will truly stop the back button from doing anything unless the user confirms a popup:
const onHashChange = useCallback(() => {
const confirm = window.confirm(
'Warning - going back will cause you to loose unsaved data. Really go back?',
);
window.removeEventListener('hashchange', onHashChange);
if (confirm) {
setTimeout(() => {
window.history.go(-1);
}, 1);
} else {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
}
}, []);
useEffect(() => {
window.location.hash = 'no-back';
setTimeout(() => {
window.addEventListener('hashchange', onHashChange);
}, 1);
return () => {
window.removeEventListener('hashchange', onHashChange);
};
}, []);
This OTN-thread contains several ways to do string aggregation, including a performance comparison: http://forums.oracle.com/forums/message.jspa?messageID=1819487#1819487
After trying all the above and using the answer from @Aaron Hall, I was getting memory errors for a ~90 Mb file on a computer running Window 10, 8 Gb RAM and Python 3.5 32-bit. I was recommended by a colleague to use numpy
instead and it works wonders.
By far, the fastest to read an entire binary file (that I have tested) is:
import numpy as np
file = "binary_file.bin"
data = np.fromfile(file, 'u1')
Multitudes faster than any other methods so far. Hope it helps someone!
Sharepoint Lists automatically have an column with "ID" which auto increments. You simply need to select this column from the "modify view" screen to view it.
Add this line above you Query
SET IDENTITY_INSERT tbl_content ON
the point can be if you are not using valid login for linked server. Problem is on destination server side.
There are few steps to try:
Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]
recreate login on destination server used by linked server.
Backup table and recreate it.
2nd resolved my issue with "The value violated the integrity constraints for the column.".
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
json might not be the best choice for on-disk formats; The trouble it has with appending data is a good example of why this might be. Specifically, json objects have a syntax that means the whole object must be read and parsed in order to understand any part of it.
Fortunately, there are lots of other options. A particularly simple one is CSV; which is supported well by python's standard library. The biggest downside is that it only works well for text; it requires additional action on the part of the programmer to convert the values to numbers or other formats, if needed.
Another option which does not have this limitation is to use a sqlite database, which also has built-in support in python. This would probably be a bigger departure from the code you already have, but it more naturally supports the 'modify a little bit' model you are apparently trying to build.
I solved this problem by adding C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0\System.Runtime.Serialization.dll in the reference
There are multiple ways to do this and from your question it's nor clear what you need.
1. If you need environment variable to be defined PER TASK ONLY, you do this:
- hosts: dev tasks: - name: Echo my_env_var shell: "echo $MY_ENV_VARIABLE" environment: MY_ENV_VARIABLE: whatever_value - name: Echo my_env_var again shell: "echo $MY_ENV_VARIABLE"
Note that MY_ENV_VARIABLE
is available ONLY for the first task, environment
does not set it permanently on your system.
TASK: [Echo my_env_var] *******************************************************
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": "whatever_value"}
TASK: [Echo my_env_var again] *************************************************
changed: [192.168.111.222] => {"changed": true, "cmd": "echo $MY_ENV_VARIABLE", ... "stdout": ""}
Hopefully soon using environment
will also be possible on play level, not only task level as above.
There's currently a pull request open for this feature on Ansible's GitHub: https://github.com/ansible/ansible/pull/8651
UPDATE: It's now merged as of Jan 2, 2015.
2. If you want permanent environment variable + system wide / only for certain user
You should look into how you do it in your Linux distribution / shell, there are multiple places for that. For example in Ubuntu you define that in files like for example:
~/.profile
/etc/environment
/etc/profile.d
directoryYou will find Ubuntu docs about it here: https://help.ubuntu.com/community/EnvironmentVariables
After all for setting environment variable in ex. Ubuntu you can just use lineinfile
module from Ansible and add desired line to certain file. Consult your OS docs to know where to add it to make it permanent.
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
I found the solution for this problem, you don't have to delete the global.asax, as it contains some valuable info for your proyect to run smoothly, instead have a look at your controller's name, in my case, my controller was named something as MyController.cs and in the global.asax it's trying to reference a Home Controller.
Look for this lines in the global asax
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
in my case i had to get like this to work
new { controller = "My", action = "Index", id = UrlParameter.Optional }
m <- matrix(1:20, ncol = 4)
colnames(m) <- letters[1:4]
The following command will select the first row of the matrix above.
subset(m, m[,4] == 16)
And this will select the last three.
subset(m, m[,4] > 17)
The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with
mf <- data.frame(m)
Then you can select with
mf[ mf$a == 16, ]
Or, you could use the subset command.
If you don't want to use NPOI.Mapper, then I'd advise you to check out this solution - it handles reading excel cell into various type and also has a simple import helper: https://github.com/hidegh/NPOI.Extensions
var data = sheet.MapTo<OrderDetails>(true, rowMapper =>
{
// map singleItem
return new OrderDetails()
{
Date = rowMapper.GetValue<DateTime>(SheetColumnTitles.Date),
// use reusable mapper for re-curring scenarios
Region = regionMapper(rowMapper.GetValue<string>(SheetColumnTitles.Region)),
Representative = rowMapper.GetValue<string>(SheetColumnTitles.Representative),
Item = rowMapper.GetValue<string>(SheetColumnTitles.Item),
Units = rowMapper.GetValue<int>(SheetColumnTitles.Units),
UnitCost = rowMapper.GetValue<decimal>(SheetColumnTitles.UnitCost),
Total = rowMapper.GetValue<decimal>(SheetColumnTitles.Total),
// read date and total as string, as they're displayed/formatted on the excel
DateFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Date),
TotalFormatted = rowMapper.GetValue<string>(SheetColumnTitles.Total)
};
});
Setting time interval to check for fix is not a good choice.. i noticed that onLocationChanged is not called if you are not moving.. what is understandable since location is not changing :)
Better way would be for example:
// To delete all the folders and files within folders recursively
File sdDir = new File(sdPath);
if(sdDir.exists())
deleteRecursive(sdDir);
// Delete any folder on a device if exists
void deleteRecursive(File fileOrDirectory) {
if (fileOrDirectory.isDirectory())
for (File child : fileOrDirectory.listFiles())
deleteRecursive(child);
fileOrDirectory.delete();
}
One way is to use DBMS_ASSERT.SQL_OBJECT_NAME :
This function verifies that the input parameter string is a qualified SQL identifier of an existing SQL object.
DECLARE
V_OBJECT_NAME VARCHAR2(30);
BEGIN
BEGIN
V_OBJECT_NAME := DBMS_ASSERT.SQL_OBJECT_NAME('tab1');
EXECUTE IMMEDIATE 'DROP TABLE tab1';
EXCEPTION WHEN OTHERS THEN NULL;
END;
END;
/
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
If I understand correctly, you want Base functionality to always be performed, while a piece of it should be left to implementations.
You might get helped by the 'template method' design pattern.
Base = function() {}
Base.prototype.do = function() {
// .. prologue code
this.impldo();
// epilogue code
}
// note: no impldo implementation for Base!
derived = new Base();
derived.impldo = function() { /* do derived things here safely */ }
string test = "abcdxxx";
test = test.Remove(test.Length - 3);
//output : abcd
you can use the in built .toLowerCase() method on javascript strings. ex: var x = "Hello"; x.toLowerCase();
If you want a string mm/dd/yyyy
instead of the datetime
object, you can use strftime
(string format time):
>>> dt.datetime.today().strftime("%m/%d/%Y")
# ^ note parentheses
'02/12/2014'
For those very beginners
who has spend few hours for this commit (with comment
and no verify
) with no further issue
git commit -m "Some comments" --no-verify
ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
Try it like this
public OnClickListener moreListener = new OnClickListener() {
@Override
public void onClick(View v) {
adapter = null;
myStringArray1.add("Andrea");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
};
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
Suppose you run your program thus (using sh
syntax):
myprog arg1 arg2 'arg 3'
If you declared your main as int main(int argc, char *argv[])
, then (in most environments), your main()
will be called as if like:
p = { "myprog", "arg1", "arg2", "arg 3", NULL };
exit(main(4, p));
However, if you declared your main as int main()
, it will be called something like
exit(main());
and you don't get the arguments passed.
Two additional things to note:
main
. If a particular platform accepts extra arguments or a different return type, then that's an extension and should not be relied upon in a portable program.*argv[]
and **argv
are exactly equivalent, so you can write int main(int argc, char *argv[])
as int main(int argc, char **argv)
.You should be able to use a var_dump() within a pre tag. Otherwise you could look into using a library like dump_r.php: https://github.com/leeoniya/dump_r.php
My solution is incorrect. OP was looking for a solution formatted with spaces to store in a log file.
A solution might be to use output buffering with var_dump, then str_replace() all the tabs with spaces to format it in the log file.
Byte Stream - Stream is sequence of data. Input stream - reads data from source. Output stream - writes data to desitnation. Java Byte Streams are used to perform input/output byte by byte(8bits at a time). A byte stream is suitable for processing raw data like binary files. Java Character Streams are used to perform input/output 2 bytes at a time, because Characters are stored using Unicode conventions in Java with 2 bytes for each character. Character stream is useful when we process(read/write) text files.
RMI(Remote Method Invocation) - an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.
Both Serialization and Marshalling are loosely used as synonyms. Here are few differences.
Serialization - Data members of an object is written to binary form or Byte Stream(and then can be written in file/memory/database etc). No information about data-types can be retained once object data members are written to binary form.
Marshalling - Object is serialized(to byte stream in binary format) with data-type + Codebase attached and then passed Remote Object(RMI). Marshalling will transform the data-type into a predetermined naming convention so that it can be reconstructed with respect to the initial data-type.
So Serialization is part of Marshalling.
CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location. (Copied from @Nasir answer)
Serialization is almost like a stupid memory-dump of the memory used by the object(s), while Marshalling stores information about custom data-types.
In a way, Serialization performs marshalling with implematation of pass-by-value because no information of data-type is passed, just the primitive form is passed to byte stream.
Serialization may have some issues related to big-endian, small-endian if the stream is going from one OS to another if the different OS have different means of representing the same data. On the other hand, marshalling is perfectly fine to migrate between OS because the result is a higher-level representation.
could be that you're missing the certificate on your device.
try looking at this answer: How to install trusted CA certificate on Android device? to see how to install the CA on your own device.
Yield(): method will stop the currently executing thread and give a chance to another thread of same priority which are waiting in queue. If thier is no thread then current thread will continue to execute. CPU will never be in ideal state.
Sleep(): method will stop the thread for particular time (time will be given in milisecond). If this is single thread which is running then CPU will be in ideal state at that period of time.
Both are static menthod.
Well I used the advice here and it screwed me as it merged my local code directly to master. .... so take it all with a grain of salt. My coworker said the following helped resolve the issue, needed to repoint my branch.
git branch --set-upstream-to=origin/feature/my-current-branch feature/my-current-branch
Show the last n days from today:
import datetime
for i in range(0, 100):
print((datetime.date.today() + datetime.timedelta(i)).isoformat())
Output:
2016-06-29
2016-06-30
2016-07-01
2016-07-02
2016-07-03
2016-07-04
Simply in windows
ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)
I think create a custom EditorTemplate is not good solution, beause you need to care about many possible tepmlates for different cases: strings, numsers, comboboxes and so on. Other solution is custom extention to HtmlHelper.
Model:
public class MyViewModel
{
[PlaceHolder("Enter title here")]
public string Title { get; set; }
}
Html helper extension:
public static MvcHtmlString BsEditorFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TValue>> expression, string htmlClass = "")
{
var modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var metadata = modelMetadata;
var viewData = new
{
HtmlAttributes = new
{
@class = htmlClass,
placeholder = metadata.Watermark,
}
};
return htmlHelper.EditorFor(expression, viewData);
}
A corresponding view:
@Html.BsEditorFor(x => x.Title)
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA <> 'x' AND columbB <> 'y'";
I'd suggest using the diamond operator (<>) in favor of != as the first one is valid SQL and the second one is a MySQL addition.
Debug and Release are just labels for different solution configurations. You can add others if you want. A project I once worked on had one called "Debug Internal" which was used to turn on the in-house editing features of the application. You can see this if you go to Configuration Manager...
(it's on the Build
menu). You can find more information on MSDN Library under Configuration Manager Dialog Box.
Each solution configuration then consists of a bunch of project configurations. Again, these are just labels, this time for a collection of settings for your project. For example, our C++ library projects have project configurations called "Debug", "Debug_Unicode", "Debug_MT", etc.
The available settings depend on what type of project you're building. For a .NET project, it's a fairly small set: #define
s and a few other things. For a C++ project, you get a much bigger variety of things to tweak.
In general, though, you'll use "Debug" when you want your project to be built with the optimiser turned off, and when you want full debugging/symbol information included in your build (in the .PDB file, usually). You'll use "Release" when you want the optimiser turned on, and when you don't want full debugging information included.
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
you can do it with _pull
.
_.pull(obj["subTopics"] , {"subTopicId":2, "number":32});
check the reference
My problem is that when i use https for the remote URL, it doesn't work, so I use http instead. This allows me to publish/sync with GitHub from Team Explorer instantly.
For adding background icon always before text when length of text is not known in advance.
.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}
java.util.Arrays.asList(new String[]{"a", "b"})
I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!
$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news);
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
}
else {
echo $news;
}
Well, my solution is sort of hack, but it works and I am using it.
1vw = 1% of viewport width
1vh = 1% of viewport height
1vmin = 1vw or 1vh, whichever is smaller
1vmax = 1vw or 1vh, whichever is larger
h1 {
font-size: 5.9vw;
}
h2 {
font-size: 3.0vh;
}
p {
font-size: 2vmin;
}
On macOS Mojave 10.14.4, you can also try Command ? + Q in a terminal.
Bootstrap.yml is used to fetch config from the server. It can be for a Spring cloud application or for others. Typically it looks like:
spring:
application:
name: "app-name"
cloud:
config:
uri: ${config.server:http://some-server-where-config-resides}
When we start the application it tries to connect to the given server and read the configuration based on spring profile mentioned in run/debug configuration.
If the server is unreachable application might even be unable to proceed further. However, if configurations matching the profile are present locally the server configs get overridden.
Good approach:
Maintain a separate profile for local and run the app using different profiles.
In my case one unmanaged dll was depending on another which was missing. In that case the error will point to the existing dll instead of the missing one which can be really confusing.
That is exactly what had happen in my case. Hope this helps someone else.
For anyone hitting this issue in the future: the specific situation here ("the server isn't sending back the WSDL properly") may or may not always be relevant, but two key aspects should always be:
faultCode=INVALID_WSDL: Expected element '{http://schemas.xmlsoap.org/wsdl/}definitions'
means that the actual content returned is not XML with a base element of "definitions" in the WSDL namespace.WSDLException (at /html)
tells you an important clue about what it did find — for this example, /html
strongly implies that a normal webpage was returned, rather than a WSDL. Another common situation is seeing something like /soapenv:Reason
, which would indicate that the server was trying to treat it as a SOAP call — for example, this can happen if your URL is for the "base" service URL rather than the WSDL.Try something like this:
yourControl.DataSource = countryInstance.Cities;
And if you are using WebForms you will need to add this line:
yourControl.DataBind();
df.index.name
should do the trick.
Python has a dir
function that let's you query object attributes. dir(df.index)
was helpful here.
An alternative solution is using an external table: http://www.orafaq.com/node/848
Use this when you have to do this import very often and very fast.
See Bavarious's answer.
Use xattr
with the -c
flag to "clear" the attributes:
xattr -c yourfile.txt
To recursively remove extended attributes on all files in a directory, combine the -c
"clear" flag with the -r
recursive flag:
xattr -rc /path/to/directory
Have a long path with spaces or special characters?
Open Terminal.app
and start typing xattr -rc
, include a trailing space, and then then drag the file or folder to the Terminal.app
window and it will automatically add the full path with proper escaping.
You can use .is(':visible')
Selects all elements that are visible.
For example:
if($('#selectDiv').is(':visible')){
Also, you can get the div which is visible by:
$('div:visible').callYourFunction();
Live example:
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
display: none; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
I searched and searched and finally found that ie needs to know the map size. Set the map size to match the div size.
map = new GMap2(document.getElementById("map_canvas2"), { size: new GSize(850, 600) });
<div id="map_canvas2" style="width: 850px; height: 600px">
</div>
If you want a ksh only method that is as fast as "test", you can do something like:
contains() # haystack needle
{
haystack=${1/$2/}
if [ ${#haystack} -ne ${#1} ] ; then
return 1
fi
return 0
}
It works by deleting the needle in the haystack and then comparing the string length of old and new haystacks.
Kenny's solution is good, however it can be written in a more elegant way
new WebDriverWait(driver, timeout)
.ignoring(StaleElementReferenceException.class)
.until((WebDriver d) -> {
d.findElement(By.id("checkoutLink")).click();
return true;
});
Or also:
new WebDriverWait(driver, timeout).ignoring(StaleElementReferenceException.class).until(ExpectedConditions.elementToBeClickable(By.id("checkoutLink")));
driver.findElement(By.id("checkoutLink")).click();
But anyway, best solution is to rely on Selenide library, it handles this kind of things and more. (instead of element references it handles proxies so you never have to deal with stale elements, which can be quite difficult). Selenide
Well, since you asked for R equivalent to other languages, I tried to do this. Seems to work though I haven't really looked at which technique is more efficient in R.
> myDf <- head(iris)
> myDf
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
> nRowsDf <- nrow(myDf)
> for(i in 1:nRowsDf){
+ print(myDf[i,4])
+ }
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.2
[1] 0.4
For the categorical columns though, it would fetch you a Data Frame which you could typecast using as.character() if needed.
If you want to determine whether a key is there in map or not, you can use the find() or count() member function of map. The find function which is used here in example returns the iterator to element or map::end otherwise. In case of count the count returns 1 if found, else it returns zero(or otherwise).
if(phone.count(key))
{ //key found
}
else
{//key not found
}
for(int i=0;i<v.size();i++){
phoneMap::iterator itr=phone.find(v[i]);//I have used a vector in this example to check through map you cal receive a value using at() e.g: map.at(key);
if(itr!=phone.end())
cout<<v[i]<<"="<<itr->second<<endl;
else
cout<<"Not found"<<endl;
}
Use df.count()
to get the number of rows.
From a programmatic standpoint, for the client it's packaging up parameters and appending them onto the url and conducting a POST vs. a GET. On the server-side, it's evaluating inbound parameters from the querystring instead of the posted bytes. Basically, it's a wash.
Where there could be advantages/disadvantages might be in how specific client platforms work with POST and GET routines in their networking stack, as well as how the web server deals with those requests. Depending on your implementation, one approach may be more efficient than the other. Knowing that would guide your decision here.
Nonetheless, from a programmer's perspective, I prefer allowing either a POST with all parameters in the body, or a GET with all params on the url, and explicitly ignoring url parameters with any POST request. It avoids confusion.
You can indeed not define the filter execution order using @WebFilter
annotation. However, to minimize the web.xml
usage, it's sufficient to annotate all filters with just a filterName
so that you don't need the <filter>
definition, but just a <filter-mapping>
definition in the desired order.
For example,
@WebFilter(filterName="filter1")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2")
public class Filter2 implements Filter {}
with in web.xml
just this:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>/url1/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern>/url2/*</url-pattern>
</filter-mapping>
If you'd like to keep the URL pattern in @WebFilter
, then you can just do like so,
@WebFilter(filterName="filter1", urlPatterns="/url1/*")
public class Filter1 implements Filter {}
@WebFilter(filterName="filter2", urlPatterns="/url2/*")
public class Filter2 implements Filter {}
but you should still keep the <url-pattern>
in web.xml
, because it's required as per XSD, although it can be empty:
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern />
</filter-mapping>
<filter-mapping>
<filter-name>filter2</filter-name>
<url-pattern />
</filter-mapping>
Regardless of the approach, this all will fail in Tomcat until version 7.0.28 because it chokes on presence of <filter-mapping>
without <filter>
. See also Using Tomcat, @WebFilter doesn't work with <filter-mapping> inside web.xml
You might be interested by TagSoup, a Java HTML parser able to handle malformed HTML. XML parsers would work only on well formed XHTML.
If I understand you correctly, you can use a combination of Series.isin()
and DataFrame.append()
:
In [80]: df1
Out[80]:
rating user_id
0 2 0x21abL
1 1 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
5 2 0x21abL
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
9 1 0x21abL
In [81]: df2
Out[81]:
rating user_id
0 2 0x1d14L
1 1 0xdbdcad7
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
5 1 0x5734a81e2
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
9 4 0x5734a81e2
In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)
In [83]: ind
Out[83]:
0 True
1 False
2 True
3 True
4 True
5 False
6 True
7 True
8 True
9 False
Name: user_id, dtype: bool
In [84]: df1[ind].append(df2[ind])
Out[84]:
rating user_id
0 2 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
0 2 0x1d14L
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
This is essentially the algorithm you described as "clunky", using idiomatic pandas
methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1
and df2
have no overlapping row indices, i.e., if
In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')
In fact, it won't give the expected output if their row indices are not equal.
You want
#content div:first-child {
/*css*/
}
On chrome (V.35.0.1916.153 m) Try this:
function loadPrint() {
window.print();
setTimeout(function () { window.close(); }, 100);
}
Works great for me. It will close window after user finished working on printing dialog.
Get second, third, fourth......Nth highest salary using following query
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP N salary FROM employees ORDER BY salary DESC)
Replace N by you number i.e. N=2 for second highest salary, N=3 for third highest salary and so on. So for second highest salary use
SELECT MIN(salary) from employees WHERE salary IN( SELECT TOP 2 salary FROM employees ORDER BY salary DESC)
SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD
I'm interested in this as well. The only explanation I've found is that xsd:include
is used for intra-namespace inclusions, while xsd:import
is for inter-namespace inclusion.
./me casts raise_dead()
I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:
my_exe ()
{
mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}
This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"
To get those variables I can do something like:
ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...