One option seems to be using CSS to style the textarea
.multi-line { height:5em; width:5em; }
See this entry on SO or this one.
Amurra's accepted answer seems to imply this class is added automatically when using EditorFor but you'd have to verify this.
EDIT: Confirmed, it does. So yes, if you want to use EditorFor, using this CSS style does what you're looking for.
<textarea class="text-box multi-line" id="StoreSearchCriteria_Location" name="StoreSearchCriteria.Location">
Elliot Beach is correct. Thanks Elliot.
Here is the code from my gist.
sudo apt-get remove docker docker-engine docker.io
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl software-properties-common
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo apt-key fingerprint 0EBFCD88
sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
xenial \
stable"
sudo apt-get update
sudo apt-get install docker-ce
sudo docker run hello-world
Decode to Unicode, encode the results to UTF8.
apple.decode('latin1').encode('utf8')
df.index
Index
object. list(df.index)
df.index['Row 2':'Row 5']
Both {} and && will cause problems due to being expanded by the command line. I would suggest trying:
find /home/me/download/ -type f -name "*.rm" -exec ffmpeg -i \{} -sameq \{}.mp3 \; -exec rm \{} \;
WebBrowser1.Document.GetElementById(*element id string*).InvokeMember("submit")
just use echo'd javascript to rid the URL of any variables with a self-submitting, blank form:
<?
if (isset($_GET['your_var'])){
//blah blah blah code
echo "<script type='text/javascript'>unsetter();</script>";
?>
Then make this javascript function:
function unsetter() {
$('<form id = "unset" name = "unset" METHOD="GET"><input type="submit"></form>').appendTo('body');
$( "#unset" ).submit();
}
console.log('Hello, \n' +
'Text under your Header\n' +
'-------------------------\n' +
'More Text\n' +
'Moree Text\n' +
'Moooooer Text\n' );
This works great for me for text only, and easy on the eye.
The issue in my case was I included a constructor taking parameters but not an empty constructor with the Inject annotation, like so.
@Inject public VisitorBean() {}
I just tested it without any constructor and this appears to work also.
I come back to this answer fairly often, though none of these are quite right for me. That said, the right answer for me is a mixture of the others.
What I find works is the following:
git config --global core.eol lf
git config --global core.autocrlf input
For repos that were checked out after those global settings were set, everything will be checked out as whatever it is in the repo – hopefully LF
(\n
). Any CRLF
will be converted to just LF
on checkin.
With an existing repo that you have already checked out – that has the correct line endings in the repo but not your working copy – you can run the following commands to fix it:
git rm -rf --cached .
git reset --hard HEAD
This will delete (rm
) recursively (r
) without prompt (-f
), all files except those that you have edited (--cached
), from the current directory (.
). The reset
then returns all of those files to a state where they have their true line endings (matching what's in the repo).
If you need to fix the line endings of files in a repo, I recommend grabbing an editor that will let you do that in bulk like IntelliJ or Sublime Text, but I'm sure any good one will likely support this.
If you are using custom adapters than android:focusable="false"
and android:focusableInTouchMode="false"
are nessesury to make list items clickable while using checkbox.
<CheckBox
android:id="@+id/checkbox_fav"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/checkbox_layout"/>
In drawable>checkbox_layout.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/uncked_checkbox"
android:state_checked="false"/>
<item android:drawable="@drawable/selected_checkbox"
android:state_checked="true"/>
<item android:drawable="@drawable/uncked_checkbox"/>
</selector>
According to spark documentation "where()
is an alias for filter()
"
filter(condition)
Filters rows using the given condition.
where()
is an alias for filter()
.
Parameters: condition – a Column
of types.BooleanType
or a string of SQL expression.
>>> df.filter(df.age > 3).collect()
[Row(age=5, name=u'Bob')]
>>> df.where(df.age == 2).collect()
[Row(age=2, name=u'Alice')]
>>> df.filter("age > 3").collect()
[Row(age=5, name=u'Bob')]
>>> df.where("age = 2").collect()
[Row(age=2, name=u'Alice')]
You can also try:
NSInteger month = 1;
NSString *inStr = [NSString stringWithFormat: @"%ld", month];
Another possible reason is indirect reference. If a code references to a struct that not included in current c file, the compiler will complain.
a->b->c //error if b not included in current c file
Mr. Curious was curious about this as well. In addition to the #>> '{}'
operator, in 9.6+ one can get the value of a jsonb string with the ->>
operator:
select to_jsonb('Some "text"'::TEXT)->>0;
?column?
-------------
Some "text"
(1 row)
If one has a json value, then the solution is to cast into jsonb first:
select to_json('Some "text"'::TEXT)::jsonb->>0;
?column?
-------------
Some "text"
(1 row)
You can get value
of key
like this...
var obj = {
a: "A",
b: "B",
c: "C"
};
console.log(obj.a);
console.log(obj['a']);
name = "a";
console.log(obj[name])
_x000D_
I am a pragmatist, so I will try to look at this in terms of costs and benefits.
Note that for any disadvantage I give, I recognize that they are solvable. That's why I don't look at anything as black and white, but rather, costs and benefits.
Advantages
Disadvantages
Again, I recognize that every one of these problems is solvable, at some cost. But there comes a point where you are spending all your time solving problems which you could have just avoided in the first place. It comes back to the benefits and how important they are to you.
You can modify a sheet via code by taking these actions
In code this would be:
Sub UnProtect_Modify_Protect()
ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="Password"
'Unprotect
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password"
'Protect
End Sub
The weakness of this method is that if the code is interrupted and error handling does not capture it, the worksheet could be left in an unprotected state.
The code could be improved by taking these actions
The code to do this would be:
Sub Re-Protect_Modify()
ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True
'Protect, even if already protected
ThisWorkbook.ActiveSheet.Range("A1").FormulaR1C1 = "Changed"
'Modify
End Sub
This code renews the protection on the worksheet, but with the ‘UserInterfaceOnly’ set to true. This allows VBA code to modify the worksheet, while keeping the worksheet protected from user input via the UI, even if execution is interrupted.
This setting is lost when the workbook is closed and re-opened. The worksheet protection is still maintained.
So the 'Re-protection' code needs to be included at the start of any procedure that attempts to modify the worksheet or can just be run once when the workbook is opened.
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
Clear improperly cached compile errors.
All Projects Locations in Eclipse
workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\
Add the following to your web.config:
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxQueryString="32768"/>
</requestFiltering>
</security>
</system.webServer>
See:
http://www.iis.net/ConfigReference/system.webServer/security/requestFiltering/requestLimits
Updated to reflect comments.
requestLimits Element for requestFiltering [IIS Settings Schema]
You may have to add the following in your web.config as well
<system.web>
<httpRuntime maxQueryStringLength="32768" maxUrlLength="65536"/>
</system.web>
See: httpRuntime Element (ASP.NET Settings Schema)
Of course the numbers (32768 and 65536) in the config settings above are just examples. You don't have to use those exact values.
<div class="modal fade bs-example-modal-lg" id="{{'modal'+ cartModal.index}}">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
<div class="col-lg-6" >
<p class="prodTitle" ng-bind="(cartModal.product.p_name|uppercase)"></p>
<p class="price-para">
<span class="currency-cls" ng-bind="cartModal.product.c_currency"></span>
<span class="price-cls" ng-bind="cartModal.product.p_price"></span>
</p>
<p class="select-color">
<span ng-repeat="color in cartModal.product.p_available_options.colors">
<button id="color-style" ng-click="cartModal.saveColor(color)" ng-style="{'background-color':color.hexcode}"></button>
</span>
</p>
<br>
<p class="select-box">
<span class="size-select-cls">
SIZE:<select ng-init="items=cartModal.product.p_available_options.sizes" ng-model="cartModal.selectedSize" ng-options="item.code as
item.name for item in items"></select>
</span>
<span class="qty">
QTY:<input type="number" min="1" ng-model="cartModal.selectedQty"/>
</span>
</p>
<p class="edit-button">
<button class="btn-primary btn-lg" data-dismiss="modal" ng-click="cartModal.save();cartModal.calculate()">EDIT</button>
</p>
</div>
<div class="col-lg-6">
<img ng-src="{{cartModal.product.imageSrc}}">
</div>
</div>
</div>
</div>
</div>
given the adjacency matrix:
{0, 1, 3, 4, 0, 0}
{0, 0, 2, 1, 2, 0}
{0, 1, 0, 3, 0, 0}
{0, 1, 1, 0, 0, 1}
{0, 0, 0, 0, 0, 6}
{0, 1, 0, 1, 0, 0}
the following Wolfram Mathematica code solve the problem to find all the simple paths between two nodes of a graph. I used simple recursion, and two global var to keep track of cycles and to store the desired output. the code hasn't been optimized just for the sake of code clarity. the "print" should be helpful to clarify how it works.
cycleQ[l_]:=If[Length[DeleteDuplicates[l]] == Length[l], False, True];
getNode[matrix_, node_]:=Complement[Range[Length[matrix]],Flatten[Position[matrix[[node]], 0]]];
builtTree[node_, matrix_]:=Block[{nodes, posAndNodes, root, pos},
If[{node} != {} && node != endNode ,
root = node;
nodes = getNode[matrix, node];
(*Print["root:",root,"---nodes:",nodes];*)
AppendTo[lcycle, Flatten[{root, nodes}]];
If[cycleQ[lcycle] == True,
lcycle = Most[lcycle]; appendToTree[root, nodes];,
Print["paths: ", tree, "\n", "root:", root, "---nodes:",nodes];
appendToTree[root, nodes];
];
];
appendToTree[root_, nodes_] := Block[{pos, toAdd},
pos = Flatten[Position[tree[[All, -1]], root]];
For[i = 1, i <= Length[pos], i++,
toAdd = Flatten[Thread[{tree[[pos[[i]]]], {#}}]] & /@ nodes;
(* check cycles!*)
If[cycleQ[#] != True, AppendTo[tree, #]] & /@ toAdd;
];
tree = Delete[tree, {#} & /@ pos];
builtTree[#, matrix] & /@ Union[tree[[All, -1]]];
];
];
to call the code: initNode = 1; endNode = 6; lcycle = {}; tree = {{initNode}}; builtTree[initNode, matrix];
paths: {{1}} root:1---nodes:{2,3,4}
paths: {{1,2},{1,3},{1,4}} root:2---nodes:{3,4,5}
paths: {{1,3},{1,4},{1,2,3},{1,2,4},{1,2,5}} root:3---nodes:{2,4}
paths: {{1,4},{1,2,4},{1,2,5},{1,3,4},{1,2,3,4},{1,3,2,4},{1,3,2,5}} root:4---nodes:{2,3,6}
paths: {{1,2,5},{1,3,2,5},{1,4,6},{1,2,4,6},{1,3,4,6},{1,2,3,4,6},{1,3,2,4,6},{1,4,2,5},{1,3,4,2,5},{1,4,3,2,5}} root:5---nodes:{6}
RESULTS:{{1, 4, 6}, {1, 2, 4, 6}, {1, 2, 5, 6}, {1, 3, 4, 6}, {1, 2, 3, 4, 6}, {1, 3, 2, 4, 6}, {1, 3, 2, 5, 6}, {1, 4, 2, 5, 6}, {1, 3, 4, 2, 5, 6}, {1, 4, 3, 2, 5, 6}}
...Unfortunately I cannot upload images to show the results in a better way :(
width
and height
are used when going the css route.
<!DOCTYPE html>
<html>
<head>
<title>Setting Width and Height on Textareas</title>
<style>
.comments { width: 300px; height: 75px }
</style>
</head>
<body>
<textarea class="comments"></textarea>
</body>
</html>
$personCount=1;
while ($personCount < 10) {
$result=0;
$result.= $personCount . "person ";
$personCount++;
echo $result;
}
check your xml file
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" >
**<requestFocus />**
</EditText>
//Remove **<requestFocus />** from xml
It seems as the Chrome debugger loads source files into memory and wont let them go despite of browser cache updates, i.e. it has its own cache apart from the browser cache that is not in sync. At least, this is the case when working with source mapped files (I am debugging typescript sources). After successfully refreshing browser cache and validating that by browsing directly to the source file, you download the updated file, but as soon as you reopen the file in the debugger it will keep returning the old file no matter the version from the ordinary browser cache. Very anoying indeed.
I would consider this a bug in chrome. I use version Version 46.0.2490.71 m.
The only thing that helps, is restarting chrome (close down all chrome browsers).
First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.
Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.
There are various methods to do this depending on your DBMS:
SQL-Server 2008 and later:
SELECT CAST(CURRENT_TIMESTAMP AS DATE)
SQL-Server 2005 and Earlier
SELECT DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)
SQLite
SELECT DATE(NOW())
Oracle
SELECT TRUNC(CURRENT_TIMESTAMP)
Postgresql
SELECT CURRENT_TIMESTAMP::DATE
If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.
Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.
If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)
) before sending to report services and handle it as described above.
If you don't want bars you can plot it like this:
import numpy as np
import matplotlib.pyplot as plt
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()
plt.plot(X,Y)
plt.show()
I think its better to to do text-align center for div and let image take care of the height. Just specify a top and bottom padding for div to have space between image and div. Look at this example: http://jsfiddle.net/Tv9mG/
Instead of concatenating paths like in some answers, I use File.expand_path
:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname
you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where ..
strips the filename of __FILE__
.
In Google Maps API v3 you can try changing marker icon. For example for green icon use:
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
Or as part of marker init:
marker = new google.maps.Marker({
icon: 'http://...'
});
Other colors:
Etc.
You can access values in the $_POST
array by their key. $_POST is an associative array, so to access taskOption
you would use $_POST['taskOption'];
.
Make sure to check if it exists in the $_POST array before proceeding though.
<form method="post" action="process.php">
<select name="taskOption">
<option value="first">First</option>
<option value="second">Second</option>
<option value="third">Third</option>
</select>
<input type="submit" value="Submit the form"/>
</form>
process.php
<?php
$option = isset($_POST['taskOption']) ? $_POST['taskOption'] : false;
if ($option) {
echo htmlentities($_POST['taskOption'], ENT_QUOTES, "UTF-8");
} else {
echo "task option is required";
exit;
}
Neither, because both are quite verbose for a very simple task. You can just do:
let result = ({
1: 'One',
2: 'Two',
3: 'Three'
})[opt] ?? 'Default' // opt can be 1, 2, 3 or anything (default)
This, of course, also works with strings, a mix of both or without a default case:
let result = ({
'first': 'One',
'second': 'Two',
3: 'Three'
})[opt] // opt can be 'first', 'second' or 3
It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.
This returns undefined
if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ??
and return a default value.
console.log('Using a valid case:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[1] ?? 'Default')
console.log('Using an invalid case/defaulting:', ({
1: 'One',
2: 'Two',
3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
If you read through any of the discussions on the android development group you will see that they discourage the use of anything that isn't in the public SDK because the rest is subject to extensive change.
This might work a little better this way
<embed src= "MyHome.pdf" width= "500" height= "375">
If for example your toggle-able icon is visible only for extra small devices, then you could do something like this:
$('[data-toggle="offcanvas"]').click(function () {
$('#side-menu').toggleClass('hidden-xs');
});
Clicking [data-toggle="offcanvas"] will add bootstrap's .hidden-xs to my #side-menu which will hide the side-menu content, but will become visible again if you increase the window size.
LFTP is great, however it is Linux only. You can find the Windows port here. Never tried though.
Achtunq, it uses Cygwin, but everything is included in the bundle.
tr:hover td {background-color:#000;}
Edit your style.xml
with:
<style name="AppTheme" parent="Base.V21.Theme.AppCompat.Light.Dialog">
Base.V21.Theme.AppCompat.Light.Dialog
provides a android poup-up theme
One can access each element of an array separately using the following code:
Object o=...;
if ( o.getClass().isArray() ) {
for(int i=0; i<Array.getLength(o); i++){
System.out.println(Array.get(o, i));
}
}
Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.
try this new DecimalFormat("#.00");
update:
double angle = 20.3034;
DecimalFormat df = new DecimalFormat("#.00");
String angleFormated = df.format(angle);
System.out.println(angleFormated); //output 20.30
Your code wasn't using the decimalformat correctly
The 0 in the pattern means an obligatory digit, the # means optional digit.
update 2: check bellow answer
If you want 0.2677
formatted as 0.27
you should use new DecimalFormat("0.00");
otherwise it will be .27
It's 2019 and you should be using this:
let arr = [...Array(20)].fill(10)
So basically 20
is the length
or a new instantiated Array
.
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
Anyway you need 'Year'.
In some engineering fields, you have fixed day and month and year can be variable. But that day and month are important for beginning calculation without considering which year you are. Your user, for example, only should select a day and a month and providing year is up to you.
You can create a custom combobox using this: Customizable ComboBox Drop-Down.
1- In VS create a user control.
2- See the code in the link above for impelemnting that control.
3- Create another user control and place in it 31 button or label and above them place a label to show months.
4- Place the control in step 3 in your custom combobox.
5- Place the control in setp 4 in step 1.
You now have a control with only days and months. You can use any year that you have in your database or ....
All methods below result in a scale from 0-100.
internal static class ColorDifference
{
internal enum Method
{
Binary, // true or false, 0 is false
Square,
Dimensional,
CIE76
}
public static double Calculate(Method method, int argb1, int argb2)
{
int[] c1 = ColorConversion.ArgbToArray(argb1);
int[] c2 = ColorConversion.ArgbToArray(argb2);
return Calculate(method, c1[1], c2[1], c1[2], c2[2], c1[3], c2[3], c1[0], c2[0]);
}
public static double Calculate(Method method, int r1, int r2, int g1, int g2, int b1, int b2, int a1 = -1, int a2 = -1)
{
switch (method)
{
case Method.Binary:
return (r1 == r2 && g1 == g2 && b1 == b2 && a1 == a2) ? 0 : 100;
case Method.CIE76:
return CalculateCIE76(r1, r2, g1, g2, b1, b2);
case Method.Dimensional:
if (a1 == -1 || a2 == -1) return Calculate3D(r1, r2, g1, g2, b1, b2);
else return Calculate4D(r1, r2, g1, g2, b1, b2, a1, a2);
case Method.Square:
return CalculateSquare(r1, r2, g1, g2, b1, b2, a1, a2);
default:
throw new InvalidOperationException();
}
}
public static double Calculate(Method method, Color c1, Color c2, bool alpha)
{
switch (method)
{
case Method.Binary:
return (c1.R == c2.R && c1.G == c2.G && c1.B == c2.B && (!alpha || c1.A == c2.A)) ? 0 : 100;
case Method.CIE76:
if (alpha) throw new InvalidOperationException();
return CalculateCIE76(c1, c2);
case Method.Dimensional:
if (alpha) return Calculate4D(c1, c2);
else return Calculate3D(c1, c2);
case Method.Square:
if (alpha) return CalculateSquareAlpha(c1, c2);
else return CalculateSquare(c1, c2);
default:
throw new InvalidOperationException();
}
}
// A simple idea, based on on a Square
public static double CalculateSquare(int argb1, int argb2)
{
int[] c1 = ColorConversion.ArgbToArray(argb1);
int[] c2 = ColorConversion.ArgbToArray(argb2);
return CalculateSquare(c1[1], c2[1], c1[2], c2[2], c1[3], c2[3]);
}
public static double CalculateSquare(Color c1, Color c2)
{
return CalculateSquare(c1.R, c2.R, c1.G, c2.G, c1.B, c2.B);
}
public static double CalculateSquareAlpha(int argb1, int argb2)
{
int[] c1 = ColorConversion.ArgbToArray(argb1);
int[] c2 = ColorConversion.ArgbToArray(argb2);
return CalculateSquare(c1[1], c2[1], c1[2], c2[2], c1[3], c2[3], c1[0], c2[0]);
}
public static double CalculateSquareAlpha(Color c1, Color c2)
{
return CalculateSquare(c1.R, c2.R, c1.G, c2.G, c1.B, c2.B, c1.A, c2.A);
}
public static double CalculateSquare(int r1, int r2, int g1, int g2, int b1, int b2, int a1 = -1, int a2 = -1)
{
if (a1 == -1 || a2 == -1) return (Math.Abs(r1 - r2) + Math.Abs(g1 - g2) + Math.Abs(b1 - b2)) / 7.65;
else return (Math.Abs(r1 - r2) + Math.Abs(g1 - g2) + Math.Abs(b1 - b2) + Math.Abs(a1 - a2)) / 10.2;
}
// from:http://stackoverflow.com/questions/9018016/how-to-compare-two-colors
public static double Calculate3D(int argb1, int argb2)
{
int[] c1 = ColorConversion.ArgbToArray(argb1);
int[] c2 = ColorConversion.ArgbToArray(argb2);
return Calculate3D(c1[1], c2[1], c1[2], c2[2], c1[3], c2[3]);
}
public static double Calculate3D(Color c1, Color c2)
{
return Calculate3D(c1.R, c2.R, c1.G, c2.G, c1.B, c2.B);
}
public static double Calculate3D(int r1, int r2, int g1, int g2, int b1, int b2)
{
return Math.Sqrt(Math.Pow(Math.Abs(r1 - r2), 2) + Math.Pow(Math.Abs(g1 - g2), 2) + Math.Pow(Math.Abs(b1 - b2), 2)) / 4.41672955930063709849498817084;
}
// Same as above, but made 4D to include alpha channel
public static double Calculate4D(int argb1, int argb2)
{
int[] c1 = ColorConversion.ArgbToArray(argb1);
int[] c2 = ColorConversion.ArgbToArray(argb2);
return Calculate4D(c1[1], c2[1], c1[2], c2[2], c1[3], c2[3], c1[0], c2[0]);
}
public static double Calculate4D(Color c1, Color c2)
{
return Calculate4D(c1.R, c2.R, c1.G, c2.G, c1.B, c2.B, c1.A, c2.A);
}
public static double Calculate4D(int r1, int r2, int g1, int g2, int b1, int b2, int a1, int a2)
{
return Math.Sqrt(Math.Pow(Math.Abs(r1 - r2), 2) + Math.Pow(Math.Abs(g1 - g2), 2) + Math.Pow(Math.Abs(b1 - b2), 2) + Math.Pow(Math.Abs(a1 - a2), 2)) / 5.1;
}
/**
* Computes the difference between two RGB colors by converting them to the L*a*b scale and
* comparing them using the CIE76 algorithm { http://en.wikipedia.org/wiki/Color_difference#CIE76}
*/
public static double CalculateCIE76(int argb1, int argb2)
{
return CalculateCIE76(Color.FromArgb(argb1), Color.FromArgb(argb2));
}
public static double CalculateCIE76(Color c1, Color c2)
{
return CalculateCIE76(c1.R, c2.R, c1.G, c2.G, c1.B, c2.B);
}
public static double CalculateCIE76(int r1, int r2, int g1, int g2, int b1, int b2)
{
int[] lab1 = ColorConversion.ColorToLab(r1, g1, b1);
int[] lab2 = ColorConversion.ColorToLab(r2, g2, b2);
return Math.Sqrt(Math.Pow(lab2[0] - lab1[0], 2) + Math.Pow(lab2[1] - lab1[1], 2) + Math.Pow(lab2[2] - lab1[2], 2)) / 2.55;
}
}
internal static class ColorConversion
{
public static int[] ArgbToArray(int argb)
{
return new int[] { (argb >> 24), (argb >> 16) & 0xFF, (argb >> 8) & 0xFF, argb & 0xFF };
}
public static int[] ColorToLab(int R, int G, int B)
{
// http://www.brucelindbloom.com
double r, g, b, X, Y, Z, fx, fy, fz, xr, yr, zr;
double Ls, fas, fbs;
double eps = 216.0f / 24389.0f;
double k = 24389.0f / 27.0f;
double Xr = 0.964221f; // reference white D50
double Yr = 1.0f;
double Zr = 0.825211f;
// RGB to XYZ
r = R / 255.0f; //R 0..1
g = G / 255.0f; //G 0..1
b = B / 255.0f; //B 0..1
// assuming sRGB (D65)
if (r <= 0.04045) r = r / 12;
else r = (float)Math.Pow((r + 0.055) / 1.055, 2.4);
if (g <= 0.04045) g = g / 12;
else g = (float)Math.Pow((g + 0.055) / 1.055, 2.4);
if (b <= 0.04045) b = b / 12;
else b = (float)Math.Pow((b + 0.055) / 1.055, 2.4);
X = 0.436052025f * r + 0.385081593f * g + 0.143087414f * b;
Y = 0.222491598f * r + 0.71688606f * g + 0.060621486f * b;
Z = 0.013929122f * r + 0.097097002f * g + 0.71418547f * b;
// XYZ to Lab
xr = X / Xr;
yr = Y / Yr;
zr = Z / Zr;
if (xr > eps) fx = (float)Math.Pow(xr, 1 / 3.0);
else fx = (float)((k * xr + 16.0) / 116.0);
if (yr > eps) fy = (float)Math.Pow(yr, 1 / 3.0);
else fy = (float)((k * yr + 16.0) / 116.0);
if (zr > eps) fz = (float)Math.Pow(zr, 1 / 3.0);
else fz = (float)((k * zr + 16.0) / 116);
Ls = (116 * fy) - 16;
fas = 500 * (fx - fy);
fbs = 200 * (fy - fz);
int[] lab = new int[3];
lab[0] = (int)(2.55 * Ls + 0.5);
lab[1] = (int)(fas + 0.5);
lab[2] = (int)(fbs + 0.5);
return lab;
}
}
Do not include bin in your JAVA_HOME env variable
You need to add the L
character to the end of the number to make Java recognize it as a long.
long i = 12345678910L;
Yes.
See Primitive Data Types which says "An integer literal is of type long if it ends with the letter L or l; otherwise it is of type int."
Use Promises.
var mongoose = require('mongoose');
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
return new Promise(function(resolve, reject) {
var collection = conn.collection(name);
collection.drop(function(err) {
if (err) { return reject(err); }
console.log('dropped ' + name);
resolve();
});
});
});
Promise.all(promises)
.then(function() { console.log('all dropped)'); })
.catch(console.error);
This drops each collection, printing “dropped” after each one, and then prints “all dropped” when complete. If an error occurs, it is displayed to stderr
.
Use Q promises or Bluebird promises.
With Q:
var Q = require('q');
var mongoose = require('mongoose');
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa','bbb','ccc'].map(function(name){
var collection = conn.collection(name);
return Q.ninvoke(collection, 'drop')
.then(function() { console.log('dropped ' + name); });
});
Q.all(promises)
.then(function() { console.log('all dropped'); })
.fail(console.error);
With Bluebird:
var Promise = require('bluebird');
var mongoose = Promise.promisifyAll(require('mongoose'));
mongoose.connect('your MongoDB connection string');
var conn = mongoose.connection;
var promises = ['aaa', 'bbb', 'ccc'].map(function(name) {
return conn.collection(name).dropAsync().then(function() {
console.log('dropped ' + name);
});
});
Promise.all(promises)
.then(function() { console.log('all dropped'); })
.error(console.error);
Simple and easy way to update the cursor
UPDATE Cursor
SET Cursor.CODE = Cursor.New_CODE
FROM (
SELECT CODE, ROW_NUMBER() OVER (ORDER BY [CODE]) AS New_CODE
FROM Table Where CODE BETWEEN 1000 AND 1999
) Cursor
Yeah Regex is cool, but there are other alternative.
This allows you to edit multiple lines at once. Now you can add *Quotes (") or anything * at start and end of each lines.
Why don't you use spring's TransactionTemplate
to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional
method, but given that it's a test I would opt for programmatic control of your transactions.
Also note that the @Transactional
annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!
@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {
@Autowired
PlatformTransactionManager platformTransactionManager;
TransactionTemplate transactionTemplate;
@Before
public void setUp() throws Exception {
transactionTemplate = new TransactionTemplate(platformTransactionManager);
}
@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {
final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
@Override
public Contract doInTransaction(TransactionStatus status) {
Contract c = contractDOD.getNewTransientContract(15);
contractRepository.save(c);
return c;
}
});
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 5; ++i) {
executorService.execute(new Runnable() {
@Override //note that there is no @Transactional configured for the method
public void run() {
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// do whatever you want to do with c1
return null;
}
});
}
});
}
executorService.shutdown();
executorService.awaitTermination(10, TimeUnit.SECONDS);
transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(TransactionStatus status) {
// validate test results in transaction
return null;
}
});
}
}
Apart from all the other answers, what you can do is :
long l = Long.parseLong("600851475143");
for example :
obj.function(Long.parseLong("600851475143"));
You are opening the file as "w"
, which stands for writable.
Using "w"
you won't be able to read the file. Use the following instead:
file = open("File.txt","r")
Additionally, here are the other options:
"r" Opens a file for reading only.
"r+" Opens a file for both reading and writing.
"rb" Opens a file for reading only in binary format.
"rb+" Opens a file for both reading and writing in binary format.
"w" Opens a file for writing only.
"a" Open for writing. The file is created if it does not exist.
"a+" Open for reading and writing. The file is created if it does not exist.
Create a variant array (easiest by reading equivalent range in to a variant variable).
Then fill the array, and assign the array directly to the range.
Dim myArray As Variant
myArray = Range("blahblah")
Range("bingbing") = myArray
The variant array will end up as a 2-D matrix.
The Question is not private or public, the question is: How is it invoked and which AOP implementation you use!
If you use (default) Spring Proxy AOP, then all AOP functionality provided by Spring (like @Transactional
) will only be taken into account if the call goes through the proxy. -- This is normally the case if the annotated method is invoked from another bean.
This has two implications:
@Transactional
Annotation is not taken into account.@See Spring Reference: Chapter 9.6 9.6 Proxying mechanisms
IMHO you should use the aspectJ mode, instead of the Spring Proxies, that will overcome the problem. And the AspectJ Transactional Aspects are woven even into private methods (checked for Spring 3.0).
Please explain your problem. You say:
But this involves adding character " to the string.
What problem is that? You can't type string foo = "Foo"bar"";
, because that'll invoke a compile error. As for the adding part, in string size terms that is not true:
@"""".Length == "\"".Length == 1
i know this is late , but you should try redirecting to a path and not to a file ha ha
These days, Android Studio setup do not provide SDK as the part of original package.
In the context of windows, when you start Android Studio 1.3.1, you see the error message saying no sdk found. You just have to proceed and provide the path where sdk can be downloaded. And you are done.
Arrays.fill works with single dimensional array, so to fill two dimensional array we can do below
for (int i = 0, len = arr.length; i < len; i++)
Arrays.fill(arr[i], 0);
I got this error on a report I copied from another project and changed the data source. I solved it by opening the properties of my dataset, going to the Parameters section, and literally just reselecting all the parameters in the right column, like I just clicked the dropdown and selected the same column. Then I hit preview, and it worked!
How about this:
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable'
If you want the filenames without the file types, just add a final sed
filter.
$ grep -rl "needle text" my_folder | tr '\n' '\0' | xargs -r -0 file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
You can filter-out unneeded file types by adding more -e 'type'
options to the last grep
command.
EDIT:
If your xargs
version supports the -d
option, the commands above become simpler:
$ grep -rl "needle text" my_folder | xargs -d '\n' -r file | grep -e ':[^:]*text[^:]*$' | grep -v -e 'executable' | sed 's|:[^:]*$||'
Kotlin Style way to do this more simple (example):
isVisible = false
Complete example:
if (some_data_array.details == null){
holder.view.some_data_array.isVisible = false}
.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto; }
.search-table, td, th{border-collapse:collapse; border:1px solid #777;}
th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
td{padding:5px 10px; height:35px;}
You should provide scroll in div.
You could created sorted list from Values and rebuild the dictionary:
myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}
newDictionary={}
sortedList=sorted(myDictionary.values())
for sortedKey in sortedList:
for key, value in myDictionary.items():
if value==sortedKey:
newDictionary[key]=value
Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}
It seems that you want to use step parameter of range function. From documentation:
range(start, stop[, step]) This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) [0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) [0, 3, 6, 9]
>>> range(0, -10, -1) [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0) []
>>> range(1, 0) []
In your case to get [0,2,4] you can use:
range(0,6,2)
OR in your case when is a var:
idx = None
for i in range(len(str1)):
if idx and i < idx:
continue
for j in range(len(str2)):
if str1[i+j] != str2[j]:
break
else:
idx = i+j
To attempt command line arguments directly is not possible.
One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).
This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html
so sudo systemctl restart myprog -v
-- systemctl will think you're trying to set one of its flags, not myprog's flag.
sudo systemctl restart myprog someotheroption
-- systemctl will restart myprog and the someotheroption service, if it exists.
The exception occurs due to this statement,
called_from.equalsIgnoreCase("add")
It seem that the previous statement
String called_from = getIntent().getStringExtra("called");
returned a null reference.
You can check whether the intent to start this activity contains such a key "called".
I believe the most simple method to inject Javascript in a WebBrowser Control HTML Document from c# is to invoke the "execScript" method with the code to be injected as argument.
In this example the javascript code is injected and executed at global scope:
var jsCode="alert('hello world from injected code');";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
If you want to delay execution, inject functions and call them after:
var jsCode="function greet(msg){alert(msg);};";
WebBrowser.Document.InvokeScript("execScript", new Object[] { jsCode, "JavaScript" });
...............
WebBrowser.Document.InvokeScript("greet",new object[] {"hello world"});
This is valid for Windows Forms and WPF WebBrowser controls.
This solution is not cross browser because "execScript" is defined only in IE and Chrome. But the question is about Microsoft WebBrowser controls and IE is the only one supported.
For a valid cross browser method to inject javascript code, create a Function object with the new Keyword. This example creates an anonymous function with injected code and executes it (javascript implements closures and the function has access to global space without local variable pollution).
var jsCode="alert('hello world');";
(new Function(code))();
Of course, you can delay execution:
var jsCode="alert('hello world');";
var inserted=new Function(code);
.................
inserted();
Hope it helps
You can use VLOOKUP, but this requires a wrapper function to return True
or False
. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.
Fill down this formula in column K next to the existing values in column I (from I1
to I2691
):
=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0
You can also use MATCH:
=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))
I think you can use eval
. Something like this
def toclass(strcls):
return eval(strcls)()
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
Try this:
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('MyBundle:MyTable')->findBy(array(), array('username' => 'ASC'));
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
for ( i = 0; i < total.length; i++ ); // remove this
{
if (total[i]!=0)
System.out.println( "Letter" + (char)( 'a' + i) + " count =" + total[i]);
}
The for loop loops until i=26
(where 26 is total.length
) and then your if
is executed, going over the bounds of the array. Remove the ;
at the end of the for
loop.
Remove all the texts in android/settings.gradle and paste the below code
rootProject.name = '****Your Project Name****'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
This issue will usually happen when you migrate from react-native < 0.60 to react-native >0.60. If you create a new project in react-native >0.60 you will see the same settings as above mentioned
Without external variables:
$('.element').bind('mousewheel', function(e, d) {
if((this.scrollTop === (this.scrollHeight - this.offsetHeight) && d < 0)
|| (this.scrollTop === 0 && d > 0)) {
e.preventDefault();
}
});
you can use the Common IO library which can get you the Base name of your file and the Extension.
String fileUrl=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg";
String fileName=FilenameUtils.getBaseName(fileUrl);
String fileExtention=FilenameUtils.getExtension(fileUrl);
//this will return filename:1414240995236 and fileExtention:jpg
We all know that programming have endless possibilities.There are numbers of solutions available for a single problem so i think all of the above solutions are perfect and may be helpful for someone but for me this one save my day..
So Code goes like this
private void getWebsite() {
new Thread(new Runnable() {
@Override
public void run() {
final StringBuilder builder = new StringBuilder();
try {
Document doc = Jsoup.connect("http://www.ssaurel.com/blog").get();
String title = doc.title();
Elements links = doc.select("a[href]");
builder.append(title).append("\n");
for (Element link : links) {
builder.append("\n").append("Link : ").append(link.attr("href"))
.append("\n").append("Text : ").append(link.text());
}
} catch (IOException e) {
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
@Override
public void run() {
result.setText(builder.toString());
}
});
}
}).start();
}
You just have to call the above function in onCreate Method
of your MainActivity
I hope this one is also helpful for you guys.
Also read the original blog at Medium
Spark 2.0.0+
You can use built-in csv data source directly:
spark.read.csv(
"some_input_file.csv", header=True, mode="DROPMALFORMED", schema=schema
)
or
(spark.read
.schema(schema)
.option("header", "true")
.option("mode", "DROPMALFORMED")
.csv("some_input_file.csv"))
without including any external dependencies.
Spark < 2.0.0:
Instead of manual parsing, which is far from trivial in a general case, I would recommend spark-csv
:
Make sure that Spark CSV is included in the path (--packages
, --jars
, --driver-class-path
)
And load your data as follows:
(df = sqlContext
.read.format("com.databricks.spark.csv")
.option("header", "true")
.option("inferschema", "true")
.option("mode", "DROPMALFORMED")
.load("some_input_file.csv"))
It can handle loading, schema inference, dropping malformed lines and doesn't require passing data from Python to the JVM.
Note:
If you know the schema, it is better to avoid schema inference and pass it to DataFrameReader
. Assuming you have three columns - integer, double and string:
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
schema = StructType([
StructField("A", IntegerType()),
StructField("B", DoubleType()),
StructField("C", StringType())
])
(sqlContext
.read
.format("com.databricks.spark.csv")
.schema(schema)
.option("header", "true")
.option("mode", "DROPMALFORMED")
.load("some_input_file.csv"))
Consider this as your select list:
<select onchange="var optionVal = $(this).find(':selected').val(); doSomething(optionVal)">
<option value="mostSeen">Most Seen</option>
<option value="newst">Newest</option>
<option value="mostSell">Most Sell</option>
<option value="mostCheap">Most Cheap</option>
<option value="mostExpensive">Most Expensive</option>
</select>
then you check selected option like this:
function doSomething(param) {
if ($(param.selected)) {
alert(param + ' is selected!');
}
}
I had a similar problem today, I'll document it here, as it's not quite the optimistic concurrency error.
I'm converting an old system to a new database and it has couple of thousand entities that I've had to script over to the new system. However, to aid with sanity I've opted to keep the original unique IDs and so was injecting that into the new object and then trying to save it.
The problem I had is that I'd used MVC Scaffolding to create base repositories and they have a pattern in their UpdateOrInsert method, that basically checks to see if the Key attribute is set before it either adds the new entity or changes its state to modified.
Because the Guid was set, it was trying to modify a row that didn't actually exist in the database.
I hope this helps someone else!
I did some measurements using attached program .net 4.7 release build without the debugger attached. I think people have been using the wrong metric since what you are about if you care about speed here is how long it takes to figure out if two byte arrays are equal. i.e. throughput in bytes.
StructuralComparison : 4.6 MiB/s
for : 274.5 MiB/s
ToUInt32 : 263.6 MiB/s
ToUInt64 : 474.9 MiB/s
memcmp : 8500.8 MiB/s
As you can see, there's no better way than memcmp
and it's orders of magnitude faster. A simple for
loop is the second best option. And it still boggles my mind why Microsoft cannot simply include a Buffer.Compare
method.
[Program.cs]:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace memcmp
{
class Program
{
static byte[] TestVector(int size)
{
var data = new byte[size];
using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
{
rng.GetBytes(data);
}
return data;
}
static TimeSpan Measure(string testCase, TimeSpan offset, Action action, bool ignore = false)
{
var t = Stopwatch.StartNew();
var n = 0L;
while (t.Elapsed < TimeSpan.FromSeconds(10))
{
action();
n++;
}
var elapsed = t.Elapsed - offset;
if (!ignore)
{
Console.WriteLine($"{testCase,-16} : {n / elapsed.TotalSeconds,16:0.0} MiB/s");
}
return elapsed;
}
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
static extern int memcmp(byte[] b1, byte[] b2, long count);
static void Main(string[] args)
{
// how quickly can we establish if two sequences of bytes are equal?
// note that we are testing the speed of different comparsion methods
var a = TestVector(1024 * 1024); // 1 MiB
var b = (byte[])a.Clone();
// was meant to offset the overhead of everything but copying but my attempt was a horrible mistake... should have reacted sooner due to the initially ridiculous throughput values...
// Measure("offset", new TimeSpan(), () => { return; }, ignore: true);
var offset = TimeZone.Zero
Measure("StructuralComparison", offset, () =>
{
StructuralComparisons.StructuralEqualityComparer.Equals(a, b);
});
Measure("for", offset, () =>
{
for (int i = 0; i < a.Length; i++)
{
if (a[i] != b[i]) break;
}
});
Measure("ToUInt32", offset, () =>
{
for (int i = 0; i < a.Length; i += 4)
{
if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) break;
}
});
Measure("ToUInt64", offset, () =>
{
for (int i = 0; i < a.Length; i += 8)
{
if (BitConverter.ToUInt64(a, i) != BitConverter.ToUInt64(b, i)) break;
}
});
Measure("memcmp", offset, () =>
{
memcmp(a, b, a.Length);
});
}
}
}
It's a convention in Ruby that methods that return boolean values end in a question mark. There's no more significance to it than that.
besides pause
.
set /p=
can be used .It will expect user input and will release the flow when enter is pressed.
or
runas /user:# "" >nul 2>&1
which will do the same except nothing from the user input will be displayed nor will remain in the command history.
Better yet, consider sp_getapplock
which is designed for this. Or use SET LOCK_TIMEOUT
Otherwise, you'd have to do something with sys.dm_tran_locks
which I'd use only for DBA stuff: not for user defined concurrency.
With the newer versions of angularjs the correct answer to this question is to use ng-if
:
<ul>
<li ng-if="list.length === 0">( No items in this list yet! )</li>
<li ng-repeat="item in list">{{ item }}</li>
</ul>
This solution will not flicker when the list is about to download either because the list has to be defined and with a length of 0 for the message to display.
Here is a plunker to show it in use: http://plnkr.co/edit/in7ha1wTlpuVgamiOblS?p=preview
Tip: You can also show a loading text or spinner:
<li ng-if="!list">( Loading... )</li>
There are a couple of different ways you can do this:
Make the other script executable, add the #!/bin/bash
line at the top, and the path where the file is to the $PATH environment variable. Then you can call it as a normal command;
Or call it with the source
command (alias is .
) like this: source /path/to/script
;
Or use the bash
command to execute it: /bin/bash /path/to/script
;
The first and third methods execute the script as another process, so variables and functions in the other script will not be accessible.
The second method executes the script in the first script's process, and pulls in variables and functions from the other script so they are usable from the calling script.
In the second method, if you are using exit
in second script, it will exit the first script as well. Which will not happen in first and third methods.
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
Another alternative
I have two plots side by side and would like to adjust tick labels separately.
The above solutions were close however they were not working out for me. I found my solution from this matplotlib page.
ax.xaxis.set_tick_params(labelsize=20)
This did the trick and was straight to the point. For my use case, it was the plot on the right that needed to be adjusted. For the plot on the left since I was creating new tick labels I was able to adjust the font in the same process as seting the labels.
ie
ax1.set_xticklabels(ax1_x, fontsize=15)
ax1.set_yticklabels(ax1_y, fontsize=15)
thus I used for the right plot,
ax2.xaxis.set_tick_params(labelsize=24)
ax2.yaxis.set_tick_params(labelsize=24)
A minor subtlety... I know... but I hope this helps someone :)
Bonus points if anyone knows how to adjust the font size of the order of magnitude label.
Just answering this old thread can be installed without pip On windows or Linux:
1) Download Requests from https://github.com/kennethreitz/requests click on clone or download button
2) Unzip the files in your python directory .Exp your python is installed in C:Python\Python.exe then unzip there
3) Depending on the Os run the following command:
Thats it :)
This REGEX is a patch from @Aamir answer that worked for me
/((?:(?:http?|ftp)[s]*:\/\/)?[a-z0-9-%\/\&=?\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?)/gi
It matches these URL formats
I don't see an obvious problem with the above.
It's possible your ldap.conf
is being overridden, but the command-line options will take precedence, ldapsearch
will ignore BINDDN
in the main ldap.conf
, so the only parameter that could be wrong is the URI.
(The order is ETCDIR/ldap.conf
then ~/ldaprc
or ~/.ldaprc
and then ldaprc
in the current directory, though there environment variables which can influence this too, see man ldapconf
.)
Try an explicit URI:
ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base -H ldap://localhost
or prevent defaults with:
LDAPNOINIT=1 ldapsearch -x -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
If that doesn't work, then some troubleshooting (you'll probably need the full path to the slapd
binary for these):
make sure your slapd.conf
is being used and is correct (as root)
slapd -T test -f slapd.conf -d 65535
You may have a left-over or default slapd.d
configuration directory which takes preference over your slapd.conf
(unless you specify your config explicitly with -f
, slapd.conf
is officially deprecated in OpenLDAP-2.4). If you don't get several pages of output then your binaries were built without debug support.
stop OpenLDAP, then manually start slapd
in a separate terminal/console with debug enabled (as root, ^C to quit)
slapd -h ldap://localhost -d 481
then retry the search and see if you can spot the problem (there will be a lot of schema noise in the start of the output unfortunately). (Note: running slapd
without the -u
/-g
options can change file ownerships which can cause problems, you should usually use those options, probably -u ldap -g ldap
)
if debug is enabled, then try also
ldapsearch -v -d 63 -W -D 'cn=Manager,dc=example,dc=com' -b "" -s base
Here's a good one:
Set line-height
equal to whatever the height
is; works like a charm!
E.g:
li {
height: 30px;
line-height: 30px;
}
You can do it with several ways in codeigniter e.g.
First By loop
foreach($myarray as $row)
{
$data = array("first"=>$row->first,"second"=>$row->sec);
$this->db->insert('table_name',$data);
}
Second -- By insert batch
$data = array(
array(
'first' => $myarray[0]['first'] ,
'second' => $myarray[0]['sec'],
),
array(
'first' => $myarray[1]['first'] ,
'second' => $myarray[1]['sec'],
),
);
$this->db->insert_batch('table_name', $data);
Third way -- By multiple value pass
$sql = array();
foreach( $myarray as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['first']).'", '.$row['sec'].')';
}
mysql_query('INSERT INTO table (first, second) VALUES '.implode(',', $sql));
I had the same problem while connecting from Android client to Kurento server. Kurento server use jks certificates, so I had to convert pem to it. As input for conversion I used cert.pem file and it lead to such errors. But if use fullchain.pem instead of cert.pem - all is OK.
I just happened to look for something similar and came up with this:
std::cout << std::setfill(' ') << std::setw(n) << ' ';
First thing, you should not do any DOM manipulation in controller function. Instead, you should use directives for this purpose. directive's link function is available for those kind of stuff only.
AngularJS Docs : Creating a Directive that Manipulates the DOM
app.directive('buttonDirective', function($timeout) {
return {
scope: {
change: '&'
},
link: function(scope, element, attrs) {
element.bind('click', function() {
$timeout(function() {
// triggering callback
scope.change();
});
});
}
};
});
change callback can be used as listener for click event.
Very useful thing have applied today in my project. One div had to be aligned right, with no floating applied.
Applying code made my goal achieved:
.div {
margin-right: 0px;
margin-left: auto;
}
StringUtils.abbreviate
from Apache Commons Lang library could be your friend:
StringUtils.abbreviate("abcdefg", 6) = "abc..."
StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
StringUtils.abbreviate("abcdefg", 4) = "a..."
Commons Lang3 even allow to set a custom String as replacement marker. With this you can for example set a single character ellipsis.
StringUtils.abbreviate("abcdefg", "\u2026", 6) = "abcde…"
edittext_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/edittext_pressed" android:state_pressed="true" /> <!-- pressed -->
<item android:drawable="@drawable/edittext_disable" android:state_enabled="false" /> <!-- focused -->
<item android:drawable="@drawable/edittext_default" /> <!-- default -->
</selector>
edittext_default.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#BBDEFB" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_pressed.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#00f" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
edittext_disable.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item>
<shape android:shape="rectangle" >
<solid android:color="#aaaaaa" />
<padding android:bottom="2dp" />
</shape>
</item>
<item android:bottom="5dp">
<shape android:shape="rectangle" >
<solid android:color="#fff" />
<padding
android:left="0dp"
android:right="0dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle" >
<solid android:color="#fff" />
</shape>
</item>
</layer-list>
Make sure the function is in the same DB schema as the table.
To expand on @Cradle 's answer: you could also write a multi-purpose function that will get you the same result per the OP's question:
Function Get-AbsolutePath {
[CmdletBinding()]
Param(
[parameter(
Mandatory=$false,
ValueFromPipeline=$true
)]
[String]$relativePath=".\"
)
if (Test-Path -Path $relativePath) {
return (Get-Item -Path $relativePath).FullName -replace "\\$", ""
} else {
Write-Error -Message "'$relativePath' is not a valid path" -ErrorId 1 -ErrorAction Stop
}
}
IMHO aperkins provided an an elegant solution cause is native and use less code. But if you need a shorter ID you can use this approach to reduce the generated String length:
// usage: GenerateShortUUID.next();
import java.util.UUID;
public class GenerateShortUUID() {
private GenerateShortUUID() { } // singleton
public static String next() {
UUID u = UUID.randomUUID();
return toIDString(u.getMostSignificantBits()) + toIDString(u.getLeastSignificantBits());
}
private static String toIDString(long i) {
char[] buf = new char[32];
int z = 64; // 1 << 6;
int cp = 32;
long b = z - 1;
do {
buf[--cp] = DIGITS66[(int)(i & b)];
i >>>= 6;
} while (i != 0);
return new String(buf, cp, (32-cp));
}
// array de 64+2 digitos
private final static char[] DIGITS66 = {
'0','1','2','3','4','5','6','7','8','9', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'-','.','_','~'
};
}
Team:
This works with ASP.NET Core; The challenge to the above is how you 'set the setting to ignore'. Depending on how you setup your application it can be quite challenging. Here is what worked for me.
This can be placed in your public void ConfigureServices(IServiceCollection services) section.
services.AddMvc().AddJsonOptions(opt =>
{
opt.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
This Question was asked here: VBA Arrays - Check strict (not approximative) match
Sub test()
vars1 = Array("Examples")
vars2 = Array("Example")
If IsInArray(Range("A1").value, vars1) Then
x = 1
End If
If IsInArray(Range("A1").value, vars2) Then
x = 1
End If
End Sub
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))
End Function
Don't use sudo
in a virtual environment because it ignores the environment's variables and therefore sudo pip
refers to your global pip installation.
So with your environment activated, rerun pip install boto3
but without sudo.
I have a combination of Hibernate+Eclipse RCP, tried using -XX:MaxPermSize=512m
and -XX:PermSize=512m
and it seems to be working for me.
If you will look at package.json
file.
you will see something like this
"start": "http-server -a localhost -p 8000"
This tells start a http-server
at address of localhost
on port 8000
http-server is a node-module.
Update:- Including comment by @Usman, ideally it should be present in your package.json
but if it's not present you can include it in scripts
section.
If You want to have a reference to this variable across the whole project, create somewhere d.ts
file, e.g. globals.d.ts
. Fill it with your global variables declarations, e.g.:
declare const BootBox: 'boot' | 'box';
Now you can reference it anywhere across the project, just like that:
const bootbox = BootBox;
Here's an example.
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
When you use setcookie
, you can either set the expiration time to 0
or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).
The problem is that you thought your jsonString is a dictionary. It's not.
It's an array of dictionaries.
In raw json strings, arrays begin with [
and dictionaries begin with {
.
I used your json string with below code :
let string = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]"
let data = string.data(using: .utf8)!
do {
if let jsonArray = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(jsonArray) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error)
}
and I am getting the output :
[["form_desc": <null>, "form_name": Activity 4 with Images, "canonical_name": df_SAWERQ, "form_id": 3465]]
I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files
This link suggests that they are:
We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.
Here are few steps that must be followed carefully
Create a folder named config inside C:\wamp\apps\phpmyadmin, the folder inside apps may have different name like phpmyadmin3.2.0.1
Return to your browser in phpmyadmin setup tab, and click New server.
Change the authentication type to ‘cookie’ and leave the username and password field empty but if you change the authentication type to ‘config’ enter the password for username root.
Use of pointer before character array
Normally, Character array is used to store single elements in it i.e 1 byte each
eg:
char a[]={'a','b','c'};
we can't store multiple value in it.
by using pointer before the character array we can store the multi dimensional array elements in the array
i.e.
char *a[]={"one","two","three"};
printf("%s\n%s\n%s",a[0],a[1],a[2]);
You need to add the python.exe in C://.../Anaconda3 installation file as well as C://.../Anaconda3/Scripts to PATH.
First go to your installation directory, in my case it is installed in C://Users/user/Anaconda3 and shift+right click and press "Open command window here" or it might be "Open powershell here", if it is powershell, just write cmd and hit enter to run command window. Then run the following command setx PATH %cd%
Then go to C://Users/user/Anaconda3/Scripts and open the command window there as above, then run the same command "setx PATH %cd%"
I realize this is a two year old question, but I still found it useful. I ended up using the sample code provided by Fudgey but with a minor mod. Saved me some time, thanks!
jQuery.fn.dataTableExt.oSort['us_date-asc'] = function(a,b) {
var x = new Date($(a).text()),
y = new Date($(b).text());
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
};
jQuery.fn.dataTableExt.oSort['us_date-desc'] = function(a,b) {
var x = new Date($(a).text()),
y = new Date($(b).text());
return ((x < y) ? 1 : ((x > y) ? -1 : 0));
};
If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm
Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)
I am using jquery 1.7.2 while writing this.
here is one of the reference I found: http://bugs.jquery.com/ticket/8338
Here's a quick one: Removal of items is quicker.
It's not a programmatic solution but you can run
java -verbose:class ....
and the JVM will dump out what it's loading, and from where.
[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar]
[Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar]
[Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
[Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar]
See here for more details.
Try wrapping your FileWriter
in a BufferedWriter
:
BufferedWriter bw = new BufferedWriter(writer);
bw.newLine();
Javadocs for BufferedWriter here.
You can use CAST and CONVERT to switch between different types of encodings. See: http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
SELECT column1, CONVERT(column2 USING utf8)
FROM my_table
WHERE my_condition;
You can do:
t1<- t1[-4:-6,-7:-9]
Whenever you try to load any data in this window this gif will load.
HTML
Make a Div
<div class="loader"></div>
CSS .
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://lkp.dispendik.surabaya.go.id/assets/loading.gif') 50% 50% no-repeat rgb(249,249,249);
jQuery
$(window).load(function() {
$(".loader").fadeOut("slow");
});
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
Just an example of event handler for Add event. Assumes that singleFileUploads option is enabled (which is the default). Read more jQuery File Upload documentation how to bound with add/fileuploadadd event. Inside loop you can use both vars this or file. An example of getting size property: this['size'] or file.size.
/**
* Handles Add event
*/
base.eventAdd = function(e, data) {
var errs = [];
var acceptFileTypes = /(\.|\/)(gif|jpe?g|png)$/i;
var maxFileSize = 5000000;
// Validate file
$.each(data.files, function(index, file) {
if (file.type.length && !acceptFileTypes.test(file.type)) {
errs.push('Selected file "' + file.name + '" is not alloawed. Invalid file type.');
}
if (this['size'] > maxFileSize) {
errs.push('Selected file "' + file.name + '" is too big, ' + parseInt(file.size / 1024 / 1024) + 'M.. File should be smaller than ' + parseInt(maxFileSize / 1024 / 1024) + 'M.');
}
});
// Output errors or submit data
if (errs.length > 0) {
alert('An error occured. ' + errs.join(" "));
} else {
data.submit();
}
};
In our case didn't work because our production server has missing
Microsoft Visual C++ 2010 SP1 Redistributable Package (x86)
We installed it and all work fine. The Application Pool must have Enable 32-bit Applications set to true and you must the x86 version of the library
See a very good article "The definitive guide to Python exceptions". The basic principles are:
BaseException.__init__
with only one argument.There is also information on organizing (in modules) and wrapping exceptions, I recommend to read the guide.
In Python,
any variable that is assigned a value is local to the block in which the assignment appears.
If a variable can't be found in the current scope, please refer to the LEGB order.
Here's a simple C++ solution:
bool IsPowerOfTwo( unsigned int i )
{
return std::bitset<32>(i).count() == 1;
}
object.__del__(self)
is called when the instance is about to be destroyed.
>>> class Test:
... def __del__(self):
... print "deleted"
...
>>> test = Test()
>>> del test
deleted
Object is not deleted unless all of its references are removed(As quoted by ethan)
Also, From Python official doc reference:
del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero
Singleton Shared Preferences Class. it may help for others in future.
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
public class SharedPref
{
private static SharedPreferences mSharedPref;
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String IS_SELECT = "IS_SELECT";
private SharedPref()
{
}
public static void init(Context context)
{
if(mSharedPref == null)
mSharedPref = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
}
public static String read(String key, String defValue) {
return mSharedPref.getString(key, defValue);
}
public static void write(String key, String value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putString(key, value);
prefsEditor.commit();
}
public static boolean read(String key, boolean defValue) {
return mSharedPref.getBoolean(key, defValue);
}
public static void write(String key, boolean value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putBoolean(key, value);
prefsEditor.commit();
}
public static Integer read(String key, int defValue) {
return mSharedPref.getInt(key, defValue);
}
public static void write(String key, Integer value) {
SharedPreferences.Editor prefsEditor = mSharedPref.edit();
prefsEditor.putInt(key, value).commit();
}
}
Simply call SharedPref.init()
on MainActivity
once
SharedPref.init(getApplicationContext());
To Write data
SharedPref.write(SharedPref.NAME, "XXXX");//save string in shared preference.
SharedPref.write(SharedPref.AGE, 25);//save int in shared preference.
SharedPref.write(SharedPref.IS_SELECT, true);//save boolean in shared preference.
To Read Data
String name = SharedPref.read(SharedPref.NAME, null);//read string in shared preference.
int age = SharedPref.read(SharedPref.AGE, 0);//read int in shared preference.
boolean isSelect = SharedPref.read(SharedPref.IS_SELECT, false);//read boolean in shared preference.
HttpOnly
cookies.document.cookie
property, which contains a semicolon separated list of name=value
pairs.If none of the above solutions worked, then stop and do a sanity check.
I got burned using the wrong -G <config>
string and it gave me this misleading error.
First, run from the VS Command Prompt not the regular command prompt. You can find it in
Start Menu -> Visual Studio 2015 -> MSBuild Command Prompt for VS2015
This sets up all the correct paths to VS tools, etc.
Now see what generators are available from cmake...
cmake -help
...<snip>...
The following generators are available on this platform:
Visual Studio 15 [arch] = Generates Visual Studio 15 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 14 2015 [arch] = Generates Visual Studio 2015 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 12 2013 [arch] = Generates Visual Studio 2013 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
Optional [arch] can be "Win64" or "ARM".
Visual Studio 10 2010 [arch] = Generates Visual Studio 2010 project files.
Optional [arch] can be "Win64" or "IA64".
...
Then chose the appropriate string with the [arch] added.
mkdir _build
cd _build
cmake .. -G "Visual Studio 15 Win64"
Running cmake in a subdirectory makes it easier to do a 'clean' since you can just delete everything in that directory.
I upgraded to Visual Studio 15 but wasn't paying attention and was trying to generate for 2012.
nice excuse to muck around with CONVERT. Probably prettier ways of doing it:
create table the_table
(
[DateKey] INT,
)
insert into the_table
values
(20120101),
(20120102),
(20120201),
(20130601)
WITH myDateCTE(DateKey, Date) as
(
SELECT
DateKey
,[Date] = CONVERT(DATETIME, CONVERT(CHAR(8),DateKey),112)
FROM the_table
)
SELECT
t.[DateKey]
, m.[Date]
, [QuarterNumber] = CONVERT(VARCHAR(20),Datepart(qq,Date))
, [QuarterString] = 'Q' + CONVERT(VARCHAR(20),Datepart(qq,Date))
, [Year] = Datepart(yyyy,Date)
, [Q-Yr] = CONVERT(VARCHAR(2),'Q' + CONVERT(VARCHAR(20),Datepart(qq,Date))) + '-' + CONVERT(VARCHAR(4),Datepart(yyyy,Date))
FROM
the_table t
inner join myDateCTE m
on
t.DateKey = m.DateKey
You need commas after end
finishing the case statement. And, the "as" goes after the case
statement, not inside it:
Insert into TblStuff(FullName, Address, City, Zip)
Select (Case When Middle is Null Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End) as FullName,
(Case When Address2 is Null Then Address1
else Address1 +', ' + Address2
End) as Address,
City as City,
Zip as Zip
from tblImport
In your case it is probably taking them in DD-MM-YY format, not MM-DD-YY.
Here's a situation where you HAVE to use property accessors. Imagine you have a GENERIC abstract class with lots of implementation goodness to inherit into 8 concrete subclasses:
public abstract class Foo<T extends Bar> {
T oneThing;
T anotherThing;
// getters and setters ommited for brevity
// Lots and lots of implementation regarding oneThing and anotherThing here
}
Now exactly how should you annotate this class? The answer is YOU CAN'T annotate it at all with either field or property access because you can't specify the target entity at this point. You HAVE to annotate the concrete implementations. But since the persisted properties are declared in this superclass, you MUST used property access in the subclasses.
Field access is not an option in an application with abstract generic super-classes.
If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.
You need to call GetResponse().
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
The specification does not limit the length of an HTTP Get request but the different browsers implement their own limitations. For example Internet Explorer has a limitation implemented at 2083 characters.
A quick solution (error free)
function getClientIP():string
{
$keys=array('HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR');
foreach($keys as $k)
{
if (!empty($_SERVER[$k]) && filter_var($_SERVER[$k], FILTER_VALIDATE_IP))
{
return $_SERVER[$k];
}
}
return "UNKNOWN";
}
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
.crop {
overflow:hidden;
white-space:nowrap;
text-overflow:ellipsis;
width:100px;
}?
I fix this problem using two clases, one similar to @jinshiyi11 answer's and the anoter is based on explicit click, in this you can click a button only once time, if you want another click you have to indicate it explicitly.
/**
* Listener que sólo permite hacer click una vez, para poder hacer click
* posteriormente se necesita indicar explicitamente.
*
* @author iberck
*/
public abstract class OnExplicitClickListener implements View.OnClickListener {
// you can perform a click only once time
private boolean canClick = true;
@Override
public synchronized void onClick(View v) {
if (canClick) {
canClick = false;
onOneClick(v);
}
}
public abstract void onOneClick(View v);
public synchronized void enableClick() {
canClick = true;
}
public synchronized void disableClick() {
canClick = false;
}
}
Example of use:
OnExplicitClickListener clickListener = new OnExplicitClickListener() {
public void onOneClick(View v) {
Log.d("example", "explicit click");
...
clickListener.enableClick();
}
}
button.setOnClickListener(clickListener);
/^(?:(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(?1)$/m
The behaviour may be undefined, but that just means there isn't a "standard". All decent compilers offer #pragmas to control packing and alignment, but may have different defaults. The defaults will also change depending on the optimisation settings used.
Also, unions are not just for saving space. They can help modern compilers with type punning. If you reinterpret_cast<>
everything the compiler can't make assumptions about what you are doing. It may have to throw away what it knows about your type and start again (forcing a write back to memory, which is very inefficient these days compared to CPU clock speed).
Probably the only valid reason for using
set enable_seqscan=false
is when you're writing queries and want to quickly see what the query plan would actually be were there large amounts of data in the table(s). Or of course if you need to quickly confirm that your query is not using an index simply because the dataset is too small.
When you call a package but do not want some of its dependencies you can do a thing like this (in this case I did not want the old log4j to be added because I needed to use the newer one):
<dependency>
<groupId>package</groupId>
<artifactId>package-pk</artifactId>
<version>${package-pk.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- LOG4J -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.5</version>
</dependency>
This works for me... but I am pretty new to java/maven so it is maybe not optimum.
I have created a realtively small (4.89 KB) javascript library for this exact functionality.
Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/
It's as simple as:
<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>
<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>
Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/
What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=
. It decodes the response which includes streaming information we can use to add a source to the <video>
tag.
You can use \blacksquare
¦:
When creating TeX, Knuth provided the symbol ¦ (solid black square), also called by mathematicians tombstone or Halmos symbol (after Paul Halmos, who pioneered its use as an equivalent of Q.E.D.). The tombstone is sometimes open: ? (hollow black square).
You can pass a regex into Javascript's split operator. For example:
"1,2 3".split(/,| /)
["1", "2", "3"]
Or, if you want to allow multiple separators together to act as one only:
"1, 2, , 3".split(/(?:,| )+/)
["1", "2", "3"]
(You have to use the non-capturing (?:) parens because otherwise it gets spliced back into the result. Or you can be smart like Aaron and use a character class.)
(Examples tested in Safari + FF)
I'm working on a similar project and I guess my code may help in the above situation
Here is the overview of what i'm doing
My project Has two fragments Called "FragmentA" and "FragmentB"
-FragmentA Contains one list View,when you click an item in FragmentA It's INDEX is passed to FragmentB using Communicator interface
I'm triggering respond() method of interface from FrgamentA using the MainActivity's reference.
Interface communcator is defined inside fragmentA, this is to provide least access previlage to communicator interface.
below is my complete working code
FragmentA.java
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator communicater;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragmenta, container,false);
}
public void setCommunicator(Communicator c){
communicater=c;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
communicater=(Communicator) getActivity();
list = (ListView) getActivity().findViewById(R.id.lvModularListView);
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.items, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);
}
public interface Communicator{
public void respond(int index);
}
}
fragmentB.java
public class FragmentA extends Fragment implements OnItemClickListener {
ListView list;
Communicator communicater;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.fragmenta, container,false);
}
public void setCommunicator(Communicator c){
communicater=c;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
communicater=(Communicator) getActivity();
list = (ListView) getActivity().findViewById(R.id.lvModularListView);
ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.items, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
list.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
communicater.respond(index);
}
public interface Communicator{
public void respond(int index);
}
}
MainActivity.java
public class MainActivity extends Activity implements FragmentA.Communicator {
FragmentManager manager=getFragmentManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragA=(FragmentA) manager.findFragmentById(R.id.fragmenta);
fragA.setCommunicator(this);
}
@Override
public void respond(int i) {
// TODO Auto-generated method stub
FragmentB FragB=(FragmentB) manager.findFragmentById(R.id.fragmentb);
FragB.changetext(i);
}
}
Just to add up on Victor's answer.
I would recommend to add a check to see, if the variable (in his case the long midnight
) is higher than 1440
. If it is, I would omit the .plusDays(1)
, otherwise the task will only run the day after tomorrow.
I did it simply like this:
Long time;
final Long tempTime = LocalDateTime.now().until(LocalDate.now().plusDays(1).atTime(7, 0), ChronoUnit.MINUTES);
if (tempTime > 1440) {
time = LocalDateTime.now().until(LocalDate.now().atTime(7, 0), ChronoUnit.MINUTES);
} else {
time = tempTime;
}
The argument order seems to matter... to exclude subdirectories, I used
robocopy \\source\folder C:\destinationfolder /XD * /MIR
...and that works for me (Windows 10 copy from Windows Server 2016)
I had a similar issue and to remove the workspace that was causing me a problem, I logged into another machine with TFS client installed and performed the following:
Minor point (code golf), but in the case where order does not matter you don't need to swap the values. Just overwrite the array position being removed with a duplicate of the last position and then return a truncated array.
func remove(s []int, i int) []int {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}
Same result.
Please note that this article: https://medium.com/the-web-tub/supporting-iphone-x-for-mobile-web-cordova-app-using-onsen-ui-f17a4c272fcd has different sizes than above and cordova plugin page:
Default@2x~iphone~anyany.png (= 1334x1334 = 667x667@2x)
Default@2x~iphone~comany.png (= 750x1334 = 375x667@2x)
Default@2x~iphone~comcom.png (= 750x750 = 375x375@2x)
Default@3x~iphone~anyany.png (= 2436x2436 = 812x812@3x)
Default@3x~iphone~anycom.png (= 2436x1242 = 812x414@3x)
Default@3x~iphone~comany.png (= 1242x2436 = 414x812@3x)
Default@2x~ipad~anyany.png (= 2732x2732 = 1366x1366@2x)
Default@2x~ipad~comany.png (= 1278x2732 = 639x1366@2x)
I resized images as above and updated ios
platform and cordova-plugin-splashscreen
to latest and the flash to white screen after a second issue was fixed. However the initial spash image has a white border at bottom now.
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
use ack its simple.
just type ack <string to be searched>
For higher API 10, the Dialog disappears when on touched outside, whereas in lower than API 11, the Dialog doesn't disappear. For prevent this, you need to do:
In styles.xml
: <item name="android:windowCloseOnTouchOutside">false</item>
OR
In onCreate()
method, use: this.setFinishOnTouchOutside(false);
Note: for API 10 and lower, this method doesn't have effect, and is not needed.
this work for me.
create a new project in android studio. Open project setting and copy the local gradle path. now open the project having gradle problem and paste that url and select local path.
click apply problem will get solved.
IEnumerable list = DataGridDetail.ItemsSource as IEnumerable;
List<string> lstFile = new List<string>();
int i = 0;
foreach (var row in list)
{
bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row)).IsChecked;
if (IsChecked)
{
MessageBox.show(i);
--Here i want to get the index or current row from the list
}
++i;
}
Slight change to the FastArray from above:
'pushtest.vbs
imax = 10000000
value = "Testvalue"
s = imax & " of """ & value & """"
t0 = timer 'Fast array
a = array()
ub = UBound(a)
For i = 0 To imax
If i>ub Then
ReDim Preserve a(Int((ub+10)*1.1))
ub = UBound(a)
End If
a(i) = value
Next
ReDim Preserve a(i-1)
s = s & "[FastArr " & FormatNumber(timer - t0, 3, -1) & "]"
MsgBox s
There is no point in checking UBound(a)
in every cycle of the for if we know exactly when it changes.
I've changed it so that it checks does UBound(a)
just before the for starts and then only every time the ReDim
is called
On my computer the old method took 7.52 seconds for an imax of 10 millions.
The new method took 5.29 seconds for an imax of also 10 millions, which signifies a performance increase of over 20% (for 10 millions tries, obviously this percentage has a direct relationship to the number of tries)
use below code it helps you....
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
options.inPurgeable = true;
Bitmap bm = BitmapFactory.decodeFile("your path of image",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,40,baos);
// bitmap object
byteImage_photo = baos.toByteArray();
//generate base64 string of image
String encodedImage =Base64.encodeToString(byteImage_photo,Base64.DEFAULT);
//send this encoded string to server
In sdk Manager download android 5.1.1, it worked for me
Assuming you are reading from a data row, what you want is:
if ( !rdrSelect.IsNull(23) )
{
//handle parsing
}
For those arriving around summer 2013, I believe some of this thread is outdated.
I followed this howto which recommends Vundle over Pathogen. After one days use I found installing plugins trivial.
The klen/python-mode plugin deserves special mention. It provides pyflakes and pylint amongst other features.
I have just started using Valloric/YouCompleteMe and I love it. It has C-lang auto-complete and python also works great thanks to jedi integration. It may well replace jedi-vim as per this discussion /davidhalter/jedi-vim/issues/119
Finally browsing the /carlhuda/janus plugins supplied is a good guide to useful scripts you might not know you are looking for such as NerdTree, vim-fugitive, syntastic, powerline, ack.vim, snipmate...
All the above '{}/{}' are found on github you can find them easily with Google.
This strongly implies that your data IS NOT NORMALISED to begin with.
Something like this should work (NB you've not mentioned of your using any other languages - so its written as a MySQL stored procedure)
create procedure replace_all(find varchar(255),
replce varchar(255),
indb varcv=char(255))
DECLARE loopdone INTEGER DEFAULT 0;
DECLARE currtable varchar(100);
DECLARE alltables CURSOR FOR SELECT t.tablename, c.column_name
FROM information_schema.tables t,
information_schema.columns c
WHERE t.table_schema=indb
AND c.table_schema=indb
AND t.table_name=c.table_name;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET loopdone = 1;
OPEN alltables;
tableloop: LOOP
FETCH alltables INTO currtable, currcol;
IF (loopdone>0) THEN LEAVE LOOP;
END IF;
SET stmt=CONCAT('UPDATE ',
indb, '.', currtable, ' SET ',
currcol, ' = word_sub(\'', find,
'\','\'', replce, '\') WHERE ',
currcol, ' LIKE \'%', find, '%\'');
PREPARE s1 FROM stmt;
EXECUTE s1;
DEALLOCATE PREPARE s1;
END LOOP;
END //
I'll leave it to you to work out how to declare the word_sub function.
I had this problem. My solution is: change same password of other in windowns. Restart Service (check logon in tab Service SQL).
You can check the HttpContext.Current.User.Identity.IsAuthenticated
property which will allow you to know whether there's a currently authenticated user or not.
lodash provides a shorthand method to check if undefined or null:
_.isNil(yourVariable)
I am getting day
, month
and year
using dedicated functions moment().date(), moment().month() and moment().year() of momentjs
.
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.
Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()
Try
byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]
byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray));
// This work because all Base64-encoding is done with pure ASCII characters
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
Unblock multi-line comment
Ctrl+5
Multi-line comment
Ctrl+4
NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.
Personally none of the above worked for me. What did:
new_str = [str(x) for x in old_obj][0]
You need to add reference (System.Web
)
Reference to System.Web
Edit %APPDATA%\Sublime Text 2\Python\Python.sublime-build
Change content to:
{
"cmd": ["C:\\python27\\python.exe", "-u", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
change the "c:\python27" part to any version of python you have in your system.
my function support removing param
function updateURLParameter(url, param, paramVal, remove = false) {
var newAdditionalURL = '';
var tempArray = url.split('?');
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var rows_txt = '';
if (additionalURL)
newAdditionalURL = decodeURI(additionalURL) + '&';
if (remove)
newAdditionalURL = newAdditionalURL.replace(param + '=' + paramVal, '');
else
rows_txt = param + '=' + paramVal;
window.history.replaceState('', '', (baseURL + "?" + newAdditionalURL + rows_txt).replace('?&', '?').replace('&&', '&').replace(/\&$/, ''));
}
Andrea is correct. we can do it using command line.
And we still can program it, by
ZkClient zkClient = new ZkClient("localhost:2181", 10000);
zkClient.deleteRecursive(ZkUtils.getTopicPath("test2"));
Actually I do not recommend you delete topic on Kafka 0.8.1.1. I can delete this topic by this method, but if you check log for zookeeper, deletion mess it up.
You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.
In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.
select
p.product_id,
p.type_id,
p.product_name,
p.type,
case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
Product p
inner join Product_Type pt on
pt.type_id = p.type_id
left join Product_ArtistAuthor paa on
paa.artist_id = p.artist_id
where
p.product_id = $pid
I used a left join since I don't know the business logic.
There's are multiple ways to split a string :
_
import net package
host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
Split based on struct :
_
type ServerDetail struct {
Host string
Port string
err error
}
ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port
Now use in you code like ServerDetail.Host
and ServerDetail.Port
If you don't want to split specific string do it like this:
type ServerDetail struct {
Host string
Port string
}
ServerDetail = strings.Split([Your_String], ":") // Common split method
and use like ServerDetail.Host
and ServerDetail.Port
.
That's All.
To encode an array that contains special characters, ISO 8859-1 to UTF8. (If utf8_encode & utf8_decode is not what is working for you, this might be an option)
Everything that is in ISO-8859-1 should be converted to UTF8:
$utf8 = utf8_encode('? ??? ??? ????!'); //contains UTF8 & ISO 8859-1 characters;
$iso88591 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8');
$data = $iso88591;
Encode should work after this:
$encoded_data = json_encode($data);
You will need to use reflection to get the type "TestRunner". Use the Assembly.GetType method.
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
Type type = assembly.GetType("TestRunner");
var obj = (TestRunner)Activator.CreateInstance(type);
obj.Run();
}
}
in addition to all the answers that other friends have , if somebody who is looking this post is looking for a way to delete a "Folder" not a "file" , should take care that Folders must delete by php rmdir() function and if u want to delete a "Folder" by unlink()
, u will encounter with a wrong Warning message that says "permission denied"
however u can make folders & files by mkdir()
but the way u delete folders (rmdir()
) is different from the way you delete files(unlink()
)
eventually as a fact:
in many programming languages, any permission related error may not directly means an actual permission issue
for example, if you want to readSync
a file that doesn't exist with node fs module
you will encounter a wrong EPERM
error
You could use hidden input tags. I get no validation errors at w3.org with this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang='en' xml:lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="content-type" />
<title>Hello</title>
</head>
<body>
<div>
<a class="article" href="link/for/non-js-users.html">
<input style="display: none" name="articleid" type="hidden" value="5" />
</a>
</div>
</body>
</html>
With jQuery you'd get the article ID with something like (not tested):
$('.article input[name=articleid]').val();
But I'd recommend HTML5 if that is an option.
Just use crontab -e
and follow the tutorial here.
Look at point 3 for a guide on how to specify the frequency.
Based on your requirement, it should effectively be:
*/10 * * * * /usr/bin/python script.py
Depends on what you have. If your svg icon is just a path, then it's easy enough to add that glyph by just copying the 'd' attribute to a new <glyph> element. However, the path needs to be scaled to the font's coordinate system (the EM-square, which typically is [0,0,2048,2048] - the standard for Truetype fonts) and aligned with the baseline you want.
Not all browsers support svg fonts however, so you're going to have to convert it to other formats too if you want it to work everywhere.
Fontforge can import svg files (select a glyph slot, File > Import and then select your svg image), and you can then convert to all the relevant font formats (svg, truetype, woff etc).
Okay, A housemate took a look at it and figured it out:
func addCategory() {
var popoverContent = self.storyboard?.instantiateViewControllerWithIdentifier("NewCategory") as UIViewController
var nav = UINavigationController(rootViewController: popoverContent)
nav.modalPresentationStyle = UIModalPresentationStyle.Popover
var popover = nav.popoverPresentationController
popoverContent.preferredContentSize = CGSizeMake(500,600)
popover.delegate = self
popover.sourceView = self.view
popover.sourceRect = CGRectMake(100,100,0,0)
self.presentViewController(nav, animated: true, completion: nil)
}
That's the way.
You don't talk to the popover itself anymore, you talk to the view controller inside of it to set the content size, by calling the property preferredContentSize
1.Click Add on your project file new item and add windows form, the default name will be Form2.
2.Create button in form1 (your original first form) and click it. Under that button add the above code i.e:
var form2 = new Form2();
form2.Show();
3.It will work.
I hope the below code will help. It will create an EditText and a Log In button. Both placed relatively. All done in MainActivity.java.
package com.example.atul.allison;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RelativeLayout;
import android.widget.Button;
import android.graphics.Color;
import android.widget.EditText;
import android.content.res.Resources;
import android.util.TypedValue;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Layout
RelativeLayout atulsLayout = new RelativeLayout(this);
atulsLayout.setBackgroundColor(Color.GREEN);
//Button
Button redButton = new Button(this);
redButton.setText("Log In");
redButton.setBackgroundColor(Color.RED);
//Username input
EditText username = new EditText(this);
redButton.setId(1);
username.setId(2);
RelativeLayout.LayoutParams buttonDetails= new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
RelativeLayout.LayoutParams usernameDetails= new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
//give rules to position widgets
usernameDetails.addRule(RelativeLayout.ABOVE,redButton.getId());
usernameDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
usernameDetails.setMargins(0,0,0,50);
buttonDetails.addRule(RelativeLayout.CENTER_HORIZONTAL);
buttonDetails.addRule(RelativeLayout.CENTER_VERTICAL);
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200,r.getDisplayMetrics());
username.setWidth(px);
//Add widget to layout(button is now a child of layout)
atulsLayout.addView(redButton,buttonDetails);
atulsLayout.addView(username,usernameDetails);
//Set these activities content/display to this view
setContentView(atulsLayout);
}
}