Specifically if you want to clear your text box in VB.NET or VB 6.0, write this code:
TextBox1.Items.Clear()
If you are using VBA, then the use this code :
TextBox1.Text = ""
or
TextBox1.Clear()
Set the styles for class active and hover:
Than you need to make the li active, on the server side. So when you are drawing the menu, you should know which page is loaded and set it to:
<li class="active">Question</li>
<li>Tags</li>
<li>Users</li>
But if you are changing the content without reloading, you cannot change set the active li element on the server, you need to use javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 300px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li>Item 1</li>
<li class="active">Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
</body>
</html>
you need to put a dot between the class like
class="column.wrapper">
In PHP, If your network under proxy. You should set the proxy URL and port
curl_setopt($ch, CURLOPT_PROXY, "http://url.com"); //your proxy url
curl_setopt($ch, CURLOPT_PROXYPORT, "80"); // your proxy port number
This is solves my problem
I think the core of this question is about virtual methods and polymorphism, not the destructor specifically. Here is a clearer example:
class A
{
public:
A() {}
virtual void foo()
{
cout << "This is A." << endl;
}
};
class B : public A
{
public:
B() {}
void foo()
{
cout << "This is B." << endl;
}
};
int main(int argc, char* argv[])
{
A *a = new B();
a->foo();
if(a != NULL)
delete a;
return 0;
}
Will print out:
This is B.
Without virtual
it will print out:
This is A.
And now you should understand when to use virtual destructors.
We can Supply parameter in different way after some search I found some useful
<plugin>
<artifactId>${release.artifactId}</artifactId>
<version>${release.version}-${release.svm.version}</version>...
...
Actually in my application I need to save and supply SVN Version as parameter so i have implemented as above .
While Running build we need supply value for those parameter as follows.
RestProj_Bizs>mvn clean install package -Drelease.artifactId=RestAPIBiz -Drelease.version=10.6 -Drelease.svm.version=74
Here I am supplying
release.artifactId=RestAPIBiz
release.version=10.6
release.svm.version=74
It worked for me. Thanks
REMEMBER, this method overwrites first array, so use only when you are sure!
$arr1 = $arr1 + $arr2;
O(1) - most cooking procedures are O(1), that is, it takes a constant amount of time even if there are more people to cook for (to a degree, because you could run out of space in your pot/pans and need to split up the cooking)
O(logn) - finding something in your telephone book. Think binary search.
O(n) - reading a book, where n is the number of pages. It is the minimum amount of time it takes to read a book.
O(nlogn) - cant immediately think of something one might do everyday that is nlogn...unless you sort cards by doing merge or quick sort!
Just Add reference to System.Web.Extensions and happy to go.
Maybe too late, but I'd cast 0/1 as bit to make the datatype eventually becomes True/False when consumed by .NET framework:
SELECT EntityId,
EntityName,
CASE
WHEN EntityProfileIs IS NULL
THEN CAST(0 as bit)
ELSE CAST(1 as bit) END AS HasProfile
FROM Entities
LEFT JOIN EntityProfiles ON EntityProfiles.EntityId = Entities.EntityId`
Functional programming is about creating side-effect-free code.
map is a functional list transformation abstraction. You use it to take a sequence of something and turn it into a sequence of something else.
You are trying to use it as an iterator. Don't do that. :)
Here is an example of how you might use map to build the list you want. There are shorter solutions (I'd just use comprehensions), but this will help you understand what map does a bit better:
def my_transform_function(input):
return [input, [1, 2, 3]]
new_list = map(my_transform, input_list)
Notice at this point, you've only done a data manipulation. Now you can print it:
for n,l in new_list:
print n, ll
-- I'm not sure what you mean by 'without loops.' fp isn't about avoiding loops (you can't examine every item in a list without visiting each one). It's about avoiding side-effects, thus writing fewer bugs.
What I started doing a while back was to have a single sub that sets the size of all my controls. I can then run this sub from any point in the code where the controls grow or shrink. It's sometimes a lot of extra finicky work, but it keeps my buttons from eating my spreadsheet.
I had this problem and it was due to an upgrade of my git executable. I rolled back to Git-2.21.0.rc1.windows.1-64-bit and added this to my environment path and it fixed my issue.
Using console.log(object)
will throw your object to the Javascript console, but that's not always what you want. Using JSON.stringify(object)
will return most stuff to be stored in a variable, for example to send it to a textarea input and submit the content back to the server.
For me, the user was mongod
instead of mongodb
sudo chown mongod:mongod /newlocation
You can see the logs for errors if the service fails:
/var/log/mongodb/mongod.log
I have got same issue on my server. Follow below steps -
It works and solved my problem.
Use time.sleep()
from time import sleep
sleep(0.05)
Let's assume that your iframe id= myIframe
here is the code:
<script>
window.setInterval("reloadIFrame();", 30000);
function reloadIFrame() {
document.getElementById("myIframe").src="YOUR_PAGE_URL_HERE";
}
</script>
Make sure the below is implemented For in-app reviews:
implementation 'com.google.android.play:core:1.8.0'
OnCreate
public void RateApp(Context mContext) {
try {
ReviewManager manager = ReviewManagerFactory.create(mContext);
manager.requestReviewFlow().addOnCompleteListener(new OnCompleteListener<ReviewInfo>() {
@Override
public void onComplete(@NonNull Task<ReviewInfo> task) {
if(task.isSuccessful()){
ReviewInfo reviewInfo = task.getResult();
manager.launchReviewFlow((Activity) mContext, reviewInfo).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(mContext, "Rating Failed", Toast.LENGTH_SHORT).show();
}
}).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
Toast.makeText(mContext, "Review Completed, Thank You!", Toast.LENGTH_SHORT).show();
}
});
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
Toast.makeText(mContext, "In-App Request Failed", Toast.LENGTH_SHORT).show();
}
});
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
}
As said before modulo isn't sufficient because it skews the distribution. Heres my code which masks off bits and uses them to ensure the distribution isn't skewed.
static uint32_t randomInRange(uint32_t a,uint32_t b) {
uint32_t v;
uint32_t range;
uint32_t upper;
uint32_t lower;
uint32_t mask;
if(a == b) {
return a;
}
if(a > b) {
upper = a;
lower = b;
} else {
upper = b;
lower = a;
}
range = upper - lower;
mask = 0;
//XXX calculate range with log and mask? nah, too lazy :).
while(1) {
if(mask >= range) {
break;
}
mask = (mask << 1) | 1;
}
while(1) {
v = rand() & mask;
if(v <= range) {
return lower + v;
}
}
}
The following simple code lets you look at the distribution:
int main() {
unsigned long long int i;
unsigned int n = 10;
unsigned int numbers[n];
for (i = 0; i < n; i++) {
numbers[i] = 0;
}
for (i = 0 ; i < 10000000 ; i++){
uint32_t rand = random_in_range(0,n - 1);
if(rand >= n){
printf("bug: rand out of range %u\n",(unsigned int)rand);
return 1;
}
numbers[rand] += 1;
}
for(i = 0; i < n; i++) {
printf("%u: %u\n",i,numbers[i]);
}
}
Use padding
on the cells and border-spacing
on the table. The former will give you cellpadding while the latter will give you cellspacing.
table { border-spacing: 5px; } /* cellspacing */
th, td { padding: 5px; } /* cellpadding */
Simpley add this two line in toolbar. Then we get new removed left side space bcoz by default it 16dp.
android:contentInsetStart="0dp"
app:contentInsetStart="0dp"
Another example similar to those here
function fileSize(b) {
var u = 0, s=1024;
while (b >= s || -b >= s) {
b /= s;
u++;
}
return (u ? b.toFixed(1) + ' ' : b) + ' KMGTPEZY'[u] + 'B';
}
It measures negligibly better performance than the others with similar features.
function count(){
var c= 0;
for(var p in this) if(this.hasOwnProperty(p))++c;
return c;
}
var O={a: 1, b: 2, c: 3};
count.call(O);
The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:
Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);
The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):
>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True
Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.
Also make sure you have all @Before
-, @After
- and whatever-JUnit-annotated methods declared as public
. I had mine declared as private
which caused the issue.
Here's how you can add additional certificates to your KeyStore to avoid this problem: Trusting all certificates using HttpClient over HTTPS
It won't prompt the user like you ask, but it will make it less likely that the user will run into a "Not trusted server certificate" error.
It's not as straightforward as looks. I just run into a similar question, and here is what I got: First, a little background on wikipedia.
Next, in CSS, for paper, they have pt
, which is point, or 1/72 inch. So if you want to have the same size of image as on the monitor, first you have to know the DPI/PPI of your monitor (usually 96, as mentioned on the wikipedia article), then convert it to inches, then convert it to points (divide by 72).
But then again, the browsers have all sorts of problems with printable content, for example, if you try to use float css tags, the Gecko-based browsers will cut your images mid page, even if you use page-break-inside: avoid; on your images (see here, in the Mozilla bug tracking system).
There is (much) more about printing from a browser in this article on A List Apart.
Furthermore, you have to deal width "Shrink to Fit" in the print preview, and the various paper sizes and orientations.
So either you just figure out a good image size in inches, I mean points, (7.1" * 72 = 511.2 so width: 511pt;
would work for the letter sized paper) regardless of the pixel sizes, or go width percentage widths, and base your image widths on the paper size.
Good luck...
Simplest way? It works. :)
Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
Try
Using connection As New SqlConnection(ConnStrg)
connection.Open()
Dim command As New SqlCommand(queryString, connection)
Dim reader As SqlDataReader = command.ExecuteReader()
Dim DTResults As New DataTable
DTResults.Load(reader)
MsgBox(DTResults.Rows(0)(0).ToString)
End Using
Catch ex As Exception
MessageBox.Show("Error while executing .. " & ex.Message, "")
Finally
End Try
Try to use:
mvn clean package install
This command should install your artifacts in you local maven repo.
PS: I see that this is an old question, but it may be helpful for somebody in the future.
$formattedPrice = Mage::helper('core')->currency($_finalPrice,true,false);
According to pyodbc documentation, connections to the SQL server are not closed by default. Some database drivers do not close connections when close() is called in order to save round-trips to the server.
To close your connection when you call close() you should set pooling to False:
import pyodbc
pyodbc.pooling = False
An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.
UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}
Example:
UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;
I think you missed a equal sign at:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);
Change to:
Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null);
Take a look at SimpleDateFormat
:
java.util.Date utilDate = new java.util.Date();
java.sql.Timestamp sq = new java.sql.Timestamp(utilDate.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
System.out.println(sdf.format(sq));
If those elements have a common class name, one may also use this:
$('#your_div .your_classname').serialize()
This way you can avoid selection of buttons, which will be selected using the jQuery selector :input
. Though this can also be avoided by using $('#your_div :input:not(:button)').serialize();
There is a chance that application pool created for you application by default is version 2. So although you see a handler for .svc extension in the list it does not work and treat it as static file. All you need is to open application pool properties and switch it to version 4.
See this link. It shows you how to dynamically create variables in PowerShell.
Here is the basic idea:
Use New-Variable and Get-Variable,
for ($i=1; $i -le 5; $i++)
{
New-Variable -Name "var$i" -Value $i
Get-Variable -Name "var$i" -ValueOnly
}
(It is taken from the link provided, and I don't take credit for the code.)
In XCode under Targets, right-click on your project and Get Info. Under the Build tab look for iOS Deployment Target. By changing this you should be able to test different iOS version.
Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: findstr /v "randomtextthatnoonewilluse" filename.txt
If you get a model instance from the database, then calling the save method will always update that instance. For example:
t = TemperatureData.objects.get(id=1)
t.value = 999 # change field
t.save() # this will update only
If your goal is prevent any INSERTs, then you can override the save
method, test if the primary key exists and raise an exception. See the following for more detail:
I'd also suggest moving the event handler outside render.
var OnSubmitTest = React.createClass({
submit: function(e){
e.preventDefault();
alert('it works!');
}
render: function() {
return (
<form onSubmit={this.submit}>
<button>Click me</button>
</form>
);
}
});
sir_neanderthal has already posted a nice answer.
I just want to point out that if you would like to use different names for your inputs you can also use (or just copy the method) require_from_group method from official jQuery Validation additional-methods.js (link to CDN for version 1.13.1).
This answer applies when a string is manually entered, not when it's read from somewhere.
A traditional variable-width CSV is unreadable for storing data as a string variable. Especially for use inside a .py
file, consider fixed-width pipe-separated data instead. Various IDEs and editors may have a plugin to format pipe-separated text into a neat table.
read_csv
Store the following in a utility module, e.g. util/pandas.py
. An example is included in the function's docstring.
import io
import re
import pandas as pd
def read_psv(str_input: str, **kwargs) -> pd.DataFrame:
"""Read a Pandas object from a pipe-separated table contained within a string.
Input example:
| int_score | ext_score | eligible |
| | 701 | True |
| 221.3 | 0 | False |
| | 576 | True |
| 300 | 600 | True |
The leading and trailing pipes are optional, but if one is present,
so must be the other.
`kwargs` are passed to `read_csv`. They must not include `sep`.
In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can
be used to neatly format a table.
Ref: https://stackoverflow.com/a/46471952/
"""
substitutions = [
('^ *', ''), # Remove leading spaces
(' *$', ''), # Remove trailing spaces
(r' *\| *', '|'), # Remove spaces between columns
]
if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
substitutions.extend([
(r'^\|', ''), # Remove redundant leading delimiter
(r'\|$', ''), # Remove redundant trailing delimiter
])
for pattern, replacement in substitutions:
str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
return pd.read_csv(io.StringIO(str_input), sep='|', **kwargs)
The code below doesn't work properly because it adds an empty column on both the left and right sides.
df = pd.read_csv(io.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
As for read_fwf
, it doesn't actually use so many of the optional kwargs that read_csv
accepts and uses. As such, it shouldn't be used at all for pipe-separated data.
if it is a RSA key
openssl rsa -pubout -in my_rsa_key.pem
if you need it in a format for openssh , please see Use RSA private key to generate public key?
Note that public key is generated from the private key and ssh uses the identity file (private key file) to generate and send public key to server and un-encrypt the encrypted token from the server via the private key in identity file.
A good example of the 307 Internal Redirect
in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.
The browser redirects seamlessly, using the same method as the original call.
Have you set up a python interpreter facet?
Open Project Structure CTRL+ALT+SHIFT+S
Project settings -> Facets -> expand Python click on child -> Python Interpreter
Then:
Project settings -> Modules -> Expand module -> Python -> Dependencies -> select Python module SDK
In addition to @zhutoulala accepted answer, here is an update to make it work with latest stable version to date (2.8) on ARMHF platforms (Raspberry Pi 3 model B). First I can confirm that you must recompile native libraries to 64 bit ARM, other answers here based on setting some environment variables won't work. As indicated in Hadoop documentation, the pre-built native libraries are 32 bit.
High level steps given in the fist link (http://www.ercoppa.org/posts/how-to-compile-apache-hadoop-on-ubuntu-linux.html) are correct. On this url http://www.instructables.com/id/Native-Hadoop-260-Build-on-Pi/ you get more details specific to Raspberry Pi, but not for Hadoop version 2.8.
Here are my indications pour Hadoop 2.8 :
CMake file patching method must be changed. Moreovere, files to patch are not the same. Unfortunately, there is no accepted patch on JIRA specific to 2.8. On this URL (https://issues.apache.org/jira/browse/HADOOP-9320) you must copy and paste Andreas Muttscheller proposed patch on your namenode :
:hadoop-2.8.0-src/hadoop-common-project/hadoop-common $ touch HADOOP-9320-v2.8.patch
:hadoop-2.8.0-src/hadoop-common-project/hadoop-common $ vim HADOOP-9320-v2.8.patch
#copy and paste proposed patch given here : https://issues.apache.org/jira/browse/HADOOP-9320?focusedCommentId=16018862&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-16018862
:hadoop-2.8.0-src/hadoop-common-project/hadoop-common $ patch < HADOOP-9320-v2.8.patch
patching file HadoopCommon.cmake
patching file HadoopJNI.cmake
:hadoop-2.8.0-src/hadoop-common-project/hadoop-common $ cd ../..
:hadoop-2.8.0-src $ sudo mvn package -Pdist,native -DskipTests -Dtar
Once build is successful :
:hadoop-2.8.0-src/hadoop-dist/target/hadoop-2.8.0/lib/native $ tar -cvf nativelibs.tar *
And replace the content of the lib/native directory of your Hadoop install with the content of this archive. Warning message when running Hadoop should disappear.
You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.
The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around:
You can access other extension pages (i.e. options page, popup page) from within the background page/script with the chrome.extension.getViews()
call. As described here.
// overwrite the console object with the right one.
var optionsPage = ( chrome.extension.getViews()
&& (chrome.extension.getViews().length > 1) )
? chrome.extension.getViews()[1] : null;
// safety precaution.
if (optionsPage) {
var console = optionsPage.console;
}
<!DOCTYPE html>
<html>
<body>
<p>Click the button to make a BUTTON element with text.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.setAttribute("style","color:red;font-size:23px");
btn.appendChild(t);
document.body.appendChild(btn);
btn.setAttribute("onclick", alert("clicked"));
}
</script>
</body>
</html>
There are actually three things here: origin master
is two separate things, and origin/master
is one thing. Three things total.
Two branches:
master
is a local branchorigin/master
is a remote branch (which is a local copy of the branch named "master" on the remote named "origin")One remote:
origin
is a remoteSince origin/master
is a branch, you can merge it. Here's a pull in two steps:
Step one, fetch master
from the remote origin
. The master
branch on origin
will be fetched and the local copy will be named origin/master
.
git fetch origin master
Then you merge origin/master
into master
.
git merge origin/master
Then you can push your new changes in master
back to origin
:
git push origin master
You can fetch multiple branches by name...
git fetch origin master stable oldstable
You can merge multiple branches...
git merge origin/master hotfix-2275 hotfix-2276 hotfix-2290
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
http://llvm.org/docs/FAQ.html#translatecxx
It handles some code, but will fail for more complex implementations as it hasn't been fully updated for some of the modern C++ conventions. So try compiling your code frequently until you get a feel for what's allowed.
Usage sytax from the command line is as follows for version 9.0.1:
clang -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
clang -march=c CPPtoC.bc -o CPPtoC.c
For older versions (unsure of transition version), use the following syntax:
llvm-g++ -c CPPtoC.cpp -o CPPtoC.bc -emit-llvm
llc -march=c CPPtoC.bc -o CPPtoC.c
Note that it creates a GNU flavor of C and not true ANSI C. You will want to test that this is useful for you before you invest too heavily in your code. For example, some embedded systems only accept ANSI C.
Also note that it generates functional but fairly unreadable code. I recommend commenting and maintain your C++ code and not worrying about the final C code.
EDIT : although official support of this functionality was removed, but users can still use this unofficial support from Julia language devs, to achieve mentioned above functionality.
Here's a different approach using CSS instead of JavaScript/AngularJS.
CSS:
.emptymsg {
display: list-item;
}
li + .emptymsg {
display: none;
}
Markup:
<ul>
<li ng-repeat="item in filteredItems"> ... </li>
<li class="emptymsg">No items found</li>
</ul>
If the list is empty, <li ng-repeat="item in filteredItems">, etc. will get commented out and will become a comment instead of a li element.
The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git
directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR
links a workspace to the repository from which it originates.
Git commands git clone
and git init
both have options --bare
that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.
In my experience, using an event listener on scroll can create a lot of noise due to piping into that event stream, which can cause performance issues if you are executing a bulky handleScroll
function.
I often use the technique shown here in the highest rated answer, but I add debounce on top of it, usually about 100ms
yields good performance to UX ratio.
Here is an example using the top-rated answer with Lodash debounce added:
import debounce from 'lodash/debounce';
export default {
methods: {
handleScroll(event) {
// Any code to be executed when the window is scrolled
this.isUserScrolling = (window.scrollY > 0);
console.log('calling handleScroll');
}
},
created() {
this.handleDebouncedScroll = debounce(this.handleScroll, 100);
window.addEventListener('scroll', this.handleDebouncedScroll);
},
beforeDestroy() {
// I switched the example from `destroyed` to `beforeDestroy`
// to exercise your mind a bit. This lifecycle method works too.
window.removeEventListener('scroll', this.handleDebouncedScroll);
}
}
Try changing the value of 100
to 0
and 1000
so you can see the difference in how/when handleScroll
is called.
BONUS: You can also accomplish this in an even more concise and reuseable manner with a library like vue-scroll
. It is a great use case for you to learn about custom directives in Vue if you haven't seen those yet. Check out https://github.com/wangpin34/vue-scroll.
This is also a great tutorial by Sarah Drasner in the Vue docs: https://vuejs.org/v2/cookbook/creating-custom-scroll-directives.html
Python doesn't have matrices. You can use a list of lists or NumPy
you should android sdk manager install 4.2 api 17 -> ARM EABI v7a System Image
if not installed ARM EABI v7a System Image, you should install all.
I was having the same problem today.. and has been searching for answers.. I am on Ubuntu... however, I could not find the correct one that works on this thread.. after much research the following worked for me finally!! :)
First, after running
mongod dbpath
if appeared that mongodb was looking for the data/db directory.. which was missing in my installed mongodb app.. so I ran the following commands:
$ sudo mkdir -p /data/db
then run,
$ sudo chown -R $USER /data/db
chown - changes ownership of files/dirs. Ie. owner of the file/dir changes to the specified one, but it doesn't modify permissions. As detailed here: https://unix.stackexchange.com/questions/402062/how-are-chown-and-chmod-command-different-in-the-given-operation
Finally, run
`$ sudo systemctl enable mongod.service
It will give a message: Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service ? /lib/systemd/system/mongod.service and started the service.
You can use column indices (letters) like this:
import pandas as pd
import numpy as np
file_loc = "path.xlsx"
df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")
print(df)
[Corresponding documentation][1]:
usecolsint, str, list-like, or callable default None
- If None, then parse all columns.
- If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
- If list of int, then indicates list of column numbers to be parsed.
If list of string, then indicates list of column names to be parsed.
New in version 0.24.0.
If callable, then evaluate each column name against it and parse the column if the callable returns True.
Returns a subset of the columns according to behavior above.
New in version 0.24.0.
This can also happen when the redirect_uri
submitted with the https://www.facebook.com/dialog/oauth request is not present in the list of Valid OAuth redirect URIs under:
After much trial and error, when I added the redirect_uri
that I was using (https://www.facebook.com/connect/login_success.html in my case), I suddenly got to the step past this error.
I've been happily using pympler for such tasks. It's compatible with many versions of Python -- the asizeof
module in particular goes back to 2.2!
For example, using hughdbrown's example but with from pympler import asizeof
at the start and print asizeof.asizeof(v)
at the end, I see (system Python 2.5 on MacOSX 10.5):
$ python pymp.py
set 120
unicode 32
tuple 32
int 16
decimal 152
float 16
list 40
object 0
dict 144
str 32
Clearly there is some approximation here, but I've found it very useful for footprint analysis and tuning.
With Javascript you can get full size profile images like this
pass your accessToken
to the getface()
function from your FB.init
call
function getface(accessToken){
FB.api('/me/friends', function (response) {
for (id in response.data) {
var homie=response.data[id].id
FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
for (album in aresponse.data) {
if (aresponse.data[album].name == "Profile Pictures") {
FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
console.log(aresponse.data[0].images[0].source);
});
}
}
});
}
});
}
Firstly you have to create state in app.js as below
.state('login', {
url: '/',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
and use below code in controller
$location.path('login');
Hope this will help you
The easiest way I have found to do this is to just use require
and the path to your JSON file.
For example, suppose you have the following JSON file.
test.json
{
"firstName": "Joe",
"lastName": "Smith"
}
You can then easily load this in your node.js application using require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
Java 8 with apache httpClient 4
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");
String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";
try {
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// set your POST request headers to accept json contents
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
// your closeablehttp response
CloseableHttpResponse response = client.execute(httpPost);
// print your status code from the response
System.out.println(response.getStatusLine().getStatusCode());
// take the response body as a json formatted string
String responseJSON = EntityUtils.toString(response.getEntity());
// convert/parse the json formatted string to a json object
JSONObject jobj = new JSONObject(responseJSON);
//print your response body that formatted into json
System.out.println(jobj);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The problem is that the base class foo
has no parameterless constructor. So you must call constructor of the base class with parameters from constructor of the derived class:
public bar(int a, int b) : base(a, b)
{
c = a * b;
}
Use this:
\d{10}
I hope it helps.
For me, the culprit is adb holding onto the apk file since I utilise it to install and start the application on my physical device through command line.
So simply:
Task Manager > End process adb.exe
And then the file is free to be deleted and the project may be cleaned
CGRect buttonFrame = CGRectMake( x-pos, y-pos, width, height ); //
CGRectMake(10,5,10,10)
UIButton *button = [[UIButton alloc] initWithFrame: buttonFrame];
button setTitle: @"My Button" forState: UIControlStateNormal];
[button addTarget:self action:@selector(btnClicked:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitleColor: [UIColor BlueVolor] forState:
UIControlStateNormal];
[view addSubview:button];
-(void)btnClicked {
// your code }
The best solution is the attribute selector in CSS (input[type="text"]
) as the others suggested.
But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.
In this case your only option seems to be to define classes on input elements.
<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...
and target them with a class selector:
input.input-box, textarea { background: cyan; }
I had the same problem and trouble getting it to work on all browsers.
So this is the best font stack for Helvetica Neue Condensed Bold I could find:
font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;
Even more stacks to find at:
http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/
With C++11 you can use the constexpr
keyword and write in your header:
private:
static constexpr const char* SOMETHING = "something";
Notes:
constexpr
makes SOMETHING
a constant pointer so you cannot write
SOMETHING = "something different";
later on.
Depending on your compiler, you might also need to write an explicit definition in the .cpp file:
constexpr const char* MyClass::SOMETHING;
If you use the string literal exactly as you have shown us, the problem is the ;
character at the end. You may not include that in the query string in the JDBC calls.
As you are inserting only a single row, a regular INSERT
should be just fine even when inserting multiple rows. Using a batched statement is probable more efficient anywy. No need for INSERT ALL
. Additionally you don't need the temporary clob and all that. You can simplify your method to something like this (assuming I got the parameters right):
String query1 = "select substr(to_char(max_data),1,4) as year, " +
"substr(to_char(max_data),5,6) as month, max_data " +
"from dss_fin_user.acq_dashboard_src_load_success " +
"where source = 'CHQ PeopleSoft FS'";
String query2 = ".....";
String sql = "insert into domo_queries (clob_column) values (?)";
PreparedStatement pstmt = con.prepareStatement(sql);
StringReader reader = new StringReader(query1);
pstmt.setCharacterStream(1, reader, query1.length());
pstmt.addBatch();
reader = new StringReader(query2);
pstmt.setCharacterStream(1, reader, query2.length());
pstmt.addBatch();
pstmt.executeBatch();
con.commit();
I had a similar problem that inspired me to develop an app that could help to capture traffic from an Android device. The app features SSH server that allows you to have traffic in Wireshark on the fly (sshdump wireshark component). As the app uses an OS feature called VPNService to capture traffic, it does not require the root access.
The app is in early Beta. If you have any issues/suggestions, do not hesitate to let me know.
If you want to select ALL(columns) data as distinct frrom a DataFrame (df), then
df.select('*').distinct().show(10,truncate=False)
What about this?
^([a-zA-Z]|[à-ú]|[À-Ú])+$
It will match every word with accented characters or not.
Just the standard scan will return the MAC.
nmap -sS target
As others have already mentioned, the best way to debug your variables is to use a modern browser's developer console (e.g. Chrome Developer Tools, Firefox+Firebug, Opera Dragonfly (which now disappeared in the new Chromium-based (Blink) Opera, but as developers say, "Dragonfly is not dead though we cannot give you more information yet").
But in case you need another approach, there's a really useful site called php.js:
which provides "JavaScript alternatives to PHP functions" - so you can use them the similar way as you would in PHP. I will copy-paste the appropriate functions to you here, BUT be aware that these codes can get updated on the original site in case some bugs are detected, so I suggest you visiting the phpjs.org site! (Btw. I'm NOT affiliated with the site, but I find it extremely useful.)
var_dump()
in JavaScriptHere is the code of the JS-alternative of var_dump()
:
http://phpjs.org/functions/var_dump/
it depends on the echo()
function: http://phpjs.org/functions/echo/
function var_dump() {
// discuss at: http://phpjs.org/functions/var_dump/
// original by: Brett Zamir (http://brett-zamir.me)
// improved by: Zahlii
// improved by: Brett Zamir (http://brett-zamir.me)
// depends on: echo
// note: For returning a string, use var_export() with the second argument set to true
// test: skip
// example 1: var_dump(1);
// returns 1: 'int(1)'
var output = '',
pad_char = ' ',
pad_val = 4,
lgth = 0,
i = 0;
var _getFuncName = function(fn) {
var name = (/\W*function\s+([\w\$]+)\s*\(/)
.exec(fn);
if (!name) {
return '(Anonymous)';
}
return name[1];
};
var _repeat_char = function(len, pad_char) {
var str = '';
for (var i = 0; i < len; i++) {
str += pad_char;
}
return str;
};
var _getInnerVal = function(val, thick_pad) {
var ret = '';
if (val === null) {
ret = 'NULL';
} else if (typeof val === 'boolean') {
ret = 'bool(' + val + ')';
} else if (typeof val === 'string') {
ret = 'string(' + val.length + ') "' + val + '"';
} else if (typeof val === 'number') {
if (parseFloat(val) == parseInt(val, 10)) {
ret = 'int(' + val + ')';
} else {
ret = 'float(' + val + ')';
}
}
// The remaining are not PHP behavior because these values only exist in this exact form in JavaScript
else if (typeof val === 'undefined') {
ret = 'undefined';
} else if (typeof val === 'function') {
var funcLines = val.toString()
.split('\n');
ret = '';
for (var i = 0, fll = funcLines.length; i < fll; i++) {
ret += (i !== 0 ? '\n' + thick_pad : '') + funcLines[i];
}
} else if (val instanceof Date) {
ret = 'Date(' + val + ')';
} else if (val instanceof RegExp) {
ret = 'RegExp(' + val + ')';
} else if (val.nodeName) {
// Different than PHP's DOMElement
switch (val.nodeType) {
case 1:
if (typeof val.namespaceURI === 'undefined' || val.namespaceURI === 'http://www.w3.org/1999/xhtml') {
// Undefined namespace could be plain XML, but namespaceURI not widely supported
ret = 'HTMLElement("' + val.nodeName + '")';
} else {
ret = 'XML Element("' + val.nodeName + '")';
}
break;
case 2:
ret = 'ATTRIBUTE_NODE(' + val.nodeName + ')';
break;
case 3:
ret = 'TEXT_NODE(' + val.nodeValue + ')';
break;
case 4:
ret = 'CDATA_SECTION_NODE(' + val.nodeValue + ')';
break;
case 5:
ret = 'ENTITY_REFERENCE_NODE';
break;
case 6:
ret = 'ENTITY_NODE';
break;
case 7:
ret = 'PROCESSING_INSTRUCTION_NODE(' + val.nodeName + ':' + val.nodeValue + ')';
break;
case 8:
ret = 'COMMENT_NODE(' + val.nodeValue + ')';
break;
case 9:
ret = 'DOCUMENT_NODE';
break;
case 10:
ret = 'DOCUMENT_TYPE_NODE';
break;
case 11:
ret = 'DOCUMENT_FRAGMENT_NODE';
break;
case 12:
ret = 'NOTATION_NODE';
break;
}
}
return ret;
};
var _formatArray = function(obj, cur_depth, pad_val, pad_char) {
var someProp = '';
if (cur_depth > 0) {
cur_depth++;
}
var base_pad = _repeat_char(pad_val * (cur_depth - 1), pad_char);
var thick_pad = _repeat_char(pad_val * (cur_depth + 1), pad_char);
var str = '';
var val = '';
if (typeof obj === 'object' && obj !== null) {
if (obj.constructor && _getFuncName(obj.constructor) === 'PHPJS_Resource') {
return obj.var_dump();
}
lgth = 0;
for (someProp in obj) {
lgth++;
}
str += 'array(' + lgth + ') {\n';
for (var key in obj) {
var objVal = obj[key];
if (typeof objVal === 'object' && objVal !== null && !(objVal instanceof Date) && !(objVal instanceof RegExp) &&
!
objVal.nodeName) {
str += thick_pad + '[' + key + '] =>\n' + thick_pad + _formatArray(objVal, cur_depth + 1, pad_val,
pad_char);
} else {
val = _getInnerVal(objVal, thick_pad);
str += thick_pad + '[' + key + '] =>\n' + thick_pad + val + '\n';
}
}
str += base_pad + '}\n';
} else {
str = _getInnerVal(obj, thick_pad);
}
return str;
};
output = _formatArray(arguments[0], 0, pad_val, pad_char);
for (i = 1; i < arguments.length; i++) {
output += '\n' + _formatArray(arguments[i], 0, pad_val, pad_char);
}
this.echo(output);
}
print_r()
in JavaScriptHere is the print_r()
function:
http://phpjs.org/functions/print_r/
It depends on echo()
too.
function print_r(array, return_val) {
// discuss at: http://phpjs.org/functions/print_r/
// original by: Michael White (http://getsprink.com)
// improved by: Ben Bryan
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// input by: Brett Zamir (http://brett-zamir.me)
// depends on: echo
// example 1: print_r(1, true);
// returns 1: 1
var output = '',
pad_char = ' ',
pad_val = 4,
d = this.window.document,
getFuncName = function(fn) {
var name = (/\W*function\s+([\w\$]+)\s*\(/)
.exec(fn);
if (!name) {
return '(Anonymous)';
}
return name[1];
};
repeat_char = function(len, pad_char) {
var str = '';
for (var i = 0; i < len; i++) {
str += pad_char;
}
return str;
};
formatArray = function(obj, cur_depth, pad_val, pad_char) {
if (cur_depth > 0) {
cur_depth++;
}
var base_pad = repeat_char(pad_val * cur_depth, pad_char);
var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char);
var str = '';
if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !==
'PHPJS_Resource') {
str += 'Array\n' + base_pad + '(\n';
for (var key in obj) {
if (Object.prototype.toString.call(obj[key]) === '[object Array]') {
str += thick_pad + '[' + key + '] => ' + formatArray(obj[key], cur_depth + 1, pad_val, pad_char);
} else {
str += thick_pad + '[' + key + '] => ' + obj[key] + '\n';
}
}
str += base_pad + ')\n';
} else if (obj === null || obj === undefined) {
str = '';
} else {
// for our "resource" class
str = obj.toString();
}
return str;
};
output = formatArray(array, 0, pad_val, pad_char);
if (return_val !== true) {
if (d.body) {
this.echo(output);
} else {
try {
// We're in XUL, so appending as plain text won't work; trigger an error out of XUL
d = XULDocument;
this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
} catch (e) {
// Outputting as plain text may work in some plain XML
this.echo(output);
}
}
return true;
}
return output;
}
var_export()
in JavaScriptYou may also find the var_export()
alternative useful, which also depends on echo()
:
http://phpjs.org/functions/var_export/
function var_export(mixed_expression, bool_return) {
// discuss at: http://phpjs.org/functions/var_export/
// original by: Philip Peterson
// improved by: johnrembo
// improved by: Brett Zamir (http://brett-zamir.me)
// input by: Brian Tafoya (http://www.premasolutions.com/)
// input by: Hans Henrik (http://hanshenrik.tk/)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// depends on: echo
// example 1: var_export(null);
// returns 1: null
// example 2: var_export({0: 'Kevin', 1: 'van', 2: 'Zonneveld'}, true);
// returns 2: "array (\n 0 => 'Kevin',\n 1 => 'van',\n 2 => 'Zonneveld'\n)"
// example 3: data = 'Kevin';
// example 3: var_export(data, true);
// returns 3: "'Kevin'"
var retstr = '',
iret = '',
value,
cnt = 0,
x = [],
i = 0,
funcParts = [],
// We use the last argument (not part of PHP) to pass in
// our indentation level
idtLevel = arguments[2] || 2,
innerIndent = '',
outerIndent = '',
getFuncName = function(fn) {
var name = (/\W*function\s+([\w\$]+)\s*\(/)
.exec(fn);
if (!name) {
return '(Anonymous)';
}
return name[1];
};
_makeIndent = function(idtLevel) {
return (new Array(idtLevel + 1))
.join(' ');
};
__getType = function(inp) {
var i = 0,
match, types, cons, type = typeof inp;
if (type === 'object' && (inp && inp.constructor) &&
getFuncName(inp.constructor) === 'PHPJS_Resource') {
return 'resource';
}
if (type === 'function') {
return 'function';
}
if (type === 'object' && !inp) {
// Should this be just null?
return 'null';
}
if (type === 'object') {
if (!inp.constructor) {
return 'object';
}
cons = inp.constructor.toString();
match = cons.match(/(\w+)\(/);
if (match) {
cons = match[1].toLowerCase();
}
types = ['boolean', 'number', 'string', 'array'];
for (i = 0; i < types.length; i++) {
if (cons === types[i]) {
type = types[i];
break;
}
}
}
return type;
};
type = __getType(mixed_expression);
if (type === null) {
retstr = 'NULL';
} else if (type === 'array' || type === 'object') {
outerIndent = _makeIndent(idtLevel - 2);
innerIndent = _makeIndent(idtLevel);
for (i in mixed_expression) {
value = this.var_export(mixed_expression[i], 1, idtLevel + 2);
value = typeof value === 'string' ? value.replace(/</g, '<')
.
replace(/>/g, '>'): value;
x[cnt++] = innerIndent + i + ' => ' +
(__getType(mixed_expression[i]) === 'array' ?
'\n' : '') + value;
}
iret = x.join(',\n');
retstr = outerIndent + 'array (\n' + iret + '\n' + outerIndent + ')';
} else if (type === 'function') {
funcParts = mixed_expression.toString()
.
match(/function .*?\((.*?)\) \{([\s\S]*)\}/);
// For lambda functions, var_export() outputs such as the following:
// '\000lambda_1'. Since it will probably not be a common use to
// expect this (unhelpful) form, we'll use another PHP-exportable
// construct, create_function() (though dollar signs must be on the
// variables in JavaScript); if using instead in JavaScript and you
// are using the namespaced version, note that create_function() will
// not be available as a global
retstr = "create_function ('" + funcParts[1] + "', '" +
funcParts[2].replace(new RegExp("'", 'g'), "\\'") + "')";
} else if (type === 'resource') {
// Resources treated as null for var_export
retstr = 'NULL';
} else {
retstr = typeof mixed_expression !== 'string' ? mixed_expression :
"'" + mixed_expression.replace(/(["'])/g, '\\$1')
.
replace(/\0/g, '\\0') + "'";
}
if (!bool_return) {
this.echo(retstr);
return null;
}
return retstr;
}
echo()
in JavaScripthttp://phpjs.org/functions/echo/
function echo() {
// discuss at: http://phpjs.org/functions/echo/
// original by: Philip Peterson
// improved by: echo is bad
// improved by: Nate
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Brett Zamir (http://brett-zamir.me)
// improved by: Brett Zamir (http://brett-zamir.me)
// revised by: Der Simon (http://innerdom.sourceforge.net/)
// bugfixed by: Eugene Bulkin (http://doubleaw.com/)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: Brett Zamir (http://brett-zamir.me)
// bugfixed by: EdorFaus
// input by: JB
// note: If browsers start to support DOM Level 3 Load and Save (parsing/serializing),
// note: we wouldn't need any such long code (even most of the code below). See
// note: link below for a cross-browser implementation in JavaScript. HTML5 might
// note: possibly support DOMParser, but that is not presently a standard.
// note: Although innerHTML is widely used and may become standard as of HTML5, it is also not ideal for
// note: use with a temporary holder before appending to the DOM (as is our last resort below),
// note: since it may not work in an XML context
// note: Using innerHTML to directly add to the BODY is very dangerous because it will
// note: break all pre-existing references to HTMLElements.
// example 1: echo('<div><p>abc</p><p>abc</p></div>');
// returns 1: undefined
var isNode = typeof module !== 'undefined' && module.exports && typeof global !== "undefined" && {}.toString.call(
global) == '[object global]';
if (isNode) {
var args = Array.prototype.slice.call(arguments);
return console.log(args.join(' '));
}
var arg = '';
var argc = arguments.length;
var argv = arguments;
var i = 0;
var holder, win = this.window;
var d = win.document;
var ns_xhtml = 'http://www.w3.org/1999/xhtml';
// If we're in a XUL context
var ns_xul = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
var stringToDOM = function(str, parent, ns, container) {
var extraNSs = '';
if (ns === ns_xul) {
extraNSs = ' xmlns:html="' + ns_xhtml + '"';
}
var stringContainer = '<' + container + ' xmlns="' + ns + '"' + extraNSs + '>' + str + '</' + container + '>';
var dils = win.DOMImplementationLS;
var dp = win.DOMParser;
var ax = win.ActiveXObject;
if (dils && dils.createLSInput && dils.createLSParser) {
// Follows the DOM 3 Load and Save standard, but not
// implemented in browsers at present; HTML5 is to standardize on innerHTML, but not for XML (though
// possibly will also standardize with DOMParser); in the meantime, to ensure fullest browser support, could
// attach http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.js (see http://svn2.assembla.com/svn/brettz9/DOMToString/DOM3.xhtml for a simple test file)
var lsInput = dils.createLSInput();
// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
lsInput.stringData = stringContainer;
// synchronous, no schema type
var lsParser = dils.createLSParser(1, null);
return lsParser.parse(lsInput)
.firstChild;
} else if (dp) {
// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
try {
var fc = new dp()
.parseFromString(stringContainer, 'text/xml');
if (fc && fc.documentElement && fc.documentElement.localName !== 'parsererror' && fc.documentElement.namespaceURI !==
'http://www.mozilla.org/newlayout/xml/parsererror.xml') {
return fc.documentElement.firstChild;
}
// If there's a parsing error, we just continue on
} catch (e) {
// If there's a parsing error, we just continue on
}
} else if (ax) {
// We don't bother with a holder in Explorer as it doesn't support namespaces
var axo = new ax('MSXML2.DOMDocument');
axo.loadXML(str);
return axo.documentElement;
}
/*else if (win.XMLHttpRequest) {
// Supposed to work in older Safari
var req = new win.XMLHttpRequest;
req.open('GET', 'data:application/xml;charset=utf-8,'+encodeURIComponent(str), false);
if (req.overrideMimeType) {
req.overrideMimeType('application/xml');
}
req.send(null);
return req.responseXML;
}*/
// Document fragment did not work with innerHTML, so we create a temporary element holder
// If we're in XHTML, we'll try to allow the XHTML namespace to be available by default
//if (d.createElementNS && (d.contentType && d.contentType !== 'text/html')) {
// Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways)
if (d.createElementNS && // Browser supports the method
(d.documentElement.namespaceURI || // We can use if the document is using a namespace
d.documentElement.nodeName.toLowerCase() !== 'html' || // We know it's not HTML4 or less, if the tag is not HTML (even if the root namespace is null)
(d.contentType && d.contentType !== 'text/html') // We know it's not regular HTML4 or less if this is Mozilla (only browser supporting the attribute) and the content type is something other than text/html; other HTML5 roots (like svg) still have a namespace
)) {
// Don't create namespaced elements if we're being served as HTML (currently only Mozilla supports this detection in true XHTML-supporting browsers, but Safari and Opera should work with the above DOMParser anyways, and IE doesn't support createElementNS anyways); last test is for the sake of being in a pure XML document
holder = d.createElementNS(ns, container);
} else {
// Document fragment did not work with innerHTML
holder = d.createElement(container);
}
holder.innerHTML = str;
while (holder.firstChild) {
parent.appendChild(holder.firstChild);
}
return false;
// throw 'Your browser does not support DOM parsing as required by echo()';
};
var ieFix = function(node) {
if (node.nodeType === 1) {
var newNode = d.createElement(node.nodeName);
var i, len;
if (node.attributes && node.attributes.length > 0) {
for (i = 0, len = node.attributes.length; i < len; i++) {
newNode.setAttribute(node.attributes[i].nodeName, node.getAttribute(node.attributes[i].nodeName));
}
}
if (node.childNodes && node.childNodes.length > 0) {
for (i = 0, len = node.childNodes.length; i < len; i++) {
newNode.appendChild(ieFix(node.childNodes[i]));
}
}
return newNode;
} else {
return d.createTextNode(node.nodeValue);
}
};
var replacer = function(s, m1, m2) {
// We assume for now that embedded variables do not have dollar sign; to add a dollar sign, you currently must use {$$var} (We might change this, however.)
// Doesn't cover all cases yet: see http://php.net/manual/en/language.types.string.php#language.types.string.syntax.double
if (m1 !== '\\') {
return m1 + eval(m2);
} else {
return s;
}
};
this.php_js = this.php_js || {};
var phpjs = this.php_js;
var ini = phpjs.ini;
var obs = phpjs.obs;
for (i = 0; i < argc; i++) {
arg = argv[i];
if (ini && ini['phpjs.echo_embedded_vars']) {
arg = arg.replace(/(.?)\{?\$(\w*?\}|\w*)/g, replacer);
}
if (!phpjs.flushing && obs && obs.length) {
// If flushing we output, but otherwise presence of a buffer means caching output
obs[obs.length - 1].buffer += arg;
continue;
}
if (d.appendChild) {
if (d.body) {
if (win.navigator.appName === 'Microsoft Internet Explorer') {
// We unfortunately cannot use feature detection, since this is an IE bug with cloneNode nodes being appended
d.body.appendChild(stringToDOM(ieFix(arg)));
} else {
var unappendedLeft = stringToDOM(arg, d.body, ns_xhtml, 'div')
.cloneNode(true); // We will not actually append the div tag (just using for providing XHTML namespace by default)
if (unappendedLeft) {
d.body.appendChild(unappendedLeft);
}
}
} else {
// We will not actually append the description tag (just using for providing XUL namespace by default)
d.documentElement.appendChild(stringToDOM(arg, d.documentElement, ns_xul, 'description'));
}
} else if (d.write) {
d.write(arg);
} else {
console.log(arg);
}
}
}
I'm surprised there hasn't been a functional solution suggested that allows you to set the length in one line. The following is based on UnderscoreJS:
var test = _.map(_.range(4), function () { return undefined; });
console.log(test.length);
For reasons mentioned above, I'd avoid doing this unless I wanted to initialize the array to a specific value. It's interesting to note there are other libraries that implement range including Lo-dash and Lazy, which may have different performance characteristics.
Markup:
<canvas id="myCanvas" width="300" height="150"></canvas>
Script (with few different options):
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.font = 'italic 18px Arial';
ctx.textAlign = 'center';
ctx. textBaseline = 'middle';
ctx.fillStyle = 'red'; // a color name or by using rgb/rgba/hex values
ctx.fillText('Hello World!', 150, 50); // text and position
</script>
Check out the MDN documentation and this JSFiddle example.
Rails core team decided to revert this change for a while, in order to discuss it in more detail. See this comment and this PR for more info.
I am leaving my answer only for educational purposes.
Rails 6.1 added a new 'syntax' for comparison operators in where
conditions, for example:
Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)
So your query can be rewritten as follows:
User.where('id >': 200)
Here is a link to PR where you can find more examples.
document.getElementById("idframe").contentWindow.document.getElementById("idelement").value;
background-image
takes multiple values.
so a combination of just 1 color linear-gradient and css blend modes
will do the trick.
.testclass {
background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
background-blend-mode: overlay;
}
note that there is no support on IE/Edge for CSS blend-modes at all.
Your HttpServletRequest
object has a getParameter(String paramName)
method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.
I have the same problem that you describe although I'm building up my LatLngBounds as proposed by above. The problem is that things are async and calling map.fitBounds()
at the wrong time may leave you with a result like in the Q.
The best way I found is to place the call in an idle handler like this:
google.maps.event.addListenerOnce(map, 'idle', function() {
map.fitBounds(markerBounds);
});
Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py
to run the script. So, for a script named test.py
containing
name = raw_input("Enter your name: ")
print "Hello, " + name
The PowerShell session would be
PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>
Actually the best way to sheared you app between users , google (firebase) proved new technology Firebase Dynamic Link Through several lines you can make it this is documentation https://firebase.google.com/docs/dynamic-links/ and the code is
Uri dynamicLinkUri = dynamicLink.getUri();
Task<ShortDynamicLink> shortLinkTask = FirebaseDynamicLinks.getInstance().createDynamicLink()
.setLink(Uri.parse("https://www.google.jo/"))
.setDynamicLinkDomain("rw4r7.app.goo.gl")
.buildShortDynamicLink()
.addOnCompleteListener(this, new OnCompleteListener<ShortDynamicLink>() {
@Override
public void onComplete(@NonNull Task<ShortDynamicLink> task) {
if (task.isSuccessful()) {
// Short link created
Uri shortLink = task.getResult().getShortLink();
Uri flowchartLink = task.getResult().getPreviewLink();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, shortLink.toString());
intent.setType("text/plain");
startActivity(intent);
} else {
// Error
// ...
}
}
});
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
More General Case: Return N points from each end of list
The answers work for the specific first and last, but some, like myself, may be looking for a solution that can be applied to a more general case in which you can return the top N points from either side of the list (say you have a sorted list and only want the 5 highest or lowest), i came up with the following solution:
In [1]
def GetWings(inlist,winglen):
if len(inlist)<=winglen*2:
outlist=inlist
else:
outlist=list(inlist[:winglen])
outlist.extend(list(inlist[-winglen:]))
return outlist
and an example to return bottom and top 3 numbers from list 1-10:
In [2]
GetWings([1,2,3,4,5,6,7,8,9,10],3)
#Out[2]
#[1, 2, 3, 8, 9, 10]
If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.
onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');"
onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"
Just put two stops -- one onmouseover and one onmouseout.
I wrap the input[type=file]
in a label tag, then style the label
to your liking, and hide the input
.
<label class="btn btn-default fileLabel" data-toggle="tooltip" data-placement="top" title="Upload">
<input type="file">
<span><i class="fa fa-upload"></i></span>
</label>
<style>
.fileLabel input[type="file"] {
position: fixed;
top: -1000px;
}
</style>
Purely CSS Solution.
As others have noted the call to .remove()
is asynchronous. We should all be aware nothing happens 'instantly', even if it is at the speed of light.
What you mean by 'instantly' is that the next line of code should be able to execute after the call to .remove()
. With asynchronous operations the next line may be when the data has been removed, it may not - it is totally down to chance and the amount of time that has elapsed.
.remove()
takes one parameter a callback function to help deal with this situation to perform operations after we know that the operation has been completed (with or without an error). .push()
takes two params, a value and a callback just like .remove()
.
Here is your example code with modifications:
ref = new Firebase("myfirebase.com")
ref.push({key:val}, function(error){
//do stuff after push completed
});
// deletes all data pushed so far
ref.remove(function(error){
//do stuff after removal
});
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
To bring more prominence to the useful comment by @johanvdw:
If you want to ensure your your javac file path is always know when cygwin starts, you may edit your .bash_profile
file. In this example you would add export PATH=$PATH:"/cygdrive/C/Program Files/Java/jdk1.6.0_23/bin/"
somewhere in the file.
When Cygwin starts, it'll search directories in PATH and this one for executable files to run.
without jQuery you can use
document.getElementById('text_input').setAttribute('maxlength',200);
From a user experience stand-point, you don't want a major action to be done passively.
Something major like a window close should be the result of an action by the user.
SQL Server 2012:
right-click on the DB > Properties > Options > [Scroll down] State > RestrictAccess > select Multi_user
and click OK.
Voila!
FileChannel.lock is probably what you want.
try (
FileInputStream in = new FileInputStream(file);
java.nio.channels.FileLock lock = in.getChannel().lock();
Reader reader = new InputStreamReader(in, charset)
) {
...
}
(Disclaimer: Code not compiled and certainly not tested.)
Note the section entitled "platform dependencies" in the API doc for FileLock.
There is also this useful function on String: components(separatedBy: String)
let string = "1;2;3"
let array = string.components(separatedBy: ";")
print(array) // returns ["1", "2", "3"]
Works well to deal with strings separated by a character like ";" or even "\n"
The simples way is to use 'to' property:
<Link to="chart" target="_blank" to="http://link2external.page.com" >Test</Link>
I use Eclipse Java EE edition
Create a "Dynamic Web Project"
Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.
When I deploy I export the project to a war file.
This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!
Once an Object is in array format you can use array_merge and convert back to Object if you need to.
abstract class Util {
public static function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__METHOD__, $d) : $d;
}
public static function array_to_object($d) {
return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
}
}
Procedural way
function object_to_array($d) {
if (is_object($d))
$d = get_object_vars($d);
return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}
function array_to_object($d) {
return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}
All credit goes to: Jason Oakley
Here is simple Scala version in Linear O(n) time:
def getProductEff(in:Seq[Int]):Seq[Int] = { //create a list which has product of every element to the left of this element val fromLeft = in.foldLeft((1, Seq.empty[Int]))((ac, i) => (i * ac._1, ac._2 :+ ac._1))._2 //create a list which has product of every element to the right of this element, which is the same as the previous step but in reverse val fromRight = in.reverse.foldLeft((1,Seq.empty[Int]))((ac,i) => (i * ac._1,ac._2 :+ ac._1))._2.reverse //merge the two list by product at index in.indices.map(i => fromLeft(i) * fromRight(i)) }
This works because essentially the answer is an array which has product of all elements to the left and to the right.
btn1.setId(1);
addRule()
, check
out the android java docs for this
LayoutParams
object.Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).
When they return look them up by the remember me token and make sure the UserId matches.
1-firstly, drop the foreign key constraint after that drop the tables.
2-you can drop all foreign key via executing the following query:
DECLARE @SQL varchar(4000)=''
SELECT @SQL =
@SQL + 'ALTER TABLE ' + s.name+'.'+t.name + ' DROP CONSTRAINT [' + RTRIM(f.name) +'];' + CHAR(13)
FROM sys.Tables t
INNER JOIN sys.foreign_keys f ON f.parent_object_id = t.object_id
INNER JOIN sys.schemas s ON s.schema_id = f.schema_id
--EXEC (@SQL)
PRINT @SQL
if you execute the printed results @SQL, the foreign keys will be dropped.
I think, this is the simplest technique to beautify the json data,
String indented = (new JSONObject(Response)).toString(4);
where Response is a String.
Simply pass the 4(indentSpaces) in toString()
method.
Note: It works fine in the android without any library. But in java you have to use the org.json library.
Float them both the same way and add the margin of 40px. If you have 2 elements floating opposite ways you will have much less control and the containing element will determine how far apart they are.
#left{
float: left;
margin-right: 40px;
}
#right{
float: left;
}
For a complete DELETE rows and reset the IDENTITY count, I use this (SQL Server 2008 R2)
USE mydb
-- ##################################################################################################################
-- DANGEROUS!!!! USE WITH CARE
-- ##################################################################################################################
DECLARE
db_cursor CURSOR FOR
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_CATALOG = 'mydb'
DECLARE @tblname VARCHAR(50)
SET @tblname = ''
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @tblname
WHILE @@FETCH_STATUS = 0
BEGIN
IF CHARINDEX('mycommonwordforalltablesIwanttodothisto', @tblname) > 0
BEGIN
EXEC('DELETE FROM ' + @tblname)
DBCC CHECKIDENT (@tblname, RESEED, 0)
END
FETCH NEXT FROM db_cursor INTO @tblname
END
CLOSE db_cursor
DEALLOCATE db_cursor
GO
The answer has been given by Faisal Khurshid and Michael_B already.
This is just an attempt to make a possible solution more obvious.
For IE11 and below you need to enable grid's older specification in the parent div e.g. body or like here "grid" like so:
.grid-parent{display:-ms-grid;}
then define the amount and width of the columns and rows like e.g. so:
.grid-parent{
-ms-grid-columns: 1fr 3fr;
-ms-grid-rows: 4fr;
}
finally you need to explicitly tell the browser where your element (item) should be placed in e.g. like so:
.grid-item-1{
-ms-grid-column: 1;
-ms-grid-row: 1;
}
.grid-item-2{
-ms-grid-column: 2;
-ms-grid-row: 1;
}
There is a subtle issue here that is a bit of a gotcha.
The toString()
method has a base implementation in Object
. CharSequence
is an interface; and although the toString()
method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence
toString()
method's javadoc puts on the toString()
method; ie that it should return a string containing the characters in the order returned by charAt()
.
Your IDE won't even help you out by reminding that you that you probably should override toString()
. For example, in intellij, this is what you'll see if you create a new CharSequence
implementation: http://puu.sh/2w1RJ. Note the absence of toString()
.
If you rely on toString()
on an arbitrary CharSequence
, it should work provided the CharSequence
implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder
and append()
, like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,
rdd = df.rdd.flatMap(list)
or
rdd = df.rdd.flatmap(lambda x: list(x))
Quickest (drops and creates all tables including data):
./manage.py reset appname | ./manage.py dbshell
Caution:
you can try with System.Web.Script.Serialization.JavaScriptSerializer
:
var json = new JavaScriptSerializer();
var data = json.Deserialize<Dictionary<string, Dictionary<string, string>>[]>(jsonStr);
I'm adding this as I haven't seen it in any of the other answers and it might be useful for someone struggling with something similar. The globals()
function returns a mutable global symbol dictionary where you can "magically" make data available for the rest of your code.
For example:
from pickle import load
def loaditem(name):
with open(r"C:\pickle\file\location"+"\{}.dat".format(name), "rb") as openfile:
globals()[name] = load(openfile)
return True
and
from pickle import dump
def dumpfile(name):
with open(name+".dat", "wb") as outfile:
dump(globals()[name], outfile)
return True
Will just let you dump/load variables out of and into the global namespace. Super convenient, no muss, no fuss. Pretty sure it's Python 3 only.
Google will eventually block your IP when you exceed a certain amount of requests.
A bit safer version than using xargs, also not recursive:
ls -p | grep -v '/$' | grep '\.pdf$' | while read file; do rm "$file"; done
Filtering our directories here is a bit unnecessary as 'rm' won't delete it anyway, and it can be removed for simplicity, but why run something that will definitely return error?
Batch files don't work that way. They don't just "type" everything - they run system commands, in this case ftp
, wait for them to return, and run the next command... so in this case, the interpreter is simply waiting for ftp
to exit.
If you must use the ftp
command, then prepare a script file (for example, commands.txt
and run ftp -s:commands.txt
.
But using cURL, or a PHP/Perl/Python/whatever script may be a better idea.
I did it many times. To bypass the JavaScript warning, I add two parens:
if ((result = get_something())) { }
You should avoid it, if you really want to use it, write a comment above it saying what you are doing.
There are 3 authentication protocols that can be used to perform authentication between Java and Active Directory on Linux or any other platform (and these are not just specific to HTTP services):
Kerberos - Kerberos provides Single Sign-On (SSO) and delegation but web servers also need SPNEGO support to accept SSO through IE.
NTLM - NTLM supports SSO through IE (and other browsers if they are properly configured).
LDAP - An LDAP bind can be used to simply validate an account name and password.
There's also something called "ADFS" which provides SSO for websites using SAML that calls into the Windows SSP so in practice it's basically a roundabout way of using one of the other above protocols.
Each protocol has it's advantages but as a rule of thumb, for maximum compatibility you should generally try to "do as Windows does". So what does Windows do?
First, authentication between two Windows machines favors Kerberos because servers do not need to communicate with the DC and clients can cache Kerberos tickets which reduces load on the DCs (and because Kerberos supports delegation).
But if the authenticating parties do not both have domain accounts or if the client cannot communicate with the DC, NTLM is required. So Kerberos and NTLM are not mutually exclusive and NTLM is not obsoleted by Kerberos. In fact in some ways NTLM is better than Kerberos. Note that when mentioning Kerberos and NTLM in the same breath I have to also mention SPENGO and Integrated Windows Authentication (IWA). IWA is a simple term that basically means Kerberos or NTLM or SPNEGO to negotiate Kerberos or NTLM.
Using an LDAP bind as a way to validate credentials is not efficient and requires SSL. But until recently implementing Kerberos and NTLM have been difficult so using LDAP as a make-shift authentication service has persisted. But at this point it should generally be avoided. LDAP is a directory of information and not an authentication service. Use it for it's intended purpose.
So how do you implement Kerberos or NTLM in Java and in the context of web applications in particular?
There are a number of big companies like Quest Software and Centrify that have solutions that specifically mention Java. I can't really comment on these as they are company-wide "identity management solutions" so, from looking the marketing spin on their website, it's hard to tell exactly what protocols are being used and how. You would need to contact them for the details.
Implementing Kerberos in Java is not terribly hard as the standard Java libraries support Kerberos through the org.ietf.gssapi classes. However, until recently there's been a major hurdle - IE doesn't send raw Kerberos tokens, it sends SPNEGO tokens. But with Java 6, SPNEGO has been implemented. In theory you should be able to write some GSSAPI code that can authenticate IE clients. But I haven't tried it. The Sun implementation of Kerberos has been a comedy of errors over the years so based on Sun's track record in this area I wouldn't make any promises about their SPENGO implementation until you have that bird in hand.
For NTLM, there is a Free OSS project called JCIFS that has an NTLM HTTP authentication Servlet Filter. However it uses a man-in-the-middle method to validate the credentials with an SMB server that does not work with NTLMv2 (which is slowly becoming a required domain security policy). For that reason and others, the HTTP Filter part of JCIFS is scheduled to be removed. Note that there are number of spin-offs that use JCIFS to implement the same technique. So if you see other projects that claim to support NTLM SSO, check the fine print.
The only correct way to validate NTLM credentials with Active Directory is using the NetrLogonSamLogon DCERPC call over NETLOGON with Secure Channel. Does such a thing exist in Java? Yes. Here it is:
http://www.ioplex.com/jespa.html
Jespa is a 100% Java NTLM implementation that supports NTLMv2, NTLMv1, full integrity and confidentiality options and the aforementioned NETLOGON credential validation. And it includes an HTTP SSO Filter, a JAAS LoginModule, HTTP client, SASL client and server (with JNDI binding), generic "security provider" for creating custom NTLM services and more.
Mike
var s = ",'first string','more','even more'";
var array = s.split(',').slice(1);
That's assuming the string you begin with is in fact a String, like you said, and not an Array of strings.
There are 2 different things.
Try using cmake itself. In the build directory, run:
cmake --build .
The expression between the <%= %> is evaluated before the c:if tag is evaluated. So, supposing that |request.isUserInRole| returns |true|, your example would be evaluated to this first:
<c:if test="true">
<li>user</li>
</c:if>
and then the c:if tag would be executed.
Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.
It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.
I had similar problem with regex = "?"
. It happens for all special characters that have some meaning in a regex. So you need to have "\\"
as a prefix to your regex.
String [] separado = line.split("\\*");
G++ does support C++14 both via -std=c++14
and -std=c++1y
. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.
I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?
It installs the latest version available in the Ubuntu repositories, not the latest version that exists.
The latest GCC version is 5.2.
var rates = document.getElementById('rates').value;
The rates element is a div
, so it won't have a value. This is probably where the undefined
is coming from.
The checked
property will tell you whether the element is selected:
if (document.getElementById('r1').checked) {
rate_value = document.getElementById('r1').value;
}
Use re.findall
or re.finditer
instead.
re.findall(pattern, string)
returns a list of matching strings.
re.finditer(pattern, string)
returns an iterator over MatchObject
objects.
Example:
re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']
[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']
Starting in version 0.7.9 you can use the filter operator .isnot
instead of comparing constraints, like this:
query.filter(User.name.isnot(None))
This method is only necessary if pep8 is a concern.
source: sqlalchemy documentation
Assuming you've done a successful Product > Archive then, from Organizer (Shift Apple 2) click Archives.
Select your Archive. Select Share. In the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution.
Click Next, enter an App name and click Save.
Full gory details with screenshots are here: Xcode4UserGuide
Latest stuff with getMapAsync
instead of the deprecated one.
1. check manifest for
<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxxxxxxxxxxxxxxxxxxxxxx"/>
You can get the API Key for your app by registering your app at Google Cloud Console
. Register your app as Native Android App
2. in your fragment layout .xml add FrameLayout(not fragment):
<FrameLayout
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_weight="2"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="@+id/mapwhere" />
or whatever height you want
3. In onCreateView in your fragment
private SupportMapFragment mSupportMapFragment;
mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
if (mSupportMapFragment == null) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
mSupportMapFragment = SupportMapFragment.newInstance();
fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
}
if (mSupportMapFragment != null)
{
mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
@Override public void onMapReady(GoogleMap googleMap) {
if (googleMap != null) {
googleMap.getUiSettings().setAllGesturesEnabled(true);
-> marker_latlng // MAKE THIS WHATEVER YOU WANT
CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
googleMap.moveCamera(cameraUpdate);
}
}
});
simple is the best and works in every version.
if a>10:
value="b"
else:
value="c"
Oracle SQL Developer doesn't support connections to PostgreSQL. Use pgAdmin to connect to PostgreSQL instead, you can get it from the following URL http://www.pgadmin.org/download/windows.php
I had to avoid javascript, but could go with server side code.
so I generated an id, created a style block, generated the link with that id. Yes its valid HTML.
a {_x000D_
text-decoration: none;_x000D_
color: blue; _x000D_
}_x000D_
_x000D_
a:hover {_x000D_
color: blue;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
a[data-hover="rnd-id-123"] { color: green; } _x000D_
a[data-hover="rnd-id-123"]:hover { color: red; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-123">some link 1</a>_x000D_
_x000D_
<br>_x000D_
_x000D_
<!-- some code in the interpreter you use, to generate the data-hover id -->_x000D_
<style>_x000D_
a[data-hover="rnd-id-456"] { color: purple; }_x000D_
a[data-hover="rnd-id-456"]:hover { color: orange; }_x000D_
</style>_x000D_
<a data-hover="rnd-id-456">some link 2</a>
_x000D_
I had a similar problem of Eclipse compiling my code just fine but Maven failed when compiling the tests every time despite the fact JUnit was in my list of dependencies and the tests were in /src/test/java/.
In my case, I had the wrong version of JUnit in my list of dependencies. I wrote JUnit4 tests (with annotations) but had JUnit 3.8.x as my dependency. Between version 3.8.x and 4 of JUnit they changed the package name from junit.framework to org.junit which is why Maven still breaks compiling using a JUnit jar.
I'm still not entirely sure why Eclipse successfully compiled. It must have its own copy of JUnit4 somewhere in the classpath. Hope this alternative solution is useful to people. I reached this solution after following Arthur's link above.
Koala_dev's answer will work, but in case you are wondering this is the reason why it works:
.
q.html, body { <--applying this css block to everything in the
html code.
q.max-width: 100%; <--all items created must not exceed 100% of the
users screen size. (no items can be off the page
requiring scroll)
q.overflow-x: hidden; <--anything that occurs off the X axis of the
page is hidden, so that you wont see it going
off the page.
.
All hex value from 100% to 0% alpha, You can set any color with alpha values mentioned below. e.g #FAFFFFFF(ARRGGBB)
100% — FF
99% — FC
98% — FA
97% — F7
96% — F5
95% — F2
94% — F0
93% — ED
92% — EB
91% — E8
90% — E6
89% — E3
88% — E0
87% — DE
86% — DB
85% — D9
84% — D6
83% — D4
82% — D1
81% — CF
80% — CC
79% — C9
78% — C7
77% — C4
76% — C2
75% — BF
74% — BD
73% — BA
72% — B8
71% — B5
70% — B3
69% — B0
68% — AD
67% — AB
66% — A8
65% — A6
64% — A3
63% — A1
62% — 9E
61% — 9C
60% — 99
59% — 96
58% — 94
57% — 91
56% — 8F
55% — 8C
54% — 8A
53% — 87
52% — 85
51% — 82
50% — 80
49% — 7D
48% — 7A
47% — 78
46% — 75
45% — 73
44% — 70
43% — 6E
42% — 6B
41% — 69
40% — 66
39% — 63
38% — 61
37% — 5E
36% — 5C
35% — 59
34% — 57
33% — 54
32% — 52
31% — 4F
30% — 4D
29% — 4A
28% — 47
27% — 45
26% — 42
25% — 40
24% — 3D
23% — 3B
22% — 38
21% — 36
20% — 33
19% — 30
18% — 2E
17% — 2B
16% — 29
15% — 26
14% — 24
13% — 21
12% — 1F
11% — 1C
10% — 1A
9% — 17
8% — 14
7% — 12
6% — 0F
5% — 0D
4% — 0A
3% — 08
2% — 05
1% — 03
0% — 00
You can get more information with
# Windows
set GIT_CURL_VERBOSE=1
set GIT_TRACE_PACKET=2
# Unix
export GIT_CURL_VERBOSE=1
export GIT_TRACE_PACKET=2
And then try a git push
.
Double-check your proxy settings if you have one.
Note: git 2.8 (March 2016) adds more information on an error 35:
See commit 0054045 (14 Feb 2016) by Shawn Pearce (spearce
).
(Merged by Junio C Hamano -- gitster
-- in commit 97c49af, 24 Feb 2016)
remote-curl
: includecurl_errorstr
on SSL setup failuresFor
curl
error 35 (CURLE_SSL_CONNECT_ERROR
) users need the additional text stored inCURLOPT_ERRORBUFFER
to debug why the connection did not start.
This iscurl_errorstr
inside ofhttp.c
, so include that in the message if it is non-empty.
Also check out the common causes for that message:
If it was working before, and not working today, it is possible the SSL private key has expired on the BitBucket side (see below, reason #3), but that doesn't seem to be the case here (the certificate is valid until 12/03/2014).
Firing off a request like the following, results in the Unknown SSL Protocol error:
curl --sslv2 https://techstacks-tools.appspot.com/
Why? Well, in this case it is because the techstacks tools site does not support SSLv2, thus, generating the curl (35) error.
You could be trying to connect to the site using an ssl cipher that the site is configured to reject.
For example, anonymous ciphers are typically disabled on ssl-encrypted sites that are customer-facing. (Many of us set a blanket rejection policy on any SSL-encrypted web site—regardless of it's purpose.)
The following command string "can" also result in the curl (35) error:
curl --ciphers ADH-RC4-MD5 https://some_web_site.some_domain.com/
Unfortunately, the type of error response you can get from curl depends largely upon the ssl server. On some sites, you'll receive the Unknown SSL Protocol error but on my techstacks-tools site, I get:
curl: (35) error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
Kudos to Google because this particular error is a bit more descriptive than the one my websites at work generate because this at least tells you that a ssl socket was started but because of handshake failures, the socket was never able to complete.
Try connecting to the site with a cipher that the site supports. Not sure which cipher to use? Well, let me introduce my cryptonark ssl cipher tester...
I came across this one earlier today working with an old WebSeAL site.
In IBM GSKit, you can specify how long the private key password is valid. After reaching a certain date, you will still be able to get webseal started and listening on port 443 (or whatever you set your https-port value to) but you will not be able to successfully negotiate an SSL session.
In today's case, the old WebSEAL instance was using long-expired kdb file with a long expired private key password. Once replaced with the correct, more-up-to-date version, everything worked again.
Some ISP's and DNS providers like to intercept your failed DNS queries in order to redirect you to a search engine results-style page offering you alternative URLs or "Did you mean...?" counter-query results.
If you see an error like this:
error:140770FC:SSL routines:SSL23_GET_SERVER_HELLO:unknown protocol,
it could be due to you typing the hostname incorrectly or the hostname is not yet tabled in your DNS. You can verify that with a simple "
host
" or "nslookup
".
Note (August 2015): Git 2.6+ (Q3 2015) will allow to specify the SSL version explicitly:
http
: add support for specifying the SSL version
See commit 01861cb (14 Aug 2015) by Elia Pinto (devzero2000
).
Helped-by: Eric Sunshine (sunshineco
).
(Merged by Junio C Hamano -- gitster
-- in commit ed070a4, 26 Aug 2015)
http.sslVersion
The SSL version to use when negotiating an SSL connection, if you want to force the default.
The available and default version depend on whether libcurl was built against NSS or OpenSSL and the particular configuration of the crypto library in use. Internally this sets the 'CURLOPT_SSL_VERSION
' option; see the libcurl documentation for more details on the format of this option and for the ssl version supported.
Actually the possible values of this option are:
- sslv2
- sslv3
- tlsv1
- tlsv1.0
- tlsv1.1
- tlsv1.2
Can be overridden by the '
GIT_SSL_VERSION
' environment variable.
To force git to use libcurl's default ssl version and ignore any explicithttp.sslversion
option, set 'GIT_SSL_VERSION' to the empty string.
To expand upon dreamlax's example... If you want to send data along with the notification
In posting code:
NSDictionary *userInfo =
[NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
[[NSNotificationCenter defaultCenter] postNotificationName:
@"TestNotification" object:nil userInfo:userInfo];
In observing code:
- (void) receiveTestNotification:(NSNotification *) notification {
NSDictionary *userInfo = notification.userInfo;
MyObject *myObject = [userInfo objectForKey:@"someKey"];
}
private void Log(string s , Color? c = null)
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = c ?? Color.Black;
richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
richTextBox.SelectionColor = Color.Black;
}
A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.
Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.
open terminal
\curl -sSL https://get.rvm.io | bash -s stable
restart terminal then
rvm install ruby-2.4.2
check ruby version it should be 2.4.2
.htaccess
is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert
).htaccess
is in UTF8 Without-BOM, make it WITH BOM.or you can do like
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new Thread( SampleFunction ).Start();
}
void SampleFunction()
{
// Gets executed on a seperate thread and
// doesn't block the UI while sleeping
for ( int i = 0; i < 5; i++ )
{
this.Invoke( ( MethodInvoker )delegate()
{
textBox1.Text += "hi";
} );
Thread.Sleep( 1000 );
}
}
}
It can also be done in some other manner
byte[] pass_byte = Encoding.ASCII.GetBytes("your input value");
and then print result. by using foreach
loop.
It seems that for ignoring files and directories there are two main ways:
.gitignore
.gitignore
file into the root of your repository besides the .git
folder (in Windows, make sure you see the true file extension and then make .gitignore.
(with the point at the end to make an empty file extension))~/.gitignore_global
and running git config --global core.excludesfile ~/.gitignore_global
to add this to your Git configurationNote: files tracked before can be untracked by running git rm --cached filename
Repository exclude - For local files that do not need to be shared, you just add the file pattern or directory to the file .git/info/exclude
. Theses rules are not committed, so they are not seen by other users. More information is here.
To make exceptions in the list of ignored files, see this question.
You probably want to use something like jQuery, which makes JS programming easier.
Something like:
$(document).ready(function(){
// Your code here
});
Would seem to do what you are after.
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
If you are using mysql client you can set up the resultFormat per session e.g.
mysql -h localhost -u root --resutl-format=json
or
mysql -h localhost -u root --vertical
Check out the full list of arguments here.
You can use an async result and a delegate for this. If you read up on the documentation it should make it pretty clear what to do. I can write up some sample code if you like and attach it to this answer.
Action isExcelInteractive = IsExcelInteractive;
private async void btnOk_Click(object sender, EventArgs e)
{
IAsyncResult result = isExcelInteractive.BeginInvoke(ItIsDone, null);
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("YAY");
}
static void IsExcelInteractive(){
while (something_is_false) // do your check here
{
if(something_is_true)
return true;
}
Thread.Sleep(1);
}
void ItIsDone(IAsyncResult result)
{
this.isExcelInteractive.EndInvoke(result);
}
Apologies if this code isn't 100% complete, I don't have Visual Studio on this computer, but hopefully it gets you where you need to get to.
If you need to iterate a queue ... queue isn't the container you need.
Why did you pick a queue?
Why don't you take a container that you can iterate over?
1.if you pick a queue then you say you want to wrap a container into a 'queue' interface: - front - back - push - pop - ...
if you also want to iterate, a queue has an incorrect interface. A queue is an adaptor that provides a restricted subset of the original container
2.The definition of a queue is a FIFO and by definition a FIFO is not iterable
Here is an out of the box future proof date snippet. Firefox defaults to jquery ui datepicker. Otherwise HTML5 datepicker is used. If FF ever support HTML5 type="date" the script will simply be redundant. Dont forget the three dependencies are needed in the head tag.
<script>
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link rel="stylesheet"href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!--Form element uses HTML 5 type="date"-->
<div class="form-group row">
<label for="date" class="col-sm-2 col-form-label"Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="date" id="date" placeholder="date">
</div>
</div>
<!--if the user is using FireFox it
autoconverts type='date' into type='text'. If the type is text the
script below will assign the jquery ui datepicker with options-->
<script>
$(function()
{
var elem = document.createElement('input');
elem.setAttribute('type', 'date');
if ( elem.type === 'text' )
{
$('#date').datepicker();
$( "#date" ).datepicker( "option", "dateFormat", 'yy-mm-dd' );
}
});
You could also use the exclude option in tsconfig.json file like so:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules"
]
}
No. Either use readFile
or readFileSync
(The latter only at startup time).
Or use an existing library like
Alternatively write your config in a js file rather then a json file like
module.exports = {
// json
}
The awnser of @Alireza is totally correct, but you must notice that when using this code
var res = from element in list
group element by element.F1
into groups
select groups.OrderBy(p => p.F2).First();
which is simillar to this code because you ordering the list and then do the grouping so you are getting the first row of groups
var res = (from element in list)
.OrderBy(x => x.F2)
.GroupBy(x => x.F1)
.Select()
Now if you want to do something more complex like take the same grouping result but take the first element of F2 and the last element of F3 or something more custom you can do it by studing the code bellow
var res = (from element in list)
.GroupBy(x => x.F1)
.Select(y => new
{
F1 = y.FirstOrDefault().F1;
F2 = y.First().F2;
F3 = y.Last().F3;
});
So you will get something like
F1 F2 F3
-----------------------------------
Nima 1990 12
John 2001 2
Sara 2010 4
You can use the Django-Truncate library to delete all data of a table without destroying the table structure.
Example:
pip install django-truncate
settings.py
file:INSTALLED_APPS = [
...
'django_truncate',
]
python manage.py truncate --apps app_name --models table_name
I don't know if this is good practice or not, but casting a Context object to an Activity object compiles fine.
Try this: ((Activity) mContext).startActivity(...)
Swift 2 and below
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
And in Swift 3 and higher this would now be written as:
let date = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateString = dateFormatter.string(from: date)
The correct API to use is UIView systemLayoutSizeFittingSize:
, passing either UILayoutFittingCompressedSize
or UILayoutFittingExpandedSize
.
For a normal UIView
using autolayout this should just work as long as your constraints are correct. If you want to use it on a UITableViewCell
(to determine row height for example) then you should call it against your cell contentView
and grab the height.
Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the preferredMaxLayoutWidth
property be set correctly such that the label provides a correct intrinsicContentSize
, which will be used in systemLayoutSizeFittingSize's
calculation.
EDIT: by request, adding example of height calculation for a table view cell
Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout.
As I said above, if you're using a multiline UILabel
it's imperative to sync the preferredMaxLayoutWidth
to the label width. I use a custom UILabel
subclass to do this:
@implementation TSLabel
- (void) layoutSubviews
{
[super layoutSubviews];
if ( self.numberOfLines == 0 )
{
if ( self.preferredMaxLayoutWidth != self.frame.size.width )
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
if ( self.numberOfLines == 0 )
{
// found out that sometimes intrinsicContentSize is 1pt too short!
s.height += 1;
}
return s;
}
@end
Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:
#import "TSTableViewController.h"
#import "TSTableViewCell.h"
@implementation TSTableViewController
- (NSString*) cellText
{
return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return 1;
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
return 1;
}
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
static TSTableViewCell *sizingCell;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
});
// configure the cell
sizingCell.text = self.cellText;
// force layout
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
// get the fitting size
CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));
return s.height;
}
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];
cell.text = self.cellText;
return cell;
}
@end
A simple custom cell:
#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's intrinsicContentSize
:
You can use stristr()
or strpos()
. Both return false if nothing is found.
You don't need to use the clipboard, you can export directly the whole resultset (not just what you see) to a file :
The export runs in the background, a popup will appear when it's done.
In newer versions of DBeaver you can just :
The export runs in the background, a popup will appear when it's done.
Compared to the previous way of doing exports, this saves you step 1 (executing the query) which can be handy with time/resource intensive queries.
In my case, it worked like that:
from BeautifulSoup import BeautifulSoup as bs
url="http://blabla.com"
soup = bs(urllib.urlopen(url))
for link in soup.findAll('a'):
print link.string
Hope it helps!
docker-compose logs <name-of-service>
From the documentation:
Usage: logs [options] [SERVICE...]
Options:
--no-color Produce monochrome output.
-f, --follow Follow log output.
-t, --timestamps Show timestamps.
--tail="all" Number of lines to show from the end of the logs for each container.
You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.
docker-compose up -d
to start all services in detached mode (-d
) (you won't see any logs in detached mode)docker-compose logs -f -t
to attach yourself to the logs of all running services, whereas -f
means you follow the log output and the -t
option gives you timestamps (See Docker reference)Ctrl + z
or Ctrl + c
to detach yourself from the log output without shutting down your running containersIf you're interested in logs of a single container you can use the docker
keyword instead:
docker logs -t -f <name-of-service>
To save the output to a file you add the following to your logs command:
docker-compose logs -f -t >> myDockerCompose.log
I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach
Class First {
private Second second;
public First(int num, String str) {
if(second== null)
{
//when junit runs, you get the mocked object(not null), hence don't
//initialize
second = new Second(str);
}
this.num = num;
}
... // some other methods
}
And, for test:
class TestFirst{
@InjectMock
First first;//inject mock the real testable class
@Mock
Second second
testMethod(){
//now you can play around with any method of the Second class using its
//mocked object(second),like:
when(second.getSomething(String.class)).thenReturn(null);
}
}
Replication is not very hard to create.
Here's some good tutorials:
http://www.ghacks.net/2009/04/09/set-up-mysql-database-replication/
http://dev.mysql.com/doc/refman/5.5/en/replication-howto.html
http://www.lassosoft.com/Beginners-Guide-to-MySQL-Replication
Here some simple rules you will have to keep in mind (there's more of course but that is the main concept):
This way, you will avoid errors.
For example: If your script insert into the same tables on both master and slave, you will have duplicate primary key conflict.
You can view the "slave" as a "backup" server which hold the same information as the master but cannot add data directly, only follow what the master server instructions.
NOTE: Of course you can read from the master and you can write to the slave but make sure you don't write to the same tables (master to slave and slave to master).
I would recommend to monitor your servers to make sure everything is fine.
Let me know if you need additional help
to color your output You can use examples from there:
https://help.ubuntu.com/community/CustomizingBashPrompt
Also a Gist for nodeJs
For example if you want part of the text in red color, just do console.log with:
"\033[31m this will be red \033[91m and this will be normal"
Based on that I've created "colog" extension for Node.js. You can install it using:
npm install colog
Repo and npm: https://github.com/dariuszp/colog
you could use something like:
[^0-9]+([0-9]+)[^0-9]+([0-9]+).+
Then get the first and second capture groups.
$total_ratings
is an array.
The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.
In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.
.canvas-container {
position: relative;
padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
height: 0;
overflow: hidden;
}
.canvas-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
In Anon's answer:
"If you need something from super's __init__
to be done in addition to what is being done in the current class's __init__
, you must call it yourself, since that will not happen automatically"
It's incredible: he is wording exactly the contrary of the principle of inheritance.
It is not that "something from super's __init__
(...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__
is overriden by the definition of the derived-clas __init__
So then, WHY defining a derived_class' __init__
, since it overrides what is aimed at when someone resorts to inheritance ??
It's because one needs to define something that is NOT done in the base-class' __init__
, and the only possibility to obtain that is to put its execution in a derived-class' __init__
function.
In other words, one needs something in base-class' __init__
in addition to what would be automatically done in the base-classe' __init__
if this latter wasn't overriden.
NOT the contrary.
Then, the problem is that the desired instructions present in the base-class' __init__
are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__
, in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__
.
That's exactly what is said in the official doc:
An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).
http://docs.python.org/tutorial/classes.html#inheritance
That's all the story:
when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__
function in the derived class
when the aim is to REPLACE the initialization performed by the base-class, __init__
must be defined in the derived-class
when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__
must be defined , comprising an explicit call to the base-class __init__
What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
Tools -> Options -> Fonts & Colors -> then click on Font browse option. Now you will see a popup box. Here you can change Font:, Font Style: and Size:
I had tested it.
You can create a class level variable to get returned value. I mean
class A {
int k = 0;
private void f(Button b, int a){
b.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
k = a * 5;
}
});
}
now you can get value of K and use it where you want.
Answer of your why is :
A local inner class instance is tied to Main class and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).
Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)
For me it was a big difference when I faced this scenario (here my story:)
<?xml version="1.0" encoding="UTF-8"?>
<sentence id="S1.6">When U937 cells were infected with HIV-1,
<xcope id="X1.6.3">
<cue ref="X1.6.3" type="negation">no</cue>
induction of NF-KB factor was detected
</xcope>
, whereas high level of progeny virions was produced,
<xcope id="X1.6.2">
<cue ref="X1.6.2" type="speculation">suggesting</cue> that this factor was
<xcope id="X1.6.1">
<cue ref="X1.6.1" type="negation">not</cue> required for viral replication
</xcope>
</xcope>.
</sentence>
I needed to extract text between tags and aggregate (by concat) the text including in innner tags.
/node()
did the job, while /text()
made half job
/text()
only returned text not included in inner tags, because inner tags are not "text nodes". You may think, "just extract text included in the inner tags in an additional xpath", however, it becomes challenging to sort the text in this original order because you dont know where to place the aggregated text from the inner tags!because you dont know where to place the aggregated text from the inner nodes.
Finally, /node()
did exactly what I wanted, because it gets the text from inner tags too.
The problem in your code is that you want to apply the operation on every row. The way you've written it though takes the whole 'bar' and 'foo' columns, converts them to strings and gives you back one big string. You can write it like:
df.apply(lambda x:'%s is %s' % (x['bar'],x['foo']),axis=1)
It's longer than the other answer but is more generic (can be used with values that are not strings).
from sys import exit
exit()
As a parameter you can pass an exit code, which will be returned to OS. Default is 0.
This below class would be able to get list of files, folder and all sub folder inside a given directory
import os
import json
class GetDirectoryList():
def __init__(self, path):
self.main_path = path
self.absolute_path = []
self.relative_path = []
def get_files_and_folders(self, resp, path):
all = os.listdir(path)
resp["files"] = []
for file_folder in all:
if file_folder != "." and file_folder != "..":
if os.path.isdir(path + "/" + file_folder):
resp[file_folder] = {}
self.get_files_and_folders(resp=resp[file_folder], path= path + "/" + file_folder)
else:
resp["files"].append(file_folder)
self.absolute_path.append(path.replace(self.main_path + "/", "") + "/" + file_folder)
self.relative_path.append(path + "/" + file_folder)
return resp, self.relative_path, self.absolute_path
@property
def get_all_files_folder(self):
self.resp = {self.main_path: {}}
all = self.get_files_and_folders(self.resp[self.main_path], self.main_path)
return all
if __name__ == '__main__':
mylib = GetDirectoryList(path="sample_folder")
file_list = mylib.get_all_files_folder
print (json.dumps(file_list))
Whereas Sample Directory looks like
sample_folder/
lib_a/
lib_c/
lib_e/
__init__.py
a.txt
__init__.py
b.txt
c.txt
lib_d/
__init__.py
__init__.py
d.txt
lib_b/
__init__.py
e.txt
__init__.py
Result Obtained
[
{
"files": [
"__init__.py"
],
"lib_b": {
"files": [
"__init__.py",
"e.txt"
]
},
"lib_a": {
"files": [
"__init__.py",
"d.txt"
],
"lib_c": {
"files": [
"__init__.py",
"c.txt",
"b.txt"
],
"lib_e": {
"files": [
"__init__.py",
"a.txt"
]
}
},
"lib_d": {
"files": [
"__init__.py"
]
}
}
},
[
"sample_folder/lib_b/__init__.py",
"sample_folder/lib_b/e.txt",
"sample_folder/__init__.py",
"sample_folder/lib_a/lib_c/lib_e/__init__.py",
"sample_folder/lib_a/lib_c/lib_e/a.txt",
"sample_folder/lib_a/lib_c/__init__.py",
"sample_folder/lib_a/lib_c/c.txt",
"sample_folder/lib_a/lib_c/b.txt",
"sample_folder/lib_a/lib_d/__init__.py",
"sample_folder/lib_a/__init__.py",
"sample_folder/lib_a/d.txt"
],
[
"lib_b/__init__.py",
"lib_b/e.txt",
"sample_folder/__init__.py",
"lib_a/lib_c/lib_e/__init__.py",
"lib_a/lib_c/lib_e/a.txt",
"lib_a/lib_c/__init__.py",
"lib_a/lib_c/c.txt",
"lib_a/lib_c/b.txt",
"lib_a/lib_d/__init__.py",
"lib_a/__init__.py",
"lib_a/d.txt"
]
]
As per 'dtb' you need to use HttpStatusCode, but following 'zeldi' you need to be extra careful with code responses >= 400.
This has worked for me:
HttpWebResponse response = null;
HttpStatusCode statusCode;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (WebException we)
{
response = (HttpWebResponse)we.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
sResponse = reader.ReadToEnd();
Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
Maybe your VMnet8 ip is not in the same network segment, e.g., my vm ip is 192.168.71.105, I can ping my windows in vm, but can't ping vm in windows, so this time you may check if vmnet8 is configured right. IP: 192.168.71.1
I realize that an answer was already accepted for this, but from a "strictly *nix purist angle" it seems like the right tool for the job is pcregrep
, which doesn't seem to have been mentioned yet. Try changing the lines:
echo $f | grep -oEi '[0-9]+_([a-z]+)_[0-9a-z]*'
name=$?
to the following:
name=$(echo $f | pcregrep -o1 -Ei '[0-9]+_([a-z]+)_[0-9a-z]*')
to get only the contents of the capturing group 1.
The pcregrep
tool utilizes all of the same syntax you've already used with grep
, but implements the functionality that you need.
The parameter -o
works just like the grep
version if it is bare, but it also accepts a numeric parameter in pcregrep
, which indicates which capturing group you want to show.
With this solution there is a bare minimum of change required in the script. You simply replace one modular utility with another and tweak the parameters.
Interesting Note: You can use multiple -o arguments to return multiple capture groups in the order in which they appear on the line.
You'll need:
cd C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin gacutil.exe /i "$(TargetPath)" /f /nologo gacutil /l "$(TargetName)" /nologo
Now, everytime you build your project, it'll be installed on GAC.
Not very pretty, but here is another way for Java 6 and bellow:
String runFct =
queryType.equals("eq") ? "method1":
queryType.equals("L_L")? "method2":
queryType.equals("L_R")? "method3":
queryType.equals("L_LR")? "method4":
"method5";
Method m = this.getClass().getMethod(runFct);
m.invoke(this);
You're interested in the collation. You could build something based on this snippet:
SELECT DATABASEPROPERTYEX('master', 'Collation');
Update
Based on your edit — If @test
and @TEST
can ever refer to two different variables, it's not SQL Server. If you see problems where the same variable is not equal to itself, check if that variable is NULL
, because NULL = NULL
returns `false.
and(re.search("bla_bla_pattern", str_item, re.IGNORECASE) == None)
is working.
To convert a string
having the form a="[[1, 3], [2, -6]]"
I wrote yet not optimized code:
matrixAr = []
mystring = "[[1, 3], [2, -4], [19, -15]]"
b=mystring.replace("[[","").replace("]]","") # to remove head [[ and tail ]]
for line in b.split('], ['):
row =list(map(int,line.split(','))) #map = to convert the number from string (some has also space ) to integer
matrixAr.append(row)
print matrixAr
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
String is a reference type, so you don't need to (and cannot) use Nullable<T>
here. Just declare typeOfContract as string and simply check for null after getting it from the query string. Or use String.IsNullOrEmpty if you want to handle empty string values the same as null.
There's a method that does this for you:
def show
@city = @user.city.present?
end
The present?
method tests for not-nil
plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.
Since this pattern is so common there's even a shortcut in ActiveRecord:
def show
@city = @user.city?
end
This is roughly equivalent.
As a note, testing vs nil
is almost always redundant. There are only two logically false values in Ruby: nil
and false
. Unless it's possible for a variable to be literal false
, this would be sufficient:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.
One reason you'd want to compare vs. nil
is if you have a tri-state variable that can be true
, false
or nil
and you need to distinguish between the last two states.
A reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
The git diffs have an extra path segment prepended to the file paths. You can strip the this entry in the path by specifying -p1 with patch, like so:
patch -p1 < save.patch