Run these three commands to make sure that you have all the relevant packages installed:
pip install bs4
pip install html5lib
pip install lxml
Then restart your Python IDE, if needed.
That should take care of anything related to this issue.
Keep in mind while using HTML5 pushstate if a user copies or bookmarks a deep link and visits it again, then that will be a direct server hit which will 404 so you need to be ready for it and even a pushstate js library won't help you. The easiest solution is to add a rewrite rule to your Nginx or Apache server like so:
Apache (in your vhost if you're using one):
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
Nginx
rewrite ^(.+)$ /index.html last;
It works for me. Please check if you are using the right imports?
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
DESCRIPTION: SC is a command line program used for communicating with the NT Service Controller and services. USAGE: sc [command] [service name] ...
The option <server> has the form "\\ServerName"
Further help on commands can be obtained by typing: "sc [command]"
Commands:
query-----------Queries the status for a service, or
enumerates the status for types of services.
queryex---------Queries the extended status for a service, or
enumerates the status for types of services.
start-----------Starts a service.
pause-----------Sends a PAUSE control request to a service.
interrogate-----Sends an INTERROGATE control request to a service.
continue--------Sends a CONTINUE control request to a service.
stop------------Sends a STOP request to a service.
config----------Changes the configuration of a service (persistant).
description-----Changes the description of a service.
failure---------Changes the actions taken by a service upon failure.
qc--------------Queries the configuration information for a service.
qdescription----Queries the description for a service.
qfailure--------Queries the actions taken by a service upon failure.
delete----------Deletes a service (from the registry).
create----------Creates a service. (adds it to the registry).
control---------Sends a control to a service.
sdshow----------Displays a service's security descriptor.
sdset-----------Sets a service's security descriptor.
GetDisplayName--Gets the DisplayName for a service.
GetKeyName------Gets the ServiceKeyName for a service.
EnumDepend------Enumerates Service Dependencies.
The following commands don't require a service name:
sc <server> <command> <option>
boot------------(ok | bad) Indicates whether the last boot should
be saved as the last-known-good boot configuration
Lock------------Locks the Service Database
QueryLock-------Queries the LockStatus for the SCManager Database
EXAMPLE: sc start MyService
I had a different but still related configuration.
Could be a custom configuration section that hasn't been declared in configSections.
Just declare the section and the error should resolve itself.
java
is the root JNDI namespace for resources. What the original snippet of code means is that the container the application was initially deployed in did not apply any additional namespaces to the JNDI context you retrieved (as an example, Tomcat automatically adds all resources to the namespace comp/env
, so you would have to do dataSource = (javax.sql.DataSource) context.lookup("java:comp/env/jdbc/myDataSource");
if the resource reference name is jdbc/myDataSource
).
To avoid having to change your legacy code I think if you register the datasource with the name myDataSource
(remove the jdbc/
) you should be fine. Let me know if that works.
Define one Enum Type as
public enum Colors {
BLUE, SILVER, MAGENTA, RED
}
Change data type of color
from String
to Colors
Change return type and argument type of getter and setter method of color to Colors
Define comparator type as follows
static class ColorComparator implements Comparator<CarSort>
{
public int compare(CarSort c1, CarSort c2)
{
return c1.getColor().compareTo(c2.getColor());
}
}
after adding elements to List, call sort method of Collection by passing list and comparator objects as arguments
i.e, Collections.sort(carList, new ColorComparator());
then print using ListIterator
.
full class implementation is as follows:
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ListIterator;
public class CarSort implements Comparable<CarSort>{
String name;
Colors color;
public CarSort(String name, Colors color){
this.name = name;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Colors getColor() {
return color;
}
public void setColor(Colors color) {
this.color = color;
}
//Implement the natural order for this class
public int compareTo(CarSort c)
{
return getName().compareTo(c.getName());
}
static class ColorComparator implements Comparator<CarSort>
{
public int compare(CarSort c1, CarSort c2)
{
return c1.getColor().compareTo(c2.getColor());
}
}
public enum Colors {
BLUE, SILVER, MAGENTA, RED
}
public static void main(String[] args)
{
List<CarSort> carList = new ArrayList<CarSort>();
List<String> sortOrder = new ArrayList<String>();
carList.add(new CarSort("Ford Figo",Colors.SILVER));
carList.add(new CarSort("Santro",Colors.BLUE));
carList.add(new CarSort("Honda Jazz",Colors.MAGENTA));
carList.add(new CarSort("Indigo V2",Colors.RED));
Collections.sort(carList, new ColorComparator());
ListIterator<CarSort> itr=carList.listIterator();
while (itr.hasNext()) {
CarSort carSort = (CarSort) itr.next();
System.out.println("Car colors: "+carSort.getColor());
}
}
}
select CustomerName,count(1) from Customers group by CustomerName having count(1) > 1
Found this while Googling. The second post makes a point about the different phases of JSF, which might be causing your error message to become lost. Also, try null in place of "newPassword" because you do not have any object with the id newPassword.
Try this
<div>{React.cloneElement(this.props.children, {...this.props})}</div>
It worked for me using react-15.1.
There are multiple ways to obfuscate code. Here's just one example:
(lambda _, __, ___, ____, _____, ______, _______, ________:
getattr(
__import__(True.__class__.__name__[_] + [].__class__.__name__[__]),
().__class__.__eq__.__class__.__name__[:__] +
().__iter__().__class__.__name__[_____:________]
)(
_, (lambda _, __, ___: _(_, __, ___))(
lambda _, __, ___:
chr(___ % __) + _(_, __, ___ // __) if ___ else
(lambda: _).func_code.co_lnotab,
_ << ________,
(((_____ << ____) + _) << ((___ << _____) - ___)) + (((((___ << __)
- _) << ___) + _) << ((_____ << ____) + (_ << _))) + (((_______ <<
__) - _) << (((((_ << ___) + _)) << ___) + (_ << _))) + (((_______
<< ___) + _) << ((_ << ______) + _)) + (((_______ << ____) - _) <<
((_______ << ___))) + (((_ << ____) - _) << ((((___ << __) + _) <<
__) - _)) - (_______ << ((((___ << __) - _) << __) + _)) + (_______
<< (((((_ << ___) + _)) << __))) - ((((((_ << ___) + _)) << __) +
_) << ((((___ << __) + _) << _))) + (((_______ << __) - _) <<
(((((_ << ___) + _)) << _))) + (((___ << ___) + _) << ((_____ <<
_))) + (_____ << ______) + (_ << ___)
)
)
)(
*(lambda _, __, ___: _(_, __, ___))(
(lambda _, __, ___:
[__(___[(lambda: _).func_code.co_nlocals])] +
_(_, __, ___[(lambda _: _).func_code.co_nlocals:]) if ___ else []
),
lambda _: _.func_code.co_argcount,
(
lambda _: _,
lambda _, __: _,
lambda _, __, ___: _,
lambda _, __, ___, ____: _,
lambda _, __, ___, ____, _____: _,
lambda _, __, ___, ____, _____, ______: _,
lambda _, __, ___, ____, _____, ______, _______: _,
lambda _, __, ___, ____, _____, ______, _______, ________: _
)
)
)
I had the same problem and my mistake was that I had installed the binary boost_1_55_0-msvc-11.0-32.exe to use with visual c++ 2010 which has the version v100 (project properties->ConfiguratioProperties->General->platformTooset) not v110 as visual c++ 2012. So I dowloaded boost_1_55_0-msvc-10.0-32.exe and now everything is ok so far.
Chrome will never implement support RTSP streaming.
At least, in the words of a Chromium developer here:
we're never going to add support for this
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
Steps to install curl in windows
Install cURL on Windows
There are 4 steps to follow to get cURL installed on Windows.
Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate
Step One: Install Visual C++ 2008 Redistributables
From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)
Step Two: Install Win(32/64) OpenSSL v1.0.0k Light
From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light
Step Three: Install cURL
Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html
Copy curl.exe to C:\Windows\System32
Step Four: Install Recent Certificates
Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt
If you have already installed curl
or after doing the above steps, add the directory where it's installed to the windows path:
1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt
pip install -U mysql-connector-python
this worked for me, if you already have installed mysql-connector-python
and then follow https://stackoverflow.com/a/50557297/6202853 this answer
Try this, It supports multi file uploading,
$('#multi_file_upload').change(function(e) {
var file_id = e.target.id;
var file_name_arr = new Array();
var process_path = site_url + 'public/uploads/';
for (i = 0; i < $("#" + file_id).prop("files").length; i++) {
var form_data = new FormData();
var file_data = $("#" + file_id).prop("files")[i];
form_data.append("file_name", file_data);
if (check_multifile_logo($("#" + file_id).prop("files")[i]['name'])) {
$.ajax({
//url : site_url + "inc/upload_image.php?width=96&height=60&show_small=1",
url: site_url + "inc/upload_contact_info.php",
cache: false,
contentType: false,
processData: false,
async: false,
data: form_data,
type: 'post',
success: function(data) {
// display image
}
});
} else {
$("#" + html_div).html('');
alert('We only accept JPG, JPEG, PNG, GIF and BMP files');
}
}
});
function check_multifile_logo(file) {
var extension = file.substr((file.lastIndexOf('.') + 1))
if (extension === 'jpg' || extension === 'jpeg' || extension === 'gif' || extension === 'png' || extension === 'bmp') {
return true;
} else {
return false;
}
}
Here #multi_file_upload is the ID of image upload field.
You can use this library, which both initially sizes your iframe correctly and also keeps it at the right size by detecting whenever the size of the iframe's content changes (either via regular checking in a setInterval
or via MutationObserver
) and resizing it.
https://github.com/davidjbradshaw/iframe-resizer
Their is also a React version.
https://github.com/davidjbradshaw/iframe-resizer-react
This works with both cross and same domain iframes.
if i understood you can do the following
Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window
Just to complete the other answers, I would like to quote Effective Java, 2nd Edition, by Joshua Bloch, chapter 10, Item 68 :
"Choosing the executor service for a particular application can be tricky. If you’re writing a small program, or a lightly loaded server, using Executors.new- CachedThreadPool is generally a good choice, as it demands no configuration and generally “does the right thing.” But a cached thread pool is not a good choice for a heavily loaded production server!
In a cached thread pool, submitted tasks are not queued but immediately handed off to a thread for execution. If no threads are available, a new one is created. If a server is so heavily loaded that all of its CPUs are fully utilized, and more tasks arrive, more threads will be created, which will only make matters worse.
Therefore, in a heavily loaded production server, you are much better off using Executors.newFixedThreadPool, which gives you a pool with a fixed number of threads, or using the ThreadPoolExecutor class directly, for maximum control."
<embed src="data:application/pdf;base64,..."/>
do not zip any hidden file:
zip newzipname filename.any -x "\.*"
with this question, it should be like:
zip newzipname filename.any -x "\__MACOSX"
It must be said, though, zip command runs in terminal just compressing the file, it does not compress any others. So do this the result is the same:
zip newzipname filename.any
First of all, MEAN is an acronym for MongoDB, Express, Angular and Node.js.
It generically identifies the combined used of these technologies in a "stack". There is no such a thing as "The MEAN framework".
Lior Kesos at Linnovate took advantage of this confusion. He bought the domain MEAN.io and put some code at https://github.com/linnovate/mean
They luckily received a lot of publicity, and theree are more and more articles and video about MEAN. When you Google "mean framework", mean.io is the first in the list.
Unfortunately the code at https://github.com/linnovate/mean seems poorly engineered.
In February I fell in the trap myself. The site mean.io had a catchy design and the Github repo had 1000+ stars. The idea of questioning the quality did not even pass through my mind. I started experimenting with it but it did not take too long to stumble upon things that were not working, and puzzling pieces of code.
The commit history was also pretty concerning. They re-engineered the code and directory structure multiple times, and merging the new changes is too time consuming.
The nice things about both mean.io and mean.js code is that they come with Bootstrap integration. They also come with Facebook, Github, Linkedin etc authentication through PassportJs and an example of a model (Article) on the backend on MongoDB that sync with the frontend model with AngularJS.
According to Linnovate's website:
Linnovate is the leading Open Source company in Israel, with the most experienced team in the country, dedicated to the creation of high-end open source solutions. Linnovate is the only company in Israel which gives an A-Z services for enterprises for building and maintaining their next web project.
From the website it looks like that their core skill set is Drupal (a PHP content management system) and only lately they started using Node.js and AngularJS.
Lately I was reading the Mean.js Blog and things became clearer. My understanding is that the main Javascript developer (Amos Haviv) left Linnovate to work on Mean.js leaving MEAN.io project with people that are novice Node.js developers that are slowing understanding how things are supposed to work.
In the future things may change but for now I would avoid to use mean.io. If you are looking for a boilerplate for a quickstart Mean.js seems a better option than mean.io.
Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:
JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);
According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:
Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
return font.deriveFont(12f);
This is the fix that worked for me. There is invalid mime or bad characterset being sent with your json data causing that errror. Add the charset like this to help it from getting confused:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
});
Reference:
Jquery - How to make $.post() use contentType=application/json?
List<target> targetList = new List<target>(originalList.Cast<target>());
You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx
But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends
http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx
Your code also seems a bit strange, like you are nesting lists?
As the documentation states, 'replace' determines whether the current element is replaced by the directive. The other option is whether it is just added to as a child basically. If you look at the source of your plnkr, notice that for the second directive where replace is false that the div tag is still there. For the first directive it is not.
First result:
<span myd1="">directive template1</span>
Second result:
<div myd2=""><span>directive template2</span></div>
java.util.Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
assert
Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne. They call your code, you call their code.
Then assert
has four roles:
Inform Alice, Bernd, Carl, and Daphne what your code expects.
Assume you have a method that processes a list of tuples and the program logic can break if those tuples are not immutable:
def mymethod(listOfTuples):
assert(all(type(tp)==tuple for tp in listOfTuples))
This is more trustworthy than equivalent information in the documentation and much easier to maintain.
Inform the computer what your code expects.
assert
enforces proper behavior from the callers of your code.
If your code calls Alices's and Bernd's code calls yours,
then without the assert
, if the program crashes in Alices code,
Bernd might assume it was Alice's fault,
Alice investigates and might assume it was your fault,
you investigate and tell Bernd it was in fact his.
Lots of work lost.
With asserts, whoever gets a call wrong, they will quickly be able to see it was
their fault, not yours. Alice, Bernd, and you all benefit.
Saves immense amounts of time.
Inform the readers of your code (including yourself) what your code has achieved at some point.
Assume you have a list of entries and each of them can be clean (which is good)
or it can be smorsh, trale, gullup, or twinkled (which are all not acceptable).
If it's smorsh it must be unsmorshed; if it's trale it must be baludoed;
if it's gullup it must be trotted (and then possibly paced, too);
if it's twinkled it must be twinkled again except on Thursdays.
You get the idea: It's complicated stuff.
But the end result is (or ought to be) that all entries are clean.
The Right Thing(TM) to do is to summarize the effect of your
cleaning loop as
assert(all(entry.isClean() for entry in mylist))
This statements saves a headache for everybody trying to understand what exactly it is that the wonderful loop is achieving. And the most frequent of these people will likely be yourself.
Inform the computer what your code has achieved at some point.
Should you ever forget to pace an entry needing it after trotting,
the assert
will save your day and avoid that your code
breaks dear Daphne's much later.
In my mind, assert
's two purposes of documentation (1 and 3) and
safeguard (2 and 4) are equally valuable.
Informing the people may even be more valuable than informing the computer
because it can prevent the very mistakes the assert
aims to catch (in case 1)
and plenty of subsequent mistakes in any case.
In javascript:
var attributes;
var spans = document.getElementsByTagName("span");
for(var s in spans){
if (spans[s].getAttribute('name') === 'test') {
attributes = spans[s].attributes;
break;
}
}
To access the attributes names and values:
attributes[0].nodeName
attributes[0].nodeValue
You can also use
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
And your func.php:
function toptable()
{
echo 'something happens in here';
}
Hope it helps somebody
Here's an alternate way of finding height. Add an additional attribute to your node called height:
class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}
Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:
int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;
q.Enqueue(root);
while(q.Count > 0)
{
lastnode = q.Dequeue();
if (lastnode.left != null){
lastnode.left.height = lastnode.height + 1;
q.Enqueue(lastnode.left);
}
if (lastnode.right != null){
lastnode.right.height = lastnode.height + 1;
q.Enqueue(lastnode.right);
}
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}
Cheers,
Use array or common container for objects only if they have default and copy constructors.
Store pointers otherwise (or smart pointers, but may meet some issues in this case).
PS: Always define own default and copy constructors otherwise auto-generated will be used
Synchronous option in-case if you are not a JS expert like me. Had to spend some time on how to access the inline function variable
var token = crypto.randomBytes(64).toString('hex');
To count everything just pipe ls to word count line:
ls | wc -l
To count with pattern, pipe to grep first:
ls | grep log | wc -l
Code:
while True:
n += 1
try:
DATA[n]['message']['text']
except:
key = DATA[n-1]['message']['text']
break
Console :
Traceback (most recent call last):
File "botnet.py", line 82, in <module>
key =DATA[n-1]['message']['text']
IndexError: list index out of range
For me, it was that route that I was calling in my node server wasn't returning anything. Adding
return res.status(200).json({
message: 'success!',
response: 'success!'
});//
to the route I was calling resolved the issue.
Let me give you an example that I find very helpful.
You can think of reference as the page number of a book. Suppose now you have two pages a and b like below.
BookPage a = getSecondPage();
BookPage b = getThirdPage();
In this case, a == b will give you false. But, why? The reason is that what == is doing is like comparing the page number. So, even if the content on these two pages is exactly the same, you will still get false.
But what do we do if you we want to compare the content?
The answer is to write your own equals method and specify what you really want to compare.
For people still struggling and the answered solution doesn't work quite as you want it to, here is the simplest solution I have found.
Wrap your main content and assign it a min view height. Adjust the 60 to whatever value your style needs.
<div id="content" style="min-height:60vh"></div>
<div id="footer"></div>
Thats it and it works pretty well.
Simplest way to achieve pretty logging in Preethi Jain szenario:
LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
loggingInInterceptor.setPrettyLogging(true);
LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
loggingOutInterceptor.setPrettyLogging(true);
factory.getInInterceptors().add(loggingInInterceptor);
factory.getOutInterceptors().add(loggingOutInterceptor);
In PowerShell 3.0, it is simpler:
Get-ChildItem -Directory #List only directories
Get-ChildItem -File #List only files
For going back to previous page using Anchor Tag <a>
, below are 2 working methods and out of them 1st one is faster and have one great advantage in going back to previous page.
I have tried both methods.
1)
<a href="#" onclick="location.href = document.referrer; return false;">Go Back</a>
Above method (1) works great if you have clicked on a link and opened link in a New Tab in current browser window.
2)
<a href="javascript:history.back()">Go Back</a>
Above method (2) only works ok if you have clicked on a link and opened link in a Current Tab in current browser window.
It will not work if you have open link in New Tab. Here history.back()
will not work if link is opened in New Tab of web browser.
This suggestion is based on pixel manipulation in canvas 2d context.
From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData
and putImageData
.
getImageData
usage:
var myImageData = context.getImageData(left, top, width, height);
The putImageData
syntax:
context.putImageData(myImageData, x, y);
Where context
is your canvas 2d context, and x
and y
are the position on the canvas.
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x
is the horizontal offset, y
is the vertical offset.
The code making image half-transparent:
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
I'm assuming that by empty you mean "has no properties of its own".
// Speed up calls to hasOwnProperty
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
// null and undefined are "empty"
if (obj == null) return true;
// Assume if it has a length property with a non-zero value
// that that property is correct.
if (obj.length > 0) return false;
if (obj.length === 0) return true;
// If it isn't an object at this point
// it is empty, but it can't be anything *but* empty
// Is it empty? Depends on your application.
if (typeof obj !== "object") return true;
// Otherwise, does it have any properties of its own?
// Note that this doesn't handle
// toString and valueOf enumeration bugs in IE < 9
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
}
return true;
}
Examples:
isEmpty(""), // true
isEmpty(33), // true (arguably could be a TypeError)
isEmpty([]), // true
isEmpty({}), // true
isEmpty({length: 0, custom_property: []}), // true
isEmpty("Hello"), // false
isEmpty([1,2,3]), // false
isEmpty({test: 1}), // false
isEmpty({length: 3, custom_property: [1,2,3]}) // false
If you only need to handle ECMAScript5 browsers, you can use Object.getOwnPropertyNames
instead of the hasOwnProperty
loop:
if (Object.getOwnPropertyNames(obj).length > 0) return false;
This will ensure that even if the object only has non-enumerable properties isEmpty
will still give you the correct results.
Stop it by-: stop-all.sh
format the namenode-: hadoop namenode -format
again start-: start-all.sh
I just ran into this problem, and since Mr. Skeet's solution did not work for me, I'll share how I solved this problem.
It turns out that I opened the java file under the 'src' before declaring it a source directory.
After right clicking on the 'src' directory in eclipse, selecting 'build path', and then 'Use as Source Folder'
Close and reopen the already opened java file (F5 refreshing it did not work).
Provided the path to the java file from "prefix1" onwards lines up with the package in the file (example from the requester's question prefix1.prefix.packagename2). This should work
Eclipse should no longer complain about 'src.'
building on these answers - i also had to modify an X86 reference under Librarian -> Command Line -> Additional Options (for the x64 Platform)
I solved this using JNA: https://github.com/twall/jna
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class prova {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
int system(String cmd);
}
private static int exec(String command) {
return CLibrary.INSTANCE.system(command);
}
public static void main(String[] args) {
exec("ls");
}
}
Change CI index.php file to:
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
define('ENVIRONMENT', 'development');
} else {
define('ENVIRONMENT', 'production');
}
if (defined('ENVIRONMENT')){
switch (ENVIRONMENT){
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:
$db['default']['db_debug'] = FALSE;
Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html
$active_group = 'development';
$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;
$db['development']['db_debug'] = TRUE;
$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;
$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;
$db['production']['db_debug'] = FALSE;
$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. eg:
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? Would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // since I recognize the 'the' convention, I know it's static
})
To handle this situation in a portable way (ie will work on all databases because it doesn’t use MySQL label Kung fu), break the procedure up into logic parts, like this:
CREATE PROCEDURE SP_Reporting(IN tablename VARCHAR(20))
BEGIN
IF tablename IS NOT NULL THEN
CALL SP_Reporting_2(tablename);
END IF;
END;
CREATE PROCEDURE SP_Reporting_2(IN tablename VARCHAR(20))
BEGIN
#proceed with code
END;
Sometimes I need a empty char array. You cannot do "np.empty(size)" because error will be reported if you fill in char later. Then I usually do something quite clumsy but it is still one way to do it:
# Suppose you want a size N char array
charlist = [' ']*N # other preset character is fine as well, like 'x'
chararray = np.array(charlist)
# Then you change the content of the array
chararray[somecondition1] = 'a'
chararray[somecondition2] = 'b'
The bad part of this is that your array has default values (if you forget to change them).
If you work on Windows , you must start Android Studio name by Administrator. It solved my problem
Universal solution, based on Django's TZ name support:
UTC-2 = 'Etc/GMT+2'
UTC-1 = 'Etc/GMT+1'
UTC = 'Etc/GMT+0'
UTC+1 = 'Etc/GMT-1'
UTC+2 = 'Etc/GMT-2'
+/- is intentionally switched.
Simply replacing .bin with .tar.bz2 is not enough, for NDK releases older than 10b. For example, https://dl.google.com/android/ndk/android-ndk-r10b-linux-x86_64.tar.bz2 is not a valid link.
Turned out that the correct link for 10b was: https://dl.google.com/android/ndk/android-ndk32-r10b-linux-x86_64.tar.bz2 (note the additional '32'). However, this doesn't seem to apply to e.g. 10a, as this link doesn't work: https://dl.google.com/android/ndk/android-ndk32-r10a-linux-x86_64.tar.bz2 .
Bottom line: use http://web.archive.org until Google fixes this, if ever...
I was facing a time offset of -1hour and 4min
Restarting Docker itself fixed the issue for me.
To set the timezone in general:
ssh into your container:
docker exec -it my_website_name bash
run dpkg-reconfigure tzdata
date
Every managed exe has a an entry point which can be seen when if you load your code to ILDASM. The Entry Point is specified in the CLR headed and would look something like this.
hymloth and sven's answers work, but they do not modify the list (the create a new one). If you need the object modification you need to assign to a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove few elements, this is memory consuming, but it runs in O(n).
glglgl's answer suffers from O(n²) complexity, because list.remove
is O(n).
Depending on the structure of your data, you may prefer noting the indexes of the elements to remove and using the del
keywork to remove by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2]
for index in reversed(to_remove): # start at the end to avoid recomputing offsets
del x[index]
Now del x[i]
is also O(n) because you need to copy all elements after index i
(a list is a vector), so you'll need to test this against your data. Still this should be faster than using remove
because you don't pay for the cost of the search step of remove, and the copy step cost is the same in both cases.
[edit] Very nice in-place, O(n) version with limited memory requirements, courtesy of @Sven Marnach. It uses itertools.compress
which was introduced in python 2.7:
from itertools import compress
selectors = (len(s) == 2 for s in x)
for i, s in enumerate(compress(x, selectors)): # enumerate elements of length 2
x[i] = s # move found element to beginning of the list, without resizing
del x[i+1:] # trim the end of the list
Don't forget the padding and margins...
jQuery.fn.slideLeftHide = function(speed, callback) {
this.animate({
width: "hide",
paddingLeft: "hide",
paddingRight: "hide",
marginLeft: "hide",
marginRight: "hide"
}, speed, callback);
}
jQuery.fn.slideLeftShow = function(speed, callback) {
this.animate({
width: "show",
paddingLeft: "show",
paddingRight: "show",
marginLeft: "show",
marginRight: "show"
}, speed, callback);
}
With the speed/callback arguments added, it's a complete drop-in replacement for slideUp()
and slideDown()
.
async
methods are different than normal methods. Whatever you return from async
methods are wrapped in a Task
.
If you return no value(void) it will be wrapped in Task
, If you return int
it will be wrapped in Task<int>
and so on.
If your async method needs to return int
you'd mark the return type of the method as Task<int>
and you'll return plain int
not the Task<int>
. Compiler will convert the int
to Task<int>
for you.
private async Task<int> MethodName()
{
await SomethingAsync();
return 42;//Note we return int not Task<int> and that compiles
}
Sameway, When you return Task<object>
your method's return type should be Task<Task<object>>
public async Task<Task<object>> MethodName()
{
return Task.FromResult<object>(null);//This will compile
}
Since your method is returning Task
, it shouldn't return any value. Otherwise it won't compile.
public async Task MethodName()
{
return;//This should work but return is redundant and also method is useless.
}
Keep in mind that async method without an await
statement is not async
.
You can create the same behavior creating a simple custom editor called DateTime.cshtml, saving it in Views/Shared/EditorTemplates
@model DateTime
@{
var css = ViewData["class"] ?? "";
@Html.TextBox("", (Model != DateTime.MinValue? Model.ToString("dd/MM/yyyy") : string.Empty), new { @class = "calendar medium " + css});
}
and in your views
@Html.EditorFor(model => model.StartDate, new { @class = "required" })
Note that in my example I'm hard-coding two css classes and the date format. You can, of course, change that. You also can do the same with others html attributes, like readonly, disabled, etc.
As per latest api docs:
$(document).ready(function() {
$('#example').dataTable({
"order": []
});
});
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you're declaring a global variable, you might want to use a namespace of some kind. Just declare the namespace outside, then you can throw whatever you want into it. Like this...
var MyProject = {};
$(document).ready(function() {
MyProject.intro = "";
MyProject.intro = "something";
});
console.log(MyProject.intro); // "something"
How about:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
The idea is not mine. I've taken it from some post on dzone.com.
Per this npm issue list, one work around could be done through npm config
name: 'foo'
config: { path: "baz" },
scripts: { start: "node ./$npm_package_config_path" }
Under windows, the scripts
could be { start: "node ./%npm_package_config_path%" }
Then run the command line as below
npm start --foo:path=myapp
the one liner for python3 is :
def bytes_xor(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
where a
, b
and the returned value are bytes()
instead of str()
of course
can't be easier, I love python3 :)
You need to do this in transaction to ensure two simultaneous clients won't insert same fieldValue twice:
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
DECLARE @id AS INT
SELECT @id = tableId FROM table WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
INSERT INTO table (fieldValue) VALUES (@newValue)
SELECT @id = SCOPE_IDENTITY()
END
SELECT @id
COMMIT TRANSACTION
you can also use Double-checked locking to reduce locking overhead
DECLARE @id AS INT
SELECT @id = tableID FROM table (NOLOCK) WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION
SELECT @id = tableID FROM table WHERE fieldValue=@newValue
IF @id IS NULL
BEGIN
INSERT INTO table (fieldValue) VALUES (@newValue)
SELECT @id = SCOPE_IDENTITY()
END
COMMIT TRANSACTION
END
SELECT @id
As for why ISOLATION LEVEL SERIALIZABLE is necessary, when you are inside a serializable transaction, the first SELECT that hits the table creates a range lock covering the place where the record should be, so nobody else can insert the same record until this transaction ends.
Without ISOLATION LEVEL SERIALIZABLE, the default isolation level (READ COMMITTED) would not lock the table at read time, so between SELECT and UPDATE, somebody would still be able to insert. Transactions with READ COMMITTED isolation level do not cause SELECT to lock. Transactions with REPEATABLE READS lock the record (if found) but not the gap.
This line:
$('#here_table').append( '<tr><td>' + 'result' + i + '</td></tr>' );
Appends to the div#here_table
not the new table
.
There are several approaches:
/* Note that the whole content variable is just a string */
var content = "<table>"
for(i=0; i<3; i++){
content += '<tr><td>' + 'result ' + i + '</td></tr>';
}
content += "</table>"
$('#here_table').append(content);
But, with the above approach it is less manageable to add styles and do stuff dynamically with <table>
.
But how about this one, it does what you expect nearly great:
var table = $('<table>').addClass('foo');
for(i=0; i<3; i++){
var row = $('<tr>').addClass('bar').text('result ' + i);
table.append(row);
}
$('#here_table').append(table);
Hope this would help.
in my problem I want the text of anchor <a>text</a>
inside my view to be based on some value
and that text is retrieved form App string Resources
so, this @()
is the solution
<a href='#'>
@(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>
if the text is not from App string Resources
use this
@(Model.ID == 0 ? "Back" :"Descart Changes")
I always just add 86400 (seconds in a day):
$stop_date = date('Y-m-d H:i:s', strtotime("2009-09-30 20:24:00") + 86400);
echo 'date after adding 1 day: '.$stop_date;
It's not the slickest way you could probably do it, but it works!
You already got the right answer, but if you dislike the UIColor
interface like me, you can do this:
#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];
UIColor+Helper.h:
#import <UIKit/UIKit.h>
@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end
UIColor+Helper.m:
#import "UIColor+Helper.h"
@implementation UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
green:((color >> 16) & 0xFF) / 255.0f
blue:((color >> 8) & 0xFF) / 255.0f
alpha:((color) & 0xFF) / 255.0f];
}
@end
https://github.com/xgqfrms-gildata/App001/issues/3
openssl.cnf
file in the right path;$ echo %OPENSSL_CONF%
$ set OPENSSL_CONF=C:\OpenSSL\bin\openssl.cnf
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
Use the getWidth method in the following class:
import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
class StringMetrics {
Font font;
FontRenderContext context;
public StringMetrics(Graphics2D g2) {
font = g2.getFont();
context = g2.getFontRenderContext();
}
Rectangle2D getBounds(String message) {
return font.getStringBounds(message, context);
}
double getWidth(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getWidth();
}
double getHeight(String message) {
Rectangle2D bounds = getBounds(message);
return bounds.getHeight();
}
}
I Know this old post but Just wanted to add few points. The standard for such problems is what works best for the situation. understanding the need for such storage, and potential use of the historical/audit/change tracking data is very importat.
Audit (security purpose) : Use a common table for all your auditable tables. define structure to store column name , before value and after value fields.
Archive/Historical: for cases like tracking previous address , phone number etc. creating a separate table FOO_HIST is better if you your active transaction table schema does not change significantly in the future(if your history table has to have the same structure). if you anticipate table normalization , datatype change addition/removal of columns, store your historical data in xml format . define a table with the following columns (ID,Date, Schema Version, XMLData). this will easily handle schema changes . but you have to deal with xml and that could introduce a level of complication for data retrieval .
The answer by Aaron is the best and is working for me :) I would vote it up but sadly I can't (missing reputation).
I've to say testing private methods is the only way to use them and have clean code on the other side.
For example:
class Something {
save(){
const data = this.getAllUserData()
if (this.validate(data))
this.sendRequest(data)
}
private getAllUserData () {...}
private validate(data) {...}
private sendRequest(data) {...}
}
It' makes a lot of sense to not test all these methods at once because we would need to mock out those private methods, which we can't mock out because we can't access them. This means we need a lot of configuration for a unit test to test this as a whole.
This said the best way to test the method above with all dependencies is an end to end test, because here an integration test is needed, but the E2E test won't help you if you are practicing TDD (Test Driven Development), but testing any method will.
You literally just pass them in std::thread(func1,a,b,c,d);
that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate
is called. You could std::join
or std::detach
it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach
.
This is how it should be done.
std::thread t(func1,a,b,c,d);
t.join();
You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.
You can send a 400 Bad Request code. It's one of the more general-purpose 4xx status codes, so you can use it to mean what you intend: the client is sending a request that's missing information/parameters that your application requires in order to process it correctly.
I am just updating this with Microsoft SQL Server Management Studio 2008 R2 version. if you run the installer normally, you can just add Management Tools – Basic, and by clicking Basic it should select Management Tools – Complete.
That is what worked for me.
Page 178, High Performance MySQL, 3rd Edition
An index that contains (or "covers") all the data needed to satisfy a query is called a covering index.
When you issue a query that is covered by an index (an indexed-covered query), you'll see "Using Index" in the Extra column in EXPLAIN.
You can combine the sparse checkout and the shallow clone features. The shallow clone cuts off the history and the sparse checkout only pulls the files matching your patterns.
git init <repo>
cd <repo>
git remote add origin <url>
git config core.sparsecheckout true
echo "finisht/*" >> .git/info/sparse-checkout
git pull --depth=1 origin master
You'll need minimum git 1.9 for this to work. Tested it myself only with 2.2.0 and 2.2.2.
This way you'll be still able to push, which is not possible with git archive
.
Try this
<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */
If your are in Visual Studio 2012 or later this has an additional setting 'SDL checks' Under Property Pages -> C/C++ -> General
Additional Security Development Lifecycle (SDL) recommended checks; includes enabling additional secure code generation features and extra security-relevant warnings as errors.
It defaults to YES - For a reason, I.E you should use the secure version of the strncpy. If you change this to NO you will not get a error when using the insecure version.
I wanted to know what is the performance difference between using utf8_general_ci
and utf8_unicode_ci
, but I did not find any benchmarks listed on the internet, so I decided to create benchmarks myself.
I created a very simple table with 500,000 rows:
CREATE TABLE test(
ID INT(11) DEFAULT NULL,
Description VARCHAR(20) DEFAULT NULL
)
ENGINE = INNODB
CHARACTER SET utf8
COLLATE utf8_general_ci;
Then I filled it with random data by running this stored procedure:
CREATE PROCEDURE randomizer()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE random CHAR(20) ;
theloop: loop
SET random = CONV(FLOOR(RAND() * 99999999999999), 20, 36);
INSERT INTO test VALUES (i+1, random);
SET i=i+1;
IF i = 500000 THEN
LEAVE theloop;
END IF;
END LOOP theloop;
END
Then I created the following stored procedures to benchmark simple SELECT
, SELECT
with LIKE
, and sorting (SELECT
with ORDER BY
):
CREATE PROCEDURE benchmark_simple_select()
BEGIN
DECLARE i INT DEFAULT 0;
theloop: loop
SELECT *
FROM test
WHERE Description = 'test' COLLATE utf8_general_ci;
SET i = i + 1;
IF i = 30 THEN
LEAVE theloop;
END IF;
END LOOP theloop;
END;
CREATE PROCEDURE benchmark_select_like()
BEGIN
DECLARE i INT DEFAULT 0;
theloop: loop
SELECT *
FROM test
WHERE Description LIKE '%test' COLLATE utf8_general_ci;
SET i = i + 1;
IF i = 30 THEN
LEAVE theloop;
END IF;
END LOOP theloop;
END;
CREATE PROCEDURE benchmark_order_by()
BEGIN
DECLARE i INT DEFAULT 0;
theloop: loop
SELECT *
FROM test
WHERE ID > FLOOR(1 + RAND() * (400000 - 1))
ORDER BY Description COLLATE utf8_general_ci LIMIT 1000;
SET i = i + 1;
IF i = 10 THEN
LEAVE theloop;
END IF;
END LOOP theloop;
END;
In the stored procedures above utf8_general_ci
collation is used, but of course during the tests I used both utf8_general_ci
and utf8_unicode_ci
.
I called each stored procedure 5 times for each collation (5 times for utf8_general_ci
and 5 times for utf8_unicode_ci
) and then calculated the average values.
My results are:
benchmark_simple_select()
utf8_general_ci
: 9,957 ms utf8_unicode_ci
: 10,271 ms In this benchmark using utf8_unicode_ci
is slower than utf8_general_ci
by 3.2%.
benchmark_select_like()
utf8_general_ci
: 11,441 ms utf8_unicode_ci
: 12,811 ms In this benchmark using utf8_unicode_ci
is slower than utf8_general_ci
by 12%.
benchmark_order_by()
utf8_general_ci
: 11,944 ms utf8_unicode_ci
: 12,887 ms In this benchmark using utf8_unicode_ci
is slower than utf8_general_ci
by 7.9%.
With C++11 you can now do
struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);
see std::get_time and strftime for reference
I just wanted to add to this one- because quite frankly, I banged my head against it for a while - and while very new to python - perhaps it will help someone else out.
writer.writerow(("ColName1", "ColName2", "ColName"))
for i in range(len(first_col_list)):
writer.writerow((first_col_list[i], second_col_list[i], third_col_list[i]))
Javax used to be only for extensions. Yet later sun added it to the java libary forgetting to remove the x. Developers started making code with javax. Yet later on in time suns decided to change it to java. Developers didn't like the idea because they're code would be ruined... so javax was kept.
I have to put
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<host>Your proxy host</host>
<port>proxy host ip</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
Before
<proxy>
<id>optional</id>
<active>true</active>
<protocol>https</protocol>
<host>Your proxy host</host>
<port>proxy host ip</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
Weird, but yes!, <protocol>http</protocol>
has to come before <protocol>https</protocol>
.
It solved my problem. Hope it helps someone who faces connections issue even after enabling proxy settings in conf/settings.xml
.
A catch-all jQuery custom event based on an extension of it's core methods like it was proposed by different people in this thread:
(function() {
var ev = new $.Event('event.css.jquery'),
css = $.fn.css,
show = $.fn.show,
hide = $.fn.hide;
// extends css()
$.fn.css = function() {
css.apply(this, arguments);
$(this).trigger(ev);
};
// extends show()
$.fn.show = function() {
show.apply(this, arguments);
$(this).trigger(ev);
};
// extends hide()
$.fn.hide = function() {
hide.apply(this, arguments);
$(this).trigger(ev);
};
})();
An external library then, uses sth like $('selector').css('property', value)
.
As we don't want to alter the library's code but we DO want to extend it's behavior we do sth like:
$('#element').on('event.css.jquery', function(e) {
// ...more code here...
});
Example: user clicks on a panel that is built by a library. The library shows/hides elements based on user interaction. We want to add a sensor that shows that sth has been hidden/shown because of that interaction and should be called after the library's function.
Another example: jsfiddle.
This is fast & works for whatever length.
public static String prefixZeros(String value, int len) {
char[] t = new char[len];
int l = value.length();
int k = len-l;
for(int i=0;i<k;i++) { t[i]='0'; }
value.getChars(0, l, t, k);
return new String(t);
}
To run the batch file when the VM
user logs in:
Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.
Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\
.
As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:
start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"
But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.
Already busy topic, but from what I read here, the following helped me realizing how it's working internally:
def bar(a=[]):
print id(a)
a = a + [1]
print id(a)
return a
>>> bar()
4484370232
4484524224
[1]
>>> bar()
4484370232
4484524152
[1]
>>> bar()
4484370232 # Never change, this is 'class property' of the function
4484523720 # Always a new object
[1]
>>> id(bar.func_defaults[0])
4484370232
To answer the question more generaly how to redirect standard output to a variable ?
do the following :
from io import StringIO
import sys
result = StringIO()
sys.stdout = result
result_string = result.getvalue()
If you need to do that only in some function do the following :
old_stdout = sys.stdout
# your function containing the previous lines
my_function()
sys.stdout = old_stdout
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
This isn't really exactly what you are asking for - but you could try creating a date input field in html something like:
<input type="date" ng-model="myDate" />
Then to print this on the page you would use:
<span ng-bind="convertToDate(myDate) | date:'medium'"></span>
Finally, in my controller I declared a method that creates a date from the input value (which in chrome is apparently parsed 1 day off):
$scope.convertToDate = function (stringDate){
var dateOut = new Date(stringDate);
dateOut.setDate(dateOut.getDate() + 1);
return dateOut;
};
So there you have it. To see the whole thing working see the following plunker: http://plnkr.co/edit/8MVoXNaIDW59kQnfpaWW?p=preview .Best of luck!
Xamarin is used for phone applications (both IOS/Android). The .NET Core is used for designing Web applications that can work on both Apache and IIS.
That is the difference in two sentences.
A good deal of times, you might be looking at whole jar files, or war files that contain many jar files in addition to themselves.
Because I didn't want to hand check each class, I wrote a java program to do that:
https://github.com/Nthalk/WhatJDK
./whatjdk some.war
some.war:WEB-INF/lib/xml-apis-1.4.01.jar contains classes compatible with Java1.1
some.war contains classes compatible with Java1.6
While this doesn't say what the class was compiled WITH, it determines what JDK's will be able to LOAD the classes, which is probably what you wanted to begin with.
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar
or toCalendar
(as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat
is used to convert Strings to Dates (parse()
) or Dates to Strings (format()
). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
If your UML modeling tool has support for specifying an Enumeration, you should use that. It will likely be easier to do and it will give your model stronger semantics. Visually the result will be very similar to a Class with an <<enumeration>>
Stereotype, but in the UML metamodel, an Enumeration is actually a separate (meta)type.
+---------------------+
| <<enumeration>> |
| DayOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
+---------------------+
Once it is defined, you can use it as the type of an Attribute just like you would a Datatype or the name one of your own Classes.
+---------------------+
| Event |
|_____________________|
| day : DayOfTheWeek |
| ... |
+---------------------+
If you're using ArgoEclipse or ArgoUML, there's a pulldown menu on the toolbar which selects among Datatype, Enumeration, Signal, etc that will allow you to create your own Enumerations. The compartment that normally contains Attributes can then be populated with EnumerationLiterals for the values of your enumeration.
Here's a picture of a slightly different example in ArgoUML:
Just use the split
function. It returns a list, so you can keep the first element:
>>> s1.split(':')
['Username', ' How are you today?']
>>> s1.split(':')[0]
'Username'
What do you think? Is it fine to remove them? Or would you keep them for increased "correctness"?
It is fine to remove them. Using return
is exactly the scenario where break
should not be used.
In my case the problem was caused by my passing a null InputStream to the ObjectMapper.readValue call:
ObjectMapper objectMapper = ...
InputStream is = null; // The code here was returning null.
Foo foo = objectMapper.readValue(is, Foo.class)
I am guessing that this is the most common reason for this exception.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
If you are reading directly from CSV file then do like this.
myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)
Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?
Its just to save a byte of data when we do javascript minification.
consider the below anonymous function
function (){}
To make the above as self invoking function we will generally change the above code as
(function (){}())
Now we added two extra characters (,)
apart from adding ()
at the end of the function which necessary to call the function. In the process of minification we generally focus to reduce the file size. So we can also write the above function as
!function (){}()
Still both are self invoking functions and we save a byte as well. Instead of 2 characters (,)
we just used one character !
You could use regex as this will give you the string if it matches the requirements. The code would be something like:
const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);
console.log(matchedResult[0]); // This will give you 1345 albany street.
So to break the code down. [1-9][0-9]*
basically means the first number cannot be a zero and has to be a number between 1-9
and the next number can be any number from 0-9
and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z]
basically matches all capital letters to small letters and has to occur one or more times and this is repeated.
Alternatively to calling plt.show()
at the end of the script, you can also control each figure separately doing:
f = plt.figure(1)
plt.hist........
............
f.show()
g = plt.figure(2)
plt.hist(........
................
g.show()
raw_input()
In this case you must call raw_input
to keep the figures alive.
This way you can select dynamically which figures you want to show
Note: raw_input()
was renamed to input()
in Python 3
function removeHash () {
history.pushState("", document.title, window.location.pathname
+ window.location.search);
}
App.$router.replace({name:"my-route", hash: '#update'})
App.$router.replace({name:"my-route", hash: ' ', params: {a: 100} })
setTimeout(removeHash, 0)
Notes:
#
must have some value after it.setTimeout
, not $nextTick
to keep the url clean.From enable-cors.org:
CORS on ASP.NET
If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:
Response.AppendHeader("Access-Control-Allow-Origin", "*");
I spent almost a day trying to figure out why I was getting this exception. After lots of struggle, this config worked perfectly (Kotlin):
AndroidManifest.xml
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="com.lomza.moviesroom.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths>
<files-path name="movies_csv_files" path="."/>
</paths>
Intent itself
fun goToFileIntent(context: Context, file: File): Intent {
val intent = Intent(Intent.ACTION_VIEW)
val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
val mimeType = context.contentResolver.getType(contentUri)
intent.setDataAndType(contentUri, mimeType)
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
return intent
}
I explain the whole process here.
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.
I realize this is a very old question, but if I landed here, so will others. So I figured I weigh in.
If you want the tooltip to be responsive to one line only regardless of how much content you add to it, the width has to be flexible. However, Bootstrap does initiate the tooltip to a width, so you have to at least declare what that width will be and make it flexible from that size on up. This is what I recommend:
.tooltip-inner {
min-width: 100px;
max-width: 100%;
}
The min-width
declares a starting size. As opposed to the max-width, as some other would suggest, which it declares a stopping width. According to your question, you shouldn't declare a final width or your tooltip content will eventually wrap at that point. Instead, you use an infinite width or flexible width. max-width: 100%;
will ensure that once the tooltip has initiated at 100px wide, it will grow and adjust to your content regardless of the amount of content you have in it.
KEEP IN MIND Tooltips are not intended to carry a lot of content. It could look funky if you had a long string across the entire screen. And it will definitely will have an impact in your responsive views, specially smartphone (320px width).
I would recommend two solutions to perfect this:
data-placement:right
, your tooltip content will not be visible in smartphones (hence why bootstrap initially designed them to be responsive to its content and allow it to wrap)@media
query to reset your tooltip to fit the smartphone view. Like this:My demo HERE demonstrates the flexibility and responsiveness on the tooltips according to content size and device display size as well
@media (max-width: 320px) {
.tooltip-inner {
min-width: initial;
width: 320px;
}
}
Remove your script, and change the HTML:
<a id="closemodal" href="https://www.google.com" class="btn btn-primary close" data-dismiss="modal" target="_blank">Launch google.com</a>
EDIT: Please note that currently this will not work as this functionality does not yet exist in bootstrap. See issue here.
You can also use List's inbuilt foreach, such as:
List<T>.ForEach(item => Console.Write(item));
This code also runs significantly faster!
The above code also makes you able to manipulate Console.WriteLine, such as doing:
List<T>.ForEach(item => Console.Write(item + ",")); //Put a,b etc.
Postback happens when a webpage posts its data back to the same script/dll/whatever that generated the page in the first place.
Example in C# (asp.net)
...
if (!IsPostback)
// generate form
else
process submitted data;
This exception will come in case your server is based on JDK 7 and your client is on JDK 6 and using SSL certificates. In JDK 7 sslv2hello message handshaking is disabled by default while in JDK 6 sslv2hello message handshaking is enabled. For this reason when your client trying to connect server then a sslv2hello message will be sent towards server and due to sslv2hello message disable you will get this exception. To solve this either you have to move your client to JDK 7 or you have to use 6u91 version of JDK. But to get this version of JDK you have to get the MOS (My Oracle Support) Enterprise support. This patch is not public.
For my Azpen A727, the Windows driver installed correctly, so only step 3 of Mohammad's answer was necessary.
Using equals()
LocalDate
does override equals:
int compareTo0(LocalDate otherDate) {
int cmp = (year - otherDate.year);
if (cmp == 0) {
cmp = (month - otherDate.month);
if (cmp == 0) {
cmp = (day - otherDate.day);
}
}
return cmp;
}
If you are not happy with the result of equals()
, you are good using the predefined methods of LocalDate
.
Notice that all of those method are using the compareTo0()
method and just check the cmp
value. if you are still getting weird result (which you shouldn't), please attach an example of input and output
I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas. http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html
I got in the habit of using it liberally in Visual C++ since doing so would trigger IntelliSense ones I hit the '>' key, and I'm lazy. (and prone to typos)
But I've continued to use it, since I find it handy to see that I'm calling a member function rather than a global function.
To expand on Trevor's answer, you can push a single tag or all of your tags at once.
git push <remote> <tag>
This is a summary of the relevant documentation that explains this (some command options omitted for brevity):
git push [[<repository> [<refspec>…]] <refspec>...
The format of a
<refspec>
parameter is…the source ref<src>
, followed by a colon:
, followed by the destination ref<dst>
…The
<dst>
tells which ref on the remote side is updated with this push…If:<dst>
is omitted, the same ref as<src>
will be updated…tag
<tag>
means the same asrefs/tags/<tag>:refs/tags/<tag>
.
git push --tags <remote>
# Or
git push <remote> --tags
Here is a summary of the relevant documentation (some command options omitted for brevity):
git push [--all | --mirror | --tags] [<repository> [<refspec>…]] --tags
All refs under
refs/tags
are pushed, in addition to refspecs explicitly listed on the command line.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
*************Resolved - #1214 - The used table type doesn't support FULLTEXT indexes***************
Its Very Simple to resolve this issue. People are answering here in very difficult words which are not easily understandable by the people who are not technical.
So i am mentioning here steps in very simple words will resolve your issue.
1.) Open your .sql file with Notepad by right clicking on file>Edit Or Simply open a Notepad file and drag and drop the file on Notepad and the file will be opened. (Note: Please don't change the extention .sql of file as its still your sql database. Also to keep a copy of your sql file to save yourself from any mishappening)
2.) Click on Notepad Menu Edit > Replace (A Window will be pop us with Find What & Replace With Fields)
3.) In Find What Field Enter ENGINE=InnoDB & In Replace With Field Enter ENGINE=MyISAM
4.) Now Click on Replace All Button
5.) Click CTRL+S or File>Save
6.) Now Upload This File and I am Sure your issue will be resolved....
Best solution of define unique key in react: inside the map you initialized the name post then key define by key={post.id} or in my code you see i define the name item then i define key by key={item.id}:
<div className="container">_x000D_
{posts.map(item =>(_x000D_
_x000D_
<div className="card border-primary mb-3" key={item.id}>_x000D_
<div className="card-header">{item.name}</div>_x000D_
<div className="card-body" >_x000D_
<h4 className="card-title">{item.username}</h4>_x000D_
<p className="card-text">{item.email}</p>_x000D_
</div>_x000D_
</div>_x000D_
))}_x000D_
</div>
_x000D_
log4j.jar
filelog4j.jar
file to build pathCall logger by:
private static org.apache.log4j.Logger log
= Logger.getLogger(<class-where-this-is-used>.class);
if log4j properties does not exist, create new file log4j.properties file new file in bin directory:
/workspace/projectdirectory/bin/
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%t %-5p %c{2} - %m%n
Before answering when to use which one, a little background:
edit: I should mention that this comparison is really from the perspective of using them in a browser with JavaScript. It's not the way either data format has to be used, and there are plenty of good parsers which will change the details to make what I'm saying not quite valid.
JSON is both more compact and (in my view) more readable - in transmission it can be "faster" simply because less data is transferred.
In parsing, it depends on your parser. A parser turning the code (be it JSON or XML) into a data structure (like a map) may benefit from the strict nature of XML (XML Schemas disambiguate the data structure nicely) - however in JSON the type of an item (String/Number/Nested JSON Object) can be inferred syntactically, e.g:
myJSON = {"age" : 12,
"name" : "Danielle"}
The parser doesn't need to be intelligent enough to realise that 12
represents a number, (and Danielle
is a string like any other). So in javascript we can do:
anObject = JSON.parse(myJSON);
anObject.age === 12 // True
anObject.name == "Danielle" // True
anObject.age === "12" // False
In XML we'd have to do something like the following:
<person>
<age>12</age>
<name>Danielle</name>
</person>
(as an aside, this illustrates the point that XML is rather more verbose; a concern for data transmission). To use this data, we'd run it through a parser, then we'd have to call something like:
myObject = parseThatXMLPlease();
thePeople = myObject.getChildren("person");
thePerson = thePeople[0];
thePerson.getChildren("name")[0].value() == "Danielle" // True
thePerson.getChildren("age")[0].value() == "12" // True
Actually, a good parser might well type the age
for you (on the other hand, you might well not want it to). What's going on when we access this data is - instead of doing an attribute lookup like in the JSON example above - we're doing a map lookup on the key name
. It might be more intuitive to form the XML like this:
<person name="Danielle" age="12" />
But we'd still have to do map lookups to access our data:
myObject = parseThatXMLPlease();
age = myObject.getChildren("person")[0].getAttr("age");
EDIT: Original:
In most programming languages (not all, by any stretch) a map lookup such as this will be more costly than an attribute lookup (like we got above when we parsed the JSON).
This is misleading: remember that in JavaScript (and other dynamic languages) there's no difference between a map lookup and a field lookup. In fact, a field lookup is just a map lookup.
If you want a really worthwhile comparison, the best is to benchmark it - do the benchmarks in the context where you plan to use the data.
As I have been typing, Felix Kling has already put up a fairly succinct answer comparing them in terms of when to use each one, so I won't go on any further.
Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:
create index arrival_year on reservations ( extract(year from arrival) );
That will open PostgreSQL with the possibility to use an index for
select *
FROM reservations
WHERE extract(year from arrival) = 2012;
Note that the expression in the index must be exactly the same expression as used in the where
clause to make this work.
It's probably because launchctl is managing your mongod instance. If you want to start and shutdown mongod instance, unload that first:
launchctl unload -w ~/Library/LaunchAgents/org.mongodb.mongod.plist
Then start mongod manually:
mongod -f path/to/mongod.conf --fork
You can find your mongod.conf location from ~/Library/LaunchAgents/org.mongodb.mongod.plist
.
After that, db.shutdownServer()
would work just fine.
Added Feb 22 2014:
If you have mongodb installed via homebrew, homebrew actually has a handy brew services
command. To show current running services:
brew services list
To start mongodb:
brew services start mongodb-community
To stop mongodb if it's already running:
brew services stop mongodb-community
Update*
As edufinn pointed out in the comment, brew services
is now available as user-defined command and can be installed with following command: brew tap gapple/services
.
You may see the same schematic explanations for both, but these are totally confusing.
For UNION:
For JOIN:
Another simple way to exclude the auto configuration classes,
Add below similar configuration to your application.yml file,
---
spring:
profiles: test
autoconfigure.exclude: org.springframework.boot.autoconfigure.session.SessionAutoConfiguration
Kotlin for XML
app:cardBackgroundColor="@android:color/red"
code
cardName.setCardBackgroundColor(ContextCompat.getColor(this, R.color.colorGray));
You can include git repository to composer.json like this:
"repositories": [
{
"type": "package",
"package": {
"name": "example-package-name", //give package name to anything, must be unique
"version": "1.0",
"source": {
"url": "https://github.com/example-package-name.git", //git url
"type": "git",
"reference": "master" //git branch-name
}
}
}],
"require" : {
"example-package-name": "1.0"
}
on this web http://quirksmode.org/css/css2/columns.html i found that easy way
<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..
I found it easiest to run my own gem server using geminabox
This is probably what you want:
using System.Security.Principal;
using(WindowsIdentity.GetCurrent().Impersonate())
{
//your code goes here
}
But I really need more details to help you out. You could do impersonation with a config file (if you're trying to do this on a website), or through method decorators (attributes) if it's a WCF service, or through... you get the idea.
Also, if we're talking about impersonating a client that called a particular service (or web app), you need to configure the client correctly so that it passes the appropriate tokens.
Finally, if what you really want do is Delegation, you also need to setup AD correctly so that users and machines are trusted for delegation.
Edit:
Take a look here to see how to impersonate a different user, and for further documentation.
All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)
well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with
\usepackage{ifthen} % provides conditonals...
Start the command, with the "optional" command set blank by default:
\newcommand {\figHoriz} [4] [] {
I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.
\ifthenelse { \equal {#1} {} } %if short caption not specified, use long caption (no slant)
{ \def\temp {\caption[#4]{\textsl{#4}}} } % if #1 == blank
{ \def\temp {\caption[#1]{\textsl{#4}}} } % else (not blank)
Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).
\begin{figure}[!]
\begin{center}
\includegraphics[width=350 pt]{#3}
\temp %see above for caption etc.
\label{#2}
\end{center}
\end{figure}
}
In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.
\MyCommand {first arg} {} {} {}
which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...
If you're like me and you just want to do path-based lookups, but don't care about real XPath, lodash's _.get()
can work. Example from lodash docs:
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// ? 3
_.get(object, ['a', '0', 'b', 'c']);
// ? 3
_.get(object, 'a.b.c', 'default');
// ? 'default'
Here's a solution for jQuery 1.4.x (unfortunately, the accepted answer didn't work for jquery 1.4.1)
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.bind(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
var handlers = this.data('events')[name.split('.')[0]];
// take out the handler we just inserted from the end
var copy = {1: null};
var last = 0, lastValue = null;
$.each(handlers, function(name, value) {
//console.log(name + ": " + value);
var isNumber = !isNaN(name);
if(isNumber) {last = name; lastValue = value;};
var key = isNumber ? (parseInt(name) + 1) : name;
copy[key] = value;
});
copy[1] = lastValue;
this.data('events')[name.split('.')[0]] = copy;
};
First save the .mat file as:
save('test.mat', '-v7')
After that, in Python, use the usual loadmat
function:
import scipy.io as sio
test = sio.loadmat('test.mat')
Using the java.time
framework built into Java 8 and later.
import java.time.LocalDateTime;
import java.time.Instant;
import java.time.ZoneId;
long epoch = Long.parseLong("1081157732");
Instant instant = Instant.ofEpochSecond(epoch);
ZonedDateTime.ofInstant(instant, ZoneOffset.UTC); # ZonedDateTime = 2004-04-05T09:35:32Z[UTC]
In this case you should better use ZonedDateTime
to mark it as date in UTC time zone because Epoch is defined in UTC in Unix time used by Java.
ZoneOffset
contains a handy constant for the UTC time zone, as seen in last line above. Its superclass, ZoneId
can be used to adjust into other time zones.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
check the position of Column annotation in java class for the field For Example,consider one table with name STUDENT with 3 column(Name,Roll_No,Marks).
Then make sure you have added below annotation of column before Getter Method instead of Setter method. It will solve ur problem @Column(name = "Name", length = 100)
**@Column(name = "NAME", length = 100)
public String getName() {**
return name;
}
public void setName(String name) {
this.name= name;
}
I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?
While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a compile time constant in the sense required by the JLS; see §15.28 Constant Expressions for the specification of a constant expression1. This refers to §4.12.4 Final Variables which defines a "constant variable" as follows:
We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).
In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.
In other examples (where the initializers are already compile-time constant expressions), declaring the variable as final
may be what is needed.
You could change your code to use an enum
rather than int
constants, but that brings another couple of different restrictions:
default
case, even if you have case
for every known value of the enum
; see Why is default required for a switch on an enum?case
labels must all be explicit enum
values, not expressions that evaluate to enum
values.1 - The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and String
only, b) allow primaries that are literals (apart from null
) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, ++
, --
or instanceof
, and e) allow type casts to primitive types or String
only.
Note that this doesn't include any form of method or lambda calls, new
, .class
. .length
or array subscripting. Furthermore, any use of array values, enum
values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).
You can divide column of dtype
timedelta
by np.timedelta64(1, 'D')
, but output is not int
, but float
, because NaN
values:
df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
First_Date Second Date Difference
0 2016-02-09 2015-11-19 82.0
1 2016-01-06 2015-11-30 37.0
2 NaT 2015-12-04 NaN
3 2016-01-06 2015-12-08 29.0
4 NaT 2015-12-09 NaN
5 2016-01-07 2015-12-11 27.0
6 NaT 2015-12-12 NaN
7 NaT 2015-12-14 NaN
8 2016-01-06 2015-12-14 23.0
9 NaT 2015-12-15 NaN
The first form is called Javadoc. You use this when you're writing formal APIs for your code, which are generated by the javadoc
tool. For an example, the Java 7 API page uses Javadoc and was generated by that tool.
Some common elements you'd see in Javadoc include:
@param
: this is used to indicate what parameters are being passed to a method, and what value they're expected to have
@return
: this is used to indicate what result the method is going to give back
@throws
: this is used to indicate that a method throws an exception or error in case of certain input
@since
: this is used to indicate the earliest Java version this class or function was available in
As an example, here's Javadoc for the compare
method of Integer
:
/**
* Compares two {@code int} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Integer.valueOf(x).compareTo(Integer.valueOf(y))
* </pre>
*
* @param x the first {@code int} to compare
* @param y the second {@code int} to compare
* @return the value {@code 0} if {@code x == y};
* a value less than {@code 0} if {@code x < y}; and
* a value greater than {@code 0} if {@code x > y}
* @since 1.7
*/
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
The second form is a block (multi-line) comment. You use this if you want to have multiple lines in a comment.
I will say that you'd only want to use the latter form sparingly; that is, you don't want to overburden your code with block comments that don't describe what behaviors the method/complex function is supposed to have.
Since Javadoc is the more descriptive of the two, and you can generate actual documentation as a result of using it, using Javadoc would be more preferable to simple block comments.
import urllib2
Traceback (most recent call last):
File "", line 1, in
import urllib2
ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.
Here is the PEP link (Python Enhancement Proposals )
http://www.python.org/dev/peps/pep-3108/#urllib-package
so instead of urllib2 you can now import urllib.request and then use it like this:
>>>import urllib.request
>>>urllib.request.urlopen('http://www.placementyogi.com')
Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x
I used this videocast to set up my GoDaddy domain with Heroku, and it worked perfectly. Very clear and well explained.
Note: Skip the part about CNAME yourdomain.com.
(note the .
) and the heroku addons:add "custom domains"
http://blog.heroku.com/archives/2009/10/7/heroku_casts_setting_up_custom_domains/
To summarize the video:
1) on GoDaddy and create a CNAME with
Alias Name: www
Host Name: proxy.heroku.com
2) check that your domain has propagated by typing host www.yourdomain.com
on the command line
3) run heroku domains:add www.yourdomain.com
4) run heroku domains:add yourdomain.com
It worked for me after these steps. Hope it works for you too!
UPDATE: things have changed, check out this post Heroku/GoDaddy: send naked domain to www
Yes, you can:
l = L[1::2]
And this is all. The result will contain the elements placed on the following positions (0
-based, so first element is at position 0
, second at 1
etc.):
1, 3, 5
so the result (actual numbers) will be:
2, 4, 6
The [1::2]
at the end is just a notation for list slicing. Usually it is in the following form:
some_list[start:stop:step]
If we omitted start
, the default (0
) would be used. So the first element (at position 0
, because the indexes are 0
-based) would be selected. In this case the second element will be selected.
Because the second element is omitted, the default is being used (the end of the list). So the list is being iterated from the second element to the end.
We also provided third argument (step
) which is 2
. Which means that one element will be selected, the next will be skipped, and so on...
So, to sum up, in this case [1::2]
means:
step=2
, so we are skipping one, as a contrary to step=1
which is default),EDIT: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: Explain Python's slice notation
enumerate()
In your code, you explicitly create and increase the counter. In Python this is not necessary, as you can enumerate through some iterable using enumerate()
:
for count, i in enumerate(L):
if count % 2 == 1:
l.append(i)
The above serves exactly the same purpose as the code you were using:
count = 0
for i in L:
if count % 2 == 1:
l.append(i)
count += 1
More on emulating for
loops with counter in Python: Accessing the index in Python 'for' loops
You would use an MvcHtmlString
if you want to pass raw HTML to an MVC helper method and you don't want the helper method to encode the HTML.
When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy
so it was slightly different. However the same should work for add policy as well.
services.AddAuthorization(options =>
{
options.AddPolicy(DefaultAuthorizedPolicy, policy =>
{
policy.Requirements.Add(new TokenAuthRequirement());
policy.AuthenticationSchemes = new List<string>()
{
CookieAuthenticationDefaults.AuthenticationScheme
}
});
});
Do take into consideration that by Default AuthenticationSchemes
property uses a read only list. I think it would be better to implement that instead of List as well.
At the Maven repo, there are samples to add the dependency in maven, sbt, gradle, etc.
https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.11
ie for Maven, you just create a project, for example
mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4
then look at the pom.xml, then at the library at the dependencies xml element:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.11</version>
</dependency>
For sbt do something like
sbt new scala/hello-world.g8
then edit the build.sbt to add the library
libraryDependencies += "org.apache.httpcomponents" % "httpcore" % "4.4.11"
It looks like this issue has to do with the difference between the Content-Type
and Accept
headers. In HTTP, Content-Type
is used in request and response payloads to convey the media type of the current payload. Accept
is used in request payloads to say what media types the server may use in the response payload.
So, having a Content-Type
in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type
does matter.
If a server is not able to process the Content-Type
of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept
header, it will return a 406 error.)
In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.
You could fix this in one of two ways:
Include the DataServiceVersion header in the request and set it be less than v3. For example:
DataServiceVersion: 2.0;
(Option 2 assumes that you aren't using any v3 features in your request payload.)
You can do it using simple jQuery loop.
Total code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;
$(".bs-example input").each(function(){
if ($.trim($(this).val()).length == 0){
$(this).addClass("highlight");
isFormValid = false;
$(this).focus();
}
else{
$(this).removeClass("highlight");
}
});
if (!isFormValid) {
alert("Please fill in all the required fields (indicated by *)");
}
return isFormValid;
}
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="text" class="form-control" id="inputEmail" placeholder="Email">
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
Raymond Chen has a really excellent blog post on this:
Both the answers are good, but a little advice:
Tuples are immutable, which implies that they cannot be changed. So if you need to manipulate data, it is better to store data in a list, it will reduce unnecessary overhead.
In your case extract the data to a list, as shown by eumiro, and after modifying create a similar tuple of similar structure as answer given by Schoolboy.
Also as suggested using numpy array is a better option
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
A reference is really a pointer with enough sugar to make it taste nice... ;)
But it also uses a different syntax to pointers, which makes it a bit easier to use references than pointers. Because of this, we don't need &
when calling the function that takes the pointer - the compiler deals with that for you. And you don't need *
to get the content of a reference.
To call a reference an alias is a pretty accurate description - it is "another name for the same thing". So when a
is passed as a reference, we're really passing a
, not a copy of a
- it is done (internally) by passing the address of a
, but you don't need to worry about how that works [unless you are writing your own compiler, but then there are lots of other fun things you need to know when writing your own compiler, that you don't need to worry about when you are just programming].
Note that references work the same way for int
or a class
type.
This answer using Pandas is adapted from above, as rolling_mean
is not part of Pandas anymore
# the recommended syntax to import pandas
import pandas as pd
import numpy as np
# prepare some fake data:
# the date-time indices:
t = pd.date_range('1/1/2010', '12/31/2012', freq='D')
# the data:
x = np.arange(0, t.shape[0])
# combine the data & index into a Pandas 'Series' object
D = pd.Series(x, t)
Now, just call the function rolling
on the dataframe with a window size, which in my example below is 10 days.
d_mva10 = D.rolling(10).mean()
# d_mva is the same size as the original Series
# though obviously the first w values are NaN where w is the window size
d_mva10[:11]
2010-01-01 NaN
2010-01-02 NaN
2010-01-03 NaN
2010-01-04 NaN
2010-01-05 NaN
2010-01-06 NaN
2010-01-07 NaN
2010-01-08 NaN
2010-01-09 NaN
2010-01-10 4.5
2010-01-11 5.5
Freq: D, dtype: float64
sendStickyBroadcast()
performs a sendBroadcast(Intent)
known as sticky, i.e. the Intent you are sending stays around after the broadcast is complete, so that others can quickly retrieve that data through the return value of registerReceiver(BroadcastReceiver, IntentFilter)
. In all other ways, this behaves the same as sendBroadcast(Intent)
. One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED
. When you call registerReceiver()
for that action -- even with a null BroadcastReceiver
-- you get the Intent that was last broadcast for that action. Hence, you can use this to find the state of the battery without necessarily registering for all future state changes in the battery.
Let's consider that the environment that one wants to update has the name venv
.
1. Backup venv requirementes (optional)
First of all, backup the requirements of the virtual environment:
pip freeze > requirements.txt
deactivate
#Move the folder to a new one
mv venv venv_old
2. Install Python
Assuming that one doesn't have sudo access, pyenv
is a reliable and fast way to install Python
. For that, one should run
$ curl https://pyenv.run | bash
and then
$ exec $SHELL
If, when one tries to update pyenv
pyenv update
And one gets the error
bash: pyenv: command not found
It is because pyenv path wasn't exported to .bashrc. It can be solved by executing the following commands:
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc
Then restart the shell
exec "$SHELL"
Now one should install the Python version that one wants. Let's say version 3.8.3
pyenv install 3.8.3
One can confirm if it was properly installed by running
pyenv versions
The output should be the location and the versions (in this case 3.8.3)
3. Create the new virtual environment
Finally, with the new Python version installed, create a new virtual environment (let's call it venv
)
python3.8 -m venv venv
Activate it
source venv/bin/activate
and install the requirements
pip install -r requirements.txt
Now one should be up and running with a new environment.
I had a similar problem, but in my case there were no files missing, there was an error in how the pdb output file was defined: I forgot the suffix .pdb (I found out with the debug logging trick).
To solve the problem I changed, in the vxproj file, the following line:
<ProgramDataBaseFileName>MyName</ProgramDataBaseFileName>
to
<ProgramDataBaseFileName>MyName.pdb</ProgramDataBaseFileName>
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xticks([0.4,0.14,0.2,0.2], fontsize = 50) # work on current fig
plt.show()
the x/yticks has the same properties as matplotlib.text
http://realfavicongenerator.net/favicon_checker?site=http://stackoverflow.com gives you favicon analysis stating which favicons are present in what size. You can process the page information to see which is the best quality favicon, and append it's filename to the URL to get it.
This is working for me.
SizedBox(
width: double.maxFinite,
child: RaisedButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
child: new Text("Button 2"),
color: Colors.lightBlueAccent,
onPressed: () => debugPrint("Button 2"),
),
),
public static void WriteLog(string strLog)
{
StreamWriter log;
FileStream fileStream = null;
DirectoryInfo logDirInfo = null;
FileInfo logFileInfo;
string logFilePath = "C:\\Logs\\";
logFilePath = logFilePath + "Log-" + System.DateTime.Today.ToString("MM-dd-yyyy") + "." + "txt";
logFileInfo = new FileInfo(logFilePath);
logDirInfo = new DirectoryInfo(logFileInfo.DirectoryName);
if (!logDirInfo.Exists) logDirInfo.Create();
if (!logFileInfo.Exists)
{
fileStream = logFileInfo.Create();
}
else
{
fileStream = new FileStream(logFilePath, FileMode.Append);
}
log = new StreamWriter(fileStream);
log.WriteLine(strLog);
log.Close();
}
Refer Link: blogspot.in
No you can't overload it; a static constructor is useful for initializing any static fields associated with a type (or any other per-type operations) - useful in particular for reading required configuration data into readonly fields, etc.
It is run automatically by the runtime the first time it is needed (the exact rules there are complicated (see "beforefieldinit"), and changed subtly between CLR2 and CLR4). Unless you abuse reflection, it is guaranteed to run at most once (even if two threads arrive at the same time).
I had found a particular case where swiping (ADB shell input touchscreen swipe ... ) to unlock the home screen doesn't work. More exactly for Acer Z160 and Acer S57. The phones are history but still, they need to be taken into consideration by us developers. Here is the code source that solved my problem. I had made my app to start with the device. and in the "onCreate" function I had changed temporarily the lock type.
Also, just in case google drive does something to the zip file I will post fragments of that code below.
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.gresanuemanuelvasi.test_wakeup">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ServiceStarter" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED"
android:directBootAware="true" tools:targetApi="n">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
class ServiceStarter: BroadcastReceiver() {
@SuppressLint("CommitPrefEdits")
override fun onReceive(context: Context?, intent: Intent?) {
Log.d("EMY_","Calling onReceive")
context?.let {
Log.i("EMY_", "Received action: ${intent!!.getAction()}, user unlocked: " + UserManagerCompat.isUserUnlocked(context))
val sp =it.getSharedPreferences("EMY_", Context.MODE_PRIVATE)
sp.edit().putString(MainActivity.MY_KEY, "M-am activat asa cum trebuie!")
if (intent!!.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
val i = Intent(it, MainActivity::class.java)
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
it.startActivity(i)
}
}
}
}
class MainActivity : AppCompatActivity() {
companion object {
const val MY_KEY="MY_KEY"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val kgm = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
val kgl = kgm.newKeyguardLock(MainActivity::class.java.simpleName)
if (kgm.inKeyguardRestrictedInputMode()) {
kgl.disableKeyguard()
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(arrayOf(Manifest.permission.RECEIVE_BOOT_COMPLETED), 1234)
}
else
{
afisareRezultat()
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
if(1234 == requestCode )
{
afisareRezultat()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun afisareRezultat() {
Log.d("EMY_","Calling afisareRezultat")
val sp = getSharedPreferences("EMY_", Context.MODE_PRIVATE);
val raspuns = sp.getString(MY_KEY, "Doesn't exists")
Log.d("EMY_", "AM primit: ${raspuns}")
sp.edit().remove(MY_KEY).apply()
}
}
You can try with ParseExact
method
Sample
Dim format As String
format = "d"
Dim provider As CultureInfo = CultureInfo.InvariantCulture
result = Date.ParseExact(DateString, format, provider)
OPEN TERMINAL
export PATH=/home/yourUserName/anaconda3/bin:$PATH
anaconda-navigator
This will get you going! cheers!
If you use Perl regular expressions, you can use positive lookahead:
For example
(?=[1-9][0-9]{2})[0-9]*[05]\b
would be numbers greater than 100 and divisible by 5
This should work:
String s = "123foo";
Character.isDigit(s.charAt(0));
You can do what I did to inspect such problem:
Study Android source code, Paint.java source, see both measureText and getTextBounds methods. You'd learn that measureText calls native_measureText, and getTextBounds calls nativeGetStringBounds, which are native methods implemented in C++.
So you'd continue to study Paint.cpp, which implements both.
native_measureText -> SkPaintGlue::measureText_CII
nativeGetStringBounds -> SkPaintGlue::getStringBounds
Now your study checks where these methods differ. After some param checks, both call function SkPaint::measureText in Skia Lib (part of Android), but they both call different overloaded form.
Digging further into Skia, I see that both calls result into same computation in same function, only return result differently.
To answer your question: Both your calls do same computation. Possible difference of result lies in fact that getTextBounds returns bounds as integer, while measureText returns float value.
So what you get is rounding error during conversion of float to int, and this happens in Paint.cpp in SkPaintGlue::doTextBounds in call to function SkRect::roundOut.
The difference between computed width of those two calls may be maximally 1.
EDIT 4 Oct 2011
What may be better than visualization. I took the effort, for own exploring, and for deserving bounty :)
This is font size 60, in red is bounds rectangle, in purple is result of measureText.
It's seen that bounds left part starts some pixels from left, and value of measureText is incremented by this value on both left and right. This is something called Glyph's AdvanceX value. (I've discovered this in Skia sources in SkPaint.cpp)
So the outcome of the test is that measureText adds some advance value to the text on both sides, while getTextBounds computes minimal bounds where given text will fit.
Hope this result is useful to you.
Testing code:
protected void onDraw(Canvas canvas){
final String s = "Hello. I'm some text!";
Paint p = new Paint();
Rect bounds = new Rect();
p.setTextSize(60);
p.getTextBounds(s, 0, s.length(), bounds);
float mt = p.measureText(s);
int bw = bounds.width();
Log.i("LCG", String.format(
"measureText %f, getTextBounds %d (%s)",
mt,
bw, bounds.toShortString())
);
bounds.offset(0, -bounds.top);
p.setStyle(Style.STROKE);
canvas.drawColor(0xff000080);
p.setColor(0xffff0000);
canvas.drawRect(bounds, p);
p.setColor(0xff00ff00);
canvas.drawText(s, 0, bounds.bottom, p);
}
Running pip install
command with --user
argument resolved the issue
python -m pip install --upgrade pip --user
try this code, it will work for all version of URLs like
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS_HOST} !^www.website.com$ [NC]
RewriteRule ^(.*)$ https://www.website.com/$1 [L,R=301]
Short and simple:
def ave(x,y):
return (x + y) / 2.0
map(ave, a[:-1], a[1:])
And here's how it looks:
>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
Due to some stupidity in how Python handles a map
over two lists, you do have to truncate the list, a[:-1]
. It works more as you'd expect if you use itertools.imap
:
>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.
HTH.
In order to avoid this kind of ClassCastException, if you have:
class A
class B extends A
You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:
public B(A a) {
super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
// If B class has more attributes, then you would initilize them here
}
A DataFrame follows the dict-like convention of iterating over the “keys” of the objects.
my_dataframe.keys()
Create a list of keys/columns - object method to_list()
and pythonic way
my_dataframe.keys().to_list()
list(my_dataframe.keys())
Basic iteration on a DataFrame returns column labels
[column for column in my_dataframe]
Do not convert a DataFrame into a list, just to get the column labels. Do not stop thinking while looking for convenient code samples.
xlarge = pd.DataFrame(np.arange(100000000).reshape(10000,10000))
list(xlarge) #compute time and memory consumption depend on dataframe size - O(N)
list(xlarge.keys()) #constant time operation - O(1)
It seems to me most of you are giving example of getters and setters not a constructor, ie http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming).
lunched-dan was closer but the example didn't work in jsFiddle.
This example creates a private constructor function that only runs during the creation of the object.
var color = 'black';
function Box()
{
// private property
var color = '';
// private constructor
var __construct = function() {
alert("Object Created.");
color = 'green';
}()
// getter
this.getColor = function() {
return color;
}
// setter
this.setColor = function(data) {
color = data;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
If you wanted to assign public properties then the constructor could be defined as such:
var color = 'black';
function Box()
{
// public property
this.color = '';
// private constructor
var __construct = function(that) {
alert("Object Created.");
that.color = 'green';
}(this)
// getter
this.getColor = function() {
return this.color;
}
// setter
this.setColor = function(color) {
this.color = color;
}
}
var b = new Box();
alert(b.getColor()); // should be green
b.setColor('orange');
alert(b.getColor()); // should be orange
alert(color); // should be black
@petah and Acrylic DNS Proxy is the best answer, and at the end he references the ability to do multi-site using an Apache which @jeremyasnyder describes a little further down...
... however, in our case we're testing a multi-tenant hosting system and so most domains we want to test go to the same virtualhost
, while a couple others are directed elsewhere.
So in our case, you simply use regex wildcards in the ServerAlias
directive, like so...
ServerAlias *.foo.local
To name a few we can use redux-react-session which is having good API for session management like, initSessionService
, refreshFromLocalStorage
, checkAuth
and many other. It also provide some advanced functionality like Immutable JS
.
Alternatively we can leverage react-web-session which provides options like callback
and timeout
.
Say you want to fill with number 13.
int[] myarr = Enumerable.Range(0, 10).Select(n => 13).ToArray();
or
List<int> myarr = Enumerable.Range(0,10).Select(n => 13).ToList();
if you prefer a list.
This is a one line solution involving LINQ.
var elements = new String[] { "1", "2", "3" };
Foo(elements.Cast<object>().ToArray())
You can do something like this:
<input type="date" value="<?php echo date("Y-m-d");?>" name="inicio">
Those errors are printed out to the standard error output (fd 2). To filter them out, simply redirect all errors to /dev/null:
find . 2>/dev/null > some_file
or first join stderr and stdout and then grep out those specific errors:
find . 2>&1 | grep -v 'Permission denied' > some_file
On the model set $incrementing
to false
public $incrementing = false;
This will stop it from thinking it is an auto increment field.
<div id="OK1" runat="server" style ="display:none" >
<asp:DropDownList ID="DropDownList2" runat="server"></asp:DropDownList>
</div>
vb.net code
Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles DropDownList1.SelectedIndexChanged
If DropDownList1.SelectedIndex = 0 Then
OK1.Style.Add("display", "none")
Else
OK1.Style.Add("display", "block")
End If
End Sub
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
I can suggest using WITH
like this:
DECLARE @Delim char(1) = ',';
SET @Ids = @Ids + @Delim;
WITH CTE(i, ls, id) AS (
SELECT 1, CHARINDEX(@Delim, @Ids, 1), SUBSTRING(@Ids, 1, CHARINDEX(@Delim, @Ids, 1) - 1)
UNION ALL
SELECT i + 1, CHARINDEX(@Delim, @Ids, ls + 1), SUBSTRING(@Ids, ls + 1, CHARINDEX(@Delim, @Ids, ls + 1) - CHARINDEX(@Delim, @Ids, ls) - 1)
FROM CTE
WHERE CHARINDEX(@Delim, @Ids, ls + 1) > 1
)
SELECT t.*
FROM yourTable t
INNER JOIN
CTE c
ON t.id = c.id;
Alter your field to be INT instead of VARCHAR.
I can not make them INT due to some other depending circumstances.
Then fix the depending circumstances first. Otherwise you are working around the real underlying issue. Using a MySQL CAST is an option, but it's masking your bad schema which should be fixed.
Here is a plotrix solution:
set.seed(0815)
x <- 1:10
F <- runif(10,1,2)
L <- runif(10,0,1)
U <- runif(10,2,3)
require(plotrix)
plotCI(x, F, ui=U, li=L)
And here is a ggplot solution:
set.seed(0815)
df <- data.frame(x =1:10,
F =runif(10,1,2),
L =runif(10,0,1),
U =runif(10,2,3))
require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
geom_point(size = 4) +
geom_errorbar(aes(ymax = U, ymin = L))
UPDATE: Here is a base solution to your edits:
set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
y = x + rnorm(20))
plot(y ~ x, data = df)
# model
mod <- lm(y ~ x, data = df)
# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx),
interval = 'confidence')
# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')
I've wrote this small script when the number of branches in my repo exceeded several hundreds. I did not know about the other methods (with CLI) so I decided to automate it with selenium. It simply opens Bitbucket website, goes to Branches, scrolls down the page to the end and clicks on every branch options menu -> clicks Delete button -> clicks Yes. It can be tuned to keep the last N (100 - default) branches and skip branches with specific names (master, develop - default, could be more). If this fits for you, you can try that way.
https://github.com/globad/remove-old-branches
All you need is to clone the repository, download the proper version of Chrome-webdriver, input few constants like URL to your repository and run the script.
The code is simple enough to understand. If you have any questions, write comments / create an Issue.
You should bind the tap event, the click does not exist on mobile safari or in the UIWbview. You can also use this polyfill ,to avoid the 300ms delay when a link is touched.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
I had this error when i renamed the pc in the windows-properties. The pc-name must be updated in the listener.ora
-file
if you want to see it graphically you can use
gitk -- foo/A