I will soon released a new version of my app to support to galaxy ace.
You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree
In order to solve your problem you should do this:
this._camera = Camera.open();
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});
Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);
params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);
don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true
to turn off the led just release the camera
Actually... filter_var($url, FILTER_VALIDATE_URL); doesn't work very well. When you type in a real url, it works but, it only checks for http:// so if you type something like "http://weirtgcyaurbatc", it will still say it's real.
This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.
#Region " ResizeImage "
Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmSource = New Drawing.Bitmap(SourceImage)
Return ResizeImage(bmSource, TargetWidth, TargetHeight)
End Function
Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)
Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
Dim nDestAspectRatio = bmDest.Width / bmDest.Height
Dim NewX = 0
Dim NewY = 0
Dim NewWidth = bmDest.Width
Dim NewHeight = bmDest.Height
If nDestAspectRatio = nSourceAspectRatio Then
'same ratio
ElseIf nDestAspectRatio > nSourceAspectRatio Then
'Source is taller
NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
Else
'Source is wider
NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
End If
Using grDest = Drawing.Graphics.FromImage(bmDest)
With grDest
.CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
.InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
.PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
.SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
.CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver
.DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
End With
End Using
Return bmDest
End Function
#End Region
public static byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
I like the viewer of Total Commander because it only loads the text you actually see and so is very fast. Of course, it is just a text/hex viewer, so it won't format your XML, but you can use a basic text search.
Is it possible that because you go from 0 to 360, you spend a little bit more time at 0/360 than you are expecting? Perhaps set toDegrees to 359 or 358.
In Laravel 5.6:
$variable = model_name::find($id);
return view('view')->with ('variable',$variable);
TL;DR For conforming browsers, yes; but there are no conforming browsers, so no.
According to the HTML 4 specification, <!------> hello-->
is a perfectly valid comment. However, I've not found a browser which implements this correctly (i.e. per the specification) due to developers not knowing, nor following, the standards (as digitaldreamer pointed out).
You can find the definition of a comment for HTML4 on the w3c's website: http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.4
Another thing that many browsers get wrong is that -- >
closes a comment just like -->
.
Swift 5 , For multi Line text in UIButton
let button = UIButton()
button.titleLabel?.lineBreakMode = .byWordWrapping
button.titleLabel?.textAlignment = .center
button.titleLabel?.numberOfLines = 0 // for Multi line text
SELECT sys.databases.name AS [Database Name],
CONVERT(VARCHAR,SUM(size)*8/1024)+' MB' AS [Size]
FROM sys.databases
JOIN sys.master_files
ON sys.databases.database_id=sys.master_files.database_id
GROUP BY sys.databases.name
ORDER BY sys.databases.name
A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.
You need to execute all the different-user commands as their own script. If it's just one, or a few commands, then inline should work. If it's lots of commands then it's probably best to move them to their own file.
su -c "cd /home/$USERNAME/$PROJECT ; svn update" -m "$USERNAME"
The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.
The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.
Hoorah!
$("#id").autocomplete(
{
search: function () {},
source: function (request, response)
{
$.ajax(
{
url: ,
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
}
});
},
minLength: 2,
select: function (event, ui)
{
var test = ui.item ? ui.item.id : 0;
if (test > 0)
{
alert(test);
}
}
});
That's not possible using the built-in Array.prototype.map
. However, you could use a simple for
-loop instead, if you do not intend to map
any values:
var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
if (myArray[i] < 10) {
hasValueLessThanTen = true;
break;
}
}
Or, as suggested by @RobW
, use Array.prototype.some
to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:
var hasValueLessThanTen = myArray.some(function (val) {
return val < 10;
});
Float:left
... Although I presume you want the input to be styled not the div?
.button input{
color:#08233e;float:left;
font:2.4em Futura, ‘Century Gothic’, AppleGothic, sans-serif;
font-size:70%;
padding:14px;
background:url(overlay.png) repeat-x center #ffcc00;
background-color:rgba(255,204,0,1);
border:1px solid #ffcc00;
-moz-border-radius:10px;
-webkit-border-radius:10px;
border-radius:10px;
border-bottom:1px solid #9f9f9f;
-moz-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
-webkit-box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
box-shadow:inset 0 1px 0 rgba(255,255,255,0.5);
cursor:pointer;
}
.button input:hover{
background-color:rgba(255,204,0,0.8);
}
What about using:
mime_body_part.setHeader("Content-Type", "text/html");
In the documentation of getContentType it says that the value returned is found using getHeader(name). So if you set the header using setHeader I guess everything should be fine.
I faced with same trouble after brew installs yarn on my MacOs Sierra 10.12.6. (And the first try of installation fall after brew update self with a message " Homebrew must be run under Ruby 2.3! You're running 2.0.0. (RuntimeError)". So I re-run it.)
So I use n manager to reinstall npm.
I think the trouble can be caused that node was installed under sudo for case.
DateTimePicker1.value = Format(Date.Now)
The ASCII table is arranged so that the value of the character '9'
is nine greater than the value of '0'
; the value of the character '8'
is eight greater than the value of '0'
; and so on.
So you can get the int value of a decimal digit char by subtracting '0'
.
char x = '9';
int y = x - '0'; // gives the int value 9
This was the only way I could get this to work
add_action('init','add_query_args');
function add_query_args()
{
add_query_arg( 'var1', 'val1' );
}
You could also try setting style
inline without using a variable, like so:
style={{"height" : "100%"}}
or,
for multiple attributes: style={{"height" : "100%", "width" : "50%"}}
At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals
You use it like this:
df1.equals(df2)
Some differenes to ==
are:
dtype
to be considered equal, see this stackoverflow questionAs you're generating the image dynamically, set the onload
property before the src
.
var img = new Image();
img.onload = function () {
alert("image is loaded");
}
img.src = "img.jpg";
Fiddle - tested on latest Firefox and Chrome releases.
You can also use the answer in this post, which I adapted for a single dynamically generated image:
var img = new Image();
// 'load' event
$(img).on('load', function() {
alert("image is loaded");
});
img.src = "img.jpg";
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
I have a Windows service, and I added the following line to the constructor for my service:
using System.Diagnostics;
try {
Process p = Process.Start(@"C:\Windows\system32\calc.exe");
} catch {
Debugger.Break();
}
When I tried to run this, the Process.Start() call was made, and no exception occurred. However, the calc.exe application did not show up. In order to make it work, I had edit the properties for my service in the Service Control Manager to enable interaction with the desktop. After doing that, the Process.Start() opened calc.exe as expected.
But as others have said, interaction with the desktop is frowned upon by Microsoft and has essentially been disabled in Vista. So even if you can get it to work in XP, I don't know that you'll be able to make it work in Vista.
Yes, in C# 6.0 -- https://msdn.microsoft.com/en-us/magazine/dn802602.aspx.
object?.SomeMethod()
Use dict.has_key()
if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when key in dict
was introduced).
You could check out JBoss Tools plugin.
If you're using the jQuery library, consider using http://api.jquery.com/jQuery.each/
From the documentation:
jQuery.each( collection, callback(indexInArray, valueOfElement) )
Returns: Object
Description: A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties.
The
$.each()
function is not the same as$(selector).each()
, which is used to iterate, exclusively, over a jQuery object. The$.each()
function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through thethis
keyword, but Javascript will always wrap thethis
value as anObject
even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
I have a Class Library WPF Project, and I Use:
'Read Settings
Dim value as string = My.Settings.my_key
value = "new value"
'Write Settings
My.Settings.my_key = value
My.Settings.Save()
In Internet Explorer 9 (and 8), the console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the console
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the console
object to be exposed.
The console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from Object
, nor its methods from Function
, like native ECMAScript functions and objects do. This is the reason apply
and call
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.
For what it's worth, you can still use some Function.prototype
methods on console
methods with a little bind()
magic:
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"
You can do this in the storyboard / xib editor as well. Just set Seperator to none.
For PHP 8:
sudo apt update
sudo apt-get install php8.0-soap
The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:
nonatomic vs. atomic - "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)
readwrite vs. readonly - "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.
retain vs. copy vs. assign
@sz3, funny enough today I had to do exactly what you were trying to achieve: 'load a specific CSS file only when a user access' a specific page. So I used the solution above.
But I am here to answer your last question: 'where exactly should I put the code. Any ideas?'
You were right including the code into the resolve, but you need to change a bit the format.
Take a look at the code below:
.when('/home', {
title:'Home - ' + siteName,
bodyClass: 'home',
templateUrl: function(params) {
return 'views/home.html';
},
controler: 'homeCtrl',
resolve: {
style : function(){
/* check if already exists first - note ID used on link element*/
/* could also track within scope object*/
if( !angular.element('link#mobile').length){
angular.element('head').append('<link id="home" href="home.css" rel="stylesheet">');
}
}
}
})
I've just tested and it's working fine, it injects the html and it loads my 'home.css' only when I hit the '/home' route.
Full explanation can be found here, but basically resolve: should get an object in the format
{
'key' : string or function()
}
You can name the 'key' anything you like - in my case I called 'style'.
Then for the value you have two options:
If it's a string, then it is an alias for a service.
If it's function, then it is injected and the return value is treated as the dependency.
The main point here is that the code inside the function is going to be executed before before the controller is instantiated and the $routeChangeSuccess event is fired.
Hope that helps.
You can use this apk
1.first install the app from the Google play store
2.install the above apk
3.launch the apk and input the package name of your app
4.then you will get the hash code you want
If NEW_TABLE already exists then ...
insert into new_table
select * from old_table
/
If you want to create NEW_TABLE based on the records in OLD_TABLE ...
create table new_table as
select * from old_table
/
If the purpose is to create a new but empty table then use a WHERE clause with a condition which can never be true:
create table new_table as
select * from old_table
where 1 = 2
/
Remember that CREATE TABLE ... AS SELECT creates only a table with the same projection as the source table. The new table does not have any constraints, triggers or indexes which the original table might have. Those still have to be added manually (if they are required).
Use controller.controller_name
In the Rails Guides, it says:
The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values
So let's say you have a CSS class active
, that should be inserted in any link whose page is currently open (maybe so that you can style differently) . If you have a static_pages
controller with an about
action, you can then highlight the link like so in your view:
<li>
<a class='button <% if controller.controller_name == "static_pages" && controller.action_name == "about" %>active<%end%>' href="/about">
About Us
</a>
</li>
Cleaned up what chuycepeda has and put it into a textarea to send back in a form.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
var str_input = '{';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
$.each(event.overlay.getPath().getArray(), function (key, latlng) {
var lat = latlng.lat();
var lon = latlng.lng();
str_input += lat + ', ' + lon + ',';
});
}
str_input = str_input.substr(0, str_input.length - 1) + '}';
$('textarea#Geofence').val(str_input);
});
if (true)
{
return View();
}
else
{
return View("another view name");
}
This simple command works like a charm:
git name-rev <SHA>
For example (where test-branch is the branch name):
git name-rev 651ad3a
251ad3a remotes/origin/test-branch
Even this is working for complex scenarios, like:
origin/branchA/
/branchB
/commit<SHA1>
/commit<SHA2>
Here git name-rev commit<SHA2>
returns branchB.
If number is separated by "." and decimals by "," (1.200.000,00) in calling gsub
you must set fixed=TRUE as.numeric(gsub(".","",y,fixed=TRUE))
Process.Start("explorer.exe" , @"C:\Users");
I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.
You can also make use of array#forEach()
method like this:
const cars = [{ make: 'audi', model: 'r8', year: '2012' }, { make: 'audi', model: 'rs5', year: '2013' }, { make: 'ford', model: 'mustang', year: '2012' }, { make: 'ford', model: 'fusion', year: '2015' }, { make: 'kia', model: 'optima', year: '2012' }];_x000D_
_x000D_
let newcars = {}_x000D_
_x000D_
cars.forEach(car => {_x000D_
newcars[car.make] ? // check if that array exists or not in newcars object_x000D_
newcars[car.make].push({model: car.model, year: car.year}) // just push_x000D_
: (newcars[car.make] = [], newcars[car.make].push({model: car.model, year: car.year})) // create a new array and push_x000D_
})_x000D_
_x000D_
console.log(newcars);
_x000D_
My website is a subdomain which is developed on angular 8 which is also using localstorage and cookies. website showed after setting the below line, along with other solutions mentioned above.
webSettings.setDomStorageEnabled(true);
The solution that we used, needed to:
There are several choices, but we found NPoi (.NET port of Java's long existing Poi open source project) to be the best: http://npoi.codeplex.com/
It also allows working with .doc and .ppt file formats
Send the passwordbox control as a parameter to your login command.
<Button Command="{Binding LoginCommand}" CommandParameter="{Binding ElementName=PasswordBox}"...>
Then you can call CType(parameter, PasswordBox).Password
in your viewmodel.
In Bootstrap 3 I've added a table-no-border class
.table-no-border>thead>tr>th,
.table-no-border>tbody>tr>th,
.table-no-border>tfoot>tr>th,
.table-no-border>thead>tr>td,
.table-no-border>tbody>tr>td,
.table-no-border>tfoot>tr>td {
border-top: none;
}
First of all inject $filter to your controller, making sure ngSanitize is loaded within your app, later within the controller usage is as follows:
$filter('linky')(text, target, attributes)
You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save
(or the before_validation
) callback. Here's an example of the relevant code for a model like yours:
class Place < ActiveRecord::Base before_save do |place| place.city = place.city.downcase.titleize place.country = place.country.downcase.titleize end end
You can also check out the Ruby on Rails guide for more info.
To answer you question more directly, something like this would work:
<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>
This just means if f.object.city
exists, display the titlecase
version of it, and if it doesn't display a blank string.
I don't believe jQuery will just naturally do a JSONP request when given a URL like that. It will, however, do a JSONP request when you tell it what argument to use for a callback:
$.get("http://metaward.com/import/http://metaward.com/u/ptarjan?jsoncallback=?", function(data) {
alert(data);
});
It's entirely up to the receiving script to make use of that argument (which doesn't have to be called "jsoncallback"), so in this case the function will never be called. But, since you stated you just want the script at metaward.com to execute, that would make it.
On Windows, setting GIT_SSH
to openssh that comes with msys git didn't work (Eclipse hung during commit). Setting it to TortoisePlink solved the problem (I guess original plink would work as well). The added bonus is now Eclipse uses keys stored in pageant.
mysqldump will not dump database events, triggers and routines unless explicitly stated when dumping individual databases;
mysqldump -uuser -p db_name --events --triggers --routines > db_name.sql
You can use apache Range API. https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/Range.html
If you run a loop taking items from z, how do you expect them not to be in z? IMHO it would make more sense comparing items from a different list to z.
More succinct-: sum(is.na(x[1]))
That is
x[1]
Look at the first column
is.na()
true if it's NA
sum()
TRUE
is 1
, FALSE
is 0
Sometimes it may occur, if there is any database connection in your code but you did not start the database server yet.
Im my case i have some piece of code to connect with mongodb
mongoose.connect("mongodb://localhost:27017/demoDb");
after i started the mongodb server with the command mongod this error is gone
HTML Imports, part of the Web Components cast, is also a way to include HTML documents in other HTML documents. See http://www.html5rocks.com/en/tutorials/webcomponents/imports/
JQUERY FORMATCURRENCY PLUGIN
http://code.google.com/p/jquery-formatcurrency/
You can create a usercontrol with the grid definition and define 'child' controls with varied column definitions in xaml. The parent needs a dependency property for columns and a method for loading the columns:
Parent:
public ObservableCollection<DataGridColumn> gridColumns
{
get
{
return (ObservableCollection<DataGridColumn>)GetValue(ColumnsProperty);
}
set
{
SetValue(ColumnsProperty, value);
}
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("gridColumns",
typeof(ObservableCollection<DataGridColumn>),
typeof(parentControl),
new PropertyMetadata(new ObservableCollection<DataGridColumn>()));
public void LoadGrid()
{
if (gridColumns.Count > 0)
myGrid.Columns.Clear();
foreach (DataGridColumn c in gridColumns)
{
myGrid.Columns.Add(c);
}
}
Child Xaml:
<local:parentControl x:Name="deGrid">
<local:parentControl.gridColumns>
<toolkit:DataGridTextColumn Width="Auto" Header="1" Binding="{Binding Path=.}" />
<toolkit:DataGridTextColumn Width="Auto" Header="2" Binding="{Binding Path=.}" />
</local:parentControl.gridColumns>
</local:parentControl>
And finally, the tricky part is finding where to call 'LoadGrid'.
I am struggling with this but got things to work by calling after InitalizeComponent
in my window constructor (childGrid is x:name in window.xaml):
childGrid.deGrid.LoadGrid();
select month(dateField), year(dateField)
simply use local time as the default:
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
Here documents with the <<-HERE
terminator work well for indented multi-line text strings. It will remove any leading tabs from the here document. (Line terminators will still remain, though.)
cat <<-____HERE
continuation
lines
____HERE
See also http://ss64.com/bash/syntax-here.html
If you need to preserve some, but not all, leading whitespace, you might use something like
sed 's/^ //' <<____HERE
This has four leading spaces.
Two of them will be removed by sed.
____HERE
or maybe use tr
to get rid of newlines:
tr -d '\012' <<-____
continuation
lines
____
(The second line has a tab and a space up front; the tab will be removed by the dash operator before the heredoc terminator, whereas the space will be preserved.)
For wrapping long complex strings over many lines, I like printf
:
printf '%s' \
"This will all be printed on a " \
"single line (because the format string " \
"doesn't specify any newline)"
It also works well in contexts where you want to embed nontrivial pieces of shell script in another language where the host language's syntax won't let you use a here document, such as in a Makefile
or Dockerfile
.
printf '%s\n' >./myscript \
'#!/bin/sh` \
"echo \"G'day, World\"" \
'date +%F\ %T' && \
chmod a+x ./myscript && \
./myscript
Go to File --> Set Path and add the folder containing the functions as Matlab files. (At least for Matlab 2007b on Vista)
There are a few different ways to go about it. reshape2
is a helpful package.
Personally, I like using data.table
Below is a step-by-step
If myDF
is your data.frame
:
library(data.table)
DT <- data.table(myDF)
DT
# this will get you your mean and SD's for each column
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x)))]
# adding a `by` argument will give you the groupings
DT[, sapply(.SD, function(x) list(mean=mean(x), sd=sd(x))), by=ID]
# If you would like to round the values:
DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID]
# If we want to add names to the columns
wide <- setnames(DT[, sapply(.SD, function(x) list(mean=round(mean(x), 3), sd=round(sd(x), 3))), by=ID], c("ID", sapply(names(DT)[-1], paste0, c(".men", ".SD"))))
wide
ID Obs.1.men Obs.1.SD Obs.2.men Obs.2.SD Obs.3.men Obs.3.SD
1: 1 35.333 8.021 36.333 10.214 33.0 9.644
2: 2 29.750 3.594 32.250 4.193 30.5 5.916
3: 3 41.500 4.950 43.500 4.950 39.0 4.243
Also, this may or may not be helpful
> DT[, sapply(.SD, summary), .SDcols=names(DT)[-1]]
Obs.1 Obs.2 Obs.3
Min. 25.00 28.00 22.00
1st Qu. 29.00 31.00 27.00
Median 33.00 32.00 36.00
Mean 34.22 36.11 33.22
3rd Qu. 38.00 40.00 37.00
Max. 45.00 48.00 42.00
question:-.DISPLAY EMPLOYEE NAME , HIS DATE OF JOINING, HIS MANAGER NAME & HIS MANAGER'S DATE OF JOINING. ANS:- select e1.ename Emp,e1.hiredate, e2.eName Mgr,e2.hiredate from emp e1, emp e2 where e1.mgr = e2.empno
If you have XDocument it is easier to use LINQ-to-XML:
var document = XDocument.Load(fileName);
var name = document.Descendants(XName.Get("Name", @"http://demo.com/2011/demo-schema")).First().Value;
If you are sure that XPath is the only solution you need:
using System.Xml.XPath;
var document = XDocument.Load(fileName);
var namespaceManager = new XmlNamespaceManager(new NameTable());
namespaceManager.AddNamespace("empty", "http://demo.com/2011/demo-schema");
var name = document.XPathSelectElement("/empty:Report/empty:ReportInfo/empty:Name", namespaceManager).Value;
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
You can get its address by using:
document.getElementById('myframe').src
Not sure if I understood your question correctly but anyways :)
Swift 4:
// attribute with color red and Bold
var attrs1 = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 20), NSAttributedStringKey.foregroundColor: UIColor.red]
// attribute with color black and Non Bold
var attrs2 = [NSAttributedStringKey.font: UIFont(name: "Roboto-Regular", size: 20), NSAttributedStringKey.foregroundColor: UIColor.black]
var color1 = NSAttributedString(string: "RED", attributes: attrs1)
var color2 = NSAttributedString(string: " BLACK", attributes: attrs2)
var string = NSMutableAttributedString()
string.append(color1)
string.append(color2)
// print the text with **RED** BLACK
print("Final String : \(string)")
If the display of the div is block by default, you can just use .show()
and .hide()
, or even simpler, .toggle()
to toggle between visibility.
Customizing the color of progressbar namely in case of spinner type needs an xml file and initiating codes in their respective java files.
Create an xml file and name it as progressbar.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
tools:context=".Radio_Activity" >
<LinearLayout
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ProgressBar
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ProgressBar>
</LinearLayout>
</LinearLayout>
Use the following code to get the spinner in various expected color.Here we use the hexcode to display spinner in blue color.
Progressbar spinner = (ProgressBar) progrees.findViewById(R.id.spinner);
spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#80DAEB"),
android.graphics.PorterDuff.Mode.MULTIPLY);
Hope this will do the job in simplest manner:
$("#myID").on('show').trigger('displayShow');
$('#myID').off('displayShow').on('displayShow', function(e) {
console.log('This event will be triggered when myID will be visible');
});
lace to store your loaded class definition and metadata. If a large code-base project is loaded, the insufficient Perm Gen size will cause the popular Java.Lang.OutOfMemoryError: PermGen.
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
Todo this in a single system call you can use the fs-extra
npm module.
After this the file will have been created as well as the directory it is to be placed in.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFile(file, err => {
console.log(err) // => null
});
Another way is to use ensureFileSync which will do the same thing but synchronous.
const fs = require('fs-extra');
const file = '/tmp/this/path/does/not/exist/file.txt'
fs.ensureFileSync(file)
Swift 5
let desiredIndex: Int = 7
let substring = str[String.Index(encodedOffset: desiredIndex)...]
This substring variable will give you the result.
Simply here Int is converted to Index and then you can split the strings. Unless you will get errors.
For this example we take it for granted that varcharcol doesn't contain ''
and have no empty cell against this column
select * from some_table where varcharCol = ''
select * from some_table where varcharCol like ''
The first one results in 0 row output while the second one shows the whole list. = is strictly-match case while like acts like a filter. if filter has no criteria, every data is valid.
like - by the virtue of its purpose works a little slower and is intended for use with varchar and similar data.
I would do it something along these lines:
class Foo{
...
};
int main(){
Foo* arrayOfFoo[100]; //[1]
arrayOfFoo[0] = new Foo; //[2]
}
[1] This makes an array of 100 pointers to Foo-objects. But no Foo-objects are actually created.
[2] This is one possible way to instantiate an object, and at the same time save a pointer to this object in the first position of your array.
I've found this issue to be prevalent in Entity Framework when we instantiate an Entity manually rather than through DBContext which will resolve all the Navigation Properties. If there are Foreign Key references (Navigation Properties) between tables and you use those references in your lambda (e.g. ProductDetail.Products.ID) then that "Products" context remains null if you manually created the Entity.
just posting in case anyone else has the same error...
I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.
The solution was to make the function asynchronous
function functionName(args) {}
becomes
async function functionName(args) {}
//get query¶ms in express
//etc. example.com/user/000000?sex=female
app.get('/user/:id', function(req, res) {
const query = req.query;// query = {sex:"female"}
const params = req.params; //params = {id:"000000"}
})
The very same. A C string is nothing but an array of characters, so a pointer to a string is a pointer to an array of characters. And a pointer to an array is the very same as a pointer to its first element.
WPF converts points to pixels with the System.Windows.FontSizeConverter. The FontSizeConverter uses the System.Windows.LengthConverter. The LengthConverter uses the factor 1.333333333333333333 to convert from points (p) to pixels (x): x = p * 1.3333333333333333
C is a very low-level language, so it permits you to create almost any legal object (.o) file that you can conceive of. You should think of C as basically dressed-up assembly language.
In particular, C does not require functions to be declared before they are used. If you call a function without declaring it, the use of the function becomes it's (implicit) declaration. In a simple test I just ran, this is only a warning in the case of built-in library functions like printf (at least in GCC), but for random functions, it will compile just fine.
Of course, when you try to link, and it can't find foo, then you will get an error.
In the case of library functions like printf, some compilers contain built-in declarations for them so they can do some basic type checking, so when the implicit declaration (from the use) doesn't match the built-in declaration, you'll get a warning.
User $()
to get jQuery
object from your link and data()
to get your values
<a id="option1"
data-id="10"
data-option="21"
href="#"
onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
Click to do something
</a>
a quick way to see your errors whilst testing:
$error= $st->errorInfo();
echo $error[2];
Just putting this here in case it helps someone, my case was different and a bit of an odd mix. I was getting this on a request that was accessed via superagent - the problem had nothing to do with certificates (which were setup properly) and all to do with the fact that I was then passing the superagent result through the async module's waterfall callback. To fix: Instead of passing the entire result, just pass result.body
through the waterfall's callback.
Instead of create the new Container class you can use a dataTable.
DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");
dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });
myDataGridView.DataSource = dt;
More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString
I've created my own dark color scheme (based on Oblivion from gedit), which I think is very nice to work with.
Preview & details at: http://www.rogerdudler.com/?p=362
We're happy to announce the beta of eclipsecolorthemes.org, a new website to download, create and maintain Eclipse color themes / schemes. The theme editor allows you to copy an existing theme and edit the colors with a live preview of your changes on specific editors. The downloadable themes support a lot of editors (PHP, Java, SQL, Ant, text, HTML, CSS, and more to follow)
There's a growing list of themes already available on the site:
You can read more about the launch here.
How to create encrypted password for passing to password
var to Ansible user
task (from @Brendan Wood's comment):
openssl passwd -salt 'some_plain_salt' -1 'some_plain_pass'
The result will look like:
$1$some_pla$lmVKJwdV3Baf.o.F0OOy71
Example of user
task:
- name: Create user
user: name="my_user" password="$1$some_pla$lmVKJwdV3Baf.o.F0OOy71"
UPD: crypt using SHA-512 see here and here:
$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$saltsalt\$')"
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
$ perl -e 'print crypt("password","\$6\$saltsalt\$") . "\n"'
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
$ ruby -e 'puts "password".crypt("$6$saltsalt$")'
$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/
Assuming that yourObject.toString() returns "true" or "false", you can try
boolean b = Boolean.valueOf(yourObject.toString())
I'm a designer and our devs had this issue when dealing with Android initially, and our web devs are having the same problem. We found that the spacing between a line of text and another object (either a component like a button, or a separate line of text) that a design program spits out is incorrect. This is because the design program isn't accounting for diacritics when it is defining the "size" of a single line of text.
We ended up adding Êg
to every line of text and manually creating spacers (little blue rectangles) that act as the "measurement" from the actual top of the text (ie, the top of the accent mark on the E) or from the descender (the bottom of a "g").
For example, say you have a really boring top navigation that is just a rectangle, and a headline beneath it. The design program will say that the space between the bottom of the top nav and the top of the headline textbox 24px. However, when you measure from the bottom of the nav to the top of an Ê accent mark, the spacing is actually 20px.
While I realize that this isn't a code solution, it should help explain the discrepancies between the design specs and what the build looks like.
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
Using multiple threads on CPython won't give you better performance for pure-Python code due to the global interpreter lock (GIL). I suggest using the multiprocessing
module instead:
pool = multiprocessing.Pool(4)
out1, out2, out3 = zip(*pool.map(calc_stuff, range(0, 10 * offset, offset)))
Note that this won't work in the interactive interpreter.
To avoid the usual FUD around the GIL: There wouldn't be any advantage to using threads for this example anyway. You want to use processes here, not threads, because they avoid a whole bunch of problems.
Sometimes if you use JavaScript the DocumentComplete
event don't return the right answer; I use the event ProgressChanged
instead:
Private Sub WebBrowser1_ProgressChanged(sender As Object, e As WebBrowserProgressChangedEventArgs) Handles WebBrowser1.ProgressChanged
Console.WriteLine("Current Progress: " + e.CurrentProgress.ToString)
If e.CurrentProgress = e.MaximumProgress Then
' The maximum progress is reached
load_started = True
End If
' The page is confirmed downloaded after the progress returns to 0
If e.CurrentProgress = 0 Then
If load_started Then
' The page is ready to print or download...
WebBrowser1.Print()
load_started = False
End If
End If
End Sub
Similar to nesting the callbacks, this technique relies on closures. Yet, the chain stays flat - instead of passing only the latest result, some state object is passed for every step. These state objects accumulate the results of the previous actions, handing down all values that will be needed later again plus the result of the current task.
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(b => [resultA, b]); // function(b) { return [resultA, b] }
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
Here, that little arrow b => [resultA, b]
is the function that closes over resultA
, and passes an array of both results to the next step. Which uses parameter destructuring syntax to break it up in single variables again.
Before destructuring became available with ES6, a nifty helper method called .spread()
was provided by many promise libraries (Q, Bluebird, when, …). It takes a function with multiple parameters - one for each array element - to be used as .spread(function(resultA, resultB) { …
.
Of course, that closure needed here can be further simplified by some helper functions, e.g.
function addTo(x) {
// imagine complex `arguments` fiddling or anything that helps usability
// but you get the idea with this simple one:
return res => [x, res];
}
…
return promiseB(…).then(addTo(resultA));
Alternatively, you can employ Promise.all
to produce the promise for the array:
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return Promise.all([resultA, promiseB(…)]); // resultA will implicitly be wrapped
// as if passed to Promise.resolve()
}).then(function([resultA, resultB]) {
// more processing
return // something using both resultA and resultB
});
}
And you might not only use arrays, but arbitrarily complex objects. For example, with _.extend
or Object.assign
in a different helper function:
function augment(obj, name) {
return function (res) { var r = Object.assign({}, obj); r[name] = res; return r; };
}
function getExample() {
return promiseA(…).then(function(resultA) {
// some processing
return promiseB(…).then(augment({resultA}, "resultB"));
}).then(function(obj) {
// more processing
return // something using both obj.resultA and obj.resultB
});
}
While this pattern guarantees a flat chain and explicit state objects can improve clarity, it will become tedious for a long chain. Especially when you need the state only sporadically, you still have to pass it through every step. With this fixed interface, the single callbacks in the chain are rather tightly coupled and inflexible to change. It makes factoring out single steps harder, and callbacks cannot be supplied directly from other modules - they always need to be wrapped in boilerplate code that cares about the state. Abstract helper functions like the above can ease the pain a bit, but it will always be present.
I would check the "End of File" flag:
If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"
You need to make sure images come first and put in a comma after the background image call. then it actually does work:
background:url(egg.png) no-repeat 70px 2px #82d4fe; /* Old browsers */
background:url(egg.png) no-repeat 70px 2px, -moz-linear-gradient(top, #82d4fe 0%, #1db2ff 78%) ; /* FF3.6+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-gradient(linear, left top, left bottom, color-stop(0%,#82d4fe), color-stop(78%,#1db2ff)); /* Chrome,Safari4+ */
background:url(egg.png) no-repeat 70px 2px, -webkit-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Chrome10+,Safari5.1+ */
background:url(egg.png) no-repeat 70px 2px, -o-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* Opera11.10+ */
background:url(egg.png) no-repeat 70px 2px, -ms-linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* IE10+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#82d4fe', endColorstr='#1db2ff',GradientType=0 ); /* IE6-9 */
background:url(egg.png) no-repeat 70px 2px, linear-gradient(top, #82d4fe 0%,#1db2ff 78%); /* W3C */
I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:
Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process
the way I use jsonp like below:
function jsonp(uri) {
return new Promise(function(resolve, reject) {
var id = '_' + Math.round(10000 * Math.random());
var callbackName = 'jsonp_callback_' + id;
window[callbackName] = function(data) {
delete window[callbackName];
var ele = document.getElementById(id);
ele.parentNode.removeChild(ele);
resolve(data);
}
var src = uri + '&callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.id = id;
script.addEventListener('error', reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
});
}
then use 'jsonp' method like this:
jsonp('http://xxx/cors').then(function(data){
console.log(data);
});
reference:
JavaScript XMLHttpRequest using JsonP
http://www.w3ctech.com/topic/721 (talk about the way of use Promise)
I know this doesn't look related, especially given the error message, but I fixed this by installing a newer version of the Android SDK Build tools.
It's worth understanding what those error messages mean - needs merge
and error: you need to resolve your current index first
indicate that a merge failed, and that there are conflicts in those files. If you've decided that whatever merge you were trying to do was a bad idea after all, you can put things back to normal with:
git reset --merge
However, otherwise you should resolve those merge conflicts, as described in the git manual.
Once you've dealt with that by either technique you should be able to checkout the 9-sign-in-out
branch. The problem with just renaming your 9-sign-in-out
to master
, as suggested in wRAR's answer is that if you've shared your previous master branch with anyone, this will create problems for them, since if the history of the two branches diverged, you'll be publishing rewritten history.
Essentially what you want to do is to merge your topic branch 9-sign-in-out
into master
but exactly keep the versions of the files in the topic branch. You could do this with the following steps:
# Switch to the topic branch:
git checkout 9-sign-in-out
# Create a merge commit, which looks as if it's merging in from master, but is
# actually discarding everything from the master branch and keeping everything
# from 9-sign-in-out:
git merge -s ours master
# Switch back to the master branch:
git checkout master
# Merge the topic branch into master - this should now be a fast-forward
# that leaves you with master exactly as 9-sign-in-out was:
git merge 9-sign-in-out
Try %*s
and %-*s
and prefix each string with the column width:
>>> print "Location: %-*s Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10 Revision: 1
>>> print "District: %-*s Date: %s" % (20,"Tower","May 16, 2012")
District: Tower Date: May 16, 2012
In the latest GitHub client for Windows, if you have uncommitted changes, and choose to create a new branch.
It prompts you how to handle this exact scenario:
The same applies if you simply switch the branch too.
This question is pretty old however it is highly visible on search engines even in Bootstrap 4 related searches. I think it worths to add an answer for disabling the rounded corners, BS4 way.
In the _variables.scss
there are several global modifiers exists to quickly change the stuff such as enabling or disabling flex gird system, rounded corners, gradients etc. :
$enable-flex: false !default;
$enable-rounded: true !default; // <-- This one
$enable-shadows: false !default;
$enable-gradients: false !default;
$enable-transitions: false !default;
Rounded corners are enabled
by default.
If you prefer compiling the Bootstrap 4 using Sass and your very own _custom.scss
like me (or using official customizer), overriding the related variable is enough:
$enable-rounded : false
Unix will only run commands if they are available on the system path, as you can view by the $PATH variable
echo $PATH
Executables located in directories that are not on the path cannot be run unless you specify their full location. So in your case, assuming the executable is in the current directory you are working with, then you can execute it as such
./my-exec
Where my-exec
is the name of your program.
The sql query sample like this
LEFT JOIN bookings
ON rooms.id = bookings.room_type_id
AND (bookings.arrival = ?
OR bookings.departure = ?)
Laravel join with multiple conditions
->leftJoin('bookings', function($join) use ($param1, $param2) {
$join->on('rooms.id', '=', 'bookings.room_type_id');
$join->on(function($query) use ($param1, $param2) {
$query->on('bookings.arrival', '=', $param1);
$query->orOn('departure', '=',$param2);
});
})
public class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for(double a : data)
sum += a;
return sum/size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for(double a :data)
temp += (a-mean)*(a-mean);
return temp/(size-1);
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if (data.length % 2 == 0)
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
return data[data.length / 2];
}
}
Oftentimes hooking refers to Win32 message hooking or the Linux/OSX equivalents, but more generically hooking is simply notifying another object/window/program/etc that you want to be notified when a specified action happens. For instance: Having all windows on the system notify you as they are about to close.
As a general rule, hooking is somewhat hazardous since doing it without understanding how it affects the system can lead to instability or at the very leas unexpected behaviour. It can also be VERY useful in certain circumstances, thought. For instance: FRAPS uses it to determine which windows it should show it's FPS counter on.
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
In your example number
is a primitive, so will be stored as a value.
If you want to use a reference then you should use one of the wrapper types (e.g. Integer
)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /dmizone_bkp
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond $1 !^(index\.php|images|robots\.txt|css|docs|js|system)
RewriteRule ^(.*)$ /dmizone_bkp/index.php?/$1 [L]
</IfModule>
Try this :
select replace (colname, char(39)+char(39), '') AS colname FROM .[dbo].[Db Name];
I have achieved the desired result. Example : Input value --> Like '%Pat') '' OR
Want Output --> *Like '%Pat') OR*
using above query achieved the desired result.
You can do it via the constructor of your class:
public class foo {
public foo(){
Bar = "bar";
}
public string Bar {get;set;}
}
If you've got another constructor (ie, one that takes paramters) or a bunch of constructors you can always have this (called constructor chaining):
public class foo {
private foo(){
Bar = "bar";
Baz = "baz";
}
public foo(int something) : this(){
//do specialized initialization here
Baz = string.Format("{0}Baz", something);
}
public string Bar {get; set;}
public string Baz {get; set;}
}
If you always chain a call to the default constructor you can have all default property initialization set there. When chaining, the chained constructor will be called before the calling constructor so that your more specialized constructors will be able to set different defaults as applicable.
I hide the warnings in the pink boxes by running the following code in a cell:
from IPython.display import HTML
HTML('''<script>
code_show_err=false;
function code_toggle_err() {
if (code_show_err){
$('div.output_stderr').hide();
} else {
$('div.output_stderr').show();
}
code_show_err = !code_show_err
}
$( document ).ready(code_toggle_err);
</script>
To toggle on/off output_stderr, click <a href="javascript:code_toggle_err()">here</a>.''')
Is there a command that does?
thread apply all where
I would like to provide alternative solution to use package flushbar.
https://github.com/AndreHaueisen/flushbar
As the package said: Use this package if you need more customization when notifying your user. For Android developers, it is made to substitute toasts and snackbars.
Another suggestion to use flushbar How to show snackbar after navigator.pop(context) in Flutter?
You can also set flushbarPosition to TOP or BOTTOM
Flushbar(
title: "Hey Ninja",
message: "Lorem Ipsum is simply dummy text of the printing and typesetting industry",
flushbarPosition: FlushbarPosition.TOP,
flushbarStyle: FlushbarStyle.FLOATING,
reverseAnimationCurve: Curves.decelerate,
forwardAnimationCurve: Curves.elasticOut,
backgroundColor: Colors.red,
boxShadows: [BoxShadow(color: Colors.blue[800], offset: Offset(0.0, 2.0), blurRadius: 3.0)],
backgroundGradient: LinearGradient(colors: [Colors.blueGrey, Colors.black]),
isDismissible: false,
duration: Duration(seconds: 4),
icon: Icon(
Icons.check,
color: Colors.greenAccent,
),
mainButton: FlatButton(
onPressed: () {},
child: Text(
"CLAP",
style: TextStyle(color: Colors.amber),
),
),
showProgressIndicator: true,
progressIndicatorBackgroundColor: Colors.blueGrey,
titleText: Text(
"Hello Hero",
style: TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0, color: Colors.yellow[600], fontFamily: "ShadowsIntoLightTwo"),
),
messageText: Text(
"You killed that giant monster in the city. Congratulations!",
style: TextStyle(fontSize: 18.0, color: Colors.green, fontFamily: "ShadowsIntoLightTwo"),
),
)..show(context);
you should add data from REFERENCES KEY in PRIMARY TABLE to FOREIGN KEY in CHILD TABLE
it means do not add random data to foreign key ? just use data from primary key that is accessable
window.onload however they are often the same thing. Similarly body.onload becomes window.onload in IE.
The previous version, xlrd 1.2.0, may appear to work, but it could also expose you to potential security vulnerabilities. With that warning out of the way, if you still want to give it a go, type the following command:
pip install xlrd==1.2.0
So I realize this is kind of old, but after much Googling, I couldn't find an answer I was happy with, so I came up with my own solution for breaking a FOR loop that immediately stops iteration, and thought I'd share it.
It requires the loop to be in a separate file, and exploits a bug in CMD error handling to immediately crash the batch processing of the loop file when redirecting the STDOUT of DIR to STDIN.
MainFile.cmd
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO.
ECHO After LOOP
PAUSE
LOOP.cmd
FOR /L %%A IN (1,1,10) DO (
ECHO %%A
IF %%A EQU 3 DIR >&0 2>NUL )
)
When run, this produces the following output. You'll notice that both iteration and execution of the loop stops when %A = 3.
:>MainFile.cmd
:>ECHO Simple test demonstrating loop breaking.
Simple test demonstrating loop breaking.
:>ECHO.
:>CMD /C Z:\LOOP.cmd
:>FOR /L %A IN (1 1 10) DO (
ECHO %A
IF %A EQU 3 DIR 1>&0 2>NUL
)
:>(
ECHO 1
IF 1 EQU 3 DIR 1>&0 2>NUL
)
1
:>(
ECHO 2
IF 2 EQU 3 DIR 1>&0 2>NUL
)
2
:>(
ECHO 3
IF 3 EQU 3 DIR 1>&0 2>NUL
)
3
:>ECHO.
:>ECHO After LOOP
After LOOP
:>PAUSE
Press any key to continue . . .
If you need to preserve a single variable from the loop, have the loop ECHO the result of the variable, and use a FOR /F loop in the MainFile.cmd to parse the output of the LOOP.cmd file.
Example (using the same LOOP.cmd file as above):
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
FOR /F "delims=" %%L IN ('CMD /C %~dp0\LOOP.cmd') DO SET VARIABLE=%%L
ECHO After LOOP
ECHO.
ECHO %VARIABLE%
ECHO.
PAUSE
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
3
Press any key to continue . . .
If you need to preserve multiple variables, you'll need to redirect them to temporary files as shown below.
MainFile.cmd
@ECHO OFF
ECHO.
ECHO Simple test demonstrating loop breaking.
ECHO.
CMD /C %~dp0\LOOP.cmd
ECHO After LOOP
ECHO.
SET /P VARIABLE1=<%TEMP%\1
SET /P VARIABLE2=<%TEMP%\2
ECHO %VARIABLE1%
ECHO %VARIABLE2%
ECHO.
PAUSE
LOOP.cmd
@ECHO OFF
FOR /L %%A IN (1,1,10) DO (
IF %%A EQU 1 ECHO ONE >%TEMP%\1
IF %%A EQU 2 ECHO TWO >%TEMP%\2
IF %%A EQU 3 DIR >&0 2>NUL
)
Output:
:>MainFile.cmd
Simple test demonstrating loop breaking.
After LOOP
ONE
TWO
Press any key to continue . . .
I hope others find this useful for breaking loops that would otherwise take too long to exit due to continued iteration.
A CSS only solution for those who are having trouble with mobile touchscreen button styling.
This will fix your hover-stick / active button problems.
body, html {
width: 600px;
}
p {
font-size: 20px;
}
button {
border: none;
width: 200px;
height: 60px;
border-radius: 30px;
background: #00aeff;
font-size: 20px;
}
button:active {
background: black;
color: white;
}
.delayed {
transition: all 0.2s;
transition-delay: 300ms;
}
.delayed:active {
transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>
<button>Normal button</button>
<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>
<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures. With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely. This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>
<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
While which
is the most common way of checking if a program is installed, it will tell you a program is installed ONLY if it's in the $PATH
. So if your program is installed, but the $PATH
wasn't updated for whatever reason*, which
will tell you the program isn't installed.
(*One example scenario is changing from Bash to Zshell and ~/.zshrc
not having the old $PATH
from ~/.bash_profile
)
command -v foo
is a better alternative to which foo
. command -v brew
will output nothing if Homebrew is not installed
command -v brew
Here's a sample script to check if Homebrew is installed, install it if it isn't, update if it is.
if [[ $(command -v brew) == "" ]]; then
echo "Installing Hombrew"
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
else
echo "Updating Homebrew"
brew update
fi
A simple function to return a JSON response with the HTTP status code.
function json_response($data=null, $httpStatus=200)
{
header_remove();
header("Content-Type: application/json");
http_response_code($httpStatus);
echo json_encode($data);
exit();
}
On Mac:
Eclipse toolbar Eclipse ? Preferences OR Command + , (comma)
General ? Appearance ? Colors and Fonts ? Basic ? Text Font
Apply
Yes it is, just use the name of the method, as you have written. Methods and functions are objects in Python, just like anything else, and you can pass them around the way you do variables. In fact, you can think about a method (or function) as a variable whose value is the actual callable code object.
Since you asked about methods, I'm using methods in the following examples, but note that everything below applies identically to functions (except without the self
parameter).
To call a passed method or function, you just use the name it's bound to in the same way you would use the method's (or function's) regular name:
def method1(self):
return 'hello world'
def method2(self, methodToRun):
result = methodToRun()
return result
obj.method2(obj.method1)
Note: I believe a __call__()
method does exist, i.e. you could technically do methodToRun.__call__()
, but you probably should never do so explicitly. __call__()
is meant to be implemented, not to be invoked from your own code.
If you wanted method1
to be called with arguments, then things get a little bit more complicated. method2
has to be written with a bit of information about how to pass arguments to method1
, and it needs to get values for those arguments from somewhere. For instance, if method1
is supposed to take one argument:
def method1(self, spam):
return 'hello ' + str(spam)
then you could write method2
to call it with one argument that gets passed in:
def method2(self, methodToRun, spam_value):
return methodToRun(spam_value)
or with an argument that it computes itself:
def method2(self, methodToRun):
spam_value = compute_some_value()
return methodToRun(spam_value)
You can expand this to other combinations of values passed in and values computed, like
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham_value)
or even with keyword arguments
def method2(self, methodToRun, ham_value):
spam_value = compute_some_value()
return methodToRun(spam_value, ham=ham_value)
If you don't know, when writing method2
, what arguments methodToRun
is going to take, you can also use argument unpacking to call it in a generic way:
def method1(self, spam, ham):
return 'hello ' + str(spam) + ' and ' + str(ham)
def method2(self, methodToRun, positional_arguments, keyword_arguments):
return methodToRun(*positional_arguments, **keyword_arguments)
obj.method2(obj.method1, ['spam'], {'ham': 'ham'})
In this case positional_arguments
needs to be a list or tuple or similar, and keyword_arguments
is a dict or similar. In method2
you can modify positional_arguments
and keyword_arguments
(e.g. to add or remove certain arguments or change the values) before you call method1
.
The &&
function is not vectorized. You need the &
function:
EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]
One reason to use an explicite Platform.runLater() could be that you bound a property in the ui to a service (result) property. So if you update the bound service property, you have to do this via runLater():
In UI thread also known as the JavaFX Application thread:
...
listView.itemsProperty().bind(myListService.resultProperty());
...
in Service implementation (background worker):
...
Platform.runLater(() -> result.add("Element " + finalI));
...
The split() method is used to split a string into an array of substrings, and returns the new array.
var array = string.split(',');
You get all tables containing the column product using this statment:
SELECT DISTINCT TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('Product')
AND TABLE_SCHEMA='YourDatabase';
Then you have to run a cursor on these tables so you select eachtime:
Select * from OneTable where product like '%XYZ%'
The results should be entered into a 3rd table or view, take a look here.
Notice: This can work only if the structure of all table is similar, otherwise aou will have to see which columns are united for all these tables and create your result table / View to contain only these columns.
For people who find this via search engines, you do not need VBA. You can just:
1.) select the query or table with your mouse
2.) click export data from the ribbon
3.) click excel from the export subgroup
4.) follow the wizard to select the output file and location.
encodeURI
and encodeURIComponent
:encodeURIComponent(value)
is mainly used to encode queryString parameter values, and it encodes every applicable character in value
. encodeURI
ignores protocol prefix (http://
) and domain name.
In very, very rare cases, when you want to implement manual encoding to encode additional characters (though they don't need to be encoded in typical cases) like: ! *
, then
you might use:
function fixedEncodeURIComponent(str) {
return encodeURIComponent(str).replace(/[!*]/g, function(c) {
return '%' + c.charCodeAt(0).toString(16);
});
}
(source)
It is because your Jenkins not able to find setting file. If deleting .m2 not work, try below solution
Go to your JOB configuration
than to the Build section
Add build step :- Invoke top level maven target and fill Maven version and Goal
than click on Advance button and mention settings file path as mention in image
I see it is an old thread but I had the same error.
I found the explanation here: http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
void execSQL(String sql)
Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
void execSQL(String sql, Object[] bindArgs)
Execute a single SQL statement that is NOT a SELECT/INSERT/UPDATE/DELETE.
ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.
OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true
};
All you have to do is to post URL encoded username and password inside query string.
/Token/userName=johndoe%40example.com&password=1234&grant_type=password
If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.
I'm using the following, though it's hardcoded for gnome-terminal
. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.
:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>
Well if you are getting into a linux machine you can use the package manager of that linux distro.
If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)
You could use yum in fedora and do the same.
if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it
From this article, you can use three options as posts above said.
KeyValuePair is quickest way.
out is at the second.
Tuple is the slowest.
Anyway, this is depend on what is the best for your scenario.
You can keep your CONTACT parameter with the following approach:
using (var stream = new MemoryStream())
{
var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.
Found as accepted answer here
No, you should run mysql -u root -p
in bash, not at the MySQL command-line.
If you are in mysql, you can exit by typing exit.
I was working with this a few days ago, and noticed that sometimes you will need to use the get()
function to print the results of your variable.
ie :
varnames = c('jan', 'feb', 'march')
file_names = list_files('path to multiple csv files saved on drive')
assign(varnames[1], read.csv(file_names[1]) # This will assign the variable
From there, if you try to print the variable varnames[1]
, it returns 'jan'.
To work around this, you need to do
print(get(varnames[1]))
If you have pip
installed (you should have it until you use Python 3.5), list the installed Python packages, like this:
$ pip list | grep -i keras
Keras (1.1.0)
If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)
Consult the pip.log
to see what’s wrong.
You can also display your Python path like this:
$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']
Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages
path (the path is different on Ubuntu).
If not, try do uninstall it, and retry installation:
$ pip uninstall Keras
It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).
The best usage is to create a virtualenv
directory (in your home, for instance), and store your virtualenvs in:
cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel
Then install Keras:
pip install keras
You get:
$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)
But, you also need to install extra libraries, like Tensorflow:
$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
...
ImportError: No module named 'tensorflow'
The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation
Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).
This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.
# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np
# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))
# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8) # mask is only
for i in circles[0, :]:
cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)
# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)
# combine foreground+background
final = cv2.bitwise_or(fg, bk)
Note: It is better to use the opencv methods because they are optimized.
You shouldn't edit it, you should completely scrap it.
Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout
correctly.
In addition to substring answer, you can do it as mystring.SubString(0,3) and check in case statement if its "abc".
But before the switch statement you need to ensure that your mystring is atleast 3 in length.
First get view (eg. by findViewById()
) and then you can use getWidth() on the view itself.
SBJSON *parser = [[SBJSON alloc] init];
NSString *url_str=[NSString stringWithFormat:@"Example APi Here"];
url_str = [url_str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:url_str]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding]
NSDictionary *statuses = [parser2 objectWithString:json_string error:nil];
NSArray *news_array=[[statuses3 objectForKey:@"sold_list"] valueForKey:@"list"];
for(NSDictionary *news in news_array)
{
@try {
[title_arr addObject:[news valueForKey:@"gtitle"]]; //values Add to title array
}
@catch (NSException *exception) {
[title_arr addObject:[NSString stringWithFormat:@""]];
}
If your python >= 3.6, F-string formatted literal is your new friend.
It's more simple, clean, and better performance.
In [1]: params=['Hello', 'adam', 42]
In [2]: %timeit "%s %s, the answer to everything is %d."%(params[0],params[1],params[2])
448 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [3]: %timeit "{} {}, the answer to everything is {}.".format(*params)
449 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %timeit f"{params[0]} {params[1]}, the answer to everything is {params[2]}."
12.7 ns ± 0.0129 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
If you can't hold all the items in memory at once, this problem becomes much harder. The heap solution requires you to hold all the elements in memory at once. This is not possible in most real world applications of this problem.
Instead, as you see numbers, keep track of the count of the number of times you see each integer. Assuming 4 byte integers, that's 2^32 buckets, or at most 2^33 integers (key and count for each int), which is 2^35 bytes or 32GB. It will likely be much less than this because you don't need to store the key or count for those entries that are 0 (ie. like a defaultdict in python). This takes constant time to insert each new integer.
Then at any point, to find the median, just use the counts to determine which integer is the middle element. This takes constant time (albeit a large constant, but constant nonetheless).
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
I think you've found a bug in the strtotime function. Whenever I have to work around this, I always find myself doing math on the month/year values. Try something like this:
$LastMonth = (date('n') - 1) % 12;
$Year = date('Y') - !$LastMonth;
No, this is not possible. In documents that make use of CSS, an inline style
attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:
The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:
declaration-list : S* declaration? [ ';' S* declaration? ]* ;
Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.
Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style
attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).
Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important
notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.
Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.
Below is the simplest way
Try the code
ALTER TRIGGER trigger_name DISABLE
That's it :)
It's a fair question and he did state apart from the obvious…
Disadvantages could include:
Performance implications Query optimizer uses field size to determine most efficent exectution plan
"1. The space alloction in extends and pages of the database are flexible. Thus when adding information to the field using update, your database would have to create a pointer if the new data is longer than the previous inserted. This the database files would become fragmented = lower performance in almost everything, from index to delete, update and inserts. " http://sqlblogcasts.com/blogs/simons/archive/2006/02/28/Why-use-anything-but-varchar_2800_max_2900_.aspx
Integration implications - hard for other systems to know how to integrate with your database Unpredictable growth of data Possible security issues e.g. you could crash a system by taking up all disk space
There is good article here: http://searchsqlserver.techtarget.com/tip/1,289483,sid87_gci1098157,00.html
You now can do this with Flexbox justify-content: flex-end
now:
div {_x000D_
display: flex;_x000D_
justify-content: flex-end;_x000D_
align-items: flex-end;_x000D_
width: 150px;_x000D_
height: 150px;_x000D_
border: solid 1px red;_x000D_
}_x000D_
_x000D_
<div>_x000D_
Something to align_x000D_
</div>
_x000D_
Consult your Caniuse to see if Flexbox is right for you.
Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:
.flex-row-container {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
flex: 1 1 30%; /*grow | shrink | basis */_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
background-color: #fff4e6;_x000D_
border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
<div class="flex-row-item">1</div>_x000D_
<div class="flex-row-item">2</div>_x000D_
<div class="flex-row-item">3</div>_x000D_
<div class="flex-row-item">4</div>_x000D_
<div class="flex-row-item">5</div>_x000D_
<div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
Hope this helps someone else.
It is matter of performance and memory usage, compile and keep the complied pattern if you need to use it a lot. A typical usage of regex is to validated user input (format), and also format output data for users, in these classes, saving the complied pattern, seems quite logical as they usually called a lot.
Below is a sample validator, which is really called a lot :)
public class AmountValidator {
//Accept 123 - 123,456 - 123,345.34
private static final String AMOUNT_REGEX="\\d{1,3}(,\\d{3})*(\\.\\d{1,4})?|\\.\\d{1,4}";
//Compile and save the pattern
private static final Pattern AMOUNT_PATTERN = Pattern.compile(AMOUNT_REGEX);
public boolean validate(String amount){
if (!AMOUNT_PATTERN.matcher(amount).matches()) {
return false;
}
return true;
}
}
As mentioned by @Alan Moore, if you have reusable regex in your code, (before a loop for example), you must compile and save pattern for reuse.
If you want query parameters, you use @QueryParam
.
public Todo getXML(@QueryParam("summary") String x,
@QueryParam("description") String y)
But you won't be able to send a PUT from a plain web browser (today). If you type in the URL directly, it will be a GET.
Philosophically, this looks like it should be a POST, though. In REST, you typically either POST to a common resource, /todo
, where that resource creates and returns a new resource, or you PUT to a specifically-identified resource, like /todo/<id>
, for creation and/or update.
Answering my own question about 2 or something years later here but...
It uses a protocol extension so you can do it without any extra code for all classes.
/*
Prerequisites
-------------
- In IB set the view's class to the type hook up any IBOutlets
- In IB ensure the file's owner is blank
*/
public protocol CreatedFromNib {
static func createFromNib() -> Self?
static func nibName() -> String?
}
extension UIView: CreatedFromNib { }
public extension CreatedFromNib where Self: UIView {
public static func createFromNib() -> Self? {
guard let nibName = nibName() else { return nil }
guard let view = NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil).last as? Self else { return nil }
return view
}
public static func nibName() -> String? {
guard let n = NSStringFromClass(Self.self).componentsSeparatedByString(".").last else { return nil }
return n
}
}
// Usage:
let myView = MyView().createFromNib()
You can use a utility function I've created for the purpose of running code in the page context and getting back the returned value.
This is done by serializing a function to a string and injecting it to the web page.
The utility is available here on GitHub.
Usage examples -
// Some code that exists only in the page context -
window.someProperty = 'property';
function someFunction(name = 'test') {
return new Promise(res => setTimeout(()=>res('resolved ' + name), 1200));
}
/////////////////
// Content script examples -
await runInPageContext(() => someProperty); // returns 'property'
await runInPageContext(() => someFunction()); // returns 'resolved test'
await runInPageContext(async (name) => someFunction(name), 'with name' ); // 'resolved with name'
await runInPageContext(async (...args) => someFunction(...args), 'with spread operator and rest parameters' ); // returns 'resolved with spread operator and rest parameters'
await runInPageContext({
func: (name) => someFunction(name),
args: ['with params object'],
doc: document,
timeout: 10000
} ); // returns 'resolved with params object'
I faced a similar problem but in my case I was trying to install Visual C++ Redistributable for Visual Studio 2015 Update 1 on Windows Server 2012 R2. However the root cause should be the same.
In short, you need to install the prerequisites of KB2999226.
In more details, the installation log I got stated that the installation for Windows Update KB2999226 failed. According to the Microsoft website here:
Prerequisites To install this update, you must have April 2014 update rollup for Windows RT 8.1, Windows 8.1, and Windows Server 2012 R2 (2919355) installed in Windows 8.1 or Windows Server 2012 R2. Or, install Service Pack 1 for Windows 7 or Windows Server 2008 R2. Or, install Service Pack 2 for Windows Vista and for Windows Server 2008.
After I have installed April 2014 on my Windows Server 2012 R2, I am able to install the Visual C++ Redistributable correctly.
I had the same problem but was because I had already previously installed xampp , and I tried to install a newer version , then I installed the newer version in another file directory (I named the file directory xampp2). I solved the problem after uninstall the newer version, rename the old one (I renamed as xamppold), and installing xampp again.
I guess if you didn't installed xampp in another file directory or something like that , it should be enough to reinstall xampp. If you are worried about your files , you always can make a backup before reinstalling xampp.
I solved the problem after watching the xampp activity log (the list of the bottom) and realizing xampp was trying to open the custom file path but I had another route path. If the first option didn't worked, at least you can scroll up in the activity log and see whats the error you get while starting as admin and trying to re install the Apache module or trying to start the module.
You may wander why I didn't just simply uninstall the whole thing from the beginning , and the answer would be I have tweak a couple of things of xampp for some different projects (from changing the ports , to add .dll to run mongo.db in Apache), and I'm just too lazy to re-do everything again :b
I hope my answer can be helpful for anyone since is my first time writing in stackoverflow :)
Cheers
For another un-free option try edtFTPnet/PRO. It has comprehensive support for SFTP, and also supports FTPS (and of course FTP) if required.
AMD
CommonJS:
Example
upper.js file
exports.uppercase = str => str.toUpperCase()
main.js file
const uppercaseModule = require('uppercase.js')
uppercaseModule.uppercase('test')
Summary
Resources:
To me the best way to debug on React-Native is by using "Reactotron".
Install Reactotron then add these to your package.json:
"reactotron-apisauce": "^1.1.2",
"reactotron-react-native-under-37": "^1.1.2",
"reactotron-redux": "^1.1.2",
now, it just the matter of logging in your code.
e.g.: console.tron.log('debug')
First, note that restarting httpd is not necessary for .htaccess files. .htaccess files are specifically for people who don't have root - ie, don't have access to the httpd server config file, and can't restart the server. As you're able to restart the server, you don't need .htaccess files and can use the main server config directly.
Secondly, if .htaccess files are being ignored, you need to check to see that AllowOverride is set correctly. See http://httpd.apache.org/docs/2.4/mod/core.html#allowoverride for details. You need to also ensure that it is set in the correct scope - ie, in the right block in your configuration. Be sure you're NOT editing the one in the block, for example.
Third, if you want to ensure that a .htaccess file is in fact being read, put garbage in it. An invalid line, such as "INVALID LINE HERE", in your .htaccess file, will result in a 500 Server Error when you point your browser at the directory containing that file. If it doesn't, then you don't have AllowOverride configured correctly.
Queue is an interface; you can't explicitly construct a Queue. You'll have to instantiate one of its implementing classes. Something like:
Queue linkedList = new LinkedList();
As of SciPy version 1.1, you can also use find_peaks. Below are two examples taken from the documentation itself.
Using the height
argument, one can select all maxima above a certain threshold (in this example, all non-negative maxima; this can be very useful if one has to deal with a noisy baseline; if you want to find minima, just multiply you input by -1
):
import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np
x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()
Another extremely helpful argument is distance
, which defines the minimum distance between two peaks:
peaks, _ = find_peaks(x, distance=150)
# difference between peaks is >= 150
print(np.diff(peaks))
# prints [186 180 177 171 177 169 167 164 158 162 172]
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.show()
You can also simplify your function, as follows:
public int fibonacci(int n) {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:
Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type. Recommended approach is implement Singletons by simply make an enum type with one element:
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
public void leaveTheBuilding() { ... }
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.
While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.
The equals method on List will do this, Lists are ordered, so to be equal two Lists must have the same elements in the same order.
return list1.equals(list2);
Extracting into an Uber-dir works for me as we s should all be using root:\java and have outlets code in packages with versioning. Ie ca.tecreations-1.0.0. Signing is okay because the jars are intact from their downloaded location. 3rd party signatures intact, extract to c:\java. There’s my project dir. run from launcher so java -cp c:\java Launcher
Current Fragment:
This works if you created a project with the fragments tabbar template.
Fragment f = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
Note that this works with the default tabbed activity template implementation.
It subjects to architecture of the server on which PHP runs. For 64-bit,
print PHP_INT_MIN . ", ” . PHP_INT_MAX;
yields -9223372036854775808, 9223372036854775807
If you just do eval $cmd
when we do cmd="ls -l"
(interactively and in a script) we get the desired result. In your case, you have a pipe with a grep without a pattern, so the grep part will fail with an error message. Just $cmd
will generate a "command not found" (or some such) message.
So try use eval and use a finished command, not one that generates an error message.
Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.
Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.
In your app level build.gradle
file add the following,
dependencies {
def fragment_version = "1.2.5"
// Kotlin
implementation "androidx.fragment:fragment-ktx:$fragment_version"
// Testing Fragments in Isolation
debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
In your activity
supportFragmentManager.commit {
replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
addToBackStack(null)
}
References
Try $("input[type='text']").attr('disabled', true);
Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.
Old thread but thought I'd just add that the reason developers use this construct is not to create a dead link, but because javascript URLs for some reason do not pass references to the active html element correctly.
e.g. handler_function(this.id)
works as onClick
but not as a javascript URL.
Thus it's a choice between writing pedantically standards-compliant code that involves you in having to manually adjust the call for each hyperlink, or slightly non-standard code which can be written once and used everywhere.
I believe you can access this from the socket's manager property?
var handshaken = io.manager.handshaken;
var connected = io.manager.connected;
var open = io.manager.open;
var closed = io.manager.closed;
To replace multiples columns convert to numpy array using .values
:
df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2
This should work. getElementsByClassName
returns an array Array-like object(see edit) of the elements matching the criteria.
var elements = document.getElementsByClassName("classname");
var myFunction = function() {
var attribute = this.getAttribute("data-myattribute");
alert(attribute);
};
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', myFunction, false);
}
jQuery does the looping part for you, which you need to do in plain JavaScript.
If you have ES6 support you can replace your last line with:
Array.from(elements).forEach(function(element) {
element.addEventListener('click', myFunction);
});
Note: Older browsers (like IE6, IE7, IE8) don´t support getElementsByClassName
and so they return undefined
.
EDIT : Correction
getElementsByClassName
doesnt return an array, but a HTMLCollection in most, or a NodeList in some browsers (Mozilla ref). Both of these types are Array-Like, (meaning that they have a length property and the objects can be accessed via their index), but are not strictly an Array or inherited from an Array. (meaning other methods that can be performed on an Array cannot be performed on these types)
Thanks to user @Nemo for pointing this out and having me dig in to fully understand.
The way to do this is near the top of the man page
grep -i -A 10 'error data'
If you want this behaviour everywhere in your app and don't want to add anything to individual viewDidAppear
etc. then you should create a subclass
class QFNavigationController:UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate{
override func viewDidLoad() {
super.viewDidLoad()
interactivePopGestureRecognizer?.delegate = self
delegate = self
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
super.pushViewController(viewController, animated: animated)
interactivePopGestureRecognizer?.isEnabled = false
}
func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
interactivePopGestureRecognizer?.isEnabled = true
}
// IMPORTANT: without this if you attempt swipe on
// first view controller you may be unable to push the next one
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return viewControllers.count > 1
}
}
Now, whenever you use QFNavigationController
you get the desired experience.
When you use jackson to map from string to your concrete class, especially if you work with generic type. then this issue may happen because of different class loader. i met it one time with below scenarior:
Project B depend on Library A
in Library A:
public class DocSearchResponse<T> {
private T data;
}
it has service to query data from external source, and use jackson to convert to concrete class
public class ServiceA<T>{
@Autowired
private ObjectMapper mapper;
@Autowired
private ClientDocSearch searchClient;
public DocSearchResponse<T> query(Criteria criteria){
String resultInString = searchClient.search(criteria);
return convertJson(resultInString)
}
}
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
in Project B:
public class Account{
private String name;
//come with other attributes
}
and i use ServiceA from library to make query and as well convert data
public class ServiceAImpl extends ServiceA<Account> {
}
and make use of that
public class MakingAccountService {
@Autowired
private ServiceA service;
public void execute(Criteria criteria){
DocSearchResponse<Account> result = service.query(criteria);
Account acc = result.getData(); // java.util.LinkedHashMap cannot be cast to com.testing.models.Account
}
}
it happen because from classloader of LibraryA, jackson can not load Account class, then just override method convertJson
in Project B to let jackson do its job
public class ServiceAImpl extends ServiceA<Account> {
@Override
public DocSearchResponse<T> convertJson(String result){
return mapper.readValue(result, new TypeReference<DocSearchResponse<T>>() {});
}
}
}
http://www.eclipsezone.com/eclipse/forums/t53459.html
Basically run it with:
-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044
The application, at launch, will wait until you connect from another source.
Don't use tellg
to determine the exact size of the file. The length determined by tellg
will be larger than the number of characters can be read from the file.
From stackoverflow question tellg() function give wrong size of file? tellg
does not report the size of the file, nor the offset from the beginning in bytes. It reports a token value which can later be used to seek to the same place, and nothing more. (It's not even guaranteed that you can convert the type to an integral type.). For Windows (and most non-Unix systems), in text mode, there is no direct and immediate mapping between what tellg returns and the number of bytes you must read to get to that position.
If it is important to know exactly how many bytes you can read, the only way of reliably doing so is by reading. You should be able to do this with something like:
#include <fstream>
#include <limits>
ifstream file;
file.open(name,std::ios::in|std::ios::binary);
file.ignore( std::numeric_limits<std::streamsize>::max() );
std::streamsize length = file.gcount();
file.clear(); // Since ignore will have set eof.
file.seekg( 0, std::ios_base::beg );
In case you arrive here looking for a way to make PDF from view templates in Express, a colleague and I made express-template-to-pdf
which allows you to generate PDF from whatever templates you're using in Express - Pug, Nunjucks, whatever.
It depends on html-pdf and is written to use in your routes just like you use res.render:
const pdfRenderer = require('@ministryofjustice/express-template-to-pdf')
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'pug')
app.use(pdfRenderer())
If you've used res.render then using it should look obvious:
app.use('/pdf', (req, res) => {
res.renderPDF('helloWorld', { message: 'Hello World!' });
})
You can pass options through to html-pdf to control the PDF document page size etc
Merely building on the excellent work of others.
As one of the possible codes
echo off
for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
echo The current directory is: "%var:~1%"
You can do it simply.
var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
here is the best way:
on this way you have only one css with all shared code and an html page. by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.
You mention that you will call on each vertical column so that you can perform calculations. I assume that you just want to examine each single variable. This can be done through the following.
df <- read.csv("myRandomFile.csv", header=TRUE)
df$ID
df$GRADES
df$GPA
Might be helpful just to assign the data to a variable.
var3 <- df$GPA
A tad more generic copy/paste function for your project.
sumjq = function(selector) {
var sum = 0;
$(selector).each(function() {
sum += Number($(this).text());
});
return sum;
}
console.log(sumjq('.price'));
(Update: a few years later Google and Qwant "airlines" still send me here when searching for "git non-default ssh port") A probably better way in newer git versions is to use the GIT_SSH_COMMAND ENV.VAR like:
GIT_SSH_COMMAND="ssh -oPort=1234 -i ~/.ssh/myPrivate_rsa.key" \
git clone myuser@myGitRemoteServer:/my/remote/git_repo/path
This has the added advantage of allowing any other ssh suitable option (port, priv.key, IPv6, PKCS#11 device, ...).
Due to PermGen removal some options were removed (like -XX:MaxPermSize
), but options -Xms
and -Xmx
work in Java 8. It's possible that under Java 8 your application simply needs somewhat more memory. Try to increase -Xmx
value. Alternatively you can try to switch to G1 garbage collector using -XX:+UseG1GC
.
Note that if you use any option which was removed in Java 8, you will see a warning upon application start:
$ java -XX:MaxPermSize=128M -version
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=128M; support was removed in 8.0
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b18)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:
select * from exception where exception_value = to_char(105);
I'm using this:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
Now (2021) the preferred way to use istanbul is via its "state of the art command line interface" nyc.
First, install it in your project with
npm i nyc --save-dev
Then, if you have a npm based project, just change the test script inside the scripts
object of your package.json file to execute code coverage of your mocha tests:
{
"scripts": {
"test": "nyc --reporter=text mocha"
}
}
Now run your tests
npm test
and you will see a table like this in your console, just after your tests output:
Just use
nyc --reporter=html
instead of text
. Now it will produce a report inside ./coverage/index.html
.
Istanbul supports a wide range of report formats. Just look at its reports library to find the most useful for you.
Just add a --reporter=REPORTER_NAME
option for each format you want.
For example, with
nyc --reporter=html --reporter=text
you will have both the console and the html report.
Just add another script in your package.json
and leave the test
script with only your test runner (e.g. mocha):
{
"scripts": {
"test": "mocha",
"test-with-coverage": "nyc --reporter=text mocha"
}
}
Now run this custom script
npm run test-with-coverage
to run tests with code coverage.
Fail if the total code coverage is below 90%:
nyc --check-coverage --lines 90
Fail if the code coverage of at least one file is below 90%:
nyc --check-coverage --lines 90 --per-file
For future Googlers, If you get an error similar below after you trigger click for a polygon
"Uncaught TypeError: Cannot read property 'vertex' of undefined"
then try the code below
google.maps.event.trigger(polygon, "click", {});
If you by any chance are using Wordpress to develop your app (it's actually a convenient way to get authorization, info pages etc even for very simple stuff), you can use the following snippet:
$response = wp_remote_post( $url, array('body' => $parameters));
if ( is_wp_error( $response ) ) {
// $response->get_error_message()
} else {
// $response['body']
}
It uses different ways of making the actual HTTP request, depending on what is available on the web server. For more details, see the HTTP API documentation.
If you don't want to develop a custom theme or plugin to start the Wordpress engine, you can just do the following in an isolated PHP file in the wordpress root:
require_once( dirname(__FILE__) . '/wp-load.php' );
// ... your code
It won't show any theme or output any HTML, just hack away with the Wordpress APIs!