According to Cormen et al. Introduction to Algorithms (Appendix B.5.3), the depth of a node X in a tree T is defined as the length of the simple path (number of edges) from the root node of T to X. The height of a node Y is the number of edges on the longest downward simple path from Y to a leaf. The height of a tree is defined as the height of its root node.
Note that a simple path is a path without repeat vertices.
The height of a tree is equal to the max depth of a tree. The depth of a node and the height of a node are not necessarily equal. See Figure B.6 of the 3rd Edition of Cormen et al. for an illustration of these concepts.
I have sometimes seen problems asking one to count nodes (vertices) instead of edges, so ask for clarification if you're not sure you should count nodes or edges during an exam or a job interview.
The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.
const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation
var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
Welcome to Java! This Nodes are like a blocks, they must be assembled to do amazing things! In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
You can delete the node from the master by issuing:
kubectl delete node hostname.company.net
The NOTReady status probably means that the master can't access the kubelet service. Check if everything is OK on the client.
I had some problems with the insertion process just like you, so here is the code how I have solved the problem:
void add_by_position(int data, int pos)
{
link *node = new link;
link *linker = head;
node->data = data;
for (int i = 0; i < pos; i++){
linker = linker->next;
}
node->next = linker;
linker = head;
for (int i = 0; i < pos - 1; i++){
linker = linker->next;
}
linker->next = node;
boundaries++;
}
NULL
isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef>
or #include <stddef.h>
should be sufficient.
The definition of NULL
is guaranteed to be available if you include cstddef
or stddef.h
. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
In the following line.
temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
You are calling First but the collection returned from db.Responses.Where is empty.
You can (should) use CROSS JOIN
. Following query will be equivalent to yours:
SELECT
table1.columnA
, table2.columnA
FROM table1
CROSS JOIN table2
WHERE table1.columnA = 'Some value'
or you can even use INNER JOIN with some always true conditon:
FROM table1
INNER JOIN table2 ON 1=1
It isn't possible as far as I can tell, since a link needs HTML, and mailto links don't create an HTML email.
This is probably for security as you could add javascript or iframes to this link and the email client might open up the end user for vulnerabilities.
Just ran into this syntax problem on a CentOS 7 machine.
On a very old Ubuntu machine running mail
, the syntax for a nicely composed email is
echo -e "$body" | mail -s "$subject" -a "From: Sender Name <$sender>" "$recipient"
However on a CentOS 7 box which came with mailx
installed, it's quite different:
echo -e "$body" | mail -s "$subject" -S "from=Sender Name <$sender>" "$recipient"
Consulting man mail
indicates that -r
is deprecated and the 'From' sender address should now be set directly using -S "variable=value"
.
In these and subsequent examples, I'm defining
$sender
as"Sender Name <[email protected]>"
and$recipients
as"[email protected]"
as I do in my bash script.
You may then find, as I did, that when you try to generate the email's body content in your script at the point of sending the email, you encounter a strange behaviour where the email body is instead attached as a binary file ("ATT00001.bin", "application/octet-stream" or "noname", depending on client).
This behaviour is how Heirloom mailx handles unrecognised / control characters in text input. (More info: https://access.redhat.com/solutions/1136493, which itself references the mailx man page for the solution.)
To get around this, I used a method which pipes the generated output through tr
before passing to mail
, and also specifies the charset of the email:
echo -e "$body" | tr -d \\r | mail -s "$subject" -S "from=$sender" -S "sendcharsets=utf-8,iso-8859-1" "$recipients"
In my script, I'm also explicitly delaring the locale beforehand as it's run as a cronjob (and cron doesn't inherit environmental variables):
LANG="en_GB.UTF8" ; export LANG ;
(An alternate method of setting locales for cronjobs is discussed here)
More info on these workarounds via https://stackoverflow.com/a/29826988/253139 and https://stackoverflow.com/a/3120227/253139.
The goal is to make the <body> element take up the available height of the screen.
If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set
body {
height: 100vh;
}
otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set
body {
min-height: 100vh;
}
this alone achieves the goal, albeit with a possible, and probably desirable, refinement.
Removing the margin of <body>.
body {
margin: 0;
}
there are two main reasons for doing so.
P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like
body {
min-height: 100vh;
margin: 0;
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title>test</title>
</head>
<body>
</body>
</html>
_x000D_
git checkout --[ours/theirs] .
will do what you want, as long as you're at the root of all conflicts. ours/theirs only affects unmerged files so you shouldn't have to grep/find/etc conflicts specifically.
Use .attr
$("current_month").attr("month")
$("current_month").attr("year")
And change the labels id to
<label year="2010" month="6" id="current_month"> June 2010</label>
This is a shot in the dark but try putting the two operands for the AND in parentheses
On ((A = B) And (C = D))
I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy
After installing http-proxy
npm install http-proxy --save
Use it like below in your server/index/app.js
var proxyServer = require('http-route-proxy');
app.use('/api/BLABLA/', proxyServer.connect({
to: 'other_domain.com:3000/BLABLA',
https: true,
route: ['/']
}));
I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.
Hope it is going to help someone else too :)
There's no specific answer. It depends on the platform. It is implementation-defined. It can be 2, 4 or something else.
The idea behind int
was that it was supposed to match the natural "word" size on the given platform: 16 bit on 16-bit platforms, 32 bit on 32-bit platforms, 64 bit on 64-bit platforms, you get the idea. However, for backward compatibility purposes some compilers prefer to stick to 32-bit int
even on 64-bit platforms.
The time of 2-byte int
is long gone though (16-bit platforms?) unless you are using some embedded platform with 16-bit word size. Your textbooks are probably very old.
If you have some column in SELECT clause , how will it select it if there is several rows ? so yes , every column in SELECT clause should be in GROUP BY clause also , you can use aggregate functions in SELECT ...
you can have column in GROUP BY clause which is not in SELECT clause , but not otherwise
OP's problem was related with HTML coding. But if you are using plain text, please use "\n" and not "\r\n".
My personal use case: using mailx mailer, simply replacing "\r\n" into "\n" fixed my issue, related with wrong automatic Content-Type setting.
Wrong header:
User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64
Correct header:
User-Agent: Heirloom mailx 12.4 7/29/08
MIME-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
I'm not saying that "application/octet-stream" and "base64" are always wrong/unwanted, but they where in my case.
there is another solution to download a web page in ajax. But I am referring to a page that must first be processed and then downloaded.
First you need to separate the page processing from the results download.
1) Only the page calculations are made in the ajax call.
$.post("CalculusPage.php", { calculusFunction: true, ID: 29, data1: "a", data2: "b" }, function(data, status) { if (status == "success") { /* 2) In the answer the page that uses the previous calculations is downloaded. For example, this can be a page that prints the results of a table calculated in the ajax call. */ window.location.href = DownloadPage.php+"?ID="+29; } } ); // For example: in the CalculusPage.php if ( !empty($_POST["calculusFunction"]) ) { $ID = $_POST["ID"]; $query = "INSERT INTO ExamplePage (data1, data2) VALUES ('".$_POST["data1"]."', '".$_POST["data2"]."') WHERE id = ".$ID; ... } // For example: in the DownloadPage.php $ID = $_GET["ID"]; $sede = "SELECT * FROM ExamplePage WHERE id = ".$ID; ... $filename="Export_Data.xls"; header("Content-Type: application/vnd.ms-excel"); header("Content-Disposition: inline; filename=$filename"); ...
I hope this solution can be useful for many, as it was for me.
you can use cURL library for posting data: http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects
I am coming here after searching google and change thing at my-end.
So I just change this sample and it will work with jquery at run-time.
$('select[name*="homepage_select"]').removeAttr('multiple')
If all your trying to do is fill the div this might help someone else, if aspect ratio is not important, is responsive.
.img-fill > img {
min-height: 100%;
min-width: 100%;
}
import numpy as np
import pandas as pd
import scipy.sparse as sparse
df = pd.DataFrame(np.arange(1,10).reshape(3,3))
arr = sparse.coo_matrix(([1,1,1], ([0,1,2], [1,2,0])), shape=(3,3))
df['newcol'] = arr.toarray().tolist()
print(df)
yields
0 1 2 newcol
0 1 2 3 [0, 1, 0]
1 4 5 6 [0, 0, 1]
2 7 8 9 [1, 0, 0]
Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.
Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).
...Just open this answer for edit to see it.
Nested lists, deeper levels: ---- leave here an empty row * first level A item - no space in front the bullet character * second level Aa item - 1 space is enough * third level Aaa item - 5 spaces min * second level Ab item - 4 spaces possible too * first level B item
Nested lists, deeper levels:
first level B item
Nested lists, deeper levels:
...Skip a line and indent eight spaces. (as said in the editor-help, just on this page)
* first level A item - no space in front the bullet character
* second level Aa item - 1 space is enough
* third level Aaa item - 5 spaces min
* second level Ab item - 4 spaces possible too
* first level B item
Joblib https://joblib.readthedocs.io supports caching functions in the Memoize pattern. Mostly, the idea is to cache computationally expensive functions.
>>> from joblib import Memory
>>> mem = Memory(cachedir='/tmp/joblib')
>>> import numpy as np
>>> square = mem.cache(np.square)
>>>
>>> a = np.vander(np.arange(3)).astype(np.float)
>>> b = square(a)
________________________________________________________________________________
[Memory] Calling square...
square(array([[ 0., 0., 1.],
[ 1., 1., 1.],
[ 4., 2., 1.]]))
___________________________________________________________square - 0...s, 0.0min
>>> c = square(a)
You can also do fancy things like using the @memory.cache decorator on functions. The documentation is here: https://joblib.readthedocs.io/en/latest/generated/joblib.Memory.html
The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.
The basic process is:
The table should, of course, be nice HTML. Something like this...
<table>
<thead>
<tr><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Sioned</td><td>62</td></tr>
<tr><td>Dylan</td><td>37</td></tr>
...etc...
</tbody>
</table>
So, first adding the click handlers...
const table = document.querySelector('table'); //get the table to be sorted
table.querySelectorAll('th') // get all the table header elements
.forEach((element, columnNo)=>{ // add a click handler for each
element.addEventListener('click', event => {
sortTable(table, columnNo); //call a function which sorts the table by a given column number
})
})
This won't work right now because the sortTable
function which is called in the event handler doesn't exist.
Lets write it...
function sortTable(table, sortColumn){
// get the data from the table cells
const tableBody = table.querySelector('tbody')
const tableData = table2data(tableBody);
// sort the extracted data
tableData.sort((a, b)=>{
if(a[sortColumn] > b[sortColumn]){
return 1;
}
return -1;
})
// put the sorted data back into the table
data2table(tableBody, tableData);
}
So now we get to the meat of the problem, we need to make the functions table2data
to get data out of the table, and data2table
to put it back in once sorted.
Here they are ...
// this function gets data from the rows and cells
// within an html tbody element
function table2data(tableBody){
const tableData = []; // create the array that'll hold the data rows
tableBody.querySelectorAll('tr')
.forEach(row=>{ // for each table row...
const rowData = []; // make an array for that row
row.querySelectorAll('td') // for each cell in that row
.forEach(cell=>{
rowData.push(cell.innerText); // add it to the row data
})
tableData.push(rowData); // add the full row to the table data
});
return tableData;
}
// this function puts data into an html tbody element
function data2table(tableBody, tableData){
tableBody.querySelectorAll('tr') // for each table row...
.forEach((row, i)=>{
const rowData = tableData[i]; // get the array for the row data
row.querySelectorAll('td') // for each table cell ...
.forEach((cell, j)=>{
cell.innerText = rowData[j]; // put the appropriate array element into the cell
})
tableData.push(rowData);
});
}
And that should do it.
A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2"
is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.
One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone
of your chosen upstream repo. So you have effectively a personal checkout
of everything, without putting some 'lock' on those files in the reference repo.
Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !
==
is an operator and equals()
is a method.
Operators are generally used for primitive type comparisons and thus ==
is used for memory address comparison and equals()
method is used for comparing objects.
An abbreviated version of your code worked for me,
class Remote: NSObject {
var data = NSMutableData()
func connect(query:NSString) {
var url = NSURL.URLWithString("http://www.google.com")
var request = NSURLRequest(URL: url)
var conn = NSURLConnection(request: request, delegate: self, startImmediately: true)
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
println("didReceiveResponse")
}
func connection(connection: NSURLConnection!, didReceiveData conData: NSData!) {
self.data.appendData(conData)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
println(self.data)
}
deinit {
println("deiniting")
}
}
This is the code I used in the calling class,
class ViewController: UIViewController {
var remote = Remote()
@IBAction func downloadTest(sender : UIButton) {
remote.connect("/apis")
}
}
You didn't specify in your question where you had this code,
var remote = Remote()
remote.connect("/apis")
If var is a local variable, then the Remote class will be deallocated right after the connect(query:NSString) method finishes, but before the data returns. As you can see by my code, I usually implement reinit (or dealloc up to now) just to make sure when my instances go away. You should add that to your Remote class to see if that's your problem.
Does the race conditions really matter if you first try an update followed by an insert? Lets say you have two threads that want to set a value for key key:
Thread 1: value = 1
Thread 2: value = 2
Example race condition scenario
The other thread fails with insert (with error duplicate key) - thread 2.
But; in a multithreaded environment, the OS scheduler decides on the order of the thread execution - in the above scenario, where we have this race condition, it was the OS that decided on the sequence of execution. Ie: It is wrong to say that "thread 1" or "thread 2" was "first" from a system viewpoint.
When the time of execution is so close for thread 1 and thread 2, the outcome of the race condition doesn't matter. The only requirement should be that one of the threads should define the resulting value.
For the implementation: If update followed by insert results in error "duplicate key", this should be treated as success.
Also, one should of course never assume that value in the database is the same as the value you wrote last.
It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.
Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.
While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.
People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.
You see the two empty -D
entries in the g++
command line? They're causing the problem. You must have values in the -D
items e.g. -DWIN32
if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:
SYSTEM ?= generic
ENVIRONMENT ?= generic
in the makefile which gives them default values.
Your output looks to be missing the all important output:
<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers
just to clarify, what actually got sent to g++
was -D -DWindows_NT
, i.e. define a preprocessor macro called -DWindows_NT
; which is of course not a valid identifier (similarly for -D -I.
)
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
For the last Spring MVC app I wrote, I didn't inject the SecurityContext holder, but I did have a base controller that I had two utility methods related to this ... isAuthenticated() & getUsername(). Internally they do the static method call you described.
At least then it's only in once place if you need to later refactor.
Here's a more concrete example of how to access GET parameters. The Request
object has a method that parses them out for you called Query:
Assuming a request URL like http://host:port/something?param1=b
func newHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("GET params were:", r.URL.Query())
// if only one expected
param1 := r.URL.Query().Get("param1")
if param1 != "" {
// ... process it, will be the first (only) if multiple were given
// note: if they pass in like ?param1=¶m2= param1 will also be "" :|
}
// if multiples possible, or to process empty values like param1 in
// ?param1=¶m2=something
param1s := r.URL.Query()["param1"]
if len(param1s) > 0 {
// ... process them ... or you could just iterate over them without a check
// this way you can also tell if they passed in the parameter as the empty string
// it will be an element of the array that is the empty string
}
}
Also note "the keys in a Values map [i.e. Query() return value] are case-sensitive."
in my case it happens when I try add types to Promise.all handler:
Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));
If remove : [number, number]
, the error is gone.
If you only want to revert a single file to its state in a given commit, you actually want to use the checkout
command:
git checkout HEAD~2 myFile
The revert
command is used for reverting entire commits (and it doesn't revert you to that commit; it actually just reverts the changes made by that commit - if you have another commit after the one you specify, the later commit won't be reverted).
Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:
@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
val cacheFile = File(context.cacheDir, "splash_video")
try {
val inputStream = context.assets.open("splash_video")
val outputStream = FileOutputStream(cacheFile)
try {
inputStream.copyTo(outputStream)
} finally {
inputStream.close()
outputStream.close()
}
} catch (e: IOException) {
throw IOException("Could not open splash_video", e)
}
return cacheFile
}
You can customize the border color by setting
tableView.separatorColor
If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:
jQuery('#mydiv').css("overflow-y", "scroll");
You can also use the option_context
, with one or more options:
with pd.option_context('display.max_rows', None, 'display.max_columns', None): # more options can be specified also
print(df)
This will automatically return the options to their previous values.
If you are working on jupyter-notebook, using display(df)
instead of print(df)
will use jupyter rich display logic (like so).
Spinner
<Spinner
android:id="@+id/To_Units"
style="@style/spinner_style" />
style.xml
<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">10dp</item>
<item name="android:paddingLeft">8dp</item>
<item name="android:paddingRight">20dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
<item name="android:popupBackground">#DFFFFFFF</item>
</style>
gradient_spinner.xml (in drawable folder)
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><layer-list>
<item><shape>
<gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />
<stroke android:width="1dp" android:color="#000000" />
<corners android:radius="4dp" />
<padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
</shape></item>
<item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
</item>
</layer-list></item>
</selector>
@drawable/spinner_arrow
is your bottom right corner image
For older versions of windows (2k, 2k3, xp)
"%Userprofile%\Local Settings\Application Data\Google\Chrome\User Data\Default\Extensions"
Solution in ES6/TypeScript:
let d = new Date;
console.log(d, [`${d.getFullYear()}`, `0${d.getMonth()}`.substr(-2), `0${d.getDate()}`.substr(-2)].join("-"));
You can create a fast refresh materialized view to store the count.
Example:
create table sometable (
id number(10) not null primary key
, name varchar2(100) not null);
create materialized view log on sometable with rowid including new values;
create materialized view sometable_count
refresh on commit
as
select count(*) count
from sometable;
insert into sometable values (1,'Raymond');
insert into sometable values (2,'Hans');
commit;
select count from sometable_count;
It will slow mutations on table sometable a bit but the counting will become a lot faster.
Try this it works sudo apt install python-pip pip install boto3
(1) Your <script>
tag should be placed before the closing </body>
tag. Your JavaScript is trying to manipulate HTML elements that haven't been loaded into the DOM yet.
(2) Your assignment of HTML content looks jumbled.
(3) Be consistent with the case in your element ID, i.e. 'DIV2' vs 'Div2'
(4) User lower case for 'document' object (credit: ThatOtherPerson)
<body>
<div id="DIV1">
// Some content goes here.
</div>
<div id="DIV2">
</div>
<script type="text/javascript">
var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML;
</script>
</body>
.pyc
contain the compiled bytecode of Python source files. The Python interpreter loads .pyc
files before .py
files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.
Having seen your fiddle in the comments the issue is quite easy to fix. You just need to add overflow:auto
or set a specific height to your div
. Live example: http://jsfiddle.net/tw16/xRcXL/3/
.Tab{
overflow:auto; /* add this */
border:solid 1px #faa62a;
border-bottom:none;
padding:7px 10px;
background:-moz-linear-gradient(center top , #FAD59F, #FA9907) repeat scroll 0 0 transparent;
background:-webkit-gradient(linear, left top, left bottom, from(#fad59f), to(#fa9907));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#fad59f, endColorstr=#fa9907)";
}
Why do you have the brackets around digit
?
It should be
NSLog("%@", digit);
You're also missing an =
in the first line...
NSString *digit = [[sender titlelabel] text];
In pgAdmin you can also use
SET search_path TO your_db_name;
LinkedHashSet
's constructors invoke the following base class constructor:
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}
As you can see, the internal map is a LinkedHashMap
. If you look inside LinkedHashMap
, you'll discover the following field:
private transient Entry<K, V> header;
This is the linked list in question.
Flatmap maps observables to observables. Map maps items to items.
Flatmap is more flexible but Map is more lightweight and direct, so it kind of depends on your usecase.
If you are doing ANYTHING async (including switching threads), you should be using Flatmap, as Map will not check if the consumer is disposed (part of the lightweight-ness)
onDestroy
isn't always called in the service so this is useless!
For example: Just run the app again with one change from Eclipse. The application is forcefully exited using SIG: 9.
I like the reasoning by an article from "cplusplus.com:"
Pass by value when the function does not want to modify the parameter and the value is easy to copy (ints, doubles, char, bool, etc... simple types. std::string, std::vector, and all other STL containers are NOT simple types.)
Pass by const pointer when the value is expensive to copy AND the function does not want to modify the value pointed to AND NULL is a valid, expected value that the function handles.
Pass by non-const pointer when the value is expensive to copy AND the function wants to modify the value pointed to AND NULL is a valid, expected value that the function handles.
Pass by const reference when the value is expensive to copy AND the function does not want to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.
Pass by non-cont reference when the value is expensive to copy AND the function wants to modify the value referred to AND NULL would not be a valid value if a pointer was used instead.
When writing template functions, there isn't a clear-cut answer because there are a few tradeoffs to consider that are beyond the scope of this discussion, but suffice it to say that most template functions take their parameters by value or (const) reference, however because iterator syntax is similar to that of pointers (asterisk to "dereference"), any template function that expects iterators as arguments will also by default accept pointers as well (and not check for NULL since the NULL iterator concept has a different syntax).
What I take from this is that the major difference between choosing to use a pointer or reference parameter is if NULL is an acceptable value. That's it.
Whether the value is input, output, modifiable etc. should be in the documentation / comments about the function, after all.
Implementation of accepted answer for Django:
import hashlib
from django.db import models
class MyModel(models.Model):
file = models.FileField() # any field based on django.core.files.File
def get_hash(self):
hash = hashlib.md5()
for chunk in self.file.chunks(chunk_size=8192):
hash.update(chunk)
return hash.hexdigest()
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
What you saw in Firefox was not the actual request; note that the HTTP method is OPTIONS, not POST. It was actually the 'pre-flight' request that the browser makes to determine whether a cross-domain AJAX request should be allowed:
The Access-Control-Request-Headers header in the pre-flight request includes the list of headers in the actual request. The server is then expected to report back whether these headers are supported in this context or not, before the browser submits the actual request.
This can be done in a single line, as long as the worksheet is active:
ActiveSheet.Visible = xlSheetHidden
However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.
Key insights for me were: - ensure that label content comes after the input-radio field - I tweaked my css to make everything a little closer
.radio-inline+.radio-inline {
margin-left: 5px;
}
If you a framework like Bootstrap you can make any iframe video responsive by using this snippet:
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" src="vid.mp4" allowfullscreen></iframe>
</div>
You can use dir(your_object)
to get the attributes and getattr(your_object, your_object_attr)
to get the values
usage :
for att in dir(your_object):
print (att, getattr(your_object,att))
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
This may help you.
public MyContext() : base("name=MyContext")
{
Database.SetInitializer(new MyContextDataInitializer());
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
Something to be aware of, the $_SESSION
variables are still set in the same page after calling session_destroy()
where as this is not the case when using unset($_SESSION)
or $_SESSION = array()
. Also, unset($_SESSION)
blows away the $_SESSION
superglobal so only do this when you're destroying a session.
With all that said, it's best to do like the PHP docs has it in the first example for session_destroy()
.
/**
* ??????????????,????????
* English: Calculating the difference between the given time and the current time and then showing the results.
*/
function date2Text(date) {
var milliseconds = new Date() - date;
var timespan = new TimeSpan(milliseconds);
if (milliseconds < 0) {
return timespan.toString() + "??";
}else{
return timespan.toString() + "?";
}
}
/**
* ???????????
* English: Using a function to calculate the time interval
* @param milliseconds ???
*/
var TimeSpan = function (milliseconds) {
milliseconds = Math.abs(milliseconds);
var days = Math.floor(milliseconds / (1000 * 60 * 60 * 24));
milliseconds -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(milliseconds / (1000 * 60 * 60));
milliseconds -= hours * (1000 * 60 * 60);
var mins = Math.floor(milliseconds / (1000 * 60));
milliseconds -= mins * (1000 * 60);
var seconds = Math.floor(milliseconds / (1000));
milliseconds -= seconds * (1000);
return {
getDays: function () {
return days;
},
getHours: function () {
return hours;
},
getMinuts: function () {
return mins;
},
getSeconds: function () {
return seconds;
},
toString: function () {
var str = "";
if (days > 0 || str.length > 0) {
str += days + "?";
}
if (hours > 0 || str.length > 0) {
str += hours + "??";
}
if (mins > 0 || str.length > 0) {
str += mins + "??";
}
if (days == 0 && (seconds > 0 || str.length > 0)) {
str += seconds + "?";
}
return str;
}
}
}
Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.
http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Even if WHERE textcolumn LIKE "%SUBSTRING%"
is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).
If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")
I made a function which handles arrays as well as single GET or POST values
function subVal($varName, $default=NULL,$isArray=FALSE ){ // $isArray toggles between (multi)array or single mode
$retVal = "";
$retArray = array();
if($isArray) {
if(isset($_POST[$varName])) {
foreach ( $_POST[$varName] as $var ) { // multidimensional POST array elements
$retArray[]=$var;
}
}
$retVal=$retArray;
}
elseif (isset($_POST[$varName]) ) { // simple POST array element
$retVal = $_POST[$varName];
}
else {
if (isset($_GET[$varName]) ) {
$retVal = $_GET[$varName]; // simple GET array element
}
else {
$retVal = $default;
}
}
return $retVal;
}
Examples:
$curr_topdiameter = subVal("topdiameter","",TRUE)[3];
$user_name = subVal("user_name","");
In case you don't want to track table view's content size changes yourself, you might find this subclass useful.
protocol ContentFittingTableViewDelegate: UITableViewDelegate {
func tableViewDidUpdateContentSize(_ tableView: UITableView)
}
class ContentFittingTableView: UITableView {
override var contentSize: CGSize {
didSet {
if !constraints.isEmpty {
invalidateIntrinsicContentSize()
} else {
sizeToFit()
}
if contentSize != oldValue {
if let delegate = delegate as? ContentFittingTableViewDelegate {
delegate.tableViewDidUpdateContentSize(self)
}
}
}
}
override var intrinsicContentSize: CGSize {
return contentSize
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return contentSize
}
}
def colision(rect, circle):
dx = rect.x - circle.x
dy = rect.y - circle.y
distance = (dy**2 + dx**2)**0.5
angle_to = (rect.angle + math.atan2(dx, dy)/3.1415*180.0) % 360
if((angle_to>135 and angle_to<225) or (angle_to>0 and angle_to<45) or (angle_to>315 and angle_to<360)):
if distance <= circle.rad/2.+((rect.height/2.0)*(1.+0.5*abs(math.sin(angle_to*math.pi/180.)))):
return True
else:
if distance <= circle.rad/2.+((rect.width/2.0)*(1.+0.5*abs(math.cos(angle_to*math.pi/180.)))):
return True
return False
For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc
to a structure below ~/.config
. For example, Qt 4 uses ~/.config/<vendor>/<programname>
with the default settings of QSettings
. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config
, XFCE does use ~/.config
).
As with SQL Server 2012, you can use the built-in format function:
SELECT FORMAT(Minutes/60.0, 'N2')
(just for further readings...)
yo have to declarate de vars...
var selectedRowId = $('#list').jqGrid ('getGridParam', 'selrow');
var columnName = $('#list').jqGrid('getCell', selectedRowId, 'columnName');
var nombre_img_articulo = $('#list').jqGrid('getCell', selectedRowId, 'img_articulo');
The compiler declares the variable in a way that makes it highly prone to an error that is often difficult to find and debug, while producing no perceivable benefits.
Your criticism is entirely justified.
I discuss this problem in detail here:
Closing over the loop variable considered harmful
Is there something you can do with foreach loops this way that you couldn't if they were compiled with an inner-scoped variable? or is this just an arbitrary choice that was made before anonymous methods and lambda expressions were available or common, and which hasn't been revised since then?
The latter. The C# 1.0 specification actually did not say whether the loop variable was inside or outside the loop body, as it made no observable difference. When closure semantics were introduced in C# 2.0, the choice was made to put the loop variable outside the loop, consistent with the "for" loop.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time.
The for
loop will not be changed, and the change will not be "back ported" to previous versions of C#. You should therefore continue to be careful when using this idiom.
Check out the manual: http://www.php.net/manual/en/datetime.format.php
<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>
Will output: 2000-01-01 00:00:00
One can invoke mysqldump locally against a remote server.
Example that worked for me:
mysqldump -h hostname-of-the-server -u mysql_user -p database_name > file.sql
I followed the mysqldump documentation on connection options.
I was using http://www.netlimiter.com/ and it works very well. Not only limit speed for single processes but also shows actual transfer rates.
In .NET 5.0 and later you can use the Convert.ToHexString()
method.
using System;
using System.Text;
string value = "Hello world";
byte[] bytes = Encoding.UTF8.GetBytes(value);
string hexString = Convert.ToHexString(bytes);
Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($" Hex value: \"{hexString}\"");
Running the above example code, you would get the following output:
String value: "Hello world"
Hex value: "48656C6C6F20776F726C64"
You can use following methods to get current date in milliseconds.
[[NSDate date] timeIntervalSince1970];
OR
double CurrentTime = CACurrentMediaTime();
If you have a button inside a Column() and want the button to take maximum width, set:
crossAxisAlignment: CrossAxisAlignment.stretch
in your Column widget. Now everything under this Column() will have maximum available width
Create a file with name .env
in the main directory besidespackage.json
and set PORT
variable to desired port number.
For example:
.env
PORT=4200
You can find the documentation for this action here: https://create-react-app.dev/docs/advanced-configuration
To check column exists
select column_name as found
from user_tab_cols
where table_name = '__TABLE_NAME__'
and column_name = '__COLUMN_NAME__'
This code is using the new React context API:
import React, { PureComponent, createContext } from 'react';
const { Provider, Consumer } = createContext({ width: 0, height: 0 });
class WindowProvider extends PureComponent {
state = this.getDimensions();
componentDidMount() {
window.addEventListener('resize', this.updateDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateDimensions);
}
getDimensions() {
const w = window;
const d = document;
const documentElement = d.documentElement;
const body = d.getElementsByTagName('body')[0];
const width = w.innerWidth || documentElement.clientWidth || body.clientWidth;
const height = w.innerHeight || documentElement.clientHeight || body.clientHeight;
return { width, height };
}
updateDimensions = () => {
this.setState(this.getDimensions());
};
render() {
return <Provider value={this.state}>{this.props.children}</Provider>;
}
}
Then you can use it wherever you want in your code like this:
<WindowConsumer>
{({ width, height }) => //do what you want}
</WindowConsumer>
Within your component, you can define an array of number (ES6) as described below:
export class SampleComponent {
constructor() {
this.numbers = Array(5).fill(0).map((x,i)=>i);
}
}
See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.
You can then iterate over this array with ngFor
:
@View({
template: `
<ul>
<li *ngFor="let number of numbers">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Or shortly:
@View({
template: `
<ul>
<li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
</ul>
`
})
export class SampleComponent {
(...)
}
Hope it helps you, Thierry
Edit: Fixed the fill statement and template syntax.
As @Raedwald pointed out, Java's Unicode doesn't cater to all the characters to get ASCII value. The correct way (Java 1.7+) is as follows :
byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)
Option #1: Try invalidateOptionsMenu()
. I don't know if this will force an immediate redraw of the action bar or not.
Option #2: See if getActionView()
returns anything for the affected MenuItem
. It is possible that showAsAction
simply automatically creates action views for you. If so, you can presumably enable/disable that View
.
I can't seem to find a way to get the currently set Menu to manipulate it except for in onPrepareOptionMenu.
You can hang onto the Menu
object you were handed in onCreateOptionsMenu()
. Quoting the docs:
You can safely hold on to menu (and any items created from it), making modifications to it as desired, until the next time onCreateOptionsMenu() is called.
Had similar problem. Added in build.gradle and it worked for me.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
you can delete it manually.
cd C:\Users\<you name>\AppData\Local\Microsoft\WindowsApps
del python.exe
del python3.exe
Now the command prompt won't be showing it anymore
where python
--> yields nothing, and you are free to install another version from source / anaconda and (after adding its address to Environment Variables -> Path) you will find that very python you just installed
I have made a little example using css
.hover {_x000D_
position: relative;_x000D_
top: 50px;_x000D_
left: 50px;_x000D_
}_x000D_
_x000D_
.tooltip {_x000D_
/* hide and position tooltip */_x000D_
top: -10px;_x000D_
background-color: black;_x000D_
color: white;_x000D_
border-radius: 5px;_x000D_
opacity: 0;_x000D_
position: absolute;_x000D_
-webkit-transition: opacity 0.5s;_x000D_
-moz-transition: opacity 0.5s;_x000D_
-ms-transition: opacity 0.5s;_x000D_
-o-transition: opacity 0.5s;_x000D_
transition: opacity 0.5s;_x000D_
}_x000D_
_x000D_
.hover:hover .tooltip {_x000D_
/* display tooltip on hover */_x000D_
opacity: 1;_x000D_
}
_x000D_
<div class="hover">hover_x000D_
<div class="tooltip">asdadasd_x000D_
</div>_x000D_
</div>
_x000D_
FIDDLE
Try this one:
<body onload="imageRefreshBig();">
Also you might want to check Javascript console for errors (in Chrome it's under Shift + Ctrl + J).
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
You need to precede the lines starting with gcc
and rm
with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line).
The result should look like this:
PROG = semsearch
all: $(PROG)
%: %.c
gcc -o $@ $< -lpthread
clean:
rm $(PROG)
Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:
PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread
clean: ; rm $(PROG)
From the fine manual:
ALTER TABLE mytable ALTER COLUMN mycolumn DROP NOT NULL;
There's no need to specify the type when you're just changing the nullability.
On spring boot 2 with webflux you need to define a ReactiveAuthenticationManager
Works the best. If you want to use it sitewide, without having to add this syntax to every class or ID, add the following CSS to your css body:
body {
-webkit-font-smoothing: antialiased;
text-shadow: 1px 1px 1px rgba(0,0,0,0.004);
background: url('./images/background.png');
text-align: left;
margin: auto;
}
I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:
myDiv {
min-height: 100%;
overflow-y: hidden;
position: relative;
}
That should do the job!
Try wrapping your entire select in brackets, then running a count(*) on that
select count(*)
from
(
select m.id
from Monitor as m
inner join Monitor_Request as mr
on mr.Company_ID=m.Company_id group by m.Company_id
having COUNT(m.Monitor_id)>=5
) myNewTable
First thing that comes into my mind:
read -r a b c <<<$(echo 1 2 3) ; echo "$a|$b|$c"
output is, unsurprisingly
1|2|3
nohup some_command > /dev/null 2>&1&
That's all you need to do!
I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors
It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked
1) Added Addcors in ConfigureServices of Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
2) Added UseCors in Configure method as below:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(builder =>builder.AllowAnyOrigin());
app.UseMvc();
}
There is no bound checking in array in C programming. If you declare array as
int arr[50];
Then you can even write as
arr[51] = 10;
The compiler would not throw an error. Hope this answers your question.
Three of the suggested methods were tested for speed with 1000 RGBA PNG images (224 x 256 pixels) running with Python 3.5 on Ubuntu 16.04 LTS (Xeon E5 2670 with SSD).
Average run times
pil :
1.037 seconds
scipy:
1.040 seconds
sk :
2.120 seconds
PIL and SciPy gave identical numpy
arrays (ranging from 0 to 255). SkImage gives arrays from 0 to 1. In addition the colors are converted slightly different, see the example from the CUB-200 dataset.
Code
Performance
run_times = dict(sk=list(), pil=list(), scipy=list())
for t in range(100):
start_time = time.time()
for i in range(1000):
z = random.choice(filenames_png)
img = skimage.color.rgb2gray(skimage.io.imread(z))
run_times['sk'].append(time.time() - start_time)
start_time = time.time()
for i in range(1000):
z = random.choice(filenames_png)
img = np.array(Image.open(z).convert('L'))
run_times['pil'].append(time.time() - start_time)
start_time = time.time()
for i in range(1000):
z = random.choice(filenames_png)
img = scipy.ndimage.imread(z, mode='L')
run_times['scipy'].append(time.time() - start_time)
for k, v in run_times.items():
print('{:5}: {:0.3f} seconds'.format(k, sum(v) / len(v)))
z = 'Cardinal_0007_3025810472.jpg'
img1 = skimage.color.rgb2gray(skimage.io.imread(z)) * 255
IPython.display.display(PIL.Image.fromarray(img1).convert('RGB'))
img2 = np.array(Image.open(z).convert('L'))
IPython.display.display(PIL.Image.fromarray(img2))
img3 = scipy.ndimage.imread(z, mode='L')
IPython.display.display(PIL.Image.fromarray(img3))
img_diff = np.ndarray(shape=img1.shape, dtype='float32')
img_diff.fill(128)
img_diff += (img1 - img3)
img_diff -= img_diff.min()
img_diff *= (255/img_diff.max())
IPython.display.display(PIL.Image.fromarray(img_diff).convert('RGB'))
import skimage.color
import skimage.io
import random
import time
from PIL import Image
import numpy as np
import scipy.ndimage
import IPython.display
skimage.version
0.13.0
scipy.version
0.19.1
np.version
1.13.1
You can find a complete list of Key Codes and an explanation here: http://code.google.com/p/androhid/wiki/Keycodes
Perhaps:
> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)
also had problems with rapidly growing overlay2
/var/lib/docker/overlay2
- is a folder where docker store writable layers for your container.
docker system prune -a
- may work only if container is stopped and removed.
in my i was able to figure out what consumes space by going into overlay2
and investigating.
that folder contains other hash named folders. each of those has several folders including diff
folder.
diff
folder - contains actual difference written by a container with exact folder structure as your container (at least it was in my case - ubuntu 18...)
so i've used du -hsc /var/lib/docker/overlay2/LONGHASHHHHHHH/diff/tmp
to figure out that /tmp
inside of my container is the folder which gets polluted.
so as a workaround i've used -v /tmp/container-data/tmp:/tmp
parameter for docker run
command to map inner /tmp
folder to host and setup a cron on host to cleanup that folder.
cron task was simple:
sudo nano /etc/crontab
*/30 * * * * root rm -rf /tmp/container-data/tmp/*
save and exit
NOTE: overlay2
is system docker folder, and they may change it structure anytime. Everything above is based on what i saw in there. Had to go in docker folder structure only because system was completely out of space and even wouldn't allow me to ssh into docker container.
From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.
cesards's answer is correct, but only for API > 15. For lower API versions I decided to use getRunningTasks()
method:
private boolean isAppInForeground(Context context)
{
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
{
ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
ActivityManager.RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName();
return foregroundTaskPackageName.toLowerCase().equals(context.getPackageName().toLowerCase());
}
else
{
ActivityManager.RunningAppProcessInfo appProcessInfo = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(appProcessInfo);
if (appProcessInfo.importance == IMPORTANCE_FOREGROUND || appProcessInfo.importance == IMPORTANCE_VISIBLE)
{
return true;
}
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
// App is foreground, but screen is locked, so show notification
return km.inKeyguardRestrictedInputMode();
}
}
Please, let me know if it works for you all.
SELECT datetime('now', 'localtime');
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
See Do I need to heartbeat to keep a TCP connection open? for more discussion.
Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..
I know that this already has been answered but.....
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:fromAlpha="1.0"
android:toAlpha="0.0"
android:duration="1000"
android:repeatCount="infinite"
android:repeatMode="reverse"
/>
Quick and easy way to quickly do a fade in and out with a self repeat. Enjoy
EDIT : In your activity add this:
yourView.startAnimation(AnimationUtils.loadAnimation(co??ntext, R.anim.yourAnimation));
For a specific file:
- git reset my_file.txt
- git checkout my_file.txt
For all added files:
- git reset .
- git checkout .
Note: checkout changes the code in the files and moves to the last updated (committed) state. reset doesn't change the codes; it just resets the header.
I also getting the same error. i have copied the api_key and change into google_services.json. after that it workig for me
"api_key": [
{
"current_key": "********************"
}
],
try this
It sounds like you want an image
button:
<input type="image" src="logg.png" name="saveForm" class="btTxt submit" id="saveForm" />
Alternatively, you can use CSS to make the existing submit
button use your image as its background.
In any case, you don't want a separate <img />
element on the page.
I have found a great work-around for this. It really only works practically if you want to be able to select up to 4 or so options from your drop down list but here it is:
For each "item" create as many rows as drop-down items you'd like to be able to select. So if you want to be able to select up to 3 characteristics from a given drop down list for each person on your list, create a total of 3 rows for each person. Then merge A:1-A:3, B:1-B:3, C:1-C:3 etc until you reach the column that you'd like your drop-down list to be. Don't merge those cells, instead place the your Data Validation drop-down in each of those cells.
Hope this is clear!!
Beautify does a good job. It provides a "Beautify on save" option, so that you may use ctrl+s to reformate html, less, css, etc
Jordans analysis of why the $_POST-array isn't populated is correct. However, you can use
$data = file_get_contents("php://input");
to just retrieve the http body and handle it yourself. See PHP input/output streams.
From a protocol perspective this is actually more correct, since you're not really processing http multipart form data anyway. Also, use application/json as content-type when posting your request.
No, there is no CSS property for minimum or maximum font size. Browsers often have a setting for minimum font size, but that’s under the control of the user, not an author.
You can use @media
queries to make some CSS settings depending on things like screen or window width. In such settings, you can e.g. set the font size to a specific small value if the window is very narrow.
You can use:
<asp:textbox id="textBox1" style="text-align:center"></asp:textbox>
Or this:
textbox.Style["text-align"] = "center"; //right, left
You can use the function RESHAPE:
B = reshape(A.',1,[]);
The basic intrinsic types (e.g. byte
, int
, string
, and arrays) will be serialized automatically by WCF. Custom classes, like your UploadedFile, won't be.
So, a silly question (but I have to ask it...): is UploadedFile marked as a [DataContract]
? If not, you'll need to make sure that it is, and that each of the members in the class that you want to send are marked with [DataMember].
Unlike remoting, where marking a class with [XmlSerializable] allowed you to serialize the whole class without bothering to mark the members that you wanted serialized, WCF needs you to mark up each member. (I believe this is changing in .NET 3.5 SP1...)
A tremendous resource for WCF development is what we know in our shop as "the fish book": Programming WCF Services by Juval Lowy. Unlike some of the other WCF books around, which are a bit dry and academic, this one takes a practical approach to building WCF services and is actually useful. Thoroughly recommended.
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
Real programmers do it with semaphores.
Have a variable set to 0
. Increment it before each AJAX call. Decrement it in each success handler, and test for 0
. If it is, you're done.
I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S
:
# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80 is a NameVirtualHost
default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
[...]
11.22.33.44:443 is a NameVirtualHost
default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80 hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001 hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000 hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443 hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001 hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000 hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK
Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).
Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default
on line 33 and /etc/apache2/sites-enabled/default-ssl
on line 163. Likewise *:30000
is listed in 2 places. The solution (in my case) was simply to delete one of the entries.
You can use the RANK function in Excel without necessarily sorting the data. Type =RANK(C2,$C$2:$C$7). Excel will find the relative position of the data in C2 and display the answer. Copy the formula through to C7 by dragging the small node at the right end of the cell cursor.
Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.
angular.module('mymodule', [])
// Click to navigate
// similar to <a href="#/partial"> but hash is not required,
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
return {
link: function(scope, element, attrs) {
element.on('click', function() {
scope.$apply(function() {
$location.path(attrs.clickLink);
});
});
}
}
}]);
It has some useful features, but I'm new to Angular so there's probably room for improvement.
You can set the format you want:
dataGridViewCellStyle.Format = "dd/MM/yyyy";
this.date.DefaultCellStyle = dataGridViewCellStyle;
// date being a System.Windows.Forms.DataGridViewTextBoxColumn
Building on @rocksportrocker solution, It would make sense to dill when sending and RECVing the results.
import dill
import itertools
def run_dill_encoded(payload):
fun, args = dill.loads(payload)
res = fun(*args)
res = dill.dumps(res)
return res
def dill_map_async(pool, fun, args_list,
as_tuple=True,
**kw):
if as_tuple:
args_list = ((x,) for x in args_list)
it = itertools.izip(
itertools.cycle([fun]),
args_list)
it = itertools.imap(dill.dumps, it)
return pool.map_async(run_dill_encoded, it, **kw)
if __name__ == '__main__':
import multiprocessing as mp
import sys,os
p = mp.Pool(4)
res = dill_map_async(p, lambda x:[sys.stdout.write('%s\n'%os.getpid()),x][-1],
[lambda x:x+1]*10,)
res = res.get(timeout=100)
res = map(dill.loads,res)
print(res)
MongoDB
has a sophisticated feature of profiling. The logging happens in system.profile
collection. The logs can be seen from:
db.system.profile.find()
There are 3 logging levels (source):
To see what profiling level the database is running in, use
db.getProfilingLevel()
and to see the status
db.getProfilingStatus()
To change the profiling status, use the command
db.setProfilingLevel(level, milliseconds)
Where level
refers to the profiling level and milliseconds
is the ms of which duration the queries needs to be logged. To turn off the logging, use
db.setProfilingLevel(0)
The query to look in the system profile collection for all queries that took longer than one second, ordered by timestamp descending will be
db.system.profile.find( { millis : { $gt:1000 } } ).sort( { ts : -1 } )
I'm a day late and a dollar short on this one. If you want to view the folder structure of the GAC in Windows Explorer, you can do this by using the registry:
For a temporary view, you can substitute a drive for the folder path, which strips away the special directory properties.
As for why you'd want to do something like this, I've used this trick to compare GAC'd DLLs between different machines to make sure they're truly the same.
No muss, no fuss
@interface MFTopAlignedLabel : UILabel
@end
@implementation MFTopAlignedLabel
- (void)drawTextInRect:(CGRect) rect
{
NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:self.text attributes:@{NSFontAttributeName:self.font}];
rect.size.height = [attributedText boundingRectWithSize:rect.size
options:NSStringDrawingUsesLineFragmentOrigin
context:nil].size.height;
if (self.numberOfLines != 0) {
rect.size.height = MIN(rect.size.height, self.numberOfLines * self.font.lineHeight);
}
[super drawTextInRect:rect];
}
@end
No muss, no Objective-c, no fuss but Swift 3:
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSFontAttributeName: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
Swift 4.2
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSAttributedString.Key.font: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
line 2 should be
for (int i = 0; i < jsonMainArr.size(); i++) { // **line 2**
For line 3, I'm having to do
JSONObject childJSONObject = (JSONObject) new JSONParser().parse(jsonMainArr.get(i).toString());
Reading this article I noticed great benefits using Guard
Here you can compare the use of guard with an example:
This is the part without guard:
func fooBinding(x: Int?) {
if let x = x where x > 0 {
// Do stuff with x
x.description
}
// Value requirements not met, do something
}
Here you’re putting your desired code within all the conditions
You might not immediately see a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements
The way to clean this up is to do each of your checks first, and exit if any aren’t met. This allows easy understanding of what conditions will make this function exit.
But now we can use guard and we can see that is possible to resolve some issues:
func fooGuard(x: Int?) {
guard let x = x where x > 0 else {
// Value requirements not met, do something
return
}
// Do stuff with x
x.description
}
- Checking for the condition you do want, not the one you don’t. This again is similar to an assert. If the condition is not met, guard‘s else statement is run, which breaks out of the function.
- If the condition passes, the optional variable here is automatically unwrapped for you within the scope that the guard statement was called – in this case, the fooGuard(_:) function.
- You are checking for bad cases early, making your function more readable and easier to maintain
This same pattern holds true for non-optional values as well:
func fooNonOptionalGood(x: Int) {
guard x > 0 else {
// Value requirements not met, do something
return
}
// Do stuff with x
}
func fooNonOptionalBad(x: Int) {
if x <= 0 {
// Value requirements not met, do something
return
}
// Do stuff with x
}
If you still have any questions you can read the entire article: Swift guard statement.
Wrapping Up
And finally, reading and testing I found that if you use guard to unwrap any optionals,
those unwrapped values stay around for you to use in the rest of your code block
.
guard let unwrappedName = userName else {
return
}
print("Your username is \(unwrappedName)")
Here the unwrapped value would be available only inside the if block
if let unwrappedName = userName {
print("Your username is \(unwrappedName)")
} else {
return
}
// this won't work – unwrappedName doesn't exist here!
print("Your username is \(unwrappedName)")
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
Using requests and json makes it simple.
json.loads
functionRequests module provides you useful function to loop for success and failure.
if(Response.ok)
: will help help you determine if your API call is successful (Response code - 200)
Response.raise_for_status()
will help you fetch the http code that is returned from the API.
Below is a sample code for making such API calls. Also can be found in github. The code assumes that the API makes use of digest authentication. You can either skip this or use other appropriate authentication modules to authenticate the client invoking the API.
#Python 2.7.6
#RestfulClient.py
import requests
from requests.auth import HTTPDigestAuth
import json
# Replace with the correct URL
url = "http://api_url"
# It is a good practice not to hardcode the credentials. So ask the user to enter credentials at runtime
myResponse = requests.get(url,auth=HTTPDigestAuth(raw_input("username: "), raw_input("Password: ")), verify=True)
#print (myResponse.status_code)
# For successful API call, response code will be 200 (OK)
if(myResponse.ok):
# Loading the response data into a dict variable
# json.loads takes in only binary or string variables so using content to fetch binary content
# Loads (Load String) takes a Json file and converts into python data structure (dict or list, depending on JSON)
jData = json.loads(myResponse.content)
print("The response contains {0} properties".format(len(jData)))
print("\n")
for key in jData:
print key + " : " + jData[key]
else:
# If response code is not ok (200), print the resulting http error code with description
myResponse.raise_for_status()
I had this problem today, and all one-liners here failed to me because the files contained spaces in the names.
This is what I came up with that worked:
grep -ril <WORD1> | sed 's/.*/"&"/' | xargs grep -il <WORD2>
I was having the same problem while developing my own website. While it was resident locally, resources opened as file//
. For pages from the internet, including my own loaded as http://
, the F12 Developer did use Edge as default, but not while they were loaded into IE11 from local files.
After following the suggestions above, I unchecked the box for "Display intranet Sites in Compatibility View".
That did the trick without adding any extra coding to my web page, or adding a multitude of pages to populate the list. Now all local files open in Edge document mode with F12.
So if you are referring to using F12 for locally hosted files, this may help.
You can do something like this:
a = [1,2,3,4,5]
b = [i**2 for i in a]
It's called a list comprehension, to make it easier for you to loop inside a list.
To set a custom height locked to somewhere:
body, html {_x000D_
height: 100%;_x000D_
}_x000D_
#outerbox {_x000D_
width: 100%;_x000D_
position: absolute; /* to place it somewhere on the screen */_x000D_
top: 130px; /* free space at top */_x000D_
bottom: 0; /* makes it lock to the bottom */_x000D_
}_x000D_
#innerbox {_x000D_
width: 100%;_x000D_
position: absolute; _x000D_
min-height: 100% !important; /* browser fill */_x000D_
height: auto; /*content fill */_x000D_
}
_x000D_
<div id="outerbox">_x000D_
<div id="innerbox"></div>_x000D_
</div>
_x000D_
must means: The clause (query) must appear in matching documents. These clauses must match, like logical AND.
should means: At least one of these clauses must match, like logical OR.
Basically they are used like logical operators AND and OR. See this.
Now in a bool query:
must means: Clauses that must match for the document to be included.
should means: If these clauses match, they increase the _score
; otherwise, they have no effect. They are simply used to refine the relevance score for each document.
Yes you can use multiple filters inside must
.
Understand does a very good job of creating call graphs.
fun Fragment?.runOnUiThread(action: () -> Unit) {
this ?: return
if (!isAdded) return // Fragment not attached to an Activity
activity?.runOnUiThread(action)
}
Then, in any Fragment
you can just call runOnUiThread
. This keeps calls consistent across activities and fragments.
runOnUiThread {
// Call your code here
}
NOTE: If
Fragment
is no longer attached to anActivity
, callback will not be called and no exception will be thrown
If you want to access this style from anywhere, you can add a common object and import the method:
object ThreadUtil {
private val handler = Handler(Looper.getMainLooper())
fun runOnUiThread(action: () -> Unit) {
if (Looper.myLooper() != Looper.getMainLooper()) {
handler.post(action)
} else {
action.invoke()
}
}
}
Is it possible to set a number to NaN or infinity?
Yes, in fact there are several ways. A few work without any imports, while others require import
, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).
The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float
:
+-------------------------------------------------------------------+
¦ result ¦ NaN ¦ Infinity ¦ -Infinity ¦
¦ module ¦ ¦ ¦ ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf") ¦ -float("inf") ¦
¦ ¦ ¦ float("infinity") ¦ -float("infinity") ¦
¦ ¦ ¦ float("+inf") ¦ float("-inf") ¦
¦ ¦ ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math ¦ math.nan ¦ math.inf ¦ -math.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath ¦ cmath.nan ¦ cmath.inf ¦ -cmath.inf ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy ¦ numpy.nan ¦ numpy.PINF ¦ numpy.NINF ¦
¦ ¦ numpy.NaN ¦ numpy.inf ¦ -numpy.inf ¦
¦ ¦ numpy.NAN ¦ numpy.infty ¦ -numpy.infty ¦
¦ ¦ ¦ numpy.Inf ¦ -numpy.Inf ¦
¦ ¦ ¦ numpy.Infinity ¦ -numpy.Infinity ¦
+-------------------------------------------------------------------+
A couple remarks to the table:
float
constructor is actually case-insensitive, so you can also use float("NaN")
or float("InFiNiTy")
. cmath
and numpy
constants return plain Python float
objects.numpy.NINF
is actually the only constant I know of that doesn't require the -
.It is possible to create complex NaN and Infinity with complex
and cmath
:
+------------------------------------------------------------------------------------------+
¦ result ¦ NaN+0j ¦ 0+NaNj ¦ Inf+0j ¦ 0+Infj ¦
¦ module ¦ ¦ ¦ ¦ ¦
¦----------+----------------+-----------------+---------------------+----------------------¦
¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf") ¦ complex("infj") ¦
¦ ¦ ¦ ¦ complex("infinity") ¦ complex("infinityj") ¦
+----------+----------------+-----------------+---------------------+----------------------¦
¦ cmath ¦ cmath.nan ¹ ¦ cmath.nanj ¦ cmath.inf ¹ ¦ cmath.infj ¦
+------------------------------------------------------------------------------------------+
The options with ¹ return a plain float
, not a complex
.
is there any function to check whether a number is infinity or not?
Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import
:
+--------------------------------------------------------------+
¦ for ¦ NaN ¦ Infinity or ¦ not NaN and ¦
¦ ¦ ¦ -Infinity ¦ not Infinity and ¦
¦ module ¦ ¦ ¦ not -Infinity ¦
¦----------+-------------+----------------+--------------------¦
¦ math ¦ math.isnan ¦ math.isinf ¦ math.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ cmath ¦ cmath.isnan ¦ cmath.isinf ¦ cmath.isfinite ¦
+----------+-------------+----------------+--------------------¦
¦ numpy ¦ numpy.isnan ¦ numpy.isinf ¦ numpy.isfinite ¦
+--------------------------------------------------------------+
Again a couple of remarks:
cmath
and numpy
functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.numpy
functions also work for numpy
arrays and everything that can be converted to one (like lists, tuple, etc.)numpy.isposinf
and numpy.isneginf
.NaN
: pandas.isna
and pandas.isnull
(but not only NaN, it matches also None
and NaT
)Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):
def isnan(value):
return value != value # NaN is not equal to anything, not even itself
infinity = float("infinity")
def isinf(value):
return abs(value) == infinity
def isfinite(value):
return not (isnan(value) or isinf(value))
To summarize the expected results for these functions (assuming the input is a float):
+----------------------------------------------------------------------+
¦ input ¦ NaN ¦ Infinity ¦ -Infinity ¦ something else ¦
¦ function ¦ ¦ ¦ ¦ ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan ¦ True ¦ False ¦ False ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf ¦ False ¦ True ¦ True ¦ False ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite ¦ False ¦ False ¦ False ¦ True ¦
+----------------------------------------------------------------------+
Is it possible to set an element of an array to NaN in Python?
In a list it's no problem, you can always include NaN (or Infinity) there:
>>> [math.nan, math.inf, -math.inf, 1] # python list
[nan, inf, -inf, 1]
However if you want to include it in an array
(for example array.array
or numpy.array
) then the type of the array must be float
or complex
because otherwise it will try to downcast it to the arrays type!
>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan, 0., 0.])
>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])
>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer
ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;
worked in Oracle
e.g:
ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;
TypeScript v3.7.3
export enum YourEnum {
enum1 = 'enum1',
enum2 = 'enum2',
enum3 = 'enum3',
}
const status = 'enumnumnum';
if (!(status in YourEnum)) {
throw new UnprocessableEntityResponse('Invalid enum val');
}
I'll just put it here for others.
Match all punctuation chars for for all languages:
Constructed from Unicode punctuation category and added some common keyboard symbols like $
and brackets and \-=_
http://www.fileformat.info/info/unicode/category/Po/list.htm
basic replace:
".test'da, te\"xt".replace(/[\-=_!"#%&'*{},.\/:;?\(\)\[\]@\\$\^*+<>~`\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2016\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18\u2e19\u2e1b\u2e1e\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g,"")
"testda text"
added \s as space
".da'fla, te\"te".split(/[\s\-=_!"#%&'*{},.\/:;?\(\)\[\]@\\$\^*+<>~`\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2016\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18\u2e19\u2e1b\u2e1e\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g)
added ^ to invert patternt to match not punctuation but the words them selves
".test';the, te\"xt".match(/[^\s\-=_!"#%&'*{},.\/:;?\(\)\[\]@\\$\^*+<>~`\u00a1\u00a7\u00b6\u00b7\u00bf\u037e\u0387\u055a-\u055f\u0589\u05c0\u05c3\u05c6\u05f3\u05f4\u0609\u060a\u060c\u060d\u061b\u061e\u061f\u066a-\u066d\u06d4\u0700-\u070d\u07f7-\u07f9\u0830-\u083e\u085e\u0964\u0965\u0970\u0af0\u0df4\u0e4f\u0e5a\u0e5b\u0f04-\u0f12\u0f14\u0f85\u0fd0-\u0fd4\u0fd9\u0fda\u104a-\u104f\u10fb\u1360-\u1368\u166d\u166e\u16eb-\u16ed\u1735\u1736\u17d4-\u17d6\u17d8-\u17da\u1800-\u1805\u1807-\u180a\u1944\u1945\u1a1e\u1a1f\u1aa0-\u1aa6\u1aa8-\u1aad\u1b5a-\u1b60\u1bfc-\u1bff\u1c3b-\u1c3f\u1c7e\u1c7f\u1cc0-\u1cc7\u1cd3\u2016\u2017\u2020-\u2027\u2030-\u2038\u203b-\u203e\u2041-\u2043\u2047-\u2051\u2053\u2055-\u205e\u2cf9-\u2cfc\u2cfe\u2cff\u2d70\u2e00\u2e01\u2e06-\u2e08\u2e0b\u2e0e-\u2e16\u2e18\u2e19\u2e1b\u2e1e\u2e1f\u2e2a-\u2e2e\u2e30-\u2e39\u3001-\u3003\u303d\u30fb\ua4fe\ua4ff\ua60d-\ua60f\ua673\ua67e\ua6f2-\ua6f7\ua874-\ua877\ua8ce\ua8cf\ua8f8-\ua8fa\ua92e\ua92f\ua95f\ua9c1-\ua9cd\ua9de\ua9df\uaa5c-\uaa5f\uaade\uaadf\uaaf0\uaaf1\uabeb\ufe10-\ufe16\ufe19\ufe30\ufe45\ufe46\ufe49-\ufe4c\ufe50-\ufe52\ufe54-\ufe57\ufe5f-\ufe61\ufe68\ufe6a\ufe6b\uff01-\uff03\uff05-\uff07\uff0a\uff0c\uff0e\uff0f\uff1a\uff1b\uff1f\uff20\uff3c\uff61\uff64\uff65]+/g)
for language like Hebrew maybe to remove " ' the single and the double quote. and do more thinking on it.
using this script:
step 1: select in Firefox holding control a column of U+1234 numbers and copy it, do not copy U+12456 they replace English
step 2 (i did in chrome)find some textarea and paste it into it then rightclick and click inspect. then you can access the selected element with $0.
var x=$0.value
var z=x.replace(/U\+/g,"").split(/[\r\n]+/).map(function(a){return parseInt(a,16)})
var ret=[];z.forEach(function(a,k){if(z[k-1]===a-1 && z[k+1]===a+1) { if(ret[ret.length-1]!="-")ret.push("-");} else { var c=a.toString(16); var prefix=c.length<3?"\\u0000":c.length<5?"\\u0000":"\\u000000"; var uu=prefix.substring(0,prefix.length-c.length)+c; ret.push(c.length<3?String.fromCharCode(a):uu)}});ret.join("")
step 3 copied over the first letters the ascii as separate chars not ranges because someone might add or remove individual chars
_method
hidden field workaround
Used in Rails and could be adapted to any framework:
add a hidden _method
parameter to any form that is not GET or POST:
<input type="hidden" name="_method" value="DELETE">
This can be done automatically in frameworks through the HTML creation helper method (e.g. Rails form_tag
)
fix the actual form method to POST (<form method="post"
)
processes _method
on the server and do exactly as if that method had been sent instead of the actual POST
Rationale / history of why it is not possible: https://softwareengineering.stackexchange.com/questions/114156/why-there-are-no-put-and-delete-methods-in-html-forms
Change to another USB port works for me. I tried reset ADB, but problem still there.
You use something like
from flask import send_file
@app.route('/get_image')
def get_image():
if request.args.get('type') == '1':
filename = 'ok.gif'
else:
filename = 'error.gif'
return send_file(filename, mimetype='image/gif')
to send back ok.gif
or error.gif
, depending on the type query parameter. See the documentation for the send_file
function and the request
object for more information.
"Converting a varbinary
to a varchar
" can mean different things.
If the varbinary is the binary representation of a string in SQL Server (for example returned by casting to varbinary
directly or from the DecryptByPassPhrase
or DECOMPRESS
functions) you can just CAST
it
declare @b varbinary(max)
set @b = 0x5468697320697320612074657374
select cast(@b as varchar(max)) /*Returns "This is a test"*/
This is the equivalent of using CONVERT
with a style parameter of 0
.
CONVERT(varchar(max), @b, 0)
Other style parameters are available with CONVERT
for different requirements as noted in other answers.
You can add functionality to an Array by extending its prototype
object.
Array.prototype.nullify = function( n ) {
n = n >>> 0;
for( var i = 0; i < n; ++i ) {
this[ i ] = null;
}
return this;
};
Then:
var arr = [].nullify(9);
or:
var arr = [].nullify(9).map(function() { return [].nullify(9); });
This is another functional lib with which you may use map: http://code.google.com/p/totallylazy/
sequence(1, 2).map(toString); // lazily returns "1", "2"
For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.
Is test.rtf
located in the same directory you're in when you run this?
If not, you'll need to provide the full path to that file.
Suppose it's located in
/Users/AshleyStallings/Documents/School Work/Computer Programming/Side Projects/data
In that case you'd enter
data/test.rtf
as your file name
Or it could be in
/Users/AshleyStallings/Documents/School Work/Computer Programming/some_other_folder
In that case you'd enter
../some_other_folder/test.rtf
You could take the average buffer gets per execution during a period of activity of the instance:
SELECT username,
buffer_gets,
disk_reads,
executions,
buffer_get_per_exec,
parse_calls,
sorts,
rows_processed,
hit_ratio,
module,
sql_text
-- elapsed_time, cpu_time, user_io_wait_time, ,
FROM (SELECT sql_text,
b.username,
a.disk_reads,
a.buffer_gets,
trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
a.parse_calls,
a.sorts,
a.executions,
a.rows_processed,
100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
module
-- cpu_time, elapsed_time, user_io_wait_time
FROM v$sqlarea a, dba_users b
WHERE a.parsing_user_id = b.user_id
AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
AND a.buffer_gets > 10000
ORDER BY buffer_get_per_exec DESC)
WHERE ROWNUM <= 20
The Matlab Compiler is the standard way to do this. mcc
is the command. The Matlab Runtime is required to run the programs; I'm not sure if it can be directly integrated with the executable or not.
You can try with:
display: inline-table;
For me it works fine.
They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20
).
In fact, the RFC even states that spaces are delimiters and should be ignored:
In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.
and
For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.
Curiously, the use of +
as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).
The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.
You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file (config.inc.php
) for you. This file is found at the root of the phpMyAdmin directory.
Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.
You now have only to move the config.inc.php
file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.
Don't forget to delete the config folder afterwards.
I don't know if this solves your problem but instead of:
$("#tbIntervalos").find("td").attr("id", horaInicial);
you can just do:
$("#tbIntervalos td#" + horaInicial);
Everyone seems to like while (true)
:
https://stackoverflow.com/a/224142/1508519
https://stackoverflow.com/a/1401169/1508519
https://stackoverflow.com/a/1401165/1508519
https://stackoverflow.com/a/1401164/1508519
https://stackoverflow.com/a/1401176/1508519
According to SLaks, they compile identically.
Ben Zotto also says it doesn't matter:
It's not faster. If you really care, compile with assembler output for your platform and look to see. It doesn't matter. This never matters. Write your infinite loops however you like.
In response to user1216838, here's my attempt to reproduce his results.
Here's my machine:
cat /etc/*-release
CentOS release 6.4 (Final)
gcc version:
Target: x86_64-unknown-linux-gnu
Thread model: posix
gcc version 4.8.2 (GCC)
And test files:
// testing.cpp
#include <iostream>
int main() {
do { break; } while(1);
}
// testing2.cpp
#include <iostream>
int main() {
while(1) { break; }
}
// testing3.cpp
#include <iostream>
int main() {
while(true) { break; }
}
The commands:
gcc -S -o test1.asm testing.cpp
gcc -S -o test2.asm testing2.cpp
gcc -S -o test3.asm testing3.cpp
cmp test1.asm test2.asm
The only difference is the first line, aka the filename.
test1.asm test2.asm differ: byte 16, line 1
Output:
.file "testing2.cpp"
.local _ZStL8__ioinit
.comm _ZStL8__ioinit,1,1
.text
.globl main
.type main, @function
main:
.LFB969:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
nop
movl $0, %eax
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE969:
.size main, .-main
.type _Z41__static_initialization_and_destruction_0ii, @function
_Z41__static_initialization_and_destruction_0ii:
.LFB970:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
subq $16, %rsp
movl %edi, -4(%rbp)
movl %esi, -8(%rbp)
cmpl $1, -4(%rbp)
jne .L3
cmpl $65535, -8(%rbp)
jne .L3
movl $_ZStL8__ioinit, %edi
call _ZNSt8ios_base4InitC1Ev
movl $__dso_handle, %edx
movl $_ZStL8__ioinit, %esi
movl $_ZNSt8ios_base4InitD1Ev, %edi
call __cxa_atexit
.L3:
leave
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE970:
.size _Z41__static_initialization_and_destruction_0ii, .-_Z41__static_initialization_and_destruction_0ii
.type _GLOBAL__sub_I_main, @function
_GLOBAL__sub_I_main:
.LFB971:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
movl $65535, %esi
movl $1, %edi
call _Z41__static_initialization_and_destruction_0ii
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE971:
.size _GLOBAL__sub_I_main, .-_GLOBAL__sub_I_main
.section .ctors,"aw",@progbits
.align 8
.quad _GLOBAL__sub_I_main
.hidden __dso_handle
.ident "GCC: (GNU) 4.8.2"
.section .note.GNU-stack,"",@progbits
With -O3
, the output is considerably smaller of course, but still no difference.
var CarId = 23;
//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);
And for basic array numbers you can also do this:
var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
to have unit-testing AND integration-testing you can use maven-surefire-plugin and maven-failsafe-plugin with restricted includes/excludes. I was playing with CDI while getting in touch with sonar/jacoco, so i ended up in this project:
https://github.com/FibreFoX/cdi-sessionscoped-login/
Maybe it helps you a little bit. in my pom.xml i use "-javaagent" implicit by setting the argLine-option in the configuration-section of the specified testing-plugins. Explicit using ANT in MAVEN projects is something i would not give a try, for me its to much mixing two worlds.
I only have a single-module maven project, but maybe it helps you to adjust yours to work.
note: maybe not all maven-plugins are up2date, maybe some issues are fixed in later versions
I solved it by keeping track of the original event that triggered the hashchange
(be it a swipe, a click or a wheel), so that the event wouldn't be mistaken for a simple landing-on-page, and using an additional flag in each of my event bindings. The browser won't set the flag again to false
when hitting the back button:
var evt = null,
canGoBackToThePast = true;
$('#next-slide').on('click touch', function(e) {
evt = e;
canGobackToThePast = false;
// your logic (remember to set the 'canGoBackToThePast' flag back to 'true' at the end of it)
}
If your image is too large (and you can't/don't want to just made the image smaller), a combination of the first two answers works great.
addButton.imageView?.contentMode = .scaleAspectFit
addButton.imageEdgeInsets = UIEdgeInsetsMake(15.0, 15.0, 15.0, 5.0)
Unless you get the image insets just right, the image will be skewed without changing the contentMode
.
Add this to you PHP file or main controller
header("Access-Control-Allow-Origin: http://localhost:9000");
You can write the where
clause as:
where (case when (:stateCode = '') then (1)
when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
else 0)
end) = 1;
Alternatively, remove the case
entirely:
where (:stateCode = '') or
((:stateCode != '') and vw.state_cd in (:stateCode));
Or, even better:
where (:stateCode = '') or vw.state_cd in (:stateCode)
meshgrid helps in creating a rectangular grid from two 1-D arrays of all pairs of points from the two arrays.
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 2, 3, 4])
Now, if you have defined a function f(x,y) and you wanna apply this function to all the possible combination of points from the arrays 'x' and 'y', then you can do this:
f(*np.meshgrid(x, y))
Say, if your function just produces the product of two elements, then this is how a cartesian product can be achieved, efficiently for large arrays.
Referred from here
This way works:
class A
{
struct Wrap
{
A& a;
Wrap(A& aa) aa(a) {}
operator int() { return a.value; }
operator std::string() { stringstream ss; ss << a.value; return ss.str(); }
}
Wrap operator*() { return Wrap(*this); }
};
split(delimiter)
by default removes trailing empty strings from result array. To turn this mechanism off we need to use overloaded version of split(delimiter, limit)
with limit
set to negative value like
String[] split = data.split("\\|", -1);
Little more details:
split(regex)
internally returns result of split(regex, 0)
and in documentation of this method you can find (emphasis mine)
The
limit
parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array.If the limit
n
is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.If
n
is non-positive then the pattern will be applied as many times as possible and the array can have any length.If
n
is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
Exception:
It is worth mentioning that removing trailing empty string makes sense only if such empty strings ware created by split mechanism. So for "".split(anything)
since we can't split ""
farther we will get as result [""]
array.
It happens because split didn't happen here, so ""
despite being empty and trailing represents original string, not empty string which was created by splitting process.
default LocalDateTime getDateFromLong(long timestamp) {
try {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneOffset.UTC);
} catch (DateTimeException tdException) {
// throw new
}
}
default Long getLongFromDateTime(LocalDateTime dateTime) {
return dateTime.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
}
Shift
+ Alt
+ F
indents the whole file.
The only thing you should do is to set optional recursive parameter
to True
.
Directory.Delete("C:\MyDummyDirectory", True)
Thanks to .NET. :)
I have found that using cabs(double)
, cabsf(float)
, cabsl(long double)
, __cabsf(float)
, __cabs(double)
, __cabsf(long double)
is the solution
Basically indexOf()
is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.
document.getElementById("oset").innerHTML = timeD2C(timeofday + "");
var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
var pos = time.indexOf('.');_x000D_
var hrs = time.substr(1, pos - 1);_x000D_
var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
if (hrs > 11) {_x000D_
hrs = (hrs - 12) + ":" + min + " PM";_x000D_
} else {_x000D_
hrs += ":" + min + " AM";_x000D_
}_x000D_
return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
And it is good to do the string conversion inside your function definition,
function timeD2C(time) {
time = time + "";
var pos = time.indexOf('.');
So that the code flow won't break at times when devs forget to pass a string into this function.
Go to >system preferences >mysql >initialize database
-Change password -Click use legacy password -Click start sql server
it should work now
a PK will become a clustered index unless you specify non clustered
Add a trigger in database:
DELIMITER //
CREATE TRIGGER update_user_password
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
IF OLD.password <> NEW.password THEN
SET NEW.password_changed_on = NOW();
END IF;
END //
DELIMITER ;
The password changed time will update only when password column is changed.
When you use spring then you can use
boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
where obj is any [map,collection,array,aything...]
otherwise: the code is:
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
for String best is:
boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
This seemed to work pretty well for me.
private DataTable ReadExcelFile(string sheetName, string path)
{
using (OleDbConnection conn = new OleDbConnection())
{
DataTable dt = new DataTable();
string Import_FileName = path;
string fileExtension = Path.GetExtension(Import_FileName);
if (fileExtension == ".xls")
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";
if (fileExtension == ".xlsx")
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Import_FileName + ";" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'";
using (OleDbCommand comm = new OleDbCommand())
{
comm.CommandText = "Select * from [" + sheetName + "$]";
comm.Connection = conn;
using (OleDbDataAdapter da = new OleDbDataAdapter())
{
da.SelectCommand = comm;
da.Fill(dt);
return dt;
}
}
}
}
For me the issue got resolved by doing the following:
Navigated to Tool --> Options --> Project and Solutions --> Web Projects
I could find the first check box "Use the 64 bit version of IIS Express of web sites and projects" was unchecked.
Selecting this check box helped me in launching the WCF Client.
VS Version : VS2019
Use margin instead of padding in the parent div: http://blog.vjeux.com/2012/css/css-absolute-position-taking-into-account-padding.html
I faced a similar problem. I tried everything with ports, hosts and config files.But nothing helped.
I checked apache error logs. They showed the following error
(OS 10038)An operation was attempted on something that is not a socket. : AH00332: winnt_accept: getsockname error on listening socket, is IPv6 available?
Finally this is what solved my problem.
1) Goto command prompt and run it in administrative mode. In windows 7 you can do it by typing cmd
in run and then pressing ctrl+shift+enter
2) run the following command:
netsh winsock reset
3) Restart the system
To mark as obsolete with a warning:
[Obsolete]
private static void SomeMethod()
You get a warning when you use it:
And with IntelliSense:
If you want a message:
[Obsolete("My message")]
private static void SomeMethod()
Here's the IntelliSense tool tip:
Finally if you want the usage to be flagged as an error:
[Obsolete("My message", true)]
private static void SomeMethod()
When used this is what you get:
Note: Use the message to tell people what they should use instead, not why it is obsolete.
From Hadoop page,
start-all.sh
This will startup a Namenode, Datanode, Jobtracker and a Tasktracker on your machine.
start-dfs.sh
This will bring up HDFS with the Namenode running on the machine you ran the command on. On such a machine you would need start-mapred.sh
to separately start the job tracker
start-all.sh/stop-all.sh
has to be run on the master node
You would use start-all.sh
on a single node cluster (i.e. where you would have all the services on the same node.The namenode is also the datanode and is the master node).
In multi-node setup,
You will use start-all.sh
on the master node and would start what is necessary on the slaves as well.
Alternatively,
Use start-dfs.sh
on the node you want the Namenode to run on. This will bring up HDFS with the Namenode running on the machine you ran the command on and Datanodes on the machines listed in the slaves file.
Use start-mapred.sh
on the machine you plan to run the Jobtracker on. This will bring up the Map/Reduce cluster with Jobtracker running on the machine you ran the command on and Tasktrackers running on machines listed in the slaves file.
hadoop-daemon.sh
as stated by Tariq is used on each individual node. The master node will not start the services on the slaves.In a single node setup this will act same as start-all.sh
.In a multi-node setup you will have to access each node (master as well as slaves) and execute on each of them.
Have a look at this start-all.sh
it call config followed by dfs and mapred
create table Customer(
CustId int primary key,
CustName varchar(20),
DOB date);
insert into Customer values(1,'kingle', TO_DATE('1994-12-16 12:00:00', 'yyyy-MM-dd hh:mi:ss'));
Java is 'Big-endian' as noted above. That means that the MSB of an int is on the left if you examine memory (on an Intel CPU at least). The sign bit is also in the MSB for all Java integer types.
Reading a 4 byte unsigned integer from a binary file stored by a 'Little-endian' system takes a bit of adaptation in Java. DataInputStream's readInt() expects Big-endian format.
Here's an example that reads a four byte unsigned value (as displayed by HexEdit as 01 00 00 00) into an integer with a value of 1:
// Declare an array of 4 shorts to hold the four unsigned bytes
short[] tempShort = new short[4];
for (int b = 0; b < 4; b++) {
tempShort[b] = (short)dIStream.readUnsignedByte();
}
int curVal = convToInt(tempShort);
// Pass an array of four shorts which convert from LSB first
public int convToInt(short[] sb)
{
int answer = sb[0];
answer += sb[1] << 8;
answer += sb[2] << 16;
answer += sb[3] << 24;
return answer;
}
You can't trigger the native validation UI (see edit below), but you can easily take advantage of the validation API on arbitrary input elements:
$('input').blur(function(event) {
event.target.checkValidity();
}).bind('invalid', function(event) {
setTimeout(function() { $(event.target).focus();}, 50);
});
The first event fires checkValidity
on every input element as soon as it loses focus, if the element is invalid
then the corresponding event will be fired and trapped by the second event handler. This one sets the focus back to the element, but that could be quite annoying, I assume you have a better solution for notifying about the errors. Here's a working example of my code above.
EDIT: All modern browsers support the reportValidity()
method for native HTML5 validation, per this answer.
$(document).on('shown.bs.modal','.modal', function () {
/// TODO EVENTS
});
Use the isChecked() function for every radioButton you have to check.
RadioButton maleRadioButton, femaleRadioButton;
maleRadioButton = (RadioButton) findViewById(R.id.maleRadioButton);
femaleRadioButton = (RadioButton) findViewById(R.id.femaleRadioButton);
Then use the result for your if/else case consideration.
if (maleRadioButton.isChecked() || femaleRadioButton.isChecked()) {
Log.d("QAOD", "Gender is Selected");
} else {
Toast.makeText(getApplicationContext(), "Please select Gender", Toast.LENGTH_SHORT).show();
Log.d("QAOD", "Gender is Null");
}
Given a radius length r and an angle t in radians and a circle's center (h,k), you can calculate the coordinates of a point on the circumference as follows (this is pseudo-code, you'll have to adapt it to your language):
float x = r*cos(t) + h;
float y = r*sin(t) + k;
You might want to consider using helper library like underscore.js, which has it's own implementation of extend()
.
And it's also a good way to learn by looking at it's source code. The annotated source code page is quite useful.
Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]
Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.
So, to summarize:
Transfer on established connection:
First connection establishment:
Subsequent connection establishments:
BigDecimal demo = new BigDecimal(15);
It is immutable beacuse it internally store you input i.e (15) as final private final BigInteger intVal;
and same concept use at the time of string creation every input finally store in
private final char value[];
.So there is no implmented bug.
You could use lsof
to see what application is listening on port 80:
sudo lsof -i TCP:80
Adding android:lineSpacingMultiplier="0.8"
can make the line spacing to 80%.
I have cooked up a plugin for IntelliJ that – in a way – gives you var
in Java. It's a hack, so the usual disclaimers apply, but if you use IntelliJ for your Java development and want to try it out, it's at https://bitbucket.org/balpha/varsity.
With \
you escape special characters
Escapes special characters to literal and literal characters to special.
E.g:
/\(s\)/
matches '(s)' while/(\s)/
matches any whitespace and captures the match.
Source: http://www.javascriptkit.com/javatutors/redev2.shtml
If i run the command line : java -Dspring.profiles.active=development -jar yourApplication.jar
from my webapplication directory it states that the path is incorrect. So i just defined the profile in manualy in the application.properties file like this :
spring.profiles.active=mysql
or
spring.profiles.active=postgres
or
spring.profiles.active=mongodb
The solutions is in fact
p{
white-space:normal;
}
You can change the break behaviors by modifying, word-break property
p{
word-break: break-all; // will break at end of line
}
break-all: Will break the string at the very end, breaking at the last word word-break: is more of pretty brake, will break nicely for example at ? point normal: same as word-break
As a completion to Gustavo Bezerra's answer:
If you want each histogram to be normalized (normed
for mpl<=2.1 and density
for mpl>=3.1) you cannot just use normed/density=True
, you need to set the weights for each value instead:
import numpy as np
import matplotlib.pyplot as plt
x = np.random.normal(1, 2, 5000)
y = np.random.normal(-1, 3, 2000)
x_w = np.empty(x.shape)
x_w.fill(1/x.shape[0])
y_w = np.empty(y.shape)
y_w.fill(1/y.shape[0])
bins = np.linspace(-10, 10, 30)
plt.hist([x, y], bins, weights=[x_w, y_w], label=['x', 'y'])
plt.legend(loc='upper right')
plt.show()
As a comparison, the exact same x
and y
vectors with default weights and density=True
: