I think you can use a sprintf :
int number = 33;
char* numberstring[(((sizeof number) * CHAR_BIT) + 2)/3 + 2];
sprintf(numberstring, "%d", number);
A const
to a pointer indicates a "read-only" memory location. Whereas the ones without const
are a read-write memory areas. So, you "cannot" convert a const
(read-only location) to a normal(read-write) location.
The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup()
to perform this action.
my proposal is this simple anonymous block:
DECLARE
lc_username VARCHAR2 (32) := 'user-name-to-kill-here';
BEGIN
FOR ln_cur IN (SELECT sid, serial# FROM v$session WHERE username = lc_username)
LOOP
EXECUTE IMMEDIATE ('ALTER SYSTEM KILL SESSION ''' || ln_cur.sid || ',' || ln_cur.serial# || ''' IMMEDIATE');
END LOOP;
END;
/
You can use below code for multiple select:
<select asp-for="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
You can also use:
<select id="EmployeeId" name="EmployeeId" multiple="multiple" asp-items="@ViewBag.Employees">
<option>Please select</option>
</select>
I was getting A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance
when I was setting parent.setChildren(new ArrayList<>())
. When I changed to parent.getChildren().clear()
, it solved the problem.
Check for more details: HibernateException - A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance.
Procedural Content Generation wiki:
if what you want isn't on there, then add it ;)
If you can't access the file and your os is any linux distro or mac os x then either of these commands should work:
sudo nano .bashrc
chmod 777 .bashrc
it is worthless
This is my solution, wish useful for you:
public class Sheet : Grid
{
public static readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register(nameof(BorderBrush), typeof(Brush), typeof(Sheet), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderBrushChanged));
public static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register(nameof(BorderThickness), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(1D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnBorderThicknessChanged, CoerceBorderThickness));
public static readonly DependencyProperty CellSpacingProperty = DependencyProperty.Register(nameof(CellSpacing), typeof(double), typeof(Sheet), new FrameworkPropertyMetadata(0D, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, OnCellSpacingChanged, CoerceCellSpacing));
public Brush BorderBrush
{
get => this.GetValue(BorderBrushProperty) as Brush;
set => this.SetValue(BorderBrushProperty, value);
}
public double BorderThickness
{
get => (double)this.GetValue(BorderThicknessProperty);
set => this.SetValue(BorderThicknessProperty, value);
}
public double CellSpacing
{
get => (double)this.GetValue(CellSpacingProperty);
set => this.SetValue(CellSpacingProperty, value);
}
protected override Size ArrangeOverride(Size arrangeSize)
{
Size size = base.ArrangeOverride(arrangeSize);
double border = this.BorderThickness;
double doubleBorder = border * 2D;
double spacing = this.CellSpacing;
double halfSpacing = spacing * 0.5D;
if (border > 0D || spacing > 0D)
{
foreach (UIElement child in this.InternalChildren)
{
this.GetChildBounds(child, out double left, out double top, out double width, out double height);
left += halfSpacing + border;
top += halfSpacing + border;
height -= spacing + doubleBorder;
width -= spacing + doubleBorder;
if (width < 0D)
{
width = 0D;
}
if (height < 0D)
{
height = 0D;
}
left -= left % 0.5D;
top -= top % 0.5D;
width -= width % 0.5D;
height -= height % 0.5D;
child.Arrange(new Rect(left, top, width, height));
}
if (border > 0D && this.BorderBrush != null)
{
this.InvalidateVisual();
}
}
return size;
}
protected override void OnRender(DrawingContext dc)
{
base.OnRender(dc);
if (this.BorderThickness > 0D && this.BorderBrush != null)
{
if (this.CellSpacing == 0D)
{
this.DrawCollapsedBorder(dc);
}
else
{
this.DrawSeperatedBorder(dc);
}
}
}
private void DrawSeperatedBorder(DrawingContext dc)
{
double spacing = this.CellSpacing;
double halfSpacing = spacing * 0.5D;
#region draw border
Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
UIElementCollection children = this.InternalChildren;
foreach (UIElement child in children)
{
this.GetChildBounds(child, out double left, out double top, out double width, out double height);
left += halfSpacing;
top += halfSpacing;
width -= spacing;
height -= spacing;
dc.DrawRectangle(null, pen, new Rect(left, top, width, height));
}
#endregion
}
private void DrawCollapsedBorder(DrawingContext dc)
{
RowDefinitionCollection rows = this.RowDefinitions;
ColumnDefinitionCollection columns = this.ColumnDefinitions;
int rowCount = rows.Count;
int columnCount = columns.Count;
const byte BORDER_LEFT = 0x08;
const byte BORDER_TOP = 0x04;
const byte BORDER_RIGHT = 0x02;
const byte BORDER_BOTTOM = 0x01;
byte[,] borderState = new byte[rowCount, columnCount];
int column = columnCount - 1;
int columnSpan;
int row = rowCount - 1;
int rowSpan;
#region generate main border data
for (int i = 0; i < rowCount; i++)
{
borderState[i, 0] = BORDER_LEFT;
borderState[i, column] = BORDER_RIGHT;
}
for (int i = 0; i < columnCount; i++)
{
borderState[0, i] |= BORDER_TOP;
borderState[row, i] |= BORDER_BOTTOM;
}
#endregion
#region generate child border data
UIElementCollection children = this.InternalChildren;
foreach (UIElement child in children)
{
this.GetChildLayout(child, out row, out rowSpan, out column, out columnSpan);
for (int i = 0; i < rowSpan; i++)
{
borderState[row + i, column] |= BORDER_LEFT;
borderState[row + i, column + columnSpan - 1] |= BORDER_RIGHT;
}
for (int i = 0; i < columnSpan; i++)
{
borderState[row, column + i] |= BORDER_TOP;
borderState[row + rowSpan - 1, column + i] |= BORDER_BOTTOM;
}
}
#endregion
#region draw border
Pen pen = new Pen(this.BorderBrush, this.BorderThickness);
double left;
double top;
double width, height;
for (int r = 0; r < rowCount; r++)
{
RowDefinition v = rows[r];
top = v.Offset;
height = v.ActualHeight;
for (int c = 0; c < columnCount; c++)
{
byte state = borderState[r, c];
ColumnDefinition h = columns[c];
left = h.Offset;
width = h.ActualWidth;
if ((state & BORDER_LEFT) == BORDER_LEFT)
{
dc.DrawLine(pen, new Point(left, top), new Point(left, top + height));
}
if ((state & BORDER_TOP) == BORDER_TOP)
{
dc.DrawLine(pen, new Point(left, top), new Point(left + width, top));
}
if ((state & BORDER_RIGHT) == BORDER_RIGHT && (c + 1 >= columnCount || (borderState[r, c + 1] & BORDER_LEFT) == 0))
{
dc.DrawLine(pen, new Point(left + width, top), new Point(left + width, top + height));
}
if ((state & BORDER_BOTTOM) == BORDER_BOTTOM && (r + 1 >= rowCount || (borderState[r + 1, c] & BORDER_TOP) == 0))
{
dc.DrawLine(pen, new Point(left, top + height), new Point(left + width, top + height));
}
}
}
#endregion
}
private void GetChildBounds(UIElement child, out double left, out double top, out double width, out double height)
{
ColumnDefinitionCollection columns = this.ColumnDefinitions;
RowDefinitionCollection rows = this.RowDefinitions;
int rowCount = rows.Count;
int row = (int)child.GetValue(Grid.RowProperty);
if (row >= rowCount)
{
row = rowCount - 1;
}
int rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
if (row + rowSpan > rowCount)
{
rowSpan = rowCount - row;
}
int columnCount = columns.Count;
int column = (int)child.GetValue(Grid.ColumnProperty);
if (column >= columnCount)
{
column = columnCount - 1;
}
int columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
if (column + columnSpan > columnCount)
{
columnSpan = columnCount - column;
}
left = columns[column].Offset;
top = rows[row].Offset;
ColumnDefinition right = columns[column + columnSpan - 1];
width = right.Offset + right.ActualWidth - left;
RowDefinition bottom = rows[row + rowSpan - 1];
height = bottom.Offset + bottom.ActualHeight - top;
if (width < 0D)
{
width = 0D;
}
if (height < 0D)
{
height = 0D;
}
}
private void GetChildLayout(UIElement child, out int row, out int rowSpan, out int column, out int columnSpan)
{
int rowCount = this.RowDefinitions.Count;
row = (int)child.GetValue(Grid.RowProperty);
if (row >= rowCount)
{
row = rowCount - 1;
}
rowSpan = (int)child.GetValue(Grid.RowSpanProperty);
if (row + rowSpan > rowCount)
{
rowSpan = rowCount - row;
}
int columnCount = this.ColumnDefinitions.Count;
column = (int)child.GetValue(Grid.ColumnProperty);
if (column >= columnCount)
{
column = columnCount - 1;
}
columnSpan = (int)child.GetValue(Grid.ColumnSpanProperty);
if (column + columnSpan > columnCount)
{
columnSpan = columnCount - column;
}
}
private static void OnBorderBrushChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateVisual();
}
}
private static void OnBorderThicknessChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateArrange();
}
}
private static void OnCellSpacingChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (d is UIElement element)
{
element.InvalidateArrange();
}
}
private static object CoerceBorderThickness(DependencyObject d, object baseValue)
{
if (baseValue is double value)
{
return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
}
return 0D;
}
private static object CoerceCellSpacing(DependencyObject d, object baseValue)
{
if (baseValue is double value)
{
return value < 0D || double.IsNaN(value) || double.IsInfinity(value) ? 0D : value;
}
return 0D;
}
}
NuPKG files are just zip files, so anything that can process a zip file should be able to process a nupkg file, i.e, 7zip.
DateTime
is not a function, but the class.
When you just reference a class like new DateTime()
PHP searches for the class in your current namespace. However the DateTime
class obviously doesn't exists in your controllers namespace but rather in root namespace.
You can either reference it in the root namespace by prepending a backslash:
$now = new \DateTime();
Or add an import statement at the top:
use DateTime;
$now = new DateTime();
The trick is to
My advise would be also to not ignore the .idea folder.
I've imported a Git-based Eclipse project to Android Studio and that went fine. Later, I wanted to import this project with Git (like the first time) to another machine with Android Studio, but that didn't worked. Android Studio did load all the files but wasn't able to "see" the project as a project. I only could open Git-files.
While importing the project for the first time (from Eclipse to Android Studio) my old .gitignore was overwritten and the new one looked like this:
So, I tried to use an empty gitignore and now it worked. The other Android Studio could load the files and the Project. I guess some files are not important (profiles_settings.xml)
for Git and importing but I am just happy it worked.
/**
* Function to read all mp3 files from sdcard and store the details in an
* ArrayList
*/
public ArrayList<HashMap<String, String>> getPlayList()
{
ArrayList<HashMap<String, String>> songsList=new ArrayList<>();
File home = new File(MEDIA_PATH);
if (home.listFiles(new FileExtensionFilter()).length > 0) {
for (File file : home.listFiles(new FileExtensionFilter())) {
HashMap<String, String> song = new HashMap<String, String>();
song.put(
"songTitle",
file.getName().substring(0,
(file.getName().length() - 4)));
song.put("songPath", file.getPath());
// Adding each song to SongList
songsList.add(song);
}
}
// return songs list array
return songsList;
}
/**
* Class to filter files which have a .mp3 extension
* */
class FileExtensionFilter implements FilenameFilter
{
@Override
public boolean accept(File dir, String name) {
return (name.endsWith(".mp3") || name.endsWith(".MP3"));
}
}
You can filter any textfiles or any other extension ..just replace it with .MP3
You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:
YOU: /setjoingroups
BotFather: Choose a bot to change group membership settings.
YOU: @YourBot
BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED
YOU: Enable
BotFather: Success! The new status is: ENABLED.
After this you will see button "Add to Group" in your bot's profile.
hsThumbList.setLayoutParams(new LayoutParams(100, 400));
handleChange({target}) {
const files = target.files
target.value = ''
}
Well if you are using a DataTable at all then rather than comparing two 'DataTables' could you just compare the DataTable that is going to have changes with the original data when it was loaded AKA DataTable.GetChanges Method (DataRowState)
I agree with Paolo that we need to see more code. I tested this overly simplified example and it worked. This means that it is able to change the form action on the fly.
<script type="text/javascript">
function submitForm(){
var form_url = $("#openid_form").attr("action");
alert("Before - action=" + form_url);
//changing the action to google.com
$("#openid_form").attr("action","http://google.com");
alert("After - action = "+$("#openid_form").attr("action"));
//submit the form
$("#openid_form").submit();
}
</script>
<form id="openid_form" action="test.html">
First Name:<input type="text" name="fname" /><br/>
Last Name: <input type="text" name="lname" /><br/>
<input type="button" onclick="submitForm()" value="Submit Form" />
</form>
EDIT: I tested the updated code you posted and found a syntax error in the declaration of providers_large
. There's an extra comma. Firefox ignores the issue, but IE8 throws an error.
var providers_large = {
google: {
name: 'Google',
url: 'https://www.google.com/accounts/o8/id'
},
facebook: {
name: 'Facebook',
form_url: 'http://wikipediamaze.rpxnow.com/facebook/start?token_url=http://www.wikipediamaze.com/Accounts/Logon'
}, //<-- Here's the problem. Remove that comma
};
If you want your requests to persists try this:
example: on your JSP or servlet page
request.getSession().setAttribute("SUBFAMILY", subFam);
and on any receiving page use the below lines to retrieve your session and data:
SubFamily subFam = (SubFamily)request.getSession().getAttribute("SUBFAMILY");
You can do it inline like this
<div style="margin:0px auto"></div>
or you can do it via class
<div class="x"><div>
in your css file or between <style></style>
add this .x{margin:0px auto}
or you can simply use the center tag
<center>
<div></div>
</center>
or if you using absolute position, you can do
.x{
width: 140px;
position: absolute;
top: 0px;
left: 50%;
margin-left: -70px; /*half the size of width*/
}
Wildcard method: Add the following entry into your DNS server and change the domain and IP address accordingly.
*.example.com IN A 1.2.3.4
I've modified your script to work with jQuery, if you wish to do so.
$(document).ready(function(){
//To add a task when the user hits the return key
$('#task-text').keydown(function(evt){
if(evt.keyCode == 13)
{
add_task($(this), evt);
}
});
//To add a task when the user clicks on the submit button
$("#add-task").click(function(evt){
add_task($("#task-text"),evt);
});
});
function add_task(textBox, evt){
evt.preventDefault();
var taskText = textBox.val();
$("<li />").text(taskText).appendTo("#tasks");
textBox.val("");
};
There is another way, take this as example
Dim sr As String
sr = "6:10"
Rows(sr).Select
All you need to do is to convert your variables iStartRow
, iEndRow
to a string.
NOTE: This answer has gotten so much attention, that I need to update it. Since the original answer was posted, the comment from @dzeikei has gotten almost as much attention as the original answer. So here are 2 possible solutions:
1. If your background thread has a reference to a Context
object:
Make sure that your background worker threads have access to a Context object (can be the Application context or the Service context). Then just do this in the background worker thread:
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(context.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
2. If your background thread does not have (or need) a Context
object
(suggested by @dzeikei):
// Get a handler that can be used to post to the main thread
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {....} // This is your code
};
mainHandler.post(myRunnable);
Thanks to https://stackoverflow.com/users/1652962/cimmanon that gave me the answer.
The solution is setting a height to the vertical scrollable element. For example:
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 0px;
}
The element will have height because flexbox recalculates it unless you want a min-height so you can use height: 100px;
that it is exactly the same as: min-height: 100px;
#container article {
flex: 1 1 auto;
overflow-y: auto;
height: 100px; /* == min-height: 100px*/
}
So the best solution if you want a min-height
in the vertical scroll:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 100px;
}
If you just want full vertical scroll in case there is no enough space to see the article:
#container article {
flex: 1 1 auto;
overflow-y: auto;
min-height: 0px;
}
The final code: http://jsfiddle.net/ch7n6/867/
Setup ANDROID_HOME , JAVA_HOME enviromental variable on Mac OS X
Add In .bash_profile file
export JAVA_HOME=$(/usr/libexec/java_home)
export ANDROID_HOME=/Users/$USER/Library/Android/sdk
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
For Test
echo $ANDROID_HOME
echo $JAVA_HOME
The entire viewcontroller which show data in collecction view using two methods of json parsig
@IBOutlet weak var imagecollectionview: UICollectionView!
lazy var data = NSMutableData()
var dictdata : NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
startConnection()
startNewConnection()
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dictdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomcellCollectionViewCell", forIndexPath: indexPath) as! CustomcellCollectionViewCell
cell.name.text = dictdata.valueForKey("Data")?.valueForKey("location") as? String
let url = NSURL(string: (dictdata.valueForKey("Data")?.valueForKey("avatar_url") as? String)! )
LazyImage.showForImageView(cell.image, url:"URL
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSizeMake(self.view.bounds.size.width/2, CGFloat(kWhateverHeightYouWant))
}
func startNewConnection()
{
let url: URL = URL(string: "YOUR URL" as String)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET" //set the get or post according to your request
// request.cachePolicy = NSURLRequest.CachePolicy.ReloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest) {
( data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
let jsonString = NSString(data: data!, encoding:String.Encoding.utf8.rawValue) as! String
}
task.resume()
}
func startConnection(){
let urlPath: String = "your URL"
let url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func buttonAction(sender: UIButton!){
startConnection()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
dictdata.setObject(JSONDictionary, forKey: "Data")
imagecollectionview.reloadData()
}
catch let JSONError as NSError {
print("\(JSONError)")
} }
On Debian LINUX, I use: ps -o pid= -u username | xargs sudo kill -9
.
With -o pid=
the ps header is supressed, and the output is only the pid list. As far as I know, Debian shell is POSIX compliant.
You can try below:
find ./ ! \( -path ./tmp -prune \) ! \( -path ./scripts -prune \) -type f -name '*_peaks.bed'
In linux terminal try this:
sudo service postgresql start
: to start the serversudo service postgresql stop
: to stop thee serversudo service postgresql status
: to check server statusYou have to close that application first. There is no way to delete it, if it's used by some application.
UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.
There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.
Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.
You just need to install it and import them your project like that :
this code import to command line :
sudo apt-get install python3-tk
after import tkinter your project :
from tkinter import *
Range("A1").value = Environ("Username")
This is better than Application.Username
, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.
Application Username
is the name of the User set in Excel > Tools > Options Environ("Username")
is the name you registered for Windows; see Control Panel >SystemBased on Robm's answer I have created a Docker image and a Bash script called portcat
.
Using portcat, you can easily map multiple ports to an existing Docker container. An example using the (optional) Bash script:
curl -sL https://raw.githubusercontent.com/archan937/portcat/master/script/install | sudo bash
portcat my-awesome-container 3456 4444:8080
And there you go! Portcat is mapping:
3456
to my-awesome-container:3456
4444
to my-awesome-container:8080
Please note that the Bash script is optional, the following commands:
ipAddress=$(docker inspect my-awesome-container | grep IPAddress | grep -o '[0-9]\{1,3\}\(\.[0-9]\{1,3\}\)\{3\}' | head -n 1)
docker run -p 3456:3456 -p 4444:4444 --name=alpine-portcat -it pmelegend/portcat:latest $ipAddress 3456 4444:8080
I hope portcat
will come in handy for you guys. Cheers!
for (int i = 0; i < list.size(); i++) {
if (i < list.size() - 1) {
if (list.get(i) > list.get(i + 1)) {
int j = list.get(i);
list.remove(i);
list.add(i, list.get(i));
list.remove(i + 1);
list.add(j);
i = -1;
}
}
}
Step by step to setup zxing 3.2.1 in eclipse
Most random number generators are, in fact, "pseudo random." They are Linear Congruential Generators, or LCGs (http://en.wikipedia.org/wiki/Linear_congruential_generator)
LCGs are quite predictable given a fixed seed. Basically, use a seed that gives you your first letter, then write an app that continues to generate the next int (char) until you hit the next letter in your target string and write down how many times you had to invoke the LCG. Continue until you've generated each and every letter.
You are somewhat close, but you should put your function inside the document.ready
event handler instead of the other-way-around.
Another way to do this is by placing your AJAX call in a generic function and call that function from an AJAX callback to loop through a set of requests in order:
$(function () {
//setup an array of AJAX options,
//each object will specify information for a single AJAX request
var ajaxes = [
{
url : '<url>',
data : {...},
callback : function (data) { /*do work on data*/ }
},
{
url : '<url2>',
data : {...},
callback : function (data) { /*maybe something different (maybe not)*/ }
}
],
current = 0;
//declare your function to run AJAX requests
function do_ajax() {
//check to make sure there are more requests to make
if (current < ajaxes.length) {
//make the AJAX request with the given info from the array of objects
$.ajax({
url : ajaxes[current].url,
data : ajaxes[current].data,
success : function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxes[current].callback(serverResponse);
},
complete : function () {
//increment the `current` counter
//and recursively call our do_ajax() function again.
current++;
do_ajax();
//note that the "success" callback will fire
//before the "complete" callback
}
});
}
}
//run the AJAX function for the first time once `document.ready` fires
do_ajax();
});
In this example, the recursive call to run the next AJAX request is being set as the complete
callback so that it runs regardless of the status of the current response. Meaning that if the request times out or returns an HTTP error (or invalid response), the next request will still run. If you require subsequent requests to only run when a request is successful, then using the success
callback to make your recursive call would likely be best.
Updated 2018-08-21 in regards to good points in comments.
I've seen this happen at my shop when my devs have a stack manager like MAMP installed that comes preconfigured with MySQL installed in a non standard place.
at your terminal run
mysql_config --socket
that will give you your path to the sock file. take that path and use it in your DATABASES HOST paramater.
What you need to do is point your
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'test',
'USER': 'test',
'PASSWORD': 'test',
'HOST': '/Applications/MAMP/tmp/mysql/mysql.sock',
'PORT': '',
},
}
also run which mysql_config
if you somehow have multiple instances of mysql server installed on the machine you may be connecting to the wrong one.
Use a HashSet<T>
. For example:
var items = "A B A D A C".Split(' ');
var unique_items = new HashSet<string>(items);
foreach (string s in unique_items)
Console.WriteLine(s);
prints
A B D C
Actually, you can achieve this pretty easy. Simply specify the line height as a number:
<p style="line-height:1.5">
<span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
<span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>
The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.
For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.
You can use typeof(Guid), "00000000-0000-0000-0000-000000000000"
for DefaultValue of the property.
If you have multidimensional data and want each axis normalized to its max or its sum:
def normalize(_d, to_sum=True, copy=True):
# d is a (n x dimension) np array
d = _d if not copy else np.copy(_d)
d -= np.min(d, axis=0)
d /= (np.sum(d, axis=0) if to_sum else np.ptp(d, axis=0))
return d
Uses numpys peak to peak function.
a = np.random.random((5, 3))
b = normalize(a, copy=False)
b.sum(axis=0) # array([1., 1., 1.]), the rows sum to 1
c = normalize(a, to_sum=False, copy=False)
c.max(axis=0) # array([1., 1., 1.]), the max of each row is 1
Locate phpMyAdmin installation path.
Open phpMyAdmin/config.inc.php
in your favourite text editor. Copy config.sample.inc.php
to config.inc.php
if it's missing.
Search for $cfg['Servers'][$i]['auth_type'] = 'config';
Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';
Maybe a bit late, but i had same problem.
Click on "Move up" button for Java path and move it at top.
It fixed problem for me
This is assuming a Conda Environment. At a high level, what worked for me was simply configuring my Conda path in Spyder. Here is how I did it:
First, determine the path your env exists at
Create your environment
In the Anaconda navigator, click to "environments" and then hit the play button on the environment you want to open.
Click "Open with Python," you should get an interactive Python shell
Type "import numpy" (choose any package)
Type "numpy" and take a look at the path that looks like this:
C:\\Users\My Name\\.conda\\envs\\pytorch-three\\lib\\site-packages\\numpy\\__init__.py
The important part is the path all the way down to site-packages
For Spyder to be able to read your packages, do the following within Spyder.
Open Spyder from anywhere
Click "tools" and "preferences"
In your Python Interpreter click "Use the following Python interpreter"
From the path above, navigate to your environment and select the Python executable. For me it was here: C:\\Users\My Name\\.conda\\envs\\pytorch-three\\python.exe
Finally, add the C:\\Users\\My Name\\.conda\\envs\\pytorch-three\\libs\\site-libs
folder to the path (which will exist in your environment). This is easily done through the little Python icon with the tooltip of "add to path"
I personally didn't need to restart my IDE, but you may need to.
Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html
It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.
Remove the FormsModule from Declaration:[] and Add the FormsModule in imports:[]
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
How about something trivial like:
inverting:
$num = -$num;
converting only positive into negative:
if ($num > 0) $num = -$num;
converting only negative into positive:
if ($num < 0) $num = -$num;
Try
<p>Click on <img src="/storage/help/button2.1.png" width="auto"
height="28"align="middle"/> button will show a page as bellow</p>
It works for me
A proper solution is using a css class instead of writing src in js file. For example instead of using:
$(this).css("background", "url('../Images/filters_collapse.jpg')");
use:
$(this).addClass("xxx");
and in a css file that is loaded in the page write:
.xxx {
background-image:url('../Images/filters_collapse.jpg');
}
Try this:
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");
Or alternatively if you have the XML in a string use the LoadXml
method.
Once you have it loaded, you can use SelectNodes
and SelectSingleNode
to query specific values, for example:
XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"
Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:
<Data>
<Employee>
<Name>Test</Name>
<ID>123</ID>
</Employee>
<Company>
<Name>ABC</Name>
<Email>[email protected]</Email>
</Company>
</Data>
I like the functions of SandRock. But I found an error in the code of dbo.fn_ConvertIpAddressToBinary. The incoming parameter of @ipAddress VARCHAR(39) is too small when you concat the @delim to it.
SET @ipAddress = @ipAddress + @delim
You can increase it to 40. Or better yet use a new variable that is bigger and use that internally. That way you don't lose the last pair on large numbers.
SELECT dbo.fn_ConvertIpAddressToBinary('ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
This answer mentions Json.NET but stops short of telling you how you can use Json.NET to serialize a dictionary:
return JsonConvert.SerializeObject( myDictionary );
As opposed to JavaScriptSerializer, myDictionary
does not have to be a dictionary of type <string, string>
for JsonConvert to work.
For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.
Like bgporter said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.
In the following example I insert 'Fu'
in to 'Kong Panda'
, to create 'Kong Fu Panda'
>>> line = 'Kong Panda'
>>> index = line.find('Panda')
>>> output_line = line[:index] + 'Fu ' + line[index:]
>>> output_line
'Kong Fu Panda'
In the example above, I used the index value to 'slice' the string in to 2 substrings: 1 containing the substring before the insertion index, and the other containing the rest. Then I simply add the desired string between the two and voilà, we have inserted a string inside another.
Python's slice notation has a great answer explaining the subject of string slicing.
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.
Browser hack: http://jszen.blogspot.com/2007/03/return-false-to-prevent-jumping.html
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
A big part of the REST philosophy is to exploit as many standard features of the HTTP protocol as possible when designing your API. Applying that philosophy to authentication, client and server would utilize standard HTTP authentication features in the API.
Login screens are great for human user use cases: visit a login screen, provide user/password, set a cookie, client provides that cookie in all future requests. Humans using web browsers can't be expected to provide a user id and password with each individual HTTP request.
But for a REST API, a login screen and session cookies are not strictly necessary, since each request can include credentials without impacting a human user; and if the client does not cooperate at any time, a 401
"unauthorized" response can be given. RFC 2617 describes authentication support in HTTP.
TLS (HTTPS) would also be an option, and would allow authentication of the client to the server (and vice versa) in every request by verifying the public key of the other party. Additionally this secures the channel for a bonus. Of course, a keypair exchange prior to communication is necessary to do this. (Note, this is specifically about identifying/authenticating the user with TLS. Securing the channel by using TLS / Diffie-Hellman is always a good idea, even if you don't identify the user by its public key.)
An example: suppose that an OAuth token is your complete login credentials. Once the client has the OAuth token, it could be provided as the user id in standard HTTP authentication with each request. The server could verify the token on first use and cache the result of the check with a time-to-live that gets renewed with each request. Any request requiring authentication returns 401
if not provided.
first, make sure you have the language pack installed by doing :
sudo apt-get install language-pack-en-base
sudo dpkg-reconfigure locales
Here is an extended version to Josh Lee's answer. If you want the div to be on sidebar to the right, and float within a range (i.e., you need to specify top and bottom anchor positions). It also fixes a bug when you view this on mobile devices (you need to check left scroll position otherwise the div will move off screen).
function moveScroller() {
var move = function() {
var st = $(window).scrollTop();
var sl = $(window).scrollLeft();
var ot = $("#scroller-anchor-top").offset().top;
var ol = $("#scroller-anchor-top").offset().left;
var bt = $("#scroller-anchor-bottom").offset().top;
var s = $("#scroller");
if(st > ot) {
if (st < bt - 280) //280px is the approx. height for the sticky div
{
s.css({
position: "fixed",
top: "0px",
left: ol-sl
});
}
else
{
s.css({
position: "fixed",
top: bt-st-280,
left: ol-sl
});
}
} else {
s.css({
position: "relative",
top: "",
left: ""
});
}
};
$(window).scroll(move);
move();
}
To expand Konamiman's solution (including all relevant null checks), this is what I've been doing:
if (node.Attributes != null)
{
var nameAttribute = node.Attributes["Name"];
if (nameAttribute != null)
return nameAttribute.Value;
throw new InvalidOperationException("Node 'Name' not found.");
}
The yield
keyword allows you to create an IEnumerable<T>
in the form on an iterator block. This iterator block supports deferred executing and if you are not familiar with the concept it may appear almost magical. However, at the end of the day it is just code that executes without any weird tricks.
An iterator block can be described as syntactic sugar where the compiler generates a state machine that keeps track of how far the enumeration of the enumerable has progressed. To enumerate an enumerable, you often use a foreach
loop. However, a foreach
loop is also syntactic sugar. So you are two abstractions removed from the real code which is why it initially might be hard to understand how it all works together.
Assume that you have a very simple iterator block:
IEnumerable<int> IteratorBlock()
{
Console.WriteLine("Begin");
yield return 1;
Console.WriteLine("After 1");
yield return 2;
Console.WriteLine("After 2");
yield return 42;
Console.WriteLine("End");
}
Real iterator blocks often have conditions and loops but when you check the conditions and unroll the loops they still end up as yield
statements interleaved with other code.
To enumerate the iterator block a foreach
loop is used:
foreach (var i in IteratorBlock())
Console.WriteLine(i);
Here is the output (no surprises here):
Begin 1 After 1 2 After 2 42 End
As stated above foreach
is syntactic sugar:
IEnumerator<int> enumerator = null;
try
{
enumerator = IteratorBlock().GetEnumerator();
while (enumerator.MoveNext())
{
var i = enumerator.Current;
Console.WriteLine(i);
}
}
finally
{
enumerator?.Dispose();
}
In an attempt to untangle this I have crated a sequence diagram with the abstractions removed:
The state machine generated by the compiler also implements the enumerator but to make the diagram more clear I have shown them as separate instances. (When the state machine is enumerated from another thread you do actually get separate instances but that detail is not important here.)
Every time you call your iterator block a new instance of the state machine is created. However, none of your code in the iterator block is executed until enumerator.MoveNext()
executes for the first time. This is how deferred executing works. Here is a (rather silly) example:
var evenNumbers = IteratorBlock().Where(i => i%2 == 0);
At this point the iterator has not executed. The Where
clause creates a new IEnumerable<T>
that wraps the IEnumerable<T>
returned by IteratorBlock
but this enumerable has yet to be enumerated. This happens when you execute a foreach
loop:
foreach (var evenNumber in evenNumbers)
Console.WriteLine(eventNumber);
If you enumerate the enumerable twice then a new instance of the state machine is created each time and your iterator block will execute the same code twice.
Notice that LINQ methods like ToList()
, ToArray()
, First()
, Count()
etc. will use a foreach
loop to enumerate the enumerable. For instance ToList()
will enumerate all elements of the enumerable and store them in a list. You can now access the list to get all elements of the enumerable without the iterator block executing again. There is a trade-off between using CPU to produce the elements of the enumerable multiple times and memory to store the elements of the enumeration to access them multiple times when using methods like ToList()
.
Here is a practical example of Anchor tag with different
Use a for
loop instead of .forEach()
var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false
for(var call of myObj) {
console.log(call)
var a = call['a'], b = call['b']
if(a == null || b == null) {
result = false
break
}
}
I suggest PlantUML. this tools is very usefull and easy to use. PlantUML have a plugin for Netbeans that you can create UML diagram from your java code.
you can install PlantUML plugin in the netbeans by this method:
Netbeans Menu -> Tools -> Plugin
Now select Available Plugins and then find PlantUML and install it.
For more information go to website: www.plantuml.com
Below code will fix root = tk.Tk()
to its size before it was called:
root.resizable(False, False)
You need to make it a generic method, like this:
public static T ConfigSetting<T>(string settingName)
{
return /* code to convert the setting to T... */
}
But the caller will have to specify the type they expect. You could then potentially use Convert.ChangeType
, assuming that all the relevant types are supported:
public static T ConfigSetting<T>(string settingName)
{
object value = ConfigurationManager.AppSettings[settingName];
return (T) Convert.ChangeType(value, typeof(T));
}
I'm not entirely convinced that all this is a good idea, mind you...
Use onClick event to clear value of target input, each time user clicks on field. This ensures that the onChange event will be triggered for the same file as well. Worked for me :)
onInputClick = (event) => {
event.target.value = ''
}
<input type="file" onChange={onFileChanged} onClick={onInputClick} />
Using TypeScript
onInputClick = ( event: React.MouseEvent<HTMLInputElement, MouseEvent>) => {
const element = event.target as HTMLInputElement
element.value = ''
}
This works for me: it will update local version to latest
npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install
to verify version
ng --version
For checking Strings for letters you can use regular expressions for example:
someString.matches("[A-F]");
For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here
public int readInt(String prompt, int min, int max)
{
Scanner scan = new Scanner(System.in);
int number = 0;
//Run once and loop until the input is within the specified range.
do
{
//Print users message.
System.out.printf("\n%s > ", prompt);
//Prevent string input crashing the program.
while (!scan.hasNextInt())
{
System.out.printf("Input doesn't match specifications. Try again.");
System.out.printf("\n%s > ", prompt);
scan.next();
}
//Set the number.
number = scan.nextInt();
//If the number is outside range print an error message.
if (number < min || number > max)
System.out.printf("Input doesn't match specifications. Try again.");
} while (number < min || number > max);
return number;
}
If u wanna Select items of List from 2nd list:
MainList.Where(p => 2ndlist.Contains(p.columns from MainList )).ToList();
ERR_CACHE_MISS
error solutionyou just need add one line code <uses-permission android:name="android.permission.INTERNET"/>
in your app/src/main/AndroidManifest.xml
file as below screenshots shows.
Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."
With that in mind, then the function given in the second link you posted should do exactly what you need:
function mres($value)
{
$search = array("\\", "\x00", "\n", "\r", "'", '"', "\x1a");
$replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");
return str_replace($search, $replace, $value);
}
try this it is worked for me.
$time="10:09";
$time = date('H:i', strtotime($time.'+1 hour'));
echo $time;
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
might fail working with link_directories, then add each static library like following:
target_link_libraries(foo /path_to_static_library/libbar.a)
I know the question is for JUnit4, but if you happen to be stuck at JUnit3, you could create a short utility function like that:
private void assertArrayEquals(Object[] esperado, Object[] real) {
assertEquals(Arrays.asList(esperado), Arrays.asList(real));
}
In JUnit3, this is better than directly comparing the arrays, since it will detail exactly which elements are different.
We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").
TCP
49187 - Fixed jnlp port
8080 - jenkins http port
Other ports needed to launch slave as a windows service
TCP
135
139
445
UDP
137
138
I think you can use loc
if you need update two columns to same value:
df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
stream feat another_feat
a 1 some_value some_value
b 2 aaaa aaaa
c 2 aaaa aaaa
d 3 some_value some_value
If you need update separate, one option is use:
df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
stream feat another_feat
a 1 some_value some_value
b 2 10 some_value
c 2 10 some_value
d 3 some_value some_value
Another common option is use numpy.where
:
df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
stream feat another_feat
a 1 20 some_value
b 2 10 some_value
c 2 10 some_value
d 3 20 some_value
EDIT: If you need divide all columns without stream
where condition is True
, use:
print df1
stream feat another_feat
a 1 4 5
b 2 4 5
c 2 2 9
d 3 1 7
#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']
df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
stream feat another_feat
a 1 4.0 5.0
b 2 2.0 2.5
c 2 1.0 4.5
d 3 1.0 7.0
If working with multiple conditions is possible use multiple numpy.where
or numpy.select
:
df0 = pd.DataFrame({'Col':[5,0,-6]})
df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing',
np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))
df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
['Increasing', 'Decreasing'],
default='No Change')
print (df0)
Col New Col1 New Col2
0 5 Increasing Increasing
1 0 No Change No Change
2 -6 Decreasing Decreasing
I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .
It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .
... and a lot of other examples as well ...
If you have a low # of commits and you don't care if these are combined into one mega-commit, this works well and isn't as scary as doing git rebase
:
unstage the files (replace 1 with # of commits)
git reset --soft HEAD~1
create a new branch
git checkout -b NewBranchName
add the changes
git add -A
make a commit
git commit -m "Whatever"
This worked for me: original command
echo "export CATALINA_HOME="/opt/tomcat9"" >> /etc/environment
Working command
echo "export CATALINA_HOME="/opt/tomcat9"" |sudo tee /etc/environment
Try $("#divVideo video")[0].load();
after you changed the src attribute.
The major issue might be the oracle database itself may not have started. So, you need to manually go via
run command -> services.msc
check for OracleXEService surely, it may be disabled
right click go to properties-> set it to Automatic and press Ok. Then just right click again and start.
This will start your database making you to connect to it
Finally, In sqlplus command line,
connect as sysdba
enter username as admin
then press enter, you'll be connected
The Better way to do that is:
For the details of specific Package
pip show <package_name>
It details out the Package_name, Version, Author, Location etc.
$ pip show numpy
Name: numpy
Version: 1.13.3
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: [email protected]
License: BSD
Location: c:\users\prowinjvm\appdata\local\programs\python\python36\lib\site-packages
Requires:
For more Details: >>> pip help
pip
should be updated to do this.
pip install --upgrade pip
On Windows recommend command is:
python -m pip install --upgrade pip
If you are using the glyphicon as the first character of the string, you can use the html char (see https://glyphicons.bootstrapcheatsheets.com/) and then apply the font to the first character of the element:
option::first-letter{
font-family: Glyphicons Halflings;
}
From Wikipedia (emphasis and link added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
So, the real percent encoding uses %20
while form data in URLs is in a modified form that uses +
. So you're most likely to only see +
in URLs in the query string after an ?
.
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
I think the issue is that you've got it just a little upside down.
public class AuroraClient : IAuroraClient
{
private readonly HttpClient _client;
public AuroraClient() : this(new HttpClientHandler())
{
}
public AuroraClient(HttpMessageHandler messageHandler)
{
_client = new HttpClient(messageHandler);
}
}
If you look at the class above, I think this is what you want. Microsoft recommends keeping the client alive for optimal performance, so this type of structure allows you to do that. Also the HttpMessageHandler is an abstract class and therefore mockable. Your test method would then look like this:
[TestMethod]
public void TestMethod1()
{
// Arrange
var mockMessageHandler = new Mock<HttpMessageHandler>();
// Set up your mock behavior here
var auroraClient = new AuroraClient(mockMessageHandler.Object);
// Act
// Assert
}
This allows you to test your logic while mocking the HttpClient's behavior.
Sorry guys, after writing this and trying it myself, I realized that you can't mock the protected methods on the HttpMessageHandler. I subsequently added the following code to allow for injection of a proper mock.
public interface IMockHttpMessageHandler
{
Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);
}
public class MockHttpMessageHandler : HttpMessageHandler
{
private readonly IMockHttpMessageHandler _realMockHandler;
public MockHttpMessageHandler(IMockHttpMessageHandler realMockHandler)
{
_realMockHandler = realMockHandler;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return await _realMockHandler.SendAsync(request, cancellationToken);
}
}
The tests written with this then look something like the following:
[TestMethod]
public async Task GetProductsReturnsDeserializedXmlXopData()
{
// Arrange
var mockMessageHandler = new Mock<IMockHttpMessageHandler>();
// Set up Mock behavior here.
var client = new AuroraClient(new MockHttpMessageHandler(mockMessageHandler.Object));
// Act
// Assert
}
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
If you have a job that continues running, you need to search the job and delete it:
kubectl get job --all-namespaces | grep <name>
and
kubectl delete job <job-name>
You can access the window object as an associative array and set it that way
window["onlyVideo"] = "TEST";
document.write(onlyVideo);
Though, this question has been answered - still I want to share something I recently developed in java script (based on the logic of an old C#. Net implementation I found in Internet) for converting Indian currency values to Words. It can handle up to 40 digits. You can have a look.
Usage: InrToWordConverter.Initialize();. var inWords = InrToWordConverter.ConvertToWord(amount);
Implementation:
htPunctuation = {};
listStaticSuffix = {};
listStaticPrefix = {};
listHelpNotation = {};
var InrToWordConverter = function () {
};
InrToWordConverter.Initialize = function () {
InrToWordConverter.LoadStaticPrefix();
InrToWordConverter.LoadStaticSuffix();
InrToWordConverter.LoadHelpofNotation();
};
InrToWordConverter.ConvertToWord = function (value) {
value = value.toString();
if (value) {
var tokens = value.split(".");
var rsPart = "";
var psPart = "";
if (tokens.length === 2) {
rsPart = String.trim(tokens[0]) || "0";
psPart = String.trim(tokens[1]) || "0";
}
else if (tokens.length === 1) {
rsPart = String.trim(tokens[0]) || "0";
psPart = "0";
}
else {
rsPart = "0";
psPart = "0";
}
htPunctuation = {};
var rsInWords = InrToWordConverter.ConvertToWordInternal(rsPart) || "Zero";
var psInWords = InrToWordConverter.ConvertToWordInternal(psPart) || "Zero";
var result = "Rupees " + rsInWords + "and " + psInWords + " Paise.";
return result;
}
};
InrToWordConverter.ConvertToWordInternal = function (value) {
var convertedString = "";
if (!(value.toString().length > 40))
{
if (InrToWordConverter.IsNumeric(value.toString()))
{
try
{
var strValue = InrToWordConverter.Reverse(value);
switch (strValue.length)
{
case 1:
if (parseInt(strValue.toString()) > 0) {
convertedString = InrToWordConverter.GetWordConversion(value);
}
else {
convertedString = "Zero ";
}
break;
case 2:
convertedString = InrToWordConverter.GetWordConversion(value);
break;
default:
InrToWordConverter.InsertToPunctuationTable(strValue);
InrToWordConverter.ReverseHashTable();
convertedString = InrToWordConverter.ReturnHashtableValue();
break;
}
}
catch (exception) {
convertedString = "Unexpected Error Occured <br/>";
}
}
else {
convertedString = "Please Enter Numbers Only, Decimal Values Are not supported";
}
}
else {
convertedString = "Please Enter Value in Less Then or Equal to 40 Digit";
}
return convertedString;
};
InrToWordConverter.IsNumeric = function (valueInNumeric) {
var isFine = true;
valueInNumeric = valueInNumeric || "";
var len = valueInNumeric.length;
for (var i = 0; i < len; i++) {
var ch = valueInNumeric[i];
if (!(ch >= '0' && ch <= '9')) {
isFine = false;
break;
}
}
return isFine;
};
InrToWordConverter.ReturnHashtableValue = function () {
var strFinalString = "";
var keysArr = [];
for (var key in htPunctuation) {
keysArr.push(key);
}
for (var i = keysArr.length - 1; i >= 0; i--) {
var hKey = keysArr[i];
if (InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) !== "") {
strFinalString = strFinalString + InrToWordConverter.GetWordConversion((htPunctuation[hKey]).toString()) + InrToWordConverter.StaticPrefixFind((hKey).toString());
}
}
return strFinalString;
};
InrToWordConverter.ReverseHashTable = function () {
var htTemp = {};
for (var key in htPunctuation) {
var item = htPunctuation[key];
htTemp[key] = InrToWordConverter.Reverse(item.toString());
}
htPunctuation = {};
htPunctuation = htTemp;
};
InrToWordConverter.InsertToPunctuationTable = function (strValue) {
htPunctuation[1] = strValue.substr(0, 3).toString();
var j = 2;
for (var i = 3; i < strValue.length; i = i + 2) {
if (strValue.substr(i).length > 0) {
if (strValue.substr(i).length >= 2) {
htPunctuation[j] = strValue.substr(i, 2).toString();
}
else {
htPunctuation[j] = strValue.substr(i, 1).toString();
}
}
else {
break;
}
j++;
}
};
InrToWordConverter.Reverse = function (strValue) {
var reversed = "";
for (var i in strValue) {
var ch = strValue[i];
reversed = ch + reversed;
}
return reversed;
};
InrToWordConverter.GetWordConversion = function (inputNumber) {
var toReturnWord = "";
if (inputNumber.length <= 3 && inputNumber.length > 0) {
if (inputNumber.length === 3) {
if (parseInt(inputNumber.substr(0, 1)) > 0) {
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1)) + "Hundred ";
}
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(2, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 2)
{
var tempString = InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 2));
if (tempString === "")
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1) + "0");
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(1, 1));
}
toReturnWord = toReturnWord + tempString;
}
if (inputNumber.length === 1)
{
toReturnWord = toReturnWord + InrToWordConverter.StaticSuffixFind(inputNumber.substr(0, 1));
}
}
return toReturnWord;
};
InrToWordConverter.StaticSuffixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticSuffix) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
valueFromNumber = listStaticSuffix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticPrefixFind = function (numberKey) {
var valueFromNumber = "";
for (var key in listStaticPrefix) {
if (String.trim(key) === String.trim(numberKey)) {
valueFromNumber = listStaticPrefix[key].toString();
break;
}
}
return valueFromNumber;
};
InrToWordConverter.StaticHelpNotationFind = function (numberKey) {
var helpText = "";
for (var key in listHelpNotation) {
if (String.trim(key.toString()) === String.trim(numberKey)) {
helpText = listHelpNotation[key].toString();
break;
}
}
return helpText;
};
InrToWordConverter.LoadStaticPrefix = function () {
listStaticPrefix[2] = "Thousand ";
listStaticPrefix[3] = "Lac ";
listStaticPrefix[4] = "Crore ";
listStaticPrefix[5] = "Arab ";
listStaticPrefix[6] = "Kharab ";
listStaticPrefix[7] = "Neel ";
listStaticPrefix[8] = "Padma ";
listStaticPrefix[9] = "Shankh ";
listStaticPrefix[10] = "Maha-shankh ";
listStaticPrefix[11] = "Ank ";
listStaticPrefix[12] = "Jald ";
listStaticPrefix[13] = "Madh ";
listStaticPrefix[14] = "Paraardha ";
listStaticPrefix[15] = "Ant ";
listStaticPrefix[16] = "Maha-ant ";
listStaticPrefix[17] = "Shisht ";
listStaticPrefix[18] = "Singhar ";
listStaticPrefix[19] = "Maha-singhar ";
listStaticPrefix[20] = "Adant-singhar ";
};
InrToWordConverter.LoadStaticSuffix = function () {
listStaticSuffix[1] = "One ";
listStaticSuffix[2] = "Two ";
listStaticSuffix[3] = "Three ";
listStaticSuffix[4] = "Four ";
listStaticSuffix[5] = "Five ";
listStaticSuffix[6] = "Six ";
listStaticSuffix[7] = "Seven ";
listStaticSuffix[8] = "Eight ";
listStaticSuffix[9] = "Nine ";
listStaticSuffix[10] = "Ten ";
listStaticSuffix[11] = "Eleven ";
listStaticSuffix[12] = "Twelve ";
listStaticSuffix[13] = "Thirteen ";
listStaticSuffix[14] = "Fourteen ";
listStaticSuffix[15] = "Fifteen ";
listStaticSuffix[16] = "Sixteen ";
listStaticSuffix[17] = "Seventeen ";
listStaticSuffix[18] = "Eighteen ";
listStaticSuffix[19] = "Nineteen ";
listStaticSuffix[20] = "Twenty ";
listStaticSuffix[30] = "Thirty ";
listStaticSuffix[40] = "Fourty ";
listStaticSuffix[50] = "Fifty ";
listStaticSuffix[60] = "Sixty ";
listStaticSuffix[70] = "Seventy ";
listStaticSuffix[80] = "Eighty ";
listStaticSuffix[90] = "Ninty ";
};
InrToWordConverter.LoadHelpofNotation = function () {
listHelpNotation[2] = "=1,000 (3 Trailing Zeros)";
listHelpNotation[3] = "=1,00,000 (5 Trailing Zeros)";
listHelpNotation[4] = "=1,00,00,000 (7 Trailing Zeros)";
listHelpNotation[5] = "=1,00,00,00,000 (9 Trailing Zeros)";
listHelpNotation[6] = "=1,00,00,00,00,000 (11 Trailing Zeros)";
listHelpNotation[7] = "=1,00,00,00,00,00,000 (13 Trailing Zeros)";
listHelpNotation[8] = "=1,00,00,00,00,00,00,000 (15 Trailing Zeros)";
listHelpNotation[9] = "=1,00,00,00,00,00,00,00,000 (17 Trailing Zeros)";
listHelpNotation[10] = "=1,00,00,00,00,00,00,00,00,000 (19 Trailing Zeros)";
listHelpNotation[11] = "=1,00,00,00,00,00,00,00,00,00,000 (21 Trailing Zeros)";
listHelpNotation[12] = "=1,00,00,00,00,00,00,00,00,00,00,000 (23 Trailing Zeros)";
listHelpNotation[13] = "=1,00,00,00,00,00,00,00,00,00,00,00,000 (25 Trailing Zeros)";
listHelpNotation[14] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,000 (27 Trailing Zeros)";
listHelpNotation[15] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (29 Trailing Zeros)";
listHelpNotation[16] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (31 Trailing Zeros)";
listHelpNotation[17] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (33 Trailing Zeros)";
listHelpNotation[18] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (35 Trailing Zeros)";
listHelpNotation[19] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (37 Trailing Zeros)";
listHelpNotation[20] = "=1,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,000 (39 Trailing Zeros)";
};
if (!String.trim) {
String.trim = function (str) {
var result = "";
var firstNonWhiteSpaceFound = false;
var startIndex = -1;
var endIndex = -1;
if (str) {
for (var i = 0; i < str.length; i++) {
if (firstNonWhiteSpaceFound === false) {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
firstNonWhiteSpaceFound = true;
startIndex = i;
endIndex = i;
}
}
else {
if (str[i] === ' ' || str[i] === '\t') {
continue;
}
else {
endIndex = i;
}
}
}
if (startIndex !== -1 && endIndex !== -1) {
result = str.slice(startIndex, endIndex + 1);
}
}
return result;
};
}
You must turn off "background refresh" for all queries. If background refresh is on, Excel works ahead while the refresh occurs and you have problems.
Data > Connections > Properties > (uncheck) enable background refresh
Changing the mirrorlist URL from https to http fixed the issue for me.
This is a bit confusing, but follow these steps to save the session.
To open the session, double click on particular saved session.
LIMIT is usually applied as the last operation, so the result will first be sorted and then limited to 20. In fact, sorting will stop as soon as first 20 sorted results are found.
INSERT INTO [DatabaseName1].dbo.[TableName1] SELECT * FROM [DatabaseName2].dbo.[TableName2]
WHERE [YourPK] not in (select [YourPK] from [DatabaseName1].dbo.[TableName1])
Try this code
var path: String = NSBundle.mainBundle().pathForResource("nameOfFile", ofType: "svg")!
var url: NSURL = NSURL.fileURLWithPath(path) //Creating a URL which points towards our path
//Creating a page request which will load our URL (Which points to our path)
var request: NSURLRequest = NSURLRequest(URL: url)
webView.loadRequest(request) //Telling our webView to load our above request
? TWO Simple Solutions:
To install the latest version of node and reinstall the old version packages just run the following command.
nvm install node --reinstall-packages-from=node
To install the latest lts
(long term support) version of node and reinstall the old version packages just run the following command.
nvm install --lts /* --reinstall-packages-from=node
Here's a GIF to support this answer.
While you are doing it - alias it as something else (or better yet, use a view or an SP and deprecate the old direct access method).
SELECT [from] AS TransferFrom -- Or something else more suitable
FROM TableName
Updated OrderByPipe: fixed not sorting strings.
create a OrderByPipe class:
import { Pipe, PipeTransform } from "@angular/core";
@Pipe( {
name: 'orderBy'
} )
export class OrderByPipe implements PipeTransform {
transform( array: Array<any>, orderField: string, orderType: boolean ): Array<string> {
array.sort( ( a: any, b: any ) => {
let ae = a[ orderField ];
let be = b[ orderField ];
if ( ae == undefined && be == undefined ) return 0;
if ( ae == undefined && be != undefined ) return orderType ? 1 : -1;
if ( ae != undefined && be == undefined ) return orderType ? -1 : 1;
if ( ae == be ) return 0;
return orderType ? (ae.toString().toLowerCase() > be.toString().toLowerCase() ? -1 : 1) : (be.toString().toLowerCase() > ae.toString().toLowerCase() ? -1 : 1);
} );
return array;
}
}
in your controller:
@Component({
pipes: [OrderByPipe]
})
or in your
declarations: [OrderByPipe]
in your html:
<tr *ngFor="let obj of objects | orderBy : ObjFieldName: OrderByType">
ObjFieldName: object field name you want to sort;
OrderByType: boolean; true: descending order; false: ascending;
Just like any other environment variable, with SET
:
SET PATH=%PATH%;c:\whatever\else
If you want to have a little safety check built in first, check to see if the new path exists first:
IF EXIST c:\whatever\else SET PATH=%PATH%;c:\whatever\else
If you want that to be local to that batch file, use setlocal
:
setlocal
set PATH=...
set OTHERTHING=...
@REM Rest of your script
Read the docs carefully for setlocal
/endlocal
, and have a look at the other references on that site - Functions is pretty interesting too and the syntax is tricky.
The Syntax page should get you started with the basics.
There's nothing here explaining the use of multiple variables, so I'll chuck it in just incase someone needs it in the future.
You need to concatenate multiple variables:
header('Location: http://linkhere.com?var1='.$var1.'&var2='.$var2.'&var3'.$var3);
The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)
var otherInput = $(this).closest('.row').find('.inputQty');
That goes up to a row level, then back down to .inputQty
.
For Xamarin.iOS developers, I found it from this document https://developer.xamarin.com/api/type/Foundation.NSAttributedString/
textField.AttributedPlaceholder = new NSAttributedString ("Hello, world",new UIStringAttributes () { ForegroundColor = UIColor.Red });
This simplest (using Calendar, sorry) is:
int year = Calendar.getInstance().get(Calendar.YEAR);
There is also the new Date and Time API JSR, as well as Joda Time
If you're wondering whether to type HEAD^
or HEAD~
in your command, just use either:
They're both names for the same commit - the first parent of the current commit.
Likewise with master~
and master^
- both names for the first parent of master.
In the same way as 2 + 2
and 2 x 2
are both 4
- they're different ways of getting there, but the answer is the same.
This answers the question: What's the difference between HEAD^ and HEAD~ in Git?
If you just did a merge (so your current commit has more than one parent), or you're still interested in how the caret and tilde work, see the other answers (which I won't duplicate here) for an in-depth explanation, as well as how to use them repeatedly (e.g.HEAD~~~
), or with numbers (e.g.HEAD^2
). Otherwise, I hope this answer saves you some time.
Build a Python list and convert that to a Numpy array. That takes amortized O(1) time per append + O(n) for the conversion to array, for a total of O(n).
a = []
for x in y:
a.append(x)
a = np.array(a)
One way I would do this without javascript would be to add a set of radio buttons that define the action to be taken:
Then the action script would take different actions depending on the value of the radio button set.
Another way would be to put two forms on the page as you suggested, just not nested. The layout may be difficult to control though:
<form name="editform" action="the_action_url" method="post"> <input type="hidden" name="task" value="update" /> <input type="text" name="foo" /> <input type="submit" name="save" value="Save" /> </form> <form name="delform" action="the_action_url" method="post"> <input type="hidden" name="task" value="delete" /> <input type="hidden" name="post_id" value="5" /> <input type="submit" name="delete" value="Delete" /> </form>
Using the hidden "task" field in the handling script to branch appropriately.
Sorry for the delay. I was with the same problem and I found a link with good answers, could that will help new guys
All credits for BinaryIntellect web site and the authors
Basically, there are four situations: using differents verbs, using routing, overload marking with [NoAction] attribute and change the action attribute name with [ActionName]
So, depends that's your requiriments and your situation.
Howsoever, follow the link:
Link: http://www.binaryintellect.net/articles/8f9d9a8f-7abf-4df6-be8a-9895882ab562.aspx
div[disabled]
{
pointer-events: none;
opacity: 0.7;
}
The above code makes the contents of the div disabled. You can make div disabled by adding disabled attribute.
<div disabled>
/* Contents */
</div>
Eclipse can't work out what you want to run and since you've not run anything before, it can't try re-running that either.
Instead of clicking the green 'run' button, click the dropdown next to it and chose Run Configurations. On the Android tab, make sure it's set to your project. In the Target tab, set the tick box and options as appropriate to target your device. Then click Run. Keep an eye on your Console tab in Eclipse - that'll let you know what's going on. Once you've got your run configuration set, you can just hit the green 'run' button next time.
Sometimes getting everything to talk to your device can be problematic to begin with. Consider using an AVD (i.e. an emulator) as alternative, at least to begin with if you have problems. You can easily create one from the menu Window -> Android Virtual Device Manager within Eclipse.
To view the progress of your project being installed and started on your device, check the console. It's a panel within Eclipse with the tabs Problems/Javadoc/Declaration/Console/LogCat etc. It may be minimised - check the tray in the bottom right. Or just use Window/Show View/Console from the menu to make it come to the front. There are two consoles, Android and DDMS - there is a dropdown by its icon where you can switch.
Yes you can use any client as long as it is supported by socket.io. No matter whether its node, java, android or swift. All you have to do is install the client package of socket.io.
To quickly find a meaningful error message by inspecting the error during debugging:
Add a quick watch for:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors
Drill down into EntityValidationErrors like this:
(collection item e.g. [0]) > ValidationErrors > (collection item e.g. [0]) > ErrorMessage
Try this:
if(Math.floor(id) == id && $.isNumeric(id))
alert('yes its an int!');
$.isNumeric(id)
checks whether it's numeric or not
Math.floor(id) == id
will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.
Perhaps you want to do
soup.find("li", { "class" : "test" }).find('a')
document.getElementById('hello').classList.add('someClass');
The .add
method will only add the class if it doesn't already exist on the element. So no need to worry about duplicate class names.
While checking null or Empty
value for a column in my project, I noticed that there are some support concern in various Databases.
Every Database doesn't support TRIM
method.
Below is the matrix just to understand the supported methods by different databases.
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:
TRIM(), RTRIM(), LTRIM()
RTRIM(), LTRIM()
RTRIM(), LTRIM()
How to Check Empty/Null :-
Below are two different ways according to different Databases-
The syntax for these trim functions are:
Use of Trim to check-
SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL
Use of LTRIM & RTRIM to check-
SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL
Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName
from UserDetails
table if it has an empty LastName
Hoping this will help you :)
You can do an http DELETE via a URL like /users/1/roles/2. That would be the most RESTful way to do it.
Otherwise I guess you can just pass the user id as part of the query params? Something like
$http.delete('/roles/' + roleid, {params: {userId: userID}}).then...
Your class shoud look something like this:
class Something { int[] array; //global array, replace type of course void function1() { array = new int[10]; //let say you declare it here that will be 10 integers in size } void function2() { array[0] = 12; //assing value at index 0 to 12. } }
That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.
Combining and organizing all the current answers into one answer, then adding my own research:
Brief summary of Microsoft gadget development:
What are they written in? Windows Vista/Seven gadgets are developed in a mix of XML, HTML, CSS, and some IE scripting language. It is also possible to use C# with the latest release of Script#.
How are they packaged/deployed? The actual gadgets are stored in *.gadget files, which are simply the text source files listed above compressed into a single zip file.
Useful references for gadget development:
where do I start? Good introductory references to Windows Vista/Seven gadget development:
If you are willing to use offline resources, this book appears to be an excellent resource:
What do I need to know? Some other useful references; not necessarily instructional
Update: Well, this has proven to be a popular answer~ Sharing my own recent experience with Windows 7 gadget development:
Perhaps the easiest way to get started with Windows 7 gadget development is to modify a gadget that has already been developed. I recently did this myself because I wanted a larger clock gadget. Unable to find any, I tinkered with a copy of the standard Windows clock gadget until it was twice as large. I recommend starting with the clock gadget because it is fairly small and well-written. Here is the process I used:
C:\Program Files\Windows Sidebar\Gadgets\Clock.Gadget\
<name>Clock</name>
This is the name that will be displayed in the "Gadgets Gallery" window.%LOCALAPPDATA%\Microsoft\Windows Sidebar\
)just wanted to leave my .scss
example here, I think its kinda best practice, especially I think if you do customization its nice to set the width only once! It is not clever to apply it everywhere, you will increase the human factor exponentially.
Im looking forward for your feedback!
// Set your parameters
$widthSmall: 768px;
$widthMedium: 992px;
// Prepare your "function"
@mixin in-between {
@media (min-width:$widthSmall) and (max-width:$widthMedium) {
@content;
}
}
// Apply your "function"
main {
@include in-between {
//Do something between two media queries
padding-bottom: 20px;
}
}
Python DBAPI spec also define 'lastrowid' attribute for cursor object, so...
id = cursor.lastrowid
...should work too, and it's per-connection based obviously.
Old thread, but learned something new, hope this might help someone.
If you want to change the background color but retain other styles, then below might help.
button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
I believe that you are looking for the java.lang.BigDecimal class.
Here is something I think will work for what you want, using a decorator.
class LogWrappedFunction(object):
def __init__(self, function):
self.function = function
def logAndCall(self, *arguments, **namedArguments):
print "Calling %s with arguments %s and named arguments %s" %\
(self.function.func_name, arguments, namedArguments)
self.function.__call__(*arguments, **namedArguments)
def logwrap(function):
return LogWrappedFunction(function).logAndCall
@logwrap
def doSomething(spam, eggs, foo, bar):
print "Doing something totally awesome with %s and %s." % (spam, eggs)
doSomething("beans","rice", foo="wiggity", bar="wack")
Run it, it will yield the following output:
C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.
You can use below as an alternative.
from time import strptime
strptime('Feb','%b').tm_mon
import calendar
calendar.month_abbr[2]
or
calendar.month[2]
Java 8+ version:
Files.createDirectories(Paths.get("/Your/Path/Here"));
The Files.createDirectories()
creates a new directory and parent directories that do not exist. This method does not throw an exception if the directory already exists.
Check out Lists.partition(java.util.List, int)
from Google Guava:
Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing
[a, b, c, d, e]
with a partition size of 3 yields[[a, b, c]
,[d, e]]
-- an outer list containing two inner lists of three and two elements, all in the original order.
In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class.
So in my humble opinion this is a more complete example based on Greg's one:
<?php
class Hello
{
/**
* Construct won't be called inside this class and is uncallable from
* the outside. This prevents instantiating this class.
* This is by purpose, because we want a static class.
*/
private function __construct() {}
private static $greeting = 'Hello';
private static $initialized = false;
private static function initialize()
{
if (self::$initialized)
return;
self::$greeting .= ' There!';
self::$initialized = true;
}
public static function greet()
{
self::initialize();
echo self::$greeting;
}
}
Hello::greet(); // Hello There!
?>
PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
I do this all the time, all I do is
WriteXLS::WriteXLS(
all.dataframes,
ExcelFileName = xl.filename,
AdjWidth = T,
AutoFilter = T,
FreezeRow = 1,
FreezeCol = 2,
BoldHeaderRow = T,
verbose = F,
na = '0'
)
and all those data frames come from here
all.dataframes <- vector()
for (obj.iter in all.objects) {
obj.name <- obj.iter
obj.iter <- get(obj.iter)
if (class(obj.iter) == 'data.frame') {
all.dataframes <- c(all.dataframes, obj.name)
}
obviously sapply routine would be better here
This might be helpful
I converted this from C# ('From: http://www.dotnetpools.com/Article/ArticleDetiail/?articleId=74)
Private Sub dgv_EmployeeTraining_RowPostPaint(sender As Object, e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)
Handles dgv_EmployeeTraining.RowPostPaint
If e.RowIndex < Me.dgv_EmployeeTraining.RowCount - 1 Then
Dim dgvRow As DataGridViewRow = Me.dgv_EmployeeTraining.Rows(e.RowIndex)
'<== This is the header Name
'If CInt(dgvRow.Cells("EmployeeStatus_Training_e26").Value) <> 2 Then
'<== But this is the name assigned to it in the properties of the control
If CInt(dgvRow.Cells("DataGridViewTextBoxColumn15").Value.ToString) <> 2 Then
dgvRow.DefaultCellStyle.BackColor = Color.FromArgb(236, 236, 255)
Else
dgvRow.DefaultCellStyle.BackColor = Color.LightPink
End If
End If
End Sub
You don't need to apply corner radius to your app icon, you can just apply square icons. The device is automatically applying corner radius.
After my investigation, I came up to this solution:
//writing the below line into the top of my style.css file
@import url('https://fonts.googleapis.com/css?family=Assistant:200,300,400,600,700,800&subset=hebrew');
MUST OBSERVE:
We must need to write the font-weight
correctly of this font. For example: font-weight:900;
will not work as we have not included 900
like 200,300,400,600,700,800
into the URL address while importing from Google with the above link. We can add or include 900
to the above URL, but that will work only if the above Google Font has this option while embedding.
In the model, write the below code;
public $timestamps = false;
This would work.
Explanation : By default laravel will expect created_at & updated_at column in your table. By making it to false it will override the default setting.
You can just go for String
replace method.-
line1 = line1.replace("\"", "");
If running on Windows, you could consider using win32crypt library. It allows storage and retrieval of protected data (keys, passwords) by the user that is running the script, thus passwords are never stored in clear text or obfuscated format in your code. I am not sure if there is an equivalent implementation for other platforms, so with the strict use of win32crypt your code is not portable.
I believe the module can be obtained here: http://timgolden.me.uk/pywin32-docs/win32crypt.html
If you are using a G Suite account, anything you try will fail. At least at the time, this answer is being typed. You must use @gmail.com
account, anything else like @example.com
will not work.
After you use the gmail.com
address. You just need to update .env
as most of the people already mentioned.
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=****@gmail.com
MAIL_PASSWORD=16digitapppassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=****@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Don't forget to create an App password, if you don't see the option probably your 2-factor authentication is not enabled. And there is no need to allow less secure apps if you follow this approach.
I am not sure if I see this option here. You can just create a /folder
in your repository and use it directly:
[a relative link](/folder/myrelativefile.md)
No blob or tree or repository name is needed, and it works like a charm.
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 LIMIT 1001, 1000
This query is not correct (or at least i don't know a possible way to use limit in UPDATE queries), you should put a where
condition on you primary key (this assumes you have an auto_increment column as your primary key, if not provide more details):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE primary_key BETWEEN 1001 AND 2000
For the second query you must use IS
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE panel_id is null
EDIT - if your primary_key is a column named MAX+1 you query should be (with backticks as stated correctly in the comment):
UPDATE `smartmeter_usage`.`users_reporting` SET panel_id = 3 WHERE `MAX+1` BETWEEN 1001 AND 2000
To update the rows with MAX+1 from 1001 TO 2000 (including 1001 and 2000)
Complete guide for working with unsigned bytes in Java:
(Source for this answer.)
The Java Language does not provide anything like the unsigned
keyword. A byte
according to the language spec represents a value between -128 - 127. For instance, if a byte
is cast to an int
Java will interpret the first bit as the sign and use sign extension.
That being said, nothing prevents you from viewing a byte
simply as 8 bits and interpret those bits as a value between 0 and 255. Just keep in mind that there's nothing you can do to force your interpretation upon someone else's method. If a method accepts a byte
, then that method accepts a value between -128 and 127 unless explicitly stated otherwise.
Here are a couple of useful conversions / manipulations for your convenience:
// From int to unsigned byte
int i = 200; // some value between 0 and 255
byte b = (byte) i; // 8 bits representing that value
// From unsigned byte to int
byte b = 123; // 8 bits representing a value between 0 and 255
int i = b & 0xFF; // an int representing the same value
(Or, if you're on Java 8+, use Byte.toUnsignedInt
.)
Best way is to use the above conversions:
// Parse an unsigned byte
byte b = (byte) Integer.parseInt("200");
// Print an unsigned byte
System.out.println("Value of my unsigned byte: " + (b & 0xFF));
The 2-complement representation "just works" for addition, subtraction and multiplication:
// two unsigned bytes
byte b1 = (byte) 200;
byte b2 = (byte) 15;
byte sum = (byte) (b1 + b2); // 215
byte diff = (byte) (b1 - b2); // 185
byte prod = (byte) (b2 * b2); // 225
Division requires manual conversion of operands:
byte ratio = (byte) ((b1 & 0xFF) / (b2 & 0xFF));
Several of the suggestions above use global variables. This is not a good solution for the problem. The count is specific to one element, and you can use jQuery's data
function to bind an item of data to an element:
$('#counter').data('count', 0);
$('#update').click(function(){
$('#counter').html(function(){
var $this = $(this),
count = $this.data('count') + 1;
$this.data('count', count);
return count;
});
});
Note also that this uses the callback syntax of html
to make the code more fluent and fast.
From What's this "serialization" thing all about?:
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
So, implement the Serializable
interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
Based on previous answers. I resolved my issue by removing global variable at package level to procedure, since there was no impact in my case.
Original script was
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
V_ERROR_NAME varchar2(200) := '';
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
Rewritten the same without global variable V_ERROR_NAME
and moved to procedure under package level as
Modified Code
create or replace PACKAGE BODY APPLICATION_VALIDATION AS
PROCEDURE APP_ERROR_X47_VALIDATION ( PROCESS_ID IN VARCHAR2 ) AS
**V_ERROR_NAME varchar2(200) := '';**
BEGIN
------ rules for validation... END APP_ERROR_X47_VALIDATION ;
/* Some more code
*/
END APPLICATION_VALIDATION; /
assign is what you are looking for.
assign("x", 5)
x
[1] 5
but buyer beware.
See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f
I've just setup a spreadsheet that uses Bazaar, with manual checkin/out via TortiseBZR. Given that the topic helped me with the save portion, I wanted to post my solution here.
The solution for me was to create a spreadsheet that exports all modules on save, and removes and re-imports the modules on open. Yes, this could be potentially dangerous for converting existing spreadsheets.
This allows me to edit the macros in the modules via Emacs (yes, emacs) or natively in Excel, and commit my BZR repository after major changes. Because all the modules are text files, the standard diff-style commands in BZR work for my sources except the Excel file itself.
I've setup a directory for my BZR repository, X:\Data\MySheet. In the repo are MySheet.xls and one .vba file for each of my modules (ie: Module1Macros). In my spreadsheet I've added one module that is exempt from the export/import cycle called "VersionControl". Each module to be exported and re-imported must end in "Macros".
Contents of the "VersionControl" module:
Sub SaveCodeModules()
'This code Exports all VBA modules
Dim i%, sName$
With ThisWorkbook.VBProject
For i% = 1 To .VBComponents.Count
If .VBComponents(i%).CodeModule.CountOfLines > 0 Then
sName$ = .VBComponents(i%).CodeModule.Name
.VBComponents(i%).Export "X:\Tools\MyExcelMacros\" & sName$ & ".vba"
End If
Next i
End With
End Sub
Sub ImportCodeModules()
With ThisWorkbook.VBProject
For i% = 1 To .VBComponents.Count
ModuleName = .VBComponents(i%).CodeModule.Name
If ModuleName <> "VersionControl" Then
If Right(ModuleName, 6) = "Macros" Then
.VBComponents.Remove .VBComponents(ModuleName)
.VBComponents.Import "X:\Data\MySheet\" & ModuleName & ".vba"
End If
End If
Next i
End With
End Sub
Next, we have to setup event hooks for open / save to run these macros. In the code viewer, right click on "ThisWorkbook" and select "View Code". You may have to pull down the select box at the top of the code window to change from "(General)" view to "Workbook" view.
Contents of "Workbook" view:
Private Sub Workbook_Open()
ImportCodeModules
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
SaveCodeModules
End Sub
I'll be settling into this workflow over the next few weeks, and I'll post if I have any problems.
Thanks for sharing the VBComponent code!
Make sure you can run powershell scripts (it is disabled by default). Likely you have already done this. http://technet.microsoft.com/en-us/library/ee176949.aspx
Set-ExecutionPolicy RemoteSigned
Run this python script on your powershell script helloworld.py
:
# -*- coding: iso-8859-1 -*-
import subprocess, sys
p = subprocess.Popen(["powershell.exe",
"C:\\Users\\USER\\Desktop\\helloworld.ps1"],
stdout=sys.stdout)
p.communicate()
This code is based on python3.4 (or any 3.x series interpreter), though it should work on python2.x series as well.
C:\Users\MacEwin\Desktop>python helloworld.py
Hello World
I solved this problem by first verifying the that remote did not have anything checked out (it really was not supposed to), and then made it bare with:
$ git config --bool core.bare true
After that git push worked fine.
Better way is to autowire with a constructor:
private final HttpServletRequest httpServletRequest;
public ClassConstructor(HttpServletRequest httpServletRequest){
this.httpServletRequest = httpServletRequest;
}
I solved this problem, I changed build system to Legacy Build System
from New Build System
In Xcode v10+, select File > Project Settings
In previous Xcode, select File > Workspace Settings
Change Build System to Legacy Build System
from New Build System
--> Click Done.
The best way to access files from resource folder inside a jar is it to use the InputStream via getResourceAsStream
. If you still need a the resource as a file instance you can copy the resource as a stream into a temporary file (the temp file will be deleted when the JVM exits):
public static File getResourceAsFile(String resourcePath) {
try {
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(resourcePath);
if (in == null) {
return null;
}
File tempFile = File.createTempFile(String.valueOf(in.hashCode()), ".tmp");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
//copy stream
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
return tempFile;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
You will need to configure your apache2.conf to make phpMyAdmin works.
sudo nano /etc/apache2/apache2.conf
Then add the following line to the end of the file.
Include /etc/phpmyadmin/apache.conf
Then restart apache
sudo service apache2 restart
Here is a simple explanation. A static method is associated with a class while an instance method is associated with a particular object. Overrides allow calling the different implementation of the overridden methods associated with the particular object. So it is counter-intuitive to override static method which is not even associated with objects but the class itself in the first place. So static methods cannot be overridden based on what object is calling it, it will always be associated with the class where it was created.
In a function, use as
render: function (args) {
if (args.value != 0)
return (parseFloat(args.value).toFixed(2));
},
looks to me yum install glibc.i686 should have worked. Unless Peter was not root. He has the 64 bit glib installed, he is installing a 32 bit package that requires the 32 bit glib which is glib.i686 for intel processors.
Use any()
.
if any(t < 0 for t in x):
# do something
You could use removeStart
and removeEnd
from Apache Commons Lang StringUtils
When we will capture the image from Camera in android then Uri or data.getdata()
comes null. we have two solutions to resolve this issue.
I will implement all methods here, Please carefully watch and read these:-
First i will tell how to get Uri from Bitmap Image: Complete code is :
First we will capture image through Intent that will same for both methods so this code i will write one time only here :
// Capture Image
captureImg.setOnClickListener(new View.OnClickListener(){
@Override public void onClick(View view){
Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager())!=null){
startActivityForResult(intent,reqcode);
}
}
});
Now we will Implement OnActivityResult :-(This will be same for both above 2 methods):-
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == reqcode && resultCode == RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ImageView.setImageBitmap(photo);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), photo);
//Show Uri path based on Image
Toast.makeText(LiveImage.this, "Here " + tempUri, Toast.LENGTH_LONG).show();
//Show Uri path based on Cursor Content Resolver
Toast.makeText(this, "Real path for URI : " + getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
}
}
Now we will create all above method to create Uri from Image and Cursor methods via classes:
Now URI path from Bitmap Image
private Uri getImageUri(Context applicationContext, Bitmap photo)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
return Uri.parse(path);
}
\ Uri from Real path of saved image
public String getRealPathFromURI(Uri uri)
{
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
If you already use jitpack.io or any repository. You can add google repository like this:
allprojects {
repositories {
maven { url "https://jitpack.io" }
maven { url "https://maven.google.com" }
}
}
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
System.out.println(String.format("%-20s= %s" , "label", "content" ));
The output looks like this:
label = content
As a reference I recommend Javadoc on formatter syntax
On order to get the above to work (I needed a pair as the key of a dictionary). I had to add:
public override Boolean Equals(Object o)
{
Pair<T, U> that = o as Pair<T, U>;
if (that == null)
return false;
else
return this.First.Equals(that.First) && this.Second.Equals(that.Second);
}
and once I did that I also added
public override Int32 GetHashCode()
{
return First.GetHashCode() ^ Second.GetHashCode();
}
to suppress a compiler warning.
Another take on this that hasn't been mentioned here is that, when in debug, the project may build, but it won't run, giving the error message displayed in the question.
If this is the case, another option to look at is the output file versus the target file. These should match.
A quick way to check the output file is to go to the project's property pages, then go to Configuration Properties -> Linker -> General (In VS 2013 - exact path may vary depending on IDE version).
There is an "Output File" setting. If it is not $(OutDir)$(TargetName)$(TargetExt)
, then you may run into issues.
This is also discussed in more detail here.
This code allows you to autoplay iframe video
<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in
{
and}
. Since{
can not be escaped, this syntax will only be recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:<?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
This sounds more like you want a tooltip for the link selected. There are many jQuery tooltips, try out jQuery qTip. It has a lot of options and is easy to change the styles.
Otherwise if you want to do this yourself you can use the jQuery .position()
. More info about .position()
is on http://api.jquery.com/position/
$("#element").position();
will return the current position of an element relative to the offset parent.
There is also the jQuery .offset(); which will return the position relative to the document.
for select2 v4.0.0 slightly different
$(".itemSearch").select2({
tags: true,
multiple: true,
tokenSeparators: [',', ' '],
minimumInputLength: 2,
minimumResultsForSearch: 10,
ajax: {
url: URL,
dataType: "json",
type: "GET",
data: function (params) {
var queryParameters = {
term: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.tag_value,
id: item.tag_id
}
})
};
}
}
});
You can put this configuration in your settings.xml file:
<repository>
<id>mvnrepository</id>
<url>http://repo1.maven.org/maven2</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
editText.setFocusable(false);
editText.setClickable(false);
To give an in-action memory usage aspect, I did an experiment with Strong, Soft, Weak & Phantom references under heavy load with heavy objects by retaining them till end of program. Then monitored heap usage & GC behavior. These metrics may vary case by case basis but surely gives high level understanding. Below are findings.
Heap & GC Behavior under heavy load
You can get more in depth graphs, stats, observations for this experiment here.
func buttonAction(sender:UIButton!)
{
var position: CGPoint = sender.convertPoint(CGPointZero, toView: self.tablevw)
let indexPath = self.tablevw.indexPathForRowAtPoint(position)
let cell: TableViewCell = tablevw.cellForRowAtIndexPath(indexPath!) as TableViewCell
println(indexPath?.row)
println("Button tapped")
}
If you are not using fig and ax plot objects you can do it like so:
import matplotlib.pyplot as plt
# do plot specifics
plt.legend('')
plt.show()
Hi I feel str_getcsv
— Parse a CSV string into an array is the best option for you.
You need to upload the file to sever
parse the file using str_getcsv.
run through the array and align as per u need in your website.
Using PHP from the command line
Use "
instead of '
on Windows when using the CLI version with -r
:
php -r "echo 1;"
-- correct
php -r 'echo 1;'
-- incorrect
PHP Parse error: syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1
Don't forget the semicolon to close the line.
Here's the answer that I found for my question:
urlList1.FocusedItem.Index
And I am getting selected item value by:
urlList1.Items(urlList1.FocusedItem.Index).SubItems(0).Text
You are accesing localhost
, meaning you have a web server running on your machine. To access it from Internet, you need to assign a public IP address to your machine. Then you can access http://<public_ip>:<port>/
. Port number is normally 80.
function ready(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();}
Use like
ready(function(){
//some code
});
(function(fn){var d=document;(d.readyState=='loading')?d.addEventListener('DOMContentLoaded',fn):fn();})(function(){
//Some Code here
//DOM is avaliable
//var h1s = document.querySelector("h1");
});
Support: IE9+
wt = tt - cpu tm.
Tt = cpu tm + wt.
Where wt
is a waiting time and tt
is turnaround time. Cpu time is also called burst time.
For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags
Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).
Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.
Or you can use this javascript
$(function () {
$("#projectKey").change(function () {
alert($('#projectKey option:selected').text());
});
});
From: https://github.blog/changelog/2019-04-09-webhooks-ip-changes/
April 9, 2019
Webhooks IP changes
The IP addresses we use to send webhooks from are broadening to encompass a larger range.
We are adding IP’s within
140.82.112.0/20
to the current pool from192.30.252.0/22
.
The easiest way is to use Resource Manager
Then you can select each density
And after importing you can see the 6 different versions of this image
Pandas will start looking from where your current python file is located. Therefore you can move from your current directory to where your data is located with '..' For example:
pd.read_csv('../../../data_folder/data.csv')
Will go 3 levels up and then into a data_folder (assuming it's there) Or
pd.read_csv('data_folder/data.csv')
assuming your data_folder is in the same directory as your .py file.
Try this
HTML
<select class="form-control"name="country">
<option class="servce_pro_disabled">Select Country</option>
<option class="servce_pro_disabled" value="Aruba" id="cl_country_option">Aruba</option>
</select>
CSS
.form-control option:first-child {
display: none;
}
document.referrer
in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). Specified by DOM Level 2. More here.
window.history
allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you'd been to.
If you're dealing with state moving around your own site, then it's possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.
For the 24-hour time, you need to use HH24
instead of HH
.
For the 12-hour time, the AM/PM indicator is written as A.M.
(if you want periods in the result) or AM
(if you don't). For example:
SELECT invoice_date,
TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
FROM invoices
;
For more information on the format models you can use with TO_CHAR
on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Firstly, it would appear that ' should be avoided - The curse of '
Secondly, if there is ever any chance that you're going to generate markup to be returned via AJAX calls, you should avoid the entity names (As not all of the HTML entities are valid in XML) and use the &#XXXX; syntax instead.
Failure to do so may result in the markup being considered as invalid XML.
The entity that is most likely to be affected by this is , which should be replaced by  
On Windows, here's how to resolve:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
C:\Program Files,C:\Program Files (x86)
and C:\ProgramData
Another approach, which is the standard way since DOM2 to bind this
within the event listener, that let you always remove the listener (among other benefits), is the handleEvent(evt)
method from the EventListener
interface:
var obj = {
handleEvent(e) {
// always true
console.log(this === obj);
}
};
document.body.addEventListener('click', obj);
Detailed information about using handleEvent
can be found here: https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38
If you are using the Python wrappers, then (assuming your matrix name is mat):
mat.shape gives you an array of the type- [height, width, channels]
mat.size gives you the size of the array
Sample Code:
import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size
The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:
DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';
I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database
So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.
To have a truly responsive (i.e. width: 100%, height: auto
) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.
Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.
So all we need to do is create a View with width: "100%"
, then use onLayout
to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.
The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.
JavaScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";
const ResponsiveImage = props => {
const [containerWidth, setContainerWidth] = useState(0);
const _onViewLayoutChange = event => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
TypeScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import {
Image,
ImageSourcePropType,
LayoutChangeEvent,
StyleSheet,
View
} from "react-native";
interface ResponsiveImageProps {
src: ImageSourcePropType;
srcWidth: number;
srcHeight: number;
}
const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
const [containerWidth, setContainerWidth] = useState<number>(0);
const _onViewLayoutChange = (event: LayoutChangeEvent) => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)
Once you've generated your JSON, you can use something like the code below to POST it
StringRequestEntity requestEntity = new StringRequestEntity(
JSON_STRING,
"application/json",
"UTF-8");
PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);
int statusCode = httpClient.executeMethod(postMethod);
Edit
Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:
StringEntity requestEntity = new StringEntity(
JSON_STRING,
ContentType.APPLICATION_JSON);
HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);
HttpResponse rawResponse = httpclient.execute(postMethod);
I know this topic is super old, but, in case if someone's looking for an answer, as me, I'm posting my solution.
This solution works IF you don't mind having some extra data at the beginning of your file.
Basically, the idea is to, if file is not existing, to create it and append current date at the first line.
Next, you can read the first line with fgets(fopen($file, 'r'))
, turn it into a DateTime
object or anything (you can obviously use it raw, unless you saved it in a weird format) and voila - you have your creation date! For example my script to refresh my log file every 30 days looks like this:
if (file_exists($logfile)) {
$now = new DateTime();
$date_created = fgets(fopen($logfile, 'r'));
if ($date_created == '') {
file_put_contents($logfile, date('Y-m-d H:i:s').PHP_EOL, FILE_APPEND | LOCK_EX);
}
$date_created = new DateTime($date_created);
$expiry = $date_created->modify('+ 30 days');
if ($now >= $expiry) {
unlink($logfile);
}
}
Somehow select2Focus didn't work here with empty selection, couldn't figured out the issue, therefore I added manual control when after focus event auto open get's triggered.
Here is coffeescript:
$("#myid").select2()
.on 'select2-blur', ->
$(this).data('select2-auto-open', 'true')
.on 'select2-focus', ->
$(this).data('select2').open() if $(this).data('select2-auto-open') != 'false'
.on 'select2-selecting', ->
$(this).data('select2-auto-open', 'false')