In JQuery:
$("#id option:selected").prop("selected", false);
$("#id").multiselect('refresh');
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
Shorter version:
$('#multiselect1').multiselect({
...
onChange: function() {
console.log($('#multiselect1').val());
}
});
You can use chosen.i download all file from this link Chosen download Link
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="prism.css" rel="stylesheet" type="text/css" />
<link href="chosen.css" rel="stylesheet" type="text/css" />
<script src="jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="chosen.jquery.js" type="text/javascript"></script>
<script src="prism.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(".chzn-select").chosen();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<ion-view view-title="Profile">
<ion-content class="padding">
<div>
<label class="item item-input">
<div class="input-label">Enter Your Option</div>
<select class="chzn-select" multiple="true" name="faculty" style="width:1000px;">
<option value="Option 2.1">Option 2.1</option>
<option value="Option 2.2">Option 2.2</option>
<option value="Option 2.3">Option 2.3</option>
</select>
</label>
</div>
</ion-content>
</ion-view>
</div>
</form>
</body>
</html>
All file on all same folder
Just by one line-
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text);
Output: ["text1", "text2"]
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.value);
Output: ["value1", "value2"]
If you use .join()
var select_button_text = $('#SelectQButton option:selected')
.toArray().map(item => item.text).join();
Output: text1,text2,text3
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $http service documentation.
Try with the PyAutoGUI module. It's multiplatform.
pip install pyautogui
And so:
import pyautogui
pyautogui.click(100, 100)
It also has other features:
import pyautogui
pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10) # move mouse 10 pixels down
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10) # drag mouse 10 pixels down
This is much easier than going through all the win32con stuff.
From here:
ArrayList is internally backed by Array in Java, any resize operation in ArrayList will slow down performance as it involves creating new Array and copying content from old array to new array.
In terms of performance Array and ArrayList provides similar performance in terms of constant time for adding or getting element if you know index. Though automatic resize of ArrayList may slow down insertion a bit Both Array and ArrayList is core concept of Java and any serious Java programmer must be familiar with these differences between Array and ArrayList or in more general Array vs List.
function final_submit1() {
var city = $("#city").val();
var airport = $("#airport").val();
var vehicle = $("#vehicle").val();
if(city && airport){
$.ajax({
type:"POST",
cache:false,
data:{"city": city,"airport": airport},
url:'http://airportLimo/ajax-car-list',
success: function (html) {
console.log(html);
//$('#add').val('data sent');
//$('#msg').html(html);
$('#pprice').html("Price: $"+html);
}
});
}
}
Collections.sort
allows you to pass an instance of a Comparator
which defines the sorting logic. So instead of sorting the list in natural order and then reversing it, one can simply pass Collections.reverseOrder()
to sort
in order to sort the list in reverse order:
// import java.util.Collections;
Collections.sort(testList, Collections.reverseOrder());
As mentioned by @Marco13, apart from being more idiomatic (and possibly more efficient), using the reverse order comparator makes sure that the sort is stable (meaning that the order of elements will not be changed when they are equal according to the comparator, whereas reversing will change the order)
Hit F4 and you'll get what you are looking for.
Any script tags posted on an ASP.NET web form will cause your site to throw and unhandled exception.
You can use a asp regex validator to confirm input, just ensure you wrap your code behind method with a if(IsValid) clause in case your javascript is bypassed. If your client javascript is bypassed and script tags are posted to your asp.net form, asp.net will throw a unhandled exception.
You can use something like:
<asp:RegularExpressionValidator ID="regexEmailValid" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbEmail" ErrorMessage="Invalid Email Format"></asp:RegularExpressionValidator>
Connection.Response resp = Jsoup.connect(url) //
.timeout(20000) //
.method(Connection.Method.GET) //
.execute();
actually, the error occurs when you have slow internet so try to maximize the timeout time and then your code will definitely work as it works for me.
You can use xarg
:
ls | xargs -L 1 -d '\n' your-desired-command
-L 1
causes pass 1 item at a time
-d '\n'
splits the output of ls
based on new line.
One liner: $page_path = end(explode('/', trim($_SERVER['REQUEST_URI'], '/')));
Get URI, trim slashes, convert to array, grab last part
There is an indexOf
method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:
if (yourArray.indexOf("someString") > -1) {
//In the array!
} else {
//Not in the array
}
If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.
Be careful with some answers...
UPDATE 2019-0829, I also included Microsoft decompiled code which should be far better than mine.
1 - You could easily represent any number with 15 significatives digits in memory with a double. See Wikipedia.
2 - The problem come from calculation of floating numbers where you could loose some precision. I mean that a number like .1 could become something like .1000000000000001 ==> after calculation. When you do some calculation, results could be truncated in order to be represented in a double. That truncation brings the error you could get.
3 - To prevent the problem when comparing double values, people introduce an error margin often called epsilon. If 2 floating numbers only have a contextual epsilon as difference, then they are considered equals. double.Epsilon is the smallest number between a double value and its neigbor (next or previous) value.
4 - The difference betwen 2 double values could be more than double.epsilon. The difference between the real double value and the one computed depends on how many calculation you have done and which ones. Many peoples think that it is always double.Epsilon but they are really wrong. To have a great answer please see: Hans Passant answer. The epsilon is based on your context where it depends on the biggest number you reach during your calculation and on the number of calculation you are doing (truncation error accumulate).
5 - This is the code that I use. Be careful that I use my epsilon only for few calculations. Otherwise I multiply my epsilon by 10 or 100.
6 - As noted by SvenL, it is possible that my epsilon is not big enough. I suggest to read SvenL comment. Also, perhaps "decimal" could do the job for your case?
Microsoft decompiled code:
// Decompiled with JetBrains decompiler
// Type: MS.Internal.DoubleUtil
// Assembly: WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// MVID: 33C590FB-77D1-4FFD-B11B-3D104CA038E5
// Assembly location: C:\Windows\Microsoft.NET\assembly\GAC_MSIL\WindowsBase\v4.0_4.0.0.0__31bf3856ad364e35\WindowsBase.dll
using MS.Internal.WindowsBase;
using System;
using System.Runtime.InteropServices;
using System.Windows;
namespace MS.Internal
{
[FriendAccessAllowed]
internal static class DoubleUtil
{
internal const double DBL_EPSILON = 2.22044604925031E-16;
internal const float FLT_MIN = 1.175494E-38f;
public static bool AreClose(double value1, double value2)
{
if (value1 == value2)
return true;
double num1 = (Math.Abs(value1) + Math.Abs(value2) + 10.0) * 2.22044604925031E-16;
double num2 = value1 - value2;
if (-num1 < num2)
return num1 > num2;
return false;
}
public static bool LessThan(double value1, double value2)
{
if (value1 < value2)
return !DoubleUtil.AreClose(value1, value2);
return false;
}
public static bool GreaterThan(double value1, double value2)
{
if (value1 > value2)
return !DoubleUtil.AreClose(value1, value2);
return false;
}
public static bool LessThanOrClose(double value1, double value2)
{
if (value1 >= value2)
return DoubleUtil.AreClose(value1, value2);
return true;
}
public static bool GreaterThanOrClose(double value1, double value2)
{
if (value1 <= value2)
return DoubleUtil.AreClose(value1, value2);
return true;
}
public static bool IsOne(double value)
{
return Math.Abs(value - 1.0) < 2.22044604925031E-15;
}
public static bool IsZero(double value)
{
return Math.Abs(value) < 2.22044604925031E-15;
}
public static bool AreClose(Point point1, Point point2)
{
if (DoubleUtil.AreClose(point1.X, point2.X))
return DoubleUtil.AreClose(point1.Y, point2.Y);
return false;
}
public static bool AreClose(Size size1, Size size2)
{
if (DoubleUtil.AreClose(size1.Width, size2.Width))
return DoubleUtil.AreClose(size1.Height, size2.Height);
return false;
}
public static bool AreClose(Vector vector1, Vector vector2)
{
if (DoubleUtil.AreClose(vector1.X, vector2.X))
return DoubleUtil.AreClose(vector1.Y, vector2.Y);
return false;
}
public static bool AreClose(Rect rect1, Rect rect2)
{
if (rect1.IsEmpty)
return rect2.IsEmpty;
if (!rect2.IsEmpty && DoubleUtil.AreClose(rect1.X, rect2.X) && (DoubleUtil.AreClose(rect1.Y, rect2.Y) && DoubleUtil.AreClose(rect1.Height, rect2.Height)))
return DoubleUtil.AreClose(rect1.Width, rect2.Width);
return false;
}
public static bool IsBetweenZeroAndOne(double val)
{
if (DoubleUtil.GreaterThanOrClose(val, 0.0))
return DoubleUtil.LessThanOrClose(val, 1.0);
return false;
}
public static int DoubleToInt(double val)
{
if (0.0 >= val)
return (int) (val - 0.5);
return (int) (val + 0.5);
}
public static bool RectHasNaN(Rect r)
{
return DoubleUtil.IsNaN(r.X) || DoubleUtil.IsNaN(r.Y) || (DoubleUtil.IsNaN(r.Height) || DoubleUtil.IsNaN(r.Width));
}
public static bool IsNaN(double value)
{
DoubleUtil.NanUnion nanUnion = new DoubleUtil.NanUnion();
nanUnion.DoubleValue = value;
ulong num1 = nanUnion.UintValue & 18442240474082181120UL;
ulong num2 = nanUnion.UintValue & 4503599627370495UL;
if (num1 == 9218868437227405312UL || num1 == 18442240474082181120UL)
return num2 > 0UL;
return false;
}
[StructLayout(LayoutKind.Explicit)]
private struct NanUnion
{
[FieldOffset(0)]
internal double DoubleValue;
[FieldOffset(0)]
internal ulong UintValue;
}
}
}
My code:
public static class DoubleExtension
{
// ******************************************************************
// Base on Hans Passant Answer on:
// https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre
/// <summary>
/// Compare two double taking in account the double precision potential error.
/// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
public static bool AboutEquals(this double value1, double value2)
{
double epsilon = Math.Max(Math.Abs(value1), Math.Abs(value2)) * 1E-15;
return Math.Abs(value1 - value2) <= epsilon;
}
// ******************************************************************
// Base on Hans Passant Answer on:
// https://stackoverflow.com/questions/2411392/double-epsilon-for-equality-greater-than-less-than-less-than-or-equal-to-gre
/// <summary>
/// Compare two double taking in account the double precision potential error.
/// Take care: truncation errors accumulate on calculation. More you do, more you should increase the epsilon.
/// You get really better performance when you can determine the contextual epsilon first.
/// </summary>
/// <param name="value1"></param>
/// <param name="value2"></param>
/// <param name="precalculatedContextualEpsilon"></param>
/// <returns></returns>
public static bool AboutEquals(this double value1, double value2, double precalculatedContextualEpsilon)
{
return Math.Abs(value1 - value2) <= precalculatedContextualEpsilon;
}
// ******************************************************************
public static double GetContextualEpsilon(this double biggestPossibleContextualValue)
{
return biggestPossibleContextualValue * 1E-15;
}
// ******************************************************************
/// <summary>
/// Mathlab equivalent
/// </summary>
/// <param name="dividend"></param>
/// <param name="divisor"></param>
/// <returns></returns>
public static double Mod(this double dividend, double divisor)
{
return dividend - System.Math.Floor(dividend / divisor) * divisor;
}
// ******************************************************************
}
The database does not do joins -- or automatic "linking" between documents. However you can do it yourself client side. If you need to do 2, that is ok, but if you had to do 2000, the number of client/server turnarounds would make the operation slow.
In MongoDB a common pattern is embedding. In relational when normalizing things get broken into parts. Often in mongo these pieces end up being a single document, so no join is needed anyway. But when one is needed, one does it client-side.
Consider the classic ORDER, ORDER-LINEITEM example. One order and 8 line items are 9 rows in relational; in MongoDB we would typically just model this as a single BSON document which is an order with an array of embedded line items. So in that case, the join issue does not arise. However the order would have a CUSTOMER which probably is a separate collection - the client could read the cust_id from the order document, and then go fetch it as needed separately.
There are some videos and slides for schema design talks on the mongodb.org web site I belive.
Using inputStream.available()
It is always acceptable for System.in.available() to return 0.
I've found the opposite - it always returns the best value for the number of bytes available. Javadoc for InputStream.available()
:
Returns an estimate of the number of bytes that can be read (or skipped over)
from this input stream without blocking by the next invocation of a method for
this input stream.
An estimate is unavoidable due to timing/staleness. The figure can be a one-off underestimate because new data are constantly arriving. However it always "catches up" on the next call - it should account for all arrived data, bar that arriving just at the moment of the new call. Permanently returning 0 when there are data fails the condition above.
First Caveat: Concrete subclasses of InputStream are responsible for available()
InputStream
is an abstract class. It has no data source. It's meaningless for it to have available data. Hence, javadoc for available()
also states:
The available method for class InputStream always returns 0.
This method should be overridden by subclasses.
And indeed, the concrete input stream classes do override available(), providing meaningful values, not constant 0s.
Second Caveat: Ensure you use carriage-return when typing input in Windows.
If using System.in
, your program only receives input when your command shell hands it over. If you're using file redirection/pipes (e.g. somefile > java myJavaApp or somecommand | java myJavaApp ), then input data are usually handed over immediately. However, if you manually type input, then data handover can be delayed. E.g. With windows cmd.exe shell, the data are buffered within cmd.exe shell. Data are only passed to the executing java program following carriage-return (control-m or <enter>
). That's a limitation of the execution environment. Of course, InputStream.available() will return 0 for as long as the shell buffers the data - that's correct behaviour; there are no available data at that point. As soon as the data are available from the shell, the method returns a value > 0. NB: Cygwin uses cmd.exe too.
Just use this:
byte[] inputData = new byte[1024];
int result = is.read(inputData, 0, is.available());
// result will indicate number of bytes read; -1 for EOF with no data read.
OR equivalently,
BufferedReader br = new BufferedReader(new InputStreamReader(System.in, Charset.forName("ISO-8859-1")),1024);
// ...
// inside some iteration / processing logic:
if (br.ready()) {
int readCount = br.read(inputData, bufferOffset, inputData.length-bufferOffset);
}
Declare this:
public static int readInputStreamWithTimeout(InputStream is, byte[] b, int timeoutMillis)
throws IOException {
int bufferOffset = 0;
long maxTimeMillis = System.currentTimeMillis() + timeoutMillis;
while (System.currentTimeMillis() < maxTimeMillis && bufferOffset < b.length) {
int readLength = java.lang.Math.min(is.available(),b.length-bufferOffset);
// can alternatively use bufferedReader, guarded by isReady():
int readResult = is.read(b, bufferOffset, readLength);
if (readResult == -1) break;
bufferOffset += readResult;
}
return bufferOffset;
}
Then use this:
byte[] inputData = new byte[1024];
int readCount = readInputStreamWithTimeout(System.in, inputData, 6000); // 6 second timeout
// readCount will indicate number of bytes read; -1 for EOF with no data read.
Just installed new version of gradle and it started working for me. I think the local instances of gradle were messed up
Using Virtual Attributes (Link to revised(paid) Railscast) you can store your price_in_cents in an integer column and add a virtual attribute price_in_dollars in your product model as a getter and setter.
# Add a price_in_cents integer column
$ rails g migration add_price_in_cents_to_products price_in_cents:integer
# Use virtual attributes in your Product model
# app/models/product.rb
def price_in_dollars
price_in_cents.to_d/100 if price_in_cents
end
def price_in_dollars=(dollars)
self.price_in_cents = dollars.to_d*100 if dollars.present?
end
Source: RailsCasts #016: Virtual Attributes: Virtual attributes are a clean way to add form fields that do not map directly to the database. Here I show how to handle validations, associations, and more.
For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind
.
Imagine for example a GridView with a ItemTemplate
and EditItemTemplate
. If you use Bind
or Eval
in the ItemTemplate
, there will be no difference. If you use Eval
in the EditItemTemplate
, the value will not be able to be passed to the Update
method of the DataSource
that the grid is bound to.
UPDATE: I've come up with this example:
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Data binding demo</title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView
ID="grdTest"
runat="server"
AutoGenerateEditButton="true"
AutoGenerateColumns="false"
DataSourceID="mySource">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Eval("Name") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox
ID="edtName"
runat="server"
Text='<%# Bind("Name") %>'
/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
<asp:ObjectDataSource
ID="mySource"
runat="server"
SelectMethod="Select"
UpdateMethod="Update"
TypeName="MyCompany.CustomDataSource" />
</body>
</html>
And here's the definition of a custom class that serves as object data source:
public class CustomDataSource
{
public class Model
{
public string Name { get; set; }
}
public IEnumerable<Model> Select()
{
return new[]
{
new Model { Name = "some value" }
};
}
public void Update(string Name)
{
// This method will be called if you used Bind for the TextBox
// and you will be able to get the new name and update the
// data source accordingly
}
public void Update()
{
// This method will be called if you used Eval for the TextBox
// and you will not be able to get the new name that the user
// entered
}
}
I would think you should add it to ~/.bash_profile
instead of .bashrc
, (creating .bash_profile
if it doesn't exist.) Then you don't have to add the extra step of checking for ~/.bashrc
in your .bash_profile
Are you comfortable working and editing in a terminal? Just in case, ~/
means your home directory, so if you open a new terminal window that is where you will be "located". And the dot at the front makes the file invisible to normal ls
command, unless you put -a
or specify the file name.
Check this answer for more detail.
i just restart my mysql server and the problem solved in windows net stop MySQL then net start MySQl ubuntu linux sudo service start mysql
You just need to cast at least one of the operands to a float:
float z = (float) x / y;
or
float z = x / (float) y;
or (unnecessary)
float z = (float) x / (float) y;
The application is in use 24 hours a day. Your maintenance / update window is 2 hours every month, how do you plan to minimise disruption?
My situation
empty Instance Name in SQL Server Management Studio > select your database engine > Right Mouse Button > Properties (Server Properties) > Link View connection properties > Product > Instance Name is empty
Data Source=.\SQLEXPRESS did not work => use localhost in web.config (see below)
Solution: in web.config
xxxxxx = name of my database without .mdf yyyyyy = name of my database in VS2012 database explorer
You can force the use of TCP instead of shared memory, either by prefixing tcp: to the server name in the connection string, or by using localhost.
Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str
is a pointer, you can use it as if it were an array like so:
char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];
...and so on. What you could also do is "add" 1 to the value of the pointer to a character str
which will then point to the second character in the string. Then you can simply do:
str = str + 1; // makes it point to 'E' now
char myChar = *str;
I hope this helps.
It sounds like you currently have 3 copies of the entire file in memory: the byte array, the string, and the array of the lines.
Instead of reading the bytes into a byte array and then converting to characters using new String()
it would be better to use an InputStreamReader, which will convert to characters incrementally, rather than all up-front.
Also, instead of using String.split("\n") to get the individual lines, you should read one line at a time. You can use the readLine()
method in BufferedReader
.
Try something like this:
BufferedReader reader = new BufferedReader(new InputStreamReader(fileInputStream, "UTF-8"));
try {
while (true) {
String line = reader.readLine();
if (line == null) break;
String[] fields = line.split(",");
// process fields here
}
} finally {
reader.close();
}
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).
I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:
find /etc -type f -exec grep -nHi -e "widehat" {} \;
Instead of:
grep -nRHi -e "widehat" /etc
extension UITextField {
func setBottomBorder(color:String) {
self.borderStyle = UITextBorderStyle.None
let border = CALayer()
let width = CGFloat(1.0)
border.borderColor = UIColor(hexString: color)!.cgColor
border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height)
border.borderWidth = width
self.layer.addSublayer(border)
self.layer.masksToBounds = true
}
}
and then just do this:
yourTextField.setBottomBorder(color: "#3EFE46")
We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST
VERIFYPEER
did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget
to the same link as the cURL was doing also resulted in a certificate error.
-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.
For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover
does not work try to reboot your machine.
I ran into the same problem and after a couple of hours of logging and investigating, I fixed it.
It turned out that for the first time the value is set in a date picker, $viewValue is a string so the dateFilter displays it as is. All I did is parse it into a Date object.
Search for that block in ui-bootstrap-tpls file
ngModel.$render = function() {
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
and replace it by:
ngModel.$render = function() {
ngModel.$viewValue = new Date(ngModel.$viewValue);
var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';
element.val(date);
updateCalendar();
};
Hopefully this will help :)
This doesn't have the regex overhead
double myNum = 0;
String testVar = "Not A Number";
if (Double.TryParse(testVar, out myNum)) {
// it is a number
} else {
// it is not a number
}
Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse.
update
secretwep brought up that the value "2345," will pass the above test as a number. However, if you need to ensure that all of the characters within the string are digits, then another approach should be taken.
example 1:
public Boolean IsNumber(String s) {
Boolean value = true;
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
return value;
}
or if you want to be a little more fancy
public Boolean IsNumber(String value) {
return value.All(Char.IsDigit);
}
update 2 ( from @stackonfire to deal with null or empty strings)
public Boolean IsNumber(String s) {
Boolean value = true;
if (s == String.Empty || s == null) {
value=false;
} else {
foreach(Char c in s.ToCharArray()) {
value = value && Char.IsDigit(c);
}
} return value;
}
One more thing node provides is the ability to create multiple v8 instanes of node using node's child process( childProcess.fork() each requiring 10mb memory as per docs) on the fly, thus not affecting the main process running the server. So offloading a background job that requires huge server load becomes a child's play and we can easily kill them as and when needed.
I've been using node a lot and in most of the apps we build, require server connections at the same time thus a heavy network traffic. Frameworks like Express.js and the new Koajs (which removed callback hell) have made working on node even more easier.
Figured it out, folks! for the NAME of the text box, you have to use "q". I had "g" just for my own personal preferences. But apparently it has to be "q".
Anyone know why?
JavaScript is an object-oriented programming language and it's used exactly for creating instances. It's prototype-based, rather than class-based, but that does not mean that it is not object-oriented.
On windows use the name of the table in quotes:
TABLE "user";
or SELECT * FROM "user";
The pdf2image library can be used.
You can install it simply using,
pip install pdf2image
Once installed you can use following code to get images.
from pdf2image import convert_from_path
pages = convert_from_path('pdf_file', 500)
Saving pages in jpeg format
for page in pages:
page.save('out.jpg', 'JPEG')
Edit: the Github repo pdf2image also mentions that it uses pdftoppm
and that it requires other installations:
pdftoppm is the piece of software that does the actual magic. It is distributed as part of a greater package called poppler. Windows users will have to install poppler for Windows. Mac users will have to install poppler for Mac. Linux users will have pdftoppm pre-installed with the distro (Tested on Ubuntu and Archlinux) if it's not, run
sudo apt install poppler-utils
.
You can install the latest version under Windows using anaconda by doing:
conda install -c conda-forge poppler
note: Windows versions upto 0.67 are available at http://blog.alivate.com.au/poppler-windows/ but note that 0.68 was released in Aug 2018 so you'll not be getting the latest features or bug fixes.
Table Name
sp_rename 'db_name.old_table_name', 'new_table_name'
Column
sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'
Index
sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'
also available for statics and datatypes
Refer django docs on static files.
In settings.py:
import os
CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8'))
MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(CURRENT_PATH, 'static'),
)
Then place your js and css files static folder in your project. Not in media folder.
In views.py:
from django.shortcuts import render_to_response, RequestContext
def view_name(request):
#your stuff goes here
return render_to_response('template.html', locals(), context_instance = RequestContext(request))
In template.html:
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/style.css" />
<script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.8.3.min.js"></script>
In urls.py:
from django.conf import settings
urlpatterns += patterns('',
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
)
Project file structure can be found here in imgbin.
LINQ is new and has its place. LINQ is not invented to replace stored procedure.
Here I will focus on some performance myths & CONS, just for "LINQ to SQL", of course I might be totally wrong ;-)
(1)People say LINQ statment can "cache" in SQL server, so it doesn't lose performance. Partially true. "LINQ to SQL" actually is the runtime translating LINQ syntax to TSQL statment. So from the performance perspective,a hard coded ADO.NET SQL statement has no difference than LINQ.
(2)Given an example, a customer service UI has a "account transfer" function. this function itself might update 10 DB tables and return some messages in one shot. With LINQ, you have to build a set of statements and send them as one batch to SQL server. the performance of this translated LINQ->TSQL batch can hardly match stored procedure. Reason? because you can tweak the smallest unit of the statement in Stored procedue by using the built-in SQL profiler and execution plan tool, you can not do this in LINQ.
The point is, when talking single DB table and small set of data CRUD, LINQ is as fast as SP. But for much more complicated logic, stored procedure is more performance tweakable.
(3)"LINQ to SQL" easily makes newbies to introduce performance hogs. Any senior TSQL guy can tell you when not to use CURSOR (Basically you should not use CURSOR in TSQL in most cases). With LINQ and the charming "foreach" loop with query, It's so easy for a newbie to write such code:
foreach(Customer c in query)
{
c.Country = "Wonder Land";
}
ctx.SubmitChanges();
You can see this easy decent code is so attractive. But under the hood, .NET runtime just translate this to an update batch. If there are only 500 lines, this is 500 line TSQL batch; If there are million lines, this is a hit. Of course, experienced user won't use this way to do this job, but the point is, it's so easy to fall in this way.
<Hoverable hoverStyle={styles.linkHover}>
<a href="https://example.com" style={styles.link}>
Go
</a>
</Hoverable>
Where Hoverable is defined as:
function Hoverable(props) {
const [hover, setHover] = useState(false);
const child = Children.only(props.children);
const onHoverChange = useCallback(
e => {
const name = e.type === "mouseenter" ? "onMouseEnter" : "onMouseLeave";
setHover(!hover);
if (child.props[name]) {
child.props[name](e);
}
},
[setHover, hover, child]
);
return React.cloneElement(child, {
onMouseEnter: onHoverChange,
onMouseLeave: onHoverChange,
style: Object.assign({}, child.props.style, hover ? props.hoverStyle : {})
});
}
It's not bad practice at all. They are usually referred as SUBQUERY, SUBSELECT or NESTED QUERY.
It's a relatively expensive operation, but it's quite common to encounter a lot of subqueries when dealing with databases since it's the only way to perform certain kind of operations on data.
Everybody is using the parse_url
function, but sometimes user may pass the argumet in different format.
So as to fix that, I have created the function. Check this out:
function fixDomainName($url='')
{
$strToLower = strtolower(trim($url));
$httpPregReplace = preg_replace('/^http:\/\//i', '', $strToLower);
$httpsPregReplace = preg_replace('/^https:\/\//i', '', $httpPregReplace);
$wwwPregReplace = preg_replace('/^www\./i', '', $httpsPregReplace);
$explodeToArray = explode('/', $wwwPregReplace);
$finalDomainName = trim($explodeToArray[0]);
return $finalDomainName;
}
Just pass the URL and get the domain.
For example,
echo fixDomainName('https://stackoverflow.com');
will return the result will be
stackoverflow.com
And in some situation:
echo fixDomainName('stackoverflow.com/questions/id/slug');
And it will also return stackoverflow.com
.
It may not be the best solution if you don't already have it, but FileMaker 11 with the Actual SQL Server ODBC driver (http://www.actualtech.com/product_sqlserver.php) worked nicely for a client of mine today. The ODBC driver is only $29, but FileMaker is $299, which is why you might only consider it if you already have it.
You are copying singleton's customVar
into a singletonVar
variable and changing that variable does not affect the original value in singleton.
// This does not update singleton variable
// It just assigns value of your local variable
Log.d("Test",singletonVar);
singletonVar="World";
Log.d("Test",singletonVar);
// This actually assigns value of variable in singleton
Singleton.customVar = singletonVar;
"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...
gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt
The above script, tested in PS 5.1 is the SAME response as below...
gc -head 25 C:\scripts\logs\robocopy_report.txt
So then just use '-head 25" already!
$value = $array[array_rand($array)];
If you want to ensure they all get called, use super
at all levels.
Just making simple to understand for beginners.
Check your git stash list with below command :
git stash list
And then apply with below command:
git stash apply stash@{n}
For example: I am applying my latest stash(latest is always index {0} on top of the stash list).
git stash apply stash@{0}
I created a jQuery version of PhpMyCoder's answer:
$('form').submit(function( e ) {
if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
//Prevent default and display error
alert("File is wrong type or over 10Mb in size!");
e.preventDefault();
}
});
function get_extension(filename) {
return filename.split('.').pop().toLowerCase();
}
VB
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim result = arr.Where(Function(a) a.Contains("ra")).Select(Function(s) Array.IndexOf(arr, s)).ToArray()
C#
string[] arr = { "ravi", "Kumar", "Ravi", "Ramesh" };
var result = arr.Where(a => a.Contains("Ra")).Select(a => Array.IndexOf(arr, a)).ToArray();
-----Detailed------
Module Module1
Sub Main()
Dim arr() As String = {"ravi", "Kumar", "Ravi", "Ramesh"}
Dim searchStr = "ra"
'Not case sensitive - checks if item starts with searchStr
Dim result1 = arr.Where(Function(a) a.ToLower.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Case sensitive - checks if item starts with searchStr
Dim result2 = arr.Where(Function(a) a.StartsWith(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
'Not case sensitive - checks if item contains searchStr
Dim result3 = arr.Where(Function(a) a.ToLower.Contains(searchStr)).Select(Function(s) Array.IndexOf(arr, s)).ToArray
Stop
End Sub
End Module
You need to call jquery first and then call javascript,as java script depends on jquery, so it should be loaded before javascript and this solved my problem.
Just add box-sizing:
input[type="text"] {
box-sizing: border-box;
}
It can be done using a single line:
perl -pi.back -e 's/oldString/newString/g;' inputFileName
Pay attention that oldString
is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+?
(The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \
, so \[
.
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Duh.... listFiles requires java.io.FileFilter. FileNameExtensionFilter extends javax.swing.filechooser.FileFilter. I solved my problem by implementing an instance of java.io.FileFilter
Edit: I did use something similar to @cFreiner's answer. I was trying to use a Java API method instead of writing my own implementation which is why I was trying to use FileNameExtensionFilter. I have many FileChoosers in my application and have used FileNameExtensionFilters for that and I mistakenly assumed that it was also extending java.io.FileFilter.
Integer Types:
short -> signed short
signed short
unsigned short
int -> signed int
signed int
unsigned int
signed -> signed int
unsigned -> unsigned int
long -> signed long
signed long
unsigned long
Be careful of char:
char (is signed or unsigned depending on the implmentation)
signed char
unsigned char
$this->validate($request,[
'input_field_name'=>'digits_between:2,5',
]);
Try this it will be work
try my code In JavaScript
var settings = {
"url": "https://myinboxhub.co.in/example",
"method": "GET",
"timeout": 0,
"headers": {},
};
$.ajax(settings).done(function (response) {
console.log(response);
if (response.auth) {
console.log('on success');
}
}).fail(function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === '(failed)net::ERR_INTERNET_DISCONNECTED') {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 413) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 405) {
msg = 'Image size is too large.';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
});;
In PHP
header('Content-type: application/json');
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Content-Length, Accept-Encoding");
I could resolve it by overriding Configuration in MyContext through adding connection string to the DbContextOptionsBuilder:
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("DbCoreConnectionString");
optionsBuilder.UseSqlServer(connectionString);
}
}
The answer by Kleist certainly works, but there is an important caveat:
When you write a Makefile
manually, you might generate a SRCS
variable using a function to select all .cpp
and .h
files. If a source file is later added, re-running make
will include it.
However, CMake (with a command like file(GLOB ...)
) will explicitly generate a file list and place it in the auto-generated Makefile
. If you have a new source file, you will need to re-generate the Makefile
by re-running cmake
.
edit: No need to remove the Makefile.
You can do it with anchor tags using css3 :target
pseudo-selector, this selector is going to be triggered when the element with the same id as the hash of the current URL get an match. Example
Knowing this, we can combine this technique with the use of proximity selectors like "+" and "~" to select any other element through the target element who id get match with the hash of the current url. An example of this would be something like what you are asking.
Additionally to the solutions that were suggested in sibling comments, you may change your testing approach a little bit and test not the whole page all at once (with a deep children components tree), but do an isolated component testing. This will simplify testing of onClick()
and similar events (see example below).
The idea is to test only one component at a time and not all of them together. In this case all children components will be mocked using the jest.mock() function.
Here is an example of how the onClick()
event may be tested in an isolated SearchForm
component using Jest and react-test-renderer.
import React from 'react';
import renderer from 'react-test-renderer';
import { SearchForm } from '../SearchForm';
describe('SearchForm', () => {
it('should fire onSubmit form callback', () => {
// Mock search form parameters.
const searchQuery = 'kittens';
const onSubmit = jest.fn();
// Create test component instance.
const testComponentInstance = renderer.create((
<SearchForm query={searchQuery} onSearchSubmit={onSubmit} />
)).root;
// Try to find submit button inside the form.
const submitButtonInstance = testComponentInstance.findByProps({
type: 'submit',
});
expect(submitButtonInstance).toBeDefined();
// Since we're not going to test the button component itself
// we may just simulate its onClick event manually.
const eventMock = { preventDefault: jest.fn() };
submitButtonInstance.props.onClick(eventMock);
expect(onSubmit).toHaveBeenCalledTimes(1);
expect(onSubmit).toHaveBeenCalledWith(searchQuery);
});
});
Try using 'Figure.set_size_inches' method, with the extra keyword argument forward=True
. According to the documentation, this should resize the figure window.
Whether that actually happens will depend on the operating system you are using.
you must install opencv-python
pip/pip3 install opencv-python
if you try import opencv-python
, receive error.
Fix this error, use the import cv2
Here is an example using lodash
4.x:
const data = {_x000D_
aaa: 111,_x000D_
abb: 222,_x000D_
bbb: 333_x000D_
};_x000D_
_x000D_
const result = _.pickBy(data, (value, key) => key.startsWith("a"));_x000D_
_x000D_
console.log(result);_x000D_
// Object { aaa: 111, abb: 222 }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>_x000D_
<strong>Open your javascript console to see the output.</strong>
_x000D_
Have you tried height: auto;
on your .container
div?
Here is a fiddle, if you change img height, container height will adjust to it.
EDIT
So if you "can't" change the inline min-height
, you can overwrite the inline style with an !important
parameter. It's not the cleanest way, but it solves your problem.
add to your .container
class this line
min-height:0px !important;
I've updated my fiddle to give you an example.
//create TreeMap instance
TreeMap treeMap = new TreeMap();
//add key value pairs to TreeMap
treeMap.put("1","One");
treeMap.put("2","Two");
treeMap.put("3","Three");
/*
get Collection of values contained in TreeMap using
Collection values()
*/
Collection c = treeMap.values();
//obtain an Iterator for Collection
Iterator itr = c.iterator();
//iterate through TreeMap values iterator
while(itr.hasNext())
System.out.println(itr.next());
or:
for (Map.Entry<K,V> entry : treeMap.entrySet()) {
V value = entry.getValue();
K key = entry.getKey();
}
or:
// Use iterator to display the keys and associated values
System.out.println("Map Values Before: ");
Set keys = map.keySet();
for (Iterator i = keys.iterator(); i.hasNext();) {
Integer key = (Integer) i.next();
String value = (String) map.get(key);
System.out.println(key + " = " + value);
}
This is function with inverted option
It will return:
function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){
$value = $newNumber - $oldNumber;
$change = '';
$sign = '';
$result = 0.00;
if ( $invert ) {
if ( $value > 0 ) {
// going UP
$change = 'up';
$sign = '+';
if ( $oldNumber > 0 ) {
$result = ($newNumber / $oldNumber) * 100;
} else {
$result = 100.00;
}
}elseif ( $value < 0 ) {
// going DOWN
$change = 'down';
//$value = abs($value);
$result = ($oldNumber / $newNumber) * 100;
$result = abs($result);
$sign = '-';
}else {
// no changes
}
}else{
if ( $newNumber > $oldNumber ) {
// increase
$change = 'up';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
}else{
$result = 100.00;
}
$sign = '+';
}elseif ( $oldNumber > $newNumber ) {
// decrease
$change = 'down';
if ( $oldNumber > 0 ) {
$result = ( ( $newNumber / $oldNumber ) - 1 )* 100;
} else {
$result = 100.00;
}
$sign = '-';
}else{
// no change
}
$result = abs($result);
}
$result_formatted = number_format($result, 2);
if ( $invert ) {
if ( $change == 'up' ) {
$change = 'down';
}elseif ( $change == 'down' ) {
$change = 'up';
}else{
//
}
if ( $sign == '+' ) {
$sign = '-';
}elseif ( $sign == '-' ) {
$sign = '+';
}else{
//
}
}
if ( $format ) {
$formatted = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
} else{
$formatted = $result_formatted;
}
return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}
Try this to reload jqGrid with new data
jQuery("#grid").jqGrid('setGridParam',{datatype:'json'}).trigger('reloadGrid');
To rebase the current local tracker branch moving local changes on top of the latest remote state:
$ git fetch && git rebase
More generally, to fast-forward and drop the local changes (hard reset)*:
$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}
to fast-forward and keep the local changes (rebase):
$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}
* - to undo the change caused by unintentional hard reset first do git reflog
, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.
UPDATE t1
SET
t1.a = t2.a,
t1.b = t2.b,
.
.
.
FROM
table1 t1
INNER JOIN table2 t2 ON t1.id=t2.id
You can try this
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
You can call the indexer directly on the datatable variable as well:
var cellValue = dt[i].ColumnName
Here's a different way to do it, but it's only useful if SecondDate is a variable you're passing in:
DateTime startDate = SecondDate.Date;
DateTime endDate = startDate.AddDays(1).AddTicks(-1);
...
e => e.FirstDate.Value >= startDate && e.FirstDate.Value <= endDate
I think that should work
I am amazed by the haphazardness of all of the solutions posted so far.
The one and only proper way to get the root folder of a C# project is to leverage the [CallerFilePath]
attribute to obtain the full path name of a source file, and then subtract the filename plus extension from it, leaving you with the path to the project.
Here is how to actually do it:
In the root folder of your project, add a file with the following content:
internal static class ProjectSourcePath
{
private const string myRelativePath = nameof(ProjectSourcePath) + ".cs";
private static string? lazyValue;
public static string Value => lazyValue ??= calculatePath();
private static string calculatePath()
{
string pathName = GetSourceFilePathName();
Assert( pathName.EndsWith( myRelativePath, Sys.StringComparison.Ordinal ) );
return pathName.Substring( 0, pathName.Length - myRelativePath.Length ) );
}
}
The string?
requires a pretty late version of C# with #nullable enable
; if you don't have it, then just remove the ?
.
The Assert()
function is my own, replace it with your own.
The function GetSourceFilePathName()
is defined as follows:
using System.Runtime.CompilerServices
public static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) //
=> callerFilePath ?? "";
Once you have this, you can use it as follows:
string projectSourcePath = ProjectSourcePath.Value;
Actually, I figured out what's wrong. For the code to work the page <head>
should have this tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
Or, as suggested in comments, if server sends HTTP Content-Encoding
header, it should work as well.
Then results from different browsers are consistent.
Here is an example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mini string length test</title>
</head>
<body>
<script type="text/javascript">
document.write('<div style="font-size:100px">'
+ (unescape(encodeURIComponent("???! Naïve?")).length) + '</div>'
);
</script>
</body>
</html>
Note: I suspect that specifying any (accurate) encoding would fix the encoding problem. It is just a coincidence that I need UTF-8.
Enclose Link component inside BrowserRouter component
export default () => (
<div>
<h1>
<BrowserRouter>
<Link to="/">Redux example</Link>
</BrowserRouter>
</h1>
</div>
)
Remove column constraint: not null
to null
ALTER TABLE test ALTER COLUMN column_01 DROP NOT NULL;
Now java 9 has factory Methods for Immutable List, Set, Map and Map.Entry .
In Java SE 8 and earlier versions, We can use Collections class utility methods like unmodifiableXXX to create Immutable Collection objects.
However these Collections.unmodifiableXXX methods are very tedious and verbose approach. To overcome those shortcomings, Oracle corp has added couple of utility methods to List, Set and Map interfaces.
Now in java 9 :- List and Set interfaces have “of()” methods to create an empty or no-empty Immutable List or Set objects as shown below:
Empty List Example
List immutableList = List.of();
Non-Empty List Example
List immutableList = List.of("one","two","three");
You must use prefix "php5.6-" instead of "php5-" as in ubuntu 14.04 and olders:
sudo apt-get install php5.6 php5.6-mcrypt
I used the above answer but made use of the RefreshAll method. I also changed it to allow for multiple connections without having to specify the names. I then linked this to a button on my spreadsheet.
Sub Refresh()
Dim conn As Variant
For Each conn In ActiveWorkbook.Connections
conn.ODBCConnection.BackgroundQuery = False
Next conn
ActiveWorkbook.RefreshAll
End Sub
No need to use str.replace
or string.replace
here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr
version of the above string, that's why you're seeing \\
here.
But, in fact the actual string contains just '\'
not \\
.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\'
in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\'
during print
then use str.replace
:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr
version will now show \\\\
:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
You can try if(typeof object !== 'undefined')
<http pattern="/resources/**" security="none"/>
Or with Java configuration:
web.ignoring().antMatchers("/resources/**");
Instead of the old:
<intercept-url pattern="/resources/**" filters="none"/>
for exp . disable security for a login page :
<intercept-url pattern="/login*" filters="none" />
you can use pixels or percent.
<div id="container">
<img id="image" src="...">
</div>
css
#image
{
width:100%;
height:
}
js-xlsx library makes it easy to convert Excel/CSV files into JSON objects.
Download the xlsx.full.min.js file from here. Write below code on your HTML page Edit the referenced js file link (xlsx.full.min.js) and link of Excel file
<!doctype html>
<html>
<head>
<title>Excel to JSON Demo</title>
<script src="xlsx.full.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
var url = "http://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
/* Call XLSX */
var workbook = XLSX.read(bstr, {
type: "binary"
});
/* DO SOMETHING WITH workbook HERE */
var first_sheet_name = workbook.SheetNames[0];
/* Get worksheet */
var worksheet = workbook.Sheets[first_sheet_name];
console.log(XLSX.utils.sheet_to_json(worksheet, {
raw: true
}));
}
oReq.send();
</script>
</body>
</html>
Input:
Output:
I'm also facing the problem that exceeding the stars than specified no of stars. For this, we don't want worry about whatever the layout type either relative or linear layout. Simply use the width as follows:
ratingBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
Please avoid using match_parent and fill_parent for ratingbar.
Hope the things would be helpful.
When you click the Button
if(isset($_POST['save'])){
$sql = "INSERT INTO `members`(`id`, `membership_id`, `email`, `first_name`)
VALUES ('".$_POST["id"]."','".$_POST["membership_id"]."','".$_POST["email"]."','".$_POST["firstname"]."')";
**if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}**
}
This will execute the Query in the variable $sql
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
You can get this error if you use wrong mode when opening the file. For example:
with open(output, 'wb') as output_file:
print output_file.read()
In that code, I want to read the file, but I use mode wb
instead of r
or r+
Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C
looks like this:
<And>
A
<And>
B
C
</And>
</And>
Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):
<Where>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>John</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>John</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>John</Value>
</Eq>
</Or>
</Or>
<And>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>Doe</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>Doe</Value>
</Eq>
</Or>
</Or>
<Or>
<Eq>
<FieldRef Name='FirstName' />
<Value Type='Text'>123</Value>
</Eq>
<Or>
<Eq>
<FieldRef Name='LastName' />
<Value Type='Text'>123</Value>
</Eq>
<Eq>
<FieldRef Name='Profile' />
<Value Type='Text'>123</Value>
</Eq>
</Or>
</Or>
</And>
</And>
</Where>
After the advice here, I have devised the following function in VB which creates passable, although not always perfect (if a company name and a suite line are given, it combines the suite and city) usable data. Please feel free to comment/refactor/yell at me for breaking one of my own rules, etc.:
Public Function parseAddress(ByVal input As String) As Collection
input = input.Replace(",", "")
input = input.Replace(" ", " ")
Dim splitString() As String = Split(input)
Dim streetMarker() As String = New String() {"street", "st", "st.", "avenue", "ave", "ave.", "blvd", "blvd.", "highway", "hwy", "hwy.", "box", "road", "rd", "rd.", "lane", "ln", "ln.", "circle", "circ", "circ.", "court", "ct", "ct."}
Dim address1 As String
Dim address2 As String = ""
Dim city As String
Dim state As String
Dim zip As String
Dim streetMarkerIndex As Integer
zip = splitString(splitString.Length - 1).ToString()
state = splitString(splitString.Length - 2).ToString()
streetMarkerIndex = getLastIndexOf(splitString, streetMarker) + 1
Dim sb As New StringBuilder
For counter As Integer = streetMarkerIndex To splitString.Length - 3
sb.Append(splitString(counter) + " ")
Next counter
city = RTrim(sb.ToString())
Dim addressIndex As Integer = 0
For counter As Integer = 0 To streetMarkerIndex
If IsNumeric(splitString(counter)) _
Or splitString(counter).ToString.ToLower = "po" _
Or splitString(counter).ToString().ToLower().Replace(".", "") = "po" Then
addressIndex = counter
Exit For
End If
Next counter
sb = New StringBuilder
For counter As Integer = addressIndex To streetMarkerIndex - 1
sb.Append(splitString(counter) + " ")
Next counter
address1 = RTrim(sb.ToString())
sb = New StringBuilder
If addressIndex = 0 Then
If splitString(splitString.Length - 2).ToString() <> splitString(streetMarkerIndex + 1) Then
For counter As Integer = streetMarkerIndex To splitString.Length - 2
sb.Append(splitString(counter) + " ")
Next counter
End If
Else
For counter As Integer = 0 To addressIndex - 1
sb.Append(splitString(counter) + " ")
Next counter
End If
address2 = RTrim(sb.ToString())
Dim output As New Collection
output.Add(address1, "Address1")
output.Add(address2, "Address2")
output.Add(city, "City")
output.Add(state, "State")
output.Add(zip, "Zip")
Return output
End Function
Private Function getLastIndexOf(ByVal sArray As String(), ByVal checkArray As String()) As Integer
Dim sourceIndex As Integer = 0
Dim outputIndex As Integer = 0
For Each item As String In checkArray
For Each source As String In sArray
If source.ToLower = item.ToLower Then
outputIndex = sourceIndex
If item.ToLower = "box" Then
outputIndex = outputIndex + 1
End If
End If
sourceIndex = sourceIndex + 1
Next
sourceIndex = 0
Next
Return outputIndex
End Function
Passing the parseAddress
function "A. P. Croll & Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947" returns:
2299 Lewes-Georgetown Hwy A. P. Croll & Son Georgetown DE 19947
The import line should be:
import React, { Component } from 'react';
Note the uppercase R for React.
Simple Solution, use methods that Android has already given, rather than reinventing wheeeeeeeeeel :-)
editComment.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int DRAWABLE_LEFT = 0;
final int DRAWABLE_TOP = 1;
final int DRAWABLE_RIGHT = 2;
final int DRAWABLE_BOTTOM = 3;
if(event.getAction() == MotionEvent.ACTION_UP) {
if(event.getRawX() >= (editComment.getRight() - editComment.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
// your action here
return true;
}
}
return false;
}
});
Non-javascript way . . aspx page:
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1"
runat="server" ErrorMessage="CustomValidator" ControlToValidate="CheckBox1"></asp:CustomValidator>
</div>
</form>
Code Behind:
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
If Not CheckBox1.Checked Then
args.IsValid = False
End If
End Sub
For any actions you might need (business Rules):
If Page.IsValid Then
'do logic
End If
Sorry for the VB code . . . you can convert it to C# if that is your pleasure. The company I am working for right now requires VB :(
I normally use Emacs (it has everything you need included).
Of course, there are other options available:
Cheers.
Use the .readline()
method (Python 2 docs, Python 3 docs):
with open('myfile.txt') as f:
first_line = f.readline()
Some notes:
f.readline()
will contain a trailing newline. You may wish to use f.readline().strip()
instead to remove the newline.with
statement automatically closes the file again when the block ends.with
statement only works in Python 2.5 and up, and in Python 2.5 you need to use from __future__ import with_statement
I got the same problem while running unit tests. I found this workaround solution:
The following workaround allows to get rid of this message:
File workaround = new File(".");
System.getProperties().put("hadoop.home.dir", workaround.getAbsolutePath());
new File("./bin").mkdirs();
new File("./bin/winutils.exe").createNewFile();
I was also having the same problem. I tried the following and it's working for me now:
Please try the following steps:
Go to..
File > Settings > Appearance & Behavior > System Settings > HTTP Proxy [Under IDE Settings] Enable following option Auto-detect proxy settings
On Mac it's under:
Android Studio > Preferences > Appearance & Behaviour... etc
you can also use the test connection button and check with google.com to see if it works or not.
"So does it mean definition equals declaration plus initialization."
Not necessarily, your declaration might be without any variable being initialized like:
void helloWorld(); //declaration or Prototype.
void helloWorld()
{
std::cout << "Hello World\n";
}
Probably, the fastest, efficient and more generic way is this (you can merge any number of objects and even copy to the first one ->assign):
function object_merge(){
for (var i=1; i<arguments.length; i++)
for (var a in arguments[i])
arguments[0][a] = arguments[i][a];
return arguments[0];
}
It also allows you to modify the first object as it passed by reference. If you don't want this but want to have a completely new object containing all properties, then you can pass {} as the first argument.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge(object1,object2,object3);
combined_object and object1 both contain the properties of object1,object2,object3.
var object1={a:1,b:2};
var object2={c:3,d:4};
var object3={d:5,e:6};
var combined_object=object_merge({},object1,object2,object3);
In this case, the combined_object contains the properties of object1,object2,object3 but object1 is not modified.
Check here: https://jsfiddle.net/ppwovxey/1/
Note: JavaScript objects are passed by reference.
If the order is not important, I prefer this style:
for(var i = array.length; i--; )
It caches the length and is much shorter to write. But it will iterate over the array in reverse order.
I want to extend Olcay's nice answer. His approach is good, your login page controller should be like this to put the referrer url into session:
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(HttpServletRequest request, Model model) {
String referrer = request.getHeader("Referer");
request.getSession().setAttribute("url_prior_login", referrer);
// some other stuff
return "login";
}
And you should extend SavedRequestAwareAuthenticationSuccessHandler
and override its onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
method. Something like this:
public class MyCustomLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
public MyCustomLoginSuccessHandler(String defaultTargetUrl) {
setDefaultTargetUrl(defaultTargetUrl);
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
HttpSession session = request.getSession();
if (session != null) {
String redirectUrl = (String) session.getAttribute("url_prior_login");
if (redirectUrl != null) {
// we do not forget to clean this attribute from session
session.removeAttribute("url_prior_login");
// then we redirect
getRedirectStrategy().sendRedirect(request, response, redirectUrl);
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
} else {
super.onAuthenticationSuccess(request, response, authentication);
}
}
}
Then, in your spring configuration, you should define this custom class as a bean and use it on your security configuration. If you are using annotation config, it should look like this (the class you extend from WebSecurityConfigurerAdapter
):
@Bean
public AuthenticationSuccessHandler successHandler() {
return new MyCustomLoginSuccessHandler("/yourdefaultsuccessurl");
}
In configure
method:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// bla bla
.formLogin()
.loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(successHandler())
.permitAll()
// etc etc
;
}
This method might not be the most efficient but is simple and does the job.
It performs two operations: firstly it calls .ToString() which is basiclly a serialization, and then the deserialization using Newtonsoft nuget (which you must install).
public T Format<T>(Object obj) =>
JsonConvert.DeserializeObject<T>(obj.ToString());
Warnings are annoying. As mentioned in other answers, you can suppress them using:
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:
import warnings
warnings.filterwarnings("error")
But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:
import warnings
warnings.simplefilter(action='error', category=FutureWarning)
Java 8 user can do that: list.removeIf(...)
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.removeIf(e -> (someCondition));
It will remove elements in the list, for which someCondition is satisfied
The error you have is because -credential
without -computername
can't exist.
You can try this way:
Invoke-Command -Credential $migratorCreds -ScriptBlock ${function:Get-LocalUsers} -ArgumentList $xmlPRE,$migratorCreds -computername YOURCOMPUTERNAME
I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.
There is an additional reason, which no one else has mentioned, why you might choose to create your object dynamically. Dynamic, heap based objects allow you to make use of polymorphism.
Taking a uniform random variable as the value of RGB may generate a large amount of gray, white, and black, which are often not the colors we want.
The cv::applyColorMap
can easily generate a random RGB palette, and you can choose a favorite color map from the list here
Example for C++11:
#include <algorithm>
#include <numeric>
#include <random>
#include <opencv2/opencv.hpp>
std::random_device rd;
std::default_random_engine re(rd());
// Generating randomized palette
cv::Mat palette(1, 255, CV_8U);
std::iota(palette.data, palette.data + 255, 0);
std::shuffle(palette.data, palette.data + 255, re);
cv::applyColorMap(palette, palette, cv::COLORMAP_JET);
// ...
// Picking random color from palette and drawing
auto randColor = palette.at<cv::Vec3b>(i % palette.cols);
cv::rectangle(img, cv::Rect(0, 0, 100, 100), randColor, -1);
Example for Python3:
import numpy as np, cv2
palette = np.arange(0, 255, dtype=np.uint8).reshape(1, 255, 1)
palette = cv2.applyColorMap(palette, cv2.COLORMAP_JET).squeeze(0)
np.random.shuffle(palette)
# ...
rand_color = tuple(palette[i % palette.shape[0]].tolist())
cv2.rectangle(img, (0, 0), (100, 100), rand_color, -1)
If you don't need so many colors, you can just cut the palette to the desired length.
ESP
is the current stack pointer, which will change any time a word or address is pushed or popped onto/off off the stack. EBP
is a more convenient way for the compiler to keep track of a function's parameters and local variables than using the ESP
directly.
Generally (and this may vary from compiler to compiler), all of the arguments to a function being called are pushed onto the stack by the calling function (usually in the reverse order that they're declared in the function prototype, but this varies). Then the function is called, which pushes the return address (EIP
) onto the stack.
Upon entry to the function, the old EBP
value is pushed onto the stack and EBP
is set to the value of ESP
. Then the ESP
is decremented (because the stack grows downward in memory) to allocate space for the function's local variables and temporaries. From that point on, during the execution of the function, the arguments to the function are located on the stack at positive offsets from EBP
(because they were pushed prior to the function call), and the local variables are located at negative offsets from EBP
(because they were allocated on the stack after the function entry). That's why the EBP
is called the Frame Pointer, because it points to the center of the function call frame.
Upon exit, all the function has to do is set ESP
to the value of EBP
(which deallocates the local variables from the stack, and exposes the entry EBP
on the top of the stack), then pop the old EBP
value from the stack, and then the function returns (popping the return address into EIP
).
Upon returning back to the calling function, it can then increment ESP
in order to remove the function arguments it pushed onto the stack just prior to calling the other function. At this point, the stack is back in the same state it was in prior to invoking the called function.
@Html.Partial("NameOfPartialView")
Very well done and answered here - http://www.sitepoint.com/css3-transform-background-image/
#myelement:before
{
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(background.png) 0 0 repeat;
-webkit-transform: rotate(30deg);
-moz-transform: rotate(30deg);
-ms-transform: rotate(30deg);
-o-transform: rotate(30deg);
transform: rotate(30deg);
}
Just try this in Javascript:
$previous = "javascript:history.go(-1)";
Or you can try it in PHP:
if(isset($_SERVER['HTTP_REFERER'])) {
$previous = $_SERVER['HTTP_REFERER'];
}
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
Update for Django 1.10+:
is_authenticated
is now an attribute in Django 1.10.
The method was removed in Django 2.0.
For Django 1.9 and older:
is_authenticated
is a function. You should call it like
if request.user.is_authenticated():
# do something if the user is authenticated
As Peter Rowell pointed out, what may be tripping you up is that in the default Django template language, you don't tack on parenthesis to call functions. So you may have seen something like this in template code:
{% if user.is_authenticated %}
However, in Python code, it is indeed a method in the User
class.
You can use PostgreSQL's interactive terminal Psql to show tables in PostgreSQL.
1. Start Psql
Usually you can run the following command to enter into psql:
psql DBNAME USERNAME
For example, psql template1 postgres
One situation you might have is: suppose you login as root, and you don't remember the database name. You can just enter first into Psql by running:
sudo -u postgres psql
In some systems, sudo command is not available, you can instead run either command below:
psql -U postgres
psql --username=postgres
2. Show tables
Now in Psql you could run commands such as:
\?
list all the commands\l
list databases\conninfo
display information about current connection\c [DBNAME]
connect to new database, e.g., \c template1
\dt
list tables of the public schema\dt <schema-name>.*
list tables of certain schema, e.g., \dt public.*
\dt *.*
list tables of all schemasSELECT * FROM my_table;
(Note: a statement must be terminated with semicolon ;
)\q
quit psqlThe runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:
Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished
This is how I did it in 2021
Let us say I have a csv sales.csv
which has the following data in it:
sales.csv:
Order Name,Price,Qty
oil,200,2
butter,180,10
and to add more rows I can load them in a data frame and append it to the csv like this:
import pandas
data = [
['matchstick', '60', '11'],
['cookies', '10', '120']
]
dataframe = pandas.DataFrame(data)
dataframe.to_csv("sales.csv", index=False, mode='a', header=False)
and the output will be:
Order Name,Price,Qty
oil,200,2
butter,180,10
matchstick,60,11
cookies,10,120
I use RStudio or Emacs and always use the editor shortcuts available to comment regions. If this is not a possibility then you could use Paul's answer but this only works if your code is syntactically correct.
Here is another dirty way I came up with, wrap it in scan()
and remove the result. It does store the comment in memory for a short while so it will probably not work with very large comments. Best still is to just put #
signs in front of every line (possibly with editor shortcuts).
foo <- scan(what="character")
These are comments
These are still comments
Can also be code:
x <- 1:10
One line must be blank
rm(foo)
Setting 700 to .ssh and 600 to authorized_keys solved the issue.
chmod 700 /root/.ssh
chmod 600 /root/.ssh/authorized_keys
It is up to you. Just use the commit message as you wish. But it is easier if you are not switching between times and languages.
And if you develop in a team - it should be discussed and set fixed.
For client side files, you cannot get a list of files in a user's local directory.
If the user has provided uploaded files, you can access them via their input
element.
<input type="file" name="client-file" id="get-files" multiple />
<script>
var inp = document.getElementById("get-files");
// Access and handle the files
for (i = 0; i < inp.files.length; i++) {
let file = inp.files[i];
// do things with file
}
</script>
Please also check your encoding: Google encodes spaces as +
instead of %20
. This may result in an invalid image link.
At first glance one really wants to use New-PSDrive
supplying it credentials.
> New-PSDrive -Name P -PSProvider FileSystem -Root \\server\share -Credential domain\user
New-PSDrive : Cannot retrieve the dynamic parameters for the cmdlet. Dynamic parameters for NewDrive cannot be retrieved for the 'FileSystem' provider. The provider does not support the use of credentials. Please perform the operation again without specifying credentials.
The documentation states that you can provide a PSCredential
object but if you look closer the cmdlet does not support this yet. Maybe in the next version I guess.
Therefore you can either use net use
or the WScript.Network
object, calling the MapNetworkDrive
function:
$net = new-object -ComObject WScript.Network
$net.MapNetworkDrive("u:", "\\server\share", $false, "domain\user", "password")
Apparently with newer versions of PowerShell, the New-PSDrive
cmdlet works to map network shares with credentials!
New-PSDrive -Name P -PSProvider FileSystem -Root \\Server01\Public -Credential user\domain -Persist
Try to generate the proxy class via SvcUtil.exe with command
Syntax:
svcutil.exe /language:<type> /out:<name>.cs /config:<name>.config http://<host address>:<port>
Example:
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceSamples/myService1
To check if service is available try in your IE URL from example upon without myService1 postfix
We can use splatting for this:
& $command @args
where @args
(automatic variable $args) is splatted into array of parameters.
Under PS, 5.1
My guess is that in your DOM-only solution you did something like:
var script = document.createElement('script');
script.src = something;
//do stuff with the script
First of all, that won't work because the script is not added to the document tree, so it won't be loaded. Furthermore, even when you do, execution of javascript continues while the other script is loading, so its content will not be available to you until that script is fully loaded.
You can listen to the script's load
event, and do things with the results as you would. So:
var script = document.createElement('script');
script.onload = function () {
//do stuff with the script
};
script.src = something;
document.head.appendChild(script); //or something of the likes
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear
getYear
is no longer used and has been replaced by thegetFullYear
method.The
getYear
method returns the year minus 1900; thus:
- For years greater than or equal to 2000, the value returned by
getYear
is 100 or greater. For example, if the year is 2026,getYear
returns 126.- For years between and including 1900 and 1999, the value returned by
getYear
is between 0 and 99. For example, if the year is 1976,getYear
returns 76.- For years less than 1900, the value returned by
getYear
is less than 0. For example, if the year is 1800,getYear
returns -100.- To take into account years before and after 2000, you should use
getFullYear
instead ofgetYear
so that the year is specified in full.
If you're on OpenWrt or using some old version of wget which doesn't gives you -i
option:
#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
wget $line
done < "$input"
Furthermore, if you don't have wget
, you can use curl
or whatever you use for downloading individual files.
sdk.dir didn't work for me because I had ANDROID_HOME environment variable with wrong path. So, solution is just to update ANDROID_HOME or remove it to use local.properties.
Android Studio restart is required after the change.
You might need to Deserialize your anonymous JSON type from the request body.
var jsonBody = HttpContext.Request.Content.ReadAsStringAsync().Result;
ScoreInputModel myDeserializedClass = JsonConvert.DeserializeObject<ScoreInputModel>(jsonBody);
Checkout this screen cast about finding memory leaks with JProfiler. It's visual explanation of @Dima Malenko Answer.
Note: Though JProfiler is not freeware, But Trial version can deal with current situation.
You use break break out of a loop or a switch statement.
You use return in the function to return a value. Return statement ends the function and returns control to where the function was called.
I think you will need to edit the doxys file and set GENERATE_UML (something like that) to true. And you need to have dot/graphviz installed.
When I received this error, I had a "helper" class that I did not declare as public that caused this issue inside of the class that used the "helper" class. Making the "helper" class public solved this error, as in:
public ServiceClass { public ServiceClass(HelperClass _helper) { } }
public class HelperClass {} // Note the public HelperClass that solved my issue.
This may help someone else who encounters this.
Add this to your .emacs file:
This will set the width that a tab is displayed to 2 characters (change the number 2 to whatever you want)
(setq default-tab-width 2)
To make sure that emacs is actually using tabs instead of spaces:
(global-set-key (kbd "TAB") 'self-insert-command)
As an aside, the default for emacs when backspacing over a tab is to convert it to spaces and then delete a space. This can be annoying. If you want it to just delete the tab, you can do this:
(setq c-backspace-function 'backward-delete-char)
Enjoy!
You can use object-fit
css3 property, something like
<!doctype html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset='utf-8'>_x000D_
<style>_x000D_
.holder {_x000D_
display: inline;_x000D_
}_x000D_
.holder img {_x000D_
max-height: 200px;_x000D_
max-width: 200px;_x000D_
object-fit: cover;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class='holder'>_x000D_
<img src='meld.png'>_x000D_
</div>_x000D_
<div class='holder'>_x000D_
<img src='twiddla.png'>_x000D_
</div>_x000D_
<div class='holder'>_x000D_
<img src='meld.png'>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
It is not exactly your answer, though, because of it doesn't stretch the container, but it behaves like the gallery and you can keep styling the img
itself.
Another drawback of this solution is still a poor support of the css3 property. More details are available here: http://www.steveworkman.com/html5-2/javascript/2012/css3-object-fit-polyfill/. jQuery solution can be found there as well.
You can create a function:
function changeInputType(oldObj, oTyp, nValue) {
var newObject = document.createElement('input');
newObject.type = oTyp;
if(oldObj.size) newObject.size = oldObj.size;
if(oldObj.value) newObject.value = nValue;
if(oldObj.name) newObject.name = oldObj.name;
if(oldObj.id) newObject.id = oldObj.id;
if(oldObj.className) newObject.className = oldObj.className;
oldObj.parentNode.replaceChild(newObject,oldObj);
return newObject;
}
And you do a call like:
changeInputType(document.getElementById('DATE_RANGE_VALUE'), 'checkbox', 7);
I'm detecting the back button by this way:
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
It works but I have to create a cookie in Chrome to detect that i'm in the page on first time because when i enter in the page without control by cookie, the browser do the back action without click in any back button.
if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null);
window.onpopstate = function () {
if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null )
{
addCookie('cookieChrome',1, 1440);
}
else
{
history.pushState('newjibberish', null, null);
}
};
}
AND VERY IMPORTANT, history.pushState("jibberish", null, null);
duplicates the browser history.
Some one knows who can i fix it?
I don't understand why nobody points to the specific issue and some answers are totally misleading, especially the accepted answer. The issue is that the OP did not pick a rule that could possibly override the margin property that is set by the User Agent (UA) directly on the ul
tag. Let's consider all the rules with a margin property used by the OP.
body {
margin:0px;
...
}
The body element is way up in the DOM and the UA rule matches an element below, so the UA wins. It's the way inheritance works. Inheritance is the means by which, in the absence of any specific declarations from any source applied by the CSS cascade, a property value of an element is obtained from its parent element. Specificity on the parent element is useless, because the UA rule matches directly the element.
#mainNav{
margin:0 auto;
...
}
This is a better attempt, a more specific selector #mainNav
, which matches the mainNav element lower in the DOM, but the same principle applies, because the ul
element is still below this element in the DOM.
#mainNav ul li{
...
margin:0;
...
}
This went too far down in the DOM! Now, the selector matches the li
element, which is below the ul
element.
So, assuming that the UA rule used the selector ul
and not !important
, which is most likely the case, the solution would have been a simple ul { margin: 0; }
, but it would be safer to make it more specific, say #mainNav ul { margin: 0 }
.
Your condition id !== 0
will always be different that zero because you are assigning a string value. On pages where the element with id views_slideshow_controls_text_next_slideshow-block
is not found, you will still try to append the img element, which causes the Cannot read property 'appendChild' of null
error.
Instead of assigning a string value, you can assign the DOM element and verify if it exists within the page.
window.onload = function loadContIcons() {
var elem = document.createElement("img");
elem.src = "http://arno.agnian.com/sites/all/themes/agnian/images/up.png";
elem.setAttribute("class", "up_icon");
var container = document.getElementById("views_slideshow_controls_text_next_slideshow-block");
if (container !== null) {
container.appendChild(elem);
} else console.log("aaaaa");
var elem1 = document.createElement("img");
elem1.src = "http://arno.agnian.com/sites/all/themes/agnian/images/down.png";
elem1.setAttribute("class", "down_icon");
container = document.getElementById("views_slideshow_controls_text_previous_slideshow-block");
if (container !== null) {
container.appendChild(elem1);
} else console.log("aaaaa");
}
Just another option, which I wrote:
Not sure if it'll help, but I've found it useful in several projects - looks like it'll do what you need.
Supports date/time formatting, date math (add/subtract date parts), date compare, date parsing, etc. It's liberally open sourced.
No reason to consider it if you're already using a framework (they're all capable), but if you just need to quickly add date manipulation to a project give it a chance.
Storing a list of object instances is very simple
class MyClass(object):
def __init__(self, number):
self.number = number
my_objects = []
for i in range(100):
my_objects.append(MyClass(i))
# later
for obj in my_objects:
print obj.number
If you are using Mysql with Hibernate v3 it's ok to use GenerationType.AUTO
because internally it will use GenerationType.IDENTITY
, which is the most optimal in for MySQL.
However in Hibernate v5, It has changed. GenerationType.AUTO
will use GenerationType.TABLE
which generates to much queries for the insertion.
You can avoid that using GenerationType.IDENTITY
(if MySQL is the only database you are using) or with these notations (if you have multiple databases):
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
Here's a total, copy and paste solution, with an
of every issue involved.
for the amazing find regarding keyPath statusBarWindow.statusBar
. Good one.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// handle the iOS bar!
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// "Status Bar Style" refers to the >>>>>color of the TEXT<<<<<< of the Apple status bar,
// it does NOT refer to the background color of the bar. This causes a lot of confusion.
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// >>>>>NOTE<<<<<
// our app is white, so we want the Apple bar to be white (with, obviously, black writing)
// make the ultimate window of OUR app actually start only BELOW Apple's bar....
// so, in storyboard, never think about the issue. design to the full height in storyboard.
let h = UIApplication.shared.statusBarFrame.size.height
let f = self.window?.frame
self.window?.frame = CGRect(x: 0, y: h, width: f!.size.width, height: f!.size.height - h)
// next, in your plist be sure to have this: you almost always want this anyway:
// <key>UIViewControllerBasedStatusBarAppearance</key>
// <false/>
// next - very simply in the app Target, select "Status Bar Style" to Default.
// Do nothing in the plist regarding "Status Bar Style" - in modern Xcode, setting
// the "Status Bar Style" toggle simply sets the plist for you.
// finally, method A:
// set the bg of the Apple bar to white. Technique courtesy Warif Akhand Rishi.
// note: self.window?.clipsToBounds = true-or-false, makes no difference in method A.
if let sb = UIApplication.shared.value(forKeyPath: "statusBarWindow.statusBar") as? UIView {
sb.backgroundColor = UIColor.white
// if you prefer a light gray under there...
//sb.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.9, alpha: 1)
}
/*
// if you prefer or if necessary, method B:
// explicitly actually add a background, in our app, to sit behind the apple bar....
self.window?.clipsToBounds = false // MUST be false if you use this approach
let whiteness = UIView()
whiteness.frame = CGRect(x: 0, y: -h, width: f!.size.width, height: h)
whiteness.backgroundColor = UIColor.green
self.window!.addSubview(whiteness)
*/
return true
}
You could create a razor file in the App_Code folder and then access it from your view pages.
Project>Repository/IdentityRepository.cs
namespace Infrastructure.Repository
{
public class IdentityRepository : IIdentityRepository
{
private readonly ISystemSettings _systemSettings;
private readonly ISessionDataManager _sessionDataManager;
public IdentityRepository(
ISystemSettings systemSettings
)
{
_systemSettings = systemSettings;
}
public string GetCurrentUserName()
{
return HttpContext.Current.User.Identity.Name;
}
}
}
Project>App_Code/IdentityRepositoryViewFunctions.cshtml:
@using System.Web.Mvc
@using Infrastructure.Repository
@functions
{
public static IIdentityRepository IdentityRepositoryInstance
{
get { return DependencyResolver.Current.GetService<IIdentityRepository>(); }
}
public static string GetCurrentUserName
{
get
{
var identityRepo = IdentityRepositoryInstance;
if (identityRepo != null)
{
return identityRepo.GetCurrentUserName();
}
return null;
}
}
}
Project>Views/Shared/_Layout.cshtml (or any other .cshtml file)
<div>
@IdentityRepositoryViewFunctions.GetCurrentUserName
</div>
In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).
ReducedForm
is a type, so you cannot say
ReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
You can only use the .
operator on an instance:
ReducedForm rf;
rf.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
Function imageMorph
will create a new img element therefore the id is removed.
Changed to
$("#wrapper > img")
You should use live() function for click event if you want you rocket lanch again.
Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/
You are looking for the insert
function, found in the table
section of the main library.
foo = {}
table.insert(foo, "bar")
table.insert(foo, "baz")
HTML CODE
<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>
<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>
JS CODE
function checkPass(){
var pass = document.getElementById("password").value;
var rpass = document.getElementById("rpassword").value;
if(pass != rpass){
document.getElementById("submit").disabled = true;
$('.missmatch').html("Entered Password is not matching!! Try Again");
}else{
$('.missmatch').html("");
document.getElementById("submit").disabled = false;
}
}
Laravel Server Requirements mention that BCMath
, Ctype
, JSON
, Mbstring
, OpenSSL
, PDO
, Tokenizer
, and XML
extensions are required. Most of the extensions are installed and enabled by default.
You can run the following command in Ubuntu to make sure the extensions are installed.
sudo apt install openssl php-common php-curl php-json php-mbstring php-mysql php-xml php-zip
PHP version specific installation (if PHP 7.4 installed)
sudo apt install php7.4-common php7.4-bcmath openssl php7.4-json php7.4-mbstring
You may need other PHP extensions for your composer packages. Find from links below.
PHP extensions for Ubuntu 20.04 LTS (Focal Fossa)
PHP extensions for Ubuntu 18.04 LTS (Bionic)
PHP extensions for Ubuntu 16.04 LTS (Xenial)
You're using smart quotes. That is, instead of standard quotation marks ("
), you are using curly quotes (”
). This happens automatically with Microsoft Word and other word processors to make things look prettier, but it also mangles HTML. Make sure to code in a plain text editor, like Notepad or Notepad2.
<html>
<head>
<title>HTML in 10 Simple Steps or Less</title>
<meta http-equiv="refresh" content="5"> <!-- See the difference? -->
</head>
<body>
</body>
</html>
If you want a flat list of all paths under a given dir (like find .
in the shell):
files = [
os.path.join(parent, name)
for (parent, subdirs, files) in os.walk(YOUR_DIRECTORY)
for name in files + subdirs
]
To only include full paths to files under the base dir, leave out + subdirs
.
Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.
The bookdown book does a great job of explaining that the best way to include images is by using include_graphics()
. For example, a full width image can be printed with a caption below:
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```
The reason this method is better than the pandoc approach ![your image](path/to/image)
:
fig.width
), the output width in the report (out.width
), add captions (fig.cap
) etc.knitr::kable()
is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.
```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```
If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table
package. It provides a tidy graphical interface for making tables.
Achieving custom styling of the table column width is beyond the scope of knitr
, but the kableExtra
package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html
The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.
If you are looking for potential extensions to the formatting, the bookdown
package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
In general, if you have your coins COIN[] and your "change range" 1..MAX, the following should find the maximum number of coins.
Initialise array CHANGEVAL[MAX] to -1
For each element coin in COIN:
set CHANGEVAL[coin] to 1
Until there are no more -1 in CHANGEVAL:
For each index I over CHANGEVAL:
if CHANGEVAL[I] != -1:
let coincount = CHANGEVAL[I]
For each element coin in COIN:
let sum = coin + I
if (COINS[sum]=-1) OR ((coincount+1)<COINS[sum]):
COINS[sum]=coincount+1
I don't know if the check for coin-minimality in the inner conditional is, strictly speaking, necessary. I would think that the minimal chain of coin-additions would end up being correct, but better safe than sorry.
this works for me every time try this.
echo "<font color='blue'>".$myvariable."</font>";
since font is not supported in html5 you can do this
echo "<p class="variablecolor">".$myvariable."</p>";
then in css do
.variablecolor{
color: blue;}
scp file user@host:/path/on/host
Before going to a command prompt, please follow these steps...
Open My Computer ? double click "C:" drive ? double click "Windows" ? double click "Microsoft.NET" ? double click "Framework" ? Inside this folder, there will be folder(s) like "v1.0.3705" and/or "v2.0.50727" and/or "v3.5" and/or "v4.0.30319".
Your latest .NET version would be in the highest v number folder, so if v4.0.30319 is available that would hold your latest .NET framework. However, the v4.0.30319 does not mean that you have the .NET framework version 4.0. The v4.0.30319 is your Visual C# compiler version, therefore, in order to find the .NET framework version do the following.
Go to a command prompt and follow this path:
C:\Windows\Microsoft.NET\Framework\v4.0.30319 (or whatever the highest v number folder)
C:\Windows\Microsoft.NET\Framework\v4.0.30319 > csc.exe
Output:
Microsoft (R) Visual C# Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5 Copyright (C) Microsoft Corporation. All rights reserved.
Example below:
You need to modify the Starter-Application class as shown below.
@SpringBootApplication
@EnableAutoConfiguration
@ComponentScan(basePackages="com.nice.application")
@EnableJpaRepositories("com.spring.app.repository")
public class InventoryApp extends SpringBootServletInitializer {..........
And update the Controller, Service and Repository packages structure as I mentioned below.
Example: REST-Controller
package com.nice.controller;
--> It has to be modified as
package com.nice.application.controller;
You need to follow proper package structure for all packages which are in Spring Boot MVC flow.
So, If you modify your project bundle package structures correctly then your spring boot app will work correctly.
Another method from PHP's user comments (simplified) and here:
function array_flatten_recursive($array) {
if (!$array) return false;
$flat = array();
$RII = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($RII as $value) $flat[] = $value;
return $flat;
}
The big benefit of this method is that it tracks the depth of the recursion, should you need that while flattening.
This will output:
$array = array(
'A' => array('B' => array( 1, 2, 3)),
'C' => array(4, 5)
);
print_r(array_flatten_recursive($array));
#Returns:
Array (
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
set scrolling="no"
attribute in your iframe.
You're looking for iotop
(assuming you've got kernel >2.6.20 and Python 2.5). Failing that, you're looking into hooking into the filesystem. I recommend the former.
If you use Eclipse Collections you can use the collectIf()
method.
MutableList<Integer> source =
Lists.mutable.with(1, null, 2, null, 3, null, 4, null, 5);
MutableList<String> result = source.collectIf(Objects::nonNull, String::valueOf);
Assert.assertEquals(Lists.immutable.with("1", "2", "3", "4", "5"), result);
It evaluates eagerly and should be a bit faster than using a Stream.
Note: I am a committer for Eclipse Collections.
One bizarre thing is that in Chrome + Firefox, the MOUSE_LEAVE event isn't dispatched for OPAQUE
and TRANSPARENT
.
With WINDOW
it works fine. That one took some time to find out! grr...
(note: jediericb mentioned this bug - which is similar but doesn't mention MOUSE_LEAVE
)
I would use a bound service to do that and communicate with it by implementing a listener in my activity. So if your app implements myServiceListener, you can register it as a listener in your service after you have bound with it, call listener.onUpdateUI from your bound service and update your UI in there!
In tool window bar select Build Variants Change Build Variant from Release to Debug
if your php version is Non-Thread-Safe (nts) you must use php extension with format example: extension=php_cl_dbg_5_2_nts.dll else if your php version is Thread-Safe (ts) you must use php extension with format example: extension=php_cl_dbg_5_2_ts.dll (notice bolded words)
So if get error like above. Firstly, check your PHP version is nts or ts, if is nts.
Then check in php.ini whether has any line like zend_extension_ts="C:\xammp\php\ext\php_dbg.dll-5.2.x" choose right version of php_dbg.dll-5.2.x from it homepage (google for it).
Change from zend_extension_ts to zend_extension_nts.
Hope this help.
You can simply use the CSS visibility: hidden/visible instead of display : none/block
div {
visibility:hidden;
-webkit-transition: opacity 1s ease-out;
-moz-transition: opacity 1s ease-out;
-o-transition: opacity 1s ease-out;
transition: opacity 1s ease-out;
opacity: 0;
}
parent:hover > div {
opacity: 1;
visibility: visible;
}
The standard solution didn't work for me, when changing the type from TEXT to LONGTEXT.
I had to it like this:
public function up()
{
DB::statement('ALTER TABLE mytable MODIFY mycolumn LONGTEXT;');
}
public function down()
{
DB::statement('ALTER TABLE mytable MODIFY mycolumn TEXT;');
}
This could be a Doctrine issue. More information here.
Another way to do it is to use the string() method, and set the value to the text type max length:
Schema::table('mytable', function ($table) {
// Will set the type to LONGTEXT.
$table->string('mycolumn', 4294967295)->change();
});
in your css file add this....
a:hover {
cursor:pointer;
}
if you don't have a css file, add this to the HEAD of your HTML page
<style type="text/css">
a:hover {
cursor:pointer;
}
</style>
also you can use the href="" attribute by returning false at the end of your javascript.
<a href="" onclick="doSomething(); return false;">a link</a>
this is good for many reasons. SEO or if people don't have javascript, the href="" will work. e.g.
<a href="nojavascriptpage.html" onclick="doSomething(); return false;">a link</a>
@see http://www.alistapart.com/articles/behavioralseparation
Edit: Worth noting @BalusC's answer where he mentions :hover
is not necessary for the OP's use case. Although other style can be add with the :hover
selector.
You've used integers in the expression 7/10, and integer 7 divided by integer 10 is zero.
What you're expecting is floating point division. Any of the following would evaluate the way you expected:
7.0 / 10
7 / 10.0
7.0 / 10.0
7 / (double) 10
Swift3 : heightForHeaderInSection works with 0, you just have to make sure header is set to clipsToBounds.
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
if you don't set clipsToBounds hidden header will be visible when scrolling.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
guard let header = view as? UITableViewHeaderFooterView else { return }
header.clipsToBounds = true
}
I found this site useful: http://www.vanseodesign.com/css/vertical-centering/ This worked for me:
HTML
<div id="parent">
<div id="child">Content here</div>
</div>
CSS
#parent {
padding: 5% 0;
}
#child {
padding: 10% 0;
}
Using javascript you can style the scroll bars. Which works fine in IE as well as FF.
Check the below links
From Twinhelix , Example 2 , Example 3 [or] you can find some 30 type of scroll style types by click the below link 30 scrolling techniques
When compiling with G++, remember to put the -lpthread flag :)
In linux, just run it, no problem. In Windows, you want to use the pythonw executable.
Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?
$ nohup mypythonprog &
C:/> start pythonw mypythonprog
I think that's right. In any case, now you can close the terminal.
Just run command prompt as administrator and type this in.
easy_install python-dateutil
Try this out
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* @param {any} str string to be evaluated
* @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');
Using writeLines also allows you to dispense with the "\n" newline character, by using c()
. As in:
writeLines(c("File not supplied.","Usage: ./program F=filename",[additional text for third line]))
This is helpful if you plan on writing a multiline message with combined fixed and variable input, such as the [additional text for third line] above.
Using strings for concatenation can lead to a runtime complexity on the order of O(n^2)
.
If you use a StringBuilder
, there is a lot less copying of memory that has to be done. With the StringBuilder(int capacity)
you can increase performance if you can estimate how large the final String
is going to be. Even if you're not precise, you'll probably only have to grow the capacity of StringBuilder
a couple of times which can help performance also.
Appears you are having 'y' default to 1: An arrow function would be useful in 2020:
let x = (y = 1) => //insert operation with y here
Let 'x' be a function where 'y' is a parameter which would be assigned a default to '1' if it is some null or undefined value, then return some operation with y.
or use display property with table-cell;
css
.table-layout {
display:table;
width:100%;
}
.table-layout .table-cell {
display:table-cell;
border:solid 1px #ccc;
}
.fixed-width-200 {
width:200px;
}
html
<div class="table-layout">
<div class="table-cell fixed-width-200">
<p>fixed width div</p>
</div>
<div class="table-cell">
<p>fluid width div</p>
</div>
</div>
R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.
Assuming the data shown in your example is in the dataframe df
library(xts)
stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
# daily returns
#
returns <- diff(stocks, arithmetic=FALSE ) - 1
#
# weekly open, high, low, close reports
#
to.weekly(stocks$Hero_close, name="Hero")
which gives the output
Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15 1669.1 1684.45 1669.1 1684.45
2013-03-22 1690.5 1690.50 1623.3 1659.60
2013-03-28 1617.7 1617.70 1542.0 1542.00
According to Opera the CSS3 standard does not define the use of border-radius
on TDs. My experience is that Firefox and Chrome support it but Opera does not (don't know about IE). The workaround is to wrap the td content in a div and then apply the border-radius
to the div.
Look at the dba_blockers
, dba_waiters
and dba_locks
for locking. The names should be self explanatory.
You could create a job that runs, say, once a minute and logged the values in the dba_blockers
and the current active sql_id
for that session. (via v$session
and v$sqlstats
).
You may also want to look in v$sql_monitor
. This will be default log all SQL that takes longer than 5 seconds. It is also visible on the "SQL Monitoring" page in Enterprise Manager.
Perl is weakly typed and context based. Many scalars can be treated both as strings and numbers, depending on the operators you use.
$a = 7*6; $b = 7x6; print "$a $b\n";
You get 42 777777
.
There is a subtle difference, however. When you read numeric data from a text file into a data structure, and then view it with Data::Dumper
, you'll notice that your numbers are quoted. Perl treats them internally as strings.
Read:$my_hash{$1} = $2 if /(.+)=(.+)\n/;
.
Dump:'foo' => '42'
If you want unquoted numbers in the dump:
Read:$my_hash{$1} = $2+0 if /(.+)=(.+)\n/;
.
Dump:'foo' => 42
After $2+0
Perl notices that you've treated $2 as a number, because you used a numeric operator.
I noticed this whilst trying to compare two hashes with Data::Dumper
.
You could try this:
if($(this).is('h1')){
doStuff();
}
See the docs for more on is().
var countries = ['United States', 'Canada', 'Argentina', 'Armenia'];
var cList = $('ul.mylist')
$.each(countries, function(i) {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(cList);
var a = $('<a/>')
.addClass('ui-all')
.text( this )
.appendTo(li);
});
$first_value = reset($array); // First element's value
$first_key = key($array); // First element's key
I found this question as the top result while Googling how to find the owner of a table in Oracle, so I thought that I would contribute a table specific answer for others' convenience.
To find the owner of a specific table in an Oracle DB, use the following query:
select owner from ALL_TABLES where TABLE_NAME ='<MY-TABLE-NAME>';
Activity
is the base class of all other activities, I don't think it will be deprecated. The relationship among them is:
Activity
<- FragmentActivity
<- AppCompatActivity
<- ActionBarActivity
'<-' means inheritance here. The reference said ActionBarActivity
is deprecated, use AppCompatActivity
instead.
So basically, using AppCompatActivity
is always the right choice. The differences between them are:
Activity
is the basic one.Activity
, FragmentActivity
provides the ability to use Fragment
.FragmentActivity
, AppCompatActivity
provides features to ActionBar
.May be use like this
if($match > 0){
$msg = 'Login Complete! Thanks';
echo "<a href='".$link_address."'>link</a>";
}
else{
$msg = 'Login Failed!<br /> Please make sure that you enter the correct details and that you have activated your account.';
}
When FIND
returns #VALUE!
, it is an error, not a string, so you can't compare FIND(...)
with "#VALUE!"
, you need to check if FIND
returns an error with ISERROR
. Also FIND
can work on multiple characters.
So a simplified and working version of your formula would be:
=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))
Or, to remove the double negations:
=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")
Think of it like an archive. MyDB.Bak contains MyDB.mdf and MyDB.ldf.
Restore with Move to say HerDB basically grabs MyDB.mdf (and ldf) from the back up, and copies them as HerDB.mdf and ldf.
So if you already had a MyDb on the server instance you are restoring to it wouldn't be touched.
For comparing to 5 commit to the current one, both on master
, just simply do:
git diff master~5:pom.xml master:pom.xml
Also you can refer to commit hash number, for example if the hash number is x110bd64
, you can do something like this to see the difference:
git diff x110bd64 pom.xml
If you send a PHP array into a function that expects a string like: echo
or print
, then the PHP interpreter will convert your array to the literal string Array
, throw this Notice and keep going. For example:
php> print(array(1,2,3))
PHP Notice: Array to string conversion in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array
In this case, the function print
dumps the literal string: Array
to stdout and then logs the Notice to stderr and keeps going.
Another example in a PHP script:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
$stuff = array(1,2,3);
foreach ($stuff as $value) {
echo $value, "\n";
}
Prints:
1
2
3
Or along with array keys
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
Prints:
name: Joe
email: [email protected]
Note that array elements could be arrays as well. In this case either use foreach
again or access this inner array elements using array syntax, e.g. $row['name']
In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1,2,3
In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);
Prints
{"name":"Joe","email":"[email protected]"}
If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose
examples
$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);
Prints:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}