Standard ISO 8601 format is used by your input string.
Instant.parse ( "2011-08-12T20:17:46.384Z" )
This format is defined by the sensible practical standard, ISO 8601.
The T
separates the date portion from the time-of-day portion. The Z
on the end means UTC (that is, an offset-from-UTC of zero hours-minutes-seconds). The Z
is pronounced “Zulu”.
The old date-time classes bundled with the earliest versions of Java have proven to be poorly designed, confusing, and troublesome. Avoid them.
Instead, use the java.time framework built into Java 8 and later. The java.time classes supplant both the old date-time classes and the highly successful Joda-Time library.
The java.time classes use ISO 8601 by default when parsing/generating textual representations of date-time values.
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds. That class can directly parse your input string without bothering to define a formatting pattern.
Instant instant = Instant.parse ( "2011-08-12T20:17:46.384Z" ) ;
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The answer to your question is yes and no, depending on what you mean by "inline function". If you're using the term like it's used in C++ development then the answer is no, you can't do that - even a lambda expression is a function call. While it's true that you can define inline lambda expressions to replace function declarations in C#, the compiler still ends up creating an anonymous function.
Here's some really simple code I used to test this (VS2015):
static void Main(string[] args)
{
Func<int, int> incr = a => a + 1;
Console.WriteLine($"P1 = {incr(5)}");
}
What does the compiler generate? I used a nifty tool called ILSpy that shows the actual IL assembly generated. Have a look (I've omitted a lot of class setup stuff)
This is the Main function:
IL_001f: stloc.0
IL_0020: ldstr "P1 = {0}"
IL_0025: ldloc.0
IL_0026: ldc.i4.5
IL_0027: callvirt instance !1 class [mscorlib]System.Func`2<int32, int32>::Invoke(!0)
IL_002c: box [mscorlib]System.Int32
IL_0031: call string [mscorlib]System.String::Format(string, object)
IL_0036: call void [mscorlib]System.Console::WriteLine(string)
IL_003b: ret
See those lines IL_0026 and IL_0027? Those two instructions load the number 5 and call a function. Then IL_0031 and IL_0036 format and print the result.
And here's the function called:
.method assembly hidebysig
instance int32 '<Main>b__0_0' (
int32 a
) cil managed
{
// Method begins at RVA 0x20ac
// Code size 4 (0x4)
.maxstack 8
IL_0000: ldarg.1
IL_0001: ldc.i4.1
IL_0002: add
IL_0003: ret
} // end of method '<>c'::'<Main>b__0_0'
It's a really short function, but it is a function.
Is this worth any effort to optimize? Nah. Maybe if you're calling it thousands of times a second, but if performance is that important then you should consider calling native code written in C/C++ to do the work.
In my experience readability and maintainability are almost always more important than optimizing for a few microseconds gain in speed. Use functions to make your code readable and to control variable scoping and don't worry about performance.
"Premature optimization is the root of all evil (or at least most of it) in programming." -- Donald Knuth
"A program that doesn't run correctly doesn't need to run fast" -- Me
You can join a table to itself as many times as you require, it is called a self join.
An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.
SELECT a.SelfJoinTableID
FROM dbo.SelfJoinTable a
INNER JOIN dbo.SelfJoinTable b
ON a.SelfJoinTableID = b.SelfJoinTableID
INNER JOIN dbo.SelfJoinTable c
ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE a.Status = 'Status to filter a'
AND b.Status = 'Status to filter b'
AND c.Status = 'Status to filter c'
EncodedParams variable is redefined as params variable will not work. You need to have same predefined call to variable, otherwise it looks possible with a little more work. Cheers! json is not used to its full capabilities in php there are better ways to call json which I don't recall at the moment.
For z-index to work, you also need to give it a position:
header {
width: 100%;
height: 100px;
background: url(../img/top.png) repeat-x;
z-index: 110;
position: relative;
}
I've answered that here: (WAMP/XAMP) send Mail using SMTP localhost (works not only GMAIL, but for others too).
Use this code:
<div class="hidden"><li><a href="somehwere">Link text</a></li></div>
As of June 2019, if your user's are on iOS 13 the cellular download limit has been lifted. User's just get a warning now. Read here
In case the article is removed here are screen shots of it below
str="abcdef"
str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach
$~ #=> #<MatchData "c">
Hope it helps. :)
<!-- index.php -->
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myForm">
<input type="text" name="fname" id="fname"/>
<input type="submit" name="click" value="button" />
</form>
<script>
$(document).ready(function(){
$(function(){
$("#myForm").submit(function(event){
event.preventDefault();
$.ajax({
method: 'POST',
url: 'submit.php',
dataType: "json",
contentType: "application/json",
data : $('#myForm').serialize(),
success: function(data){
alert(data);
},
error: function(xhr, desc, err){
console.log(err);
}
});
});
});
});
</script>
</body>
</html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>
we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.
If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.
Are you explicitly calling Dispose on their control?
In that case, you don't need to use angular.copy()
Explanation :
=
represents a reference whereas angular.copy()
creates a new object as a deep copy.
Using =
would mean that changing a property of response.data
would change the corresponding property of $scope.example
or vice versa.
Using angular.copy()
the two objects would remain seperate and changes would not reflect on each other.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
You can add element to arrayList using add() method in Kotlin. For example,
arrayList.add(10)
Above code will add element 10 to arrayList.
However, if you are using Array or List, then you can not add element. This is because Array and List are Immutable. If you want to add element, you will have to use MutableList.
Several workarounds:
toMutableList()
method. Then, add element into it.System.arraycopy()
method.It's called dependency injection via constructor injection: class A
gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.
There's an interesting introduction on wikipedia.
For const-correctness I'd write:
using T = int;
class A
{
public:
A(const T &thing) : m_thing(thing) {}
// ...
private:
const T &m_thing;
};
but a problem with this class is that it accepts references to temporary objects:
T t;
A a1{t}; // this is ok, but...
A a2{T()}; // ... this is BAD.
It's better to add (requires C++11 at least):
class A
{
public:
A(const T &thing) : m_thing(thing) {}
A(const T &&) = delete; // prevents rvalue binding
// ...
private:
const T &m_thing;
};
Anyway if you change the constructor:
class A
{
public:
A(const T *thing) : m_thing(*thing) { assert(thing); }
// ...
private:
const T &m_thing;
};
it's pretty much guaranteed that you won't have a pointer to a temporary.
Also, since the constructor takes a pointer, it's clearer to users of A
that they need to pay attention to the lifetime of the object they pass.
Somewhat related topics are:
You should have header files (.h) that contain the function's declaration, then a corresponding .cpp file that contains the definition. You then include the header file everywhere you need it. Note that the .cpp file that contains the definitions also needs to include (it's corresponding) header file.
// main.cpp
#include "second.h"
int main () {
secondFunction();
}
// second.h
void secondFunction();
// second.cpp
#include "second.h"
void secondFunction() {
// do stuff
}
Since I often come here and then wondering how to use the brackets, this answer might be useful for those like me.
EXEC sp_rename '[DB].[dbo].[Tablename].OldColumnName', 'NewColumnName', 'COLUMN';
OldColumnName
must not be in []
. It will not work.NewColumnName
into []
, it will result into [[NewColumnName]]
.Here is a POSIX version that combines many of the previous answers to deliver following features:
Here is the code and some test cases:
import threading
import signal
import os
import time
class TerminateExecution(Exception):
"""
Exception to indicate that execution has exceeded the preset running time.
"""
def quit_function(pid):
# Killing all subprocesses
os.setpgrp()
os.killpg(0, signal.SIGTERM)
# Killing the main thread
os.kill(pid, signal.SIGTERM)
def handle_term(signum, frame):
raise TerminateExecution()
def invoke_with_timeout(timeout, fn, *args, **kwargs):
# Setting a sigterm handler and initiating a timer
old_handler = signal.signal(signal.SIGTERM, handle_term)
timer = threading.Timer(timeout, quit_function, args=[os.getpid()])
terminate = False
# Executing the function
timer.start()
try:
result = fn(*args, **kwargs)
except TerminateExecution:
terminate = True
finally:
# Restoring original handler and cancel timer
signal.signal(signal.SIGTERM, old_handler)
timer.cancel()
if terminate:
raise BaseException("xxx")
return result
### Test cases
def countdown(n):
print('countdown started', flush=True)
for i in range(n, -1, -1):
print(i, end=', ', flush=True)
time.sleep(1)
print('countdown finished')
return 1337
def really_long_function():
time.sleep(10)
def really_long_function2():
os.system("sleep 787")
# Checking that we can run a function as expected.
assert invoke_with_timeout(3, countdown, 1) == 1337
# Testing various scenarios
t1 = time.time()
try:
print(invoke_with_timeout(1, countdown, 3))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function2))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
t1 = time.time()
try:
print(invoke_with_timeout(1, really_long_function))
assert(False)
except BaseException:
assert(time.time() - t1 < 1.1)
print("All good", time.time() - t1)
# Checking that classes are referenced and not
# copied (as would be the case with multiprocessing)
class X:
def __init__(self):
self.value = 0
def set(self, v):
self.value = v
x = X()
invoke_with_timeout(2, x.set, 9)
assert x.value == 9
Swift 4
enum ImageFormat {
case png
case jpeg(CGFloat)
}
extension UIImage {
func base64(format: ImageFormat) -> String? {
var imageData: Data?
switch format {
case .png: imageData = UIImagePNGRepresentation(self)
case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
}
return imageData?.base64EncodedString()
}
}
extension String {
func imageFromBase64() -> UIImage? {
guard let data = Data(base64Encoded: self) else { return nil }
return UIImage(data: data)
}
}
You should definitely have a look at this answer of mine:
and also have a look at all the links included therein.
Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.
If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:
$(document).ready(function() {
$("[id^=content]").hover(function() {
$(this).addClass('transition');
}, function() {
$(this).removeClass('transition');
});
});
Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.
Simple solution if you are using C++11. Probably O(1) time as well:
st.pop_back();
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
It turns out, I was using the fetch
method incorrectly.
fetch
expects two parameters: an endpoint to the API, and an optional object which can contain body and headers.
I was wrapping the intended object within a second object, which did not get me any desired result.
Here's how it looks on a high level:
fetch('API_ENDPOINT', OBJECT)
.then(function(res) {
return res.json();
})
.then(function(resJson) {
return resJson;
})
I structured my object as such:
var obj = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Origin': '',
'Host': 'api.producthunt.com'
},
body: JSON.stringify({
'client_id': '(API KEY)',
'client_secret': '(API SECRET)',
'grant_type': 'client_credentials'
})
Heres a Swift version:
// MARK: Gesture Extensions
extension UIView {
func addTapGesture(#tapNumber: Int, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer (target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
func addTapGesture(#tapNumber: Int, action: ((UITapGestureRecognizer)->())?) {
let tap = BlockTap (tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
}
}
This can be helpful:
<input type="text" name="username" value="admin" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
Update:
and if want to disable from tab index you can use it this way:
<input type="text" name="username" value="admin" tabindex="-1" >
<style type="text/css">
input[name=username] {
pointer-events: none;
}
</style>
Here's an alternate way of finding height. Add an additional attribute to your node called height:
class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}
Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:
int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;
q.Enqueue(root);
while(q.Count > 0)
{
lastnode = q.Dequeue();
if (lastnode.left != null){
lastnode.left.height = lastnode.height + 1;
q.Enqueue(lastnode.left);
}
if (lastnode.right != null){
lastnode.right.height = lastnode.height + 1;
q.Enqueue(lastnode.right);
}
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}
Cheers,
There is a comparison of the features and performance of RabbitMQ ActiveMQ and QPID given at
http://bhavin.directi.com/rabbitmq-vs-apache-activemq-vs-apache-qpid/
Personally I have tried all the above three. RabbitMQ is the best performance wise according to me, but it does not have failover and recovery options. ActiveMQ has the most features, but is slower.
Update : HornetQ is also an option you can look into, it is JMS Complaint, a better option than ActiveMQ if you are looking for a JMS based solution.
use a FileWriter instead.
FileWriter(File file, boolean append)
the second argument in the constructor tells the FileWriter to append any given input to the file rather than overwriting it.
here is some code for your example:
File log = new File("log.txt")
try{
if(!log.exists()){
System.out.println("We had to make a new file.");
log.createNewFile();
}
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("******* " + timeStamp.toString() +"******* " + "\n");
bufferedWriter.close();
System.out.println("Done");
} catch(IOException e) {
System.out.println("COULD NOT LOG!!");
}
In the action method of the request to the url "http://localhost:85458/api/ctrl/"
var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;
this will get you http://localhost:85458
I had the same error, but for me, it was attributed to having a database and a table that were named the same. When I added the ADO .NET Entity Object to my project, it misgenerated what I wanted in my database context file:
// Table
public virtual DbSet<OBJ> OBJs { get; set; }
which should've been:
public virtual DbSet<OBJ> OBJ { get; set; }
And
// Database?
public object OBJ { get; internal set; }
which I actually didn't really need, so I commented it out.
I was trying to pull in my table like this, in my controller, when I got my error:
protected Model1 db = new Model1();
public ActionResult Index()
{
var obj =
from p in db.OBJ
orderby p.OBJ_ID descending
select p;
return View(obj);
}
I corrected my database context and all was fine, after that.
Install firebug and use console.log
instead of alert
. Then you will see the exact element your accessing.
Sessions are stored on the server and are set from server side code, not client side code such as JavaScript.
What you want is a cookie, someone's given a brilliant explanation in this Stack Overflow question here: How do I set/unset cookie with jQuery?
You could potentially use sessions and set/retrieve them with jQuery and AJAX, but it's complete overkill if Cookies will do the trick.
Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.
Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.
If you are comparing schemas on the same database then try:
select * from dba_objects
where schema_name = 'ASCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects
where schema_name = 'BSCHEMA'
and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
and switch around the orders of ASCHEMA and BSCHEMA.
If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas
For the ones who are getting the error while requesting JSON data:
If your are requesting JSON data, the JSON might be too large and that what cause the error to happen.
My solution is to copy the request link to new tab (get
request from browser)
copy the data to JSON viewer online where you have auto parsing and work on it there.
But as your system grows in size and functionality... i think that returning always a json is not a bad idea at all. Is more a architectural / "big scale design" matter.
You can think about returing always a JSON with two know fields : code and data. Where code is a numeric code specifying the success of the operation to be done and data is any aditional data related with the operation / service requested.
Come on, when we use a backend a service provider, any service can be checked to see if it worked well.
So i stick, to not let spring manage this, exposing hybrid returning operations (Some returns data other nothing...).. instaed make sure that your server expose a more homogeneous interface. Is more simple at the end of the day.
You could modify .adm
and add
.adm{
clear:both;
}
That should make it move to a new line
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
I found the log file at /usr/local/var/log/postgres.log on a mac installation from brew.
Templates. I think that is Smarty syntax.
public void selectImageAndResize(){
int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
if (returnVal == jFileChooser.APPROVE_OPTION) { //select image
File file = jFileChooser.getSelectedFile(); //get the image
BufferedImage bi;
try {
//
//transforms selected file to buffer
//
bi=ImageIO.read(file);
ImageIcon iconimage = new ImageIcon(bi);
//
//get image dimensions
//
BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
iconimage.paintIcon(null, g, 0,0);
g.dispose();
//
//resize image according to jlabel
//
BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight());
ImageIcon resizedicon=new ImageIcon(resizedimage);
jLabel2.setIcon(resizedicon);
} catch (Exception ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
}
else {
System.out.println("File access cancelled by user.");
}
}
PHP_EOL (string) The correct 'End Of Line' symbol for this platform. Available since PHP 4.3.10 and PHP 5.0.2
You can use this constant when you read or write text files on the server's filesystem.
Line endings do not matter in most cases as most software are capable of handling text files regardless of their origin. You ought to be consistent with your code.
If line endings matter, explicitly specify the line endings instead of using the constant. For example:
\r\n
\r\n
as row separatorThis is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.
I am not aware of anything in the standard library. However, you could use something like:
def mean(numbers):
return float(sum(numbers)) / max(len(numbers), 1)
>>> mean([1,2,3,4])
2.5
>>> mean([])
0.0
In numpy, there's numpy.mean()
.
Possible solution:
var tasks = dataList
.Select(data => Task.Factory.StartNew(arg => DoThreadStuff(data), TaskContinuationOptions.LongRunning | TaskContinuationOptions.PreferFairness))
.ToArray();
var timeout = TimeSpan.FromMinutes(1);
Task.WaitAll(tasks, timeout);
Assuming dataList is the list of items and each item needs to be processed in a separate thread.
I am not 100% sure if this works all the time, but in my application this gives me the expected behavior.
Lets say you are on ABOUT page and you have the following route:
yourApp.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/about', {
templateUrl: 'about.html',
controller: 'AboutCtrl'
}).
otherwise({
redirectTo: '/'
});
}
]);
Now, in you HTML
<ul>
<li><a href="#/about#tab1">First Part</a></li>
<li><a href="#/about#tab2">Second Part</a></li>
<li><a href="#/about#tab3">Third Part</a></li>
</ul>
<div id="tab1">1</div>
<div id="tab2">2</div>
<div id="tab3">3</div>
In conclusion
Including the page name before the anchor did the trick for me. Let me know about your thoughts.
Downside
This will re-render the page and then scroll to the anchor.
UPDATE
A better way is to add the following:
<a href="#tab1" onclick="return false;">First Part</a>
Related question: What is the best way to access unknown array elements without generating PHP notice?
Using the answer from the question above, you can safely get a value from $_POST without generating PHP notice if the key does not exists.
echo _arr($_POST, 'username', 'no username supplied');
// will print $_POST['username'] or 'no username supplied'
Maybe this can help you
Cursor c = db.rawQuery("query",null);
int id[] = new int[c.getCount()];
int i = 0;
if (c.getCount() > 0)
{
c.moveToFirst();
do {
id[i] = c.getInt(c.getColumnIndex("field_name"));
i++;
} while (c.moveToNext());
c.close();
}
You can create a trigger which updates NoofUses
column in Coupon
table whenever
couponid
is used in CouponUse
table
query :
CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end
Maybe you should try it with -quality 100 -size "1024x1024", because resize often gives results that are ugly to view.
if you are using .bind(this), try this:
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
$(this.pagination).find("a").on('click', function(evt) {
let index = Array.from(evt.target.parentElement.children).indexOf(evt.target);
this.goTo(index);
}.bind(this))
You can use css ellipsis;
but you have to give fixed width and overflow:hidden:
to that element.
<span style="display:block;text-overflow: ellipsis;width: 200px;overflow: hidden; white-space: nowrap;">_x000D_
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat._x000D_
</span>
_x000D_
Efficient can mean throughput or latency.
For throughout, see the answer by Anders Cedronius, it’s a good one.
For lower latency, I would recommend this code:
uint32_t reverseBits( uint32_t x )
{
#if defined(__arm__) || defined(__aarch64__)
__asm__( "rbit %0, %1" : "=r" ( x ) : "r" ( x ) );
return x;
#endif
// Flip pairwise
x = ( ( x & 0x55555555 ) << 1 ) | ( ( x & 0xAAAAAAAA ) >> 1 );
// Flip pairs
x = ( ( x & 0x33333333 ) << 2 ) | ( ( x & 0xCCCCCCCC ) >> 2 );
// Flip nibbles
x = ( ( x & 0x0F0F0F0F ) << 4 ) | ( ( x & 0xF0F0F0F0 ) >> 4 );
// Flip bytes. CPUs have an instruction for that, pretty fast one.
#ifdef _MSC_VER
return _byteswap_ulong( x );
#elif defined(__INTEL_COMPILER)
return (uint32_t)_bswap( (int)x );
#else
// Assuming gcc or clang
return __builtin_bswap32( x );
#endif
}
Compilers output: https://godbolt.org/z/5ehd89
This enables you to write something like:
void doSomething() {
List<String>list = new ArrayList<String>();
//do something
}
Later on, you might want to change it to:
void doSomething() {
List<String>list = new LinkedList<String>();
//do something
}
without having to change the rest of the method.
However, if you want to use a CopyOnWriteArrayList
for example, you would need to declare it as such, and not as a List if you wanted to use its extra methods (addIfAbsent for example):
void doSomething() {
CopyOnWriteArrayList<String>list = new CopyOnWriteArrayList<String>();
//do something, for example:
list.addIfAbsent("abc");
}
From the document.getElementsByTagName
I guess you are running the javascript in a browser.
The traditional way to expose functionality to javascript running in the browser is calling a remote URL using AJAX. The X in AJAX is for XML, but nowadays everybody uses JSON instead of XML.
For example, using jQuery you can do something like:
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
You will need to implement a python webservice on the server side. For simple webservices I like to use Flask.
A typical implementation looks like:
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
You can run IronPython (kind of Python.Net) in the browser with silverlight, but I don't know if NLTK is available for IronPython.
You mentioned that you're interested in the equality of the contents of the list (and didn't mention order). So containsExactlyInAnyOrder
from AssertJ is a good fit. It comes packaged with spring-boot-starter-test
, for example.
From the AssertJ docs ListAssert#containsExactlyInAnyOrder:
Verifies that the actual group contains exactly the given values and nothing else, in any order. Example:
// an Iterable is used in the example but it would also work with an array
Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);
// assertion will pass
assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);
// assertion will fail as vilya is contained twice in elvesRings.
assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);
According to the documentation.
If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.
You can check what all devices are used by tensorflow by -
from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())
Also as suggested in this answer
import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.
If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.
pip install tensorflow-gpu
As Kevin Haines points out, ints have the natural size suggested by the execution environment, which has to fit within INT_MIN and INT_MAX.
The C89 standard states that UINT_MAX
should be at least 2^16-1, USHRT_MAX
2^16-1 and ULONG_MAX
2^32-1 . That makes a bit-count of at least 16 for short and int, and 32 for long. For char it states explicitly that it should have at least 8 bits (CHAR_BIT
).
C++ inherits those rules for the limits.h file, so in C++ we have the same fundamental requirements for those values.
You should however not derive from that that int is at least 2 byte. Theoretically, char, int and long could all be 1 byte, in which case CHAR_BIT
must be at least 32. Just remember that "byte" is always the size of a char, so if char is bigger, a byte is not only 8 bits any more.
You have to manually copy each key/value pair to a new map
. This is a loop that people have to reprogram any time they want a deep copy of a map
.
You can automatically generate the function for this by installing mapper
from the maps
package using
go get -u github.com/drgrib/maps/cmd/mapper
and running
mapper -types string:aStruct
which will generate the file map_float_astruct.go
containing not only a (deep) Copy
for your map but also other "missing" map
functions ContainsKey
, ContainsValue
, GetKeys
, and GetValues
:
func ContainsKeyStringAStruct(m map[string]aStruct, k string) bool {
_, ok := m[k]
return ok
}
func ContainsValueStringAStruct(m map[string]aStruct, v aStruct) bool {
for _, mValue := range m {
if mValue == v {
return true
}
}
return false
}
func GetKeysStringAStruct(m map[string]aStruct) []string {
keys := []string{}
for k, _ := range m {
keys = append(keys, k)
}
return keys
}
func GetValuesStringAStruct(m map[string]aStruct) []aStruct {
values := []aStruct{}
for _, v := range m {
values = append(values, v)
}
return values
}
func CopyStringAStruct(m map[string]aStruct) map[string]aStruct {
copyMap := map[string]aStruct{}
for k, v := range m {
copyMap[k] = v
}
return copyMap
}
Full disclosure: I am the creator of this tool. I created it and its containing package because I found myself constantly rewriting these algorithms for the Go map
for different type combinations.
Since 10gR2, Oracle allows to fine-tune the behaviour of string comparisons by setting the NLS_COMP
and NLS_SORT
session parameters:
SQL> SET HEADING OFF
SQL> SELECT *
2 FROM NLS_SESSION_PARAMETERS
3 WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');
NLS_SORT
BINARY
NLS_COMP
BINARY
SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
2 FROM DUAL;
0
SQL>
SQL> ALTER SESSION SET NLS_COMP=LINGUISTIC;
Session altered.
SQL> ALTER SESSION SET NLS_SORT=BINARY_CI;
Session altered.
SQL>
SQL> SELECT *
2 FROM NLS_SESSION_PARAMETERS
3 WHERE PARAMETER IN ('NLS_COMP', 'NLS_SORT');
NLS_SORT
BINARY_CI
NLS_COMP
LINGUISTIC
SQL>
SQL> SELECT CASE WHEN 'abc'='ABC' THEN 1 ELSE 0 END AS GOT_MATCH
2 FROM DUAL;
1
You can also create case insensitive indexes:
create index
nlsci1_gen_person
on
MY_PERSON
(NLSSORT
(PERSON_LAST_NAME, 'NLS_SORT=BINARY_CI')
)
;
This information was taken from Oracle case insensitive searches. The article mentions REGEXP_LIKE
but it seems to work with good old =
as well.
In versions older than 10gR2 it can't really be done and the usual approach, if you don't need accent-insensitive search, is to just UPPER()
both the column and the search expression.
val = -3.1234
fraction = abs(val - as.integer(val) )
"\n"
is not working everywhere!For example in email, it adds the exact "\n" into the text instead of a new line if you use it in the custom keyboard like: textDocumentProxy.insertText("\n")
There are another newLine characters available but I can't just simply paste them here (Because they make a new lines).
using this extension:
extension CharacterSet {
var allCharacters: [Character] {
var result: [Character] = []
for plane: UInt8 in 0...16 where self.hasMember(inPlane: plane) {
for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
if let uniChar = UnicodeScalar(unicode), self.contains(uniChar) {
result.append(Character(uniChar))
}
}
}
return result
}
}
you can access all characters in any CharacterSet
. There is a character set called newlines
. Use one of them to fulfill your requirements:
let newlines = CharacterSet.newlines.allCharacters
for newLine in newlines {
print("Hello World \(newLine) This is a new line")
}
Then store the one you tested and worked everywhere and use it anywhere. Note that you can't relay on the index of the character set. It may change.
But most of the times "\n"
just works as expected.
I just thought I would recommend Ninja IDE, open source and all.. I use it for all my Python development now days when I got a GUI to work with and looks the same when I am on my Windows and Linux machines.
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
You may use this command for listing the files for your own debuggable apk:
adb shell run-as com.corp.appName ls /data/data/com.corp.appName/cache
And this script for pulling from cache:
#!/bin/sh
adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"
Then you can pull a file from cache like this:
./pull.sh cache/someCachedData.txt
Root is not required.
All Elements
$('#tabla > tbody > tr').each(function() {
$(this).find("td:gt(0)").each(function(){
alert($(this).html());
});
});
Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.
Dim I, J, K, L As Integer
Dim K1, L1 As String
K1 = K
L1 = L
Cells(2, 1) = K1 & " - uploaded"
Cells(3, 1) = L1 & " - expanded"
MsgBox "records uploaded " & K & " records expanded " & L
The escape code "
can also be used instead of "
.
Just use "justify-content-center" in the row's class attribute.
<div class="container">
<div class="row justify-content-center">
<h1>This is a header</h1>
</div>
</div>
addClass(element, className1, className2){
element.classList.add(className1, className2);
}
removeClass(element, className1, className2) {
element.classList.remove(className1, className2);
}
removeClass(myElement, 'myClass1', 'myClass2');
addClass(myElement, 'myClass1', 'myClass2');
Just for anybody who is interested. I was working on an iOS project that required similar functionality so I ended porting the answer by @jeznag to swift
private func addMinutesToDate(minutes: Int, beforeDate: NSDate) -> NSDate {
var SIXTY_SECONDS = 60
var m = (Double) (minutes * SIXTY_SECONDS)
var c = beforeDate.timeIntervalSince1970 + m
var newDate = NSDate(timeIntervalSince1970: c)
return newDate
}
Thats quite simple. For example, here is a random code of mine:
function news_get_by_id ( $news_id )
{
$this->db->select('*');
$this->db->select("DATE_FORMAT( date, '%d.%m.%Y' ) as date_human", FALSE );
$this->db->select("DATE_FORMAT( date, '%H:%i') as time_human", FALSE );
$this->db->from('news');
$this->db->where('news_id', $news_id );
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->row_array();
return $row;
}
}
This will return the "row" you selected as an array so you can access it like:
$array = news_get_by_id ( 1 );
echo $array['date_human'];
I also would strongly advise, not to chain the query like you do. Always have them separately like in my code, which is clearly a lot easier to read.
Please also note that if you specify the table name in from(), you call the get() function without a parameter.
If you did not understand, feel free to ask :)
Table structure...very basic:
create table tabla(ID int, Stuff varchar (50));
insert into tabla values(1, '32.43');
insert into tabla values(2, '43.33');
insert into tabla values(3, '23.22');
Query:
SELECT SUM(cast(Stuff as decimal(4,2))) as result FROM tabla
Or, try this:
SELECT SUM(cast(isnull(Stuff,0) as decimal(12,2))) as result FROM tabla
Working on SQLServer 2008
The modify()
method that can be used to add increments to an existing DateTime
value.
Create a new DateTime
object with the current date and time:
$due_dt = new DateTime();
Once you have the DateTime
object, you can manipulate its value by adding or subtracting time periods:
$due_dt->modify('+1 day');
You can read more on the PHP Manual.
On OpenWRT the only way to reliably do this, at least for me, is by running these commands:
# Get switch name
swconfig list
# assuming switch name is "switch0"
swconfig dev switch0 show | grep link:
# Possible output
root@OpenWrt:~# swconfig dev switch0 show | grep link:
link: port:0 link:up speed:1000baseT full-duplex txflow rxflow
link: port:1 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
link: port:2 link:up speed:1000baseT full-duplex txflow rxflow eee100 eee1000 auto
link: port:3 link:down
link: port:4 link:up speed:1000baseT full-duplex eee100 eee1000 auto
link: port:5 link:down
link: port:6 link:up speed:1000baseT full-duplex txflow rxflow
This will show either "link:down" or "link:up" on every port of your switch.
Update 2013-01-07: If you want to see a good mix of component-based game engine with the (in my opinion) superior approach of reactive programming take a look at the V-Play engine. It very well integrates QTs QML property binding functionality.
We did some research on CBSE in games at our university and I collected some material over the years:
CBSE in games literature:
A very good and clean example of a component-based game-engine in C# is the Elephant game framework.
If you really want to know what components are read: Component-based Software Engineering! They define a component as:
A software component is a software element that conforms to a component model and can be independently deployed and composed without modification according to a composition standard.
A component model defines specific interaction and composition standards. A component model implementation is the dedicated set of executable software elements required to support the execution of components that conform to the model.
A software component infrastructure is a set of interacting software components designed to ensure that a software system or subsystem constructed using those components and interfaces will satisfy clearly defined performance specifications.
My opinions after 2 years of experience with CBSE in games thought are that object-oriented programming is simply a dead-end. Remember my warning as you watch your components become smaller and smaller, and more like functions packed in components with a lot of useless overhead. Use functional-reactive programming instead. Also take a look at my fresh blog post (which lead me to this question while writing it :)) about Why I switched from component-based game engine architecture to FRP.
CBSE in games papers:
CBSE in games web-links (sorted by relevancy):
Use import javax.persistence.Entity; Instead of import org.hibernate.annotations.Entity;
use this:
this.permissionChanged = function (obj, event) {
if (event.type != "load") {
}
}
use inline-block
instead of inline
. Read more information here about the difference between inline and inline-block.
.inline {
display: inline-block;
border: 1px solid red;
margin:10px;
}
Simple and best code:
def max_occ(lst,x):
count=0
for i in lst:
if (i==x):
count=count+1
return count
lst=[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]
x=max(lst,key=lst.count)
print(x,"occurs ",max_occ(lst,x),"times")
Output: 4 occurs 6 times
Assuming you don't want to create another class, you can always let the deserializer give you a dictionary of key-value-pairs, like so:
string s = //{ "user" : { "id" : 12345, "screen_name" : "twitpicuser"}};
var serializer = new JavaScriptSerializer();
var result = serializer.DeserializeObject(s);
You'll get back something, where you can do:
var userId = int.Parse(result["user"]["id"]); // or (int)result["user"]["id"] depending on how the JSON is serialized.
// etc.
Look at result
in the debugger to see, what's in there.
You could change the @RequestParam type to an Integer and make it not required. This would allow your request to succeed, but it would then be null. You could explicitly set it to your default value in the controller method:
@RequestMapping(value = "/test", method = RequestMethod.POST)
@ResponseBody
public void test(@RequestParam(value = "i", required=false) Integer i) {
if(i == null) {
i = 10;
}
// ...
}
I have removed the defaultValue from the example above, but you may want to include it if you expect to receive requests where it isn't set at all:
http://example.com/test
Just Go to Model file of the corresponding Controller and check the primary key filed name
such as
protected $primaryKey = 'info_id';
here info id is field name available in database table
More info can be found at "Primary Keys" section of the docs.
From the docs of the flush
method:
Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.
The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.
findAny
& orElse
By using findAny()
and orElse()
:
Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);
Stops looking after finding an occurrence.
findAny
Optional<T> findAny()
Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)
using from ListSelectionModel
:
ListSelectionModel cellSelectionModel = table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String selectedData = null;
int[] selectedRow = table.getSelectedRows();
int[] selectedColumns = table.getSelectedColumns();
for (int i = 0; i < selectedRow.length; i++) {
for (int j = 0; j < selectedColumns.length; j++) {
selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
}
}
System.out.println("Selected: " + selectedData);
}
});
If I understand you correctly, you can use a combination of Series.isin()
and DataFrame.append()
:
In [80]: df1
Out[80]:
rating user_id
0 2 0x21abL
1 1 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
5 2 0x21abL
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
9 1 0x21abL
In [81]: df2
Out[81]:
rating user_id
0 2 0x1d14L
1 1 0xdbdcad7
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
5 1 0x5734a81e2
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
9 4 0x5734a81e2
In [82]: ind = df2.user_id.isin(df1.user_id) & df1.user_id.isin(df2.user_id)
In [83]: ind
Out[83]:
0 True
1 False
2 True
3 True
4 True
5 False
6 True
7 True
8 True
9 False
Name: user_id, dtype: bool
In [84]: df1[ind].append(df2[ind])
Out[84]:
rating user_id
0 2 0x21abL
2 1 0xdafL
3 0 0x21abL
4 4 0x1d14L
6 1 0x21abL
7 0 0xdafL
8 4 0x1d14L
0 2 0x1d14L
2 1 0x21abL
3 3 0x21abL
4 3 0x21abL
6 2 0x1d14L
7 0 0xdafL
8 0 0x1d14L
This is essentially the algorithm you described as "clunky", using idiomatic pandas
methods. Note the duplicate row indices. Also, note that this won't give you the expected output if df1
and df2
have no overlapping row indices, i.e., if
In [93]: df1.index & df2.index
Out[93]: Int64Index([], dtype='int64')
In fact, it won't give the expected output if their row indices are not equal.
Your going to need CURL for that task I'm afraid. Nice easy way to do it here: http://davidwalsh.name/execute-http-post-php-curl
Hope that helps
//add cookie
var panelIdCookie = new HttpCookie("panelIdCookie");
panelIdCookie.Values.Add("panelId", panelId.ToString(CultureInfo.InvariantCulture));
panelIdCookie.Expires = DateTime.Now.AddMonths(2);
Response.Cookies.Add(panelIdCookie);
//read cookie
var httpCookie = Request.Cookies["panelIdCookie"];
if (httpCookie != null)
{
panelId = Convert.ToInt32(httpCookie["panelId"]);
}
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
You can start your application as administrator if you add Application Manifest to your project.
Just Add New Item to your project and select "Application Manifest File". Change the <requestedExecutionLevel>
element to:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This code is perfect for me:
this.context.beginPath();
this.context.moveTo(data[0].x, data[0].y);
for (let i = 1; i < data.length; i++) {
this.context.bezierCurveTo(
data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
data[i - 1].y,
data[i - 1].x + (data[i].x - data[i - 1].x) / 2,
data[i].y,
data[i].x,
data[i].y);
}
you have correct smooth line and correct endPoints NOTICE! (y = "canvas height" - y);
The for loop iterates over the elements of the array, not its indexes. Suppose you have a list ar = [2, 4, 6]:
When you iterate over it with for i in ar:
the values of i will be 2, 4 and 6. So, when you try to access ar[i]
for the first value, it might work (as the last position of the list is 2, a[2] equals 6), but not for the latter values, as a[4] does not exist.
If you intend to use indexes anyhow, try using for index, value in enumerate(ar):
, then theSum = theSum + ar[index]
should work just fine.
if you have many networks attached to you OS, yo must especify one of this network in the bind-addres from my.conf file. an example:
[mysqld]
bind-address = 127.100.10.234
this ip is from a ethX configuration.
well If you have 150 columns then I think that UNPIVOT is not an option. So you could use xml trick
;with CTE1 as (
select ID, EntityID, (select t.* for xml raw('row'), type) as Data
from temp1 as t
), CTE2 as (
select
C.id, C.EntityID,
F.C.value('local-name(.)', 'nvarchar(128)') as IndicatorName,
F.C.value('.', 'nvarchar(max)') as IndicatorValue
from CTE1 as c
outer apply c.Data.nodes('row/@*') as F(C)
)
select * from CTE2 where IndicatorName like 'Indicator%'
You could also write dynamic SQL, but I like xml more - for dynamic SQL you have to have permissions to select data directly from table and that's not always an option.
UPDATE
As there a big flame in comments, I think I'll add some pros and cons of xml/dynamic SQL. I'll try to be as objective as I could and not mention elegantness and uglyness. If you got any other pros and cons, edit the answer or write in comments
cons
pros
inserted
and deleted
tables inside your trigger (not possible with dynamic at all);Is this what you are looking for ?
Sub getRowCol()
Range("A1").Select ' example
Dim col, row
col = Split(Selection.Address, "$")(1)
row = Split(Selection.Address, "$")(2)
MsgBox "Column is : " & col
MsgBox "Row is : " & row
End Sub
I came here for a reminder of how to set up the query but the existing examples were hard to follow. Here is an example with more explanation.
SQLiteDatabase db = helper.getReadableDatabase();
String table = "table2";
String[] columns = {"column1", "column3"};
String selection = "column3 =?";
String[] selectionArgs = {"apple"};
String groupBy = null;
String having = null;
String orderBy = "column3 DESC";
String limit = "10";
Cursor cursor = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
Parameters
table
: the name of the table you want to querycolumns
: the column names that you want returned. Don't return data that you don't need.selection
: the row data that you want returned from the columns (This is the WHERE clause.)selectionArgs
: This is substituted for the ?
in the selection
String above.groupBy
and having
: This groups duplicate data in a column with data having certain conditions. Any unneeded parameters can be set to null.orderBy
: sort the datalimit
: limit the number of results to return1) What is the difference between both the way of creating class objects.
a) pointer
Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:
delete example;
b) Simple declaration
Example example;
you get a variable, not a pointer, and it will be destroyed out of scope it was declared.
2) Singleton C++
This SO question may helps you
Make sure you have this code on you component:
export class Component {
checked = true;
}
A more modern version of kaiido's answer using fetch would be:
function toObjectUrl(url) {
return fetch(url)
.then((response)=> {
return response.blob();
})
.then(blob=> {
return URL.createObjectURL(blob);
});
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.
You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602
The reseting input file is on very single
$('input[type=file]').val(null);
If you bind reset the file in change other field of the form, or load form with ajax.
This example is applicable
selector for example is $('input[type=text]')
or any element of the form
event click
, change
, or any event
$('body').delegate('event', 'selector', function(){
$('input[type=file]').val(null) ;
});
As mentioned by others in the comments, a really simple solution to this issue is to declare the database 'host' within the database configuration. Adding this answer just to make it a little more clear for anyone reading this.
In a Ruby on Rails app for example, edit /config/database.yml:
development:
adapter: postgresql
encoding: unicode
database: database_name
pool: 5
host: localhost
Note: the last line added to specify the host. Prior to updating to Yosemite I never needed to specify the host in this way.
Hope this helps someone.
Cheers
Vue by default ships with the v-html directive to show it, you bind it onto the element itself rather than using the normal moustache binding for string variables.
So for your specific example you would need:
<div id="logapp">
<table>
<tbody>
<tr v-repeat="logs">
<td v-html="fail"></td>
<td v-html="type"></td>
<td v-html="description"></td>
<td v-html="stamp"></td>
<td v-html="id"></td>
</tr>
</tbody>
</table>
</div>
There is no functional or performance difference between the two. Use whichever syntax appeals to you.
It's just like the use of AS and IS when declaring a function or procedure. They are completely interchangeable.
Please consider the follwing codes:
from numpy import zeros
scores = zeros((len(chain1),len(chain2)), float)
I'm sure this could help to some degree cxx checker. Also this tool seems to be pretty good KWStyle It's from Kitware, the guys who develop Cmake.
You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.
The string representation of a float doesn't work this way. For example, repr(1.3)
yields '1.3'
, but repr(1.33)
yields '1.3300000000000001'
.
A accurate string representation of a floating point number produces a variable length string.
Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.
If you use x.astype('str')
, it will always convert things to an array of strings of length 1.
For example, using x = np.array(1.344566)
, x.astype('str')
yields '1'
!
You need to be more explict and use the '|Sx'
dtype syntax, where x
is the length of the string for each element of the array.
For example, use x.astype('|S10')
to convert the array to strings of length 10.
Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...
<div id="invocieContainer">
<div class="row">
...Your html Page content here....
</div>
</div>
<script src="/Scripts/printThis.js"></script>
<script>
$(document).on("click", "#btnPrint", function(e) {
e.preventDefault();
e.stopPropagation();
$("#invocieContainer").printThis({
debug: false, // show the iframe for debugging
importCSS: true, // import page CSS
importStyle: true, // import style tags
printContainer: true, // grab outer container as well as the contents of the selector
loadCSS: "/Content/bootstrap.min.css", // path to additional css file - us an array [] for multiple
pageTitle: "", // add title to print page
removeInline: false, // remove all inline styles from print elements
printDelay: 333, // variable print delay; depending on complexity a higher value may be necessary
header: null, // prefix to html
formValues: true // preserve input/form values
});
});
</script>
For printThis.js souce code, copy and pase below URL in new tab https://raw.githubusercontent.com/jasonday/printThis/master/printThis.js
in 1.x there used to be things DataTables couldn't do which DataSets could (don't remember exactly what). All that was changed in 2.x. My guess is that's why a lot of examples still use DataSets. DataTables should be quicker as they are more lightweight. If you're only pulling a single resultset, its your best choice between the two.
You don't have to use atan2 to calculate the angle between two vectors. If you just want the quickest way, you can use dot(v1, v2)=|v1|*|v2|*cos A
to get
A = Math.acos( dot(v1, v2)/(v1.length()*v2.length()) );
Another implementation, using Array.reduce (I think it’s the only one missing!):
const splitArray = (arr, size) =>
{
if (size === 0) {
return [];
}
return arr.reduce((split, element, index) => {
index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
return split;
}, []);
};
As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if
block is omitted you get an error, which might be what you want.
The core idea given here seems to me to be the best approach for this problem. Unfortunately, it has received less votes while the later answer that has more votes is not complete (as observed in the comments). Hopefully, the implementation below provides a short and complete solution for truncation.
def trunc(num, digits):_x000D_
l = str(float(num)).split('.')_x000D_
digits = min(len(l[1]), digits)_x000D_
return (l[0]+'.'+l[1][:digits])
_x000D_
which should take care of all corner cases found here and here.
I think that it's good to try to avoid large file commits as being part of the repository (e.g. a database dump might be better off elsewhere), but if one considers the size of the kernel in its repository, you can probably expect to work comfortably with anything smaller in size and less complex than that.
Take a look at the JavaDoc for RestTemplate.
There is the corresponding getForObject
methods that are the HTTP GET equivalents of postForObject
, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.
Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange
methods allow you to provide an HttpEntity
object representing the details of the request (including headers). The execute
methods allow you to specify a RequestCallback
from which you can add the headers upon its invocation.
$(window).load is an event that fires when the DOM and all the content (everything) on the page is fully loaded like CSS, images and frames. One best example is if we want to get the actual image size or to get the details of anything we use it.
$(document).ready() indicates that code in it need to be executed once the DOM got loaded and ready to be manipulated by script. It won't wait for the images to load for executing the jQuery script.
<script type = "text/javascript">
//$(window).load was deprecated in 1.8, and removed in jquery 3.0
// $(window).load(function() {
// alert("$(window).load fired");
// });
$(document).ready(function() {
alert("$(document).ready fired");
});
</script>
$(window).load fired after the $(document).ready().
$(window).load was deprecated in 1.8, and removed in jquery 3.0
Run a custom maven command in Eclipse as follows:
clean install -X
Note: Eclipse prefixes the command with mvn
automatically.
npm start
will run whatever you have defined for the start
command of the scripts
object in your package.json
file.
So if it looks like this:
"scripts": {
"start": "ng serve"
}
Then npm start
will run ng serve
.
Yes you could use an <input type="hidden" />
and set the value of that hidden field in your javascript code so it gets posted with your other form data.
Use IsNumeric Function :
IsNumeric(number)
If you want to validate a phone number you should use a regular expression, for example:
^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{3})$
Or, you could try changing the parameter type to string, then convert the string to an integer in the method. I am new to MVC, but I believe you need nullable objects in your parameter list, how else will the controller indicate that no such parameter was provided? So...
public ActionResult ViewNextItem(string id)...
As explained in the accepted answer, https://stackoverflow.com/a/18665488/4038790, you need to check via a server.
Because there's no reliable way to check this in the browser, I suggest you build yourself a quick server endpoint that you can use to check if any url is loadable via iframe. Once your server is up and running, just send a AJAX request to it to check any url by providing the url in the query string as url
(or whatever your server desires). Here's the server code in NodeJs:
const express = require('express')_x000D_
const app = express()_x000D_
_x000D_
app.get('/checkCanLoadIframeUrl', (req, res) => {_x000D_
const request = require('request')_x000D_
const Q = require('q')_x000D_
_x000D_
return Q.Promise((resolve) => {_x000D_
const url = decodeURIComponent(req.query.url)_x000D_
_x000D_
const deafultTimeout = setTimeout(() => {_x000D_
// Default to false if no response after 10 seconds_x000D_
resolve(false)_x000D_
}, 10000)_x000D_
_x000D_
request({_x000D_
url,_x000D_
jar: true /** Maintain cookies through redirects */_x000D_
})_x000D_
.on('response', (remoteRes) => {_x000D_
const opts = (remoteRes.headers['x-frame-options'] || '').toLowerCase()_x000D_
resolve(!opts || (opts !== 'deny' && opts !== 'sameorigin'))_x000D_
clearTimeout(deafultTimeout)_x000D_
})_x000D_
.on('error', function() {_x000D_
resolve(false)_x000D_
clearTimeout(deafultTimeout)_x000D_
})_x000D_
}).then((result) => {_x000D_
return res.status(200).json(!!result)_x000D_
})_x000D_
})_x000D_
_x000D_
app.listen(process.env.PORT || 3100)
_x000D_
Why not use do something like:
File myRelativeDir = new File("../../foo");
String fullPath = myRelativeDir.getCanonicalPath();
Sting wildCard = fullPath + File.separator + "*.txt";
// now you have a fully qualified path
Then you won't have to worry about relative paths and can do your wildcarding as needed.
and here the fork of the toolkit wich contains the port to 4.O,
https://github.com/jogibear9988/wpftoolkit
it's worked very well to me .
Just consolidating and prepared the single command to address source and docs download...
mvn dependency:sources dependency:resolve -Dclassifier=javadoc
I got here because I was concerned that cr-lfs that I specified in C# strings were not being shown in SQl Server Management Studio query responses.
It turns out, they are there, but are not being displayed.
To "see" the cr-lfs, use the print statement like:
declare @tmp varchar(500)
select @tmp = msgbody from emailssentlog where id=6769;
print @tmp
Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.
View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are
The git merge-base
command can be used to find a common ancestor. So if my_experiment has not been merged into master yet and my_experiment was created from master you could:
git log --oneline `git merge-base my_experiment master`..my_experiment
In my case the issue was there was some process that had locked my keychain access...
Force quit all other apps to make sure keychain access is not locked on your Mac
As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.
If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").
But this function is not intended to reload the browser.
All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).
For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.
Hence the need for the function
history.pushState({},"Results for `Cats`",'url.html?s=cats');
It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.
When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.
If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.
As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.
See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.
I used this
:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top
PHP56
vim /etc/httpd/conf/httpd.conf
LoadModule php5_module libexec/apache/libphp5.so
AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps
Here is another solution.
try
{
(void) std::stoi(myString); //cast to void to ignore the return value
//Success! myString contained an integer
}
catch (const std::logic_error &e)
{
//Failure! myString did not contain an integer
}
you can create a workspace and put folders in that : File > save workspace as and drag and drop your folders in saved workspace
Looking at the sample I guess you mean that a string array is actually an array of HEX representation of bytes, don't you?
If yes, then for each string item I would do the following:
build a byte value, where first char is higher bits and second char is lower ones. E.g.
int byteVal = (firstCharNumber << 4) | secondCharNumber;
if the zipcode field is not a required field then add null=True and blank=True, then run makemigrations and migrate command to successfully reflect the changes in the database.
I create a simple Java application by archetype maven-archetype-quickstar, then revise pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>bar</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>bar</name>
<description>bar</description>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.0-beta3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-server</artifactId>
<version>3.0.0-beta3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-api</artifactId>
<version>3.0.0-beta3</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-firefox-driver</artifactId>
<version>3.0.0-beta3</version>
</dependency>
</dependencies>
<build>
<finalName>bar</finalName>
</build>
</project>
and
package bar;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class AppTest {
/**
* Web driver.
*/
private static WebDriver driver = null;
/**
* Entry point.
*
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// Download "geckodriver.exe" from https://github.com/mozilla/geckodriver/releases
System.setProperty("webdriver.gecko.driver","F:\\geckodriver.exe");
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://localhost:8080/foo/");
String sTitle = driver.getTitle();
System.out.println(sTitle);
}
}
You also use on Mac OS X, Linux: https://github.com/mozilla/geckodriver/releases
and
// On Mac OS X.
System.setProperty("webdriver.gecko.driver", "/Users/donhuvy/Downloads/geckodriver");
You can use JavaScript
:
<script type ="text/javascript">
function WriteToFile(passForm) {
set fso = CreateObject("Scripting.FileSystemObject");
set s = fso.CreateTextFile("C:\test.txt", True);
s.writeline(document.passForm.input1.value);
s.writeline(document.passForm.input2.value);
s.writeline(document.passForm.input3.value);
s.Close();
}
</script>
If this does not work, an alternative is the ActiveX
object:
<script type = "text/javascript">
function WriteToFile(passForm)
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile("C:\\Test.txt", true);
s.WriteLine(document.passForm.input.value);
s.Close();
}
</script>
Unfortunately, the ActiveX
object, to my knowledge, is only supported in IE
.
If you're on Unix,
import signal
...
class Alarm(Exception):
pass
def alarm_handler(signum, frame):
raise Alarm
signal.signal(signal.SIGALRM, alarm_handler)
signal.alarm(5*60) # 5 minutes
try:
stdoutdata, stderrdata = proc.communicate()
signal.alarm(0) # reset the alarm
except Alarm:
print "Oops, taking too long!"
# whatever else
TLDR
A closure is a link between a function and its outer lexical (ie. as-written) environment, such that the identifiers (variables, parameters, function declarations etc) defined within that environment are visible from within the function, regardless of when or from where the function is invoked.
Details
In the terminology of the ECMAScript specification, a closure can be said to be implemented by the [[Environment]]
reference of every function-object, which points to the lexical environment within which the function is defined.
When a function is invoked via the internal [[Call]]
method, the [[Environment]]
reference on the function-object is copied into the outer environment reference of the environment record of the newly-created execution context (stack frame).
In the following example, function f
closes over the lexical environment of the global execution context:
function f() {}
In the following example, function h
closes over the lexical environment of function g
, which, in turn, closes over the lexical environment of the global execution context.
function g() {
function h() {}
}
If an inner function is returned by an outer, then the outer lexical environment will persist after the outer function has returned. This is because the outer lexical environment needs to be available if the inner function is eventually invoked.
In the following example, function j
closes over the lexical environment of function i
, meaning that variable x
is visible from inside function j
, long after function i
has completed execution:
function i() {_x000D_
var x = 'mochacchino'_x000D_
return function j() {_x000D_
console.log('Printing the value of x, from within function j: ', x)_x000D_
}_x000D_
} _x000D_
_x000D_
const k = i()_x000D_
setTimeout(k, 500) // invoke k (which is j) after 500ms
_x000D_
In a closure, the variables in the outer lexical environment themselves are available, not copies.
function l() {_x000D_
var y = 'vanilla';_x000D_
_x000D_
return {_x000D_
setY: function(value) {_x000D_
y = value;_x000D_
},_x000D_
logY: function(value) {_x000D_
console.log('The value of y is: ', y);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
const o = l()_x000D_
o.logY() // The value of y is: vanilla_x000D_
o.setY('chocolate')_x000D_
o.logY() // The value of y is: chocolate
_x000D_
The chain of lexical environments, linked between execution contexts via outer environment references, forms a scope chain and defines the identifiers visible from any given function.
Please note that in an attempt to improve clarity and accuracy, this answer has been substantially changed from the original.
With the magic of user-defined literals, we have yet another solution to this. C++14 added a std::string
literal operator.
using namespace std::string_literals;
auto const x = "\0" "0"s;
Constructs a string of length 2, with a '\0' character (null) followed by a '0' character (the digit zero). I am not sure if it is more or less clear than the initializer_list<char>
constructor approach, but it at least gets rid of the '
and ,
characters.
MS made a COM library called Office Web Components to do this. MSOWC.dll needs to be registered on the server. It can create and manipulate office document files.
Alternatively you could read you csv with header=None
and then add it with df.columns
:
Cov = pd.read_csv("path/to/file.txt", sep='\t', header=None)
Cov.columns = ["Sequence", "Start", "End", "Coverage"]
If you were to use the C library then this could be done:
time_t t;
struct tm * timeinfo;
time (&t);
timeinfo = localtime (&t);
NSLog(@"Hour: %d Minutes: %d", timeinfo->tm_hour, timeinfo->tm_min);
And using Swift:
var t = time_t()
time(&t)
let x = localtime(&t)
println("Hour: \(x.memory.tm_hour) Minutes: \(x.memory.tm_min)")
For further guidance see: http://www.cplusplus.com/reference/ctime/localtime/
There's a difference between the header and body of a HTTP response. PUT should never return a body, but must return a response code in the header. Just choose 200 if it was successful, and 4xx if not. There is no such thing as a null return code. Why do you want to do this?
In my case I need to insert a row with text 'Please dial *001 for help'. In this case the special character is an asterisk.
By using direct insert using sqlPlus it failed with error "SP2-0734: unknown command beginning ... "
I tryed set escape without success.
To achieve, I created a file insert.sql on filesystem with
insert into testtable (testtext) value ('Please dial *001 for help');
Then from sqlPlus I executed
@insert.sql
And row was inserted.
Try this
npm uninstall angular-cli
npm install @angular/cli --save-dev
Another way is using a SQL Server built-in feature named Client Statistics
which is accessible through Menu > Query > Include Client Statistics.
You can run each query in separated query window and compare the results which is given in Client Statistics
tab just beside the Messages
tab.
For example in image below it shows that the average time elapsed to get the server reply for one of my queries is 39 milliseconds.
You can read all 3 ways for acquiring execution time in here.
You may even need to display Estimated Execution Plan
ctrlL for further investigation about your query.
Since .NET Core 2.0 or .NET Standard 2.1 respectively, this is baked into the .NET runtime [1]:
"hello world".Replace("World", "csharp", StringComparison.CurrentCultureIgnoreCase); // "hello csharp"
VS Code (integrated Git) IDE Users:
If you want to accept all the incoming changes in the conflict file then do the following steps.
1. Go to command palette - Ctrl + Shift + P
2. Select the option - Merge Conflict: Accept All Incoming
Similarly you can do for other options like Accept All Both, Accept All Current etc.,
You cannot load images directly with @2x
or @3x
, system selects appropriate image automatically, just specify the name using UIImage
:
UIImage(named: "green-square-Retina")
<?php
$array[$new_key] = $array[$old_key];
unset($array[$old_key]);
?>
If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
Because more ways to think about it are always good:
select reverse(substring(reverse(columnName), 1, 3))
NULL values are stored separately in a special bitmap space for all the columns.
If you do not distinguish between NULL
and ''
in your application, then I would recommend you to store ''
in your tables (unless the string column is a foreign key, in which case it would probably be better to prohibit the column from storing empty strings and allow the NULLs, if that is compatible with the logic of your application).
Have a look at the link below, which suggests it is possible to alter the contents of an iFrame within your page with Javascript, although you are most likely to run into a few cross browser issues. If you can do this you can use the javascript in your page to add hidden dom elements to the iFrame containing your values, which the iFrame can read. Accessing the document inside an iFrame
Highlight block of text, then:
Comment Block: Ctrl + K + C
Uncomment Block: Ctrl + K + U
Tested in Visual Studio 2012
All of these are good answers, but I would like to suggest one more that I feel is a better code standard. You may choose to use a flag in the loop condition that indicates whether or not to continue looping and avoid using break
all together.
$arr = array('one', 'two', 'three', 'four', 'stop', 'five');
$length = count($arr);
$found = false;
for ($i = 0; $i < $length && !$found; $i++) {
$val = $arr[$i];
if ($val == 'stop') {
$found = true; // this will cause the code to
// stop looping the next time
// the condition is checked
}
echo "$val<br />\n";
}
I consider this to be better code practice because it does not rely on the scope that break
is used. Rather, you define a variable that indicates whether or not to break a specific loop. This is useful when you have many loops that may or may not be nested or sequential.
As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:
<?php
$world = _("World");
$str = <<<EOF
<p>Hello</p>
<p>$world</p>
EOF;
echo $str;
?>
a workaround idea that comes to mind is building a class with a magic getter method.
You would declare a class like this:
class Translator
{
public function __get($name) {
return _($name); // Does the gettext lookup
}
}
Initialize an object of the class at some point:
$translate = new Translator();
You can then use the following syntax to do a gettext lookup inside a HEREDOC block:
$str = <<<EOF
<p>Hello</p>
<p>{$translate->World}</p>
EOF;
echo $str;
?>
$translate->World
will automatically be translated to the gettext lookup thanks to the magic getter method.
To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!
, you will have to use the following notation:
$translate->{"Hello World!!!!!!"}
This is all untested but should work.
Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.
If you want to quickly check if a module is installed (at least on Unix systems, with Bash as shell), add this to your .bashrc file:
alias modver="perl -e\"eval qq{use \\\$ARGV[0];\\\\\\\$v=\\\\\\\$\\\${ARGV[0]}::VERSION;};\ print\\\$@?qq{No module found\\n}:\\\$v?qq{Version \\\$v\\n}:qq{Found.\\n};\"\$1"
Then you can:
=> modver XML::Simple
No module found
=> modver DBI
Version 1.607
Perhaps 0
or '\u0000'
would do?
Check this out:
plt.hist(myarray, density = True)
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
Compare NET Objects can help you!
CompareLogic logic = new CompareLogic();
var compare = logic.Compare(obj1, obj2);
comparacao.Differences.ForEach(diff => Debug.Write(diff.PropertyName));
// Or formatted summary
Debug.Write(comparacao.DifferencesString);
There is an example how to achieve it, when the card is at the very bottom of the screen. If someone has this kind of problem just do something like that:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="-5dp"
card_view:cardCornerRadius="4dp">
<SomeView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp">
</SomeView>
</android.support.v7.widget.CardView>
Card View has a negative bottom margin. The view inside a Card View has the same, but positive bottom margin. This way rounded parts are hidden below the screen, but everything looks exactly the same, because the inner view has a counter margin.
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
Use the HttpClient
class from HttpClientModule
if you're using Angular 4.3.x and above:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
HttpClientModule
],
...
class MyService() {
constructor(http: HttpClient) {...}
It's an upgraded version of http
from @angular/http
module with the following improvements:
- Interceptors allow middleware logic to be inserted into the pipeline
- Immutable request/response objects
- Progress events for both request upload and response download
You can read about how it works in Insider’s guide into interceptors and HttpClient mechanics in Angular.
- Typed, synchronous response body access, including support for JSON body types
- JSON is an assumed default and no longer needs to be explicitly parsed
- Post-request verification & flush based testing framework
Going forward the old http client will be deprecated. Here are the links to the commit message and the official docs.
Also pay attention that old http was injected using Http
class token instead of the new HttpClient
:
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule
],
...
class MyService() {
constructor(http: Http) {...}
Also, new HttpClient
seem to require tslib
in runtime, so you have to install it npm i tslib
and update system.config.js
if you're using SystemJS
:
map: {
...
'tslib': 'npm:tslib/tslib.js',
And you need to add another mapping if you use SystemJS:
'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',
Here i have done complete bins for above query. below is demo link, i think it may help you
Demo: http://codebins.com/bin/4ldqp9b/1
HTML:
<div id="edge">
<div class="box" style="top:20; background:#f8a2a4;">
</div>
<div class="box" style="top:70; background:#a2f8a4;">
</div>
<div class="box" style="top:120; background:#5599fd;">
</div>
</div>
<br/>
<input type="button" id="btnAnimate" name="btnAnimate" value="Animate" />
CSS:
body{
background:#ffffef;
}
#edge{
width:500px;
height:200px;
border:1px solid #3377af;
padding:5px;
}
.box{
position:absolute;
left:10;
width:40px;
height:40px;
border:1px solid #a82244;
}
JQuery:
$(function() {
$("#btnAnimate").click(function() {
var move = "";
if ($(".box:eq(0)").css('left') == "10px") {
move = "+=" + ($("#edge").width() - 35);
} else {
move = "-=" + ($("#edge").width() - 35);
}
$(".box").animate({
left: move
}, 500, function() {
if ($(".box:eq(0)").css('left') == "475px") {
$(this).css('background', '#afa799');
} else {
$(".box:eq(0)").css('background', '#f8a2a4');
$(".box:eq(1)").css('background', '#a2f8a4');
$(".box:eq(2)").css('background', '#5599fd');
}
});
});
});
I'd go for jpeg
. Read this post regarding image size reduction and after deciding on the technique, use ImageMagick
Hope this helps
The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:
document.getElementById('div_register').setAttribute("style","width:500px");
For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:
document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";
Thus, the most cross-browser compatible example for you would be:
document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width='500px';
I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers!
document.getElementById("div_register").setAttribute("class","wide");
.wide {
display:block;
width:500px;
}
.hide {
display:none;
}
.narrow {
display:block;
width:100px;
}
Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.
This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).
You could also use Django Crispy Forms, it's a great tool to define forms in case you'd like to use some CSS framework like Bootstrap or Foundation. And it's easy to specify classes for your form fields there.
Your form class would like this then:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, Field
from crispy_forms.bootstrap import FormActions
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
helper = FormHelper()
helper.form_class = 'your-form-class'
helper.layout = Layout(
Field('name', css_class='name-class'),
Field('age', css_class='age-class'),
Field('django_hacker', css-class='hacker-class'),
FormActions(
Submit('save_changes', 'Save changes'),
)
)
$('#select-meal-type :selected')
will contain an array of all of the selected items.
$('#select-meal-type option:selected').each(function() {
alert($(this).val());
});
?
in the "Ouput Window". you can usually do CTRL-ALT-O to make it visible. Or through menus using View->Output.
I had a similar issue on my controller and here is what worked for me:
model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""
"DateSigned" is the value from my model The line reads, if the model value has a value then format the value, otherwise show nothing.
Hope that helps
I came across this post looking for a "shaking" implementation. millenomi's answer worked well for me, although i was looking for something that required a bit more "shaking action" to trigger. I've replaced to Boolean value with an int shakeCount. I also reimplemented the L0AccelerationIsShaking() method in Objective-C. You can tweak the ammount of shaking required by tweaking the ammount added to shakeCount. I'm not sure i've found the optimal values yet, but it seems to be working well so far. Hope this helps someone:
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {
if (self.lastAcceleration) {
if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7] && shakeCount >= 9) {
//Shaking here, DO stuff.
shakeCount = 0;
} else if ([self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.7]) {
shakeCount = shakeCount + 5;
}else if (![self AccelerationIsShakingLast:self.lastAcceleration current:acceleration threshold:0.2]) {
if (shakeCount > 0) {
shakeCount--;
}
}
}
self.lastAcceleration = acceleration;
}
- (BOOL) AccelerationIsShakingLast:(UIAcceleration *)last current:(UIAcceleration *)current threshold:(double)threshold {
double
deltaX = fabs(last.x - current.x),
deltaY = fabs(last.y - current.y),
deltaZ = fabs(last.z - current.z);
return
(deltaX > threshold && deltaY > threshold) ||
(deltaX > threshold && deltaZ > threshold) ||
(deltaY > threshold && deltaZ > threshold);
}
PS: I've set the update interval to 1/15th of a second.
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 15)];
I was able to bypass all the framework messages by making the property a string in my view model.
[Range(0, 15, ErrorMessage = "Can only be between 0 .. 15")]
[StringLength(2, ErrorMessage = "Max 2 digits")]
[Remote("PredictionOK", "Predict", ErrorMessage = "Prediction can only be a number in range 0 .. 15")]
public string HomeTeamPrediction { get; set; }
Then I need to do some conversion in my get method:
viewModel.HomeTeamPrediction = databaseModel.HomeTeamPrediction.ToString();
and post method:
databaseModel.HomeTeamPrediction = int.Parse(viewModel.HomeTeamPrediction);
This works best when using the range attribute, otherwise some additional validation would be needed to make sure the value is a number.
You can also specify the type of number by changing the numbers in the range to the correct type:
[Range(0, 10000000F, ErrorMessageResourceType = typeof(GauErrorMessages), ErrorMessageResourceName = nameof(GauErrorMessages.MoneyRange))]
In the Windows command prompt you can disable tab completion, by launching it thusly:
cmd.exe /f:off
Then the tab character will be echoed to the screen and work as you expect. Or you can disable the tab completion character, or modify what character is used for tab completion by modifying the registry.
The cmd.exe
help page explains it:
You can enable or disable file name completion for a particular invocation of CMD.EXE with the /F:ON or /F:OFF switch. You can enable or disable completion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\CompletionChar HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\PathCompletionChar and/or HKEY_CURRENT_USER\Software\Microsoft\Command Processor\CompletionChar HKEY_CURRENT_USER\Software\Microsoft\Command Processor\PathCompletionChar
with the hex value of a control character to use for a particular function (e.g. 0x4 is Ctrl-D and 0x6 is Ctrl-F). The user specific settings take precedence over the machine settings. The command line switches take precedence over the registry settings.
If completion is enabled with the /F:ON switch, the two control characters used are Ctrl-D for directory name completion and Ctrl-F for file name completion. To disable a particular completion character in the registry, use the value for space (0x20) as it is not a valid control character.
It is not necessary to add ()
in the WHERE clause as we do in a regular SQL. Because Dapper does that automatically for us. Here is the syntax
:-
const string SQL = "SELECT IntegerColumn, StringColumn FROM SomeTable WHERE IntegerColumn IN @listOfIntegers";
var conditions = new { listOfIntegers };
var results = connection.Query(SQL, conditions);
Below is the link which guide in parsing JSON string in android.
http://www.ibm.com/developerworks/xml/library/x-andbene1/?S_TACT=105AGY82&S_CMP=MAVE
Also according to your json string code snippet must be something like this:-
JSONObject mainObject = new JSONObject(yourstring);
JSONObject universityObject = mainObject.getJSONObject("university");
JSONString name = universityObject.getString("name");
JSONString url = universityObject.getString("url");
Following is the API reference for JSOnObject: https://developer.android.com/reference/org/json/JSONObject.html#getString(java.lang.String)
Same for other object.
The first snippet is correct, but you need to call it after onMeasure()
gets executed. Otherwise the size is not yet measured for the view.
For me both keys for sql-mode
worked. Whether I used
# dash no quotes
sql-mode=NO_ENGINE_SUBSTITUTION
or
# underscore no quotes
sql_mode=NO_ENGINE_SUBSTITUTION
in the my.ini
file made no difference and both were accepted, as far as I could test it.
What actually made a difference was a missing newline at the end of the my.ini
file.
So everyone having problems with this or similar problems with my.ini
/my.cnf
: Make sure there is a blank line at the end of the file!
Tested using MySQL 5.7.27.
In my Case , it was not a library, it was some classes ..
Undefined symbols for architecture x86_64:
"_OBJC_CLASS_$_ClassNmae", referenced from: objc-class-ref in SomeClassName" . . .d: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Solution I had several targets in Xcode with several schemas ( Production , Dev etc ) .. some of my newly added implementation ( Class.m ) were missing in
Xcode->Targets->Build Phases->Compile Sources
So I had to add them manually.
then I could compile & build successfully.
alert("xxxxxxxxxxx_456".substr(-3))
caveat: according to mdc, not IE compatible
Most universal way is to take value by name. It doesn't matter if its input or select form element type.
var value = $('[name="foo"]');
This question has not enough information to answer. A general solution (depending on your GUI framework): add a mouse event handler that will catch clicks and mouse movements. This will give you your (x, y) coordinates. Next use these coordinates to crop your image.
<script type="text/javascript">
$(function() {
$("#datepicker").datepicker({
onSelect: function(value, date) {
window.location = 'day.jsp' ;
}
});
});
</script>
<div id="datepicker"></div>
I think you can try this .It works fine .
Since getEntries
returns a raw List
, it could hold anything.
The warning-free approach is to create a new List<SyndEntry>
, then cast each element of the sf.getEntries()
result to SyndEntry
before adding it to your new list. Collections.checkedList
does not do this checking for you—although it would have been possible to implement it to do so.
By doing your own cast up front, you're "complying with the warranty terms" of Java generics: if a ClassCastException
is raised, it will be associated with a cast in the source code, not an invisible cast inserted by the compiler.
I've experienced the same issue because of certifi
library. Installing a different version helped me as well.
I came up with the same problem and I'm sharing how I fixed it. It may help some people.
First, check your Android version. If it is running on Android 6.0 and higher (API level 23+), then you need to :
**<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />**
<application ...>
...
</application>
Then, request that the user approve each permission at runtime
if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// here, Permission is not granted
ActivityCompat.requestPermissions(this, new String[] {android.Manifest.permission.CAMERA}, 50);
}
For more information, have a look at the API documentation here
Behe's answer with sorting plugins did not work on my Jenkins machine. I received the error java.lang.UnsupportedOperationException
due to trying to sort an immutable collection i.e. Jenkins.instance.pluginManager.plugins
. Simple fix for the code:
List<String> jenkinsPlugins = new ArrayList<String>(Jenkins.instance.pluginManager.plugins);
jenkinsPlugins.sort { it.displayName }
.each { plugin ->
println ("${plugin.shortName}:${plugin.version}")
}
Use the http://<jenkins-url>/script
URL to run the code.
I think troelskn is close. I would do this instead:
class ClassToTest
{
protected function testThisMethod()
{
// Implement stuff here
}
}
Then, implement something like this:
class TestClassToTest extends ClassToTest
{
public function testThisMethod()
{
return parent::testThisMethod();
}
}
You then run your tests against TestClassToTest.
It should be possible to automatically generate such extension classes by parsing the code. I wouldn't be surprised if PHPUnit already offers such a mechanism (though I haven't checked).
My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R
'USERNAME' %in% names(Sys.getenv())
See mozilla.org's write-up on how CORS works.
You'll need your server to send back the proper response headers, something like:
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, PUT, GET, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization
Bear in mind you can use "*"
for Access-Control-Allow-Origin
that will only work if you're trying to pass Authentication data. In that case, you need to explicitly list the origin domains you want to allow. To allow multiple domains, see this post
Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.
This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.
The HttpSession#setMaxInactiveInterval()
doesn't change much here by the way. It does exactly the same as <session-timeout>
in web.xml
, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static
method).
To play around and experience this yourself, try to set <session-timeout>
to 1 minute and create a HttpSessionListener
like follows:
@WebListener
public class HttpSessionChecker implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event) {
System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
}
}
(if you're not on Servlet 3.0 yet and thus can't use @WebListener
, then register in web.xml
as follows):
<listener>
<listener-class>com.example.HttpSessionChecker</listener-class>
</listener>
Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed
line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.
Windows Service runs using a local system account.It can start automatically as the user logs into the system or it can be started manually.However, a windows service say BST can be run using a particular user account on the machine.This can be done as follows:start services.msc and go to the properties of your windows service,BST.From there you can give the login parameters of the required user.Service then runs with that user account and no other user can run that service.
Use read -p
:
# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user
If you like to confirm:
read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1
You should also quote your variables to prevent pathname expansion and word splitting with spaces:
# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"