If you have a form as such:
<form id="myform">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$('#myform').submit(function() {
// DO STUFF...
return true; // return false to cancel form action
});
These answers don't cover very well MULTIPLE variables.
Doing the inline assignment in a stored procedure causes those results to ALSO be sent back in the resultset. That can be confusing. To using the SELECT...INTO syntax with multiple variables you do:
SELECT a, b INTO @a, @b FROM mytable LIMIT 1;
The SELECT must return only 1 row, hence LIMIT 1, although that isn't always necessary.
NEW ANSWER Use Glide library for this. This lib is also recommended by Google. See How to round an image with Glide library?
OLD ANSWER
Just add that image in a cardView
and set cardView's elevation on 0dp...will do the trick (in my case was a viewPager
with images - just replace the viewPager
with an ImageView
):
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="250dp"
app:cardElevation="0dp">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
I often use something similar to this:
import os
DATA_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'datadir'))
# if you have more paths to set, you might want to shorten this as
here = lambda x: os.path.abspath(os.path.join(os.path.dirname(__file__), x))
DATA_DIR = here('datadir')
pathjoin = os.path.join
# ...
# later in script
for fn in os.listdir(DATA_DIR):
f = open(pathjoin(DATA_DIR, fn))
# ...
The variable
__file__
holds the file name of the script you write that code in, so you can make paths relative to script, but still written with absolute paths. It works quite well for several reasons:
But you need to watch for platform compatibility - Windows' os.pathsep is different than UNIX.
Well your onclick function works absolutely fine its your this line
window.external.values(a.value, b.value, c.value, d.value, e.value);
window.external is object and has no method name values
<html>
<head>
<script type="text/javascript">
function exportToForm(a,b,c,d,e) {
// window.external.values(a.value, b.value, c.value, d.value, e.value);
//use alert to check its working
alert("HELLO");
}
</script>
</head>
<body>
<img onclick="exportToForm('1.6','55','10','50','1');" src="China-Flag-256.png"/>
<button onclick="exportToForm('1.6','55','10','50','1');" style="background-color: #00FFFF">Export</button>
</body>
</html>
$('#testID2').addClass('test3').removeClass('test2');
jQuery addClass API reference
Your question has already been answered, but IIRC you can replace lines like:
if d.has_key(scope_item):
with:
if scope_item in d:
That is, d
references d.keys()
in that construction. Sometimes defaultdict
isn't the best option (for example, if you want to execute multiple lines of code after the else
associated with the above if
), and I find the in
syntax easier to read.
<span>
elements are inline elements, as such layout properties such as width
or margin
don't work. You can fix that by either changing the <span>
to a block element (such as <div>
), or by using padding instead.
Note that making a span
element a block element by adding display: block;
is redundant, as a span
is by definition a otherwise style-less inline element whereas div
is an otherwise style-less block element. So the correct solution is to use a div
instead of a block-span
.
I'm not exactly sure how cordova works, but once the licenses are accepted it creates a file. You could create that file manually. It is described on this question, but here's the commands to create the required license file.
Linux:
mkdir "$ANDROID_HOME/licenses"
echo -e "\n8933bad161af4178b1185d1a37fbf41ea5269c55" > "$ANDROID_HOME/licenses/android-sdk-license"
Windows:
mkdir "%ANDROID_HOME%\licenses"
echo |set /p="8933bad161af4178b1185d1a37fbf41ea5269c55" > "%ANDROID_HOME%\licenses\android-sdk-license"
The "call" solution has some problems.
It fails with many different contents, as the parameters of a CALL
are parsed twice by the parser.
These lines will produce more or less strange problems
one
two%222
three & 333
four=444
five"555"555"
six"&666
seven!777^!
the next line is empty
the end
Therefore you shouldn't use the value of %%a
with a call, better move it to a variable and then call a function with only the name of the variable.
@echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ t.txt"`) do (
set "myVar=%%a"
call :processLine myVar
)
goto :eof
:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
ENDLOCAL
goto :eof
This feature has been introduced in npm v5
. update to npm using npm install -g npm@latest
and
to update package.json
delete /node_modules
and package-lock.json (if you have any)
run npm update
. this will update the dependencies package.json to the latest, based on semver.
to update to very latest version. you can go with npm-check-updates
We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.
CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;
...your code here...
END
Try this..
select starttime,endtime, case
when DATEDIFF(minute,starttime,endtime) < 60 then DATEDIFF(minute,starttime,endtime)
when DATEDIFF(minute,starttime,endtime) >= 60
then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416
All You need is DateDiff..
I believe your issue is with regards to the server. The angular documentation with regards to HTML5 mode (at the link in your question) states:
Server side Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application (e.g. index.html)
I believe you'll need to setup a url rewrite from /about to /.
List<T>.Add
adds a single element. Instead, use List<T>.AddRange
to add multiple values.
Additionally, List<T>.AddRange
takes an IEnumerable<T>
, so you don't need to convert tripDetails
into a List<TripDetails>
, you can pass it directly, e.g.:
tripDetailsCollection.AddRange(tripDetails);
Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow()
,doAnswer()
,doNothing()
,doReturn()
family of methods from Mockito framework to mock void methods.
For example,
Mockito.doThrow(new Exception()).when(instance).methodName();
or if you want to combine it with follow-up behavior,
Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();
Presuming that you are looking at mocking the setter setState(String s)
in the class World below is the code uses doAnswer
method to mock the setState
.
World mockWorld = mock(World.class);
doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
System.out.println("called with arguments: " + Arrays.toString(args));
return null;
}
}).when(mockWorld).setState(anyString());
EDIT : Solution without touching RegistryKeys - im Sorry Op.
I found out that there is a solution in C# - the original can be found here : https://blogs.msdn.microsoft.com/webdav_101/2016/07/26/sample-detecting-installed-outlook-and-its-bitness/
I modified it a bit for my needs.
just pass the correct outlookPath to GetOutlookBitness()
public enum BinaryType : uint
{
SCS_32BIT_BINARY = 0, // A 32-bit Windows-based application
SCS_64BIT_BINARY = 6, // A 64-bit Windows-based application.
SCS_DOS_BINARY = 1, // An MS-DOS – based application
SCS_OS216_BINARY = 5, // A 16-bit OS/2-based application
SCS_PIF_BINARY = 3, // A PIF file that executes an MS-DOS – based application
SCS_POSIX_BINARY = 4, // A POSIX – based application
SCS_WOW_BINARY = 2 // A 16-bit Windows-based application
}
[DllImport("kernel32.dll")]
static extern bool GetBinaryType(string lpApplicationName, out BinaryType lpBinaryType);
public int GetOutlookBitness(string FilePath)
{
int bitness = 0;
if (File.Exists(FilePath))
{
BinaryType type;
GetBinaryType(FilePath, out type);
switch (type)
{
case BinaryType.SCS_32BIT_BINARY:
bitness = 32;
break;
case BinaryType.SCS_64BIT_BINARY:
bitness = 64;
break;
}
}
return bitness;
}
For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc
file.
Simply call test2
from test1
like:
EXEC test2 @newId, @prod, @desc;
Make sure to get @id
using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:
SELECT @newId = SCOPE_IDENTITY()
There's a static method values()
which is documented, but not where you'd expect it: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
enum MyEnum {
FIRST, SECOND, THIRD;
private static MyEnum[] allValues = values();
public static MyEnum fromOrdinal(int n) {return allValues[n];}
}
In principle, you can use just values()[i]
, but there are rumors that values()
will create a copy of the array each time it is invoked.
For Spark 1.5 or later, you can use the functions package:
from pyspark.sql.functions import *
newDf = df.withColumn('address', regexp_replace('address', 'lane', 'ln'))
Quick explanation:
withColumn
is called to add (or replace, if the name exists) a column to the data frame. regexp_replace
will generate a new column by replacing all substrings that match the pattern.This is a simple copy, just like you would do with memcpy()
(indeed, some compilers actually produce a call to memcpy()
for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.
It can be done fully client side, but all javascript file names must be specified. For example, as array items:
function loadScripts(){
var directory = 'script/';
var extension = '.js';
var files = ['model', 'view', 'controller'];
for (var file of files){
var path = directory + file + extension;
var script = document.createElement("script");
script.src = path;
document.body.appendChild(script);
}
}
You can go to /etc/init.d/ - you will see a daemon template called skeleton.
You can duplicate it and then enter your script under the start function.
The $
marks the end of a string, so something like this should work: [[^abc]*]$
where you're looking for anything NOT ENDING in any iteration of abc
, but it would have to be at the end
Also if you're using a scripting language with regex (like php or js), they have a search function that stops when it first encounters a pattern (and you can specify start from the left or start from the right, or with php, you can do an implode to mirror the string).
A late entry...
To test whether or not the IIS Application gets started before the debugger has had enough time to attach just add this to the top or bottom of your GLOBAL.ASAX's Application_Start
.
throw new ApplicationException("Yup, it fired");
You can push your local branch to a new remote branch like so:
git push origin master:test
(Assuming origin
is your remote, master
is your local branch name and test
is the name of the new remote branch, you wish to create.)
If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u
(on newer versions of Git) or --set-upstream
, so:
git push -u origin master:test
or
git push --set-upstream origin master:test
...will create a new remote branch, named test
, in remote repository origin
, based on your local master
, and setup your local master
to track it.
Yes Go does accept first-class functions.
See the article "First Class Functions in Go" for useful links.
By having the .5s delay on transitioning the opacity property, the element will be completely transparent (and thus invisible) the whole time its height is transitioning. So the only thing you will actually see is the opacity changing. So you will get the same effect as leaving the height property out of the transition :
"transition: opacity .5s .5s;"
Is that what you're wanting? If not, and you're wanting to see the height transition, you can't have an opacity of zero during the whole time that it's transitioning.
When you type x = 0
that is creating a new int
variable (name) and assigning a zero to it.
When you type x[age1]
that is trying to access the age1
'th entry, as if x
were an array.
Use SpecialCells to delete only the rows that are visible after autofiltering:
ActiveSheet.Range("$A$1:$I$" & lines).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
If you have a header row in your range that you don't want to delete, add an offset to the range to exclude it:
ActiveSheet.Range("$A$1:$I$" & lines).Offset(1, 0).SpecialCells _
(xlCellTypeVisible).EntireRow.Delete
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}
array_push == $res_arr_values[] = $row;
example
<?php
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
?>
I know it has a lot of answers, but I want to write my version of split function like others and like string_split SQL Server 2016 native function.
create function [dbo].[Split]
(
@Value nvarchar(max),
@Delimiter nvarchar(50)
)
returns @tbl table
(
Seq int primary key identity(1, 1),
Value nvarchar(max)
)
as begin
declare @Xml xml = cast('<d>' + replace(@Value, @Delimiter, '</d><d>') + '</d>' as xml)
insert into @tbl
(Value)
select a.split.value('.', 'nvarchar(max)') as Value
from @Xml.nodes('/d') a(split)
return
end
Here's a answer to question.
CREATE TABLE Testdata
(
SomeID INT,
OtherID INT,
String VARCHAR(MAX)
)
INSERT Testdata SELECT 1, 9, '18,20,22'
INSERT Testdata SELECT 2, 8, '17,19'
INSERT Testdata SELECT 3, 7, '13,19,20'
INSERT Testdata SELECT 4, 6, ''
INSERT Testdata SELECT 9, 11, '1,2,3,4'
select t.SomeID, t.OtherID, s.Value
from Testdata t
cross apply dbo.Split(t.String, ',') s
--Output
SomeID OtherID Value
1 9 18
1 9 20
1 9 22
2 8 17
2 8 19
3 7 13
3 7 19
3 7 20
4 6
9 11 1
9 11 2
9 11 3
9 11 4
Joining Split with other split
declare @Names nvarchar(max) = 'a,b,c,d'
declare @Codes nvarchar(max) = '10,20,30,40'
select n.Seq, n.Value Name, c.Value Code
from dbo.Split(@Names, ',') n
inner join dbo.Split(@Codes, ',') c on n.Seq = c.Seq
--Output
Seq Name Code
1 a 10
2 b 20
3 c 30
4 d 40
Split two times
declare @NationLocSex nvarchar(max) = 'Korea,Seoul,1;Vietnam,Kiengiang,0;China,Xian,0'
; with rows as
(
select Value
from dbo.Split(@NationLocSex, ';')
)
select rw.Value r, cl.Value c
from rows rw
cross apply dbo.Split(rw.Value, ',') cl
--Output
r c
Korea,Seoul,1 Korea
Korea,Seoul,1 Seoul
Korea,Seoul,1 1
Vietnam,Kiengiang,0 Vietnam
Vietnam,Kiengiang,0 Kiengiang
Vietnam,Kiengiang,0 0
China,Xian,0 China
China,Xian,0 Xian
China,Xian,0 0
Split to columns
declare @Numbers nvarchar(50) = 'First,Second,Third'
; with t as
(
select case when Seq = 1 then Value end f1,
case when Seq = 2 then Value end f2,
case when Seq = 3 then Value end f3
from dbo.Split(@Numbers, ',')
)
select min(f1) f1, min(f2) f2, min(f3) f3
from t
--Output
f1 f2 f3
First Second Third
Generate rows by range
declare @Ranges nvarchar(50) = '1-2,4-6'
declare @Numbers table (Num int)
insert into @Numbers values (1),(2),(3),(4),(5),(6),(7),(8)
; with t as
(
select r.Seq, r.Value,
min(case when ft.Seq = 1 then ft.Value end) ValueFrom,
min(case when ft.Seq = 2 then ft.Value end) ValueTo
from dbo.Split(@Ranges, ',') r
cross apply dbo.Split(r.Value, '-') ft
group by r.Seq, r.Value
)
select t.Seq, t.Value, t.ValueFrom, t.ValueTo, n.Num
from t
inner join @Numbers n on n.Num between t.ValueFrom and t.ValueTo
--Output
Seq Value ValueFrom ValueTo Num
1 1-2 1 2 1
1 1-2 1 2 2
2 4-6 4 6 4
2 4-6 4 6 5
2 4-6 4 6 6
The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?
If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:
public class MyClass
{
public void doSomething(int i)
{
...
}
public void doSomething(int i, String s)
{
...
}
public void doSomething(int i, String s, boolean b)
{
...
}
}
If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:
public MyClass
{
public void doSomething(int... integers)
{
for (int i : integers)
{
...
}
}
}
Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
In the project file is folder "bin/debug/your_appliacion_name.exe". This is final executable program file.
Your compound PRIMARY KEY
specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT
(already implied), too:
CREATE TABLE tags
(
question_id INTEGER NOT NULL,
tag_id SERIAL NOT NULL,
tag1 VARCHAR(20),
tag2 VARCHAR(20),
tag3 VARCHAR(20),
PRIMARY KEY(question_id, tag_id)
);
NOTICE: CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
CREATE TABLE
pg=> \d tags
Table "public.tags"
Column | Type | Modifiers
-------------+-----------------------+-------------------------------------------------------
question_id | integer | not null
tag_id | integer | not null default nextval('tags_tag_id_seq'::regclass)
tag1 | character varying(20) |
tag2 | character varying(20) |
tag3 | character varying(20) |
Indexes:
"tags_pkey" PRIMARY KEY, btree (question_id, tag_id)
You can use mt_rand()
$random = $ran[mt_rand(0, count($ran) - 1)];
This comes in handy as a function as well if you need the value
function random_value($array, $default=null)
{
$k = mt_rand(0, count($array) - 1);
return isset($array[$k])? $array[$k]: $default;
}
There are specific suffixes for long
(e.g. 39832L
), float
(e.g. 2.4f
) and double
(e.g. -7.832d
).
If there is no suffix, and it is an integral type (e.g. 5623
), it is assumed to be an int
. If it is not an integral type (e.g. 3.14159
), it is assumed to be a double
.
In all other cases (byte
, short
, char
), you need the cast as there is no specific suffix.
The Java spec allows both upper and lower case suffixes, but the upper case version for long
s is preferred, as the upper case L
is less easy to confuse with a numeral 1
than the lower case l
.
See the JLS section 3.10 for the gory details (see the definition of IntegerTypeSuffix
).
Please check the below code:-
.backgroundImageCVR{_x000D_
position:relative;_x000D_
padding:15px;_x000D_
}_x000D_
.background-image{_x000D_
position:absolute;_x000D_
left:0;_x000D_
right:0;_x000D_
top:0;_x000D_
bottom:0;_x000D_
background:url('http://www.planwallpaper.com/static/images/colorful-triangles-background_yB0qTG6.jpg');_x000D_
background-size:cover;_x000D_
z-index:1;_x000D_
-webkit-filter: blur(10px);_x000D_
-moz-filter: blur(10px);_x000D_
-o-filter: blur(10px);_x000D_
-ms-filter: blur(10px);_x000D_
filter: blur(10px); _x000D_
}_x000D_
.content{_x000D_
position:relative;_x000D_
z-index:2;_x000D_
color:#fff;_x000D_
}
_x000D_
<div class="backgroundImageCVR">_x000D_
<div class="background-image"></div>_x000D_
<div class="content">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis aliquam erat in ante malesuada, facilisis semper nulla semper. Phasellus sapien neque, faucibus in malesuada quis, lacinia et libero. Sed sed turpis tellus. Etiam ac aliquam tortor, eleifend rhoncus metus. Ut turpis massa, sollicitudin sit amet molestie a, posuere sit amet nisl. Mauris tincidunt cursus posuere. Nam commodo libero quis lacus sodales, nec feugiat ante posuere. Donec pulvinar auctor commodo. Donec egestas diam ut mi adipiscing, quis lacinia mauris condimentum. Quisque quis odio venenatis, venenatis nisi a, vehicula ipsum. Etiam at nisl eu felis vulputate porta.</p>_x000D_
<p>Fusce ut placerat eros. Aliquam consequat in augue sed convallis. Donec orci urna, tincidunt vel dui at, elementum semper dolor. Donec tincidunt risus sed magna dictum, quis luctus metus volutpat. Donec accumsan et nunc vulputate accumsan. Vestibulum tempor, erat in mattis fringilla, elit urna ornare nunc, vel pretium elit sem quis orci. Vivamus condimentum dictum tempor. Nam at est ante. Sed lobortis et lorem in sagittis. In suscipit in est et vehicula.</p>_x000D_
</div>_x000D_
</div>
_x000D_
array_map seems good for this too
$codes = array('tn','us','fr');
$names = array('Tunisia','United States','France');
array_map(function ($code, $name) {
echo '<option value="' . $code . '">' . $name . '</option>';
}, $codes, $names);
Other benefits are:
If one array is shorter than the other, the callback receive null
values to fill in the gap.
You can use more than 2 arrays to iterate through.
I don't think you can get it directly, but there are a few ways to find it indirectly.
One way is to use the GC.GetTotalMemory
method to measure the amount of memory used before and after creating your object. This won't be perfect, but as long as you control the rest of the application you may get the information you are interested in.
Apart from that you can use a profiler to get the information or you could use the profiling api to get the information in code. But that won't be easy to use I think.
See Find out how much memory is being used by an object in C#? for a similar question.
Try opening config-db.php, it's inside /etc/phpmyadmin. In my case, the user was phpmyadmin, and my password was correct. Maybe your problem is that you're using the usual 'root' username, and your password could be correct.
I have created a thin wrapper around fetch() with many improvements if you are using a purely json REST API:
// Small library to improve on fetch() usage
const api = function(method, url, data, headers = {}){
return fetch(url, {
method: method.toUpperCase(),
body: JSON.stringify(data), // send it as stringified json
credentials: api.credentials, // to keep the session on the request
headers: Object.assign({}, api.headers, headers) // extend the headers
}).then(res => res.ok ? res.json() : Promise.reject(res));
};
// Defaults that can be globally overwritten
api.credentials = 'include';
api.headers = {
'csrf-token': window.csrf || '', // only if globally set, otherwise ignored
'Accept': 'application/json', // receive json
'Content-Type': 'application/json' // send json
};
// Convenient methods
['get', 'post', 'put', 'delete'].forEach(method => {
api[method] = api.bind(null, method);
});
To use it you have the variable api
and 4 methods:
api.get('/todo').then(all => { /* ... */ });
And within an async
function:
const all = await api.get('/todo');
// ...
Example with jQuery:
$('.like').on('click', async e => {
const id = 123; // Get it however it is better suited
await api.put(`/like/${id}`, { like: true });
// Whatever:
$(e.target).addClass('active dislike').removeClass('like');
});
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
For a massive speed increase, use NumPy's where function.
Create a two-column DataFrame with 100,000 rows with some zeros.
df = pd.DataFrame(np.random.randint(0,3, (100000,2)), columns=list('ab'))
numpy.where
df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
%timeit df['b'] = np.where(df.a.values == 0, np.nan, df.b.values)
685 µs ± 6.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit df.loc[df['a'] == 0, 'b'] = np.nan
3.11 ms ± 17.2 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Numpy's where
is about 4x faster
Answer to the original question:
os.urandom(n)
Quote from: http://docs.python.org/2/library/os.html
Return a string of n random bytes suitable for cryptographic use.
This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, NotImplementedError will be raised.
For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom.
1. Response to the main question
The script $(window).height()
does work well (showing the viewport's height and not the document with scrolling height), BUT it needs that you put correctly the doctype tag in your document, for example these doctypes:
For HTML 5:
<!DOCTYPE html>
For transitional HTML4:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Probably the default doctype assumed by some browsers is such, that $(window).height()
takes the document's height and not the browser's height. With the doctype specification, it's satisfactorily solved, and I'm pretty sure you peps will avoid the "changing scroll-overflow to hidden and then back", which is, I'm sorry, a bit dirty trick, specially if you don't document it on the code for future programmer's usage.
2. An ADDITIONAL tip, note aside: Moreover, if you are doing a script, you can invent tests to help programmers in using your libraries, let me invent a couple:
$(document).ready(function() {
if(typeof $=='undefined') {
alert("PROGRAMMER'S Error: you haven't called JQuery library");
} else if (typeof $.ui=='undefined') {
alert("PROGRAMMER'S Error: you haven't installed the UI Jquery library");
}
if(document.doctype==null || screen.height < parseInt($(window).height()) ) {
alert("ERROR, check your doctype, the calculated heights are not what you might expect");
}
});
EDIT: about the part 2, "An ADDITIONAL tip, note aside": @Machiel, in yesterday's comment (2014-09-04), was UTTERLY right: the check of the $ can not be inside the ready event of Jquery, because we are, as he pointed out, assuming $ is already defined. THANKS FOR POINTING THAT OUT, and do please the rest of you readers correct this, if you used it in your scripts. My suggestion is: in your libraries put an "install_script()" function which initializes the library (put any reference to $ inside such init function, including the declaration of ready()) and AT THE BEGINNING of such "install_script()" function, check if the $ is defined, but make everything independent of JQuery, so your library can "diagnose itself" when JQuery is not yet defined. I prefer this method rather than forcing the automatic creation of a JQuery bringing it from a CDN. Those are tiny notes aside for helping out other programmers. I think that people who make libraries must be richer in the feedback to potential programmer's mistakes. For example, Google Apis need an aside manual to understand the error messages. That's absurd, to need external documentation for some tiny mistakes that don't need you to go and search a manual or a specification. The library must be SELF-DOCUMENTED. I write code even taking care of the mistakes I might commit even six months from now, and it still tries to be a clean and not-repetitive code, already-written-to-prevent-future-developer-mistakes.
if(jRadioButton1.isSelected()){
jTextField1.setText("Welcome");
}
else if(jRadioButton2.isSelected()){
jTextField1.setText("Hello");
}
AWS released a new Service to query S3 buckets with SQL: Amazon Athena https://aws.amazon.com/athena/
Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
Ctrl + C + V works for me on VS2012 with no extension.
It's Much Simplier!
Pure batch solution. No temp files. No long scripts.
@echo off
setlocal enabledelayedexpansion
set String=abcde12345
for /L %%x in (1,1,1000) do ( if "!String:~%%x!"=="" set Lenght=%%x & goto Result )
:Result
echo Lenght: !Lenght!
1000
is the maximum estimated string lenght. Change it based on your needs.
Okay I had the same issue and solved it. For some reason the mysql_secure_installation script doesn't work out of the box when using Homebrew to install mysql, so I did it manually. On the CLI enter:
mysql -u root
That should get you into mysql. Now do the following (taken from mysql_secure_installation):
UPDATE mysql.user SET Password=PASSWORD('your_new_pass') WHERE User='root';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'
DROP DATABASE test;
FLUSH PRIVILEGES;
Now exit and get back into mysql with: mysql -u root -p
I fix without .row
<div class="col col-33 left" ng-repeat="photo in photos">
Content here...
</div>
and css
.left {
float: left;
}
Use the below code. Align the button to buttom. It's working.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btn_back"
android:layout_width="100dp"
android:layout_height="80dp"
android:text="Back" />
<TextView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.97"
android:gravity="center"
android:text="Payment Page" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
</LinearLayout>
</LinearLayout>
There is an easier way to get a property from a json string. Using a package.json
file as an example, try this:
#!/usr/bin/env bash
my_val="$(json=$(<package.json) node -pe "JSON.parse(process.env.json)['version']")"
We're using process.env
because this gets the file's contents into node.js as a string without any risk of malicious contents escaping their quoting and being parsed as code.
Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon, level)
.setLargeIcon(largeIcon)
.setContentIntent(intent)
.setColorized(true)
.setDefaults(0)
.setCategory(Notification.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_HIGH);
You say in a comment you want to get "15.09.2016".
For this, use Date
and DateFormatter
:
let date = Date()
let formatter = DateFormatter()
Give the format you want to the formatter:
formatter.dateFormat = "dd.MM.yyyy"
Get the result string:
let result = formatter.string(from: date)
Set your label:
label.text = result
Result:
15.09.2016
the ideal way is to
{{ something|safe }}
than completely turning off auto escaping.
To get all rows, don't specify the key. Try this:
$meta_values = get_post_meta( get_the_ID() );
var_dump( $meta_values );
Hope it helps!
I already found the answer
Swift 4
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)
Swift 3
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)
std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; }
else {
while(str.at(0) == ' ') { str.erase(0, 1);}
while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
return str ;
}
}
// creation
cv::SimpleBlobDetector * blob_detector;
blob_detector = new SimpleBlobDetector();
blob_detector->create("SimpleBlobDetector");
// change params - first move it to public!!
blob_detector->params.filterByArea = true;
blob_detector->params.minArea = 1;
blob_detector->params.maxArea = 32000;
// or read / write them with file
FileStorage fs("test_fs.yml", FileStorage::WRITE);
FileNode fn = fs["features"];
//blob_detector->read(fn);
// detect
vector<KeyPoint> keypoints;
blob_detector->detect(img_text, keypoints);
fs.release();
I do know why, but params are protected. So I moved it in file features2d.hpp to be public:
virtual void read( const FileNode& fn );
virtual void write( FileStorage& fs ) const;
public:
Params params;
protected:
struct CV_EXPORTS Center
{
Point2d loc
If you will not do this, the only way to change params is to create file (FileStorage fs("test_fs.yml", FileStorage::WRITE);
), than open it in notepad, and edit. Or maybe there is another way, but I`m not aware of it.
You can use as below :
.width100 {_x000D_
max-width: 100px;_x000D_
height: 100px;_x000D_
width: auto;_x000D_
border: solid red;_x000D_
}
_x000D_
<img src="https://www.gravatar.com/avatar/dc48e9b92e4210d7a3131b3ef46eb8b1?s=512&d=identicon&r=PG" class="width100" />
_x000D_
I will use horizontal stackview. It can remove the frame when the subview is hidden.
In image below, the red view is the actual container for your content and has 10pt trailing space to orange superview (ShowHideView), then just connect ShowHideView to IBOutlet and show/hide/remove it programatically.
I know that the question is two years old, but it was the first result of what I am looking for. I found a good answers and I hope I can help other users.
I will make this brief:
use the $_SERVER["PHP_SELF"]
Variable with htmlspecialchars
():
`htmlspecialchars($_SERVER["PHP_SELF"]);`
PHP_SELF returns the filename of the currently executing script.
htmlspecialchars
() function converts special characters to HTML entities.
--> NO XSSScript are executed sequentially only if they do not have either a "defer" or an "async" attribute. Knowing one of the possible ID/SRC/TITLE attributes of the script tag could work also in those cases. So both Greg and Justin suggestions are correct.
There is already a proposal for a document.currentScript
on the WHATWG lists.
EDIT: Firefox > 4 already implement this very useful property but it is not available in IE11 last I checked and only available in Chrome 29 and Safari 8.
EDIT: Nobody mentioned the "document.scripts" collection but I believe that the following may be a good cross browser alternative to get the currently running script:
var me = document.scripts[document.scripts.length -1];
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
The top answer is useful but I expanded on it a bit.
If you want to set the value of your file object (the f
in as f
) based on the arguments passed to open()
here's one way to do it:
def save_arg_return_data(*args, **kwargs):
mm = MagicMock(spec=file)
mm.__enter__.return_value = do_something_with_data(*args, **kwargs)
return mm
m = MagicMock()
m.side_effect = save_arg_return_array_of_data
# if your open() call is in the file mymodule.animals
# use mymodule.animals as name_of_called_file
open_name = '%s.open' % name_of_called_file
with patch(open_name, m, create=True):
#do testing here
Basically, open()
will return an object and with
will call __enter__()
on that object.
To mock properly, we must mock open()
to return a mock object. That mock object should then mock the __enter__()
call on it (MagicMock
will do this for us) to return the mock data/file object we want (hence mm.__enter__.return_value
). Doing this with 2 mocks the way above allows us to capture the arguments passed to open()
and pass them to our do_something_with_data
method.
I passed an entire mock file as a string to open()
and my do_something_with_data
looked like this:
def do_something_with_data(*args, **kwargs):
return args[0].split("\n")
This transforms the string into a list so you can do the following as you would with a normal file:
for line in file:
#do action
declare n number(10);
begin
select count(*) into n from tab where tname='TEST';
if (n = 0) then
execute immediate
'create table TEST ( ID NUMBER(3), NAME VARCHAR2 (30) NOT NULL)';
end if;
end;
It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:
import itertools
m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i) # skips m = 5
As an aside, you woudn't want to use (*range(m), *range(m + 1, n))
even though it works because it will expand the iterables into a tuple and this is memory inefficient.
Credit: comment by njzk2, answer by Locke
JavaScript has an eval
function that evaluates a string and executes it as code:
eval(settings.functionName + '(' + t.parentNode.id + ')');
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Extending the friederbluemle solution, download the pngcrush and then use the code like this if you are running it on multiple png files
path =r"C:\\project\\project\\images" # path to all .png images
import os
png_files =[]
for dirpath, subdirs, files in os.walk(path):
for x in files:
if x.endswith(".png"):
png_files.append(os.path.join(dirpath, x))
file =r'C:\\Users\\user\\Downloads\\pngcrush_1_8_9_w64.exe' #pngcrush file
for name in png_files:
cmd = r'{} -ow -rem allb -reduce {}'.format(file,name)
os.system(cmd)
here all the png file related to projects are in 1 folder.
Mysql has this handy UPDATE INTO command ;)
edit Looks like they renamed it to REPLACE
REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted
I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).
It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java
as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:
<classpathentry kind="src" output="bin/classes" path="src/test/java">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:
There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.
Simply way in React
<input
onKeyPress={(event) => {
if (!/[0-9]/.test(event.key)) {
event.preventDefault();
}
}}
/>
IMHO the only 100% reliable way to test if you can write to a directory is to actually write to it and eventually catch exceptions.
There is a workaround which may help. You may "register" results for each set_fact iteration and then map that results to list:
---
- hosts: localhost
tasks:
- name: set fact
set_fact: foo_item="{{ item }}"
with_items:
- four
- five
- six
register: foo_result
- name: make a list
set_fact: foo="{{ foo_result.results | map(attribute='ansible_facts.foo_item') | list }}"
- debug: var=foo
Output:
< TASK: debug var=foo >
---------------------
\ ^__^
\ (oo)\_______
(__)\ )\/\
||----w |
|| ||
ok: [localhost] => {
"var": {
"foo": [
"four",
"five",
"six"
]
}
}
Form frm1 = new Form1();
frm1.Controls.Find("control_name",true)[0].Text = "I changed this from another form";
Get a date object from the jquery date picker using
var myDate = $('element').datepicker('getDate')
For mysql the date needs to be in the proper format. One option which handles any timezone issues is to use moment.js
moment(myDate).format('YYYY-MM-DD HH:mm:ss')
You need to use overflow option like below:
.nav{
max-height: 300px;
overflow-y: scroll;
}
Change the height according to amount of items you need to show
If you're coding in PHP and want to remove .php so you can have a URL like:
http://yourdomain.com/blah -> which points to /blah.php
This is all you need:
<IfModule mod_rewrite.c>
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
</IfModule>
Using 400
status codes for any other purpose than indicating that the request is malformed is just plain wrong.
If the request payload contains a byte-sequence that could not be parsed as application/json
(if the server expects that dataformat), the appropriate status code is 415
:
The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
If the request payload is syntactically correct but semantically incorrect, the non-standard 422
response code may be used, or the standard 403
status code:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.
This actually happens because the complex objects are what makes the resulting json object fails. And it fails because when the object is mapped it maps the children, which maps their parents, making a circular reference to occur. Json would take infinite time to serialize it, so it prevents the problem with the exception.
Entity Framework mapping also produces the same behavior, and the solution is to discard all unwanted properties.
Just expliciting the final answer, the whole code would be:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
new {
Result = (from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
}
, JsonRequestBehavior.AllowGet
);
}
It could also be the following in case you don't want the objects inside a Result
property:
public JsonResult getJson()
{
DataContext db = new DataContext ();
return this.Json(
(from obj in db.Things select new {Id = obj.Id, Name = obj.Name})
, JsonRequestBehavior.AllowGet
);
}
If you have node
then you can use fs
like in this answer to get all the files:
const { resolve } = require('path'),
{ readdir } = require('fs').promises;
async function getFiles(dir) {
const dirents = await readdir(dir, { withFileTypes: true });
const files = await Promise.all(dirents.map((dirent) => {
const res = resolve(dir, dirent.name);
return dirent.isDirectory() ? getFiles(res) : res;
}));
return Array.prototype.concat(...files);
}
And you might use that like this:
const directory = "./Documents/";
getFiles(directory).then(results => {
const html = `<ul>` +
results.map(fileOrDirectory => `<li>${fileOrDirectory}</li>`).join('\n') +
`</ul>`;
process.stdout.write(html);
// or you could use something like fs.writeFile to write the file directly
});
You could call it at the command-line with something like this:
$ node thatScript.js > index.html
There are few more classess in Bootstrap 4 (added in recent versions) not mentioned in other answers.
.text-black-50
and .text-white-50
are 50% transparent.
.text-body {_x000D_
color: #212529 !important;_x000D_
}_x000D_
_x000D_
.text-black-50 {_x000D_
color: rgba(0, 0, 0, 0.5) !important;_x000D_
}_x000D_
_x000D_
.text-white-50 {_x000D_
color: rgba(255, 255, 255, 0.5) !important;_x000D_
}_x000D_
_x000D_
/*DEMO*/_x000D_
p{padding:.5rem}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
_x000D_
<p class="text-body">.text-body</p>_x000D_
<p class="text-black-50">.text-black-50</p>_x000D_
<p class="text-white-50 bg-dark">.text-white-50</p>
_x000D_
This code may help some one
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<style type="text/css">
.democlass{
color:red;
}
</style>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var row = table.insertRow(rowCount);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[2].cells[i].innerHTML;
}
row = table.insertRow(table.rows.length);
for(var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if(i == (colCount - 1)) {
newcell.innerHTML = "<INPUT type=\"button\" value=\"Delete Row\" onclick=\"removeRow(this)\"/>";
} else {
newcell.innerHTML = table.rows[3].cells[i].innerHTML;
}
}
}
/**
* This method deletes the specified section of the table
* OR deletes the specified rows from the table.
*/
function removeRow(src) {
var oRow = src.parentElement.parentElement;
var rowsCount = 0;
for(var index = oRow.rowIndex; index >= 0; index--) {
document.getElementById("dataTable").deleteRow(index);
if(rowsCount == (4 - 1)) {
return;
}
rowsCount++;
}
//once the row reference is obtained, delete it passing in its rowIndex
/* document.getElementById("dataTable").deleteRow(oRow.rowIndex); */
}
</SCRIPT>
</HEAD>
<BODY>
<form name="myForm">
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD>
<INPUT type="checkbox" name="chk"/>
</TD>
<TD>
Code
</TD>
<TD>
<INPUT type="text" name="txt"/>
</TD>
<TD>
Select Country
</TD>
<TD>
<SELECT name="country">
<OPTION value="in">India</OPTION>
<OPTION value="de">Germany</OPTION>
<OPTION value="fr">France</OPTION>
<OPTION value="us">United States</OPTION>
<OPTION value="ch">Switzerland</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>
First Name
</TD>
<TD>
<INPUT type="text" name="txt1"/>
</TD>
<TD>
Last Name
</TD>
<TD>
<INPUT type="text" name="txt2"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD>Phone</TD>
<TD>
<INPUT type="text" name="txt3"/>
</TD>
<TD>Address</TD>
<TD>
<INPUT type="text" name="txt4" class="democlass"/>
</TD>
</TR>
<TR>
<TD> </TD>
<TD> </TD>
<TD>
</TD>
<TD> </TD>
<TD>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -
Base Functions
def a(x):
print('a')
return x
def b(x):
print('b')
return x
AND
if(a(True) and b(True)):
print(1,end='\n\n')
if(a(False) and b(True)):
print(2,end='\n\n')
AND-OUTPUT
a
b
1
a
OR
if(a(True) or b(False)):
print(3,end='\n\n')
if(a(False) or b(True)):
print(4,end='\n\n')
OR-OUTPUT
a
3
a
b
4
a='\nu + \lambda + \theta'
d=a.encode('string_escape').replace('\\\\','\\')
print(d)
# \nu + \lambda + \theta
This shows that there is a single backslash before the n
, l
and t
:
print(list(d))
# ['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']
There is something funky going on with your GUI. Here is a simple example of grabbing some user input through a Tkinter.Entry
. Notice that the text retrieved only has a single backslash before the n
, l
, and t
. Thus no extra processing should be necessary:
import Tkinter as tk
def callback():
print(list(text.get()))
root = tk.Tk()
root.config()
b = tk.Button(root, text="get", width=10, command=callback)
text=tk.StringVar()
entry = tk.Entry(root,textvariable=text)
b.pack(padx=5, pady=5)
entry.pack(padx=5, pady=5)
root.mainloop()
If you type \nu + \lambda + \theta
into the Entry box, the console will (correctly) print:
['\\', 'n', 'u', ' ', '+', ' ', '\\', 'l', 'a', 'm', 'b', 'd', 'a', ' ', '+', ' ', '\\', 't', 'h', 'e', 't', 'a']
If your GUI is not returning similar results (as your post seems to suggest), then I'd recommend looking into fixing the GUI problem, rather than mucking around with string_escape
and string replace
.
saveFileOnUserDevice = function(file){ // content: blob, name: string
if(navigator.msSaveBlob){ // For ie and Edge
return navigator.msSaveBlob(file.content, file.name);
}
else{
let link = document.createElement('a');
link.href = window.URL.createObjectURL(file.content);
link.download = file.name;
document.body.appendChild(link);
link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
link.remove();
window.URL.revokeObjectURL(link.href);
}
}
Here is a work around for the problem when you click "Run App" (green arrow) and get the following in the Edit Configuration dialog:
Error: Please select Android SDK
In Android Studio, do:
File > Settings
. Appearance & Behavior > System Settings > Android SDK
.Edit
buttonThis seems to save away the SDK location - even though nothing has changed - into some internal location. I inspected the .idea
and .gradle
folders but didn't see what Studio did to change a config file - but now I can run the app.
And to summarize the previous fixes - these are normally OK for a repo without build problems:
local.properties file is copied into the root folder by Studio.
The path in the local.properties file has the correct path to the android SDK - in my case it is
sdk.dir=C:\\android\\sdk
(note that this path has a different format - Studio should write this file for you based on the Text Entry field in the Android SDK Settings dialog)settings.gradle file is present in the repo - and references the application folder (typically :app)
I had this same issue . I removed dll from temp folder, remove read only access and restarted machine and got it working.
For VS Code 1.38 or if you could not find any "lightbulb" button. Pay close attention to the greyed out text above the conflicts; there is a list of actions you can take.
you can do the next "\"Value3 Line1 Value3 Line2\""
. It works for me generating a csv file in java
public static void main(String args[]){
LocalDate date=LocalDate.now();
System.out.println("Current date = "+date);
}
Try inserting <xsl:number format="1. "/><xsl:value-of select="."/><xsl:text>
in the place of ???.
Note the "1. " - this is the number format. More info: here
Its not very elegant but in case you cant change the creation of dictionary, and all you need is a dirty hack, how about this:
var item = MyDictionary.Where(x => x.Key.ToLower() == MyIndex.ToLower()).FirstOrDefault();
if (item != null)
{
TheValue = item.Value;
}
Use border-collapse and border-spacing to get spaces between the table cells. I would not recommend using floating cells as suggested by QQping.
You can use this CSS:
.content {
height: 100%;
display: inline-table;
background-color: blue;
}
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
Just make your Add
function static
by adding the static
keyword like this:
public static int Add(int x, int y)
You must do the following command:
sort -n -k1 filename
That should do it :)
I faced the same problem due to illegal spaces in my entire code.
I fixed it by selecting one of these spaces and use find and replace
to replace all matches with regular spaces.
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
On Excel 2010 try this:
This will insert a 10 second sleep in between every call to foo()
, which is approximately what you asked for should the call complete quickly.
import time
while True:
foo()
time.sleep(10)
To do other things while your foo()
is being called in a background thread
import time
import sys
import threading
def foo():
sys.stdout.write('({}) foo\n'.format(time.ctime()))
def foo_target():
while True:
foo()
time.sleep(10)
t = threading.Thread(target=foo_target)
t.daemon = True
t.start()
print('doing other things...')
You can use this syntax but it will require some changes in the SVG file. And remove any fill/stroke from the SVG itself.
icon.svg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<!-- use symbol instead of defs and g,
must add viewBox on symbol just copy yhe viewbox from the svg tag itself
must add id on symbol
-->
<symbol id="location" viewBox="0 0 430.114 430.114">
<!-- add all the icon's paths and shapes here -->
<path d="M356.208,107.051c-1.531-5.738-4.64-11.852-6.94-17.205C321.746,23.704,261.611,0,213.055,0 C148.054,0,76.463,43.586,66.905,133.427v18.355c0,0.766,0.264,7.647,0.639,11.089c5.358,42.816,39.143,88.32,64.375,131.136 c27.146,45.873,55.314,90.999,83.221,136.106c17.208-29.436,34.354-59.259,51.17-87.933c4.583-8.415,9.903-16.825,14.491-24.857 c3.058-5.348,8.9-10.696,11.569-15.672c27.145-49.699,70.838-99.782,70.838-149.104v-20.262 C363.209,126.938,356.581,108.204,356.208,107.051z M214.245,199.193c-19.107,0-40.021-9.554-50.344-35.939 c-1.538-4.2-1.414-12.617-1.414-13.388v-11.852c0-33.636,28.56-48.932,53.406-48.932c30.588,0,54.245,24.472,54.245,55.06 C270.138,174.729,244.833,199.193,214.245,199.193z"/>
</symbol>
icon.html
<svg><use xlink:href="file_path/location.svg#location"></use></svg>
@Anachronist is closest here, @Simone not far off. The caveat with percentage padding on an element is that it's based on its parent's width, so if different to your container, the proportions will be off.
The most reliable, simplest answer is:
body {_x000D_
/* for demo */_x000D_
background: lightgray;_x000D_
}_x000D_
.fixed-aspect-wrapper {_x000D_
/* anything or nothing, it doesn't matter */_x000D_
width: 60%;_x000D_
/* only need if other rulesets give this padding */_x000D_
padding: 0;_x000D_
}_x000D_
.fixed-aspect-padder {_x000D_
height: 0;_x000D_
/* last padding dimension is (100 * height / width) of item to be scaled */_x000D_
padding: 0 0 56.25%;_x000D_
position: relative;_x000D_
/* only need next 2 rules if other rulesets change these */_x000D_
margin: 0;_x000D_
width: auto;_x000D_
}_x000D_
.whatever-needs-the-fixed-aspect {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
/* for demo */_x000D_
border: 0;_x000D_
background: white;_x000D_
}
_x000D_
<div class="fixed-aspect-wrapper">_x000D_
<div class="fixed-aspect-padder">_x000D_
<iframe class="whatever-needs-the-fixed-aspect" src="/"></iframe>_x000D_
</div>_x000D_
</div>
_x000D_
In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.
Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.
Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.
Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.
The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:
struct { 11
char a; 012345678901
short b; ------------
char c; axbbcxxxdddd
int d;
};
This structure will occupy 12 bytes of memory (x being pad bytes).
Python works similarly (see the struct documentation):
>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12
Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:
>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'
Beware of letting struct handle padding. In C, these structures:
struct A { struct B {
short a; int a;
char b; char b;
}; };
are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:
>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'
If you work in MVC 4, you can watch this solution, it worked for me.
Add the following Application_Error method to my Global.asax
:
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
Server.ClearError();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
routeData.Values.Add("action", "Index");
routeData.Values.Add("exception", exception);
if (exception.GetType() == typeof(HttpException))
{
routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
}
else
{
routeData.Values.Add("statusCode", 500);
}
IController controller = new ErrorController();
controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
Response.End();
The controller itself is really simple:
public class ErrorController : Controller
{
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
Check the full source code of Mvc4CustomErrorPage at GitHub.
A more-advanced example:
? unlimited arguments.
? exist on file system (either
file
ordirectory
?) or a genericstring
.? specify if is a file
? specify is a directory
? no extensions, would work in legacy scripts!
? minimal code ?
@echo off :loop ::-------------------------- has argument ? if ["%~1"]==[""] ( echo done. goto end ) ::-------------------------- argument exist ? if not exist %~s1 ( echo not exist ) else ( echo exist if exist %~s1\NUL ( echo is a directory ) else ( echo is a file ) ) ::-------------------------- shift goto loop :end pause
? other stuff..?
¦ in %~1
- the ~
removes any wrapping "
or '
.
¦ in %~s1
- the s
makes the path be DOS 8.3 naming
, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "
s.
¦ the ["%~1"]==[""]
"can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1
(just without the "
wrapping, if any..)
if there were no arguments of if we've used shift
and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""]
.
¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)
save it as identifier.cmd
it can identify an unlimited arguments (normally you are limited to %1
-%9
), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).
this allows you to run the following commands:
?identifier.cmd c:\windows
and to get
exist is a directory done
?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE"
and to get
exist is a file done
? and multiple arguments (of course this is the whole-deal..)
identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world
and to get
exist is a directory exist is a file exist is a file not exist done.
naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)
published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory
and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax
One case I found where setAttribute
is necessary is when changing ARIA attributes, since there are no corresponding properties. For example
x.setAttribute('aria-label', 'Test');
x.getAttribute('aria-label');
There's no x.arialabel
or anything like that, so you have to use setAttribute.
Edit: x["aria-label"] does not work. You really do need setAttribute.
x.getAttribute('aria-label')
null
x["aria-label"] = "Test"
"Test"
x.getAttribute('aria-label')
null
x.setAttribute('aria-label', 'Test2')
undefined
x["aria-label"]
"Test"
x.getAttribute('aria-label')
"Test2"
One difference is that:
:map
does nvo
== normal + (visual + select) + operator pending:map!
does ic
== insert + command-line modeas stated on help map-modes
tables.
So: map
does not map to all modes.
To map to all modes you need both :map
and :map!
.
Instead of using re.search
use re.findall
it will return you all matches in a List
. Or you could also use re.finditer
(which i like most to use) it will return an Iterator Object
and you can just use it to iterate over all found matches.
line = 'bla bla bla<form>Form 1</form> some text...<form>Form 2</form> more text?'
for match in re.finditer('<form>(.*?)</form>', line, re.S):
print match.group(1)
Why don't you try this (in the 2nd line where 'form#' you need to put the proper selector of your html form):
$('.checkAll').click(function(){
$('form#myForm input:checkbox').each(function(){
$(this).prop('checked',true);
})
});
$('.uncheckAll').click(function(){
$('form#myForm input:checkbox').each(function(){
$(this).prop('checked',false);
})
});
Your html should be like this:
<form id="myForm">
<span class="checkAll">checkAll</span>
<span class="uncheckAll">uncheckAll</span>
<input type="checkbox" class="checkSingle"></input>
....
</form>
I hope that helps.
You are confused on this.
A keystore
is a container of certificates, private keys etc.
There are specifications of what should be the format of this keystore and the predominant is the #PKCS12
JKS is Java's keystore implementation. There is also BKS etc.
These are all keystore types.
So to answer your question:
difference between .keystore files and .jks files
There is none. JKS are keystore files.
There is difference though between keystore types. E.g. JKS
vs #PKCS12
The i
element is non-semantic, so for the screen readers, Googlebot, etc., it should be some kind of transparent (just like span
or div
elements). But it's not a good choice for the developer, because it joins the presentation layer with the structure layer - and that's a bad practice.
em
element (strong
as well) should be always used in a semantic context, not a presentation one. It has to be used whenever some word or sentence is important. Just for an example in the previous sentence, I should use em
to put more emphasis on the 'should be always used' part. Browsers provides some default CSS properties for these elements, but you can and you're supposed to override the default values if your design requires this to keep the correct semantic meaning of these elements.
<span class="italic">Italic Text</span>
is the most wrong way. First of all, it's inconvenient in use. Secondly, it suggest that the text should be italic. And the structure layer (HTML, XML, etc.) shouldn't ever do it. Presentation should be always kept separated from the structure.
<span class="footnote">Italic Text</span>
seems to be the best way for a footnote. It doesn't suggest any presentation and just describes the markup. You can't predict what will happen in the feature. If a footnote will grow up in the feature, you might be forced to change its class name (to keep some logic in your code).
So whenever you've some important text, use em
or strong
to emphasis it. But remember that these elements are inline elements and shouldn't be used to emphasis large blocks of text.
Use CSS if you care only about how something looks like and always try to avoid any extra markup.
A friend showed me how to do this as follows:
"./" works when the file requesting the image (e.g., "example.js") is on the same level within the folder tree structure as the folder "images".
var arr = [];
for(var i=1; i<=mynumber; i++) {
arr.push("" + i);
}
This seems to be faster in Chrome, according to JSPerf, but please note that it is all very browser dependant.
There's 4 things you can change about this snippet:
for
or while
.push
or direct access by index.toString
.In each and every browser total speed would be combination of how much better each option for each item in this list performs in that particular browser.
TL;DR: it is probably not good idea to try to micro-optimize this particular piece.
Temporarily show Menu Bar on ATOM:
Press ALT
Key to make the Menu bar appear but it is not permanent.
Always display the Menu Bar on ATOM:
To make the change permanent, press ALT + V
and then select Toggle Menu Bar
option from the "View" drop-down down.
[Tested on ATOM running on Ubuntu 16.04]
Just download and install the latest version of Virtual box, run it then run the emulator and viola, it will be up and running. This one worked for me.
Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.
Here is my JavaScript (using AngluarJS):
$scope.updateUserActivity = function (_objuserActivity) {
$http
({
method: 'post',
url: 'your url here',
headers: { 'Content-Type': 'application/json'},
data: JSON.stringify(_objuserActivity)
})
.then(function (response)
{
alert("success");
})
.catch(function (response)
{
alert("failure");
})
.finally(function ()
{
});
And here is my WebAPI Controller:
[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
return "hello";
}
I believe you are getting an empty array because PHP is expecting the posted data to be in a Querystring format (key=value&key1=value1).
Try changing your curl request to:
curl -i -X POST -d 'json={"screencast":{"subject":"tools"}}' \
http://localhost:3570/index.php/trainingServer/screencast.json
and see if that helps any.
The biggest difference between Task.Delay
and Thread.Sleep
is that Task.Delay
is intended to run asynchronously. It does not make sense to use Task.Delay
in synchronous code. It is a VERY bad idea to use Thread.Sleep
in asynchronous code.
Normally you will call Task.Delay()
with the await
keyword:
await Task.Delay(5000);
or, if you want to run some code before the delay:
var sw = new Stopwatch();
sw.Start();
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Guess what this will print? Running for 0.0070048 seconds.
If we move the await delay
above the Console.WriteLine
instead, it will print Running for 5.0020168 seconds.
Let's look at the difference with Thread.Sleep
:
class Program
{
static void Main(string[] args)
{
Task delay = asyncTask();
syncCode();
delay.Wait();
Console.ReadLine();
}
static async Task asyncTask()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("async: Starting");
Task delay = Task.Delay(5000);
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
await delay;
Console.WriteLine("async: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("async: Done");
}
static void syncCode()
{
var sw = new Stopwatch();
sw.Start();
Console.WriteLine("sync: Starting");
Thread.Sleep(5000);
Console.WriteLine("sync: Running for {0} seconds", sw.Elapsed.TotalSeconds);
Console.WriteLine("sync: Done");
}
}
Try to predict what this will print...
async: Starting
async: Running for 0.0070048 seconds
sync: Starting
async: Running for 5.0119008 seconds
async: Done
sync: Running for 5.0020168 seconds
sync: Done
Also, it is interesting to notice that Thread.Sleep
is far more accurate, ms accuracy is not really a problem, while Task.Delay
can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (use Stopwatch
Class if you need something more accurate). Thread.Sleep
still ties up your Thread, Task.Delay
release it to do other work while you wait.
almost never
Whenever you need to have a vector of char bigger that 2gb on a 32 bit system. In every other use case, using a signed type is much safer than using an unsigned type.
example:
std::vector<A> data;
[...]
// calculate the index that should be used;
size_t i = calc_index(param1, param2);
// doing calculations close to the underflow of an integer is already dangerous
// do some bounds checking
if( i - 1 < 0 ) {
// always false, because 0-1 on unsigned creates an underflow
return LEFT_BORDER;
} else if( i >= data.size() - 1 ) {
// if i already had an underflow, this becomes true
return RIGHT_BORDER;
}
// now you have a bug that is very hard to track, because you never
// get an exception or anything anymore, to detect that you actually
// return the false border case.
return calc_something(data[i-1], data[i], data[i+1]);
The signed equivalent of size_t
is ptrdiff_t
, not int
. But using int
is still much better in most cases than size_t. ptrdiff_t
is long
on 32 and 64 bit systems.
This means that you always have to convert to and from size_t whenever you interact with a std::containers, which not very beautiful. But on a going native conference the authors of c++ mentioned that designing std::vector with an unsigned size_t was a mistake.
If your compiler gives you warnings on implicit conversions from ptrdiff_t to size_t, you can make it explicit with constructor syntax:
calc_something(data[size_t(i-1)], data[size_t(i)], data[size_t(i+1)]);
if just want to iterate a collection, without bounds cheking, use range based for:
for(const auto& d : data) {
[...]
}
here some words from Bjarne Stroustrup (C++ author) at going native
For some people this signed/unsigned design error in the STL is reason enough, to not use the std::vector, but instead an own implementation.
I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...
Here's what I came up with:
python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"
That's the one-liner, here's it a little more readable:
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)
This worked for downloading a tarball. I was able to extract the package and download it after downloading.
EDIT:
To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint
package, but this was tested on my machine and works fine:
#!/usr/bin/env python
from clint.textui import progress
import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
total_length = int(r.headers.get('content-length'))
for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1):
if chunk:
f.write(chunk)
f.flush()
Chrome and Safari has a restriction on using ajax with local resources. That's why it's throwing an error like
Origin null is not allowed by Access-Control-Allow-Origin.
Solution: Use firefox or upload your data to a temporary server. If you still want to use Chrome, start it with the below option;
--allow-file-access-from-files
More info how to add the above parameter to your Chrome: Right click the Chrome icon on your task bar, right click the Google Chrome on the pop-up window and click properties and add the above parameter inside the Target textbox under Shortcut tab. It will like as below;
C:\Users\XXX_USER\AppData\Local\Google\Chrome\Application\chrome.exe --allow-file-access-from-files
Hope this will help!
I also put dsym, app bundle, and crash log together in the same directory before running symbolicate crash
Then I use this function defined in my .profile to simplify running symbolicatecrash:
function desym
{
/Developer/Platforms/iPhoneOS.platform/Developer/Library/PrivateFrameworks/DTDeviceKit.framework/Versions/A/Resources/symbolicatecrash -A -v $1 | more
}
The arguments added there may help you.
You can check to make sure spotlight "sees" your dysm files by running the command:
mdfind 'com_apple_xcode_dsym_uuids = *'
Look for the dsym you have in your directory.
NOTE: As of the latest Xcode, there is no longer a Developer directory. You can find this utility here:
/Applications/Xcode.app/Contents/SharedFrameworks/DTDeviceKitBase.framework/Vers??ions/A/Resources/symbolicatecrash
Will return false
only for undefined
and null
:
return value ?? false
Suppose you want to insert a particular line of text (not an empty line):
@echo off
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
set /a totallines+=1
@echo off
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /p L=
IF %%i==%insertat% ECHO(!TL!
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
My implementation
import $ from 'jquery';
$(document).ready(() => {
$('#whatDescribesYouSelectInput').on('change', (e) => {
if (e.target.value === 'Other') {
$('#whatDescribesYouOtherInput').attr('type', 'text');
$('#specifyLabel').show();
} else {
$('#whatDescribesYouOtherInput').attr('type', 'hidden');
$('#specifyLabel').hide();
}
});
});
you can use the identity
log[a]x
log[b]x = ---------
log[a]b
so this would be applicable for log2.
log[10]x
log[2]x = ----------
log[10]2
just plug this into the java Math log10 method....
ZIP Code is a highly localised field, and many countries have characters in their postcodes, e.g., UK, Canada. Therefore, in this example, you should use a string / varchar field to store it if at any point you would be shipping or getting users, customers, clients, etc. from other countries.
However, in the general case, you should use the recommended answer (printf("%05d", number);
).
As mentioned in Alain Beauvois's answer, and now (Q4 2013) better explained in
Copy the URL from GitHub and select in Eclipse from the menu the
File ? Import ? Git ? Projects from Git
If the Git repo isn't cloned yet:
In> order to checkout a remote project, you will have to clone its repository first.
Open the Eclipse Import wizard (e.g. File => Import
), select Git => Projects
from Git and click Next
.
Select “URI
” and click Next
.
Now you will have to enter the repository’s location and connection data. Entering the URI will automatically fill some fields. Complete any other required fields and hit Next
. If you use GitHub, you can copy the URI from the web page.
Select all branches you wish to clone and hit Next again.
Hit the Clone… button to open another wizard for cloning Git repositories.
Original answer (July 2011)
First, if your "Working Directory" is C:\Users
, that is odd, since it would mean you have cloned the GitHub repo directly within C:\Users (i.e. you have a .git
directory in C:\Users
)
Usually, you would clone a GitHub repo in "any directory of your choice\theGitHubRepoName
".
As described in the EGit user Manual page:
In any case (unless you create a "bare" Repository, but that's not discussed here), the new Repository is essentially a folder on the local hard disk which contains the "working directory" and the metadata folder.
The metadata folder is a dedicated child folder named ".git
" and often referred to as ".git-folder
". It contains the actual repository (i.e. the Commits, the References, the logs and such).The metadata folder is totally transparent to the Git client, while the working directory is used to expose the currently checked out Repository content as files for tools and editors.
Typically, if these files are to be used in Eclipse, they must be imported into the Eclipse workspace in one way or another. In order to do so, the easiest way would be to check in .project files from which the "Import Existing Projects" wizard can create the projects easily. Thus in most cases, the structure of a Repository containing Eclipse projects would look similar to something like this:
See also the Using EGit with Github section.
My working directory is now
c:\users\projectname\.git
You should have the content of that repo checked out in c:\users\projectname
(in other words, you should have more than just the .git
).
So then I try to import the project using the eclipse "import" option.
When I try to import selecting the option "Use the new projects wizard", the source code is not imported.
That is normal.
If I import selecting the option "Import as general project" the source code is imported but the created project created by Eclipse is not a java project.
Again normal.
When selecting the option "Use the new projects wizard" and creating a new java project using the wizard should'nt the code be automatically imported ?
No, that would only create an empty project.
If that project is created in c:\users\projectname
, you can then declare the eisting source directory in that project.
Since it is defined in the same working directory than the Git repo, that project should then appear as "versioned".
You could also use the "Import existing project" option, if your GitHub repo had versioned the .project
and .classpath
file, but that may not be the case here.
This answer describes a solution using MVVM.
This solution is great if you want to add a logging box to a window, that automatically scrolls to the bottom each time a new logging message is added.
Once these attached properties are added, they can be reused anywhere, so it makes for very modular and reusable software.
Add this XAML:
<TextBox IsReadOnly="True"
Foreground="Gainsboro"
FontSize="13"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="True"
attachedBehaviors:TextBoxApppendBehaviors.AppendText="{Binding LogBoxViewModel.AttachedPropertyAppend}"
attachedBehaviors:TextBoxClearBehavior.TextBoxClear="{Binding LogBoxViewModel.AttachedPropertyClear}"
TextWrapping="Wrap">
Add this attached property:
public static class TextBoxApppendBehaviors
{
#region AppendText Attached Property
public static readonly DependencyProperty AppendTextProperty =
DependencyProperty.RegisterAttached(
"AppendText",
typeof (string),
typeof (TextBoxApppendBehaviors),
new UIPropertyMetadata(null, OnAppendTextChanged));
public static string GetAppendText(TextBox textBox)
{
return (string)textBox.GetValue(AppendTextProperty);
}
public static void SetAppendText(
TextBox textBox,
string value)
{
textBox.SetValue(AppendTextProperty, value);
}
private static void OnAppendTextChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if (args.NewValue == null)
{
return;
}
string toAppend = args.NewValue.ToString();
if (toAppend == "")
{
return;
}
TextBox textBox = d as TextBox;
textBox?.AppendText(toAppend);
textBox?.ScrollToEnd();
}
#endregion
}
And this attached property (to clear the box):
public static class TextBoxClearBehavior
{
public static readonly DependencyProperty TextBoxClearProperty =
DependencyProperty.RegisterAttached(
"TextBoxClear",
typeof(bool),
typeof(TextBoxClearBehavior),
new UIPropertyMetadata(false, OnTextBoxClearPropertyChanged));
public static bool GetTextBoxClear(DependencyObject obj)
{
return (bool)obj.GetValue(TextBoxClearProperty);
}
public static void SetTextBoxClear(DependencyObject obj, bool value)
{
obj.SetValue(TextBoxClearProperty, value);
}
private static void OnTextBoxClearPropertyChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
if ((bool)args.NewValue == false)
{
return;
}
var textBox = (TextBox)d;
textBox?.Clear();
}
}
Then, if you're using a dependency injection framework such as MEF, you can place all of the logging-specific code into it's own ViewModel:
public interface ILogBoxViewModel
{
void CmdAppend(string toAppend);
void CmdClear();
bool AttachedPropertyClear { get; set; }
string AttachedPropertyAppend { get; set; }
}
[Export(typeof(ILogBoxViewModel))]
public class LogBoxViewModel : ILogBoxViewModel, INotifyPropertyChanged
{
private readonly ILog _log = LogManager.GetLogger<LogBoxViewModel>();
private bool _attachedPropertyClear;
private string _attachedPropertyAppend;
public void CmdAppend(string toAppend)
{
string toLog = $"{DateTime.Now:HH:mm:ss} - {toAppend}\n";
// Attached properties only fire on a change. This means it will still work if we publish the same message twice.
AttachedPropertyAppend = "";
AttachedPropertyAppend = toLog;
_log.Info($"Appended to log box: {toAppend}.");
}
public void CmdClear()
{
AttachedPropertyClear = false;
AttachedPropertyClear = true;
_log.Info($"Cleared the GUI log box.");
}
public bool AttachedPropertyClear
{
get { return _attachedPropertyClear; }
set { _attachedPropertyClear = value; OnPropertyChanged(); }
}
public string AttachedPropertyAppend
{
get { return _attachedPropertyAppend; }
set { _attachedPropertyAppend = value; OnPropertyChanged(); }
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Here's how it works:
I use the Intellij Community Edition. Go to the "Run/Debug Configurations" > Runner tab > Environment variables > click button "...". Add: SPRING_PROFILES_ACTIVE = local
Try to use Aspose.cells library (not free, but trial is enough to read), it is quite good
Install-package Aspose.cells
There is sample code:
using Aspose.Cells;
using System;
namespace ExcelReader
{
class Program
{
static void Main(string[] args)
{
// Replace path for your file
readXLS(@"C:\MyExcelFile.xls"); // or "*.xlsx"
Console.ReadKey();
}
public static void readXLS(string PathToMyExcel)
{
//Open your template file.
Workbook wb = new Workbook(PathToMyExcel);
//Get the first worksheet.
Worksheet worksheet = wb.Worksheets[0];
//Get cells
Cells cells = worksheet.Cells;
// Get row and column count
int rowCount = cells.MaxDataRow;
int columnCount = cells.MaxDataColumn;
// Current cell value
string strCell = "";
Console.WriteLine(String.Format("rowCount={0}, columnCount={1}", rowCount, columnCount));
for (int row = 0; row <= rowCount; row++) // Numeration starts from 0 to MaxDataRow
{
for (int column = 0; column <= columnCount; column++) // Numeration starts from 0 to MaxDataColumn
{
strCell = "";
strCell = Convert.ToString(cells[row, column].Value);
if (String.IsNullOrEmpty(strCell))
{
continue;
}
else
{
// Do your staff here
Console.WriteLine(strCell);
}
}
}
}
}
}
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
Try this code in Swift or Objective-C
Swift
self.tabBarController.selectedIndex = 1
Objective-C
[self.tabBarController setSelectedIndex:1];
On my system (Ubuntu 17.10) your example just works as desired, both when typed from the command line (into sh
) and when executed as a sh
script:
[bash]§ sh
$ STR="Hello\nWorld"
$ echo $STR
Hello
World
$ exit
[bash]§ echo "STR=\"Hello\nWorld\"
> echo \$STR" > test-str.sh
[bash]§ cat test-str.sh
STR="Hello\nWorld"
echo $STR
[bash]§ sh test-str.sh
Hello
World
I guess this answers your question: it just works. (I have not tried to figure out details such as at what moment exactly the substitution of the newline character for \n
happens in sh
).
However, i noticed that this same script would behave differently when executed with bash
and would print out Hello\nWorld
instead:
[bash]§ bash test-str.sh
Hello\nWorld
I've managed to get the desired output with bash
as follows:
[bash]§ STR="Hello
> World"
[bash]§ echo "$STR"
Note the double quotes around $STR
. This behaves identically if saved and run as a bash
script.
The following also gives the desired output:
[bash]§ echo "Hello
> World"
There isn't a direct way to do this like you've attempted.
The usual approach is to use "varargs" and check against the number of arguments. Something like:
function f(arg1, arg2, arg3)
if nargin < 3
arg3 = 'some default'
end
end
There are a few fancier things you can do with isempty
, etc., and you might want to look at Matlab central for some packages that bundle these sorts of things.
You might have a look at varargin
, nargchk
, etc. They're useful functions for this sort of thing. varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.
I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.
class Gouda(Cheese):
def __init__(self):
super(Gouda).__init__(num_holes=10)
class Parmesan(Cheese):
def __init__(self):
super(Parmesan).__init__(num_holes=15)
In order to search for a specific method in a whole module
for method in dir(module) :
if "keyword_of_methode" in method :
print(method, end="\n")
All created by user files saved in C:\xampp\htdocs
directory by default,
so no need to type the default path in a browser window, just type
http://localhost/yourfilename.php
or http://localhost/yourfoldername/yourfilename.php
this will show you the content of your new page.
You can open the preferences (multiple options):
Tools
-> Preferences
And depending on the Spyder version you can change the interpreter in the Python interpreter
section (Spyder 3.x):
or in the advanced Console
section (Spyder 2.x):
Since PHP 7.3 the hrtime function should be used for any timing.
$start = hrtime(true);
// execute...
$end = hrtime(true);
echo ($end - $start); // Nanoseconds
echo ($end - $start) / 1000000000; // Seconds
The mentioned microtime function relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.
I see this is a fairly old question, but this looks like one of those times when something's been written without knowledge of a language feature. The collections
library exists to fulfill these purposes.
from collections import Counter
letter_counter = Counter()
for letter in 'The quick brown fox jumps over the lazy dog':
letter_counter[letter] += 1
>>> letter_counter
Counter({' ': 8, 'o': 4, 'e': 3, 'h': 2, 'r': 2, 'u': 2, 'T': 1, 'a': 1, 'c': 1, 'b': 1, 'd': 1, 'g': 1, 'f': 1, 'i': 1, 'k': 1, 'j': 1, 'm': 1, 'l': 1, 'n': 1, 'q': 1, 'p': 1, 's': 1, 't': 1, 'w': 1, 'v': 1, 'y': 1, 'x': 1, 'z': 1})
In this example the spaces are being counted, obviously, but whether or not you want those filtered is up to you.
As for the dict.get(a_key, default_value)
, there have been several answers to this particular question -- this method returns the value of the key, or the default_value you supply. The first argument is the key you're looking for, the second argument is the default for when that key is not present.
A JAR is basically a ZIP file so treat it as such. Below contains an example on how to extract one file from a WAR file (also treat it as a ZIP file) and outputs the string contents. For binary you'll need to modify the extraction process, but there are plenty of examples out there for that.
public static void main(String args[]) {
String relativeFilePath = "style/someCSSFile.css";
String zipFilePath = "/someDirectory/someWarFile.war";
String contents = readZipFile(zipFilePath,relativeFilePath);
System.out.println(contents);
}
public static String readZipFile(String zipFilePath, String relativeFilePath) {
try {
ZipFile zipFile = new ZipFile(zipFilePath);
Enumeration<? extends ZipEntry> e = zipFile.entries();
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry) e.nextElement();
// if the entry is not directory and matches relative file then extract it
if (!entry.isDirectory() && entry.getName().equals(relativeFilePath)) {
BufferedInputStream bis = new BufferedInputStream(
zipFile.getInputStream(entry));
// Read the file
// With Apache Commons I/O
String fileContentsStr = IOUtils.toString(bis, "UTF-8");
// With Guava
//String fileContentsStr = new String(ByteStreams.toByteArray(bis),Charsets.UTF_8);
// close the input stream.
bis.close();
return fileContentsStr;
} else {
continue;
}
}
} catch (IOException e) {
logger.error("IOError :" + e);
e.printStackTrace();
}
return null;
}
In this example I'm using Apache Commons I/O and if you are using Maven here is the dependency:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
In general, it's not going to have enough of an impact to worry about, particularly since it's an intranet app and not a general-use Internet app. In particular, since it's intranet, SEO isn't a concern, since your intranet shouldn't be accessible to search engines. (and if it is, it isn't an intranet app).
And any framework worth it's salt either already has a default way to do this, or is fairly easy to change how it deals with multi-word URL components, so I wouldn't worry about it too much.
That said, here's how I see the various options:
Hyphen
Underscore
CamelCase
/
anyways. If you find that you have a URL component that is more than 2 "words" long, you should probably try to find a better name for that concept.yum uses RPM, so the following command will list the contents of the installed package:
$ rpm -ql package-name
I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run
from PyQt4.QtCore import SIGNAL
from a python interpreter but only without activating my virtualenv.
The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?
A more un-obtrusive way (assuming you use jQuery):
HTML:
<a id="my-link" href="page.html">page link</a>
Javascript:
$('#my-link').click(function(e)
{
e.preventDefault();
});
The advantage of this is the clean separation between logic and presentation. If one day you decide that this link would do something else, you don't have to mess with the markup, just the JS.
Multiline comment in Python:
For me, both ''' and """ worked.
Example:
a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)
Example:
a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)
I usually use BOOST_FOREACH:
#include <boost/foreach.hpp>
BOOST_FOREACH( vector_type::value_type& value, v ) {
// do something with 'value'
}
It works on STL containers, arrays, C-style strings, etc.
The solution is pretty easy... Searched for it for a while and it turns out that you just have to edit 2 config-files:
/usr/my.cnf
/etc/mysql/my.cnf
in both files you'll have to add:
[mysqld]
...
sql_mode=NO_ENGINE_SUBSTITUTION
At least, that's what's working for 5.6.24-2+deb.sury.org~precise+2
Use this code (taken from css-tricks) that will work on all browser
overflow-wrap: break-word;
word-wrap: break-word;
-ms-word-break: break-all;
/* This is the dangerous one in WebKit, as it breaks things wherever */
word-break: break-all;
/* Instead use this non-standard one: */
word-break: break-word;
/* Adds a hyphen where the word breaks, if supported (No Blink) */
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
you can try this
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.paragraphs:
fullText.append(para.text)
return '\n'.join(fullText)
add -e
key for passing environment variables to container.
example:
$ MYSQLHOSTIP=$(sudo docker inspect -format="{{ .NetworkSettings.IPAddress }}" $MYSQL_CONRAINER_ID)
$ sudo docker run -e DBIP=$MYSQLHOSTIP -i -t myimage /bin/bash
root@87f235949a13:/# echo $DBIP
172.17.0.2
Short of writing a full application, us Python guys can achieve files of any size with four lines, same snippet on Windows and Linux (the os.stat()
line is just a check):
>>> f = open('myfile.txt','w')
>>> f.seek(1024-1) # an example, pick any size
>>> f.write('\x00')
>>> f.close()
>>> os.stat('myfile.txt').st_size
1024L
>>>
UPDATED: As of angularjs 1.5, promise methods success and error have been deprecated. (see this answer)
from current docs:
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
you can use the function's other arguments like so:
error(function(data, status, headers, config) {
console.log(data);
console.log(status);
}
see $http docs:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
The first maximum you would hit is the length of a String which is 231-1 digits. It's much smaller than the maximum of a BigInteger but IMHO it loses much of its value if it can't be printed.
Make sure you have the correct database selected. You may have the master database selected if you are trying to run it in a new query window.
Extending your PATH
with:
export PATH=/usr/local/share/npm/bin:$PATH
isn't a terrible idea. Having said that, you shouldn't have to do it.
Run this:
npm config get prefix
The default on OS X is /usr/local
, which means that npm will symlink binaries into /usr/local/bin
, which should already be on your PATH
(especially if you're using Homebrew).
So:
npm config set prefix /usr/local
if it's something else, andsudo
with npm! According to the jslint docs, you should just be able to npm install
it.If you installed npm as sudo (sudo brew install
), try reinstalling it with plain ol' brew install
. Homebrew is supposed to help keep you sudo
-free.
For disabling swiping
mViewPager.beginFakeDrag();
For enable swiping
if (mViewPager.isFakeDragging())
mViewPager.endFakeDrag();
The match between .val('Bruce jones')
and value="Bruce Jones"
is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase()
on both.
I know this is an older question, but none of the above answers worked for me. In my case, the issue turned out to be that I had absolute include paths but without drive letters. Compilation was fine, but Visual Studio couldn't find an include file when I right-clicked and tried to open it. Adding the drive letters to my include paths corrected the problem.
I would never recommend hard-coding drive letters in any aspect of your project files; either use relative paths, macros, environment variables, or some mix of the tree for any permanent situation. However, in this case, I'm working in some temporary projects where absolute paths were necessary in the short term. Not being able to right-click to open the files was extremely frustrating, and hopefully this will help others.
ImageArtist is a pure gd wrapper authored by me, this enables you to do complex image manipulations insanely easy, for your question solution can be done using very few steps using this powerful library.
here is a sample code.
$img1 = new Image("./cover.jpg");
$img2 = new Image("./box.png");
$img2->merge($img1,9,9);
$img2->save("./merged.png",IMAGETYPE_PNG);
This is how my result looks like.
The overall dimensions of a range are in its Width
and Height
properties.
Dim r As Range
Set r = ActiveSheet.Range("A4:H12")
Debug.Print r.Width
Debug.Print r.Height
Yes you can use .is(':visible')
in jquery. But while the code is running under the safari browser
.is(':visible')
is won't work.
So please use the below code
if( $(".example").offset().top > 0 )
The above line will work both IE as well as safari also.
I have the same problem. but when i add direction: rtl;
in tabs and accordion combo but it crashes my structure.
The way to do it is add div with direction: rtl;
as parent element, and for child div set direction: ltr;
.
I use this first https://api.jquery.com/wrap/
$( ".your selector of child element" ).wrap( "<div class='scroll'></div>" );
then just simply work with css :)
In children div add to css
.your_class {
direction: ltr;
}
And to parent div added by jQuery with class .scroll
.scroll {
unicode-bidi:bidi-override;
direction: rtl;
overflow: scroll;
overflow-x: hidden!important;
}
Works prefect for me
If you'd rather use xpath and that span is the only span below your div, use my example below. I'd recommend using CSS (see sircapsalot's post).
String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']//span)).getText();
css example:
String kk = wd.findElement(By.cssSelector("div[id='customSelect_3'] span[class='selectLabel clear']")).getText();
ValidateForm
returns boolean
,not a string
.
When you do this if(ValidateForm() == 'false')
, is the same of if(false == 'false')
, which is not true.
function post(url, formId) {
if(!ValidateForm()) {
// False
} else {
// True
}
}
It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null
.
Given your statement:
img1.ImageUrl = ConfigurationManager
.AppSettings
.Get("Url")
.Replace("###", randomString)
+ Server.UrlEncode(
((System.Web.UI.MobileControls.Form)Page
.FindControl("mobileForm"))
.Title);
I'm guessing either the call to AppSettings.Get("Url")
is returning null because the value isn't found or the call to Page.FindControl("mobileForm")
is returning null because the control isn't found.
You could easily break this out into multiple statements to solve the problem:
var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
as System.Web.UI.MobileControls.Form;
if(configUrl != null && mobileFormControl != null)
{
img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}
Two things occur to me.
First, are you sure you mean ManyToOne for address? That means multiple people will have the same address. If it's edited for one of them, it'll be edited for all of them. Is that your intent? 99% of the time addresses are "private" (in the sense that they belong to only one person).
Secondly, do you have any other eager relationships on the Person entity? If I recall correctly, Hibernate can only handle one eager relationship on an entity but that is possibly outdated information.
I say that because your understanding of how this should work is essentially correct from where I'm sitting.
This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.
FileStream fileStream = File.Open(<path>, FileMode.Open);
/*
* Set the length of filestream to 0 and flush it to the physical file.
*
* Flushing the stream is important because this ensures that
* the changes to the stream trickle down to the physical file.
*
*/
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.
Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.
Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.
class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
}
public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };
return query.ToList();
}
}
Came across this issue after I merged a pull request on Bitbucket.
Had to do
git fetch
and that was it.
I solved this by doing the following:
WebServer(ISS)->WebServer->Application Development
add .NET Extensibility 3.5
add .NET Extensibility 4.5
add ASP.NET 4.5
add ISAPI Extensions
add ISAPI Filters
Have a look at this jQuery plugin from OvalPixels.
It may do the trick.
I have a very simple solution for this problem. You don't need to use the console.
TLDR: Create repo, move files to existing projects folder, SourceTree will ask you where his files are, locate the files. Done, your repo is in another folder.
Long answer:
Tips: Clone in SourceTree option is not available right after you create new repository so you first have to click on Create Readme File for that option to become available.
I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below
function isInCharacterRange(int $r): bool {
return $r == 0x09 ||
$r == 0x0A ||
$r == 0x0D ||
$r >= 0x20 && $r <= 0xDF77 ||
$r >= 0xE000 && $r <= 0xFFFD ||
$r >= 0x10000 && $r <= 0x10FFFF;
}
function xml(string $s, bool $escapeNewline = true): string {
$w = '';
$Last = 0;
$l = strlen($s);
$i = 0;
while ($i < $l) {
$r = mb_substr(substr($s, $i), 0, 1);
$Width = strlen($r);
$i += $Width;
switch ($r) {
case '"':
$esc = '"';
break;
case "'":
$esc = ''';
break;
case '&':
$esc = '&';
break;
case '<':
$esc = '<';
break;
case '>':
$esc = '>';
break;
case "\t":
$esc = '	';
break;
case "\n":
if (!$escapeNewline) {
continue 2;
}
$esc = '
';
break;
case "\r":
$esc = '
';
break;
default:
if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
$esc = "\u{FFFD}";
break;
}
continue 2;
}
$w .= substr($s, $Last, $i - $Last - $Width) . $esc;
$Last = $i;
}
$w .= substr($s, $Last);
return $w;
}
Note you'll need at least PHP7.2 because of the mb_ord
usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!
For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887
You can use the ::marker
CSS pseudo-element to select the marker box of a list item (i.e. bullets or numbers).
ul li::marker {
color: red;
}
Note: At the time of posting this answer, this is considered experimental technology and has only been implemented in Firefox and Safari (so far).
I apologize, but I'm adding my 2 cents to the thread just in case anyone has the same problem.
return new HttpStatusCodeResult(401)
- and ASP.NET is super nice to detect this, and it redirects the user to the login page! Magic, right? It even has the proper ReturnUrl
parameter etc.But you see where I'm getting here? I return 401. And ASP.NET redirects the user. Which is essentially returns 302. One status code is replaced with another.
And some IIS servers (just some!) throw this exception. Some don't. - I don't have it on my test serevr, only on my production server (ain't it always the case right o_O)
I know my answer is essentially repeating what's already said here, but sometimes it's just hard to figure out where this overwriting happens exactly.
Eventhough it is an old question, this may help someone.
We can choose multiple files while browsing for a file using "multiple"
<input type="file" name="datafile" size="40" multiple>
The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.
You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.
For proxy issue, there are some material here:
Why can't I get Python's urlopen() method to work on Windows?
Hope it helps!
Using the request library can help minimize the cruft:
var request = require('request')
request({ uri: 'http://api.com/1' }, function(err, response, body){
// use body
request({ uri: 'http://api.com/2' }, function(err, response, body){
// use body
request({ uri: 'http://api.com/3' }, function(err, response, body){
// use body
})
})
})
But for maximum awesomeness you should try some control-flow library like Step - it will also allow you to parallelize requests, assuming that it's acceptable:
var request = require('request')
var Step = require('step')
// request returns body as 3rd argument
// we have to move it so it works with Step :(
request.getBody = function(o, cb){
request(o, function(err, resp, body){
cb(err, body)
})
}
Step(
function getData(){
request.getBody({ uri: 'http://api.com/?method=1' }, this.parallel())
request.getBody({ uri: 'http://api.com/?method=2' }, this.parallel())
request.getBody({ uri: 'http://api.com/?method=3' }, this.parallel())
},
function doStuff(err, r1, r2, r3){
console.log(r1,r2,r3)
}
)
for me, the problem was from require('jquery-validation')
i added in the begging of that js file which Validate method used which is necessary as an npm module
unfortunately, when web pack compiles the js files, they aren't in order, so that the validate method is before defining it! and the error comes
so better to use another js file for compiling this library or use local validate method file or even using CDN but in all cases make sure you attached jquery before
It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.
But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.
So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing
AFAIK, HTML5 does not provide an API which supports full screen.
This question has some view points on making html5 video full screen for example using webkitEnterFullscreen
in webkit.
Is there a way to make html5 video fullscreen
Following the documentation of fopen
:
``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.
So if you pFile2=fopen("myfile2.txt", "a");
the stream is positioned at the end to append automatically. just do:
FILE *pFile;
FILE *pFile2;
char buffer[256];
pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
perror("Error opening file.");
}
else {
while(fgets(buffer, sizeof(buffer), pFile)) {
fprintf(pFile2, "%s", buffer);
}
}
fclose(pFile);
fclose(pFile2);
Since Angular 1.5 it's possible to use Components. Components are the-way-to-go and solves this problem easy.
<myComponent data-ng-model="$ctrl.result"></myComponent>
app.component("myComponent", {
templateUrl: "yourTemplate.html",
controller: YourController,
bindings: {
ngModel: "="
}
});
Inside YourController all you need to do is:
this.ngModel = "x"; //$scope.$apply("$ctrl.ngModel"); if needed
You might have a lower project language level than your JDK.
Check if: "Projeckt structure/project/Project-> language level" is lower than your JDK. I had the same problem with JDK 9 and the language level was per default set to 6.
I set the Project Language Level to 9 and everything worked fine after that.
You might have the same issue.