I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0)
instead.
From http://www.codeave.com/javascript/code.asp?u_log=7004:
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
This is not a new question. I addresed it in comments in one SO post, and posted my alternative implementations in another post. The comments in the first post actually elucidate the performance differences between the different implementations.
Basically, which works fastest depends on what database object you use with it.
Handling CORS requests properly is a tad more involved. Here is a function that will respond more fully (and properly).
/**
* An example CORS-compliant method. It will allow any GET, POST, or OPTIONS requests from any
* origin.
*
* In a production environment, you probably want to be more restrictive, but this gives you
* the general idea of what is involved. For the nitty-gritty low-down, read:
*
* - https://developer.mozilla.org/en/HTTP_access_control
* - https://fetch.spec.whatwg.org/#http-cors-protocol
*
*/
function cors() {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
}
When a browser wants to execute a cross-site request it first confirms that this is okay with a "pre-flight" request to the URL. By allowing CORS you are telling the browser that responses from this URL can be shared with other domains.
CORS does not protect your server. CORS attempts to protect your users by telling browsers what the restrictions should be on sharing responses with other domains. Normally this kind of sharing is utterly forbidden, so CORS is a way to poke a hole in the browser's normal security policy. These holes should be as small as possible, so always check the HTTP_ORIGIN against some kind of internal list.
There are some dangers here, especially if the data the URL serves up is normally protected. You are effectively allowing browser content that originated on some other server to read (and possibly manipulate) data on your server.
If you are going to use CORS, please read the protocol carefully (it is quite small) and try to understand what you're doing. A reference URL is given in the code sample for that purpose.
It has been observed that the HTTP_ORIGIN header is insecure, and that is true. In fact, all HTTP headers are insecure to varying meanings of the term. Unless a header includes a verifiable signature/hmac, or the whole conversation is authenticated via TLS, headers are just "something the browser has told me".
In this case, the browser is saying "an object from domain X wants to get a response from this URL. Is that okay?" The point of CORS is to be able to answer, "yes I'll allow that".
edit to my previous answer: if you want to count a function's invocations, you might want to try:
var countMe = ( function() {
var c = 0;
return function() {
c++;
return c;
}
})();
alert(countMe()); // Alerts "1"
alert(countMe()); // Alerts "2"
Here, c serves as the counter, and you do not have to use arguments.callee.
Make sure that you have made the content-type
as application/json
in header request and Post from body under the raw tab.
{
"address": "colombo",
"username": "hesh",
"password": "123",
"registetedDate": "2015-4-3",
"firstname": "hesh",
"contactNo": "07762",
"accountNo": "16161",
"lastName": "jay",
"arrayObjectName" : [{
"Id" : 1,
"Name": "ABC" },
{
"Id" : 2,
"Name" : "XYZ"
}],
"intArrayName" : [111,222,333],
"stringArrayName" : ["a","b","c"]
}
Well, I still find some room to answer.
In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:
Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.
I used FPDF v. 1.53 and didn't want to upgrade because of possible side effects. I used the following code according to Yacoby:
Line 1164:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
$mqr=get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
}
Line 1203:
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
set_magic_quotes_runtime($mqr);
}
JavaScript to validate the phone number:
function phonenumber(inputtxt) {_x000D_
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
if(inputtxt.value.match(phoneno)) {_x000D_
return true;_x000D_
}_x000D_
else {_x000D_
alert("message");_x000D_
return false;_x000D_
}_x000D_
}
_x000D_
The above script matches:
XXX-XXX-XXXX
XXX.XXX.XXXX
XXX XXX XXXX
If you want to use a + sign before the number in the following way
+XX-XXXX-XXXX
+XX.XXXX.XXXX
+XX XXXX XXXX
use the following code:
function phonenumber(inputtxt) {
var phoneno = /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
if(inputtxt.value.match(phoneno)) {
return true;
}
else {
alert("message");
return false;
}
}
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
System.out.println(list);
list.removeAll(Arrays.asList("", null));
System.out.println(list);
Output:
[, Hi, null, How]
[Hi, How]
Test this:
DECLARE @result NVARCHAR(MAX)
SELECT @result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
Since Expression Language 3.0, it is valid to use += operator for string concatenation.
${(empty value)? "none" : value += " enabled"} // valid as of EL 3.0
Quoting EL 3.0 Specification.
String Concatenation Operator
To evaluate
A += B
- Coerce A and B to String.
- Return the concatenated string of A and B.
To summarize and complement the existing answers, as of Windows PowerShell v5.1 / PowerShell Core 7.0.0-preview.4:
David Mohundro's answer rightfully points that instead of [bool]
parameters you should use [switch]
parameters in PowerShell, where the presence vs. absence of the switch name (-Unify
specified vs. not specified) implies its value, which makes the original problem go away.
However, on occasion you may still need to pass the switch value explicitly, particularly if you're constructing a command line programmatically:
In PowerShell Core, the original problem (described in Emperor XLII's answer) has been fixed.
That is, to pass $true
explicitly to a [switch]
parameter named -Unify
you can now write:
pwsh -File .\RunScript.ps1 -Unify:$true # !! ":" separates name and value, no space
The following values can be used: $false
, false
, $true
, true
, but note that passing 0
or 1
does not work.
Note how the switch name is separated from the value with :
and there must be no whitespace between the two.
Note: If you declare a [bool]
parameter instead of a [switch]
(which you generally shouldn't), you must use the same syntax; even though -Unify $false
should work, it currently doesn't - see this GitHub issue.
In Windows PowerShell, the original problem persists, and - given that Windows PowerShell is no longer actively developed - is unlikely to get fixed.
The workaround suggested in LarsWA's answer - even though it is based on the official help topic as of this writing - does not work in v5.1
Using -Command
instead of -File
is the only effective workaround:
:: # From cmd.exe
powershell -Command "& .\RunScript.ps1 -Unify:$true"
With -Command
you're effectively passing a piece of PowerShell code, which is then evaluated as usual - and inside PowerShell passing $true
and $false
works (but not true
and false
, as now also accepted with -File
).
Caveats:
Using -Command
can result in additional interpretation of your arguments, such as if they contain $
chars. (with -File
, arguments are literals).
Using -Command
can result in a different exit code.
For details, see this answer and this answer.
I am not getting your question properly but as per your heading, you can convert any type of object to string by using toString()
function on a String
Object.
Euler Path - An Euler path is a path in which each edge is traversed exactly once.
Hamiltonian Path - An Hamiltonian path is path in which each vertex is traversed exactly once.
If you have ever confusion remember E - Euler E - Edge.
This is a bit old thread, but if someone experimenting, learning, or testing basic flask app, started from a script that runs in the background, the quickest way to stop it is to kill the process running on the port you are running your app on. Note: I am aware the author is looking for a way not to kill or stop the app. But this may help someone who is learning.
sudo netstat -tulnp | grep :5001
You'll get something like this.
tcp 0 0 0.0.0.0:5001 0.0.0.0:* LISTEN 28834/python
To stop the app, kill the process
sudo kill 28834
Based on Tomasz Nurkiewiczs answer, the "problem" is that typescript is typesafe. :) So the document.getElementById()
returns the type HTMLElement
which does not contain a value
property. The subtype HTMLInputElement
does however contain the value
property.
So a solution is to cast the result of getElementById()
to HTMLInputElement
like this:
var inputValue = (<HTMLInputElement>document.getElementById(elementId)).value;
<>
is the casting operator in typescript. See the question TypeScript: casting HTMLElement.
The resulting javascript from the line above looks like this:
inputValue = (document.getElementById(elementId)).value;
i.e. containing no type information.
There are 3 ways to allow cross domain origin (excluding jsonp
):
1) Set the header in the page directly using a templating language like PHP. Keep in mind there can be no HTML before your header or it will fail.
<?php header("Access-Control-Allow-Origin: http://example.com"); ?>
2) Modify the server configuration file (apache.conf
) and add this line. Note that "*"
represents allow all. Some systems might also need the credential set. In general allow all access is a security risk and should be avoided:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Credentials true
3) To allow multiple domains on Apache web servers add the following to your config file
<IfModule mod_headers.c>
SetEnvIf Origin "http(s)?://(www\.)?(example.org|example.com)$" AccessControlAllowOrigin=$0$1
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
Header set Access-Control-Allow-Credentials true
</IfModule>
4) For development use only hack your browser and allow unlimited CORS using the Chrome Allow-Control-Allow-Origin extension
5) Disable CORS in Chrome: Quit Chrome completely. Open a terminal and execute the following. Just be cautious you are disabling web security:
open -a Google\ Chrome --args --disable-web-security --user-data-dir
All you need is to Stop the ASP.NET Development Server and run the project again
In order to get local time in pure Javascript use this built in function
// return new Date().toLocaleTimeString();
See below example
function getLocaltime(){
return new Date().toLocaleTimeString();
}
console.log(getLocaltime());
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/[email protected]/dist/react.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script>
<script src="https://unpkg.com/[email protected]/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.Component{
constructor(props){
super(props);
this.state = {
counter : 0,
isToggle: false
}
this.onEventHandler = this.onEventHandler.bind(this);
}
increment = ()=>{
this.setState({counter:this.state.counter + 1});
}
decrement= ()=>{
if(this.state.counter > 0 ){
this.setState({counter:this.state.counter - 1});
}else{
this.setState({counter:0});
}
}
// Either do it as onEventHandler = () => {} with binding with this // object.
onEventHandler(){
this.setState({isToggle:!this.state.isToggle})
alert('Hello');
}
render(){
return(
<div>
<button onClick={this.increment}> Increment </button>
<button onClick={this.decrement}> Decrement </button>
{this.state.counter}
<button onClick={this.onEventHandler}> {this.state.isToggle ? 'Hi':'Ajay'} </button>
</div>
)
}
}
ReactDOM.render(
<App/>,
document.getElementById('root'),
);
</script>
</body>
</html>
Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.
<p>
tags have built in padding and margin. You could create a CSS selector combined with some javascript for instances when your <p>
is empty. Probably overkill, but it should do what you need it to do.
CSS example: .NoPaddingOrMargin {padding: 0px; margin:0px}
To find a hostname in your local network by IP address you can use:
nmblookup -A <ip>
To find a hostname on the internet you could use the host
program:
host <ip>
Or you can install nbtscan
by running:
sudo apt-get install nbtscan
And use:
nbtscan <ip>
Update 2018-05-13
You can query a name server with nslookup
. It works both ways!
nslookup <IP>
nslookup <hostname>
To call any method of an object instantiated from a class (with statement new), you need to "point" to it. From the outside you just use the resource created by the new statement.
Inside any object PHP created by new, saves the same resource into the $this variable.
So, inside a class you MUST point to the method by $this.
In your class, to call smallTest
from inside the class, you must tell PHP which of all the objects created by the new statement you want to execute, just write:
$this->smallTest();
// On the state
constructor() {
this.state = {
email: ''
}
}
// Input view ( always check if property is available in state {this.state.email ? this.state.email : ''}
<Input
value={this.state.email ? this.state.email : ''}
onChange={event => this.setState({ email: event.target.value)}
type="text"
name="emailAddress"
placeholder="[email protected]" />
There is a new index method called difference
. It returns the original columns, with the columns passed as argument removed.
Here, the result is used to remove columns B
and D
from df
:
df2 = df[df.columns.difference(['B', 'D'])]
Note that it's a set-based method, so duplicate column names will cause issues, and the column order may be changed.
Advantage over drop
: you don't create a copy of the entire dataframe when you only need the list of columns. For instance, in order to drop duplicates on a subset of columns:
# may create a copy of the dataframe
subset = df.drop(['B', 'D'], axis=1).columns
# does not create a copy the dataframe
subset = df.columns.difference(['B', 'D'])
df = df.drop_duplicates(subset=subset)
That happened to me too, because I was trying to get an IEnumerable
but the response had a single value. Please try to make sure it's a list of data in your response. The lines I used (for api url get) to solve the problem are like these:
HttpResponseMessage response = await client.GetAsync("api/yourUrl");
if (response.IsSuccessStatusCode)
{
IEnumerable<RootObject> rootObjects =
awaitresponse.Content.ReadAsAsync<IEnumerable<RootObject>>();
foreach (var rootObject in rootObjects)
{
Console.WriteLine(
"{0}\t${1}\t{2}",
rootObject.Data1, rootObject.Data2, rootObject.Data3);
}
Console.ReadLine();
}
Hope It helps.
Use the options
command, e.g. options(max.print=1000000)
.
See ?options
:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
If you are using MySql 5.7 or later, according to these links (MySql Official, SO QA), we can select one record per group by
with out the need of any aggregate functions.
So the query can be simplified to this.
select * from comments_table group by commentname;
Try out the query in action here
Below query will provide exactly the same result as given in the desired response:
db.books.aggregate([
{
$group: {
_id: { addresses: "$addr", books: "$book" },
num: { $sum :1 }
}
},
{
$group: {
_id: "$_id.addresses",
bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
}
},
{
$project: {
_id: 1,
bookCounts:1,
"totalBookAtAddress": {
"$sum": "$bookCounts.count"
}
}
}
])
The response will be looking like below:
/* 1 */
{
"_id" : "address4",
"bookCounts" : [
{
"bookName" : "book3",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 2 */
{
"_id" : "address90",
"bookCounts" : [
{
"bookName" : "book33",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 3 */
{
"_id" : "address15",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 4 */
{
"_id" : "address3",
"bookCounts" : [
{
"bookName" : "book9",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 5 */
{
"_id" : "address5",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 6 */
{
"_id" : "address1",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 3
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 4
},
/* 7 */
{
"_id" : "address2",
"bookCounts" : [
{
"bookName" : "book1",
"count" : 2
},
{
"bookName" : "book5",
"count" : 1
}
],
"totalBookAtAddress" : 3
},
/* 8 */
{
"_id" : "address77",
"bookCounts" : [
{
"bookName" : "book11",
"count" : 1
}
],
"totalBookAtAddress" : 1
},
/* 9 */
{
"_id" : "address9",
"bookCounts" : [
{
"bookName" : "book99",
"count" : 1
}
],
"totalBookAtAddress" : 1
}
Here are some more console logging "pro tips":
console.table
var animals = [
{ animal: 'Horse', name: 'Henry', age: 43 },
{ animal: 'Dog', name: 'Fred', age: 13 },
{ animal: 'Cat', name: 'Frodo', age: 18 }
];
console.table(animals);
console.trace
Shows you the call stack for leading up to the console.
You can even customise your consoles to make them stand out
console.todo = function(msg) {
console.log(‘ % c % s % s % s‘, ‘color: yellow; background - color: black;’, ‘–‘, msg, ‘–‘);
}
console.important = function(msg) {
console.log(‘ % c % s % s % s’, ‘color: brown; font - weight: bold; text - decoration: underline;’, ‘–‘, msg, ‘–‘);
}
console.todo(“This is something that’ s need to be fixed”);
console.important(‘This is an important message’);
If you really want to level up don't limit your self to the console statement.
Here is a great post on how you can integrate a chrome debugger right into your code editor!
https://hackernoon.com/debugging-react-like-a-champ-with-vscode-66281760037
In array you also can use variables passing to req.params:
app.get(["/:foo", "/:foo/:bar"], /* function */);
The following code is using jQuery to generate a custom rightclick
event based on the default mousedown
and mouseup
events.
It considers the following points:
contextmenu
event is not triggered there)on('contextmenu', ...)
does$(function ()_x000D_
{ // global rightclick handler - trigger custom event "rightclick"_x000D_
var mouseDownElements = [];_x000D_
$(document).on('mousedown', '*', function(event)_x000D_
{_x000D_
if (event.which == 3)_x000D_
{_x000D_
mouseDownElements.push(this);_x000D_
}_x000D_
});_x000D_
$(document).on('mouseup', '*', function(event)_x000D_
{_x000D_
if (event.which == 3 && mouseDownElements.indexOf(this) >= 0)_x000D_
{_x000D_
$(this).trigger('rightclick');_x000D_
}_x000D_
});_x000D_
$(document).on('mouseup', function()_x000D_
{_x000D_
mouseDownElements.length = 0;_x000D_
});_x000D_
// disable contextmenu_x000D_
$(document).on('contextmenu', function(event)_x000D_
{_x000D_
event.preventDefault();_x000D_
});_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
// Usage:_x000D_
$('#testButton').on('rightclick', function(event)_x000D_
{_x000D_
alert('this was a rightclick');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="testButton">Rightclick me</button>
_x000D_
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
The maximum row size for a given table is determined by several factors:
The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.
The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size, which is defined by the innodb_page_size configuration option. “Limits on InnoDB Tables”.
SQL server determines case sensitivity by COLLATION
.
COLLATION
can be set at various levels.
One can check the COLLATION
at each level as mentioned in Raj More's answer.
Check Server Collation
SELECT SERVERPROPERTY('COLLATION')
Check Database Collation
SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;
Check Column Collation
select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name
Check Expression Collation
For expression level COLLATION
you need to look at the expression. :)
It would be generally at the end of the expression as in below example.
SELECT name FROM customer ORDER BY name COLLATE Latin1_General_CS_AI;
Collation Description
For getting description of each COLLATION
value try this.
SELECT * FROM fn_helpcollations()
And you should see something like this.
You can always put a WHERE
clause to filter and see description only for your COLLATION
.
You can find a list of collations here.
To get the value you would do this:
document.getElementById("genderf").value;
But to check, whether the radio button is checked or selected:
document.getElementById("genderf").checked;
To get the width in a cross browser/device way use:
function getActualWidth() {
var actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;
return actualWidth;
}
please try to make it as a character
string str = "Tigger";
//then str[0] will return 'T' not "T"
This snippet works in IE7 at least
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test</title>
<style>
#foo {
position: fixed;
bottom: 0;
right: 0;
}
</style>
</head>
<body>
<div id="foo">Hello World</div>
</body>
</html>
The -fpermissive
flag causes the compiler to report some things that are actually errors (but are permitted by some compilers) as warnings, to permit code to compile even if it doesn't conform to the language rules. You really should fix the underlying problem. Post the smallest, compilable code sample that demonstrates the problem.
-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using-fpermissive
will allow some nonconforming code to compile.
For everyone asking for code in C#, below is a simplified version of my implementation.
public static void TakeScreenshot(IWebDriver driver, IWebElement element)
{
try
{
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
System.Drawing.Rectangle croppedImage = new System.Drawing.Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);
screenshot = screenshot.Clone(croppedImage, screenshot.PixelFormat);
screenshot.Save(String.Format(@"C:\SeleniumScreenshots\" + fileName, System.Drawing.Imaging.ImageFormat.Jpeg));
}
catch (Exception e)
{
logger.Error(e.StackTrace + ' ' + e.Message);
}
}
document.location is deprecated in favor of window.location, which can be accessed by just location, since it's a global object.
The location object has multiple properties and methods. If you try to use it as a string then it acts like location.href.
I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth
TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.
To get an idea of what I mean, watch Microsoft's introductory video on the language.
For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.
It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.
There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)
As an example, here's some TypeScript (you can play with this in the TypeScript Playground)
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
And here's the JavaScript it would produce
var Greeter = (function () {
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
})();
Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.
It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet()
method returns a string.
Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio
I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.
Another way of doing this, assuming we have weights at the same index as the elements in the element array.
import numpy as np
weights = [0.1, 0.3, 0.5] #weights for the item at index 0,1,2
# sum of weights should be <=1, you can also divide each weight by sum of all weights to standardise it to <=1 constraint.
trials = 1 #number of trials
num_item = 1 #number of items that can be picked in each trial
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# gives number of times an item was selected at a particular index
# this assumes selection with replacement
# one possible output
# selected_item_arr
# array([[0, 0, 1]])
# say if trials = 5, the the possible output could be
# selected_item_arr
# array([[1, 0, 0],
# [0, 0, 1],
# [0, 0, 1],
# [0, 1, 0],
# [0, 0, 1]])
Now let's assume, we have to sample out 3 items in 1 trial. You can assume that there are three balls R,G,B present in large quantity in ratio of their weights given by weight array, the following could be possible outcome:
num_item = 3
trials = 1
selected_item_arr = np.random.multinomial(num_item, weights, trials)
# selected_item_arr can give output like :
# array([[1, 0, 2]])
you can also think number of items to be selected as number of binomial/ multinomial trials within a set. So, the above example can be still work as
num_binomial_trial = 5
weights = [0.1,0.9] #say an unfair coin weights for H/T
num_experiment_set = 1
selected_item_arr = np.random.multinomial(num_binomial_trial, weights, num_experiment_set)
# possible output
# selected_item_arr
# array([[1, 4]])
# i.e H came 1 time and T came 4 times in 5 binomial trials. And one set contains 5 binomial trails.
If you by writing "non letters and numbers" exclude more than [A-Za-z0-9]
(ie. considering letters like åäö
to be letters to) and want to be able to accurately handle UTF-8 strings \p{L}
and \p{N}
will be of aid.
\p{N}
will match any "Number"\p{L}
will match any "Letter Character", which includes
Documentation PHP: Unicode Character Properties
$data = "Thäre!wouldn't%bé#äny";
$new_data = str_replace ("'", "", $data);
$new_data = preg_replace ('/[^\p{L}\p{N}]/u', '_', $new_data);
var_dump (
$new_data
);
output
string(23) "Thäre_wouldnt_bé_äny"
+ theme(plot.title = element_text(size=22))
Here is the full set of things you can change in element_text
:
element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
color = NULL)
When u call finish onDestroy() of that activity will be called and it will go back to previous activity in the activity stack... So.. for exit do not call finish();
Try adding wmode, it seems to have two parameters.
&wmode=Opaque
&wmode=transparent
I can't find a technical reason why it works, or much more explanation but take at look at this query.
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/lzQgAR_J1PI?wmode=transparent" frameborder="0" wmode="Opaque">
or this
//Fix z-index youtube video embedding
$(document).ready(function (){
$('iframe').each(function(){
var url = $(this).attr("src");
$(this).attr("src",url+"?wmode=transparent");
});
});
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
You can also do this in a .htaccess file assuming they are enabled on the website.
SetEnv KOHANA_ENV production
Would be all you need to add to a .htaccess to add the environment variable
To differentiate between scroll up/down in jQuery, you could use:
var mousewheelevt = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel" //FF doesn't recognize mousewheel as of FF3.x
$('#yourDiv').bind(mousewheelevt, function(e){
var evt = window.event || e //equalize event object
evt = evt.originalEvent ? evt.originalEvent : evt; //convert to originalEvent if possible
var delta = evt.detail ? evt.detail*(-40) : evt.wheelDelta //check for detail first, because it is used by Opera and FF
if(delta > 0) {
//scroll up
}
else{
//scroll down
}
});
This method also works in divs that have overflow:hidden
.
I successfully tested it in FireFox, IE and Chrome.
An updated version of Rails/ActiveRecord may support this syntax natively. It would look similar to:
Foo.where(foo: 'bar').or.where(bar: 'bar')
As noted in this pull request https://github.com/rails/rails/pull/9052
For now, simply sticking with the following works great:
Foo.where('foo= ? OR bar= ?', 'bar', 'bar')
My server was throwing this exception in the pass 2 days and I solved it by moving the disconnecting function with:
outputStream.close();
inputStream.close();
Client.close();
To the end of the listing thread. if it will helped anyone.
Why not read the file in text mode, rather than binary mode?
To exclude everything in a directory, but some sub-directories, do the following:
wp-content/*
!wp-content/plugins/
!wp-content/themes/
Source: https://gist.github.com/444295
pyplot
is a sub-module of matplotlib
which doesn't get imported with a simple import matplotlib
.
>>> import matplotlib
>>> print matplotlib.pyplot
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>
It seems customary to do: import matplotlib.pyplot as plt
at which time you can use the various functions and classes it contains:
p = plt.plot(...)
if (empty($var) && $pieces[$var] != '0') {
//do something
}
In my case this code worked.
The problem arose because you added the following code as request header in your front-end :
headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');
Those headers belong to response, not request. So remove them, including the line :
headers.append('GET', 'POST', 'OPTIONS');
Your request had 'Content-Type: application/json'
, hence triggered what is called CORS preflight. This caused the browser sent the request with OPTIONS method. See CORS preflight for detailed information.
Therefore in your back-end, you have to handle this preflighted request by returning the response headers which include :
Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept
Of course, the actual syntax depends on the programming language you use for your back-end.
In your front-end, it should be like so :
function performSignIn() {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('Authorization', 'Basic ' + base64.encode(username + ":" + password));
headers.append('Origin','http://localhost:3000');
fetch(sign_in, {
mode: 'cors',
credentials: 'include',
method: 'POST',
headers: headers
})
.then(response => response.json())
.then(json => console.log(json))
.catch(error => console.log('Authorization failed : ' + error.message));
}
You can use also util methods mentioned in this blog: Getting cell witdth and height from excel with Apache POI. It can solve your problem.
Copy & paste from that blog:
static public class PixelUtil {
public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256;
public static final short EXCEL_ROW_HEIGHT_FACTOR = 20;
public static final int UNIT_OFFSET_LENGTH = 7;
public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 };
public static short pixel2WidthUnits(int pxs) {
short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH));
widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)];
return widthUnits;
}
public static int widthUnits2Pixel(short widthUnits) {
int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH;
int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
public static int heightUnits2Pixel(short heightUnits) {
int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR);
int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR;
pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH));
return pixels;
}
}
So when you want to get cell width and height you can use this to get value in pixel, values are approximately.
PixelUtil.heightUnits2Pixel((short) row.getHeight())
PixelUtil.widthUnits2Pixel((short) sh.getColumnWidth(columnIndex));
If both of your servers are using WHM, I think we can reduce the time to nil. Create your domain in the new server and set everything ready. Go to the previous server and delete the account corresponding to that domain. Until now I have got no errors by doing this and felt the update instantaneous. FYI I used hostgator hosting (both dedicated servers). And I really dont know why it is so. It's supposed to be not like that until the TTL is over.
111 means connection refused, which in turn means that your mysqld only listens to the localhost
interface.
To alter it you may want to look at the bind-address
value in the mysqld
section of your my.cnf
file.
following code works just fine for me.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movieurl));
startActivity(intent);
IMO, in your case you can try this:
- Map the shared folder to a drive or folder on your machine. (here's how)
- Access the mapped drive/folder as you normally would local files.
Nothing needs to be installed. No services need to be running except those that enable folder sharing.
If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.
This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.
Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.
If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:
PsExec \\yourServerName -u yourUserName cmd.exe
Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.
I am not sure but I think you need either the Server (lanmanserver
) or the Terminal Services (TermService
) service to be running (which should have already be running).
If you changed the location, using option 'Use custom location (does not modify Tomcat installation)' and the deployed directory is "wtpwebapps" then you'll have to:
<role rolename="manager-gui"/> <role rolename="manager-status"/> <role rolename="manager-jmx"/> <role rolename="manager-script"/> <role rolename="admin-gui"/> <role rolename="admin"/> <user username="admin" password="yourpassword" roles="admin, admin-gui, manager-gui"/>
readonly="true"into the <Resource/> key of the <GlobalNamingResources/> group.
NOTE: if you change the server configuration, say if you like to compare the default configuration (use tomcat installation directory) and the 'new directory', when switching back to the 'new directory' this 'tomcat-users.xml' will be overwritten by the default file, so SAVE THE CONTENT OF THIS FILE somewhere before doing that, then copy it back. If you only give the the username "admin" role, you will be prompted of help messages. It says: you should not grant the admin-gui, or manager-gui role the 'manager-jmx' and 'manager-script' roles.
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.
The syntax is the following:
function clickOnUpload() {
$timeout(function() {
angular.element('#myselector').triggerHandler('click');
});
};
// Using Angular Extend
angular.extend($scope, {
clickOnUpload: clickOnUpload
});
// OR Using scope directly
$scope.clickOnUpload = clickOnUpload;
More info on Angular Extend way here.
If you are using old versions of angular, you should use trigger instead of triggerHandler.
If you need to apply stop propagation you can use this method as follows:
<a id="myselector" ng-click="clickOnUpload(); $event.stopPropagation();">
Something
</a>
If the table has date field, this(User::orderBy('created_at', 'desc')->first();
) is the best solution, I think.
But there is no date field, Model ::orderBy('id', 'desc')->first()->id;
is the best solution, I am sure.
I want change default directory dumpfile.
You could create a new directory and give it required privileges, for example:
SQL> CREATE DIRECTORY dmpdir AS '/opt/oracle';
Directory created.
SQL> GRANT read, write ON DIRECTORY dmpdir TO scott;
Grant succeeded.
To use the newly created directory, you could just add it as a parameter:
DIRECTORY=dmpdir
Oracle introduced a default directory from 10g R2, called DATA_PUMP_DIR, that can be used. To check the location, you could look into dba_directories:
SQL> select DIRECTORY_NAME, DIRECTORY_PATH from dba_directories where DIRECTORY_NAME = 'DATA_PUMP_DIR';
DIRECTORY_NAME DIRECTORY_PATH
-------------------- --------------------------------------------------
DATA_PUMP_DIR C:\app\Lalit/admin/orcl/dpdump/
SQL>
As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2
and mod-perl
via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.
Yes you can do the following.
[[float(y) for y in x] for x in l]
Thanks for your answers. I missed that my data is stored in a List<String>
which is passed to the tested method. The mistake was that I put the string into the first element of the ArrayList. That's why I thought the String consists of just one single line, because the debugger showed me only one entry.
If you want to remove all new line characters and replace them with some character (say comma) then you can use the following.
(Get-Content test.txt) -join ","
This works because Get-Content returns array of lines. You can see it as tokenize function available in many languages.
Just press Alt+Shift+Q,c for quick access.(In windows)
Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.
Restart kernel and clear output (if not starting with new notebook), then run
%matplotlib tk
For more info go to Plotting with matplotlib
I am using Memurai which is Redis-compatible cache and datastore for Windows. It is also recommended by Microsoft open tech as it written on their former project here.
This project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way.
I find the answer from @Austin Phillips is spot on. One small improvement I'd do is to add -o (to ignore the pid of the script itself) and match for the script with basename (ie same code can be put into any script):
if pidof -x "`basename $0`" -o $$ >/dev/null; then
echo "Process already running"
fi
In case the elements you want to join is not an array just a space separated string, you can do something like this:
foo="aa bb cc dd"
bar=`for i in $foo; do printf ",'%s'" $i; done`
bar=${bar:1}
echo $bar
'aa','bb','cc','dd'
for example, my use case is that some strings are passed in my shell script and I need to use this to run on a SQL query:
./my_script "aa bb cc dd"
In my_script, I need to do "SELECT * FROM table WHERE name IN ('aa','bb','cc','dd'). Then above command will be useful.
Note 1: The height of any sub-tree is computed only once.
Note 2: If the left sub-tree is unbalanced then the computation of the right sub-tree, potentially containing million elements, is skipped.
// return height of tree rooted at "tn" if, and only if, it is a balanced subtree
// else return -1
int maxHeight( TreeNode const * tn ) {
if( tn ) {
int const lh = maxHeight( tn->left );
if( lh == -1 ) return -1;
int const rh = maxHeight( tn->right );
if( rh == -1 ) return -1;
if( abs( lh - rh ) > 1 ) return -1;
return 1 + max( lh, rh );
}
return 0;
}
bool isBalanced( TreeNode const * root ) {
// Unless the maxHeight is -1, the subtree under "root" is balanced
return maxHeight( root ) != -1;
}
1. Change a folder's name from oldfolder to newfolder
git mv oldfolder newfolder
2. If newfolder is already in your repository & you'd like to override it and use:- force
git mv -f oldfolder newfolder
Don't forget to add the changes to index & commit them after renaming with git mv.
3. Renaming foldername to folderName on case insensitive file systems
Simple renaming with a normal mv command(not git mv) won’t get recognized as a filechange from git. If you try it with the ‘git mv’ command like in the following line
git mv foldername folderName
If you’re using a case insensitive filesystem, e.g. you’re on a Mac and you didn’t configure it to be case sensitive, you’ll experience an error message like this one:
fatal: renaming ‘foldername’ failed: Invalid argument
And here is what you can do in order to make it work:-
git mv foldername tempname && git mv tempname folderName
This splits up the renaming process by renaming the folder at first to a completely different foldername. After renaming it to the different foldername the folder can finally be renamed to the new folderName. After those ‘git mv’s, again, do not forget to add and commit the changes. Though this is probably not a beautiful technique, it works perfectly fine. The filesystem will still not recognize a change of the letter cases, but git does due to renaming it to a new foldername, and that’s all we wanted :)
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
Installation the native library on Ubuntu server with:
sudo apt-get install libtcnative-1
If that does not work tomcat-native needs to be installed
Install Oracle java7:
Install tomcat apr:
Install tomcat tomcat-native:
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
ssh user@machine python < script.py - arg1 arg2
Because cat |
is usually not necessary
If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website. e.g.
import webbrowser
webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)
In the docker containers(centos based images) it is located at
/etc/mysql/my.cnf
In modes 'a'
or 'a+'
, any writing is done at the end of the file, even if at the current moment when the write()
function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.
1st way, can be used if there are no issues to load the file into memory:
def line_prepender(filename, line):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
2nd way:
def line_pre_adder(filename, line_to_prepend):
f = fileinput.input(filename, inplace=1)
for xline in f:
if f.isfirstline():
print line_to_prepend.rstrip('\r\n') + '\n' + xline,
else:
print xline,
I don't know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don't know the mechanism
It basically means that the object implements the __getitem__()
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.
Try:
git remote prune origin
From the Git remote documentation:
prune
Deletes all stale remote-tracking branches under <name>. These stale branches have already been removed from the remote repository referenced by <name>, but are still locally available in "remotes/<name>".
With --dry-run option, report what branches will be pruned, but do not actually prune them.
Java doesn't use includes the way C does. Instead java uses a concept called the classpath, a list of resources containing java classes. The JVM can access any class on the classpath by name so if you can extend classes and refer to types simply by declaring them. The closes thing to an include statement java has is 'import'. Since classes are broken up into namespaces like foo.bar.Baz, if you're in the qux package and you want to use the Baz class without having to use its full name of foo.bar.Baz, then you need to use an import statement at the beginning of your java file like so:
import foo.bar.Baz
The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!
If you want to hide them anyway: error_reporting(0);
When you do -
for word in string:
You are not iterating through the words in the string, you are iterating through the characters in the string. To iterate through the words, you would first need to split the string into words , using str.split()
, and then iterate through that . Example -
my_string = "this is a string"
for word in my_string.split():
print (word)
Please note, str.split()
, without passing any arguments splits by all whitespaces (space, multiple spaces, tab, newlines, etc).
To update just one gem (and it's dependencies), do:
bundle update gem-name
But to update just the gem alone (without updating it's dependencies), do
bundle update --source gem-name
Create a new template and check DBname. Use that template for your tracefile.
There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.
I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:
@media only screen and (min-width: 1024px) and (max-height: 1366px)
and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
/* ... */
}
I'd like to add complementary information: In postman app you may use the "request" object to see your subsituted input data. (refer to https://www.getpostman.com/docs/postman/scripts/postman_sandbox in paragraph "Request/response related properties", ie.
console.log("header : " + request.headers["Content-Type"]);
console.log("body : " + request.data);
console.log("url : " + request.url);
I didn't test for header substitution but it works for url and body.
Alex
First off, you should use dataUsingEncoding:
instead of going through UTF8String
. You only use UTF8String
when you need a C
string in that encoding.
Then, for UTF-16
, just pass NSUnicodeStringEncoding
instead of NSUTF8StringEncoding
in your dataUsingEncoding:
message.
This worked for me: put the hover styling in a new class
.fakehover {background: red}
Then add / remove the class as and when required
$(".someclass > li").on("mouseenter", function(e) {
$(this).addClass("fakehover");
});
$(".someclass > li").on("mouseleave", function(e) {
$(this).removeClass("fakehover");
});
Repeat for touchstart and touchend events. Or whatever events you like to get the desired result, for example I wanted the hover effect to be toggled on a touch screen.
The essence of object oriented programming is encapsulating logic together with the data it operates on.
Instance methods are the logic, instance fields are the data. Together, they form an object.
public class Foo
{
private String foo;
public Foo(String foo){ this.foo = foo; }
public getFoo(){ return this.foo; }
public static void main(String[] args){
System.out.println( getFoo() );
}
}
What could possibly be the result of running the above program?
Without an object, there is no instance data, and while the instance methods exist as part of the class definition, they need an object instance to provide data for them.
In theory, an instance method that does not access any instance data could work in a static context, but then there isn't really any reason for it to be an instance method. It's a language design decision to allow it anyway rather than making up an extra rule to forbid it.
Programatically this can be achieved with SCHTASKS:
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=1074)]]" /EC Security /tn on_shutdown_normal /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6006)]]" /EC Security /tn on_shutdown_6006 /tr "c:\some.bat"
SCHTASKS /Create /SC ONEVENT /mo "Event[System[(EventID=6008)]]" /EC Security /tn on_shutdown_6008 /tr "c:\some.bat"
several years ago I wrote script library for bash which supported associative arrays among other features (logging, configuration files, extended support for command line argument, generate help, unit testing, etc). The library contains a wrapper for associative arrays and automatically switches to appropriate model (internal for bash4 and emulate for previous versions). It was called shell-framework and hosted at origo.ethz.ch but today the resource is closed. If someone still needs it I can share it with you.
See the following snippet, is this what you want?
body {
background: silver;
padding: 0 10px;
}
#content:after {
height: 10px;
display: block;
width: 100px;
background: #808080;
border-right: 1px white;
content: '';
}
#footer:before {
display: block;
content: '';
background: silver;
height: 10px;
margin-top: -20px;
margin-left: 101px;
}
#content {
background: white;
}
#footer {
padding-top: 10px;
background: #404040;
}
p {
padding: 100px;
text-align: center;
}
#footer p {
color: white;
}
_x000D_
<body>
<div id="content"><p>#content</p></div>
<div id="footer"><p>#footer</p></div>
</body>
_x000D_
Non of them worked for me. I did this and it worked:
To encode as a json:
JSONObject obj = new JSONObject();
obj.put("productId", 100);
To decode:
long temp = (Long) obj.get("productId");
Something like this:
var div = document.getElementById("result");_x000D_
_x000D_
var str = "{'a':1}";_x000D_
str = str.replace(/\'/g, '"');_x000D_
var parsed = JSON.parse(str);_x000D_
console.log(parsed);_x000D_
div.innerText = parsed.a;
_x000D_
<div id="result"></div>
_x000D_
They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.
git reset --soft HEAD~1.
This will undo the last commit in local repos and move everything back to stage area like before doing the commit. Then just use any Git UI tool as normal (like TortoiseGit, Git UI, Git Extensions...) to unstage the files that we do not want to commit then do the commit again.
try using INSTALL_ROOT.
make install INSTALL_ROOT=$INSTALL_DIRECTORY
The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this
FOR SQL SERVER 2005 and above
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified =(int)cmd.ExecuteScalar();
if (con.State == System.Data.ConnectionState.Open)
con.Close();
return modified;
}
}
FOR previous versions
using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
{
cmd.Parameters.AddWithValue("@na", Mem_NA);
cmd.Parameters.AddWithValue("@occ", Mem_Occ);
con.Open();
int modified = Convert.ToInt32(cmd.ExecuteScalar());
if (con.State == System.Data.ConnectionState.Open) con.Close();
return modified;
}
}
You need to use .each
:
var listItems = $("#productList li");
listItems.each(function(idx, li) {
var product = $(li);
// and the rest of your code
});
This is the correct way to loop through a jQuery selection.
In modern Javascript you can also use a for .. of
loop:
var listItems = $("#productList li");
for (let li of listItems) {
let product = $(li);
}
Be aware, however, that older browsers will not support this syntax, and you may well be better off with the jQuery syntax above.
You should look this example to understand Lazy Loading architecture
private readonly Lazy<List<int>> list = new Lazy<List<int>>(() =>
{
List<int> configList = new List<int>(Thread.CurrentThread.ManagedThreadId);
return configList;
});
public void Execute()
{
list.Value.Add(0);
if (list.IsValueCreated)
{
list.Value.Add(1);
list.Value.Add(2);
foreach (var item in list.Value)
{
Console.WriteLine(item);
}
}
else
{
Console.WriteLine("Value not created");
}
}
--> output --> 0 1 2
but if this code dont write "list.Value.Add(0);"
output --> Value not created
You should call the element's native .click()
method or use the createEvent
API.
For more info, please visit: https://learn.jquery.com/events/triggering-event-handlers/
(Copying answer from question)
To add an insecure docker registry, add the file /etc/docker/daemon.json
with the following content:
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
and then restart docker.
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
As a reason of this problem, some code is broken or undefined.You may see an error in a java class such as "The type javax.servlet.http.HttpSession cannot be resolved. It is indirectly referenced from required .class files". you shuold download " javax.servlet.jar" as mentioned before. Then configure your project build path, add the javax.servlet.jar as an external jar.I hope it fixes the problem.At least it worked for me.
I faced a similar issue during work with Ubuntu 16.04 by using Docker. In my case that was a problem with Composer, but error message (and thus the problem) was the same.
Because of minimalist Docker-oriented base image I had missing ca-certificates
package and simple apt-get install ca-certificates
helped me.
The solution to the issue when i had this earlier today was that there was an additional set of tags bolted on the end of my Web.config. Once removed the functionality returned.
As you can see in the Java Source of the java.lang.String class:
/**
* Allocates a new <code>String</code> that contains characters from
* a subarray of the character array argument. The <code>offset</code>
* argument is the index of the first character of the subarray and
* the <code>count</code> argument specifies the length of the
* subarray. The contents of the subarray are copied; subsequent
* modification of the character array does not affect the newly
* created string.
*
* @param value array that is the source of characters.
* @param offset the initial offset.
* @param count the length.
* @exception IndexOutOfBoundsException if the <code>offset</code>
* and <code>count</code> arguments index characters outside
* the bounds of the <code>value</code> array.
*/
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.value = new char[count];
this.count = count;
System.arraycopy(value, offset, this.value, 0, count);
}
Parameter references are surrounded by <code></code>
tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).
Go to the query designer window, switch to SQL mode, and try this:
Update Table Set MyField = 0
Where MyField Is Null;
Starting with SQL Server 2012, you could use TRY_PARSE or TRY_CONVERT.
SELECT TRY_PARSE(MyVarcharCol as int)
SELECT TRY_CONVERT(int, MyVarcharCol)
As said, the browser doesn't let the server know when it closes.
Still, there are some ways to achieve close to this behavior. You can put a small AJAX script in place that updates the server regularly that the browser is open. You should pair this with something that fires on actions made by the user, so you can time out an idle session as well as one that has closed out.
This one is correct:
ALTER TABLE `users`
ADD COLUMN `count` SMALLINT(6) NOT NULL AFTER `lastname`,
ADD COLUMN `log` VARCHAR(12) NOT NULL AFTER `count`,
ADD COLUMN `status` INT(10) UNSIGNED NOT NULL AFTER `log`;
Put 0 as default in SQL or add 0 into your area of table
public ActionResult Index()
{
List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();
var orderlist = (from a in db.OrderMasters
join b in db.Customers on a.CustomerId equals b.Id
join c in db.CustomerAddresses on b.Id equals c.CustomerId
where a.Status == "Pending"
select new
{
Customername = b.Customername,
Phone = b.Phone,
OrderId = a.OrderId,
OrderDate = a.OrderDate,
NoOfItems = a.NoOfItems,
Order_amt = a.Order_amt,
dis_amt = a.Dis_amt,
net_amt = a.Net_amt,
status=a.Status,
address = c.address,
City = c.City,
State = c.State,
Pin = c.Pin
}) ;
foreach (var item in orderlist)
{
CustomerOrder_Result clr = new CustomerOrder_Result();
clr.Customername=item.Customername;
clr.Phone = item.Phone;
clr.OrderId = item.OrderId;
clr.OrderDate = item.OrderDate;
clr.NoOfItems = item.NoOfItems;
clr.Order_amt = item.Order_amt;
clr.net_amt = item.net_amt;
clr.address = item.address;
clr.City = item.City;
clr.State = item.State;
clr.Pin = item.Pin;
clr.status = item.status;
obj.Add(clr);
}
The random_real class from the Boost random library is what you need.
DELIMITER $$
CREATE PROCEDURE `databasename`.`update_char_set`()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE t_sql VARCHAR(256);
DECLARE tableName VARCHAR(128);
DECLARE lists CURSOR FOR SELECT table_name FROM `information_schema`.`TABLES` WHERE table_schema = 'databasename';
DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
OPEN lists;
FETCH lists INTO tableName;
REPEAT
SET @t_sql = CONCAT('ALTER TABLE ', tableName, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci');
PREPARE stmt FROM @t_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
FETCH lists INTO tableName;
UNTIL done END REPEAT;
CLOSE lists;
END$$
DELIMITER ;
CALL databasename.update_char_set();
What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:
If you have a class Automobile
, then Car
and Truck
are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.
I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:
List<Car> cars;
List<Automobile> automobiles = cars;
// You'd expect this to work because Car is-a Automobile, but
// throws inconvertible types compile error.
The reason of the error is, however, correct: List<Car>
does not inherit from List<Automobile>
and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:
List<Car> cars;
List<? extends Automobile> automobiles = cars; // no error
The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:
class AutoColorComparer implements Comparator<Automobile>
public int compare(Automobile a, Automobile b) {
// Return comparison of colors
}
This can be used with Collections.sort:
public static <T> void sort(List<T> list, Comparator<? super T> c)
// Which you can call like this, without errors:
List<Car> cars = getListFromSomewhere();
Collections.sort(cars, new AutoColorComparer());
You could even call it with a comparer that compares objects and use it with any type.
A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you get something, use covariance and when you put something, use contravariance. This is best explained in an answer to Stack Overflow question How would contravariance be used in Java generics?.
List<? extends Map<String, String>>
You use extends
, so the rules for covariance applies. Here you have a list of maps and each item you store in the list must be a Map<string, string>
or derive from it. The statement List<Map<String, String>>
cannot derive from Map
, but must be a Map
.
Hence, the following will work, because TreeMap
inherits from Map
:
List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(new TreeMap<String, String>());
but this will not:
List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new TreeMap<String, String>());
and this will not work either, because it does not satisfy the covariance constraint:
List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new ArrayList<String>()); // This is NOT allowed, List does not implement Map
This is probably obvious, but you may have already noted that using the extends
keyword only applies to that parameter and not to the rest. I.e., the following will not compile:
List<? extends Map<String, String>> mapList = new List<? extends Map<String, String>>();
mapList.add(new TreeMap<String, Element>()) // This is NOT allowed
Suppose you want to allow any type in the map, with a key as string, you can use extend
on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:
List<? extends Map<String, ? extends Node>> listOfMapsOfNodes = new...;
// Now you can do:
listOfMapsOfNodes.add(new TreeMap<Sting, Element>());
listOfMapsOfNodes.add(new TreeMap<Sting, CDATASection>());
If you want to be able to toggle the display of whitespaces on and off, you can install the HighlightWhitespaces plugin
You can use numpy:
import numpy as np
Example from Empty Array:
np.empty([2, 2])
array([[ -9.74499359e+001, 6.69583040e-309],
[ 2.13182611e-314, 3.06959433e-309]])
Please visit this repo.
Widget _gridView() {
return GridView.count(
crossAxisCount: 4,
padding: EdgeInsets.all(4.0),
childAspectRatio: 8.0 / 9.0,
children: itemList
.map(
(Item) => ItemList(item: Item),
)
.toList(),
);
}
We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,
server{
server_name domain.com sub.domain.com; # multiple domains
location /{
proxy_pass http://127.0.0.1:8080;
proxy_set_header Host $host;
proxy_pass_request_headers on;
}
location /static/{
alias /absolute/path/to/static/files; # nginx will handle js/css
}
}
in above setup your Nodejs app will,
HTTP_HOST
header where you can apply domain specific logic to serve the response. 'Your Application must be managed by a process manager like pm2 or supervisor for handling situations/reusing sockets or resources etc.
Setup an error reporting service for getting production errors like sentry or rollbar
NOTE: you can setup logic for handing domain specific request routes, create a middleware for expressjs application
Go to this link and wait for a while to load.
http://www.java.com/en/download/testjava.jsp
You will see the below image:
You can alternatively open command window and type java -version
In the case of 401 vs 403, this has been answered many times. This is essentially a 'HTTP request environment' debate, not an 'application' debate.
There seems to be a question on the roll-your-own-login issue (application).
In this case, simply not being logged in is not sufficient to send a 401 or a 403, unless you use HTTP Auth vs a login page (not tied to setting HTTP Auth). It sounds like you may be looking for a "201 Created", with a roll-your-own-login screen present (instead of the requested resource) for the application-level access to a file. This says:
"I heard you, it's here, but try this instead (you are not allowed to see it)"
In order to open a link in a new tab/window you'll use <a target="_blank">
.
value _blank
= targeted browsing context: a new one: tab or window depending on your browsing settings
value _new
= not valid; no such value in HTML5 for target attribute on a element
target attribute with all its values on a element: video demo
same browsers may return string for border width, in this parseInt will return NaN so make sure you parse value to int properly.
var getInt = function (string) {
if (typeof string == "undefined" || string == "")
return 0;
var tempInt = parseInt(string);
if (!(tempInt <= 0 || tempInt > 0))
return 0;
return tempInt;
}
var liWidth = $(this).width();
liWidth += getInt($(this).css("padding-left"));
liWidth += getInt($(this).css("padding-right"));
liWidth += getInt($(this).css("border-left-width"));
liWidth += getInt($(this).css("border-right-width"));
This one is violent use with caution :
pkill -9 -e -f processname
If your process name is "sh" it will also kill "bash"
seeing how the rules are fairly complicated, I'd suggest the following:
/^[a-z](\w*)[a-z0-9]$/i
match the whole string and capture intermediate characters. Then either with the string functions or the following regex:
/__/
check if the captured part has two underscores in a row. For example in Python it would look like this:
>>> import re
>>> def valid(s):
match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
if match is not None:
return match.group(1).count('__') == 0
return False
Here is another image map plugin I wrote to enhance image maps: https://github.com/gestixi/pictarea
It makes it easy to highlight all the area and let you specify different styles depending on the state of the zone: normal, hover, active, disable.
You can also specify how many zones can be selected at the same time.
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
If we are using Java 7 and above and also know the content to be added (appended) to the file we can make use of newBufferedWriter method in NIO package.
public static void main(String[] args) {
Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
String text = "\n Welcome to Java 8";
//Writing to the file temp.txt
try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
writer.write(text);
} catch (IOException e) {
e.printStackTrace();
}
}
There are few points to note:
StandardCharsets
.try-with-resource
statement in which resources are automatically closed after the try.Though OP has not asked but just in case we want to search for lines having some specific keyword e.g. confidential
we can make use of stream APIs in Java:
//Reading from the file the first line which contains word "confidential"
try {
Stream<String> lines = Files.lines(FILE_PATH);
Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
if(containsJava.isPresent()){
System.out.println(containsJava.get());
}
} catch (IOException e) {
e.printStackTrace();
}
It is returning a Buffer object.
If you want it in a string, you can convert it with data.toString()
:
var fs = require("fs");
fs.readFile("test.txt", function (err, data) {
if (err) throw err;
console.log(data.toString());
});
Get-ChildItem $originalPath\* -Include @("*.gif", "*.jpg", "*.xls*", "*.doc*", "*.pdf*", "*.wav*", "*.ppt")
It may not be exactly what you want, but my workaround is to apply the autowidth styling to a wrapper div - then set your input to 100%.
I solved this, without having to completely reinstall Visual Studio 2013.
For those who may come across this in the future, the following steps worked for me:
vs_professional.exe
).If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3
Click the link for 'examine the log file' and look near the bottom of the log, for this line:
open regedit.exe
and do an Edit > Find...
for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
. This was found in:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}
Edit the BundleVersion
value and change it to a lower version. I changed mine from 12.0.21005.13
to 12.0.21000.13
:
Exit the registry
Run the ISO (or vs_professional.exe
) again. If it has a repair button like the image below, you can skip to step 4.
Run the ISO (or vs_professional.exe
) again. This time repair should be visible.
Click Repair
and let it update your installation and apply its embedded license key. This took about 20 minutes.
Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product
:
Hope this helps somebody in the future!
To get the results in excel like file, you have one option to get it done with csv file. Use below commands with provided options.
jmeter -n -t /path-to-jmeter-test/file.jmx -l TestResults.csv
-n states Non GUI mode
-t states Test JMX File
-l state Log the results in provided file
Also you can pass any results related parameters dynamically in command line arguments using -Jprop.name=value which are already defined in jmeter.properties in bin folder.
The OP, MAW74656, originally posted this answer in the question body in response to the accepted answer, as explained in this comment:
I used this and wrote a public method to call the code and return the boolean.
The OP's answer:
Code Used:
public bool tablesAreTheSame(DataTable table1, DataTable table2) { DataTable dt; dt = getDifferentRecords(table1, table2); if (dt.Rows.Count == 0) return true; else return false; } //Found at http://canlu.blogspot.com/2009/05/how-to-compare-two-datatables-in-adonet.html private DataTable getDifferentRecords(DataTable FirstDataTable, DataTable SecondDataTable) { //Create Empty Table DataTable ResultDataTable = new DataTable("ResultDataTable"); //use a Dataset to make use of a DataRelation object using (DataSet ds = new DataSet()) { //Add tables ds.Tables.AddRange(new DataTable[] { FirstDataTable.Copy(), SecondDataTable.Copy() }); //Get Columns for DataRelation DataColumn[] firstColumns = new DataColumn[ds.Tables[0].Columns.Count]; for (int i = 0; i < firstColumns.Length; i++) { firstColumns[i] = ds.Tables[0].Columns[i]; } DataColumn[] secondColumns = new DataColumn[ds.Tables[1].Columns.Count]; for (int i = 0; i < secondColumns.Length; i++) { secondColumns[i] = ds.Tables[1].Columns[i]; } //Create DataRelation DataRelation r1 = new DataRelation(string.Empty, firstColumns, secondColumns, false); ds.Relations.Add(r1); DataRelation r2 = new DataRelation(string.Empty, secondColumns, firstColumns, false); ds.Relations.Add(r2); //Create columns for return table for (int i = 0; i < FirstDataTable.Columns.Count; i++) { ResultDataTable.Columns.Add(FirstDataTable.Columns[i].ColumnName, FirstDataTable.Columns[i].DataType); } //If FirstDataTable Row not in SecondDataTable, Add to ResultDataTable. ResultDataTable.BeginLoadData(); foreach (DataRow parentrow in ds.Tables[0].Rows) { DataRow[] childrows = parentrow.GetChildRows(r1); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } //If SecondDataTable Row not in FirstDataTable, Add to ResultDataTable. foreach (DataRow parentrow in ds.Tables[1].Rows) { DataRow[] childrows = parentrow.GetChildRows(r2); if (childrows == null || childrows.Length == 0) ResultDataTable.LoadDataRow(parentrow.ItemArray, true); } ResultDataTable.EndLoadData(); } return ResultDataTable; }
If you need unary numeral system, you can convert an integer like this:
>> n = 6
>> '1' * n
'111111'
If you need a support of negative ints you can just write like that:
>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'
Zero is special case which takes an empty string in this case, which is correct.
>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''
two things
one: compile is out of date rather it is better to use implementation,
and two: volley 1.0.0 is out of date and syncing project will no work
alternatively in build.gradle add implementation 'com.android.volley:volley:1.1.1' or implementation 'com.android.volley:volley:1.1.+' for 1.1.0 and newer versions.
You can do it using remote debugging, here is official documentation. Basic process:
*
from dev tools on pc/mac.*
This is now "Remote devices".
See this pure Python ping by Matthew Dixon Cowles and Jens Diemer. Also, remember that Python requires root to spawn ICMP (i.e. ping) sockets in linux.
import ping, socket
try:
ping.verbose_ping('www.google.com', count=3)
delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
print "Ping Error:", e
The source code itself is easy to read, see the implementations of verbose_ping
and of Ping.do
for inspiration.
I've been struggling with this problem in one form or another for AGES, thank you, Thank You, THANK YOU.... :)
I just wanted to point out that you can get a generalizable solution from what Bob Lee's done by just extending View and overriding onMeasure. That way you can use this with any drawable you want, and it won't break if there's no image:
public class CardImageView extends View {
public CardImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CardImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CardImageView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable bg = getBackground();
if (bg != null) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * bg.getIntrinsicHeight() / bg.getIntrinsicWidth();
setMeasuredDimension(width,height);
}
else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
My problem was I had due to the non-existence of a native Swift CommonCrypto, used a bridging header and a target that with some magic included it in the build. Since CommonCrypto is now native, I solved the problem by removing the target and the #import
and instead added an import CommonCrypto
where I used it.
In my understanding searching distinctive colors is related to search efficiently from an unit cube, where 3 dimensions of the cube are three vectors along red, green and blue axes. This can be simplified to search in a cylinder (HSV analogy), where you fix Saturation (S) and Value (V) and find random Hue values. It works in many cases, and see this here :
https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
In R,
get_distinct_hues <- function(ncolor,s=0.5,v=0.95,seed=40) {
golden_ratio_conjugate <- 0.618033988749895
set.seed(seed)
h <- runif(1)
H <- vector("numeric",ncolor)
for(i in seq_len(ncolor)) {
h <- (h + golden_ratio_conjugate) %% 1
H[i] <- h
}
hsv(H,s=s,v=v)
}
An alternative way, is to use R package "uniformly" https://cran.r-project.org/web/packages/uniformly/index.html
and this simple function can generate distinctive colors:
get_random_distinct_colors <- function(ncolor,seed = 100) {
require(uniformly)
set.seed(seed)
rgb_mat <- runif_in_cube(n=ncolor,d=3,O=rep(0.5,3),r=0.5)
rgb(r=rgb_mat[,1],g=rgb_mat[,2],b=rgb_mat[,3])
}
One can think of a little bit more involved function by grid-search:
get_random_grid_colors <- function(ncolor,seed = 100) {
require(uniformly)
set.seed(seed)
ngrid <- ceiling(ncolor^(1/3))
x <- seq(0,1,length=ngrid+1)[1:ngrid]
dx <- (x[2] - x[1])/2
x <- x + dx
origins <- expand.grid(x,x,x)
nbox <- nrow(origins)
RGB <- vector("numeric",nbox)
for(i in seq_len(nbox)) {
rgb <- runif_in_cube(n=1,d=3,O=as.numeric(origins[i,]),r=dx)
RGB[i] <- rgb(rgb[1,1],rgb[1,2],rgb[1,3])
}
index <- sample(seq(1,nbox),ncolor)
RGB[index]
}
check this functions by:
ncolor <- 20
barplot(rep(1,ncolor),col=get_distinct_hues(ncolor)) # approach 1
barplot(rep(1,ncolor),col=get_random_distinct_colors(ncolor)) # approach 2
barplot(rep(1,ncolor),col=get_random_grid_colors(ncolor)) # approach 3
However, note that, defining a distinct palette with human perceptible colors is not simple. Which of the above approach generates diverse color set is yet to be tested.
$row['Value']
is probably a string. Try using intval($row['Value'])
.
Also, make sure you set $sum = 0
before the loop.
Or, better yet, add SUM(Value) AS Val_Sum
to your SQL query.
It's only possible when the server sends this header: Access-Control-Allow-Origin: *
If this is your code then you can setup it like this (PHP):
header('Access-Control-Allow-Origin: *');
<?php
parse_str(http_build_query($_COOKIE),$arr);
foreach ($arr as $k=>$v) {
setCookie("$k","",1000,"/");
}
In Visual Studio you can use nuget to download the latest version. Just right click on the project and click 'Manage NuGet Packages' then search online for MySql.Data and install.
To install OpenJDK 8 JRE using yum with non root user, run this command:
sudo yum install java-1.8.0-openjdk
to verify java -version
Use jq -s add
:
$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
"a": 0,
"b": "bar",
"c": "baz"
}
This reads all JSON texts from stdin into an array (jq -s
does that) then it "reduces" them.
(add
is defined as def add: reduce .[] as $x (null; . + $x);
, which iterates over the input array's/object's values and adds them. Object addition == merge.)
Check for "projtemp" and then check if the previous one is a number entry (like 19,18..etc..) if that is so then get the row no of that proj temp ....
and if that is not so ..then re-check that the previous entry is projtemp or a number entry ...
I had similar problem I did the following steps and it worked.Go to mac terminal and execute the commands,
1.npm config set prefix /usr/local
2.sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
This two commands will set the npm path right and you no longer have to use sudo in npm. Next uninstall the gulp
npm uninstall gulp
Installl gulp again without sudo, npm install gulp -g
This should work!!
For what it's worth I do this differently. A successful call just has the JSON objects. I don't need a higher level JSON object that contains a success field indicating true and a payload field that has the JSON object. I just return the appropriate JSON object with a 200 or whatever is appropriate in the 200 range for the HTTP status in the header.
However, if there is an error (something in the 400 family) I return a well-formed JSON error object. For example, if the client is POSTing a User with an email address and phone number and one of these is malformed (i.e. I cannot insert it into my underlying database) I will return something like this:
{
"description" : "Validation Failed"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Invalid phone number."
} ],
}
Important bits here are that the "field" property must match the JSON field exactly that could not be validated. This allows clients to know exactly what went wrong with their request. Also, "message" is in the locale of the request. If both the "emailAddress" and "phoneNumber" were invalid then the "errors" array would contain entries for both. A 409 (Conflict) JSON response body might look like this:
{
"description" : "Already Exists"
"errors" : [ {
"field" : "phoneNumber",
"message" : "Phone number already exists for another user."
} ],
}
With the HTTP status code and this JSON the client has all they need to respond to errors in a deterministic way and it does not create a new error standard that tries to complete replace HTTP status codes. Note, these only happen for the range of 400 errors. For anything in the 200 range I can just return whatever is appropriate. For me it is often a HAL-like JSON object but that doesn't really matter here.
The one thing I thought about adding was a numeric error code either in the the "errors" array entries or the root of the JSON object itself. But so far we haven't needed it.
It's a subtle difference, but this works fine for me:
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
Notice, the difference between getColumnDimensionByColumn
and getColumnDimension
Also, I'm not even setting AutoSize and it works fine.
IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.
Using conda install scipy instead of pip solved the problem for me!
I haven't used Cassandra, but I have used MongoDB and think it's awesome.
If you're after simple setup, this is it: You simply untar MongoDB and run the mongod daemon and that's it ... it's running.
Obviously that's only a starter, but to get you started it's easy.
Wrap the <form>
element inside a div
container and apply css to the div
instead which makes things easier.
#aDiv{width: 300px; height: 300px; margin: 0 auto;}
_x000D_
<html>_x000D_
_x000D_
<head></head>_x000D_
_x000D_
<body>_x000D_
<div>_x000D_
<form>_x000D_
<div id="aDiv">_x000D_
<table>_x000D_
<tr>_x000D_
<td>Name :</td>_x000D_
<td>_x000D_
<input type="text" name="name">_x000D_
</td>_x000D_
<br>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Email :</td>_x000D_
<td>_x000D_
<input type="text" name="email">_x000D_
</td>_x000D_
<br>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Password :</td>_x000D_
<td>_x000D_
<input type="password" name="pwd">_x000D_
</td>_x000D_
<br>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>Confirm Password :</td>_x000D_
<td>_x000D_
<input type="password" name="cpwd">_x000D_
<br>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>_x000D_
<input type="submit" value="Submit">_x000D_
</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>_x000D_
</form>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Have to join the fun...
private void TestBench()
{
// An object to test
string[] stringEnumerable = new string[] { "Easy", "as", "Pi" };
ObjectListFromUnknown(stringEnumerable);
}
private void ObjectListFromUnknown(object o)
{
if (typeof(IEnumerable<object>).IsAssignableFrom(o.GetType()))
{
List<object> listO = ((IEnumerable<object>)o).ToList();
// Test it
foreach (var v in listO)
{
Console.WriteLine(v);
}
}
}
x86 is for a 32-bit OS, and x64 is for a 64-bit OS
I think you can't achieve what you want in a more efficient manner than you proposed.
The underlying problem is that the timestamps (as you seem aware) are made up of two parts. The data that represents the UTC time, and the timezone, tz_info. The timezone information is used only for display purposes when printing the timezone to the screen. At display time, the data is offset appropriately and +01:00 (or similar) is added to the string. Stripping off the tz_info value (using tz_convert(tz=None)) doesn't doesn't actually change the data that represents the naive part of the timestamp.
So, the only way to do what you want is to modify the underlying data (pandas doesn't allow this... DatetimeIndex are immutable -- see the help on DatetimeIndex), or to create a new set of timestamp objects and wrap them in a new DatetimeIndex. Your solution does the latter:
pd.DatetimeIndex([i.replace(tzinfo=None) for i in t])
For reference, here is the replace
method of Timestamp
(see tslib.pyx):
def replace(self, **kwds):
return Timestamp(datetime.replace(self, **kwds),
offset=self.offset)
You can refer to the docs on datetime.datetime
to see that datetime.datetime.replace
also creates a new object.
If you can, your best bet for efficiency is to modify the source of the data so that it (incorrectly) reports the timestamps without their timezone. You mentioned:
I want to work with timezone naive timeseries (to avoid the extra hassle with timezones, and I do not need them for the case I am working on)
I'd be curious what extra hassle you are referring to. I recommend as a general rule for all software development, keep your timestamp 'naive values' in UTC. There is little worse than looking at two different int64 values wondering which timezone they belong to. If you always, always, always use UTC for the internal storage, then you will avoid countless headaches. My mantra is Timezones are for human I/O only.
Free "Export to KML" script for ArcGIS 9
Here is a list of available methods that someone found.
Also, it seems to me that the most efficient representation of a polygon layer is by using Google Maps API's polyline encoding, which significantly compresses lat-lng data. But getting into that format takes work: use ArcMap to export Shape as lat/lng coordinates, then convert into polylines using Google Maps API.
Use the filter_var()
function to validate whether a string is URL or not:
var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
It is bad practice to use regular expressions when not necessary.
EDIT: Be careful, this solution is not unicode-safe and not XSS-safe. If you need a complex validation, maybe it's better to look somewhere else.
Came across this and thought I would point out that for MVC 5 all you need to do is set the value on the model. For Example:
Model:
public class ExampleModel
{
public PackingListInputModel()
{
RadioButtonField = "One";
}
public string RadioButtonField { get; set; }
}
View :
@model ExampleModel
@using (Html.BeginForm)
{
@Html.RadioButtonFor(m => m.RadioButtonField , "One")
@Html.RadioButtonFor(m => m.RadioButtonField , "Two")
}
The state of the first radio button ("One") will be set as active because the value matches what was set in the model.
The drawPolygon
function below can be used to draw any polygon with rounded corners.
function drawPolygon(ctx, pts, radius) {
if (radius > 0) {
pts = getRoundedPoints(pts, radius);
}
var i, pt, len = pts.length;
ctx.beginPath();
for (i = 0; i < len; i++) {
pt = pts[i];
if (i == 0) {
ctx.moveTo(pt[0], pt[1]);
} else {
ctx.lineTo(pt[0], pt[1]);
}
if (radius > 0) {
ctx.quadraticCurveTo(pt[2], pt[3], pt[4], pt[5]);
}
}
ctx.closePath();
}
function getRoundedPoints(pts, radius) {
var i1, i2, i3, p1, p2, p3, prevPt, nextPt,
len = pts.length,
res = new Array(len);
for (i2 = 0; i2 < len; i2++) {
i1 = i2-1;
i3 = i2+1;
if (i1 < 0) {
i1 = len - 1;
}
if (i3 == len) {
i3 = 0;
}
p1 = pts[i1];
p2 = pts[i2];
p3 = pts[i3];
prevPt = getRoundedPoint(p1[0], p1[1], p2[0], p2[1], radius, false);
nextPt = getRoundedPoint(p2[0], p2[1], p3[0], p3[1], radius, true);
res[i2] = [prevPt[0], prevPt[1], p2[0], p2[1], nextPt[0], nextPt[1]];
}
return res;
};
function getRoundedPoint(x1, y1, x2, y2, radius, first) {
var total = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)),
idx = first ? radius / total : (total - radius) / total;
return [x1 + (idx * (x2 - x1)), y1 + (idx * (y2 - y1))];
};
The function receives an array with the polygon points, like this:
var canvas = document.getElementById("cv");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "#000000";
ctx.lineWidth = 5;
drawPolygon(ctx, [[20, 20],
[120, 20],
[120, 120],
[ 20, 120]], 10);
ctx.stroke();
This is a port and a more generic version of a solution posted here.
$var=$TZ;
TZ=$TZ+24;
date;
TZ=$var;
Will get you yesterday in AIX and set back the TZ variable back to original
This is not possible with native HTML input elements. You can use webshim polyfill, which gives you this option by using this markup.
<input type="date" data-date-inline-picker="true" />
Here is a small demo
This answer is not exactly what you want, but it might be useful in some cases. If you know the element has some dimensions when displayed, you can also use this:
var hasDisplayNone = (element.offsetHeight === 0 && element.offsetWidth === 0);
EDIT: Why this might be better than direct check of CSS display
property? Because you do not need to check all parent elements. If some parent element has display: none
, its children are hidden too but still has element.style.display !== 'none'
.
just like this :
global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);
simply your selecting all the rows then order them DESC by id , and displaying only the first
You need a SQL profiler, which actually runs outside SQL Management Studio. If you have a paid version of SQL Server (like the developer edition), it should be included in that as another utility.
If you're using a free edition (SQL Express), they have freeware profiles that you can download. I've used AnjLab's profiler (available at http://sites.google.com/site/sqlprofiler), and it seemed to work well.
There is an article on javaworld.com that explains the difference => Which ClassLoader should you use
(1)
Thread context classloaders provide a back door around the classloading delegation scheme.
Take JNDI for instance: its guts are implemented by bootstrap classes in rt.jar (starting with J2SE 1.3), but these core JNDI classes may load JNDI providers implemented by independent vendors and potentially deployed in the application's -classpath. This scenario calls for a parent classloader (the primordial one in this case) to load a class visible to one of its child classloaders (the system one, for example). Normal J2SE delegation does not work, and the workaround is to make the core JNDI classes use thread context loaders, thus effectively "tunneling" through the classloader hierarchy in the direction opposite to the proper delegation.
(2) from the same source:
This confusion will probably stay with Java for some time. Take any J2SE API with dynamic resource loading of any kind and try to guess which loading strategy it uses. Here is a sampling:
- JNDI uses context classloaders
- Class.getResource() and Class.forName() use the current classloader
- JAXP uses context classloaders (as of J2SE 1.4)
- java.util.ResourceBundle uses the caller's current classloader
- URL protocol handlers specified via java.protocol.handler.pkgs system property are looked up in the bootstrap and system classloaders only
- Java Serialization API uses the caller's current classloader by default
The best and the safest way to show a 'ProgressDialog' in an AsyncTask, avoiding memory leak problem is to use a 'Handler' with Looper.main().
private ProgressDialog tProgressDialog;
then in the 'onCreate'
tProgressDialog = new ProgressDialog(this);
tProgressDialog.setMessage(getString(R.string.loading));
tProgressDialog.setIndeterminate(true);
Now you r done with the setup part. Now call 'showProgress()' and 'hideProgress()' in AsyncTask.
private void showProgress(){
new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
tProgressDialog.show();
}
}.sendEmptyMessage(1);
}
private void hideProgress(){
new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
tProgressDialog.dismiss();
}
}.sendEmptyMessage(1);
}
In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.
So your example:
<span style="color:blue" style="font-style:italic">Test</span>
is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.
Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.
(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:
Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
For >= 2nd row values insert into table-
$file = fopen($filename, "r");
//$sql_data = "SELECT * FROM prod_list_1 ";
$count = 0; // add this line
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//print_r($emapData);
//exit();
$count++; // add this line
if($count>1){ // add this line
$sql = "INSERT into prod_list_1(p_bench,p_name,p_price,p_reason) values ('$emapData[0]','$emapData[1]','$emapData[2]','$emapData[3]')";
mysql_query($sql);
} // add this line
}
The Tesseract documentation contains some good details on how to improve the OCR quality via image processing steps.
To some degree, Tesseract automatically applies them. It is also possible to tell Tesseract to write an intermediate image for inspection, i.e. to check how well the internal image processing works (search for tessedit_write_images
in the above reference).
More importantly, the new neural network system in Tesseract 4 yields much better OCR results - in general and especially for images with some noise. It is enabled with --oem 1
, e.g. as in:
$ tesseract --oem 1 -l deu page.png result pdf
(this example selects the german language)
Thus, it makes sense to test first how far you get with the new Tesseract LSTM mode before applying some custom pre-processing image processing steps.
Sometimes happened because of convert data type , for example you have an object that you considered as string.
socket.id in nodejs either in js client as example, is not a string. to use it as string you have to add the word String before:
String(socket.id);
One issue I've had, and it was horribly tricky, was that the OCI call to describe a column attributes behaves diffrently depending on Oracle versions. Describing a simple NUMBER column created without any prec or scale returns differenlty on 9i, 1Og and 11g
Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl
runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests
or urllib2
.
You can use the subprocess
module to execute curl
and get at the retrieved content:
import subprocess
// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])
Python 3's subprocess
module also contains .run()
with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.
Date d=new Date(new Date().getTime()+28800000);
String s=new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(d);
HH will return 0-23 for hours.
kk will return 1-24 for hours.
See more here: Customizing Formats
use method setIs24HourView(Boolean is24HourView) to set time picker to set 24 hour view.
<div *ngIf="currentStatus !== ('status1' || 'status2' || 'status3' || 'status4')">
I don't have much time and your jsfidle did not work right now.
But maybe this will help you getting started.
First of all you should avoid to put css in your html tags. Like align="center"
.
Put stuff like that in your css since it is much clearer and won't deprecate that fast.
If you want to design responsive layouts you should use media queries wich were introduced in css3 and are supported very well by now.
Example css:
@media screen and (min-width: 100px) and (max-width: 199px)
{
.button
{
width: 25px;
}
}
@media screen and (min-width: 200px) and (max-width: 299px)
{
.button
{
width: 50px;
}
}
You can use any css you want inside a media query.
http://www.w3.org/TR/css3-mediaqueries/
SELECT CONVERT(varchar, @datetime, 103) --for UK Date format 'DD/MM/YYYY'
101 - US - MM/DD/YYYY
108 - Time - HH:MI:SS
112 - Date - YYYYMMDD
121 - ODBC - YYYY-MM-DD HH:MI:SS.FFF
20 - ODBC - YYYY-MM-DD HH:MI:SS
Another point to add.
Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.
int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)
Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.
Can overload class constructors, methods.
Can consider as Compile Time (static / Early Binding) polymorphism.
=====================================================================================================
Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.
Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.
Can Consider as Run Time (Dynamic / Late Binding) polymorphism.
Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx
=====================================================================================================
Helpful Links
http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism
Why do you want to enforce that only a single thread can access the DB at any one time?
It is the job of the database driver to implement any necessary locking, assuming a Connection
is only used by one thread at a time!
Most likely, your database is perfectly capable of handling multiple, parallel access
You can use datetime.strftime
to get the time in Epoch form, using the %s
format string:
def expires():
future = datetime.datetime.now() + datetime.timedelta(seconds=5*60)
return int(future.strftime("%s"))
Note: This only works under linux, and this method doesn't work with timezones.