If you want to rotate a vector you should construct what is known as a rotation matrix.
Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are
x' = x cos ? - y sin ?
y' = x sin ? + y cos ?
To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider
Unit vector along X axis = <1, 0>
x' = 1 cos 90 - 0 sin 90 = 0
y' = 1 sin 90 + 0 cos 90 = 1
New coordinates of the vector, <x', y'> = <0, 1> ? Y-axis
When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is
|cos ? -sin ?| |x| = |x cos ? - y sin ?| = |x'|
|sin ? cos ?| |y| |x sin ? + y cos ?| |y'|
That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be
|cos ? -sin ? 0| |x| |x cos ? - y sin ?| |x'|
|sin ? cos ? 0| |y| = |x sin ? + y cos ?| = |y'|
| 0 0 1| |z| | z | |z'|
around the Y-axis would be
| cos ? 0 sin ?| |x| | x cos ? + z sin ?| |x'|
| 0 1 0| |y| = | y | = |y'|
|-sin ? 0 cos ?| |z| |-x sin ? + z cos ?| |z'|
around the X-axis would be
|1 0 0| |x| | x | |x'|
|0 cos ? -sin ?| |y| = |y cos ? - z sin ?| = |y'|
|0 sin ? cos ?| |z| |y sin ? + z cos ?| |z'|
Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.
Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.
I hope this clarifies basic rotation.
The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.
I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).
A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.
Set a negative z-index
for the child, and remove the one set on the parent.
.parent {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 150px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.parent2 {_x000D_
position: relative;_x000D_
width: 350px;_x000D_
height: 40px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
}_x000D_
.child {_x000D_
position: relative;_x000D_
background-color: blue;_x000D_
height: 200px;_x000D_
}_x000D_
.wrapper {_x000D_
position: relative;_x000D_
background: green;_x000D_
height: 350px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">parent 1 parent 1_x000D_
<div class="child">child child child</div>_x000D_
</div>_x000D_
<div class="parent2">parent 2 parent 2_x000D_
</div>_x000D_
</div>
_x000D_
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:background="@drawable/home_button"
android:drawableLeft="@android:drawable/ic_menu_edit"
android:drawablePadding="6dp"
android:gravity="left|center"
android:height="60dp"
android:padding="6dp"
android:text="AndroidDhina"
android:textColor="#000"
android:textStyle="bold" />
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
Here is a simple example:
EXEC sp_executesql @sql, N'@p1 INT, @p2 INT, @p3 INT', @p1, @p2, @p3;
Your call will be something like this
EXEC sp_executesql @statement, N'@LabID int, @BeginDate date, @EndDate date, @RequestTypeID varchar', @LabID, @BeginDate, @EndDate, @RequestTypeID
Here is a bash script for newer Maven copy and paste it...
# @author Yucca Nel
#!/bin/sh
#This installs maven2 & a default JDK
sudo apt-get install maven2;
#Makes the /usr/lib/mvn in case...
sudo mkdir -p /usr/lib/mvn;
#Clean out /tmp...
sudo rm -rf /tmp/*;
cd /tmp;
#Update this line to reflect newer versions of maven
wget http://mirrors.powertech.no/www.apache.org/dist//maven/binaries/apache-maven-3.0.3-bin.tar.gz;
tar -xvf ./*gz;
#Move it to where it to logical location
sudo mv /tmp/apache-maven-3.* /usr/lib/mvn/;
#Link the new Maven to the bin... (update for higher/newer version)...
sudo ln -s /usr/lib/mvn/apache-maven-3.0.3/bin/mvn /usr/bin/mvn;
#test
mvn -version;
exit 0;
Create the database, with Script Database as... CREATE To
Within SSMS on the source server, use the export wizard with the destination server database as the destination.
What does the
yield
keyword do in Python?
yield
, when called, returns a Generator.yield from
.return
in a generator.)yield
is only legal inside of a function definition, and the inclusion of yield
in a function definition makes it return a generator.
The idea for generators comes from other languages (see footnote 1) with varying implementations. In Python's Generators, the execution of the code is frozen at the point of the yield. When the generator is called (methods are discussed below) execution resumes and then freezes at the next yield.
yield
provides an
easy way of implementing the iterator protocol, defined by the following two methods:
__iter__
and next
(Python 2) or __next__
(Python 3). Both of those methods
make an object an iterator that you could type-check with the Iterator
Abstract Base
Class from the collections
module.
>>> def func():
... yield 'I am'
... yield 'a generator!'
...
>>> type(func) # A function with yield is still a function
<type 'function'>
>>> gen = func()
>>> type(gen) # but it returns a generator
<type 'generator'>
>>> hasattr(gen, '__iter__') # that's an iterable
True
>>> hasattr(gen, 'next') # and with .next (.__next__ in Python 3)
True # implements the iterator protocol.
The generator type is a sub-type of iterator:
>>> import collections, types
>>> issubclass(types.GeneratorType, collections.Iterator)
True
And if necessary, we can type-check like this:
>>> isinstance(gen, types.GeneratorType)
True
>>> isinstance(gen, collections.Iterator)
True
A feature of an Iterator
is that once exhausted, you can't reuse or reset it:
>>> list(gen)
['I am', 'a generator!']
>>> list(gen)
[]
You'll have to make another if you want to use its functionality again (see footnote 2):
>>> list(func())
['I am', 'a generator!']
One can yield data programmatically, for example:
def func(an_iterable):
for item in an_iterable:
yield item
The above simple generator is also equivalent to the below - as of Python 3.3 (and not available in Python 2), you can use yield from
:
def func(an_iterable):
yield from an_iterable
However, yield from
also allows for delegation to subgenerators,
which will be explained in the following section on cooperative delegation with sub-coroutines.
yield
forms an expression that allows data to be sent into the generator (see footnote 3)
Here is an example, take note of the received
variable, which will point to the data that is sent to the generator:
def bank_account(deposited, interest_rate):
while True:
calculated_interest = interest_rate * deposited
received = yield calculated_interest
if received:
deposited += received
>>> my_account = bank_account(1000, .05)
First, we must queue up the generator with the builtin function, next
. It will
call the appropriate next
or __next__
method, depending on the version of
Python you are using:
>>> first_year_interest = next(my_account)
>>> first_year_interest
50.0
And now we can send data into the generator. (Sending None
is
the same as calling next
.) :
>>> next_year_interest = my_account.send(first_year_interest + 1000)
>>> next_year_interest
102.5
yield from
Now, recall that yield from
is available in Python 3. This allows us to delegate coroutines to a subcoroutine:
def money_manager(expected_rate):
# must receive deposited value from .send():
under_management = yield # yield None to start.
while True:
try:
additional_investment = yield expected_rate * under_management
if additional_investment:
under_management += additional_investment
except GeneratorExit:
'''TODO: write function to send unclaimed funds to state'''
raise
finally:
'''TODO: write function to mail tax info to client'''
def investment_account(deposited, manager):
'''very simple model of an investment account that delegates to a manager'''
# must queue up manager:
next(manager) # <- same as manager.send(None)
# This is where we send the initial deposit to the manager:
manager.send(deposited)
try:
yield from manager
except GeneratorExit:
return manager.close() # delegate?
And now we can delegate functionality to a sub-generator and it can be used by a generator just as above:
my_manager = money_manager(.06)
my_account = investment_account(1000, my_manager)
first_year_return = next(my_account) # -> 60.0
Now simulate adding another 1,000 to the account plus the return on the account (60.0):
next_year_return = my_account.send(first_year_return + 1000)
next_year_return # 123.6
You can read more about the precise semantics of yield from
in PEP 380.
The close
method raises GeneratorExit
at the point the function
execution was frozen. This will also be called by __del__
so you
can put any cleanup code where you handle the GeneratorExit
:
my_account.close()
You can also throw an exception which can be handled in the generator or propagated back to the user:
import sys
try:
raise ValueError
except:
my_manager.throw(*sys.exc_info())
Raises:
Traceback (most recent call last):
File "<stdin>", line 4, in <module>
File "<stdin>", line 6, in money_manager
File "<stdin>", line 2, in <module>
ValueError
I believe I have covered all aspects of the following question:
What does the
yield
keyword do in Python?
It turns out that yield
does a lot. I'm sure I could add even more
thorough examples to this. If you want more or have some constructive criticism, let me know by commenting
below.
__iter__
method returning an iterator. An iterator provides a .next
(Python 2 or .__next__
(Python 3) method, which is implicitly called by for
loops until it raises StopIteration
, and once it does, it will continue to do so.yield
part..next
method, when instead he should use the builtin function, next
. It would be an appropriate layer of indirection, because his code does not work in Python 3.yield
does at all.yield
provides along with the new functionality yield from
in Python 3. The top/accepted answer is a very incomplete answer.yield
in a generator expression or comprehension.The grammar currently allows any expression in a list comprehension.
expr_stmt: testlist_star_expr (annassign | augassign (yield_expr|testlist) |
('=' (yield_expr|testlist_star_expr))*)
...
yield_expr: 'yield' [yield_arg]
yield_arg: 'from' test | testlist
Since yield is an expression, it has been touted by some as interesting to use it in comprehensions or generator expression - in spite of citing no particularly good use-case.
The CPython core developers are discussing deprecating its allowance. Here's a relevant post from the mailing list:
On 30 January 2017 at 19:05, Brett Cannon wrote:
On Sun, 29 Jan 2017 at 16:39 Craig Rodrigues wrote:
I'm OK with either approach. Leaving things the way they are in Python 3 is no good, IMHO.
My vote is it be a SyntaxError since you're not getting what you expect from the syntax.
I'd agree that's a sensible place for us to end up, as any code relying on the current behaviour is really too clever to be maintainable.
In terms of getting there, we'll likely want:
- SyntaxWarning or DeprecationWarning in 3.7
- Py3k warning in 2.7.x
- SyntaxError in 3.8
Cheers, Nick.
-- Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
Further, there is an outstanding issue (10544) which seems to be pointing in the direction of this never being a good idea (PyPy, a Python implementation written in Python, is already raising syntax warnings.)
Bottom line, until the developers of CPython tell us otherwise: Don't put yield
in a generator expression or comprehension.
return
statement in a generatorIn Python 2:
In a generator function, the
return
statement is not allowed to include anexpression_list
. In that context, a barereturn
indicates that the generator is done and will causeStopIteration
to be raised.
An expression_list
is basically any number of expressions separated by commas - essentially, in Python 2, you can stop the generator with return
, but you can't return a value.
In Python 3:
In a generator function, the
return
statement indicates that the generator is done and will causeStopIteration
to be raised. The returned value (if any) is used as an argument to constructStopIteration
and becomes theStopIteration.value
attribute.
The languages CLU, Sather, and Icon were referenced in the proposal to introduce the concept of generators to Python. The general idea is that a function can maintain internal state and yield intermediate data points on demand by the user. This promised to be superior in performance to other approaches, including Python threading, which isn't even available on some systems.
This means, for example, that range
objects aren't Iterator
s, even though they are iterable, because they can be reused. Like lists, their __iter__
methods return iterator objects.
yield
was originally introduced as a statement, meaning that it
could only appear at the beginning of a line in a code block.
Now yield
creates a yield expression.
https://docs.python.org/2/reference/simple_stmts.html#grammar-token-yield_stmt
This change was proposed to allow a user to send data into the generator just as
one might receive it. To send data, one must be able to assign it to something, and
for that, a statement just won't work.
The difference lies in the fact that ./gradlew
indicates you are using a gradle wrapper. The wrapper is generally part of a project and it facilitates installation of gradle. If you were using gradle without the wrapper you would have to manually install it - for example, on a mac brew install gradle
and then invoke gradle using the gradle
command. In both cases you are using gradle, but the former is more convenient and ensures version consistency across different machines.
Each Wrapper is tied to a specific version of Gradle, so when you first run one of the commands above for a given Gradle version, it will download the corresponding Gradle distribution and use it to execute the build.
Not only does this mean that you don’t have to manually install Gradle yourself, but you are also sure to use the version of Gradle that the build is designed for. This makes your historical builds more reliable
Read more here - https://docs.gradle.org/current/userguide/gradle_wrapper.html
Also, Udacity has a neat, high level video explaining the concept of the gradle wrapper - https://www.youtube.com/watch?v=1aA949H-shk
Try running all targets individually to check that all are running correct
run ant target name to run a target individually
e.g. ant build-project
Also the default target you specified is
project basedir="." default="build" name="iControlSilk4J"
This will only execute build-subprojects,build-project and init
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
Edit your phpmyadmin config.inc.php file and if you have Password, insert that in front of Password in following code:
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = '**your-root-username**';
$cfg['Servers'][$i]['password'] = '**root-password**';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
Perhaps the easiest is to use position: absolute
to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.
css:
<style>
body {
margin: 0 0 20px;
}
.footer {
position: absolute;
bottom: 0;
height: 20px;
background: #f0f0f0;
width: 100%;
}
</style>
Here is the html main content.
<div class="footer"> Here is the footer. </div>
Looks like some changes to SASS have made possible what you've initially tried doing:
@import "../subdir/common";
We even got this to work for some totally unrelated folder located in c:\projects\sass
:
@import "../../../../../../../../../../projects/sass/common";
Just add enough ../
to be sure you'll end up at the drive root and you're good to go.
Of course, this solution is far from pretty, but I couldn't get an import from a totally different folder to work, neither using I c:\projects\sass
nor setting the environment variable SASS_PATH
(from: :load_paths reference) to that same value.
Here is a pitfall to avoid. In case you need to access your variable $name within a function, you need to say "global $name;" at the beginning of that function. You need to repeat this for each function in the same file.
include('front.inc');
global $name;
function foo() {
echo $name;
}
function bar() {
echo $name;
}
foo();
bar();
will only show errors. The correct way to do that would be:
include('front.inc');
function foo() {
global $name;
echo $name;
}
function bar() {
global $name;
echo $name;
}
foo();
bar();
you cant change the background of checkbox but some how you can do a trick try this :)
.divBox {_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
background: #ddd;_x000D_
margin: 20px 90px;_x000D_
position: relative;_x000D_
-webkit-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
-moz-box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
box-shadow: 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.divBox label {_x000D_
display: block;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
-webkit-transition: all .5s ease;_x000D_
-moz-transition: all .5s ease;_x000D_
-o-transition: all .5s ease;_x000D_
-ms-transition: all .5s ease;_x000D_
transition: all .5s ease;_x000D_
cursor: pointer;_x000D_
position: absolute;_x000D_
top: 1px;_x000D_
z-index: 1;_x000D_
/* _x000D_
use this background transparent to check the value of checkbox _x000D_
background: transparent;_x000D_
*/_x000D_
background: Black;_x000D_
-webkit-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
-moz-box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
box-shadow:inset 0px 1px 3px rgba(0,0,0,0.5);_x000D_
}_x000D_
_x000D_
.divBox input[type=checkbox]:checked + label {_x000D_
background: green;_x000D_
}
_x000D_
<div class="divBox">_x000D_
<input type="checkbox" value="1" id="checkboxFourInput"name="" />_x000D_
<label for="checkboxFourInput"></label>_x000D_
</div>
_x000D_
For installing
gem install gemname -v versionnumber
For uninstall
gem uninstall gemname -v versionnumber
Easiest and Best Solution
Save your .py file in a folder. This case my folder name is test. In the command prompt run the following
c:\test> set FLASK_APP=application.py
c:\test> set FLASK_RUN_PORT=8000
c:\test> flask run
----------------- Following will be returned ----------------
* Serving Flask app "application.py"
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:8000/ (Press CTRL+C to quit)
127.0.0.1 - - [23/Aug/2019 09:40:04] "[37mGET / HTTP/1.1[0m" 200 -
127.0.0.1 - - [23/Aug/2019 09:40:04] "[33mGET /favicon.ico HTTP/1.1[0m" 404 -
Now on your browser type: http://127.0.0.1:8000. Thanks
Jobs.aspx
This is the phyiscal file -> CodeFile="Jobs.aspx.cs"
This is the class which handles the events of the page -> Inherits="Members_Jobs"
Jobs.aspx.cs
This is the partial class which manages the page events -> public partial class Members_Jobs : System.Web.UI.Page
The other part of the partial class should be -> public partial class Members_Jobs
this is usually the designer file.
you dont need to have partial classes and could declare your controls all in 1 class and not have a designer file.
EDIT 27/09/2013 11:37
if you are still having issues with this I would do as Bharadwaj suggested and delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option, something like "Convert to Web Application", which will regenerate your designer file
The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:
When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:
Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.
In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company
with the value 'ABC123'
and the field address
with the value '123 Street'
, in the exact order:
db.inventory.find( {
producer: {
company: 'ABC123',
address: '123 Street'
}
});
Declare this Mixin:
@mixin vertical-align($position: relative) {
position: $position;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Then include it in your element:
.element{
@include vertical-align();
}
This works:
async function IsLoggedIn(): Promise<boolean> {
try {
await new Promise((resolve, reject) =>
app.auth().onAuthStateChanged(
user => {
if (user) {
// User is signed in.
resolve(user)
} else {
// No user is signed in.
reject('no user logged in')
}
},
// Prevent console error
error => reject(error)
)
)
return true
} catch (error) {
return false
}
}
Combining the Dictionary approach from Tim with the variant array from Jean_Francois below.
The array you want is in objDict.keys
Sub A_Unique_B()
Dim X
Dim objDict As Object
Dim lngRow As Long
Set objDict = CreateObject("Scripting.Dictionary")
X = Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp)))
For lngRow = 1 To UBound(X, 1)
objDict(X(lngRow)) = 1
Next
Range("B1:B" & objDict.Count) = Application.Transpose(objDict.keys)
End Sub
Assuming the "commit" element represents a standard Form submit button then you can attach an event handler to the WebBrowsers Navigated event.
It is from an external js file and it is the only file linked to the page.
OK.
When I double click this file I get the following error
Sounds like you're double-clicking/running a .js file, which will attempt to run the script outside the browser, like a command line script. And that would explain this error:
Windows Script Host Error: 'window' is not defined Code: 800A1391
... not an error you'll see in a browser. And of course, the browser is what supplies the window
object.
ADDENDUM: As a course of action, I'd suggest opening the relevant HTML file and taking a peek at the console. If you don't see anything there, it's likely your window.onload
definition is simply being hit after the browser fires the window.onload
event.
$(document).ready(function() {
$('#div2').hide(0);
$('#preview').on('click', function() {
$('#div1').hide(300, function() { // first hide div1
// then show div2
$('#div2').show(300);
});
});
});
You missed #
before div2
The way your code works is pretty close to the "canonical" way to write it. I'd throw an AssertionError
within the catch, though. It signals that that line should never be reached.
catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
Try this:
var options = {
url: 'http://url',
timeout: 120000
}
request(options, function(err, resp, body) {});
Refer to request's documentation for other options.
$(this).find(".bgHeaderH2").html();
or
$(this).find(".bgHeaderH2").text();
Steps to launch new activity as follows:
1.Get intent for package
2.If intent is null redirect user to playstore
3.If intent is not null open activity
public void launchNewActivity(Context context, String packageName) {
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.CUPCAKE) {
intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
}
if (intent == null) {
try {
intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setData(Uri.parse("market://details?id=" + packageName));
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + packageName)));
}
} else {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
409 Conflict
could be an acceptable solution.
According to: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.
The doc continues with an example:
Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.
In my case, I would like to PUT a string, that must be unique, to a database via an API. Before adding it to the database, I am checking that it is not already in the database.
If it is, I will return "Error: The string is already in the database", 409
.
I believe this is what the OP wanted: an error code suitable for when the data does not pass the server's criteria.
I know this was answered a long time ago, but I've recently spent hours trying to solve a similar problem. The setup is local PC running Debian 8 using Eclipse CDT Neon.2, remote ARM7 board (Olimex) running Debian 7. Tool chain is Linaro 4.9 using gdbserver on the remote board and the Linaro GDB on the local PC. My issue was that the debug session would start and the program would execute, but breakpoints did not work and when manually paused "no source could be found" would result. My compile line options (Linaro gcc) included -ggdb -O0 as many have suggested but still the same problem. Ultimately I tried gdb proper on the remote board and it complained of no symbols. The curious thing was that 'file' reported debug not stripped on the target executable.
I ultimately solved the problem by adding -g to the linker options. I won't claim to fully understand why this helped, but I wanted to pass this on for others just in case it helps. In this case Linux did indeed need -g on the linker options.
You can get the duration from the 'contentDetails' field in the json response.
For only date use
date("Y-m-d");
and for only time use
date("H:i:s");
I would recommend using the commons-dbcp library. There are numerous examples listed on how to use it, here is the link to the move simple one. The usage is very simple:
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.driver.OracleDriver")
ds.setUsername("scott");
ds.setPassword("tiger");
ds.setUrl(connectURI);
...
Connection conn = ds.getConnection();
You only need to create the data source once, so make sure you read the documentation if you do not know how to do that. If you are not aware of how to properly write JDBC statements so you do not leak resources, you also might want to read this Wikipedia page.
I have struggled with this problem since I don’t know why my droplevel() function does not work. Work through several and learn that ‘a’ in your table is columns name and ‘b’, ‘c’ are index. Do like this will help
df.columns.name = None
df.reset_index() #make index become label
Not sure why the simplest solution is not mentioned. You can simply do File>New Window
and open the other project in the new window.
You can use single line comments:
-- this is a comment
# this is also a comment
Or a multiline comment:
/*
multiline
comment
*/
compactitem
does the job.
\usepackage{paralist}
...
\begin{compactitem}[$\bullet$]
\item Element 1
\item Element 2
\end{compactitem}
\vspace{\baselineskip} % new line after list
In case you're having this problem in flex/adobe air and find yourself here first, i've found a solution, and have posted it on a related question: ADD COLUMN to sqlite db IF NOT EXISTS - flex/air sqlite?
My comment here: https://stackoverflow.com/a/24928437/2678219
So the bad news is that XCode is needed for its iOS Simulator as well as its Application Loader facility for actually uploading the programs to iOS devices for "real" testing. You'll need XCode for signing your apps before submitting to the App Store. Unfortunately, XCode is only available for OS X.
However, the good news is that you may be able to purchase OS X and run it in a virtual machine such as VMWare Workstation. I don't know how straightforward this is, as it is rather difficult to get OS X to run on non-Apple hardware, but a quick Google search shows that it is possible. This method would (likely) be cheaper than purchasing a new Mac, although the Mac Mini retails in the US for only $599. Some posts I've seen indicate that this may or may not be legal, others say you need OS X Server for virtualization. I'll leave the research up to you.
There are also services such as MacInCloud that allow you to rent a Mac server that you can access from Windows via remote desktop, or through your browser. Unfortunately, I don't think you'd be able to use Application Loader, as you have to physically connect the device to your computer, but it would work for development and simulation, at least.
Good luck!
Server-side functions are on the server-side, client-side functions reside on the client.
What you can do is you have to set hidden form variable and submit the form, then on page use Page_Load
handler you can access value of variable and call the server method.
find the cxfreeze
script and run it. It will be in the same path as your other python helper scripts, such as pip
.
cxfreeze Main.py --target-dir dist
read more at: http://cx-freeze.readthedocs.org/en/latest/script.html#script
As long as Event_ID is Integer, do this:
INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
FROM Table
WHERE Event_ID = "120"
Thanks for the responses. I think I've solved the problem just now.
Since LD_PRELOAD is for setting some library proloaded, I check the library that ld preloads with LD_PRELOAD, one of which is "liblunar-calendar-preload.so", that is not existing in the path "/usr/lib/liblunar-calendar-preload.so", but I find a similar library "liblunar-calendar-preload-2.0.so", which is a difference version of the former one.
Then I guess maybe liblunar-calendar-preload.so was updated to a 2.0 version when the system updated, leaving LD_PRELOAD remain to be "/usr/lib/liblunar-calendar-preload.so". Thus the preload library name was not updated to the newest version.
To avoid changing environment variable, I create a symbolic link under the path "/usr/lib"
sudo ln -s liblunar-calendar-preload-2.0.so liblunar-calendar-preload.so
Then I restart bash, the error is gone.
Diamond inheritance runnable usage example
This example shows how to use a virtual base class in the typical scenario: to solve diamond inheritance problems.
Consider the following working example:
main.cpp
#include <cassert>
class A {
public:
A(){}
A(int i) : i(i) {}
int i;
virtual int f() = 0;
virtual int g() = 0;
virtual int h() = 0;
};
class B : public virtual A {
public:
B(int j) : j(j) {}
int j;
virtual int f() { return this->i + this->j; }
};
class C : public virtual A {
public:
C(int k) : k(k) {}
int k;
virtual int g() { return this->i + this->k; }
};
class D : public B, public C {
public:
D(int i, int j, int k) : A(i), B(j), C(k) {}
virtual int h() { return this->i + this->j + this->k; }
};
int main() {
D d = D(1, 2, 4);
assert(d.f() == 3);
assert(d.g() == 5);
assert(d.h() == 7);
}
Compile and run:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
If we remove the virtual
into:
class B : public virtual A
we would get a wall of errors about GCC being unable to resolve D members and methods that were inherited twice via A:
main.cpp:27:7: warning: virtual base ‘A’ inaccessible in ‘D’ due to ambiguity [-Wextra]
27 | class D : public B, public C {
| ^
main.cpp: In member function ‘virtual int D::h()’:
main.cpp:30:40: error: request for member ‘i’ is ambiguous
30 | virtual int h() { return this->i + this->j + this->k; }
| ^
main.cpp:7:13: note: candidates are: ‘int A::i’
7 | int i;
| ^
main.cpp:7:13: note: ‘int A::i’
main.cpp: In function ‘int main()’:
main.cpp:34:20: error: invalid cast to abstract class type ‘D’
34 | D d = D(1, 2, 4);
| ^
main.cpp:27:7: note: because the following virtual functions are pure within ‘D’:
27 | class D : public B, public C {
| ^
main.cpp:8:21: note: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:34:7: error: cannot declare variable ‘d’ to be of abstract type ‘D’
34 | D d = D(1, 2, 4);
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:35:14: error: request for member ‘f’ is ambiguous
35 | assert(d.f() == 3);
| ^
main.cpp:8:21: note: candidates are: ‘virtual int A::f()’
8 | virtual int f() = 0;
| ^
main.cpp:17:21: note: ‘virtual int B::f()’
17 | virtual int f() { return this->i + this->j; }
| ^
In file included from /usr/include/c++/9/cassert:44,
from main.cpp:1:
main.cpp:36:14: error: request for member ‘g’ is ambiguous
36 | assert(d.g() == 5);
| ^
main.cpp:9:21: note: candidates are: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
main.cpp:24:21: note: ‘virtual int C::g()’
24 | virtual int g() { return this->i + this->k; }
| ^
main.cpp:9:21: note: ‘virtual int A::g()’
9 | virtual int g() = 0;
| ^
./main.out
Tested on GCC 9.3.0, Ubuntu 20.04.
You can implement your OTF
font using @font-face like:
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWeb.otf") format("opentype");
}
@font-face {
font-family: GraublauWeb;
font-weight: bold;
src: url("path/GraublauWebBold.otf") format("opentype");
}
// Edit: OTF now works in most browsers, see comments
However if you want to support a wide variety of browsers i would recommend you to switch to WOFF
and TTF
font types. WOFF
type is implemented by every major desktop browser, while the TTF
type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.
@font-face {
font-family: GraublauWeb;
src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf") format("truetype");
}
If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:
@font-face {
font-family: GraublauWeb;
src: url("webfont.eot"); /* IE9 Compat Modes */
src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
url("webfont.woff") format("woff"), /* Modern Browsers */
url("webfont.ttf") format("truetype"), /* Safari, Android, iOS */
url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}
You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:
hope this helps
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
In Windows, I only managed to be able to delete the lock file after Ending Task for all Git Windows (32bit) processes in the Task Manager.
Solution (Win 10)
1. End Task for all Git Windows (32bit) processes in the Task Manager
2. Delete the .git/index.lock file
Run
cordova -v
to see the currently running version. Run the npm info command
npm info cordova
for a longer listing that includes the current version along with other available version numbers
Use the following script tag in your jsp/js file:
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
this will work for sure.
This solution uses the select
module to "read any available data" from an IO stream. This function blocks initially until data is available, but then reads only the data that is available and doesn't block further.
Given the fact that it uses the select
module, this only works on Unix.
The code is fully PEP8-compliant.
import select
def read_available(input_stream, max_bytes=None):
"""
Blocks until any data is available, then all available data is then read and returned.
This function returns an empty string when end of stream is reached.
Args:
input_stream: The stream to read from.
max_bytes (int|None): The maximum number of bytes to read. This function may return fewer bytes than this.
Returns:
str
"""
# Prepare local variables
input_streams = [input_stream]
empty_list = []
read_buffer = ""
# Initially block for input using 'select'
if len(select.select(input_streams, empty_list, empty_list)[0]) > 0:
# Poll read-readiness using 'select'
def select_func():
return len(select.select(input_streams, empty_list, empty_list, 0)[0]) > 0
# Create while function based on parameters
if max_bytes is not None:
def while_func():
return (len(read_buffer) < max_bytes) and select_func()
else:
while_func = select_func
while True:
# Read single byte at a time
read_data = input_stream.read(1)
if len(read_data) == 0:
# End of stream
break
# Append byte to string buffer
read_buffer += read_data
# Check if more data is available
if not while_func():
break
# Return read buffer
return read_buffer
You can try this, $myArray
as the Array
$filename = "mylog.txt";
$text = "";
foreach($myArray as $key => $value)
{
$text .= $key." : ".$value."\n";
}
$fh = fopen($filename, "w") or die("Could not open log file.");
fwrite($fh, $text) or die("Could not write file!");
fclose($fh);
To give the simplest answer I can think of:
Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.
Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.
(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)
Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.
We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.
You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.
So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.
if you know the index of the item of default value,just
lstDepartment.SelectedIndex = 1;//the second item
or if you know the value you want to set, just
lstDepartment.SelectedValue = "the value you want to set";
You may try this, Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory
Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/
Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop
#!/bin/bash -v
hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv
hive -f ./AllstarFull.hive
hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv
hive -f ./Appearances.hive
hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv
hive -f ./AwardsManagers.hive
Sample of generated Hive scripts
CREATE DATABASE IF NOT EXISTS lahman;
USE lahman;
CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
SELECT * FROM AllstarFull;
Thanks Vijay
Just to expand on @splattne's answer a little:
MapPath(string virtualPath)
calls the following:
public string MapPath(string virtualPath)
{
return this.MapPath(VirtualPath.CreateAllowNull(virtualPath));
}
MapPath(VirtualPath virtualPath)
in turn calls MapPath(VirtualPath virtualPath, VirtualPath baseVirtualDir, bool allowCrossAppMapping)
which contains the following:
//...
if (virtualPath == null)
{
virtualPath = VirtualPath.Create(".");
}
//...
So if you call MapPath(null)
or MapPath("")
, you are effectively calling MapPath(".")
Cast abc to an integer.
(int)(Math.random()*100);
if you are using spring security then you can get the current logged in user by
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName(); //get logged in username
Just add parameters, split by comma:
UPDATE tablename SET column1 = "value1", column2 = "value2" ....
see the link also MySQL UPDATE
I use the following to create a temp exact as the table but without the identity:
SELECT TOP 0 CONVERT(INT,0)myid,* INTO #temp FROM originaltable
ALTER TABLE #temp DROP COLUMN id
EXEC tempdb.sys.sp_rename N'#temp.myid', N'id', N'COLUMN'
Gets a warning about renames but no big deal. I use this on production class systems. Helps make sure the copy will follow any future table modifications and the temp produced is capable of getting rows additional times within a task. Please note that the PK constraint is also removed - if you need it you can add it at the end.
If you would like to monitor the changes each time there is a keystroke on the keyboard.
const textarea = document.querySelector(`#string`)
textarea.addEventListener("keydown", (e) =>{
console.log('test')
})
Expanding on Greg Kindel's second answer, you can write a function to eliminate some of the boilerplate:
var fmt = {
join: function() {
return Array.prototype.slice.call(arguments).join(' ');
},
log: function() {
console.log(this.join(...arguments));
}
}
Usage:
var age = 7;
var years = 5;
var sentence = fmt.join('I am now', age, 'years old!');
fmt.log('In', years, 'years I will be', age + years, 'years old!');
Print a string as hex bytes?
The accepted answer gives:
s = "Hello world !!"
":".join("{:02x}".format(ord(c)) for c in s)
returns:
'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21'
The accepted answer works only so long as you use bytes (mostly ascii characters). But if you use unicode, e.g.:
a_string = u"?????? ???!!" # "Prevyet mir", or "Hello World" in Russian.
You need to convert to bytes somehow.
If your terminal doesn't accept these characters, you can decode from UTF-8 or use the names (so you can paste and run the code along with me):
a_string = (
"\N{CYRILLIC CAPITAL LETTER PE}"
"\N{CYRILLIC SMALL LETTER ER}"
"\N{CYRILLIC SMALL LETTER I}"
"\N{CYRILLIC SMALL LETTER VE}"
"\N{CYRILLIC SMALL LETTER IE}"
"\N{CYRILLIC SMALL LETTER TE}"
"\N{SPACE}"
"\N{CYRILLIC SMALL LETTER EM}"
"\N{CYRILLIC SMALL LETTER I}"
"\N{CYRILLIC SMALL LETTER ER}"
"\N{EXCLAMATION MARK}"
"\N{EXCLAMATION MARK}"
)
So we see that:
":".join("{:02x}".format(ord(c)) for c in a_string)
returns
'41f:440:438:432:435:442:20:43c:438:440:21:21'
a poor/unexpected result - these are the code points that combine to make the graphemes we see in Unicode, from the Unicode Consortium - representing languages all over the world. This is not how we actually store this information so it can be interpreted by other sources, though.
To allow another source to use this data, we would usually need to convert to UTF-8 encoding, for example, to save this string in bytes to disk or to publish to html. So we need that encoding to convert the code points to the code units of UTF-8 - in Python 3, ord
is not needed because bytes
are iterables of integers:
>>> ":".join("{:02x}".format(c) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
Or perhaps more elegantly, using the new f-strings (only available in Python 3):
>>> ":".join(f'{c:02x}' for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
In Python 2, pass c
to ord
first, i.e. ord(c)
- more examples:
>>> ":".join("{:02x}".format(ord(c)) for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
>>> ":".join(format(ord(c), '02x') for c in a_string.encode('utf-8'))
'd0:9f:d1:80:d0:b8:d0:b2:d0:b5:d1:82:20:d0:bc:d0:b8:d1:80:21:21'
grep '^..' my_file
example
THIS
IS
THE
FILE
EOF_MYFILE
it gives as output only lines with at least 2 characters.
THIS
IS
THE
FILE
EOF_MYFILE
See also the results with grep '^' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
and also with grep '^.' my_file
outputs
THIS
IS
THE
FILE
EOF_MYFILE
In cpp, you need to pay special attention to string types when using execvp
:
#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;
const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());
// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
string arg;
cin >> arg;
if (arg.empty()) {
argv[arg_i] = nullptr;
break;
} else {
argv[arg_i] = strdup(arg.c_str());
}
++arg_i;
}
// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
// Print error if command not found
cerr << "command '" << command << "' not found\n";
}
Reference: execlp?execvp?????
As explained in "Deleting your master branch" by Matthew Brett, you need to change your GitHub repo default branch.
You need to go to the GitHub page for your forked repository, and click on the “Settings” button.
Click on the "Branches" tab on the left hand side. There’s a “Default branch” dropdown list near the top of the screen.
From there, select placeholder (where placeholder is the dummy name for your new default branch).
Confirm that you want to change your default branch.
Now you can do (from the command line):
git push origin :master
Or, since 2012, you can delete that same branch directly on GitHub:
That was announced in Sept. 2013, a year after I initially wrote that answer.
For small changes like documentation fixes, typos, or if you’re just a walking software compiler, you can get a lot done in your browser without needing to clone the entire repository to your computer.
Note: for BitBucket, Tum reports in the comments:
About the same for Bitbucket
Repo -> Settings -> Repository details -> Main branch
The easiest way is with REBOL 3:
http://rebolforum.com/index.cgi?f=printtopic&permalink=Nick25-Aug-2013/10:08:38-7:00&archiveflag=new
Here are 10 fully functional demo programs, with GUIs. These run on Android and desktop OSs, using the exact same code:
REBOL []
load-gui
view [text "Hello World!"]
REBOL [title: "Tiny Note Editor"]
do %r3-gui.r3 ; download this file manually or just use load-gui as above
view [
a1: area
button "Save" on-action [write %notes.txt get-face a1]
button "Load" on-action [set-face a1 to-string read %notes.txt]
]
REBOL [title: "Data Entry to CSV File"]
do %r3-gui.r3
view [
text "First Name:"
f1: field
text "Last Name:"
f2: field
button "Submit" on-action [
write/append %cntcts.txt rejoin [
mold get-face f1 " " mold get-face f2 newline
]
request "" "Saved"
]
a1: area
button "Load" on-action [set-face a1 to-string read %cntcts.txt]
]
REBOL [title: "Text File Reader (How to use a text list file selector)"]
do %r3-gui.r3
view [
a1: area
button "Load" on-action [
files: read %./
view/modal [
text "File Name:"
t2: text-list files on-action [
set-face a1 to-string read(to-file pick files get-face t2)
unview
]
]
]
]
REBOL [title: "List-View (Grid) Example"]
do %r3-gui.r3
view [
text-table ["1" 200 "2" 100 "3"][
["asdf" "a" "4"]
["sdfg" "b" "3"]
["dfgh" "c" "2"]
["fghj" "d" "1"]
]
]
REBOL [title: "Calculator"]
do %r3-gui.r3
stylize [
btn: button [
facets: [init-size: 50x50]
actors: [on-action:[set-face f join get-face f get-face face]]
]
]
view [
hgroup [
f: field return
btn "1" btn "2" btn "3" btn " + " return
btn "4" btn "5" btn "6" btn " - " return
btn "7" btn "8" btn "9" btn " * " return
btn "0" btn "." btn " / " btn "=" on-action [
attempt [set-face f form do get-face f]
]
]
]
REBOL [title: "Sliding Tile Puzzle"]
do %r3-gui.r3
stylize [
p: button [
facets: [init-size: 60x60 max-size: 60x60]
actors: [
on-action: [
t: face/gob/offset
face/gob/offset: x/gob/offset
x/gob/offset: t
]
]
]
]
view/options [
hgroup [
p "8" p "7" p "6" return
p "5" p "4" p "3" return
p "2" p "1" x: box 60x60 white
]
] [bg-color: white]
REBOL [title: "Math Test"]
do %r3-gui.r3
random/seed now
x: does [rejoin [random 10 " + " random 20]]
view [
f1: field (x)
text "Answer:"
f2: field on-action [
either (get-face f2) = (form do get-face f1) [
request "Yes!" "Yes!"][request "No!" "No!"
]
set-face f1 x
set-face f2 ""
focus f2
]
]
REBOL [title: "Minimal Cash Register"]
do %r3-gui.r3
stylize [fld: field [init-size: 80]]
view [
hgroup [
text "Cashier:" cashier: fld
text "Item:" item: fld
text "Price:" price: fld on-action [
if error? try [to-money get-face price] [
request "Error" "Price error"
return none
]
set-face a rejoin [
get-face a mold get-face item tab get-face price newline
]
set-face item copy "" set-face price copy ""
sum: 0
foreach [item price] load get-face a [
sum: sum + to-money price
]
set-face subtotal form sum
set-face tax form sum * .06
set-face total form sum * 1.06
focus item
]
return
a: area 600x300
return
text "Subtotal:" subtotal: fld
text "Tax:" tax: fld
text "Total:" total: fld
button "Save" on-action [
items: replace/all (mold load get-face a) newline " "
write/append %sales.txt rejoin [
items newline get-face cashier newline now/date newline
]
set-face item copy "" set-face price copy ""
set-face a copy "" set-face subtotal copy ""
set-face tax copy "" set-face total copy ""
]
]
]
REBOL [title: "Requestors"]
do %r3-gui.r3
x: request/ask "Question" "Do you like this?."
either x = false [print "No!"] [print "Yes!"]
x: request/custom "" "Do you like this?" ["Yay" "Boo"]
either x = false [print "Boo!"] [print "Yay!"]
view [button "Click me" on-action[request "Ok" "You clicked the button."]]
You can use it which is most helpful.
df = pd.read_csv(('data.txt'), sep="\t", skiprows=[0,1], names=['FromNode','ToNode'])
In elasticsearch path home dir i.e. typically /usr/share/elasticsearch
,
There is a config file bin/elasticsearch.in.sh
.
Edit parameter ES_MIN_MEM
, ES_MAX_MEM
in this file to change -Xms2g
, -Xmx4g
respectively.
And Please make sure you have restarted the node after this config change.
I would change your binding to be:
<button type="button" value="click me" onclick="check_me" />
I would then change your check_me()
function declaration to be:
function check_me() {
//event.preventDefault();
var hello = document.myForm.username.value;
var err = '';
if(hello == '' || hello == null) {
err = 'User name required';
}
if(err != '') {
alert(err);
$('username').focus();
event.preventDefault();
} else {
return true; }
}
For me the solution was to add the registry to here:
/etc/sysconfig/docker-registries
DOCKER_REGISTRIES=''
DOCKER_EXTRA_REGISTRIES='--insecure-registry b.example.com'
No, not reliably. There are simply too many unknown variables
The list goes on. Someday I hope there will be such a method of reliably accomplishing this with JavaScript, but until that day comes, your out of luck.
I hate these kinds of answers and I hope someone can prove me wrong.
You could also, in another directory:
The only thing I found that worked was a post here: https://stackoverflow.com/a/44548729/9488229
I improved it, and now it provides all these features:
Javascript:
$(document).ready(function () {
$('.btn').on('click', function() {
var e=this;
setTimeout(function() {
e.innerHTML='<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Searching...';
e.disabled=true;
},0);
return true;
});
});
We can call Controller method using Javascript / Jquery very easily as follows:
Suppose following is the Controller method to be called returning an array of some class objects. Let the class is 'A'
public JsonResult SubMenu_Click(string param1, string param2)
{
A[] arr = null;
try
{
Processing...
Get Result and fill arr.
}
catch { }
return Json(arr , JsonRequestBehavior.AllowGet);
}
Following is the complex type (class)
public class A
{
public string property1 {get ; set ;}
public string property2 {get ; set ;}
}
Now it was turn to call above controller method by JQUERY. Following is the Jquery function to call the controller method.
function callControllerMethod(value1 , value2) {
var strMethodUrl = '@Url.Action("SubMenu_Click", "Home")?param1=value1 ¶m2=value2'
$.getJSON(strMethodUrl, receieveResponse);
}
function receieveResponse(response) {
if (response != null) {
for (var i = 0; i < response.length; i++) {
alert(response[i].property1);
}
}
}
In the above Jquery function 'callControllerMethod' we develop controller method url and put that in a variable named 'strMehodUrl' and call getJSON method of Jquery API.
receieveResponse is the callback function receiving the response or return value of the controllers method.
Here we made use of JSON , since we can't make use of the C# class object
directly into the javascript function , so we converted the result (arr) in controller method into JSON object as follows:
Json(arr , JsonRequestBehavior.AllowGet);
and returned that Json object.
Now in callback function of the Javascript / JQuery we can make use of this resultant JSON object and work accordingly to show response data on UI.
For more detaill click here
Try the jQuery starts-with
selector, '^=', eg
[id^="jander"]
I have to ask though, why don't you want to do this using classes?
Restart your IDE and everything will be fine
you could use getAttribute:
var p = document.getElementById("p");
var alignP = p.getAttribute("align");
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute
Globals in Python are global to a module, not across all modules. (Many people are confused by this, because in, say, C, a global is the same across all implementation files unless you explicitly make it static
.)
There are different ways to solve this, depending on your actual use case.
Before even going down this path, ask yourself whether this really needs to be global. Maybe you really want a class, with f
as an instance method, rather than just a free function? Then you could do something like this:
import module1
thingy1 = module1.Thingy(a=3)
thingy1.f()
If you really do want a global, but it's just there to be used by module1
, set it in that module.
import module1
module1.a=3
module1.f()
On the other hand, if a
is shared by a whole lot of modules, put it somewhere else, and have everyone import it:
import shared_stuff
import module1
shared_stuff.a = 3
module1.f()
… and, in module1.py:
import shared_stuff
def f():
print shared_stuff.a
Don't use a from
import unless the variable is intended to be a constant. from shared_stuff import a
would create a new a
variable initialized to whatever shared_stuff.a
referred to at the time of the import, and this new a
variable would not be affected by assignments to shared_stuff.a
.
Or, in the rare case that you really do need it to be truly global everywhere, like a builtin, add it to the builtin module. The exact details differ between Python 2.x and 3.x. In 3.x, it works like this:
import builtins
import module1
builtins.a = 3
module1.f()
Do this:
driver.ExecuteScript("window.open('your URL', '_blank');");
This what worked for me. set HeaderStyle-Width="5%", in the footer set textbox width Width="15",also set the width of your gridview to 100%. following is the one of the column of my gridview.
<asp:TemplateField HeaderText = "sub" HeaderStyle-ForeColor="White" HeaderStyle-Width="5%">
<ItemTemplate>
<asp:Label ID="sub" runat="server" Font-Size="small" Text='<%# Eval("sub")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_sub" runat="server" Text='<%# Eval("sub")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_sub" runat="server" Width="15"></asp:TextBox>
</FooterTemplate>
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.
import React from 'react';
import withRouter from 'react-router-dom';
const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)
export withRouter(MyComponent);
In okhttp v4.* I got it working that way
// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
// ...
json : String = "..."
val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)
// go on with Request.Builder() etc
I think it would be smart to only show the hand/pointer cursor when JavaScript is available. So people will not have the feeling they can click on something that is not clickable.
To achieve that you could use the JavaScript libary jQuery to add the CSS to the element like so
$("li").css({"cursor":"pointer"});
Or chain it directly to the click handler.
Or when modernizer in combination with <html class="no-js">
is used, the CSS would look like this:
.js li { cursor: pointer; }
I didn't know you could do that with cp.
You can do it with mkdir ..
mkdir -p /var/path/to/your/dir
EDIT See lhunath's answer for incorporating cp.
You can even say:
FollowHyperlink "www.google.com"
If you get Automation Error then use http://
:
ThisWorkbook.FollowHyperlink("http://www.google.com")
The new recommend way in Python3 is to use pathlib:
from pathlib import Path
mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
print(file.name)
# do your stuff
Instead of *.mp4
you can use any filter, even a recursive one like **/*.mp4
. If you want to use more than one extension, you can simply iterate all with *
or **/*
(recursive) and check every file's extension with file.name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))
The hacky, practical answer for people trying to evaluate which Heroku plan they need and can't wait for heroku's slow row counter to refresh:
Basically you want to run \dt
in psql
, copy the results to your favorite text editor (it will look like this:
public | auth_group | table | axrsosvelhutvw
public | auth_group_permissions | table | axrsosvelhutvw
public | auth_permission | table | axrsosvelhutvw
public | auth_user | table | axrsosvelhutvw
public | auth_user_groups | table | axrsosvelhutvw
public | auth_user_user_permissions | table | axrsosvelhutvw
public | background_task | table | axrsosvelhutvw
public | django_admin_log | table | axrsosvelhutvw
public | django_content_type | table | axrsosvelhutvw
public | django_migrations | table | axrsosvelhutvw
public | django_session | table | axrsosvelhutvw
public | exercises_assignment | table | axrsosvelhutvw
), then run a regex search and replace like this:
^[^|]*\|\s+([^|]*?)\s+\| table \|.*$
to:
select '\1', count(*) from \1 union/g
which will yield you something very similar to this:
select 'auth_group', count(*) from auth_group union
select 'auth_group_permissions', count(*) from auth_group_permissions union
select 'auth_permission', count(*) from auth_permission union
select 'auth_user', count(*) from auth_user union
select 'auth_user_groups', count(*) from auth_user_groups union
select 'auth_user_user_permissions', count(*) from auth_user_user_permissions union
select 'background_task', count(*) from background_task union
select 'django_admin_log', count(*) from django_admin_log union
select 'django_content_type', count(*) from django_content_type union
select 'django_migrations', count(*) from django_migrations union
select 'django_session', count(*) from django_session
;
(You'll need to remove the last union
and add the semicolon at the end manually)
Run it in psql
and you're done.
?column? | count
--------------------------------+-------
auth_group_permissions | 0
auth_user_user_permissions | 0
django_session | 1306
django_content_type | 17
auth_user_groups | 162
django_admin_log | 9106
django_migrations | 19
[..]
// 2 dimensional array of arrays of Ints
var arr = [[Int]]()
OR:
// 2 dimensional array of arrays of Ints
var arr: [[Int]] = []
OR if you need an array of predefined size (as mentioned by @0x7fffffff in comments):
// 2 dimensional array of arrays of Ints set to 0. Arrays size is 10x5
var arr = Array(count: 3, repeatedValue: Array(count: 2, repeatedValue: 0))
// ...and for Swift 3+:
var arr = Array(repeating: Array(repeating: 0, count: 2), count: 3)
arr[0][1] = 18
OR
let myVar = 18
arr[0][1] = myVar
arr[1] = [123, 456, 789]
OR
arr[0] += 234
OR
arr[0] += [345, 678]
If you had 3x2 array of 0(zeros) before these changes, now you have:
[
[0, 0, 234, 345, 678], // 5 elements!
[123, 456, 789],
[0, 0]
]
So be aware that sub arrays are mutable and you can redefine initial array that represented matrix.
let a = 0
let b = 1
if arr.count > a && arr[a].count > b {
println(arr[a][b])
}
Remarks: Same markup rules for 3 and N dimensional arrays.
You can listen resize
event and fire where some dimension change
directive
(function() {
'use strict';
angular
.module('myApp.directives')
.directive('resize', ['$window', function ($window) {
return {
link: link,
restrict: 'A'
};
function link(scope, element, attrs){
scope.width = $window.innerWidth;
function onResize(){
// uncomment for only fire when $window.innerWidth change
// if (scope.width !== $window.innerWidth)
{
scope.width = $window.innerWidth;
scope.$digest();
}
};
function cleanUp() {
angular.element($window).off('resize', onResize);
}
angular.element($window).on('resize', onResize);
scope.$on('$destroy', cleanUp);
}
}]);
})();
In html
<div class="row" resize> ,
<div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod">
<h4 ng-bind="::v.known_as"></h4>
</div>
</div>
Controller :
$scope.$watch('width', function(old, newv){
console.log(old, newv);
})
You can go through all the answers above to understand why the .add()
is restricted to '<?>'
, '<? extends>'
, and partly to '<? super>'
.
But here's the conclusion of it all if you want to remember it, and dont want to go exploring the answer every time:
List<? extends A>
means this will accept any List
of A
and subclass of A
.
But you cannot add anything to this list. Not even objects of type A
.
List<? super A>
means this will accept any list of A
and superclass of A
.
You can add objects of type A
and its subclasses.
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).
The code I am looking for is adjusting the savefig call to:
fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable
This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.
import matplotlib.pyplot as plt
import numpy as np
plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')
This produces:
[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.
Another way of doing this, in code only, is to detect if the process is running as admin like in the answer by @NG.. And then open the application again and close the current one.
I use this code when an application only needs admin privileges when run under certain conditions, such as when installing itself as a service. So it doesn't need to run as admin all the time like the other answers force it too.
Note in the below code NeedsToRunAsAdmin
is a method that detects if under current conditions admin privileges are required. If this returns false
the code will not elevate itself. This is a major advantage of this approach over the others.
Although this code has the advantages stated above, it does need to re-launch itself as a new process which isn't always what you want.
private static void Main(string[] args)
{
if (NeedsToRunAsAdmin() && !IsRunAsAdmin())
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.UseShellExecute = true;
proc.WorkingDirectory = Environment.CurrentDirectory;
proc.FileName = Assembly.GetEntryAssembly().CodeBase;
foreach (string arg in args)
{
proc.Arguments += String.Format("\"{0}\" ", arg);
}
proc.Verb = "runas";
try
{
Process.Start(proc);
}
catch
{
Console.WriteLine("This application requires elevated credentials in order to operate correctly!");
}
}
else
{
//Normal program logic...
}
}
private static bool IsRunAsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(id);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
i have been working on Apachi Axis1.1 and Axis2.0 and JAX-WS but i would suggest you must JAX-WS because it allow you make wsdl in any format , i was making operation as GetInquiry() in Apache Axis2 it did not allow me to Start Operation name in Upper Case , so i find it not good , so i would suggest you must use JAX-WS
As we read in this answer, HTML5 will solve this for you if you're open to that route. HTML5 audio is supported in all modern browsers.
Here's a copy of the example:
var snd = new Audio("file.wav"); // buffers automatically when created
snd.play();
You can just use return
to end the method's execution
You can use from-exponential module. It is lightweight and fully tested.
import fromExponential from 'from-exponential';
fromExponential(1.123e-10); // => '0.0000000001123'
The parent function needs the virtual
keyword, and the child function needs the override
keyword in front of the function definition.
If you have
dict = {key1:value1, key2:value2, key3:value3,...}
In Python 2, dict.items()
copies each tuples and returns the list of tuples in dictionary i.e. [(key1,value1), (key2,value2), ...]
.
Implications are that the whole dictionary is copied to new list containing tuples
dict = {i: i * 2 for i in xrange(10000000)}
# Slow and memory hungry.
for key, value in dict.items():
print(key,":",value)
dict.iteritems()
returns the dictionary item iterator. The value of the item returned is also the same i.e. (key1,value1), (key2,value2), ...
, but this is not a list. This is only dictionary item iterator object. That means less memory usage (50% less).
d.items() -> list(d.items())
d.iteritems() -> iter(d.items())
The tuples are the same. You compared tuples in each so you get same.
dict = {i: i * 2 for i in xrange(10000000)}
# More memory efficient.
for key, value in dict.iteritems():
print(key,":",value)
In Python 3, dict.items()
returns iterator object. dict.iteritems() is removed so there is no more issue.
<link rel="icon" type="image/x-icon" href="http://example.com/favicon.ico" /> <link rel="icon" type="image/png" href="http://example.com/favicon.png" /> <link rel="icon" type="image/gif" href="http://example.com/favicon.gif" /> <link rel="icon" type="image/jpeg" href="http://example.com/favicon.jpeg" /> <link rel="icon" type="image/webp" href="http://example.com/favicon.webp" />
It all depends on which format of image you like to use!
if you have an icon of your website, it will be much better for UX!
show logo in the browser tab
I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,
return File(returnFilePath, contentType, fileName);
would give the error in mobile safari, where as
return File(returnFilePath, contentType);
would not.
I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.
'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''
def compare(bin1, bin2):
return bin1.lstrip('0') == bin2.lstrip('0')
def add(bin1, bin2):
result = ''
blen = max((len(bin1), len(bin2))) + 1
bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
carry_s = '0'
for b1, b2 in list(zip(bin1, bin2))[::-1]:
count = (carry_s, b1, b2).count('1')
carry_s = '1' if count >= 2 else '0'
result += '1' if count % 2 else '0'
return result[::-1]
if __name__ == '__main__':
print(add('101', '100'))
I leave the subtraction func as an exercise for the reader.
Implemented in JavaScript (ES6):
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
Usage:
const [ x, y ] = pointsOnCircle({ radius: 100, angle: 180, cx: 150, cy: 150 });
console.log( x, y );
/**
* Calculate x and y in circle's circumference
* @param {Object} input - The input parameters
* @param {number} input.radius - The circle's radius
* @param {number} input.angle - The angle in degrees
* @param {number} input.cx - The circle's origin x
* @param {number} input.cy - The circle's origin y
* @returns {Array[number,number]} The calculated x and y
*/
function pointsOnCircle({ radius, angle, cx, cy }){
angle = angle * ( Math.PI / 180 ); // Convert from Degrees to Radians
const x = cx + radius * Math.sin(angle);
const y = cy + radius * Math.cos(angle);
return [ x, y ];
}
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
function draw( x, y ){
ctx.clearRect( 0, 0, canvas.width, canvas.height );
ctx.beginPath();
ctx.strokeStyle = "orange";
ctx.arc( 100, 100, 80, 0, 2 * Math.PI);
ctx.lineWidth = 3;
ctx.stroke();
ctx.closePath();
ctx.beginPath();
ctx.fillStyle = "indigo";
ctx.arc( x, y, 6, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
}
let angle = 0; // In degrees
setInterval(function(){
const [ x, y ] = pointsOnCircle({ radius: 80, angle: angle++, cx: 100, cy: 100 });
console.log( x, y );
draw( x, y );
document.querySelector("#degrees").innerHTML = angle + "°";
document.querySelector("#points").textContent = x.toFixed() + "," + y.toFixed();
}, 100 );
_x000D_
<p>Degrees: <span id="degrees">0</span></p>
<p>Points on Circle (x,y): <span id="points">0,0</span></p>
<canvas width="200" height="200" style="border: 1px solid"></canvas>
_x000D_
A strong reference (which you will use in most cases) means that you want to "own" the object you are referencing with this property/variable. The compiler will take care that any object that you assign to this property will not be destroyed as long as you point to it with a strong reference. Only once you set the property to nil
will the object get destroyed (unless one or more other objects also hold a strong reference to it).
In contrast, with a weak reference you signify that you don't want to have control over the object's lifetime. The object you are referencing weakly only lives on because at least one other object holds a strong reference to it. Once that is no longer the case, the object gets destroyed and your weak property will automatically get set to nil
. The most frequent use cases of weak references in iOS are:
delegate properties, which are often referenced weakly to avoid retain cycles, and
subviews/controls of a view controller's main view because those views are already strongly held by the main view.
atomic vs. nonatomic refers to the thread safety of the getter and setter methods that the compiler synthesizes for the property. atomic (the default) tells the compiler to make the accessor methods thread-safe (by adding a lock before an ivar is accessed) and nonatomic does the opposite. The advantage of nonatomic is slightly higher performance. On iOS, Apple uses nonatomic for almost all their properties so the general advice is for you to do the same.
Yes its late - but may help someone on reference
xml with EditText, Button and TextView
onClick on Button will update the value from EditText to TextView
<EditText
android:id="@+id/et_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn_submit_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/txt_id"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Look at the code do the action in your class
Don't need to initialize the id's of components like in Java. You can do it by their xml Id's
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
btn_submit_id.setOnClickListener {
txt_id.setText(et_id.text);
}
}
also you can set value in TextView like,
textview.text = "your value"
I did following steps to downgrade Gradle back to the original version:
Probably last step is enough as in my case the path to the new Gradle distribution was hardcoded there under 'Gradle home' option.
Use >
and <
for 'greater-than' and 'less-than' respectively
You will have to use javascript, or the JQuery framework to do that. her is an example using Jquery
$('#toggle').click(function () {
//check if checkbox is checked
if ($(this).is(':checked')) {
$('#sendNewSms').removeAttr('disabled'); //enable input
} else {
$('#sendNewSms').attr('disabled', true); //disable input
}
});
Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.
Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.
either ceil and floor should give the same out out put
Math.ceil(x.y) == Math.floor(x.y)
or simply check for equality with double value
x.y == Math.ceil(x.y)
x.y == Math.floor(x.y)
or
Math.round(x.y) == x.y
Depending on what technologies you're using and what versions will influence how you define a RestTemplate
in your @Configuration
class.
Spring >= 4 without Spring Boot
Simply define an @Bean
:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
Spring Boot <= 1.3
No need to define one, Spring Boot automatically defines one for you.
Spring Boot >= 1.4
Spring Boot no longer automatically defines a RestTemplate
but instead defines a RestTemplateBuilder
allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder
as an argument in your @Bean
method to create a RestTemplate
:
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
// Do any additional configuration here
return builder.build();
}
Using it in your class
@Autowired
private RestTemplate restTemplate;
Use setInterval() to run a piece of code every x milliseconds.
You can wrap the code you want to run every second in a function called runFunction
.
So it would be:
var t=setInterval(runFunction,1000);
And to stop it, you can run:
clearInterval(t);
Opposite up is children(), but opposite in position is prepend(). Here a very good tutorial.
In my case, it was an infinite sort. That is, at first the line moved up according to the condition, and then the same line moved down to the same place. I added one more condition at the end that unambiguously established the order of the lines.
Implement Activity with View.OnClickListener
like below.
public class MyActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_options);
Button button = findViewById(R.id.button);
Button button2 = findViewById(R.id.button2);
button.setOnClickListener(this);
button2.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id) {
case R.id.button:
// Write your code here first button
break;
case R.id.button2:
// Write your code here for second button
break;
}
}
}
This version is using recursion
import pprint
from collections import deque
pp = pprint.PrettyPrinter(indent=4)
inp = raw_input("Enter a sentence to show as trie\n")
words = inp.split(" ")
trie = {}
def trie_recursion(trie_ds, word):
try:
letter = word.popleft()
out = trie_recursion(trie_ds.get(letter, {}), word)
except IndexError:
# End of the word
return {}
# Dont update if letter already present
if not trie_ds.has_key(letter):
trie_ds[letter] = out
return trie_ds
for word in words:
# Go through each word
trie = trie_recursion(trie, deque(word))
pprint.pprint(trie)
Output:
Coool <algos> python trie.py
Enter a sentence to show as trie
foo bar baz fun
{
'b': {
'a': {
'r': {},
'z': {}
}
},
'f': {
'o': {
'o': {}
},
'u': {
'n': {}
}
}
}
Another simple solution is:
sb.setLength(sb.length() - 1);
A more complicated solution:
The above solution assumes that sb.length() > 0
... i.e. there is a "last character" to remove. If you can't make that assumption, and/or you can't deal with the exception that would ensue if the assumption is incorrect, then check the StringBuilder's length first; e.g.
// Readable version
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
or
// Concise but harder-to-read version of the above.
sb.setLength(Math.max(sb.length() - 1, 0));
L
: long i = 12345678910L;
.BTW: it doesn't have to be an upper case L, but lower case is confused with 1
many times :).
I had the same problem.
My Solution:
go to /etc/phpmyadmin and edit apache.conf
in the <Directory>[...]</Directory>
section you can add
php_value upload_max_filesize 10M
php_value post_max_size 10M
Solved the problem for me!
why dont you try something very simple?
use psexec with command 'shutdown /r /f /t 0' and a PC list from CMD.
Surely everyone's missed a trick here. The current file size limit of a json file is 18,446,744,073,709,551,616 characters or if you prefer bytes, or even 2^64 bytes if you're looking at 64 bit infrastructures at least.
For all intents, and purposes we can assume it's unlimited as you'll probably have a hard time hitting this issue...
Try this:
SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches
Cast the dtype
of the col to str
and you can perform vectorised slicing calling str
:
In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df
Out[29]:
First Second new_col
0 123 234 1
1 22 4353 2
2 32 355 3
3 453 453 4
4 45 345 4
5 453 453 4
6 56 56 5
if you need to you can cast the dtype
back again calling astype(int)
on the column
Not quite...
http://en.wikipedia.org/wiki/Representational_State_Transfer
REST was initially described in the context of HTTP, but is not limited to that protocol. RESTful architectures can be based on other Application Layer protocols if they already provide a rich and uniform vocabulary for applications based on the transfer of meaningful representational state. RESTful applications maximise the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimise the addition of new application-specific features on top of it.
http://www.looselycoupled.com/glossary/SOAP
(Simple Object Access Protocol) The standard for web services messages. Based on XML, SOAP defines an envelope format and various rules for describing its contents. Seen (with WSDL and UDDI) as one of the three foundation standards of web services, it is the preferred protocol for exchanging web services, but by no means the only one; proponents of REST say that it adds unnecessary complexity.
This can't be done in just HTML (with form elements into option
elements).
Or you can just use a standard select multiple
field.
<select multiple>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
If my compiler is set to 32 bit, size_t
is nothing other than a typedef for unsigned int
. If my compiler is set to 64 bit, size_t
is nothing other than a typedef for unsigned long long
.
your question and the answers looks different. I don't know if I am mistaken, but for those who googles and reach here my answer would be the following:
My Answer explained:
here is a simple javascript for that
call this when you need to scroll the screen to an element which has id="yourSpecificElementId"
window.scroll(0,findPos(document.getElementById("yourSpecificElementId")));
ie. for the above question, if the intention is to scroll the screen to the div with id 'divFirst'
the code would be: window.scroll(0,findPos(document.getElementById("divFirst")));
and you need this function for the working:
//Finds y value of given object
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
the screen will be scrolled to your specific element.
Try:
select
id,
StartDate,
CASE WHEN StartDate IS NULL
THEN 'Awaiting'
ELSE 'Approved' END AS StartDateStatus
FROM myTable
You code would have been doing a When StartDate = NULL, I think.
NULL
is never equal to NULL
(as NULL is the absence of a value). NULL
is also never not equal to NULL
. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL
.
You can run the following:
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
And this returns:
EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1
For completeness, in SQL Server you can:
SET ANSI_NULLS OFF;
Which would result in your equals comparisons working differently:
SET ANSI_NULLS OFF
SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison
Which returns:
EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1
But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...
Also, it will no longer work in upcoming versions of SQL server:
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
String numero = total.getText().toString();
int dec = numero.indexOf(".");
int longitud = numero.length();
if (dec+3 == longitud && dec != -1) { //3 number decimal + 1
log.i("ento","si");
numero = numero.substring(0,dec+3);
if (contador == 0) {
contador = 1;
total.setText(numero);
total.setSelection(numero.length());
} else {
contador = 0;
}
}
}
Check the .aws directory under home directory. Windows: C:\Users<home-name>.aws Linux: ~/.aws
Under this directory, you will find the config as well as credentials file. It will have the information from the aws configure that you may have run before. IF not, then
Run aws configure
Enter the access key -
secret key - enter secret key
region - (ap-southeast-1 or us-east-1 or any other regions)
format - (json or leave it blank, it will pick up default values you may simply hit enter)
From the Step 2, you should see the config file, open it, it should have the region. Please ensure there is region specified.
You may now run the following command to list the buckets
aws s3 ls
It should work fine.
With stringr package, one can also write a simple script that could traverse a vector of strings for example through a for loop.
Let's say
df$text
contains a vector of strings that we are interested in analysing. First, we add additional columns to the existing dataframe df as below:
df$strings = as.integer(NA)
df$characters = as.integer(NA)
Then we run a for-loop over the vector of strings as below:
for (i in 1:nrow(df))
{
df$strings[i] = str_count(df$text[i], '\\S+') # counts the strings
df$characters[i] = str_count(df$text[i]) # counts the characters & spaces
}
The resulting columns: strings and character will contain the counts of words and characters and this will be achieved in one-go for a vector of strings.
Trace.Write("Error Message") and Trace.Warn("Error Message") are the methods to use in web, need to decorate the page header trace=true and in config file to hide the error message text to go to end-user and so as to stay in iis itself for programmer debug.
in a bash script the following works:
#!/bin/sh
text="this is line one\nthis is line two\nthis is line three"
echo -e $text > filename
alternatively:
text="this is line one
this is line two
this is line three"
echo "$text" > filename
cat filename gives:
this is line one
this is line two
this is line three
See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf
Generically, you can determine the answer by running the command:
httpd -V
(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V
This will return various details about how httpd is built and configured, including the default location of the main configuration file.
One of the lines of output should look like:
-D SERVER_CONFIG_FILE="conf/httpd.conf"
which, combined with the line:
-D HTTPD_ROOT="/etc/httpd"
will give you a full path to the default location of the configuration file
A hook that allows for overriding copy events, could be used for doing the same with paste events. The input element cannot be display: none; or visibility: hidden; sadly
export const useOverrideCopy = () => {
const [copyListenerEl, setCopyListenerEl] = React.useState(
null as HTMLInputElement | null
)
const [, setCopyHandler] = React.useState<(e: ClipboardEvent) => void | null>(
() => () => {}
)
// appends a input element to the DOM, that will be focused.
// when using copy/paste etc, it will target focused elements
React.useEffect(() => {
const el = document.createElement("input")
// cannot focus a element that is not "visible" aka cannot use display: none or visibility: hidden
el.style.width = "0"
el.style.height = "0"
el.style.opacity = "0"
el.style.position = "fixed"
el.style.top = "-20px"
document.body.appendChild(el)
setCopyListenerEl(el)
return () => {
document.body.removeChild(el)
}
}, [])
// adds a event listener for copying, and removes the old one
const overrideCopy = (newOverrideAction: () => any) => {
setCopyHandler((prevCopyHandler: (e: ClipboardEvent) => void) => {
const copyHandler = (e: ClipboardEvent) => {
e.preventDefault()
newOverrideAction()
}
copyListenerEl?.removeEventListener("copy", prevCopyHandler)
copyListenerEl?.addEventListener("copy", copyHandler)
copyListenerEl?.focus() // when focused, all copy events will trigger listener above
return copyHandler
})
}
return { overrideCopy }
}
Used like this:
const customCopyEvent = () => {
console.log("doing something")
}
const { overrideCopy } = useOverrideCopy()
overrideCopy(customCopyEvent)
Every time you call overrideCopy it will refocus and call your custom event on copy.
SELECT date1 - date2
FROM some_table
returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So
SELECT (date1 - date2) * 24 * 60 difference_in_minutes
FROM some_table
should be what you're looking for
You use:
yourcommand > /dev/null 2>&1
If it should run in the Background add an &
yourcommand > /dev/null 2>&1 &
>/dev/null 2>&1
means redirect stdout
to /dev/null
AND stderr
to the place where stdout
points at that time
If you want stderr
to occur on console and only stdout
going to /dev/null
you can use:
yourcommand 2>&1 > /dev/null
In this case stderr
is redirected to stdout
(e.g. your console) and afterwards the original stdout
is redirected to /dev/null
If the program should not terminate you can use:
nohup yourcommand &
Without any parameter all output lands in nohup.out
From ES6,
var co = require('co');
var $ = require('jQuery');
// because jquery doesn't support Promises/A+ spec
function ajax(opts) {
return new Promise(function(resolve, reject) {
$.extend(opts, {
success: resolve,
error: reject
});
$.ajax(opts);
}
}
var poll = function() {
co(function *() {
return yield ajax({
url: '/my-api',
type: 'json',
method: 'post'
});
}).then(function(response) {
console.log(response);
}).catch(function(err) {
console.log(err);
});
};
setInterval(poll, 5000);
Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:
<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>
The cleanest way is use a function of janitor
package that is built for exactly this purpose.
janitor::row_to_names(DF,1)
If you want to use any other row than the first one, pass it in the second parameter.
@ManyToMany
associationsMost often, you will need to use @JoinTable
annotation to specify the mapping of a many-to-many table relationship:
So, assuming you have the following database tables:
In the Post
entity, you would map this relationship, like this:
@ManyToMany(cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
@JoinTable(
name = "post_tag",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "tag_id")
)
private List<Tag> tags = new ArrayList<>();
The @JoinTable
annotation is used to specify the table name via the name
attribute, as well as the Foreign Key column that references the post
table (e.g., joinColumns
) and the Foreign Key column in the post_tag
link table that references the Tag
entity via the inverseJoinColumns
attribute.
Notice that the cascade attribute of the
@ManyToMany
annotation is set toPERSIST
andMERGE
only because cascadingREMOVE
is a bad idea since we the DELETE statement will be issued for the other parent record,tag
in our case, not to thepost_tag
record.
@OneToMany
associationsThe unidirectional @OneToMany
associations, that lack a @JoinColumn
mapping, behave like many-to-many table relationships, rather than one-to-many.
So, assuming you have the following entity mappings:
@Entity(name = "Post")
@Table(name = "post")
public class Post {
@Id
@GeneratedValue
private Long id;
private String title;
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();
//Constructors, getters and setters removed for brevity
}
@Entity(name = "PostComment")
@Table(name = "post_comment")
public class PostComment {
@Id
@GeneratedValue
private Long id;
private String review;
//Constructors, getters and setters removed for brevity
}
Hibernate will assume the following database schema for the above entity mapping:
As already explained, the unidirectional @OneToMany
JPA mapping behaves like a many-to-many association.
To customize the link table, you can also use the @JoinTable
annotation:
@OneToMany(
cascade = CascadeType.ALL,
orphanRemoval = true
)
@JoinTable(
name = "post_comment_ref",
joinColumns = @JoinColumn(name = "post_id"),
inverseJoinColumns = @JoinColumn(name = "post_comment_id")
)
private List<PostComment> comments = new ArrayList<>();
And now, the link table is going to be called post_comment_ref
and the Foreign Key columns will be post_id
, for the post
table, and post_comment_id
, for the post_comment
table.
Unidirectional
@OneToMany
associations are not efficient, so you are better off using bidirectional@OneToMany
associations or just the@ManyToOne
side.
You will also get this error when there are stale EXCEL.EXE
processes in the system (Use Task Manager --> Processes
tab to view these.)
Kill all those instances and the application would work normally.
Since no answer here mentions a perfect, fail-proof ID that is both PERSISTENT through system updates and exists in ALL devices (mainly due to the fact that there isn't an individual solution from Google), I decided to post a method that is the next best thing by combining two of the available identifiers, and a check to chose between them at run-time.
Before code, 3 facts:
TelephonyManager.getDeviceId()
(a.k.a.IMEI) will not work well or at all for non-GSM, 3G, LTE, etc. devices, but will always return a unique ID when related hardware is present, even when no SIM is inserted or even when no SIM slot exists (some OEM's have done this).
Since Gingerbread (Android 2.3) android.os.Build.SERIAL
must exist on any device that doesn't provide IMEI, i.e., doesn't have the aforementioned hardware present, as per Android policy.
Due to fact (2.), at least one of these two unique identifiers will ALWAYS be present, and SERIAL can be present at the same time that IMEI is.
Note: Fact (1.) and (2.) are based on Google statements
SOLUTION
With the facts above, one can always have a unique identifier by checking if there is IMEI-bound hardware, and fall back to SERIAL when it isn't, as one cannot check if the existing SERIAL is valid. The following static class presents 2 methods for checking such presence and using either IMEI or SERIAL:
import java.lang.reflect.Method;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
public class IDManagement {
public static String getCleartextID_SIMCHECK (Context mContext){
String ret = "";
TelephonyManager telMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(isSIMAvailable(mContext,telMgr)){
Log.i("DEVICE UNIQUE IDENTIFIER",telMgr.getDeviceId());
return telMgr.getDeviceId();
}
else{
Log.i("DEVICE UNIQUE IDENTIFIER", Settings.Secure.ANDROID_ID);
// return Settings.Secure.ANDROID_ID;
return android.os.Build.SERIAL;
}
}
public static String getCleartextID_HARDCHECK (Context mContext){
String ret = "";
TelephonyManager telMgr = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if(telMgr != null && hasTelephony(mContext)){
Log.i("DEVICE UNIQUE IDENTIFIER",telMgr.getDeviceId() + "");
return telMgr.getDeviceId();
}
else{
Log.i("DEVICE UNIQUE IDENTIFIER", Settings.Secure.ANDROID_ID);
// return Settings.Secure.ANDROID_ID;
return android.os.Build.SERIAL;
}
}
public static boolean isSIMAvailable(Context mContext,
TelephonyManager telMgr){
int simState = telMgr.getSimState();
switch (simState) {
case TelephonyManager.SIM_STATE_ABSENT:
return false;
case TelephonyManager.SIM_STATE_NETWORK_LOCKED:
return false;
case TelephonyManager.SIM_STATE_PIN_REQUIRED:
return false;
case TelephonyManager.SIM_STATE_PUK_REQUIRED:
return false;
case TelephonyManager.SIM_STATE_READY:
return true;
case TelephonyManager.SIM_STATE_UNKNOWN:
return false;
default:
return false;
}
}
static public boolean hasTelephony(Context mContext)
{
TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
if (tm == null)
return false;
//devices below are phones only
if (Build.VERSION.SDK_INT < 5)
return true;
PackageManager pm = mContext.getPackageManager();
if (pm == null)
return false;
boolean retval = false;
try
{
Class<?> [] parameters = new Class[1];
parameters[0] = String.class;
Method method = pm.getClass().getMethod("hasSystemFeature", parameters);
Object [] parm = new Object[1];
parm[0] = "android.hardware.telephony";
Object retValue = method.invoke(pm, parm);
if (retValue instanceof Boolean)
retval = ((Boolean) retValue).booleanValue();
else
retval = false;
}
catch (Exception e)
{
retval = false;
}
return retval;
}
}
I would advice on using getCleartextID_HARDCHECK
. If the reflection doesn't stick in your environment, use the getCleartextID_SIMCHECK
method instead, but take in consideration it should be adapted to your specific SIM-presence needs.
P.S.: Do please note that OEM's have managed to bug out SERIAL against Google policy (multiple devices with same SERIAL), and Google as stated there is at least one known case in a big OEM (not disclosed and I don't know which brand it is either, I'm guessing Samsung).
Disclaimer: This answers the original question of getting a unique device ID, but the OP introduced ambiguity by stating he needs a unique ID for an APP. Even if for such scenarios Android_ID would be better, it WILL NOT WORK after, say, a Titanium Backup of an app through 2 different ROM installs (can even be the same ROM). My solution maintains persistence that is independent of a flash or factory reset, and will only fail when IMEI or SERIAL tampering occurs through hacks/hardware mods.
Don't use it. The description says:
Register one or more global variables with the current session.
Two things that came to my mind:
$_SESSION['var'] = "value"
.See also the warnings from the manual:
If you want your script to work regardless of
register_globals
, you need to instead use the$_SESSION
array as$_SESSION
entries are automatically registered. If your script usessession_register()
, it will not work in environments where the PHP directiveregister_globals
is disabled.
This is pretty important, because the register_globals
directive is set to False
by default!
Further:
This registers a
global
variable. If you want to register a session variable from within a function, you need to make sure to make it global using theglobal
keyword or the$GLOBALS[]
array, or use the special session arrays as noted below.
and
If you are using
$_SESSION
(or$HTTP_SESSION_VARS
), do not usesession_register()
,session_is_registered()
, andsession_unregister()
.
I dissent from both the answers. Don't create a reference at all, but use late binding:
Dim objExcelApp As Object
Dim wb As Object
Sub Initialize()
Set objExcelApp = CreateObject("Excel.Application")
End Sub
Sub ProcessDataWorkbook()
Set wb = objExcelApp.Workbooks.Open("path to my workbook")
Dim ws As Object
Set ws = wb.Sheets(1)
ws.Cells(1, 1).Value = "Hello"
ws.Cells(1, 2).Value = "World"
'Close the workbook
wb.Close
Set wb = Nothing
End Sub
You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().
This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.
Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.
After building your project the website needs some time to walk through the new dll :). It's normal that loading a webpage after rebuilding takes some time. This shouldn't happen when only changing something in for example javascript.
Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.
edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.
$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);
<script>
function myFunction() {
var y = parseInt(document.getElementById("txt1").value);
var z = parseInt(document.getElementById("txt2").value);
var x = y + z;
document.getElementById("result").innerHTML = x;
}
</script>
<p>
<label>Enter First Number : </label><br>
<input type="number" id="txt1" name="text1"><br/>
<label>Enter Second Number : </label><br>
<input type="number" id="txt2" name="text2">
</p>
<p>
<button onclick="myFunction()">Calculate</button>
</p>
<br/>
<p id="result"></p>
Similar to David Hall's response, if you are a non-coder, it may be easiest to right-click within results, then choose Pane > Criteria. This allows you to adjust sort, add filters, etc... without adjusting SQL code.
Finally I fixed the problem by modifying build.gradle
like this:
android {
compileSdkVersion 26
buildToolsVersion "26.0.2"
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
implementation 'com.android.support:design:26.1.0'
}
I've removed these lines as these will produce more errors:
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
Also I had same problem with migrating an existing project from 2.3 to 3.0.1 and with modifying the project gradle files like this, I came up with a working solution:
build.gradle (module app)
android {
compileSdkVersion 27
buildToolsVersion "27.0.1"
defaultConfig {
applicationId "com.mobaleghan.tablighcalendar"
minSdkVersion 16
targetSdkVersion 27
}
dependencies {
implementation 'com.android.support:appcompat-v7:25.1.0'
implementation 'com.android.support:design:25.1.0'
implementation 'com.android.support:preference-v7:25.1.0'
implementation 'com.android.support:recyclerview-v7:25.1.0'
implementation 'com.android.support:support-annotations:25.1.0'
implementation 'com.android.support:support-v4:25.1.0'
implementation 'com.android.support:cardview-v7:25.1.0'
implementation 'com.google.android.apps.dashclock:dashclock-api:2.0.0'
}
Top level build.gradle
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
For lists, use enumerate
for field, possible_values in enumerate(fields):
print(field, possible_values)
iteritems
will not work for list objects
The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...
The new variable needs to be created first.
The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --
df$newVariableName <- NA
Then you continue with whatever conditional assignment rules you have, like
df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"
I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/
Found this thread while I was looking for a solution to the exact problem described in the original post. None of the answers met my situation entirely, however. Brody's answer was pretty close. Here is my situation and solution I found to it.
I have two ILists of the same type returned by NHibernate and have emerged the two IList into one, hence the need for sorting.
Like Brody said I implemented an ICompare on the object (ReportFormat) which is the type of my IList:
public class FormatCcdeSorter:IComparer<ReportFormat>
{
public int Compare(ReportFormat x, ReportFormat y)
{
return x.FormatCode.CompareTo(y.FormatCode);
}
}
I then convert the merged IList to an array of the same type:
ReportFormat[] myReports = new ReportFormat[reports.Count]; //reports is the merged IList
Then sort the array:
Array.Sort(myReports, new FormatCodeSorter());//sorting using custom comparer
Since one-dimensional array implements the interface System.Collections.Generic.IList<T>
, the array can be used just like the original IList.
Just in case you are able to utilize a scripting language to prepare your SQL queries, you could reuse field=value pairs by using SET
instead of (a,b,c) VALUES(a,b,c)
.
An example with PHP:
$pairs = "a=$a,b=$b,c=$c";
$query = "INSERT INTO $table SET $pairs ON DUPLICATE KEY UPDATE $pairs";
Example table:
CREATE TABLE IF NOT EXISTS `tester` (
`a` int(11) NOT NULL,
`b` varchar(50) NOT NULL,
`c` text NOT NULL,
UNIQUE KEY `a` (`a`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
This question is eight years old and still not a fully correct answer! No, you should not have to import an entire third party API to do this simple task. Bad advice.
The following method will:
I've tried to optimise for the most common case, while still ensuring you could pipe /dev/random through this and get a valid string in XML.
public static String encodeXML(CharSequence s) {
StringBuilder sb = new StringBuilder();
int len = s.length();
for (int i=0;i<len;i++) {
int c = s.charAt(i);
if (c >= 0xd800 && c <= 0xdbff && i + 1 < len) {
c = ((c-0xd7c0)<<10) | (s.charAt(++i)&0x3ff); // UTF16 decode
}
if (c < 0x80) { // ASCII range: test most common case first
if (c < 0x20 && (c != '\t' && c != '\r' && c != '\n')) {
// Illegal XML character, even encoded. Skip or substitute
sb.append("�"); // Unicode replacement character
} else {
switch(c) {
case '&': sb.append("&"); break;
case '>': sb.append(">"); break;
case '<': sb.append("<"); break;
// Uncomment next two if encoding for an XML attribute
// case '\'' sb.append("'"); break;
// case '\"' sb.append("""); break;
// Uncomment next three if you prefer, but not required
// case '\n' sb.append(" "); break;
// case '\r' sb.append(" "); break;
// case '\t' sb.append("	"); break;
default: sb.append((char)c);
}
}
} else if ((c >= 0xd800 && c <= 0xdfff) || c == 0xfffe || c == 0xffff) {
// Illegal XML character, even encoded. Skip or substitute
sb.append("�"); // Unicode replacement character
} else {
sb.append("&#x");
sb.append(Integer.toHexString(c));
sb.append(';');
}
}
return sb.toString();
}
Edit: for those who continue to insist it foolish to write your own code for this when there are perfectly good Java APIs to deal with XML, you might like to know that the StAX API included with Oracle Java 8 (I haven't tested others) fails to encode CDATA content correctly: it doesn't escape ]]> sequences in the content. A third party library, even one that's part of the Java core, is not always the best option.
Try changing your code to this:
private void Test()
{
System.IO.MemoryStream data = new System.IO.MemoryStream(TestStream());
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
}
in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.
As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?
$('#myForm').ajaxSend( function() {
$(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
$(this).removeClass('loading');
});
Example CSS, to hide #myForm with a spinner:
.loading {
display: block;
background: url(spinner.gif) no-repeat center middle;
width: 124px;
height: 124px;
margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
display: none;
}
Small tip for you. Microsoft frequently has 'launch parties' or 'launch events' in which they frequently distribute licensed, not for resale copies, of that product. I've gotten the last two versions of VS (2005 and 2008) by attending my local .NET user group chapter during those days.
Some of the following solutions have problems with performance, functionality and style... They are not thought through enough, and some of them fail for different cases. I tried to address this problem in my own solution, and I would really much appreciate your feedback:
http://stamat.wordpress.com/javascript-object-comparison/
//Returns the object's class, Array, Date, RegExp, Object are of interest to us
var getClass = function(val) {
return Object.prototype.toString.call(val)
.match(/^\[object\s(.*)\]$/)[1];
};
//Defines the type of the value, extended typeof
var whatis = function(val) {
if (val === undefined)
return 'undefined';
if (val === null)
return 'null';
var type = typeof val;
if (type === 'object')
type = getClass(val).toLowerCase();
if (type === 'number') {
if (val.toString().indexOf('.') > 0)
return 'float';
else
return 'integer';
}
return type;
};
var compareObjects = function(a, b) {
if (a === b)
return true;
for (var i in a) {
if (b.hasOwnProperty(i)) {
if (!equal(a[i],b[i])) return false;
} else {
return false;
}
}
for (var i in b) {
if (!a.hasOwnProperty(i)) {
return false;
}
}
return true;
};
var compareArrays = function(a, b) {
if (a === b)
return true;
if (a.length !== b.length)
return false;
for (var i = 0; i < a.length; i++){
if(!equal(a[i], b[i])) return false;
};
return true;
};
var _equal = {};
_equal.array = compareArrays;
_equal.object = compareObjects;
_equal.date = function(a, b) {
return a.getTime() === b.getTime();
};
_equal.regexp = function(a, b) {
return a.toString() === b.toString();
};
// uncoment to support function as string compare
// _equal.fucntion = _equal.regexp;
/*
* Are two values equal, deep compare for objects and arrays.
* @param a {any}
* @param b {any}
* @return {boolean} Are equal?
*/
var equal = function(a, b) {
if (a !== b) {
var atype = whatis(a), btype = whatis(b);
if (atype === btype)
return _equal.hasOwnProperty(atype) ? _equal[atype](a, b) : a==b;
return false;
}
return true;
};
you can use regex as the delimiter:
pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")
Thank you for the good script.
I have just added the shift event on the above function to go back between elements, I thought someone may need this.
$('body').on('keydown', 'input, select, textarea', function(e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
, prev
;
if (e.shiftKey) {
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
prev = focusable.eq(focusable.index(this)-1);
if (prev.length) {
prev.focus();
} else {
form.submit();
}
}
}
else
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button,textarea').filter(':visible');
next = focusable.eq(focusable.index(this)+1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
I'm using AWS LightSail and for my instance to work, I had to change:
bind-address = 127.0.0.1
to
bind-address = <Private IP Assigned by Amazon>
Then I was able to connect remotely.
it defaults to submitting a form, easiest way is to add "return false"
<button type="cancel" onclick="window.location='http://stackoverflow.com';return false;">Cancel</button>
I assume that you haven't set the TableName
property of the DataTable, for example via constructor:
var tbl = new DataTable("dtImage");
If you don't provide a name, it will be automatically created with "Table1"
, the next table will get "Table2"
and so on.
Then the solution would be to provide the TableName
and then check with Contains(nameOfTable)
.
To clarify it: You'll get an ArgumentException
if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException
if there's already a DataTable in the DataSet with the same name(not case-sensitive).
Two solutions that work (on modern Chrome at least - haven't tested beyond):
Another option is the SimpleXML extension (I believe it comes standard with most php installs.)
http://php.net/manual/en/book.simplexml.php
The syntax looks something like this for your example
$xml = new SimpleXMLElement($xmlString);
echo $xml->bbb->cccc->dddd['Id'];
echo $xml->bbb->cccc->eeee['name'];
// or...........
foreach ($xml->bbb->cccc as $element) {
foreach($element as $key => $val) {
echo "{$key}: {$val}";
}
}
Just use print(*(dict.keys()))
The * can be used for unpacking containers e.g. lists. For more info on * check this SO answer.
Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar
, don't pass "foobar"
. You have to pass "FooBar"
with that exact capitalization for it to work.
I've never used it but there is a JWT implementation on NuGet.
Package: https://nuget.org/packages/JWT
Source: https://github.com/johnsheehan/jwt
.NET 4.0 compatible: https://www.nuget.org/packages/jose-jwt/
You can also go here: https://jwt.io/ and click "libraries".
You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.
Checkout the Datatables API documentation on this.
Example:
HTML
<input type="text" id="myInputTextField">
JS
oTable = $('#myTable').DataTable(); //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as @Lionel said
$('#myInputTextField').keyup(function(){
oTable.search($(this).val()).draw() ;
})
The bug has been fixed in the latest androidx version. And the famous workaround will cause crash now. so we need not it now.
In Python 3.8+ you can do
import hashlib
with open("your_filename.txt", "rb") as f:
file_hash = hashlib.md5()
while chunk := f.read(8192):
file_hash.update(chunk)
print(file_hash.digest())
print(file_hash.hexdigest()) # to get a printable str instead of bytes
Consider using hashlib.blake2b
instead of md5
(just replace md5
with blake2b
in the above snippet). It's cryptographically secure and faster than MD5.
h:button
- clicking on a h:button
issues a bookmarkable GET
request.
h:commandbutton
- Instead of a get request, h:commandbutton
issues a POST request which sends the form data back to the server.
There are a few pieces to doing this, assuming each list does not contain duplicates, Name is a unique identifier, and neither list is ordered.
First create an append extension method to get a single list:
static class Ext {
public static IEnumerable<T> Append(this IEnumerable<T> source,
IEnumerable<T> second) {
foreach (T t in source) { yield return t; }
foreach (T t in second) { yield return t; }
}
}
Thus can get a single list:
var oneList = list1.Append(list2);
Then group on name
var grouped = oneList.Group(p => p.Name);
Then can process each group with a helper to process one group at a time
public Person MergePersonGroup(IGrouping<string, Person> pGroup) {
var l = pGroup.ToList(); // Avoid multiple enumeration.
var first = l.First();
var result = new Person {
Name = first.Name,
Value = first.Value
};
if (l.Count() == 1) {
return result;
} else if (l.Count() == 2) {
result.Change = first.Value - l.Last().Value;
return result;
} else {
throw new ApplicationException("Too many " + result.Name);
}
}
Which can be applied to each element of grouped
:
var finalResult = grouped.Select(g => MergePersonGroup(g));
(Warning: untested.)
The underlying problem here is the 1st level cache of JPA. From the JPA spec Version 2.2 section 3.1. emphasise is mine:
An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance.
This is important because JPA tracks changes to that entity in order to flush them to the database. As a side effect it also means within a single persistence context an entity gets only loaded once. This why reloading the changed entity doesn't have any effect.
You have a couple of options how to handle this:
Evict the entity from the EntityManager
.
This may be done by calling EntityManager.detach
, annotating the updating method with @Modifying(clearAutomatically = true)
which evicts all entities.
Make sure changes to these entities get flushed first or you might end up loosing changes.
Use a different persistence context to load the entity.
The easiest way to do this is to do it in a separate transaction.
With Spring this can be done by having separate methods annotated with @Transactional
on beans called from a bean not annotated with @Transactional
.
Another way is to use a TransactionTemplate
which works especially nicely in tests where it makes transaction boundaries very visible.
export default is used to export a single class, function or primitive.
export default function() { } can be used when the function has no name. There can only be one default export in a file.
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
By code:
btn_edit.IsEnabled = true;
By XAML:
<Button Content="Edit data" Grid.Column="1" Name="btn_edit" Grid.Row="1" IsEnabled="False" />
Constants can't be changed, static variables have more to do with how they are allocated and where they are accessible.
Check out this site.
Here's a full featured TimeOfDay class.
This is overkill for simple cases, but if you need more advanced functionality like I did, this may help.
It can handle the corner cases, some basic math, comparisons, interaction with DateTime, parsing, etc.
Below is the source code for the TimeOfDay class. You can see usage examples and learn more here:
This class uses DateTime for most of its internal calculations and comparisons so that we can leverage all of the knowledge already embedded in DateTime.
// Author: Steve Lautenschlager, CambiaResearch.com
// License: MIT
using System;
using System.Text.RegularExpressions;
namespace Cambia
{
public class TimeOfDay
{
private const int MINUTES_PER_DAY = 60 * 24;
private const int SECONDS_PER_DAY = SECONDS_PER_HOUR * 24;
private const int SECONDS_PER_HOUR = 3600;
private static Regex _TodRegex = new Regex(@"\d?\d:\d\d:\d\d|\d?\d:\d\d");
public TimeOfDay()
{
Init(0, 0, 0);
}
public TimeOfDay(int hour, int minute, int second = 0)
{
Init(hour, minute, second);
}
public TimeOfDay(int hhmmss)
{
Init(hhmmss);
}
public TimeOfDay(DateTime dt)
{
Init(dt);
}
public TimeOfDay(TimeOfDay td)
{
Init(td.Hour, td.Minute, td.Second);
}
public int HHMMSS
{
get
{
return Hour * 10000 + Minute * 100 + Second;
}
}
public int Hour { get; private set; }
public int Minute { get; private set; }
public int Second { get; private set; }
public double TotalDays
{
get
{
return TotalSeconds / (24d * SECONDS_PER_HOUR);
}
}
public double TotalHours
{
get
{
return TotalSeconds / (1d * SECONDS_PER_HOUR);
}
}
public double TotalMinutes
{
get
{
return TotalSeconds / 60d;
}
}
public int TotalSeconds
{
get
{
return Hour * 3600 + Minute * 60 + Second;
}
}
public bool Equals(TimeOfDay other)
{
if (other == null) { return false; }
return TotalSeconds == other.TotalSeconds;
}
public override bool Equals(object obj)
{
if (obj == null) { return false; }
TimeOfDay td = obj as TimeOfDay;
if (td == null) { return false; }
else { return Equals(td); }
}
public override int GetHashCode()
{
return TotalSeconds;
}
public DateTime ToDateTime(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day, Hour, Minute, Second);
}
public override string ToString()
{
return ToString("HH:mm:ss");
}
public string ToString(string format)
{
DateTime now = DateTime.Now;
DateTime dt = new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
return dt.ToString(format);
}
public TimeSpan ToTimeSpan()
{
return new TimeSpan(Hour, Minute, Second);
}
public DateTime ToToday()
{
var now = DateTime.Now;
return new DateTime(now.Year, now.Month, now.Day, Hour, Minute, Second);
}
#region -- Static --
public static TimeOfDay Midnight { get { return new TimeOfDay(0, 0, 0); } }
public static TimeOfDay Noon { get { return new TimeOfDay(12, 0, 0); } }
public static TimeOfDay operator -(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 - ts;
return new TimeOfDay(dt2);
}
public static bool operator !=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds != t2.TotalSeconds;
}
}
public static bool operator !=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 != dt2;
}
public static bool operator !=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 != dt2;
}
public static TimeOfDay operator +(TimeOfDay t1, TimeOfDay t2)
{
DateTime now = DateTime.Now;
DateTime dt1 = new DateTime(now.Year, now.Month, now.Day, t1.Hour, t1.Minute, t1.Second);
TimeSpan ts = new TimeSpan(t2.Hour, t2.Minute, t2.Second);
DateTime dt2 = dt1 + ts;
return new TimeOfDay(dt2);
}
public static bool operator <(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds < t2.TotalSeconds;
}
}
public static bool operator <(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 < dt2;
}
public static bool operator <(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 < dt2;
}
public static bool operator <=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
if (t1 == t2) { return true; }
return t1.TotalSeconds <= t2.TotalSeconds;
}
}
public static bool operator <=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 <= dt2;
}
public static bool operator <=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 <= dt2;
}
public static bool operator ==(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else { return t1.Equals(t2); }
}
public static bool operator ==(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 == dt2;
}
public static bool operator ==(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 == dt2;
}
public static bool operator >(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds > t2.TotalSeconds;
}
}
public static bool operator >(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 > dt2;
}
public static bool operator >(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 > dt2;
}
public static bool operator >=(TimeOfDay t1, TimeOfDay t2)
{
if (ReferenceEquals(t1, t2)) { return true; }
else if (ReferenceEquals(t1, null)) { return true; }
else
{
return t1.TotalSeconds >= t2.TotalSeconds;
}
}
public static bool operator >=(TimeOfDay t1, DateTime dt2)
{
if (ReferenceEquals(t1, null)) { return false; }
DateTime dt1 = new DateTime(dt2.Year, dt2.Month, dt2.Day, t1.Hour, t1.Minute, t1.Second);
return dt1 >= dt2;
}
public static bool operator >=(DateTime dt1, TimeOfDay t2)
{
if (ReferenceEquals(t2, null)) { return false; }
DateTime dt2 = new DateTime(dt1.Year, dt1.Month, dt1.Day, t2.Hour, t2.Minute, t2.Second);
return dt1 >= dt2;
}
/// <summary>
/// Input examples:
/// 14:21:17 (2pm 21min 17sec)
/// 02:15 (2am 15min 0sec)
/// 2:15 (2am 15min 0sec)
/// 2/1/2017 14:21 (2pm 21min 0sec)
/// TimeOfDay=15:13:12 (3pm 13min 12sec)
/// </summary>
public static TimeOfDay Parse(string s)
{
// We will parse any section of the text that matches this
// pattern: dd:dd or dd:dd:dd where the first doublet can
// be one or two digits for the hour. But minute and second
// must be two digits.
Match m = _TodRegex.Match(s);
string text = m.Value;
string[] fields = text.Split(':');
if (fields.Length < 2) { throw new ArgumentException("No valid time of day pattern found in input text"); }
int hour = Convert.ToInt32(fields[0]);
int min = Convert.ToInt32(fields[1]);
int sec = fields.Length > 2 ? Convert.ToInt32(fields[2]) : 0;
return new TimeOfDay(hour, min, sec);
}
#endregion
private void Init(int hour, int minute, int second)
{
if (hour < 0 || hour > 23) { throw new ArgumentException("Invalid hour, must be from 0 to 23."); }
if (minute < 0 || minute > 59) { throw new ArgumentException("Invalid minute, must be from 0 to 59."); }
if (second < 0 || second > 59) { throw new ArgumentException("Invalid second, must be from 0 to 59."); }
Hour = hour;
Minute = minute;
Second = second;
}
private void Init(int hhmmss)
{
int hour = hhmmss / 10000;
int min = (hhmmss - hour * 10000) / 100;
int sec = (hhmmss - hour * 10000 - min * 100);
Init(hour, min, sec);
}
private void Init(DateTime dt)
{
Init(dt.Hour, dt.Minute, dt.Second);
}
}
}
After this our "Push to Git" worked fine.
Your mistake is using the datetime
module instead of the date
module. You meant to do this:
from datetime import date
date = models.DateField(_("Date"), default=date.today)
If you only want to capture the current date the proper way to handle this is to use the auto_now_add
parameter:
date = models.DateField(_("Date"), auto_now_add=True)
However, the modelfield docs clearly state that auto_now_add
and auto_now
will always use the current date and are not a default value that you can override.
The above solutions missed out on where to keep your backup (.bak) file. This should do the trick. It worked for me.
The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:
A data frame of four rows:
df = pd.DataFrame({'A': [1,2,3,4]})
Now trying to assign a list/array of two elements to it:
df['B'] = [3,4] # or df['B'] = np.array([3,4])
Both errors out:
ValueError: Length of values does not match length of index
Because the data frame has four rows but the list and array has only two elements.
Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:
df['B'] = pd.Series([3,4])
df
# A B
#0 1 3.0
#1 2 4.0
#2 3 NaN # NaN because the value at index 2 and 3 doesn't exist in the Series
#3 4 NaN
For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:
df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))
# A B
#0 1 1.0
#1 2 5.0
#2 7 9.0
#3 8 NaN
along the lines of bayer's answer:
''.join(i for i in s if i.isdigit())
Let's assume this is your class:
class Test
{
private $baz = 1;
public function foo() { ... }
public function bar()
{
printf("baz = %d\n", $this->baz);
}
public static function staticMethod() { echo "static method\n"; }
}
From within the foo()
method, let's look at the different options:
$this->staticMethod();
So that calls staticMethod()
as an instance method, right? It does not. This is because the method is declared as public static
the interpreter will call it as a static method, so it will work as expected. It could be argued that doing so makes it less obvious from the code that a static method call is taking place.
$this::staticMethod();
Since PHP 5.3 you can use $var::method()
to mean <class-of-$var>::
; this is quite convenient, though the above use-case is still quite unconventional. So that brings us to the most common way of calling a static method:
self::staticMethod();
Now, before you start thinking that the ::
is the static call operator, let me give you another example:
self::bar();
This will print baz = 1
, which means that $this->bar()
and self::bar()
do exactly the same thing; that's because ::
is just a scope resolution operator. It's there to make parent::
, self::
and static::
work and give you access to static variables; how a method is called depends on its signature and how the caller was called.
To see all of this in action, see this 3v4l.org output.
A simple solution is to use BindingList<T>
instead of ObservableCollection<T>
. Indeed the BindingList relay item change notifications. So with a binding list, if the item implements the interface INotifyPropertyChanged
then you can simply get notifications using the ListChanged event.
See also this SO answer.
Option 1: In SSMS go to View > Object Explorer Details
or press F7. Use the Search
box. Finally in the displayed list right click and select Synchronize
to find the object in the Object Explorer
tree.
Option 2: Install an Add-On like dbForge Search
. Right click on the displayed list and select Find in Object Explorer
.
you can do this :
declare @rowCount int
exec yourStoredProcedureName @outputparameterspOf = @rowCount output
It depends what is the character and what encoding it is in:
An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.
An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).
A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).
A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.
A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).
An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.
The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.
That would mean that there are between 0.03125 and 0.125 characters in a bit.
.spec.ts
file is used for unit testing
of your application.
If you don't to get it generated just use --spec=false
while creating new Component
. Like this
ng generate component --spec=false mycomponentName
tools:context=".MainActivity"
thisline is used in xml file which indicate that which java source file is used to access this xml file.
it means show this xml preview for perticular java files.
You could try:
.modal.modal-wide .modal-dialog {
width: 90%;
}
.modal-wide .modal-body {
overflow-y: auto;
}
Just add .modal-wide to your classes
In the endpoint tag you need to include the property address=""
<endpoint address="" binding="webHttpBinding" bindingConfiguration="SecureBasicRest" behaviorConfiguration="svcEndpoint" name="webHttp" contract="SvcContract.Authenticate" />