You just have to set UIFileSharingEnabled
(Application Supports iTunes file sharing
) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.
In the past, it was also necessary to define CFBundleDisplayName
(Bundle Display Name
), if it wasn't already there. More details here.
AFAIK, you don't need to map the UNC path to a drive letter in order to establish credentials for a server. I regularly used batch scripts like:
net use \\myserver /user:username password
:: do something with \\myserver\the\file\i\want.xml
net use /delete \\my.server.com
However, any program running on the same account as your program would still be able to access everything that username:password
has access to. A possible solution could be to isolate your program in its own local user account (the UNC access is local to the account that called NET USE
).
Note: Using SMB accross domains is not quite a good use of the technology, IMO. If security is that important, the fact that SMB lacks encryption is a bit of a damper all by itself.
This worked for me:
min-height: 14px;
height: 14px;
Use Type.IsAssignableTo
(as of .NET 5.0):
typeof(MyType).IsAssignableTo(typeof(IMyInterface));
As stated in a couple of comments IsAssignableFrom may be considered confusing by being "backwards".
Merge two different eloquent collections into one and some objects happen to have the same id, one will overwrite the other. Use push() method instead or rethink your approach to the problem to avoid that. Refer to web
The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.
java.util.Date constructor with parameters like
new Date(int year, int month, int date, int hrs, int min).
is deprecated and preferably do not use it any more. Oracle docs prefers the way over java.util.Calendar. So you can set any date and instantiate Date object through the getTime() method.
Calendar calendar = Calendar.getInstance();
calendar.set(2018, 11, 31, 59, 59, 59);
Date happyNewYearDate = calendar.getTime();
Notice that month number starts from 0
I can usually resolve this problem when a computer is under my control, but it's more of a nuisance when working with a grid. When a grid is not homogenous, not all libraries may be installed, and my experience has often been that a package wasn't installed because a dependency wasn't installed. To address this, I check the following:
.libPaths()
is a good check.ldd
results for R, to be sure about shared librariesHaving encountered this quite a bit, some of these steps become fairly routine. Although #7 might seem like a good starting point, these are listed in approximate order of the frequency that I use them.
Another option is:
<Grid container justify = "center">
<Your centered component/>
</Grid>
Arbitrarily choosing to keep the minimum PIC_ID. Also, avoid using the implicit join syntax.
SELECT U.NAME, MIN(P.PIC_ID)
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
GROUP BY U.NAME;
I've had this same issue but have now found the resolution for it.
The trick is to create a wallpaper image of 1920*1200. When you then apply this wallpaper to the different machines, Windows 7 automatically resizes for best fit.
Hope this helps you all
If you're iterating over an object instead of an array, you'll need to access the properties using:
$id = $blog->id;
$title = $blog->title;
$content = $blog->content;
That, or change your object to an array.
Remove the width and display: block
and then add display: inline-block
to the button. To have it remain centered you can either add text-align: center;
on the body
or do the same on a newly created container.
The advantage of this approach (as opossed to centering with auto margins) is that the button will remain centered regardless of how much text it has.
Example: http://cssdeck.com/labs/2u4kf6dv
I'm doing something like that but on hover instead of on click.. This is the code I'm using, you might be able to tweak it up a bit to get it to work on click
$('.navbar .dropdown').hover(function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(250).slideDown();
}, function() {
$(this).find('.dropdown-menu').first().stop(true, true).delay(100).slideUp()
});
Create a hidden column "dateOrder" (for example) with the date as string with the format "yyyyMMddHHmmss" and use the property "orderData" to point to that column.
var myTable = $("#myTable").dataTable({
columns: [
{ data: "id" },
{ data: "date", "orderData": 4 },
{ data: "name" },
{ data: "total" },
{ data: "dateOrder", visible: false }
] });
It presents a prompt to the user (the optional arg
of raw_input([arg])
), gets input from the user and returns the data input by the user in a string. See the docs for raw_input()
.
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input()
in that the latter tries to interpret the input given by the user; it is usually best to avoid input()
and to stick with raw_input()
and custom parsing/conversion code.
Note: This is for Python 2.x
Here is another answer:
With DinnerComboBox
.AddItem "Italian"
.AddItem "Chinese"
.AddItem "Frites and Meat"
End With
Source: Show the
I had very similar problem for something like an hour, until I figured out what went wrong. My problem was, that I used SSL, instead of ssl. Check is case sensitive in the code. AlexV guided me to the source of the problem. That helo/ehlo -stuff seems irrelevant.
<?php
echo preg_replace( '#<li[^>]+>#', '<li class="col-sm-4">',
wp_nav_menu(
array(
'menu' => $nav_menu,
'container' => false,
'container_class' => false,
'menu_class' => false,
'items_wrap' => '%3$s',
'depth' => 1,
'echo' => false
)
)
);
?>
try this
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
<tr style="height:100px">_x000D_
<td valign="top">January</td>_x000D_
<td valign="bottom">$100</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
use valign="top" for td style
A funny way to do this is
>>> np.array([True, False, False]) + 0
np.array([1, 0, 0])
Here's a complete answer with Objective C and Swift:
1) Create an IBAction
unwind segue in your destination view controller (where you want to segue to). Anywhere in the implementation file.
// Objective C
- (IBAction)unwindToContainerVC:(UIStoryboardSegue *)segue {
}
// Swift
@IBAction func unwindToContainerVC(segue: UIStoryboardSegue) {
}
2) On the source view controller (the controller you're segueing from), ^ + drag from "Name of activity" to exit. You should see the unwind segue created in step 1 in the popup. (If you don't see it, review step one). Pick unwindToContainerVC: from the popup, or whatever you named your method to connect your source controller to the unwind IBAction.
3) Select the segue in the source view controller's document outline of the storyboard (it will be listed near the bottom), and give it an identifier.
4) Call the unwind segue using this method from source view controller, substituting your unwind segue name.
// Objective C
[self performSegueWithIdentifier:@"unwindToContainerVC" sender:self];
// Swift
self.performSegueWithIdentifier("unwindToContainerVC", sender: self)
NB. Use the sourceViewController property of the segue parameter on the unwind method to access any exposed properties on the source controller. Also, notice that the framework handles dismissing the source controller. If you'd like to confirm this add a dealloc method to the source controller with a log message that should fire once it has been killed. If dealloc doesn't fire you may have a retain cycle.
it may be another mysqld instance running and stoped it with:
sudo service mysql stop
Worked for me.
Backtick quotes with a space inside and two spaces to follow. Repeat as needed for more lines:
text1 text1
`(space)`(space)(space)
`(space)`(space)(space)
text2 text2
It looks decent in Markdown source:
text1 text1
` `
` `
text2 text2
Combining matty-j suggestion with the snippet of the question, I ended up with this code focusing on resizing the grid after the data was loaded.
The HTML:
<div ng-grid="gridOptions" class="gridStyle"></div>
The directive:
angular.module('myApp.directives', [])
.directive('resize', function ($window) {
return function (scope, element) {
var w = angular.element($window);
scope.getWindowDimensions = function () {
return { 'h': w.height(), 'w': w.width() };
};
scope.$watch(scope.getWindowDimensions, function (newValue, oldValue) {
// resize Grid to optimize height
$('.gridStyle').height(newValue.h - 250);
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
The controller:
angular.module('myApp').controller('Admin/SurveyCtrl', function ($scope, $routeParams, $location, $window, $timeout, Survey) {
// Retrieve data from the server
$scope.surveys = Survey.query(function(data) {
// Trigger resize event informing elements to resize according to the height of the window.
$timeout(function () {
angular.element($window).resize();
}, 0)
});
// Configure ng-grid.
$scope.gridOptions = {
data: 'surveys',
...
};
}
I've taked the solution of @AZ_ and converted it in a kotlin extension function:
So copy this in your code:
@SuppressLint("ClickableViewAccessibility")
fun EditText.setDrawableRightTouch(setClickListener: () -> Unit) {
this.setOnTouchListener(View.OnTouchListener { _, event ->
val DRAWABLE_LEFT = 0
val DRAWABLE_TOP = 1
val DRAWABLE_RIGHT = 2
val DRAWABLE_BOTTOM = 3
if (event.action == MotionEvent.ACTION_UP) {
if (event.rawX >= this.right - this.compoundDrawables[DRAWABLE_RIGHT].bounds.width()
) {
setClickListener()
return@OnTouchListener true
}
}
false
})
}
You can use it just calling the setDrawableRightTouch
function on your EditText
:
yourEditText.setDrawableRightTouch {
//your code
}
That comment looks like it is a custom version of Bootstrap v2.3.3, here is the default header in the .css, notice the last comment line:
/*!
* Bootstrap v2.3.2
*
* Copyright 2013 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world by @mdo and @fat.
*/
What are you trying to accomplish? If it's customization then you have a set of files to work with though that seems like a bad idea. Otherwise, I would suggest going with the full build of v4.1.x since that is the current release.
As Service is already a Context itself
you can even get it through:
Context mContext = this;
OR
Context mContext = [class name].this; //[] only specify the class name
// mContext = JobServiceSchedule.this;
For anyone coming here looking for how to do this in C#, I have tried the following method and had success in dotnet core 2.0.3
and entity framework core 2.0.3
First create your model class.
public class User
{
public string Name { get; set; }
public int Address { get; set; }
public int ZIP { get; set; }
public string Gender { get; set; }
}
Then install EPPlus Nuget package. (I used version 4.0.5, probably will work for other versions as well.)
Install-Package EPPlus -Version 4.0.5
The create ExcelExportHelper
class, which will contain the logic to convert dataset to Excel rows. This class do not have dependencies with your model class or dataset.
public class ExcelExportHelper
{
public static string ExcelContentType
{
get
{ return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; }
}
public static DataTable ListToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable dataTable = new DataTable();
for (int i = 0; i < properties.Count; i++)
{
PropertyDescriptor property = properties[i];
dataTable.Columns.Add(property.Name, Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType);
}
object[] values = new object[properties.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = properties[i].GetValue(item);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static byte[] ExportExcel(DataTable dataTable, string heading = "", bool showSrNo = false, params string[] columnsToTake)
{
byte[] result = null;
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet workSheet = package.Workbook.Worksheets.Add(String.Format("{0} Data", heading));
int startRowFrom = String.IsNullOrEmpty(heading) ? 1 : 3;
if (showSrNo)
{
DataColumn dataColumn = dataTable.Columns.Add("#", typeof(int));
dataColumn.SetOrdinal(0);
int index = 1;
foreach (DataRow item in dataTable.Rows)
{
item[0] = index;
index++;
}
}
// add the content into the Excel file
workSheet.Cells["A" + startRowFrom].LoadFromDataTable(dataTable, true);
// autofit width of cells with small content
int columnIndex = 1;
foreach (DataColumn column in dataTable.Columns)
{
int maxLength;
ExcelRange columnCells = workSheet.Cells[workSheet.Dimension.Start.Row, columnIndex, workSheet.Dimension.End.Row, columnIndex];
try
{
maxLength = columnCells.Max(cell => cell.Value.ToString().Count());
}
catch (Exception) //nishanc
{
maxLength = columnCells.Max(cell => (cell.Value +"").ToString().Length);
}
//workSheet.Column(columnIndex).AutoFit();
if (maxLength < 150)
{
//workSheet.Column(columnIndex).AutoFit();
}
columnIndex++;
}
// format header - bold, yellow on black
using (ExcelRange r = workSheet.Cells[startRowFrom, 1, startRowFrom, dataTable.Columns.Count])
{
r.Style.Font.Color.SetColor(System.Drawing.Color.White);
r.Style.Font.Bold = true;
r.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
r.Style.Fill.BackgroundColor.SetColor(Color.Brown);
}
// format cells - add borders
using (ExcelRange r = workSheet.Cells[startRowFrom + 1, 1, startRowFrom + dataTable.Rows.Count, dataTable.Columns.Count])
{
r.Style.Border.Top.Style = ExcelBorderStyle.Thin;
r.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;
r.Style.Border.Left.Style = ExcelBorderStyle.Thin;
r.Style.Border.Right.Style = ExcelBorderStyle.Thin;
r.Style.Border.Top.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Bottom.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Left.Color.SetColor(System.Drawing.Color.Black);
r.Style.Border.Right.Color.SetColor(System.Drawing.Color.Black);
}
// removed ignored columns
for (int i = dataTable.Columns.Count - 1; i >= 0; i--)
{
if (i == 0 && showSrNo)
{
continue;
}
if (!columnsToTake.Contains(dataTable.Columns[i].ColumnName))
{
workSheet.DeleteColumn(i + 1);
}
}
if (!String.IsNullOrEmpty(heading))
{
workSheet.Cells["A1"].Value = heading;
// workSheet.Cells["A1"].Style.Font.Size = 20;
workSheet.InsertColumn(1, 1);
workSheet.InsertRow(1, 1);
workSheet.Column(1).Width = 10;
}
result = package.GetAsByteArray();
}
return result;
}
public static byte[] ExportExcel<T>(List<T> data, string Heading = "", bool showSlno = false, params string[] ColumnsToTake)
{
return ExportExcel(ListToDataTable<T>(data), Heading, showSlno, ColumnsToTake);
}
}
Now add this method where you want to generate the excel file, probably for a method in the controller. You can pass parameters for your stored procedure as well. Note that the return type of the method is FileContentResult
. Whatever query you execute, important thing is you must have the results in a List
.
[HttpPost]
public async Task<FileContentResult> Create([Bind("Id,StartDate,EndDate")] GetReport getReport)
{
DateTime startDate = getReport.StartDate;
DateTime endDate = getReport.EndDate;
// call the stored procedure and store dataset in a List.
List<User> users = _context.Reports.FromSql("exec dbo.SP_GetEmpReport @start={0}, @end={1}", startDate, endDate).ToList();
//set custome column names
string[] columns = { "Name", "Address", "ZIP", "Gender"};
byte[] filecontent = ExcelExportHelper.ExportExcel(users, "Users", true, columns);
// set file name.
return File(filecontent, ExcelExportHelper.ExcelContentType, "Report.xlsx");
}
More details can be found here
DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);
assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.
The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.
As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.
If you need to parse other formats, you can check out the Standard DateTime Format Strings.
Here is an example of a drawable that will be white by default, black when pressed:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid
android:color="#1E669B"/>
<stroke
android:width="2dp"
android:color="#1B5E91"/>
<corners
android:radius="6dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
<item>
<shape>
<gradient
android:angle="270"
android:endColor="#1E669B"
android:startColor="#1E669B"/>
<stroke
android:width="4dp"
android:color="#1B5E91"/>
<corners
android:radius="7dp"/>
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp"/>
</shape>
</item>
</selector>
Well, you are using both frame.setSize()
and frame.pack()
.
You should use one of them at one time.
Using setSize()
you can give the size of frame you want but if you use pack()
, it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.
Try removing frame.pack()
from your code or putting it before setting size and then run it.
In internet explorer, if the new url is from the same domain as the current url, the window will be open without an address bar. Otherwise, it will cause an address bar to appear. One workaround is to open a page from the same domain and then redirect from that page.
Add .idea
and *.iml
to .gitignore
, you don't need those files to successfully import and compile the project.
Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).
var count_data = data.length;
$.each( data, function( index ){
var column = ( index < count_data/2 ) ? 1 : 2;
$("#column"+column).append(this.name+'<br/>');
});
<div id="majors_view" class="span12 pull-left">
<div class="row-fluid">
<div class="span5" id="column1"> </div>
<div class="span5 offset1" id="column2"> </div>
</div>
</div>
You know, I've found (and I've tested this over and over) that try/except does not perform all that well, for whatever reason. I frequently try several ways of doing things, and I don't think I've ever found a method that uses try/except to perform the best of those tested, in fact it seems to me those methods have usually come out close to the worst, if not the worst. Not in every case, but in many cases. I know a lot of people say it's the "Pythonic" way, but that's one area where I part ways with them. To me, it's neither very performant nor very elegant, so, I tend to only use it for error trapping and reporting.
I was going to gripe that PHP, perl, ruby, C, and even the freaking shell have simple functions for testing a string for integer-hood, but due diligence in verifying those assumptions tripped me up! Apparently this lack is a common sickness.
Here's a quick and dirty edit of Bruno's post:
import sys, time, re
g_intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
testvals = [
# integers
0, 1, -1, 1.0, -1.0,
'0', '0.','0.0', '1', '-1', '+1', '1.0', '-1.0', '+1.0', '06',
# non-integers
'abc 123',
1.1, -1.1, '1.1', '-1.1', '+1.1',
'1.1.1', '1.1.0', '1.0.1', '1.0.0',
'1.0.', '1..0', '1..',
'0.0.', '0..0', '0..',
'one', object(), (1,2,3), [1,2,3], {'one':'two'},
# with spaces
' 0 ', ' 0.', ' .0','.01 '
]
def isInt_try(v):
try: i = int(v)
except: return False
return True
def isInt_str(v):
v = str(v).strip()
return v=='0' or (v if v.find('..') > -1 else v.lstrip('-+').rstrip('0').rstrip('.')).isdigit()
def isInt_re(v):
import re
if not hasattr(isInt_re, 'intRegex'):
isInt_re.intRegex = re.compile(r"^([+-]?[1-9]\d*|0)$")
return isInt_re.intRegex.match(str(v).strip()) is not None
def isInt_re2(v):
return g_intRegex.match(str(v).strip()) is not None
def check_int(s):
s = str(s)
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
def timeFunc(func, times):
t1 = time.time()
for n in range(times):
for v in testvals:
r = func(v)
t2 = time.time()
return t2 - t1
def testFuncs(funcs):
for func in funcs:
sys.stdout.write( "\t%s\t|" % func.__name__)
print()
for v in testvals:
if type(v) == type(''):
sys.stdout.write("'%s'" % v)
else:
sys.stdout.write("%s" % str(v))
for func in funcs:
sys.stdout.write( "\t\t%s\t|" % func(v))
sys.stdout.write("\r\n")
if __name__ == '__main__':
print()
print("tests..")
testFuncs((isInt_try, isInt_str, isInt_re, isInt_re2, check_int))
print()
print("timings..")
print("isInt_try: %6.4f" % timeFunc(isInt_try, 10000))
print("isInt_str: %6.4f" % timeFunc(isInt_str, 10000))
print("isInt_re: %6.4f" % timeFunc(isInt_re, 10000))
print("isInt_re2: %6.4f" % timeFunc(isInt_re2, 10000))
print("check_int: %6.4f" % timeFunc(check_int, 10000))
Here are the performance comparison results:
timings..
isInt_try: 0.6426
isInt_str: 0.7382
isInt_re: 1.1156
isInt_re2: 0.5344
check_int: 0.3452
A C method could scan it Once Through, and be done. A C method that scans the string once through would be the Right Thing to do, I think.
EDIT:
I've updated the code above to work in Python 3.5, and to include the check_int function from the currently most voted up answer, and to use the current most popular regex that I can find for testing for integer-hood. This regex rejects strings like 'abc 123'. I've added 'abc 123' as a test value.
It is Very Interesting to me to note, at this point, that NONE of the functions tested, including the try method, the popular check_int function, and the most popular regex for testing for integer-hood, return the correct answers for all of the test values (well, depending on what you think the correct answers are; see the test results below).
The built-in int() function silently truncates the fractional part of a floating point number and returns the integer part before the decimal, unless the floating point number is first converted to a string.
The check_int() function returns false for values like 0.0 and 1.0 (which technically are integers) and returns true for values like '06'.
Here are the current (Python 3.5) test results:
isInt_try | isInt_str | isInt_re | isInt_re2 | check_int |
0 True | True | True | True | True |
1 True | True | True | True | True |
-1 True | True | True | True | True |
1.0 True | True | False | False | False |
-1.0 True | True | False | False | False |
'0' True | True | True | True | True |
'0.' False | True | False | False | False |
'0.0' False | True | False | False | False |
'1' True | True | True | True | True |
'-1' True | True | True | True | True |
'+1' True | True | True | True | True |
'1.0' False | True | False | False | False |
'-1.0' False | True | False | False | False |
'+1.0' False | True | False | False | False |
'06' True | True | False | False | True |
'abc 123' False | False | False | False | False |
1.1 True | False | False | False | False |
-1.1 True | False | False | False | False |
'1.1' False | False | False | False | False |
'-1.1' False | False | False | False | False |
'+1.1' False | False | False | False | False |
'1.1.1' False | False | False | False | False |
'1.1.0' False | False | False | False | False |
'1.0.1' False | False | False | False | False |
'1.0.0' False | False | False | False | False |
'1.0.' False | False | False | False | False |
'1..0' False | False | False | False | False |
'1..' False | False | False | False | False |
'0.0.' False | False | False | False | False |
'0..0' False | False | False | False | False |
'0..' False | False | False | False | False |
'one' False | False | False | False | False |
<obj..> False | False | False | False | False |
(1, 2, 3) False | False | False | False | False |
[1, 2, 3] False | False | False | False | False |
{'one': 'two'} False | False | False | False | False |
' 0 ' True | True | True | True | False |
' 0.' False | True | False | False | False |
' .0' False | False | False | False | False |
'.01 ' False | False | False | False | False |
Just now I tried adding this function:
def isInt_float(s):
try:
return float(str(s)).is_integer()
except:
return False
It performs almost as well as check_int (0.3486) and it returns true for values like 1.0 and 0.0 and +1.0 and 0. and .0 and so on. But it also returns true for '06', so. Pick your poison, I guess.
May be i did not fully understand the problem, but, centering all view inside a ConstraintLayout seems very simple. This is what I used:
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center">
Last two lines did the trick!
Fetch does not use cookie by default. To enable cookie, do this:
fetch(url, {
credentials: "same-origin"
}).then(...).catch(...);
If you are using PHP >= 7.2 consider using inbuilt sodium core extension for encrption.
Find more information here - http://php.net/manual/en/intro.sodium.php
.
In your test code your are trying to pass App
to the spyOn function, but spyOn will only work with objects, not classes. Generally you need to use one of two approaches here:
1) Where the click handler calls a function passed as a prop, e.g.
class App extends Component {
myClickFunc = () => {
console.log('clickity clickcty');
this.props.someCallback();
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now pass in a spy function as a prop to the component, and assert that it is called:
describe('my sweet test', () => {
it('clicks it', () => {
const spy = jest.fn();
const app = shallow(<App someCallback={spy} />)
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
2) Where the click handler sets some state on the component, e.g.
class App extends Component {
state = {
aProperty: 'first'
}
myClickFunc = () => {
console.log('clickity clickcty');
this.setState({
aProperty: 'second'
});
}
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro" onClick={this.myClickFunc}>
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
You can now make assertions about the state of the component, i.e.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const p = app.find('.App-intro')
p.simulate('click')
expect(app.state('aProperty')).toEqual('second');
})
})
A more concise--but not necessarily faster--method is to use DataFrame.isin()
and DataFrame.any()
In [27]: n = 10
In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))
In [29]: df
Out[29]:
a b
0 0 0
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
7 3 0
8 1 1
9 2 2
[10 rows x 2 columns]
In [30]: df.isin([1, 2])
Out[30]:
a b
0 False False
1 True True
2 True True
3 True False
4 True False
5 False True
6 True True
7 False False
8 True True
9 True True
[10 rows x 2 columns]
In [31]: df.isin([1, 2]).any(1)
Out[31]:
0 False
1 True
2 True
3 True
4 True
5 True
6 True
7 False
8 True
9 True
dtype: bool
In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
a b
1 1 1
2 1 1
3 2 3
4 2 3
5 0 2
6 1 2
8 1 1
9 2 2
[8 rows x 2 columns]
just found out, what was the problem in my case (provider strato): I had the same problem with output "shell request failed on channel 0" in the end.
I have to use the master password with the web-domain name as login. (In German www.wunschname.de, where wunschname is your web-address.)
A ssh login with sftp-user names and the corresponding passwords is without success. (Although scp and sftp works with these sftp users!)
In Mvc 4 you can use AcceptVerbsAttribute, I think this is a very clean solution
[AcceptVerbs(WebRequestMethods.Http.Get, WebRequestMethods.Http.Post)]
public IHttpActionResult Login()
{
// Login logic
}
Here are my steps for the task:
I am trying to write a sample program to do AES encryption using Openssl.
This answer is kind of popular, so I'm going to offer something more up-to-date since OpenSSL added some modes of operation that will probably help you.
First, don't use AES_encrypt
and AES_decrypt
. They are low level and harder to use. Additionally, it's a software-only routine, and it will never use hardware acceleration, like AES-NI. Finally, its subject to endianess issues on some obscure platforms.
Instead, use the EVP_*
interfaces. The EVP_*
functions use hardware acceleration, like AES-NI, if available. And it does not suffer endianess issues on obscure platforms.
Second, you can use a mode like CBC, but the ciphertext will lack integrity and authenticity assurances. So you usually want a mode like EAX, CCM, or GCM. (Or you manually have to apply a HMAC after the encryption under a separate key.)
Third, OpenSSL has a wiki page that will probably interest you: EVP Authenticated Encryption and Decryption. It uses GCM mode.
Finally, here's the program to encrypt using AES/GCM. The OpenSSL wiki example is based on it.
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <string.h>
int main(int arc, char *argv[])
{
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Set up the key and iv. Do I need to say to not hard code these in a real application? :-) */
/* A 256 bit key */
static const unsigned char key[] = "01234567890123456789012345678901";
/* A 128 bit IV */
static const unsigned char iv[] = "0123456789012345";
/* Message to be encrypted */
unsigned char plaintext[] = "The quick brown fox jumps over the lazy dog";
/* Some additional data to be authenticated */
static const unsigned char aad[] = "Some AAD data";
/* Buffer for ciphertext. Ensure the buffer is long enough for the
* ciphertext which may be longer than the plaintext, dependant on the
* algorithm and mode
*/
unsigned char ciphertext[128];
/* Buffer for the decrypted text */
unsigned char decryptedtext[128];
/* Buffer for the tag */
unsigned char tag[16];
int decryptedtext_len = 0, ciphertext_len = 0;
/* Encrypt the plaintext */
ciphertext_len = encrypt(plaintext, strlen(plaintext), aad, strlen(aad), key, iv, ciphertext, tag);
/* Do something useful with the ciphertext here */
printf("Ciphertext is:\n");
BIO_dump_fp(stdout, ciphertext, ciphertext_len);
printf("Tag is:\n");
BIO_dump_fp(stdout, tag, 14);
/* Mess with stuff */
/* ciphertext[0] ^= 1; */
/* tag[0] ^= 1; */
/* Decrypt the ciphertext */
decryptedtext_len = decrypt(ciphertext, ciphertext_len, aad, strlen(aad), tag, key, iv, decryptedtext);
if(decryptedtext_len < 0)
{
/* Verify error */
printf("Decrypted text failed to verify\n");
}
else
{
/* Add a NULL terminator. We are expecting printable text */
decryptedtext[decryptedtext_len] = '\0';
/* Show the decrypted text */
printf("Decrypted text is:\n");
printf("%s\n", decryptedtext);
}
/* Remove error strings */
ERR_free_strings();
return 0;
}
void handleErrors(void)
{
unsigned long errCode;
printf("An error occurred\n");
while(errCode = ERR_get_error())
{
char *err = ERR_error_string(errCode, NULL);
printf("%s\n", err);
}
abort();
}
int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *aad,
int aad_len, unsigned char *key, unsigned char *iv,
unsigned char *ciphertext, unsigned char *tag)
{
EVP_CIPHER_CTX *ctx = NULL;
int len = 0, ciphertext_len = 0;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the encryption operation. */
if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
handleErrors();
/* Set IV length if default 12 bytes (96 bits) is not appropriate */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
handleErrors();
/* Initialise key and IV */
if(1 != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if(aad && aad_len > 0)
{
if(1 != EVP_EncryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
}
/* Provide the message to be encrypted, and obtain the encrypted output.
* EVP_EncryptUpdate can be called multiple times if necessary
*/
if(plaintext)
{
if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
handleErrors();
ciphertext_len = len;
}
/* Finalise the encryption. Normally ciphertext bytes may be written at
* this stage, but this does not occur in GCM mode
*/
if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
ciphertext_len += len;
/* Get the tag */
if(1 != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, tag))
handleErrors();
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
return ciphertext_len;
}
int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *aad,
int aad_len, unsigned char *tag, unsigned char *key, unsigned char *iv,
unsigned char *plaintext)
{
EVP_CIPHER_CTX *ctx = NULL;
int len = 0, plaintext_len = 0, ret;
/* Create and initialise the context */
if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
/* Initialise the decryption operation. */
if(!EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL))
handleErrors();
/* Set IV length. Not necessary if this is 12 bytes (96 bits) */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 16, NULL))
handleErrors();
/* Initialise key and IV */
if(!EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv)) handleErrors();
/* Provide any AAD data. This can be called zero or more times as
* required
*/
if(aad && aad_len > 0)
{
if(!EVP_DecryptUpdate(ctx, NULL, &len, aad, aad_len))
handleErrors();
}
/* Provide the message to be decrypted, and obtain the plaintext output.
* EVP_DecryptUpdate can be called multiple times if necessary
*/
if(ciphertext)
{
if(!EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
handleErrors();
plaintext_len = len;
}
/* Set expected tag value. Works in OpenSSL 1.0.1d and later */
if(!EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tag))
handleErrors();
/* Finalise the decryption. A positive return value indicates success,
* anything else is a failure - the plaintext is not trustworthy.
*/
ret = EVP_DecryptFinal_ex(ctx, plaintext + len, &len);
/* Clean up */
EVP_CIPHER_CTX_free(ctx);
if(ret > 0)
{
/* Success */
plaintext_len += len;
return plaintext_len;
}
else
{
/* Verify failed */
return -1;
}
}
In bash you simply can ${var/find/replace}
PATH=${PATH/%:\/home\/wrong\/dir\//}
Or in this case (as the replace bit is empty) just:
PATH=${PATH%:\/home\/wrong\/dir\/}
I came here first but went else ware as I thought there would be a parameter expansion to do this. Easier than sed!.
How to replace placeholder character or word in variable with value from another variable in Bash?
Piggy backing off of user1927494's answer, In case you want to run a single test before all others, you can do this:
@Test()
public void testOrderDoesntMatter_1() {
}
@Test(priority=-1)
public void testToRunFirst() {
}
@Test()
public void testOrderDoesntMatter_2() {
}
btn.titleLabel?.font = .systemFont(ofSize: 12)
You could do something like this:
public System.Collections.IEnumerable GetDogsWithBreedNames()
{
var db = new DogDataContext(ConnectString);
var result = from d in db.Dogs
join b in db.Breeds on d.BreedId equals b.BreedId
select new
{
Name = d.Name,
BreedName = b.BreedName
};
return result.ToList();
}
For me I put my dependencies in the wrong spot.
buildscript {
dependencies {
//Don't put dependencies here.
}
}
dependencies {
//Put them here
}
Are you using standards mode? This solution depends on it I think.
If you're trying to make 2 columns you could do something like this:
<div id="outer">
<div id="left">
sidebar
</div>
<div id="main">
lorem ispsum etc...
</div>
</div>
Then use CSS to style it:
div#outer
{
width:100%;
height: 500px;
}
div#left
{
width: 100px;
height: 100%;
float:left;
background: green;
}
div#main
{
width: auto;
margin-left: 100px; /* same as div#left width */
height: 100%;
background:red;
}
If you don't want 2 columns you can probably remove <div id="left">
As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.
It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.
Here are some flag values to add some additional info on how to allow more memory when you start up your node server.
1GB - 8GB
#increase to 1gb
node --max-old-space-size=1024 index.js
#increase to 2gb
node --max-old-space-size=2048 index.js
#increase to 3gb
node --max-old-space-size=3072 index.js
#increase to 4gb
node --max-old-space-size=4096 index.js
#increase to 5gb
node --max-old-space-size=5120 index.js
#increase to 6gb
node --max-old-space-size=6144 index.js
#increase to 7gb
node --max-old-space-size=7168 index.js
#increase to 8gb
node --max-old-space-size=8192 index.js
I resolved my problem with this one liner
npm cache clean --force
It works like a charm all the time. I love one liners. Note: since its a clean install, I had no concerns emptying npm cache.
Had the same errors, my story was following:
after bad merging (via git) one of my .csproj files had duplicated compile
entries like:
<Compile Include="Clients\Tree.cs" />
<Compile Include="Clients\Car.cs" />
<Compile Include="Clients\Tree.cs" /> //it's a duplicate
If you have a big solution and more than 300 messages in the errors window it's hard to detect this issue. So I've opened damaged .csproj file via notepad and removed duplicated entries. Worked in my case.
More simplified:
resultList.Remove(resultList.Single(x => x.Id == 2));
there is no needing to create a new var object.
process.cwd()
returns the current working directory,
i.e. the directory from which you invoked the node
command.
__dirname
returns the directory name of the directory containing the JavaScript source code file
If you have wget installed, you can use parallel_sync.
pip install parallel_sync
from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)
Doc: https://pythonhosted.org/parallel_sync/pages/examples.html
This is pretty powerful. It can download files in parallel, retry upon failure , and it can even download files on a remote machine.
I was having trouble getting this to work alongside background colours and accessory views in the cell. Ended up having to:
1) Set the cells background view property with a UIView set with a background colour.
let view = UIView()
view.backgroundColor = UIColor.white
self.backgroundView = view
2) Re-position this view in layoutSubviews to add the idea of spacing
override func layoutSubviews() {
super.layoutSubviews()
backgroundView?.frame = backgroundView?.frame.inset(by: UIEdgeInsets(top: 2, left: 0, bottom: 0, right: 0)) ?? CGRect.zero
}
It is because it's being converted from a binary representation. Just because it has printed all those decimal digits doesn't mean it can represent all decimal values to that precision. Take, for example, this in Python:
>>> 0.14285714285714285
0.14285714285714285
>>> 0.14285714285714286
0.14285714285714285
Notice how I changed the last digit, but it printed out the same number anyway.
ps -fC PROCESSNAME
ps and grep is a dangerous combination -- grep tries to match everything on each line (thus the all too common: grep -v grep hack). ps -C doesn't use grep, it uses the process table for an exact match. Thus, you'll get an accurate list with: ps -fC sh rather finding every process with sh somewhere on the line.
If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON
template< typename TContainer >
static bool EraseFromUnorderedByIndex( TContainer& inContainer, size_t inIndex )
{
if ( inIndex < inContainer.size() )
{
if ( inIndex != inContainer.size() - 1 )
inContainer[inIndex] = inContainer.back();
inContainer.pop_back();
return true;
}
return false;
}
Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.
In my case, this error comes from my trial to remove dependencies to MSVC-version dependent runtime library DLL (msvcr10.dll or so) and/or remove static runtime library too, to remove excess fat from my executables.
So I use /NODEFAULTLIB linker switch, my self-made "msvcrt-light.lib" (google for it when you need), and mainCRTStartup()
/ WinMainCRTStartup()
entries.
It is IMHO since Visual Studio 2015, so I stuck to older compilers.
However, defining symbol _NO_CRT_STDIO_INLINE removes all hassle, and a simple "Hello World" application is again 3 KB small and doesn't depend to unusual DLLs. Tested in Visual Studio 2017.
I think this is what you need:
At first you need to install sshpass
on your machine.
then you can write your own script:
while read pass port user ip; do
sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
COMMAND 1
.
.
.
COMMAND n
ENDSSH1
done <<____HERE
PASS PORT USER IP
. . . .
. . . .
. . . .
PASS PORT USER IP
____HERE
try this it work out for me perfectly go to project and right click on your java file at the right corner, go to properties, go to run, go to browse, and then select Main class. now you can run your program again.
The InterruptedException
is usually thrown when a sleep is interrupted.
std::move
?A: std::move()
is a function from the C++ Standard Library for casting to a rvalue reference.
Simplisticly std::move(t)
is equivalent to:
static_cast<T&&>(t);
An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.
int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated
An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:
template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
return a;
}
As you can see, std::move
returns T&&
no matter if called with a value (T
), reference type (T&
), or rvalue reference (T&&
).
A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.
foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)
int a = 3 * 5;
foo(a); // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`
What it does not do:
A: You should use std::move
if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).
This begs the following follow-up questions for me:
What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.
What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.
Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.
In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.
What you are trying to achieve is equivalent to
interface Event {
name: string;
dateCreated: string;
type: string;
}
interface UserEvent extends Event {
UserId: string;
}
The way you defined the types does not allow for specifying inheritance, however you can achieve something similar using intersection types, as artem pointed out.
Yes you can, for example:
[textField setKeyboardType:UIKeyboardTypeNumberPad];
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
Try this:
import re
mystr = 'This is a string, with words!'
wordList = re.sub("[^\w]", " ", mystr).split()
How it works:
From the docs :
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function.
so in our case :
pattern is any non-alphanumeric character.
[\w] means any alphanumeric character and is equal to the character set [a-zA-Z0-9_]
a to z, A to Z , 0 to 9 and underscore.
so we match any non-alphanumeric character and replace it with a space .
and then we split() it which splits string by space and converts it to a list
so 'hello-world'
becomes 'hello world'
with re.sub
and then ['hello' , 'world']
after split()
let me know if any doubts come up.
Slug is a URL friendly short label for specific content. It only contain Letters, Numbers, Underscores or Hyphens. Slugs are commonly save with the respective content and it pass as a URL string.
Slug can create using SlugField
Ex:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
If you want to use title as slug, django has a simple function called slugify
from django.template.defaultfilters import slugify
class Article(models.Model):
title = models.CharField(max_length=100)
def slug(self):
return slugify(self.title)
If it needs uniqueness, add unique=True
in slug field.
for instance, from the previous example:
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
Are you lazy to do slug process ? don't worry, this plugin will help you. django-autoslug
Your code seems right, check if you have fopen wrappers enabled (allow_url_fopen = On
on php.ini)
Also, as mentioned by other answers, you should provide a properly encoded URI or encode it using urlencode() function. You should also check if there is any error fetching the XML string and if there is any parsing error, which you can output using libxml_get_errors() as follows:
<?php
if (($response_xml_data = file_get_contents($map_url))===false){
echo "Error fetching XML\n";
} else {
libxml_use_internal_errors(true);
$data = simplexml_load_string($response_xml_data);
if (!$data) {
echo "Error loading XML\n";
foreach(libxml_get_errors() as $error) {
echo "\t", $error->message;
}
} else {
print_r($data);
}
}
?>
If the problem is you can't fetch the XML code maybe it's because you need to include some custom headers in your request, check how to use stream_context_create() to create a custom stream context for use when calling file_get_contents()
on example 4 at http://php.net/manual/en/function.file-get-contents.php
1· Do I need these DLL's?
It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.
- Where can I get them?
most dlls can be found at https://www.dll-files.com
I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll
For me leshims.dll
can be placed at C:\Windows\System32\
. Context: windows 7 64bit.
If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.
$("span").toggle();
Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
Markushi wrote a circle button widget with amazing effects. Click here!
You have three options:
@Transient
method@PostLoad
entity listener@Formula
annotationWhile Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:
@Column(name = "price")
private Double price;
@Column(name = "tax_percentage")
private Double taxes;
@Transient
private Double priceWithTaxes;
@PostLoad
private void onLoad() {
this.priceWithTaxes = price * taxes;
}
So, you can use the Hibernate @Formula
like this:
@Formula("""
round(
(interestRate::numeric / 100) *
cents *
date_part('month', age(now(), createdOn)
)
/ 12)
/ 100::numeric
""")
private double interestDollars;
PHP Manual says:
gethostname (PHP >= 5.3.0) gethostname — Gets the host name
Look:
<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>
http://php.net/manual/en/function.gethostname.php
Enjoy
Add a toolbar to your xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment title"/>
</android.support.v7.widget.Toolbar>
Then inside your onCreateView method in the Fragment:
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
Some of the other answers are useless because as soon as you re-import the IntelliJ IDEA project from the maven project, all changes will be lost.
The building of the jar needs to be triggered by a run/debug configuration, not by the project settings.
Jetbrains has a nice description of how you can accomplish this here:
https://www.jetbrains.com/help/idea/maven.html
Scroll down to the section called "Configuring triggers for Maven goals".
(The only disadvantage of their description is that their screenshots are in the default black-on-white color scheme instead of the super-awesome darcula theme. Ugh!)
So, basically, what you do is that you open the "Maven Projects" panel, you find the project of interest, (in your case, the project that builds your jar,) underneath it you find the maven goal that you want to execute, (usually the "package" goal creates jars,) you open up the context menu on it, (right-click on a Windows machine,) and there will be an "Execute before Run/Debug..." option that you can select and it will take you by the hand from there. Really easy.
To achieve that, I suggest you to use AngularJS Environment Plugin: https://www.npmjs.com/package/angular-environment
Here's an example:
angular.module('yourApp', ['environment']).
config(function(envServiceProvider) {
// set the domains and variables for each environment
envServiceProvider.config({
domains: {
development: ['localhost', 'dev.local'],
production: ['acme.com', 'acme.net', 'acme.org']
// anotherStage: ['domain1', 'domain2'],
// anotherStage: ['domain1', 'domain2']
},
vars: {
development: {
apiUrl: '//localhost/api',
staticUrl: '//localhost/static'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
},
production: {
apiUrl: '//api.acme.com/v2',
staticUrl: '//static.acme.com'
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
}
// anotherStage: {
// customVar: 'lorem',
// customVar: 'ipsum'
// }
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
});
And then, you can call the variables from your controllers such as this:
envService.read('apiUrl');
Hope it helps.
When choosing the "best" approach, a more important consideration than speed might be the maintainability and correctness of your code. If so, SQL_CALC_FOUND_ROWS is preferable because you only need to maintain a single query. Using a single query completely precludes the possibility of a subtle difference between the main and count queries, which may lead to an inaccurate COUNT.
File names are case sensitive - please check your file name. it should be in same case in view folder
Also, if nothing else from given solutions doesn't work, check if you imported "FormsModule" inside of "AppModule", that was a key for me.
since your local username on your laptop frequently does not match the server's username, you can set this in the ~/.subversion/servers file
Add the server to the [groups] section with a name, then add a section with that name and provide a username.
for example, for a login like [email protected]
this is what your config would look like:
[groups]
exampleserver = svn.example.com
[exampleserver]
username = me
Referring to SimpleDataFormat JavaDoc:
Letter | Date or Time Component | Presentation | Examples
---------------------------------------------------------
H | Hour in day (0-23) | Number | 0
h | Hour in am/pm (1-12) | Number | 12
if "ABCD" in "xxxxABCDyyyy":
# whatever
In my case, I use this Java class:
private String getCurrentProcessName() {
String processName = "";
int pid = android.os.Process.myPid();
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
if (processInfo.pid == pid) {
processName = processInfo.processName;
break;
}
}
return processName;
}
We create a validation set to
Why validation set used:
Here is a pure css version
.example-print {_x000D_
display: none;_x000D_
}_x000D_
@media print {_x000D_
.example-screen {_x000D_
display: none;_x000D_
}_x000D_
.example-print {_x000D_
display: block;_x000D_
}_x000D_
}
_x000D_
<div class="example-screen">You only see me in the browser</div>_x000D_
_x000D_
<div class="example-print">You only see me in the print</div>
_x000D_
Just to add a little further documentation to this page - I have been struggling with this problem for a while.
As said above, the easiest way to get the URL is via window.location.href
.
we can then extract parts of the URL through vanilla Javascript by using let urlElements = window.location.href.split('/')
We would then console.log(urlElements)
to see the Array of elements produced by calling .split() on the URL.
Once you have found which index in the array you want to access, you can then assigned this to a variable
let urlElelement = (urlElements[0])
And now you can use the value of urlElement, which will be the specific part of your URL, wherever you want.
There are quite a few projects that have settled on the Generic Graphics Toolkit for this. The GMTL in there is nice - it's quite small, very functional, and been used widely enough to be very reliable. OpenSG, VRJuggler, and other projects have all switched to using this instead of their own hand-rolled vertor/matrix math.
I've found it quite nice - it does everything via templates, so it's very flexible, and very fast.
Edit:
After the comments discussion, and edits, I thought I'd throw out some more information about the benefits and downsides to specific implementations, and why you might choose one over the other, given your situation.
GMTL -
Benefits: Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use.
Downsides: API is very focused specifically on rendering and graphics. Doesn't include general purpose (NxM) matrices, matrix decomposition and solving, etc, since these are outside the realm of traditional graphics/geometry applications.
Eigen -
Benefits: Clean API, fairly easy to use. Includes a Geometry module with quaternions and geometric transforms. Low memory overhead. Full, highly performant solving of large NxN matrices and other general purpose mathematical routines.
Downsides: May be a bit larger scope than you are wanting (?). Fewer geometric/rendering specific routines when compared to GMTL (ie: Euler angle definitions, etc).
IMSL -
Benefits: Very complete numeric library. Very, very fast (supposedly the fastest solver). By far the largest, most complete mathematical API. Commercially supported, mature, and stable.
Downsides: Cost - not inexpensive. Very few geometric/rendering specific methods, so you'll need to roll your own on top of their linear algebra classes.
NT2 -
Benefits: Provides syntax that is more familiar if you're used to MATLAB. Provides full decomposition and solving for large matrices, etc.
Downsides: Mathematical, not rendering focused. Probably not as performant as Eigen.
LAPACK -
Benefits: Very stable, proven algorithms. Been around for a long time. Complete matrix solving, etc. Many options for obscure mathematics.
Downsides: Not as highly performant in some cases. Ported from Fortran, with odd API for usage.
Personally, for me, it comes down to a single question - how are you planning to use this. If you're focus is just on rendering and graphics, I like Generic Graphics Toolkit, since it performs well, and supports many useful rendering operations out of the box without having to implement your own. If you need general purpose matrix solving (ie: SVD or LU decomposition of large matrices), I'd go with Eigen, since it handles that, provides some geometric operations, and is very performant with large matrix solutions. You may need to write more of your own graphics/geometric operations (on top of their matrices/vectors), but that's not horrible.
!= is OK to compare two variables. It doesn't work, though, with multiple comparisons.
Authentication is managed at a database level. When you try to connect to the system using a database, mongo actually checks for the credentials you provide in the collection <database>.system.users
. So, basically when you are trying to connect to "test", it looks for the credentials in test.system.users
and returns an error because it cannot find them (as they are stored in admin.system.users
). Having the right to read and write from all db doesn't mean you can directly connect to them.
You have to connect to the database holding the credentials first. Try:
mongo admin -u admin -p SECRETPASSWORD
For more info, check this http://docs.mongodb.org/manual/reference/privilege-documents/
This is not an exact answer, but if you're looking to uninstall the app because you have an updated .apk to install, you can try this:
adb install -r yourapp.apk
The -r
option tells adb to reinstall the app
This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.
You can fork this and use it as a great starting point for your specific expectations:
Here are two screenshots I took for you... wide and thin:
.keypress(function(e)
{
var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];
if (!($.inArray(e.which, key_codes) >= 0)) {
e.preventDefault();
}
});
You need Backspace and Delete keys too ;)
You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:
1.) change type of ID to int
instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea
First option requires to change every table that has a reference to this table, BUT it's worth it.
The second most upvoted answer here is on the closest track possible to a one-liner jQuery method of the intended behavior the OP wants, but they stumbled at the end of their code, and it has a flaw. If your item to be removed isn't actually in the array, the last item will get removed.
A few have noticed this issue, and some have offered ways to loop through to guard against this. I offer the shortest, cleanest method I could find, and I have commented under their answer for the way to fix their code according to this method.
var x = [1, 2, "bye", 3, 4];
var y = [1, 2, 3, 4];
var removeItem = "bye";
// Removing an item that exists in array
x.splice( $.inArray(removeItem,x), $.inArray(removeItem,x) ); // This is the one-liner used
// Removing an item that DOESN'T exist in array
y.splice( $.inArray(removeItem,y), $.inArray(removeItem,y) ); // Same usage, different array
// OUTPUT -- both cases are expected to be [1,2,3,4]
alert(x + '\n' + y);
array x will remove the element "bye" easily, and array y will be untouched.
The use of the argument $.inArray(removeItem,array)
as a second argument actually ends up being the length to splice. Since the item was not found, this evaluates to array.splice(-1,-1);
, which will just result in nothing being spliced... all without having to write a loop for this.
innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.
I encountered same problem and took 2 hours to figure it out.
If you're a homebrew user instead of macports, homebrew has an ant recipe.
brew install ant
The asynchronous solution from Edward:
is simple and might just work for you.
I would also like to give a more advanced version which has these advantages:
This might be in particular useful in large software projects where you have many task executed repetitively in your process and you care about resource usage (threads) and also startup overhead.
Idea: Have one service thread which processes all registered timed tasks. Use boost io_service for that.
Code similar to: http://www.boost.org/doc/libs/1_65_1/doc/html/boost_asio/tutorial/tuttimer2/src.html
#include <cstdio>
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
int main()
{
boost::asio::io_service io;
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
t.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
boost::asio::deadline_timer t2(io, boost::posix_time::seconds(1));
t2.async_wait([](const boost::system::error_code& /*e*/){
printf("Printed after 1s\n"); });
// both prints happen at the same time,
// but only a single thread is used to handle both timed tasks
// - namely the main thread calling io.run();
io.run();
return 0;
}
The three dots (...)
are called the spread operator, and this is conceptually similar to the ES6 array spread operator, JSX
taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX
Spread properties in object initializers copies own enumerable properties from a provided object onto the newly created object.
let n = { x, y, ...z }; n; // { x: 1, y: 2, a: 3, b: 4 }
Reference:
1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties
It means that the object you pass in the request (I guess it is pagedoc
) has a circular reference, something like:
var a = {};
a.b = a;
JSON.stringify
cannot convert structures like this.
N.B.: This would be the case with DOM nodes, which have circular references, even if they are not attached to the DOM tree. Each node has an ownerDocument
which refers to document
in most cases. document
has a reference to the DOM tree at least through document.body
and document.body.ownerDocument
refers back to document
again, which is only one of multiple circular references in the DOM tree.
You can specify the color
option as a list directly to the plot
function.
from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np # I find np.random.randint to be better
# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)
# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))
# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)
To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.
my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.
The last example yields the follow simple gradient of colors for me:
I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.
In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.
This question has been an active area of research in the last years. The main idea is to do a preprocessing on the graph once, to speed up all following queries. With this additional information itineraries can be computed very fast. Still, Dijkstra's Algorithm is the basis for all optimisations.
Arachnid described the usage of bidirectional search and edge pruning based on hierarchical information. These speedup techniques work quite well, but the most recent algorithms outperform these techniques by all means. With current algorithms a shortest paths can be computed in considerable less time than one millisecond on a continental road network. A fast implementation of the unmodified algorithm of Dijkstra needs about 10 seconds.
The article Engineering Fast Route Planning Algorithms gives an overview of the progress of research in that field. See the references of that paper for further information.
The fastest known algorithms do not use information about the hierarchical status of the road in the data, i.e. if it is a highway or a local road. Instead, they compute in a preprocessing step an own hierarchy that optimised to speed up route planning. This precomputation can then be used to prune the search: Far away from start and destination slow roads need not be considered during Dijkstra's Algorithm. The benefits are very good performance and a correctness guarantee for the result.
The first optimised route planning algorithms dealt only with static road networks, that means an edge in the graph has a fixed cost value. This not true in practice, since we want to take dynamic information like traffic jams or vehicle dependent restrictrions into account. Latest algorithms can also deal with such issues, but there are still problems to solve and the research is going on.
If you need the shortest path distances to compute a solution for the TSP, then you are probably interested in matrices that contain all distances between your sources and destinations. For this you could consider Computing Many-to-Many Shortest Paths Using Highway Hierarchies. Note, that this has been improved by newer approaches in the last 2 years.
Shaun F's answer will not work if Schema doesn't exist in the DB. If anyone is looking for way to create schema then just execute following script to create schema.
create schema [schema_name]
CREATE TABLE [schema_name].[table_name](
...
) ON [PRIMARY]
While adding new table, go to table design mode and press F4
to open property Window and select the schema from dropdown. Default is dbo
.
You can also change the schema of the current Table using Property window.
Refer:
I would use filter
:
str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)
Python 3 returns an iterator from filter
, so should be wrapped in a call to list()
str_list = list(filter(None, str_list))
You don't need order by in your sub query. Move it out into the main query, and include the column you want to order by in the subquery.
however, your query is just returning a count, so I don't see the point of the order by.
Let's say there is an administrator dashboard where users are listed with their id printed as a data attribute so it can be retrieved at some point via JavaScript.
An update could be executed this way …
class UserRepository extends \Doctrine\ORM\EntityRepository
{
public function updateUserStatus($userId, $newStatus)
{
return $this->createQueryBuilder('u')
->update()
->set('u.isActive', '?1')
->setParameter(1, $qb->expr()->literal($newStatus))
->where('u.id = ?2')
->setParameter(2, $qb->expr()->literal($userId))
->getQuery()
->getSingleScalarResult()
;
}
AJAX action handling:
# Post datas may be:
# handled with a specific custom formType — OR — retrieved from request object
$userId = (int)$request->request->get('userId');
$newStatus = (int)$request->request->get('newStatus');
$em = $this->getDoctrine()->getManager();
$r = $em->getRepository('NAMESPACE\User')
->updateUserStatus($userId, $newStatus);
if ( !empty($r) ){
# Row updated
}
Working example using Doctrine 2.5 (on top of Symfony3).
Querying user_tables
and dba_tables
didn't work.
This one did:
select table_name from all_tables
Lexical scope means that in a nested group of functions, the inner functions have access to the variables and other resources of their parent scope. This means that the child functions are lexically bound to the execution context of their parents. Lexical scope is sometimes also referred to as static scope.
function grandfather() {
var name = 'Hammad';
// 'likes' is not accessible here
function parent() {
// 'name' is accessible here
// 'likes' is not accessible here
function child() {
// Innermost level of the scope chain
// 'name' is also accessible here
var likes = 'Coding';
}
}
}
The thing you will notice about lexical scope is that it works forward, meaning name can be accessed by its children's execution contexts. But it doesn't work backward to its parents, meaning that the variable likes
cannot be accessed by its parents.
This also tells us that variables having the same name in different execution contexts gain precedence from top to bottom of the execution stack. A variable, having a name similar to another variable, in the innermost function (topmost context of the execution stack) will have higher precedence.
Here's a technique that allows you to center ANY content both vertically and horizontally!
Basically, you just need a two containers and make sure your elements meet the following criteria.
display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
If you use this technique, just add your image (along with any other content you want to go with it) to the content box.
body {_x000D_
margin : 0;_x000D_
}_x000D_
_x000D_
.outer-container {_x000D_
position : absolute;_x000D_
display: table;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
background: #ccc;_x000D_
}_x000D_
_x000D_
.inner-container {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.centered-content {_x000D_
display: inline-block;_x000D_
background: #fff;_x000D_
padding : 12px;_x000D_
border : 1px solid #000;_x000D_
}_x000D_
_x000D_
img {_x000D_
max-width : 120px;_x000D_
}
_x000D_
<div class="outer-container">_x000D_
<div class="inner-container">_x000D_
<div class="centered-content">_x000D_
<img src="https://i.stack.imgur.com/mRsBv.png" />_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
See also this Fiddle!
<script>
function check(){
return false;
}
</script>
<form name="form1" method="post" onsubmit="return check();" action="target">
<input type="text" />
<input type="submit" value="enviar" />
</form>
A minor addition to the answers already posted: object files not compiled to be position independent are relocatable; they contain relocation table entries.
These entries allow the loader (that bit of code that loads a program into memory) to rewrite the absolute addresses to adjust for the actual load address in the virtual address space.
An operating system will try to share a single copy of a "shared object library" loaded into memory with all the programs that are linked to that same shared object library.
Since the code address space (unlike sections of the data space) need not be contiguous, and because most programs that link to a specific library have a fairly fixed library dependency tree, this succeeds most of the time. In those rare cases where there is a discrepancy, yes, it may be necessary to have two or more copies of a shared object library in memory.
Obviously, any attempt to randomize the load address of a library between programs and/or program instances (so as to reduce the possibility of creating an exploitable pattern) will make such cases common, not rare, so where a system has enabled this capability, one should make every attempt to compile all shared object libraries to be position independent.
Since calls into these libraries from the body of the main program will also be made relocatable, this makes it much less likely that a shared library will have to be copied.
These all do {1..8}
and should all be POSIX. They also will not break if you
put a conditional continue
in the loop. The canonical way:
f=
while [ $((f+=1)) -le 8 ]
do
echo $f
done
Another way:
g=
while
g=${g}1
[ ${#g} -le 8 ]
do
echo ${#g}
done
and another:
set --
while
set $* .
[ ${#} -le 8 ]
do
echo ${#}
done
If I'm not mistaken, the question requires "contains number", not "is number". So:
function hasNumber(myString) {
return /\d/.test(myString);
}
some great answers here, but they do not tackle how to use super()
in the case where different classes in the hierarchy have different signatures ... especially in the case of __init__
to answer that part and to be able to effectively use super()
i'd suggest reading my answer super() and changing the signature of cooperative methods.
here's just the solution to this scenario:
- the top-level classes in your hierarchy must inherit from a custom class like
SuperObject
:- if classes can take differing arguments, always pass all arguments you received on to the super function as keyword arguments, and, always accept
**kwargs
.
class SuperObject:
def __init__(self, **kwargs):
print('SuperObject')
mro = type(self).__mro__
assert mro[-1] is object
if mro[-2] is not SuperObject:
raise TypeError(
'all top-level classes in this hierarchy must inherit from SuperObject',
'the last class in the MRO should be SuperObject',
f'mro={[cls.__name__ for cls in mro]}'
)
# super().__init__ is guaranteed to be object.__init__
init = super().__init__
init()
example usage:
class A(SuperObject):
def __init__(self, **kwargs):
print("A")
super(A, self).__init__(**kwargs)
class B(SuperObject):
def __init__(self, **kwargs):
print("B")
super(B, self).__init__(**kwargs)
class C(A):
def __init__(self, age, **kwargs):
print("C",f"age={age}")
super(C, self).__init__(age=age, **kwargs)
class D(B):
def __init__(self, name, **kwargs):
print("D", f"name={name}")
super(D, self).__init__(name=name, **kwargs)
class E(C,D):
def __init__(self, name, age, *args, **kwargs):
print( "E", f"name={name}", f"age={age}")
super(E, self).__init__(name=name, age=age, *args, **kwargs)
E(name='python', age=28)
output:
E name=python age=28
C age=28
A
D name=python
B
SuperObject
Lets assume you have a bunch of urls separated by spaces. In this case, you could do this:
function quote(text) {
var urls = text.split(/ /)
for (var i = 0; i < urls.length; i++) urls[i] = "'" + urls[i] + "'"
return urls.join(" ")
}
This function takes a string like "http://example.com http://blarg.test"
and returns a string like "'http://example.com' 'http://blarg.test'"
.
It works very simply: it takes your string of urls, splits it by spaces, surrounds each resulting url with quotes and finally combines all of them back with spaces.
Just to expand on $http
(shortcut methods) here: http://docs.angularjs.org/api/ng.$http
//Snippet from the page
$http.get('/someUrl').success(successCallback);
$http.post('/someUrl', data).success(successCallback);
//available shortcut methods
$http.get
$http.head
$http.post
$http.put
$http.delete
$http.jsonp
After declaring correctly in pubspec.yaml, consider giving full path of the image ex.
'assets/images/about_us.png'
instead of just images/..
worked for me after wasting 2 hours on such a trivial error.
On tables of >1000000 rows I've found that these are both fast, with floor
just slightly faster:
df['mydate'] = df.index.floor('d')
or
df['mydate'] = df.index.normalize()
If your index has timezones and you don't want those in the result, do:
df['mydate'] = df.index.tz_localize(None).floor('d')
df.index.date
is many times slower; to_datetime()
is even worse. Both have the further disadvantage that the results cannot be saved to an hdf store as it does not support type datetime.date.
Note that I've used the index as the date source here; if your source is another column, you would need to add .dt
, e.g. df.mycol.dt.floor('d')
The following illustrates the solution, assign your string to a variable pointer to a constant array of char (a string is a constant pointer to a constant array of char - plus length info):
#include <iostream>
void Swap(const char * & left, const char * & right) {
const char *const temp = left;
left = right;
right = temp;
}
int main() {
const char * x = "Hello"; // These works because you are making a variable
const char * y = "World"; // pointer to a constant string
std::cout << "x = " << x << ", y = " << y << '\n';
Swap(x, y);
std::cout << "x = " << x << ", y = " << y << '\n';
}
Vertex *f=(findvertex(from));
if(!f) {
cerr << "vertex not found" << endl;
exit(1) // or return;
}
Because findVertex
can return NULL
if it can't find the vertex.
Otherwise this f->adj;
is trying to do
NULL->adj;
Which causes access violation.
From within a function, rm all objects in .GlobalEnv except the function
initialize <- function(country.name) {
if (length(setdiff(ls(pos = .GlobalEnv), "initialize")) > 0) {
rm(list=setdiff(ls(pos = .GlobalEnv), "initialize"), pos = .GlobalEnv)
}
}
INSERT
INTO remotedblink.remotedatabase.remoteschema.remotetable
SELECT *
FROM mytable
There is no such thing as "the end of the table" in relational databases.
In JavaScript 1.8.5, Object.getOwnPropertyNames
returns an array of all properties found directly upon a given object.
Object.getOwnPropertyNames ( obj )
and another method Object.keys
, which returns an array containing the names of all of the given object's own enumerable properties.
Object.keys( obj )
I used forEach
to list values and keys in obj, same as for (var key in obj) ..
Object.keys(obj).forEach(function (key) {
console.log( key , obj[key] );
});
This all are new features in ECMAScript , the mothods getOwnPropertyNames
, keys
won't supports old browser's.
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
In XAML, add and define a RowStyle Property for the DataGrid with a goal to set the Background of the Row, to the Color defined in my Employee Object.
<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="{Binding ColorSet}"/>
</Style>
</DataGrid.RowStyle>
And in my Employee Class
public class Employee {
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string ColorSet { get; set; }
public Employee() { }
public Employee(int id, string name, int age)
{
Id = id;
Name = name;
Age = age;
if (Age > 50)
{
ColorSet = "Green";
}
else if (Age > 100)
{
ColorSet = "Red";
}
else
{
ColorSet = "White";
}
}
}
This way every Row of the DataGrid has the BackGround Color of the ColorSet
Property of my Object.
Just sort by whatever (mpg for example, question is not clear on this)
mt <- mtcars[order(mtcars$mpg), ]
then use the by function to get the top n rows in each group
d <- by(mt, mt["cyl"], head, n=4)
If you want the result to be a data.frame:
Reduce(rbind, d)
Edit: Handling ties is more difficult, but if all ties are desired:
by(mt, mt["cyl"], function(x) x[rank(x$mpg) %in% sort(unique(rank(x$mpg)))[1:4], ])
Another approach is to break ties based on some other information, e.g.,
mt <- mtcars[order(mtcars$mpg, mtcars$hp), ]
by(mt, mt["cyl"], head, n=4)
When I edit, rename, and move a file at the same time, none of these solutions work. The solution is to do it in two commits (edit and rename/move seperate) and then fixup
the second commit via git rebase -i
to have it in one commit.
You are using .index()
which will only find the first occurrence of your value in the list. So if you have a value 1.0 at index 2, and at index 9, then .index(1.0)
will always return 2
, no matter how many times 1.0
occurs in the list.
Use enumerate()
to add indices to your loop instead:
def find(lst, a, b):
result = []
for i, x in enumerate(lst):
if x<a or x>b:
result.append(i)
return result
You can collapse this into a list comprehension:
def find(lst, a, b):
return [i for i, x in enumerate(lst) if x<a or x>b]
Like this:
border: 1px solid black;
Why it didn't work? because:
Always declare the border-style (solid in my example) property before the border-width property. An element must have borders before you can change the color.
For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.
For Kotlin Here is added the lambda expression and Optimized the Code.
radioGroup.setOnCheckedChangeListener { radioGroup, optionId ->
run {
when (optionId) {
R.id.radioButton1 -> {
// do something when radio button 1 is selected
}
R.id.radioButton2 -> {
// do something when radio button 2 is selected
}
// add more cases here to handle other buttons in the your RadioGroup
}
}
}
Hope this will help you. Thanks!
You can use ref.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {}
},
template: `
<div>
<ChildForm :item="item" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.$refs.form.submit()
}
},
components: { ChildForm },
})
If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.
import ChildForm from './components/ChildForm'
new Vue({
el: '#app',
data: {
item: {},
bus: new Vue(),
},
template: `
<div>
<ChildForm :item="item" :bus="bus" ref="form" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.bus.$emit('submit')
}
},
components: { ChildForm },
})
Code of component.
<template>
...
</template>
<script>
export default {
name: 'NowForm',
props: ['item', 'bus'],
methods: {
submit() {
...
}
},
mounted() {
this.bus.$on('submit', this.submit)
},
}
</script>
https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/
Adding processData: false
to the $.ajax
options will fix this issue.
You need to use an explicit java.util.Iterator
to iterate over the Map
's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map
of Integer
, String
pairs, removing any entry whose Integer
key is null or equals 0.
Map<Integer, String> map = ...
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, String> entry = it.next();
// Remove entry if key is null or equals 0.
if (entry.getKey() == null || entry.getKey() == 0) {
it.remove();
}
}
For int
types use:
int myInteger = 1;
String myString = Integer.toString(myInteger);
For Integer
types use:
Integer myIntegerObject = new Integer(1);
String myString = myIntegerObject.toString();
What is a CSS map file?
It is a JSON format file that links the CSS file to its source files, normally, files written in preprocessors (i.e., Less, Sass, Stylus, etc.), this is in order do a live debug to the source files from the web browser.
What is CSS preprocessor? Examples: Sass, Less, Stylus
It is a CSS generator tool that uses programming power to generate CSS robustly and quickly.
First navigate to below location and open it in a text editor
<TOMCAT_HOME>/conf/tomcat-users.xml
For tomcat 7, Add the following xml code somewhere between <tomcat-users>
I find the following solution.
<role rolename="manager-gui"/>
<user username="username" password="password" roles="manager-gui"/>
Now restart the tomcat server.
This Perl one-liner comments out lines 1 to 3 of the file orig.sh
inclusive (where the first line is numbered 0), and writes the commented version to cmt.sh
.
perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh
Obviously you can change the boundary numbers as required.
If you want to edit the file in place, it's even shorter:
perl -in -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh
$ cat orig.sh
a
b
c
d
e
f
$ perl -n -e '$s=1;$e=3; $_="#$_" if $i>=$s&&$i<=$e;print;$i++' orig.sh > cmt.sh
$ cat cmt.sh
a
#b
#c
#d
e
f
It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.
Try this
boxValue = boxValue.replace(/[^0-9\.]/g,"");
This Regular Expression will allow only digits and dots in the value of text box.
You could just use the bound ng-model
(answers[item.questID]
) value itself in your ng-change method to detect if it has been checked or not.
Example:-
<input type="checkbox" ng-model="answers[item.questID]"
ng-change="stateChanged(item.questID)" /> <!-- Pass the specific id -->
and
$scope.stateChanged = function (qId) {
if($scope.answers[qId]){ //If it is checked
alert('test');
}
}
just use
file:///
works in IE, Firefox and Chrome as far as I can tell.
see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
The original conio.h was implemented by Borland, so its not a part of the C Standard Library nor is defined by POSIX.
But here is an implementation for Linux that uses ncurses to do the job.
First of all you are import this line:
import 'package:flutter/services.dart';
Then You can use bellow this some line of code in main.dart file
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
systemNavigationBarColor: Colors.amber, // navigation bar color
statusBarColor: Colors.white, // status bar color
statusBarIconBrightness: Brightness.dark, // status bar icon color
systemNavigationBarIconBrightness: Brightness.dark, // color of navigation controls
));
Note: If you follow above this steep. as a result you control all of screen. But if you control individual screen status bar color then you can try this ...
import 'package:flutter/services.dart';
Widget build(BuildContext context) {
SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
statusBarColor: Colors.transparent,
systemNavigationBarColor: Colors.transparent,
));
}
The master of all commands is
gg=G
This indents the entire file!
And below are some of the simple and elegant commands used to indent lines quickly in Vim or gVim.
To indent the current line
==
To indent the all the lines below the current line
=G
To indent n
lines below the current line
n==
For example, to indent 4 lines below the current line
4==
To indent a block of code, go to one of the braces and use command
=%
These are the simplest, yet powerful commands to indent multiple lines.
There is a very simple way to remove NULL values from JSON object. By default JSON object includes NULL values. Following can be used to remove NULL from JSON string
JsonConvert.SerializeObject(yourClassObject, new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore}))
As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt
The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)
Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.
Your int length = jsonObj.length();
should be int length = ja_data.length();
This would select 4 in your case
SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
This would delete them
DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)
The del
keyword would do.
>>> a=1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
But in this case I vote for self.left = None
I had this problem - my service type was in the GAC. It WOULD work if i added the dll containing the type to the bin folder but as it was in the GAC this was NOT what I wanted. I eventually added this to the web.config for the service
<system.web>
<customErrors mode="RemoteOnly" />
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="[name in GAC], Version=[version in GAC], Culture=neutral, PublicKeyToken=[ac token]" />
</assemblies>
</compilation>
</system.web>
and it worked without needing any dlls in the bin folder.
The problem is that in IE (which is what I presume you're testing in), the <iframe>
element has a document
property that refers to the document containing the iframe, and this is getting used before the contentDocument
or contentWindow.document
properties. What you need is:
function GetDoc(x) {
return x.contentDocument || x.contentWindow.document;
}
Also, document.all
is not available in all browsers and is non-standard. Use document.getElementById()
instead.
/private/etc/my.cnf for Catalina
You've practically written the format yourself.
yourdate.ToString("yyyyMMddHHmmss")
Everything else should be self-explanatory.
you can try binding property whit route
in your component.ts
user:any = 'linkABC'
;
in your component.html
<a target="_blank" href="yourtab/{{user}}">new tab </a>
Since itunesconnect has been changed i am updating with the new steps here.
You have to follow through these steps
Dim NewHandle As YourType = CType(Microsoft.VisualBasic.CallByName(ObjectThatContainsYourVariable, "YourVariableName", CallType), YourType)
For current datetime, you can use now() function in postgresql insert query.
You can also refer following link.
insert statement in postgres for data type timestamp without time zone NOT NULL,.
In my case it worked great just by doing the following:
[HttpPost]
public ActionResult DoSomething(int custNum)
{
// Some magic code here...
}
<form id="frmSomething" method="post">
<div>
<!-- Some magic html here... -->
</div>
<button id="btnSubmit" type="submit">Submit</button>
</form>
var frmSomething= $("#frmSomething");
var btnSubmit= $("#btnSubmit");
var custNum = 100;
btnSubmit.click(function()
{
frmSomething.attr("action", "/Home/DoSomething?custNum=" + custNum);
btnSubmit.submit();
});
Hope this helps vatos!
Due to onAttach
is deprecated in API23 and above...
In my Fragment, I declare and set parentActivity
before hand everytime when I go into Fragment. Most likely happen due to when we pressed back button caused the context to become null. Therefore below is my solution.
private Activity parentActivity;
public void onStart(){
super.onStart();
parentActivity = getActivity();
//...
}
$files = [
'./first.jpg',
'./second.jpg',
'./third.jpg'
];
foreach ($files as $file) {
if (file_exists($file)) {
unlink($file);
} else {
// File not found.
}
}
I had a button where the background-image
had a shadow below it so the text alignment was off from the top. Changing the line-height
wouldn't help. I added padding-bottom
to it and it worked.
So what you have to do is determine the line-height
you want to play with. So, for example, if I have a button who's height is truly 90px
but I want the line-height to be 80px
I would have something like this:
input[type=butotn].mybutton{
background: url(my/image.png) no-repeat center top; /*Image is 90px x 150px*/
width: 150px;
height: 80px; /*shadow at the bottom is 10px (90px-10px)*/
padding-bottom: 10px; /*the padding will make up for the lost height while maintaining the line-height to the proper height */
}
I hope this helps.
I was having this issue when trying to add a project reference, and after a lot of searching and trying many of the things above, my build configuration and outputs were correct.
I finally just deleted the \bin and \obj folders from the source and referencing project.
Honestly I believe it was the obj
folder not containing the correct metadata or corrupted metadata.
All is fixed now.
This was with Visual Studio 2015 - .NET 4.6 projects.
UPDATE:
The above worked on the first build, but on subsequent builds it failed, so I ended up recreating the solution file, and removing and reading the NuGet packages that were referenced incorrectly in my project files which pointed to the incorrect hint path.
That seemed to have fixed it thus far on subsequent builds.
<ItemGroup>
<Reference Include="Antlr3.Runtime, Version=3.5.0.2, Culture=neutral, PublicKeyToken=eb42632606e9261f, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\packages\Antlr.3.5.0.2\lib\Antlr3.Runtime.dll</HintPath>
</Reference>
</ItemGroup>
Assuming the second window is defined as public partial class Window2 : Window
, you can do it by:
Window2 win2 = new Window2();
win2.Show();
You can use the substr
function like this:
echo substr($myStr, 0, 5);
The second argument to substr
is from what position what you want to start and third arguments is for how many characters you want to return.
The angular2 way is to use listen
or listenGlobal
from Renderer
For example, if you want to add a click event to a Component, you have to use Renderer and ElementRef (this gives you as well the option to use ViewChild, or anything that retrieves the nativeElement
)
constructor(elementRef: ElementRef, renderer: Renderer) {
// Listen to click events in the component
renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
})
);
You can use listenGlobal
that will give you access to document
, body
, etc.
renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
Note that since beta.2 both listen
and listenGlobal
return a function to remove the listener (see breaking changes section from changelog for beta.2). This is to avoid memory leaks in big applications (see #6686).
So to remove the listener we added dynamically we must assign listen
or listenGlobal
to a variable that will hold the function returned, and then we execute it.
// listenFunc will hold the function returned by "renderer.listen"
listenFunc: Function;
// globalListenFunc will hold the function returned by "renderer.listenGlobal"
globalListenFunc: Function;
constructor(elementRef: ElementRef, renderer: Renderer) {
// We cache the function "listen" returns
this.listenFunc = renderer.listen(elementRef.nativeElement, 'click', (event) => {
// Do something with 'event'
});
// We cache the function "listenGlobal" returns
this.globalListenFunc = renderer.listenGlobal('document', 'click', (event) => {
// Do something with 'event'
});
}
ngOnDestroy() {
// We execute both functions to remove the respectives listeners
// Removes "listen" listener
this.listenFunc();
// Removs "listenGlobal" listener
this.globalListenFunc();
}
Here's a plnkr with an example working. The example contains the usage of listen
and listenGlobal
.
25/02/2017: Renderer
has been deprecated, now we should use (see line below). See the commit.RendererV2
10/03/2017: RendererV2
was renamed to Renderer2
. See the breaking changes.
RendererV2
has no more listenGlobal
function for global events (document, body, window). It only has a listen
function which achieves both functionalities.
For reference, I'm copy & pasting the source code of the DOM Renderer implementation since it may change (yes, it's angular!).
listen(target: 'window'|'document'|'body'|any, event: string, callback: (event: any) => boolean):
() => void {
if (typeof target === 'string') {
return <() => void>this.eventManager.addGlobalEventListener(
target, event, decoratePreventDefault(callback));
}
return <() => void>this.eventManager.addEventListener(
target, event, decoratePreventDefault(callback)) as() => void;
}
As you can see, now it verifies if we're passing a string (document, body or window), in which case it will use an internal addGlobalEventListener
function. In any other case, when we pass an element (nativeElement) it will use a simple addEventListener
To remove the listener it's the same as it was with Renderer
in angular 2.x. listen
returns a function, then call that function.
// Add listeners
let global = this.renderer.listen('document', 'click', (evt) => {
console.log('Clicking the document', evt);
})
let simple = this.renderer.listen(this.myButton.nativeElement, 'click', (evt) => {
console.log('Clicking the button', evt);
});
// Remove listeners
global();
simple();
plnkr with Angular 4.0.0-rc.1 using RendererV2
plnkr with Angular 4.0.0-rc.3 using Renderer2
This was done using Toad for Oracle 12.8.0.49
ALTER TABLE SCHEMA.TABLENAME
MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;
For example,
ALTER TABLE PAYROLL.EMPLOYEES
MODIFY (JOBTITLE VARCHAR2(12)) ;
The Spring container is able to resolve Setter-based circular dependencies but gives a runtime exception BeanCurrentlyInCreationException in case of Constructor-based circular dependencies. In case of Setter-based circular dependency, the IOC container handles it differently from a typical scenario wherein it would fully configure the collaborating bean before injecting it. For eg., if Bean A has a dependency on Bean B and Bean B on Bean C, the container fully initializes C before injecting it to B and once B is fully initialized it is injected to A. But in case of circular dependency, one of the beans is injected to the other before it is fully initialized.
It's just common stuff for making cin input work faster.
For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.
The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).
Just write:
private static double balance = 0;
and you could also write those like that:
private static int id = 0;
private static double annualInterestRate = 0;
public static java.util.Date dateCreated;
The sequences in postgresql are transaction safe. So you can use the
currval(sequence)
currval
Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer even if other sessions are executing nextval meanwhile.
You can use the key code page in order to find the:
event.code
to diference the number keyboard.
function getNumberFromKeyEvent(event) {
if (event.code.indexOf('Numpad') === 0) {
var number = parseInt(event.code.replace('Numpad', ''), 10);
if (number >= 0 && number <= 9) {
// numbers from numeric keyboard
}
}
}
There are 3 steps that needs to be run.
It is very interesting that this simplest usage is not clearly described anywhere. And i believe there is a danger, you should pay attention to the verified_email
parameter coming in the response. Because if I am not wrong it may yield fake emails to register your application. (This is just my interpretation, has a fair chance that I may be wrong!)
I find facebook's OAuth mechanics much much clearly described.
What you are doing is printing the value in the array at spot [3][3], which is invalid for a 3by3 array, you need to loop over all the spots and print them.
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
printf("%d ", array[i][j]);
}
printf("\n");
}
This will print it in the following format
10 23 42
1 654 0
40652 22 0
if you want more exact formatting you'll have to change how the printf is formatted.
As told before, filesystem may run out of inodes, if there are a lot of small files. I have provided some means to find directories that contain most files here.
you could also store your data in an service with an setter and get it over a getter
import { Injectable } from '@angular/core';
@Injectable()
export class StorageService {
public scope: Array<any> | boolean = false;
constructor() {
}
public getScope(): Array<any> | boolean {
return this.scope;
}
public setScope(scope: any): void {
this.scope = scope;
}
}
As many people suggested, you could use std::make_pair
.
But I would like to point out another method of doing the same:
revenue.push_back({"string",map[i].second});
push_back() accepts a single parameter, so you could use "{}" to achieve this!
printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).
So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.
For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.
(This goes for everyone else reading this too.)
// export in index.js
export { default as Foo } from './Foo';
export { default as Bar } from './Bar';
// then import both
import { Foo, Bar } from 'my/module';
After reading all the answers but none really working for numbers only with copy and paste I came up with this solution.
parseInt
solution: fails as parseInt("2a")
is valid; onKeyup sulution:
fails on copy and paste, backspace;javascript
converts 40817810000000023511 into 40817810000000023500 because it is 53 bit language<input
name="address.line1"
value={values.address.line1}
onChange={(event: any) => {
if (isFinite(event.target.value)) {
// UPDATE YOUR STATE (i am using formik)
setFieldValue("address.line1", event.target.value);
}
}}
/>
Change your network adapter to a bridged connection, this will directly connect to your computers physical network.
Try this to switch to php4:
AddHandler application/x-httpd-php4 .php
Upd. Looks like I didn't understand your question correctly. This will not help if you have only php 4 on your server.
The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):
customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}
Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport
struct over time.
Just to add to what's already here, use the following:
background: -moz-linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
background: -webkit-linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
background: linear-gradient(rgba(0,0,0,.7),rgba(0,0,0,.7));
filter: unquote("progid:DXImageTransform.Microsoft.gradient( startColorstr='#b3000000', endColorstr='#b3000000',GradientType=0 )");
...for cross-browser support of a 70% linear-gradient overlay. To brighten the image, you can change all those 0,0,0
's into 255,255,255
's. If 70% is a bit much, go ahead and change the .7
. And, for future reference check out this: http://www.colorzilla.com/gradient-editor/
public class KeyNote
{
public long KeyNoteId { get; set; }
public long CourseId { get; set; }
public string CourseName { get; set; }
public string Note { get; set; }
public DateTime CreatedDate { get; set; }
}
public List<KeyNote> KeyNotes { get; set; }
public List<RefCourse> GetCourses { get; set; }
List<RefCourse> courses = KeyNotes.Select(x => new RefCourse { CourseId = x.CourseId, Name = x.CourseName }).Distinct().ToList();
By using the above logic, we can get the unique Course
s.
No. From the XHTML 1.0 Spec
In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.
There is nothing to change. Pass only in the connect function {useNewUrlParser: true }
.
This will work:
MongoClient.connect(url, {useNewUrlParser:true,useUnifiedTopology: true }, function(err, db) {
if(err) {
console.log(err);
}
else {
console.log('connected to ' + url);
db.close();
}
})
If you're doing shell commands and you (like I) have a fetish for pipelining, this one is good:
seq 1 $END | xargs -I {} echo {}
A class based clean to use solution:
import signal
import time
class GracefulKiller:
kill_now = False
def __init__(self):
signal.signal(signal.SIGINT, self.exit_gracefully)
signal.signal(signal.SIGTERM, self.exit_gracefully)
def exit_gracefully(self,signum, frame):
self.kill_now = True
if __name__ == '__main__':
killer = GracefulKiller()
while not killer.kill_now:
time.sleep(1)
print("doing something in a loop ...")
print("End of the program. I was killed gracefully :)")
If you mean using a literal, you simply have to create a binary string:
insert into Files (FileId, FileData) values (1, 0x010203040506)
And you will have a record with a six byte value for the FileData field.
You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).
You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).
In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.
Alter your field to be INT instead of VARCHAR.
I can not make them INT due to some other depending circumstances.
Then fix the depending circumstances first. Otherwise you are working around the real underlying issue. Using a MySQL CAST is an option, but it's masking your bad schema which should be fixed.