Use references all the time and pointers only when you have to refer to NULL
which reference cannot refer.
See this FAQ : http://www.parashift.com/c++-faq-lite/references.html#faq-8.6
If one wants to split string while keeping separators by regex without capturing group:
def finditer_with_separators(regex, s):
matches = []
prev_end = 0
for match in regex.finditer(s):
match_start = match.start()
if (prev_end != 0 or match_start > 0) and match_start != prev_end:
matches.append(s[prev_end:match.start()])
matches.append(match.group())
prev_end = match.end()
if prev_end < len(s):
matches.append(s[prev_end:])
return matches
regex = re.compile(r"[\(\)]")
matches = finditer_with_separators(regex, s)
If one assumes that regex is wrapped up into capturing group:
def split_with_separators(regex, s):
matches = list(filter(None, regex.split(s)))
return matches
regex = re.compile(r"([\(\)])")
matches = split_with_separators(regex, s)
Both ways also will remove empty groups which are useless and annoying in most of the cases.
There are a lot of answers here but I couldn't find the semantic distinction mentioned on any.
It's not about the thread itself; both methods are required as they support very different use-cases.
sleep()
sends the Thread to sleep as it was before, it just packs the context and stops executing for a predefined time. So in order to wake it up before the due time, you need to know the Thread reference. This is not a common situation in a multi-threaded environment. It's mostly used for time-synchronization (e.g. wake in exactly 3.5 seconds) and/or hard-coded fairness (just sleep for a while and let others threads work).
wait()
, on the contrary, is a thread (or message) synchronization mechanism that allows you to notify a Thread of which you have no stored reference (nor care). You can think of it as a publish-subscribe pattern (wait
== subscribe and notify()
== publish). Basically using notify() you are sending a message (that might even not be received at all and normally you don't care).
To sum up, you normally use sleep()
for time-syncronization and wait()
for multi-thread-synchronization.
They could be implemented in the same manner in the underlying OS, or not at all (as previous versions of Java had no real multithreading; probably some small VMs doesn't do that either). Don't forget Java runs on a VM, so your code will be transformed in something different according to the VM/OS/HW it runs on.
I'll try to keep it simple.
Supervised Learning: In this technique of learning, we are given a data set and the system already knows the correct output of the data set. So here, our system learns by predicting a value of its own. Then, it does an accuracy check by using a cost function to check how close its prediction was to the actual output.
Unsupervised Learning: In this approach, we have little or no knowledge of what our result would be. So instead, we derive structure from the data where we don't know effect of variable. We make structure by clustering the data based on relationship among the variable in data. Here, we don't have a feedback based on our prediction.
This can be changed in your my.ini
file (on Windows, located in \Program Files\MySQL\MySQL Server) under the server section, for example:
[mysqld]
max_allowed_packet = 10M
Your result is wrong for Java. Please provide some context how you arrived at it (your program, implementation and version of Java).
From the Java Language Specification
15.17.3 Remainder Operator %
[...]
The remainder operation for operands that are integers after binary numeric promotion (§5.6.2) produces a result value such that (a/b)*b+(a%b) is equal to a.
15.17.2 Division Operator /
[...]
Integer division rounds toward 0.
Since / is rounded towards zero (resulting in zero), the result of % should be negative in this case.
There are three good answers to this question.
unsrt
bibliography style, if you're happy with its formatting otherwisemakebst
(link) tool to design your own bibliography styleAnd my personal recommendation:
biblatex
package (link). It's the most complete and flexible bibliography tool in the LaTeX world.Using biblatex
, you'd write something like
\documentclass[12pt]{article}
\usepackage[sorting=none]{biblatex}
\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases
\begin{document}
\cite{robertson2007}
\cite{earnshaw1842}
\printbibliography
\end{document}
I just wrote this short script; seems to work.
/**
* Find all the elements with a tagName that matches.
* @param {RegExp} regEx regular expression to match against tagName
* @returns {Array} elements in the DOM that match
*/
function getAllTagMatches(regEx) {
return Array.prototype.slice.call(document.querySelectorAll('*')).filter(function (el) {
return el.tagName.match(regEx);
});
}
getAllTagMatches(/^di/i); // Returns an array of all elements that begin with "di", eg "div"
open your Redis cli and There two possible option that you could use:
FLUSHDB - Delete all the keys of the currently selected DB. FLUSHALL - Delete all the keys of all the existing databases, not just the currently selected one.
Working with Spring Boot 2, I needed to do something similar. Most of the answers above work fine, just beware that at various phases in the app lifecycles the results will be different.
For example, after a ApplicationEnvironmentPreparedEvent
any properties inside application.properties
are not present. However, after a ApplicationPreparedEvent
event they are.
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
I think that without using -exec
you can simply provide /dev/null
as at least one argument in case nothing is found:
grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null
To reduce verbosity, you can use a static import:
import static java.util.concurrent.TimeUnit.NANOSECONDS;
-and henceforth just type
NANOSECONDS.toSeconds(elapsedTime);
You can also use the following query to get Schemas for a specific Database user:
select s.schema_id, s.name as schema_name
from sys.schemas s
inner join sys.sysusers u on u.uid = s.principal_id
where u.name='DataBaseUserUserName'
order by s.name
I think that this construct: if exists (select...
is specific for MS SQL. In MySQL EXISTS
predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);
You can rewrite the above lines of code like this:
DELIMITER $$
CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)
BEGIN
DECLARE count_prim INT;
DECLARE count_sec INT;
SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;
if (count_prim > 0) then
set resultado = 0;
elseif (count_sec > 0) then
set resultado = -1;
else
set resultado = -2;
end if;
SELECT resultado;
END
I ended up using:
Function DirectoryExists(Directory As String) As Boolean
DirectoryExists = False
If Len(Dir(Directory, vbDirectory)) > 0 Then
If (GetAttr(Directory) And vbDirectory) = vbDirectory Then
DirectoryExists = True
End If
End If
End Function
which is a mix of @Brian and @ZygD answers. Where I think @Brian's answer is not enough and don't like the On Error Resume Next
used in @ZygD's answer
jQuery's .trigger('click');
will only cause an event to trigger on this event, it will not trigger the default browser action as well.
You can simulate the same functionality with the following JavaScript:
jQuery('#foo').on('click', function(){
var bar = jQuery('#bar');
var href = bar.attr('href');
if(bar.attr("target") === "_blank")
{
window.open(href);
}else{
window.location = href;
}
});
Try putting display: block
in the <li>
tags instead of the <ul>
LinearLayout : A layout that organizes its children into a single horizontal or vertical row. It creates a scrollbar if the length of the window exceeds the length of the screen.It means you can align views one by one (vertically/ horizontally).
RelativeLayout : This enables you to specify the location of child objects relative to each other (child A to the left of child B) or to the parent (aligned to the top of the parent). It is based on relation of views from its parents and other views.
WebView : to load html, static or dynamic pages.
For more information refer this link:http://developer.android.com/guide/topics/ui/layout-objects.html
When you install Homestead, this creates a default "homestead" database in the VM. You should SSH into the VM
homestead ssh
and run your migrations from there. If you are working locally with no VM, you'll need to create your database manually. By default, the database should be called homestead, the username is homestead and the password is secret.
check this thread on laracasts or this blog post for more details
if you are getting
[PDOException] SQLSTATE[HY000] [2002] No such file or directory
try changing "host" in the /app/config/database.php file from "localhost" to "127.0.0.1" . you can find more details and other fixes here on this thread.
Also check whether you have specified the correct unix_socket
. check this thread .
seaborn has a wrapper function scatterplot
that does it more efficiently.
sns.scatterplot(data = df, x = 'one', y = 'two', data = 'key1'])
In my case I was developing an ASP.Net MVC5 web app and the certificate errors on my local dev machine (IISExpress certificate) started becoming a practical concern once I started working with service workers. Chrome simply wouldn't register my service worker because of the certificate error.
I did, however, notice that during my automated Selenium browser tests, Chrome seem to just "ignore" all these kinds of problems (e.g. the warning page about an insecure site), so I asked myself the question: How is Selenium starting Chrome for running its tests, and might it also solve the service worker problem?
Using Process Explorer on Windows, I was able to find out the command-line arguments with which Selenium is starting Chrome:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-background-networking --disable-client-side-phishing-detection --disable-default-apps --disable-hang-monitor --disable-popup-blocking --disable-prompt-on-repost --disable-sync --disable-web-resources --enable-automation --enable-logging --force-fieldtrials=SiteIsolationExtensions/Control --ignore-certificate-errors --log-level=0 --metrics-recording-only --no-first-run --password-store=basic --remote-debugging-port=12207 --safebrowsing-disable-auto-update --test-type=webdriver --use-mock-keychain --user-data-dir="C:\Users\Sam\AppData\Local\Temp\some-non-existent-directory" data:,
There are a bunch of parameters here that I didn't end up doing necessity-testing for, but if I run Chrome this way, my service worker registers and works as expected.
The only one that does seem to make a difference is the --user-data-dir parameter, which to make things work can be set to a non-existent directory (things won't work if you don't provide the parameter).
Hope that helps someone else with a similar problem. I'm using Chrome 60.0.3112.90.
Not pretty. Definitely not pretty:
ls $Env:windir\Microsoft.NET\Framework | ? { $_.PSIsContainer } | select -exp Name -l 1
This may or may not work. But as far as the latest version is concerned this should be pretty reliable, as there are essentially empty folders for old versions (1.0, 1.1) but not newer ones – those only appear once the appropriate framework is installed.
Still, I suspect there must be a better way.
This message can also occur when you specify the incorrect decryption password (yeah, lame, but not quite obvious to realize this from the error message, huh?).
I was using the command line to decrypt the recent DataBase backup for my auxiliary tool and suddenly faced this issue.
Finally, after 10 mins of grief and plus reading through this question/answers I have remembered that the password is different and everything worked just fine with the correct password.
Your question is a little unclear, but if what you're doing is trying to get your friend's latest changes, then typically what your friend needs to do is to push those changes up to a remote repo (like one hosted on GitHub), and then you fetch or pull those changes from the remote:
Your friend pushes his changes to GitHub:
git push origin <branch>
Clone the remote repository if you haven't already:
git clone https://[email protected]/abc/theproject.git
Fetch or pull your friend's changes (unnecessary if you just cloned in step #2 above):
git fetch origin
git merge origin/<branch>
Note that git pull
is the same as doing the two steps above:
git pull origin <branch>
Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.
Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:
And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.
It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?
Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:
UPDATE INVOICE
SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
, INV_TOTAL = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)
WHERE INV_ID = I_INV_ID;
Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.
The element.style property lets you know only the CSS properties that were defined as inline in that element (programmatically, or defined in the style attribute of the element), you should get the computed style.
Is not so easy to do it in a cross-browser way, IE has its own way, through the element.currentStyle property, and the DOM Level 2 standard way, implemented by other browsers is through the document.defaultView.getComputedStyle method.
The two ways have differences, for example, the IE element.currentStyle property expect that you access the CSS property names composed of two or more words in camelCase (e.g. maxHeight, fontSize, backgroundColor, etc), the standard way expects the properties with the words separated with dashes (e.g. max-height, font-size, background-color, etc). ......
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hyphen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
When you change count = count + 1
to count = count + 3
or count = count + 9
, count
will never be equal to 100. At the very best it'll be 99. That's not enough.
What you've got here is the classic case of infinite loop: count
is never equal to 100 (sure, at some point it'll be greater than 100, but your while
loop doesn't check for this condition) and the while
loop goes on and on.
What you want is probably:
while count < 100: # Or <=, if you feel like printing a hundred.
Not:
while count != 0: # Spaces around !=. Makes Guido van Rossum happy.
Now the loop will terminate when count >= 100
.
Take a look at Python documentation.
You're thinking too complicated. It's actually just $('#'+openaddress)
.
FETCH_HEAD
is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull
first invokes git fetch
, in normal cases fetching a branch from the remote; FETCH_HEAD
points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull
then invokes git merge
, merging FETCH_HEAD
into the current branch.
The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.
This is a bit like doing git fetch
without arguments (or git remote update
), updating all your remote branches, then running git merge origin/<branch>
, but using FETCH_HEAD
internally instead to refer to whatever single ref was fetched, instead of needing to name things.
You have never declared fib
to be an array. Use var fib = [];
to solve this.
Also, you're never modifying the y
variable, neither using it.
The code below makes more sense, plus, it doesn't create unused variables:
var i;_x000D_
var fib = []; // Initialize array!_x000D_
_x000D_
fib[0] = 0;_x000D_
fib[1] = 1;_x000D_
for (i = 2; i <= 10; i++) {_x000D_
// Next fibonacci number = previous + one before previous_x000D_
// Translated to JavaScript:_x000D_
fib[i] = fib[i - 2] + fib[i - 1];_x000D_
console.log(fib[i]);_x000D_
}
_x000D_
You may try like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
g.drawRect (x, y, width, height); //can use either of the two//
g.fillRect (x, y, width, height);
g.setColor(color);
}
}
where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue
if you want to use rectangle object you could do it like this:
import java.applet.Applet;
import java.awt.*;
public class Rect1 extends Applet {
public void paint (Graphics g) {
Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
g.setColor(color);
}
}
I'd guess that speed is still the issue. Cross platform is going to be an issue isn't it since you don't know what 3d card is available when you write the code? Does java have anything to support auto discovery of 3d capabilities? And I'd guess that there are tools to ease porting a game between the wii, xbox, and ps3, but expensive I'll bet.
The ps3 has java, via the blue ray support. Check the bd-j site.
You can try, (filtering with 1 object like a list or a set of values)
ds = ds.filter(functions.col(COL_NAME).isin(myList));
or as @Tony Fraser suggested, you can try, (with a Seq of objects)
ds = ds.filter(functions.col(COL_NAME).isin(mySeq));
All the answers are correct but most of them do not represent a good coding style. Also, you should always consider the variable length of arguments for the future, even though they are static at a certain point in time.
If you are having 112 columns in one single table and you would like to insert data from source table, you could do as
create table employees as select * from source_employees where employee_id=100;
Or from sqlplus do as
copy from source_schema/password insert employees using select * from
source_employees where employee_id=100;
var markerArray = [];
markerArray.push(L.marker([51.505, -0.09]));
...
var group = L.featureGroup(markerArray).addTo(map);
map.fitBounds(group.getBounds());
As a rephrasing of Andrey's answer:
The Boost TypeIndex library can be used to print names of types.
Inside a template, this might read as follows
#include <boost/type_index.hpp>
#include <iostream>
template<typename T>
void printNameOfType() {
std::cout << "Type of T: "
<< boost::typeindex::type_id<T>().pretty_name()
<< std::endl;
}
you can use this function to download file from base64.
function downloadPDF(pdf) {
const linkSource = `data:application/pdf;base64,${pdf}`;
const downloadLink = document.createElement("a");
const fileName = "abc.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();}
This code will made an anchor tag with href and download file. if you want to use button then you can call click method on your button click.
i hope this will help of you thanks
In Python 3.4 and above, you can use the object oriented pathlib module interface which includes wrappers for much of the os module. Here is an example of getting the file stats.
>>> import pathlib
>>> fname = pathlib.Path('test.py')
>>> assert fname.exists(), f'No such file: {fname}' # check that the file exists
>>> print(fname.stat())
os.stat_result(st_mode=33206, st_ino=5066549581564298, st_dev=573948050, st_nlink=1, st_uid=0, st_gid=0, st_size=413, st_atime=1523480272, st_mtime=1539787740, st_ctime=1523480272)
For more information about what os.stat_result
contains, refer to the documentation. For the modification time you want fname.stat().st_mtime
:
>>> import datetime
>>> mtime = datetime.datetime.fromtimestamp(fname.stat().st_mtime)
>>> print(mtime)
datetime.datetime(2018, 10, 17, 10, 49, 0, 249980)
If you want the creation time on Windows, or the most recent metadata change on Unix, you would use fname.stat().st_ctime
:
>>> ctime = datetime.datetime.fromtimestamp(fname.stat().st_ctime)
>>> print(ctime)
datetime.datetime(2018, 4, 11, 16, 57, 52, 151953)
This article has more helpful info and examples for the pathlib module.
Sorry for updating an old POST. I got the reported problem and I solved it as said below.
Assuming you are using Eclipse + m2e maven plugin, if you get this access restriction error, right click on the project/module in which you have the error --> Properties --> Build Path --> Library --> Replace JDK/JRE to the one that is used in eclipse workspace.
I followed the above steps and the issue is resolved.
I used this in my acoustic model: probably this helps in ur model.
def one_hot_encoding(x, n_out):
x = x.astype(int)
shape = x.shape
x = x.flatten()
N = len(x)
x_categ = np.zeros((N,n_out))
x_categ[np.arange(N), x] = 1
return x_categ.reshape((shape)+(n_out,))
With abstract classes you can have some kind of skeleton for other classes to extend.
You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.
inf
is infinity - a value that is greater than any other value. -inf
is therefore smaller than any other value.
nan
stands for Not A Number, and this is not equal to 0
.
Although positive and negative infinity can be said to be symmetric about 0
, the same can be said for any value n
, meaning that the result of adding the two yields nan
. This idea is discussed in this math.se question.
Because nan
is (literally) not a number, you can't do arithmetic with it, so the result of the second operation is also not a number (nan
)
Set your environmental variable Path
to point to where the adb
application is at: [directory of sdk folder]\platform-tools
The following is much simpler
if(floor($num) == $num) {
echo number_format($num);
} else {
echo $num;
}
If you don't mind modifying your HTML a little to include the value
attribute of the options, you can significantly reduce the code necessary to do this:
<option>B</option>
to
<option value="B">B</option>
This will be helpful when you want to do something like:
<option value="IL">Illinois</option>
With that, the follow jQuery will make the change:
$("select option[value='B']").attr("selected","selected");
If you decide not to include the use of the value
attribute, you will be required to cycle through each option, and manually check its value:
$("select option").each(function(){
if ($(this).text() == "B")
$(this).attr("selected","selected");
});
Export the store from the module you called createStore
with. Then you are assured it will both be created and will not pollute the global window space.
const store = createStore(myReducer);
export store;
or
const store = createStore(myReducer);
export default store;
import {store} from './MyStore'
store.dispatch(...)
or if you used default
import store from './MyStore'
store.dispatch(...)
If you need multiple instances of a store, export a factory function.
I would recommend making it async
(returning a promise
).
async function getUserStore (userId) {
// check if user store exists and return or create it.
}
export getUserStore
On the client (in an async
block)
import {getUserStore} from './store'
const joeStore = await getUserStore('joe')
The problem is in the network layer. Here are the status codes explained:
Connection refused
: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.
Connection timed out
: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.
That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.
Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.
It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.
As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.
To rule out network congestion as a problem you could use a tool like mtr
or traceroute
or even ping
to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.
Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).
If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp
is definetly recommended then.
The quickest and the most intuitive method of them all is to remap )
for walk-down-commenting of lines, and then (
for walk-up-uncommenting. Try it and you won't go back.
In Ruby or Bash, with 2-space indents:
map ) I# <Esc>j
map ( k^2x
In C/C++ or PHP, with 4-space indents:
map ) I// <Esc>j
map ( k^4x
Downsides are that you lose (
and )
for sentence-movement (but das
can fill in there), and you'll occasionally fall back on select-and-replace or CtrlV for handling long sections. But that's pretty rare.
And for C-style, the long comments are best handled with:
set cindent
set formatoptions=tcqr
... Which combines well with using V[move]gq
to redo the word-wrapping.
look at String.indexOf
and String.substring
.
Make sure you check for -1 for indexOf
.
Run like:
$ mvn help:describe -DartifactId=maven-war-plugin -DgroupId=org.apache.maven.plugins
for plug-in that have no version. You get output:
Name: Maven WAR Plugin Description: Builds a Web Application Archive (WAR) file from the project output and its dependencies. Group Id: org.apache.maven.plugins Artifact Id: maven-war-plugin Version: 2.2 Goal Prefix: war
Use version that shown in output.
UPDATE If you want to select among list of versions, use http://search.maven.org/ or http://mvnrepository.com/ Note that your favorite Java IDE must have Maven package search dialog. Just check docs.
SUPER UPDATE I also use:
$ mvn dependency:tree
$ mvn dependency:list
$ mvn dependency:resolve
$ mvn dependency:resolve-plugins # <-- THIS
Recently I discover how to get latest version for plug-in (or library) so no longer needs for googling or visiting Maven Central:
$ mvn versions:display-dependency-updates
$ mvn versions:display-plugin-updates # <-- THIS
I know this is an old thread, however, this topic in my opinion becomes of great importance for those using the functional approach for all those usecases where you need a microservice that loads "instantly" and therefore you avoid using annotations. The problem that remained unsolved was to load eventually the environment variables which I had in my application.yml.
public class AppPropsLoader {
public static Properties load() {
var propPholderConfig = new PropertySourcesPlaceHolderConfigurer();
var yaml = new YamlPropertiesFactoryBean();
ClassPathResource resource = new ClassPathResource("application.yml");
Objects.requireNonNull(resource, "File application.yml does not exist");
yaml.setResources(resource);
Objects.requireNonNull(yaml.getObject(), "Configuration cannot be null");
propPholderConfig.postProcessBeanFactory(new DefaultListableBeanFactory());
propPholderConfig.setProperties(yaml.getObject());
PropertySources appliedPropertySources =
propPholderConfig.getAppliedPropertySources();
var resolver = new PropertySourcesPlaceholderResolver(appliedPropertySources);
Properties resolvedProps = new Properties();
for (Map.Entry<Object, Object> prop: yaml.getObject().entrySet()) {
resolvedProps.setProperty((String)prop.getKey(),
getPropertyValue(resolver.resolvePlaceHolders(prop.getValue()));
}
return resolvedProps;
}
static String getPropertyValue(Object prop) {
var val = String.valueOf(prop);
Pattern p = Pattern.compile("^(\\$\\{)([a-zA-Z0-9-._]+)(\\})$");
Matcher m = p.matcher(val);
if(m.matches()) {
return System.getEnv(m.group(2));
}
return val;
}
}
Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager
and EntityManagerFactory
, without explicit Spring dependencies in your code:
http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa
This allows you to either inject the EntityManagerFactory
, or else inject a thread-safe, transactional proxy of an EntityManager
directly. The latter makes for simpler code, but means more Spring plumbing is required.
3 years later and not a single person has answered this question completely.
The asker wants to cancel the default form submission and call their own Ajax. This is a simple request with a simple solution. There is no need to intercept every character entered into each input.
Assuming the form has a submit button, whether a <button id="save-form">
or an <input id="save-form" type="submit">
, do:
$("#save-form").on("click", function () {
$.ajax({
...
});
return false;
});
EDIT Feb 1, 2013. Due to the popularity of this answer and the changes to jQuery in version 1.9 (and 2.0) regarding properties and attributes, I added some notes and a fiddle to see how it works when accessing properties/attributes on input, buttons and some selects. The fiddle here: http://jsfiddle.net/pVBU8/1/
get all the inputs:
var allInputs = $(":input");
get all the inputs type:
allInputs.attr('type');
get the values:
allInputs.val();
NOTE: .val() is NOT the same as :checked for those types where that is relevent. use:
.attr("checked");
EDIT Feb 1, 2013 - re: jQuery 1.9 use prop() not attr() as attr will not return proper values for properties that have changed.
.prop('checked');
or simply
$(this).checked;
to get the value of the check - whatever it is currently. or simply use the ':checked' if you want only those that ARE checked.
EDIT: Here is another way to get type:
var allCheckboxes=$('[type=checkbox]');
EDIT2: Note that the form of:
$('input:radio');
is perferred over
$(':radio');
which both equate to:
$('input[type=radio]');
but the "input" is desired so it only gets the inputs and does not use the universal '*" when the form of $(':radio')
is used which equates to $('*:radio');
EDIT Aug 19, 2015: preference for the $('input[type=radio]');
should be used as that then allows modern browsers to optimize the search for a radio input.
EDIT Feb 1, 2013 per comment re: select elements @dariomac
$('select').prop("type");
will return either "select-one" or "select-multiple" depending upon the "multiple" attribute and
$('select')[0].type
returns the same for the first select if it exists. and
($('select')[0]?$('select')[0].type:"howdy")
will return the type if it exists or "howdy" if it does not.
$('select').prop('type');
returns the property of the first one in the DOM if it exists or "undefined" if none exist.
$('select').type
returns the type of the first one if it exists or an error if none exist.
The problem we were having is that, by default, ISOStrings aren't localized to your timezone. So, this is kinda hacky, but here's how we ended up solving this issue:
/** Imports Moment for time utilities. */
const moment = require("moment-timezone")
moment().tz("America/Chicago").format()
//** Returns now in ISO format in Central Time */
export function getNowISO() {
return `${moment().toISOString(true).substring(0, 23)}Z`
}
_x000D_
This will leave you with an exact ISO-formatted, localized string.
Important note: Moment now suggests using other packages for new projects.
Response.Write("<script>alert('Data inserted successfully')</script>");
You may pass an object to the data
option in $.ajax
. jQuery will send this as regular post data, just like a normal HTML form.
$.ajax({
type: "POST",
url: "TelephoneNumbers.aspx/DeleteNumber",
data: dataO, // same as using {numberId: 1, companyId: 531}
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert('In Ajax');
}
});
There are no performance implications since the compiler will translate your lambda expression into an equivalent delegate. Lambda expressions are nothing more than a language feature that the compiler translates into the exact same code that you are used to working with.
The compiler will convert the code you have to something like this:
public partial class MyPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//snip
MyButton.Click += new EventHandler(delegate (Object o, EventArgs a)
{
//snip
});
}
}
I believe, by default, boto picks the region which is set in aws cli. You can run command #aws configure and press enter (it shows what creds you have set in aws cli with region)twice to confirm your region.
From wikipedia.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
"Transitional//EN\">\n" +
"<html>\n" +
"<head><title>Hello WWW</title></head>\n" +
"<body>\n" +
"<h1>Hello WWW</h1>\n" +
"</body></html>");
}
}
This, of course, works only if you have added the servlet-api.jar
to Eclipse build path. Typically your application server (e.g Tomcat) will have the right jar file.
Use IFNULL:
IFNULL(expr1, 0)
From the documentation:
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
My favorite way:
Imports System.Runtime.CompilerServices
<Extension()> _
Public Sub RemoveAll(Of T)(ByRef arr As T(), matching As Predicate(Of T))
If Not IsNothing(arr) Then
If arr.Count > 0 Then
Dim ls As List(Of T) = arr.ToList
ls.RemoveAll(matching)
arr = ls.ToArray
End If
End If
End Sub
Then in the code, whenever I need to remove something from an array I can do it by some property in some object in that array having a certain value, like:
arr.RemoveAll(Function(c) c.MasterContactID.Equals(customer.MasterContactID))
Or if I already know the exact object I want to remove, I can just do:
arr.RemoveAll(function(c) c.equals(customer))
Two likely definitions:
getActivity()
in a Fragment
returns the Activity
the Fragment
is currently associated with. (see http://developer.android.com/reference/android/app/Fragment.html#getActivity()).getActivity()
is user-defined.You can run this in powershell:
[System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile
Which outputs this for .net 4:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config
Note however that this might change depending on whether .net is running as 32 or 64 bit which will result in \Framework\
or \Framework64\
respectively.
Do you want to order it?
Select * From temp where mydate > '2009-06-29 04:00:44' ORDER BY mydate;
It is located on the Android Studio
folder itself, on where you installed it.
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.
My env is OSX Yosemite. Had the same issue .... solved by adding the following
1) edit and add the following line to .bash_profile file.
[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"
2) Restart terminal and try RVM command again
I suppose rgba()
would work here. After all, browser support for both box-shadow
and rgba()
is roughly the same.
/* 50% black box shadow */
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);
div {_x000D_
width: 200px;_x000D_
height: 50px;_x000D_
line-height: 50px;_x000D_
text-align: center;_x000D_
color: white;_x000D_
background-color: red;_x000D_
margin: 10px;_x000D_
}_x000D_
_x000D_
div.a {_x000D_
box-shadow: 10px 10px 10px #000;_x000D_
}_x000D_
_x000D_
div.b {_x000D_
box-shadow: 10px 10px 10px rgba(0, 0, 0, 0.5);_x000D_
}
_x000D_
<div class="a">100% black shadow</div>_x000D_
<div class="b">50% black shadow</div>
_x000D_
Yes, python strings are immutable and any modification will result in creating a new string. This is how it's mostly done.
So, go ahead with it.
This should work:
<script type="text/javascript">
var testing='this is d23553 test 32533\n31203 not 333';
var r = new RegExp(/(?:^|[^\d])(\d{5})(?:$|[^\d])/mg);
var matches = [];
while ((match = r.exec(testing))) matches.push(match[1]);
alert('Found: '+matches.join(', '));
</script>
So below is my previous fix for this problem, but it turns out it isn't permanent. It works but every time you restart Terminal, you'd have to do the same thing which isn't practical.
So that is why I suggest you delete the current google-cloud-sdk directory, and just redo the installation. Be sure (as Zachary has mentioned) to answer yes (Y) to the prompt Modify profile to update your $PATH and enable bash completion? (Y/n)
.
Here is my old answer, but just redo the installation:
I had the same problem,
gcloud
wasn't working for me. But then, in the same directory as mygoogle-cloud-sdk
folder which I had just installed (myhome
directory), I found this file calledtest
. Inside thistest
file I found two commands:
# The next line updates PATH for the Google Cloud SDK.
source '[path-to-my-home]/google-cloud-sdk/path.bash.inc'
# The next line enables bash completion for gcloud.
source '[path-to-my-home]/google-cloud-sdk/completion.bash.inc'
After I ran these two
source
commands in terminal,gcloud
worked!
yes on your aspx page include a script tag with runat=server
<script language="c#" runat="server">
public void Page_Load(object sender, EventArgs e)
{
// some load code
}
</script>
You can also use classic ASP Syntax
<% if (this.MyTextBox.Visible) { %>
<span>Only show when myTextBox is visible</span>
<% } %>
Pandas does this very elegantly, though ofc list comprehensions will always be more technically Pythonic. I don't have time to put in a speed comparison right now (I'll come back later and put it in):
import pandas as pd
mydict = {'one': 1, 'two': 2, 'three': 3}
mykeys = ['three', 'one']
temp_df = pd.DataFrame().append(mydict)
# You can export DataFrames to a number of formats, using a list here.
temp_df[mykeys].values[0]
# Returns: array([ 3., 1.])
# If you want a dict then use this instead:
# temp_df[mykeys].to_dict(orient='records')[0]
# Returns: {'one': 1.0, 'three': 3.0}
I would do it this way
$("#idElement").val('optionValue').trigger('change');
1.1) First-level cache
First-level cache always Associates with the Session object. Hibernate uses this cache by default. Here, it processes one transaction after another one, means wont process one transaction many times. Mainly it reduces the number of SQL queries it needs to generate within a given transaction. That is instead of updating after every modification done in the transaction, it updates the transaction only at the end of the transaction.
1.2) Second-level cache
Second-level cache always associates with the Session Factory object. While running the transactions, in between it loads the objects at the Session Factory level, so that those objects will be available to the entire application, not bound to single user. Since the objects are already loaded in the cache, whenever an object is returned by the query, at that time no need to go for a database transaction. In this way the second level cache works. Here we can use query level cache also.
Quoted from: http://javabeat.net/introduction-to-hibernate-caching/
Here is a happy little list to put in your .jshintrc
I will add to this list at time passes.
{
// other settings...
// ENVIRONMENTS
// "browser": true, // Is in most configs by default
"node": true,
// others (e.g. yui, mootools, rhino, worker, etc.)
"globals": {
"$":false,
"jquery":false,
"angular":false
// other explicit global names to exclude
},
}
Assuming you have a properties file on your classpath that contains
api.orders.pingFrequency=4
I tried inside a @Controller
@Controller
public class MyController {
@Value("${api.orders.pingFrequency}")
private Integer pingFrequency;
...
}
With my servlet context containing :
<context:property-placeholder location="classpath:myprops.properties" />
It worked perfectly.
So either your property is not an integer type, you don't have the property placeholder configured correctly, or you are using the wrong property key.
I tried running with an invalid property value, 4123;
. The exception I got is
java.lang.NumberFormatException: For input string: "4123;"
which makes me think the value of your property is
api.orders.pingFrequency=(java.lang.Integer)${api.orders.pingFrequency}
How about this? /(7|8|9)\d{9}/
It starts by either looking for 7 or 8 or 9, and then followed by 9 digits.
In my case (using webpack 4) within an anonymous function, that I was using as a callback.
I had to use window.$.ajax()
instead of $.ajax()
despite having:
import $ from 'jquery';
window.$ = window.jQuery = $;
Unique counts of field values are achieved by using facets. See ES documentation for the full story, but the gist is that you will create a query and then ask ES to prepare facets on the results for counting values found in fields. It's up to you to customize the fields used and even describe how you want the values returned. The most basic of facet types is just to group by terms, which would be like an IP address above. You can get pretty complex with these, even requiring a query within your facet!
{
"query": {
"match_all": {}
},
"facets": {
"terms": {
"field": "ip_address"
}
}
}
Regular expressions to the rescue:
import re
re.sub(r'\W+', '', your_string)
By Python definition
'\W
==[^a-zA-Z0-9_]
, which excludes allnumbers
,letters
and_
This should work with any div
or screen size:
.center-screen {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
text-align: center;_x000D_
min-height: 100vh;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="center-screen">_x000D_
I'm in the center_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
See more details about flex
here. This should work on most of the browsers, see compatibility matrix here.
Update: If you don't want the scroll bar, make min-height
smaller, for example min-height: 95vh;
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
In your example, you can't: the 5px margin
is added to the bounding box of div#two
and div#three
effectively making their width and height 100% of parent + 5px, which will overflow.
You can use padding
on the parent Element to ensure there's 5px
of space inside its border:
<style>
html, body {width:100%;height:100%;margin:0;padding:0;}
.border {border:1px solid black;}
#one {padding:5px;width:500px;height:300px;}
#two {width:100%;height:50px;}
#three {width:100px;height:100%;}
</style>
EDIT: In testing, removing the width:100%
from div#two
will actually let it work properly as div
s are block-level and will always fill their parents' widths by default. That should clear your first case if you'd like to use margin.
According to the api docs, doing:
dataFrame1.except(dataFrame2)
will return a new DataFrame containing rows in dataFrame1 but not in dataframe2.
Here is an example using jQuery...
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.json.org/json2.js"></script>
<script type="text/javascript">
$(function() {
var frm = $(document.myform);
var dat = JSON.stringify(frm.serializeArray());
alert("I am about to POST this:\n\n" + dat);
$.post(
frm.attr("action"),
dat,
function(data) {
alert("Response: " + data);
}
);
});
</script>
</head>
The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.
The commands are adduser
and addgroup
.
Here's a template for Docker you can use in busybox environments (alpine) as well as Debian-based environments (Ubuntu, etc.):
ENV USER=docker
ENV UID=12345
ENV GID=23456
RUN adduser \
--disabled-password \
--gecos "" \
--home "$(pwd)" \
--ingroup "$USER" \
--no-create-home \
--uid "$UID" \
"$USER"
Note the following:
--disabled-password
prevents prompt for a password--gecos ""
circumvents the prompt for "Full Name" etc. on Debian-based systems--home "$(pwd)"
sets the user's home to the WORKDIR. You may not want this.--no-create-home
prevents cruft getting copied into the directory from /etc/skel
The usage description for these applications is missing the long flags present in the code for adduser and addgroup.
The following long-form flags should work both in alpine as well as debian-derivatives:
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: adduser [OPTIONS] USER [GROUP]
Create new user, or add USER to GROUP
--home DIR Home directory
--gecos GECOS GECOS field
--shell SHELL Login shell
--ingroup GRP Group (by name)
--system Create a system user
--disabled-password Don't assign a password
--no-create-home Don't create home directory
--uid UID User id
One thing to note is that if --ingroup
isn't set then the GID is assigned to match the UID. If the GID corresponding to the provided UID already exists adduser will fail.
BusyBox v1.28.4 (2018-05-30 10:45:57 UTC) multi-call binary.
Usage: addgroup [-g GID] [-S] [USER] GROUP
Add a group or add a user to a group
--gid GID Group id
--system Create a system group
I discovered all of this while trying to write my own alternative to the fixuid project for running containers as the hosts UID/GID.
My entrypoint helper script can be found on GitHub.
The intent is to prepend that script as the first argument to ENTRYPOINT
which should cause Docker to infer UID and GID from a relevant bind mount.
An environment variable "TEMPLATE" may be required to determine where the permissions should be inferred from.
(At the time of writing I don't have documentation for my script. It's still on the todo list!!)
Just add this to config
<system.net>
<defaultProxy useDefaultCredentials="true" >
</defaultProxy>
</system.net>
With this approach, there is no need to import any library.
DateTime now = DateTime.now();
String convertedDateTime = "${now.year.toString()}-${now.month.toString().padLeft(2,'0')}-${now.day.toString().padLeft(2,'0')} ${now.hour.toString()}-${now.minute.toString()}";
Output
2020-12-05 14:57
It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-line
or white-space: pre-wrap
. Clean and elegant. The lowest version of IE that supports the pair is 8.
https://css-tricks.com/almanac/properties/w/whitespace/
P.S. Until CSS3 become common you'd probably need to manually trim off initial and/or trailing white-spaces.
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
It's always best to use the lowest base type possible. This gives the implementer of your interface, or consumer of your method, the opportunity to use whatever they like behind the scenes.
For collections you should aim to use IEnumerable where possible. This gives the most flexibility but is not always suited.
According to the release-notes, Java 11 removed the Java EE modules:
java.xml.bind (JAXB) - REMOVED
See JEP 320 for more info.
You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.3</version>
<scope>runtime</scope>
</dependency>
Use latest release of Eclipse Implementation of JAXB 3.0.0:
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>3.0.0</version>
<scope>runtime</scope>
</dependency>
Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*
, so update import statements:
javax.xml.bind -> jakarta.xml.bind
The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature
You can simply center the image and text in the parent tag by setting
div {
text-align: center;
}
vertical center the img and span
img {
vertical-align:middle;
}
span {
vertical-align:middle;
}
You can just add second set below, and one thing to mention is that h4 has block display attribute, so you might want to set
h4 {
display: inline-block
}
to set the h4 "inline".
The full example is shown here.
<div id="photo" style="text-align: center">_x000D_
<img style="vertical-align:middle" src="https://via.placeholder.com/22x22" alt="">_x000D_
<span style="vertical-align:middle">Take a photo</span>_x000D_
</div>
_x000D_
Object.defineProperties(Element.prototype,{
group : {
value: function (str, context) {
// str is valid css selector like :not([attr_name]) or .class_name
var t = "to_select_siblings___";
var parent = context ? context : this.parentNode;
parent.setAttribute(t, '');
var rez = document.querySelectorAll("[" + t + "] " + (context ? '' : ">") + this.nodeName + (str || "")).toArray();
parent.removeAttribute(t);
return rez;
}
},
siblings: {
value: function (str, context) {
var rez=this.group(str,context);
rez.splice(rez.indexOf(this), 1);
return rez;
}
},
nth: {
value: function(str,context){
return this.group(str,context).indexOf(this);
}
}
}
Ex
/* html */
<ul id="the_ul"> <li></li> ....<li><li>....<li></li> </ul>
/*js*/
the_ul.addEventListener("click",
function(ev){
var foo=ev.target;
foo.setAttribute("active",true);
foo.siblings().map(function(elm){elm.removeAttribute("active")});
alert("a click on li" + foo.nth());
});
You can use either resample or Grouper
(which resamples under the hood).
First make sure that the datetime column is actually of datetimes (hit it with pd.to_datetime
). It's easier if it's a DatetimeIndex:
In [11]: df1
Out[11]:
abc xyz
Date
2013-06-01 100 200
2013-06-03 -20 50
2013-08-15 40 -5
2014-01-20 25 15
2014-02-21 60 80
In [12]: g = df1.groupby(pd.Grouper(freq="M")) # DataFrameGroupBy (grouped by Month)
In [13]: g.sum()
Out[13]:
abc xyz
Date
2013-06-30 80 250
2013-07-31 NaN NaN
2013-08-31 40 -5
2013-09-30 NaN NaN
2013-10-31 NaN NaN
2013-11-30 NaN NaN
2013-12-31 NaN NaN
2014-01-31 25 15
2014-02-28 60 80
In [14]: df1.resample("M", how='sum') # the same
Out[14]:
abc xyz
Date
2013-06-30 40 125
2013-07-31 NaN NaN
2013-08-31 40 -5
2013-09-30 NaN NaN
2013-10-31 NaN NaN
2013-11-30 NaN NaN
2013-12-31 NaN NaN
2014-01-31 25 15
2014-02-28 60 80
Note: Previously pd.Grouper(freq="M")
was written as pd.TimeGrouper("M")
. The latter is now deprecated since 0.21.
I had thought the following would work, but it doesn't (due to as_index
not being respected? I'm not sure.). I'm including this for interest's sake.
If it's a column (it has to be a datetime64 column! as I say, hit it with to_datetime
), you can use the PeriodIndex:
In [21]: df
Out[21]:
Date abc xyz
0 2013-06-01 100 200
1 2013-06-03 -20 50
2 2013-08-15 40 -5
3 2014-01-20 25 15
4 2014-02-21 60 80
In [22]: pd.DatetimeIndex(df.Date).to_period("M") # old way
Out[22]:
<class 'pandas.tseries.period.PeriodIndex'>
[2013-06, ..., 2014-02]
Length: 5, Freq: M
In [23]: per = df.Date.dt.to_period("M") # new way to get the same
In [24]: g = df.groupby(per)
In [25]: g.sum() # dang not quite what we want (doesn't fill in the gaps)
Out[25]:
abc xyz
2013-06 80 250
2013-08 40 -5
2014-01 25 15
2014-02 60 80
To get the desired result we have to reindex...
In [39]: df
Out[39]:
index a b c
0 1 2 3 4
1 2 3 4 5
In [40]: df1 = df[['b', 'c']]
In [41]: df1
Out[41]:
b c
0 3 4
1 4 5
Swift 4.0
Store:
let arrayFruit = ["Apple","Banana","Orange","Grapes","Watermelon"]
//store in user default
UserDefaults.standard.set(arrayFruit, forKey: "arrayFruit")
Fetch:
if let arr = UserDefaults.standard.array(forKey: "arrayFruit") as? [String]{
print(arr)
}
You can use code snippets to insert any lines you want.
Also, if you type three single quotation marks (''') on the line above the function header, it will insert the XML header template that you can then fill out.
These XML comments can be interpreted by documentation software, and they are included in the build output as an assembly.xml file. If you keep that XML file with the DLL and reference that DLL in another project, those comments become available in intellisense.
The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)
*::after {
content: none !important;
}
*::before {
content: none !important;
}
_x000D_
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
It may be possible that the server is already running. Please check it by the command mongo is working or not.
It used to be generally recommended best practice1 to use pass by const ref for all types, except for builtin types (char
, int
, double
, etc.), for iterators and for function objects (lambdas, classes deriving from std::*_function
).
This was especially true before the existence of move semantics. The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.
With C++11, we have gained move semantics. In a nutshell, move semantics permit that, in some cases, an object can be passed “by value” without copying it. In particular, this is the case when the object that you are passing is an rvalue.
In itself, moving an object is still at least as expensive as passing by reference. However, in many cases a function will internally copy an object anyway — i.e. it will take ownership of the argument.2
In these situations we have the following (simplified) trade-off:
“Pass by value” still causes the object to be copied, unless the object is an rvalue. In the case of an rvalue, the object can be moved instead, so that the second case is suddenly no longer “copy, then move” but “move, then (potentially) move again”.
For large objects that implement proper move constructors (such as vectors, strings …), the second case is then vastly more efficient than the first. Therefore, it is recommended to use pass by value if the function takes ownership of the argument, and if the object type supports efficient moving.
A historical note:
In fact, any modern compiler should be able to figure out when passing by value is expensive, and implicitly convert the call to use a const ref if possible.
In theory. In practice, compilers can’t always change this without breaking the function’s binary interface. In some special cases (when the function is inlined) the copy will actually be elided if the compiler can figure out that the original object won’t be changed through the actions in the function.
But in general the compiler can’t determine this, and the advent of move semantics in C++ has made this optimisation much less relevant.
1 E.g. in Scott Meyers, Effective C++.
2 This is especially often true for object constructors, which may take arguments and store them internally to be part of the constructed object’s state.
I've faced this issue several times on MacOS. Git is case sensitive but Mac is only case preserving.
Someone commit a file: Foobar.java
and after a few days decides to rename it to FooBar.java
. When you pull the latest code it fails with The following untracked working tree files would be overwritten by checkout...
The only reliable way that I've seen that fixes this is:
git rm Foobar.java
git commit -m 'TEMP COMMIT!!'
git rebase --continue
git rebase -i HEAD~2
and drop
the TEMP COMMIT!!
FooBar.java
In the object you're mapping:
@JsonSerialize(using = CustomDateSerializer.class)
public DateTime getDate() { ... }
In CustomDateSerializer:
public class CustomDateSerializer extends JsonSerializer<DateTime> {
private static DateTimeFormatter formatter =
DateTimeFormat.forPattern("dd-MM-yyyy");
@Override
public void serialize(DateTime value, JsonGenerator gen,
SerializerProvider arg2)
throws IOException, JsonProcessingException {
gen.writeString(formatter.print(value));
}
}
Here you go: ES5
var test = 'Hello World';
if( test.indexOf('World') >= 0){
// Found world
}
With ES6 best way would be to use includes
function to test if the string contains the looking work.
const test = 'Hello World';
if (test.includes('World')) {
// Found world
}
There is a straightforward solution without messing with matplotlib: just pandas.
Tweaking the original example:
table = sql.read_frame(query,connection)
ax = table[0].plot(color=colors[0],ylim=(0,100))
ax2 = table[1].plot(secondary_y=True,color=colors[1], ax=ax)
ax.set_ylabel('Left axes label')
ax2.set_ylabel('Right axes label')
Basically, when the secondary_y=True
option is given (eventhough ax=ax
is passed too) pandas.plot
returns a different axes which we use to set the labels.
I know this was answered long ago, but I think this approach worths it.
If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.
For DataTables 1.9
Use bPaginate
option to disable pagination.
$('#example').dataTable({
"bPaginate": false
});
For DataTables 1.10+
Use paging
option to disable pagination.
$('#example').dataTable({
"paging": false
});
See this jsFiddle for code and demonstration.
For DataTables 1.9
Use sDom
option to configure which control elements appear on the page.
$('#example').dataTable({
"sDom": "lfrti"
});
For DataTables 1.10+
Use dom
option to configure which control elements appear on the page.
$('#example').dataTable({
"dom": "lfrti"
});
See this jsFiddle for code and demonstration.
All solutions work great, except when applied in programming languages that closures (e.g. Coda, Excel, Spreadsheet's REGEXREPLACE
).
Two original solutions of mine below use only 1 concatenation and 1 regex.
The idea is to append replacement values if they are not already in the string. Then, using a single regex, we perform all needed replacements:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||cat,dog,goat").replace(
/cat(?=[\s\S]*(dog))|dog(?=[\s\S]*(goat))|goat(?=[\s\S]*(cat))|\|\|\|\|.*$/gi, "$1$2$3");
document.body.innerHTML = str;
_x000D_
Explanations:
cat(?=[\s\S]*(dog))
means that we look for "cat". If it matches, then a forward lookup will capture "dog" as group 1, and "" otherwise."$1$2$3"
(the concatenation of all three groups), which will always be either "dog", "cat" or "goat" for one of the above casesstr+"||||cat,dog,goat"
, we remove them by also matching \|\|\|\|.*$
, in which case the replacement "$1$2$3"
will evaluate to "", the empty string.One problem with Method #1 is that it cannot exceed 9 replacements at a time, which is the maximum number of back-propagation groups. Method #2 states not to append just replacement values, but replacements directly:
var str = "I have a cat, a dog, and a goat.";
str = (str+"||||,cat=>dog,dog=>goat,goat=>cat").replace(
/(\b\w+\b)(?=[\s\S]*,\1=>([^,]*))|\|\|\|\|.*$/gi, "$2");
document.body.innerHTML = str;
_x000D_
Explanations:
(str+"||||,cat=>dog,dog=>goat,goat=>cat")
is how we append a replacement map to the end of the string.(\b\w+\b)
states to "capture any word", that could be replaced by "(cat|dog|goat) or anything else.(?=[\s\S]*...)
is a forward lookup that will typically go to the end of the document until after the replacement map.
,\1=>
means "you should find the matched word between a comma and a right arrow"([^,]*)
means "match anything after this arrow until the next comma or the end of the doc"|\|\|\|\|.*$
is how we remove the replacement map.You can also quite easily use pdfminer as a library. You have access to the pdf's content model, and can create your own text extraction. I did this to convert pdf contents to semi-colon separated text, using the code below.
The function simply sorts the TextItem content objects according to their y and x coordinates, and outputs items with the same y coordinate as one text line, separating the objects on the same line with ';' characters.
Using this approach, I was able to extract text from a pdf that no other tool was able to extract content suitable for further parsing from. Other tools I tried include pdftotext, ps2ascii and the online tool pdftextonline.com.
pdfminer is an invaluable tool for pdf-scraping.
def pdf_to_csv(filename):
from pdflib.page import TextItem, TextConverter
from pdflib.pdfparser import PDFDocument, PDFParser
from pdflib.pdfinterp import PDFResourceManager, PDFPageInterpreter
class CsvConverter(TextConverter):
def __init__(self, *args, **kwargs):
TextConverter.__init__(self, *args, **kwargs)
def end_page(self, i):
from collections import defaultdict
lines = defaultdict(lambda : {})
for child in self.cur_item.objs:
if isinstance(child, TextItem):
(_,_,x,y) = child.bbox
line = lines[int(-y)]
line[x] = child.text
for y in sorted(lines.keys()):
line = lines[y]
self.outfp.write(";".join(line[x] for x in sorted(line.keys())))
self.outfp.write("\n")
# ... the following part of the code is a remix of the
# convert() function in the pdfminer/tools/pdf2text module
rsrc = PDFResourceManager()
outfp = StringIO()
device = CsvConverter(rsrc, outfp, "ascii")
doc = PDFDocument()
fp = open(filename, 'rb')
parser = PDFParser(doc, fp)
doc.initialize('')
interpreter = PDFPageInterpreter(rsrc, device)
for i, page in enumerate(doc.get_pages()):
outfp.write("START PAGE %d\n" % i)
interpreter.process_page(page)
outfp.write("END PAGE %d\n" % i)
device.close()
fp.close()
return outfp.getvalue()
UPDATE:
The code above is written against an old version of the API, see my comment below.
package com.concepttimes.java;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class IllegalStateExceptionDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
List al = new ArrayList();
al.add("Sachin");
al.add("Rahul");
al.add("saurav");
Iterator itr = al.iterator();
while (itr.hasNext()) {
itr.remove();
}
}
}
IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.
Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/
To view any variable in chrome, go to "Sources", and then "Watch" and add it. If you add the "window" variable here then you can expand it and explore.
Function ListRowCount(ByVal FirstCellName as String) as Long
With thisworkbook.Names(FirstCellName).RefersToRange
If isempty(.Offset(1,0).value) Then
ListRowCount = 1
Else
ListRowCount = .End(xlDown).row - .row + 1
End If
End With
End Function
But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count
As it was mentioned by Davos you can use the IDLEX
It happens that I'm using Linux version and from all extensions I needed only LineNumbers. So I've downloaded IDLEX archive, took LineNumbers.py from it, copied it to Python's lib folder ( in my case its /usr/lib/python3.5/idlelib ) and added following lines to configuration file in my home folder which is ~/.idlerc/config-extensions.cfg:
[LineNumbers]
enable = 1
enable_shell = 0
visible = True
[LineNumbers_cfgBindings]
linenumbers-show =
Check this fiddle.
$('#email').bind("cut copy paste",function(e) {
e.preventDefault();
});
You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.
You can find a detailed explanation here.
It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:
my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
for i in range(my_strings.count(undesirable_string)):
my_strings.remove(undesirable_string)
which changes my_strings to ['a', 'c', 'e']
For cases like the one you described, I found this to work. It's relatively short and sweet:
let attributedString = NSMutableAttributedString(string: "follow the yellow brick road") //can essentially come from a textField.text as well (will need to unwrap though)
let text = "follow the yellow brick road"
let str = NSString(string: text)
let theRange = str.rangeOfString("yellow")
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.yellowColor(), range: theRange)
The correct way to do this as of v4 is:
$('.select2-chosen').select2('data')[0].text
It is undocumented so could break in the future without warning.
You will probably want to check if there is a selection first however:
var s = $('.select2-chosen');
if(s.select2('data') && !!s.select2('data')[0]){
//do work
}
The greatest value of an integer has little to do with the maximum number of rows you can store in a table.
It's true that if you use an int or bigint as your primary key, you can only have as many rows as the number of unique values in the data type of your primary key, but you don't have to make your primary key an integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.
There are other constraints on table size besides number of rows. For instance you could use an operating system that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each row is 1KB in size.
The limits of database size is really high:
http://dev.mysql.com/doc/refman/5.1/en/source-configuration-options.html
The MyISAM storage engine supports 232 rows per table, but you can build MySQL with the --with-big-tables
option to make it support up to 264 rows per table.
http://dev.mysql.com/doc/refman/5.1/en/innodb-restrictions.html
The InnoDB storage engine has an internal 6-byte row ID per table, so there are a maximum number of rows equal to 248 or 281,474,976,710,656.
An InnoDB tablespace also has a limit on table size of 64 terabytes. How many rows fits into this depends on the size of each row.
The 64TB limit assumes the default page size of 16KB. You can increase the page size, and therefore increase the tablespace up to 256TB. But I think you'd find other performance factors make this inadvisable long before you grow a table to that size.
The top border of frame is of size 30.You can write code for printing the coordinate of any point on the frame using MouseInputAdapter.You will find when the cursor is just below the top border of the frame the y coordinate is not zero , its close to 30.Hence if you give size to frame 300 * 300 , the size available for putting the components on the frame is only 300 * 270.So if you need to have size 300 * 300 ,give 300 * 330 size of the frame.
In my case it was because I was using a port other than the default port 80. I was able to access the site locally using localhost but not on another machine using the IP address.
To solve the issue I had to add a firewall inbound rule to allow the port.
try this
lblMsg.Text = @"Your search result for <b style=""color:green;"">" + txtCode.Text.Trim() + "</b> ";
Though the installer answer is a good answer, it is not always practical when dealing with software you did not write. A simple answer is to create the log and the event source using the PowerShell command New-EventLog (http://technet.microsoft.com/en-us/library/hh849768.aspx)
Run PowerShell as an Administrator and run the following command changing out the log name and source that you need.
New-EventLog -LogName Application -Source TFSAggregator
I used it to solve the Event Log Exception when Aggregator runs issue from codeplex.
This will return to you a string excluding everything after the comma
str = str.Substring(0, str.IndexOf(','));
Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:
commaPos = str.IndexOf(',');
if(commaPos != -1)
str = str.Substring(0, commaPos)
I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int
, then do myInt.ToString()
like:
myInt = (int)double.Parse(myString)
This parses the double using the current culture (here in the US, we use .
for decimal points). However, this again assumes that your input string is can be parsed.
When it comes to memory usage, x86 is limited to circa 3 / 3,5 Gb, while x64 works fine with 4 Gb and more.
Moreover, when it comes to Windows, x86 will run on both X86 and x64 processors, while x64 requires x64 processor only.
I came across the same problem using a Wordpress page and plugin. This didn't work for the iframe plugin
[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730#?platform=iphone"]
but this does:
[iframe src="https://itunes.apple.com/gb/app/witch-hunt/id896152730" width="100%" height="480" ]
As you see,
I just left off the #?platform=iphone
part in the end.
var height = document.body.clientHeight;
var width = document.body.clientWidth;
Check: this article for better explanation.
You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python - for good reason!
The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! ;-)
And if you would tell us what your real problem is, you might even get a pythonic answer. "Getting something in one line" us usually not a programming problem.
I like the answer regarding passing functions around, its a very handy technique.
On the flip side you can also achieve this using pub/sub or using a variant, a dispatcher, as Flux does. The theory is super simple, have component 5 dispatch a message which component 3 is listening for. Component 3 then updates its state which triggers the re-render. This requires stateful components, which, depending on your viewpoint, may or may not be an anti-pattern. I'm against them personally and would rather that something else is listening for dispatches and changes state from the very top-down (Redux does this, but adds additional terminology).
import { Dispatcher } from flux
import { Component } from React
const dispatcher = new Dispatcher()
// Component 3
// Some methods, such as constructor, omitted for brevity
class StatefulParent extends Component {
state = {
text: 'foo'
}
componentDidMount() {
dispatcher.register( dispatch => {
if ( dispatch.type === 'change' ) {
this.setState({ text: 'bar' })
}
}
}
render() {
return <h1>{ this.state.text }</h1>
}
}
// Click handler
const onClick = event => {
dispatcher.dispatch({
type: 'change'
})
}
// Component 5 in your example
const StatelessChild = props => {
return <button onClick={ onClick }>Click me</button>
}
The dispatcher bundles with Flux is very simple, it simply registers callbacks and invokes them when any dispatch occurs, passing through the contents on the dispatch (in the above terse example there is no payload
with the dispatch, simply a message id). You could adapt this to traditional pub/sub (e.g. using the EventEmitter from events, or some other version) very easily if that makes more sense to you.
<script>
window.fbAsyncInit = function() {
FB.init({
appId :'your-app-id',
xfbml :true,
version :'v2.1'
});
};
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if(d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src ="// connect.facebook.net/en_US /sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}
(document,'script','facebook-jssdk'));
</script>
From the documentation: The Facebook SDK for JavaScript doesn't have any standalone files that need to be downloaded or installed, instead you simply need to include a short piece of regular JavaScript in your HTML tha
True
... and False
obviously.
Otherwise, None
evaluates to False, as does the integer 0
and also the float 0.0
(although I wouldn't use floats like that).
Also, empty lists []
, empty tuplets ()
, and empty strings ''
or ""
evaluate to False.
Try it yourself with the function bool()
:
bool([])
bool(['a value'])
bool('')
bool('A string')
bool(True) # ;-)
bool(False)
bool(0)
bool(None)
bool(0.0)
bool(1)
etc..
SKU can also refer to a unique identifier or code that refers to the particular stock keeping unit. These codes are not regulated or standardized. When a company receives items from a vendor, it has a choice of maintaining the vendor's SKU or creating its own.[2] This makes them distinct from Global Trade Item Number (GTIN), which are standard, global, tracking units. Universal Product Code (UPC), International Article Number (EAN), and Australian Product Number (APN) are special cases of GTINs.
curl -K myconfig.txt -o output.txt
Writes the first output received in the file you specify (overwrites if an old one exists).
curl -K myconfig.txt >> output.txt
Appends all output you receive to the specified file.
Note: The -K is optional.
You can also use pandas.Series.isin although it's a little bit longer than 'a' in s.values
:
In [2]: s = pd.Series(list('abc'))
In [3]: s
Out[3]:
0 a
1 b
2 c
dtype: object
In [3]: s.isin(['a'])
Out[3]:
0 True
1 False
2 False
dtype: bool
In [4]: s[s.isin(['a'])].empty
Out[4]: False
In [5]: s[s.isin(['z'])].empty
Out[5]: True
But this approach can be more flexible if you need to match multiple values at once for a DataFrame (see DataFrame.isin)
>>> df = DataFrame({'A': [1, 2, 3], 'B': [1, 4, 7]})
>>> df.isin({'A': [1, 3], 'B': [4, 7, 12]})
A B
0 True False # Note that B didn't match 1 here.
1 False True
2 True True
A few other things:
Don't forget that some numbers will repeat! so you need to do something like....
my totalQuestions was 47.
func getRandomNumbers(totalQuestions:Int) -> NSMutableArray
{
var arrayOfRandomQuestions: [Int] = []
print("arraySizeRequired = 40")
print("totalQuestions = \(totalQuestions)")
//This will output a 40 random numbers between 0 and totalQuestions (47)
while arrayOfRandomQuestions.count < 40
{
let limit: UInt32 = UInt32(totalQuestions)
let theRandomNumber = (Int(arc4random_uniform(limit)))
if arrayOfRandomQuestions.contains(theRandomNumber)
{
print("ping")
}
else
{
//item not found
arrayOfRandomQuestions.append(theRandomNumber)
}
}
print("Random Number set = \(arrayOfRandomQuestions)")
print("arrayOutputCount = \(arrayOfRandomQuestions.count)")
return arrayOfRandomQuestions as! NSMutableArray
}
Try this.
public enum Event {
FORGOT_PASSWORD("forgot password");
private final String value;
private Event(final String description) {
this.value = description;
}
private Event() {
this.value = this.name();
}
@JsonValue
final String value() {
return this.value;
}
}
You are not allowed to have div
tags between tr
tags. You have to look for some other strategies like creating a CSS class with display: none
and adding it to concerning rows or adding inline style display: none
to concerning rows.
.hidden
{
display:none;
}
<table>
<tr><td>I am visible</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
<tr class="hidden"><td>I am hidden using CSS class</td><tr>
</table>
or
<table>
<tr><td>I am visible</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
<tr style="display:none"><td>I am hidden using inline style</td><tr>
</table>
You want str replace, because performance-wise it's much cheaper and still fits your needs!
$title = str_replace( array( '\'', '"', ',' , ';', '<', '>' ), ' ', $rawtitle);
(Unless this is all about security and sql injection, in that case, I'd rather to go with a POSITIVE list of ALLOWED characters... even better, stick with tested, proven routines.)
Btw, since the OP talked about title-setting: I wouldn't replace special chars with nothing, but with a space. A superficious space is less of a problem than two words glued together...
I just created a removeAccents method based on the reading of this thread and this other one too (How to remove accents and turn letters into "plain" ASCII characters?).
The method is here: https://github.com/lingtalfi/Bat/blob/master/StringTool.md#removeaccents
Tests are here: https://github.com/lingtalfi/Bat/blob/master/btests/StringTool/removeAccents/stringTool.removeAccents.test.php,
and here is what was tested so far:
$a = [
// easy
'',
'a',
'après',
'dédé fait la fête ?',
// hard
'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
'ZZCNASLEÓzzcnasleó',
'qqqqZZCNASLEÓzzcnasleóqqq',
'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ',
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ',
'AaAaAaCcCcCcCcDdÐdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIJjKk',
'LlLlLl??LlNnNnNn?OoOoOoRrRrRrSsSsSsŠšTtTtTtUuUuUuUuUuUuWwYyŸZzZzŽž',
'?ƒOoUuAaIiOoUuUuUuUuUu????',
'??',
];
and it converts only accentuated things (letters/ligatures/cédilles/some letters with a line through/...?).
Here is the content of the method: (https://github.com/lingtalfi/Bat/blob/master/StringTool.php#L83)
public static function removeAccents($str)
{
static $map = [
// single letters
'à' => 'a',
'á' => 'a',
'â' => 'a',
'ã' => 'a',
'ä' => 'a',
'a' => 'a',
'å' => 'a',
'a' => 'a',
'a' => 'a',
'a' => 'a',
'?' => 'a',
'À' => 'A',
'Á' => 'A',
'Â' => 'A',
'Ã' => 'A',
'Ä' => 'A',
'A' => 'A',
'Å' => 'A',
'A' => 'A',
'A' => 'A',
'A' => 'A',
'?' => 'A',
'ç' => 'c',
'c' => 'c',
'c' => 'c',
'c' => 'c',
'c' => 'c',
'Ç' => 'C',
'C' => 'C',
'C' => 'C',
'C' => 'C',
'C' => 'C',
'd' => 'd',
'd' => 'd',
'Ð' => 'D',
'D' => 'D',
'Ð' => 'D',
'è' => 'e',
'é' => 'e',
'ê' => 'e',
'ë' => 'e',
'e' => 'e',
'e' => 'e',
'e' => 'e',
'e' => 'e',
'e' => 'e',
'È' => 'E',
'É' => 'E',
'Ê' => 'E',
'Ë' => 'E',
'E' => 'E',
'E' => 'E',
'E' => 'E',
'E' => 'E',
'E' => 'E',
'ƒ' => 'f',
'g' => 'g',
'g' => 'g',
'g' => 'g',
'g' => 'g',
'G' => 'G',
'G' => 'G',
'G' => 'G',
'G' => 'G',
'h' => 'h',
'h' => 'h',
'H' => 'H',
'H' => 'H',
'ì' => 'i',
'í' => 'i',
'î' => 'i',
'ï' => 'i',
'i' => 'i',
'i' => 'i',
'i' => 'i',
'i' => 'i',
'?' => 'i',
'i' => 'i',
'Ì' => 'I',
'Í' => 'I',
'Î' => 'I',
'Ï' => 'I',
'I' => 'I',
'I' => 'I',
'I' => 'I',
'I' => 'I',
'I' => 'I',
'I' => 'I',
'j' => 'j',
'J' => 'J',
'k' => 'k',
'K' => 'K',
'l' => 'l',
'l' => 'l',
'l' => 'l',
'l' => 'l',
'?' => 'l',
'L' => 'L',
'L' => 'L',
'L' => 'L',
'L' => 'L',
'?' => 'L',
'ñ' => 'n',
'n' => 'n',
'n' => 'n',
'n' => 'n',
'?' => 'n',
'Ñ' => 'N',
'N' => 'N',
'N' => 'N',
'N' => 'N',
'ò' => 'o',
'ó' => 'o',
'ô' => 'o',
'õ' => 'o',
'ö' => 'o',
'ð' => 'o',
'ø' => 'o',
'o' => 'o',
'o' => 'o',
'o' => 'o',
'o' => 'o',
'o' => 'o',
'?' => 'o',
'Ò' => 'O',
'Ó' => 'O',
'Ô' => 'O',
'Õ' => 'O',
'Ö' => 'O',
'Ø' => 'O',
'O' => 'O',
'O' => 'O',
'O' => 'O',
'O' => 'O',
'O' => 'O',
'?' => 'O',
'r' => 'r',
'r' => 'r',
'r' => 'r',
'R' => 'R',
'R' => 'R',
'R' => 'R',
's' => 's',
'š' => 's',
's' => 's',
's' => 's',
'S' => 'S',
'Š' => 'S',
'S' => 'S',
'S' => 'S',
't' => 't',
't' => 't',
't' => 't',
'T' => 'T',
'T' => 'T',
'T' => 'T',
'ù' => 'u',
'ú' => 'u',
'û' => 'u',
'ü' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'u' => 'u',
'Ù' => 'U',
'Ú' => 'U',
'Û' => 'U',
'Ü' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'U' => 'U',
'w' => 'w',
'W' => 'W',
'ý' => 'y',
'ÿ' => 'y',
'y' => 'y',
'Ý' => 'Y',
'Ÿ' => 'Y',
'Y' => 'Y',
'z' => 'z',
'z' => 'z',
'ž' => 'z',
'Z' => 'Z',
'Z' => 'Z',
'Ž' => 'Z',
// accentuated ligatures
'?' => 'A',
'?' => 'a',
];
return strtr($str, $map);
}
This worked for me: social.msdn.microsoft.com/Forums/en/transactsql/thread/02c6da90-954d-487d-a823-e24b891ec1b0?prof=required
if exists (
select * from tempdb.dbo.sysobjects o
where o.xtype in ('U')
and o.id = object_id(N'tempdb..#tempTable')
)
DROP TABLE #tempTable;
BATCH may not be able to do this, but you can use JScript or VBScript if you don't want to use tools that are not installed by default with Windows.
The first example on this page downloads a binary file in VBScript: http://www.robvanderwoude.com/vbstech_internet_download.php
This SO answer downloads a file using JScript (IMO, the better language): Windows Script Host (jscript): how do i download a binary file?
Your batch script can then just call out to a JScript or VBScript that downloads the file.
I found 2 reason for this issue:
Sometimes its because of multiple included libraries. For example you add
compile 'com.nineoldandroids:library:2.4.0'
in your gradle and add another library that it also use "nineoldandroids" in it's gradle!
If you have built an Android app and received this error, then congratulations, you have a lot of code!
So, why?
The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, including Android framework methods, library methods, and methods in your own code. Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration.
Then what should you do?
Avoiding the 65K Limit - How?
put
multiDexEnabled true
in the defaultConfig, buildType, or productFlavor sections of your Gradle build file.
2.In your manifest add the MultiDexApplication class from the multidex support library to the application element.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
Note: If your app uses extends the Application class, you can override the attachBaseContext() method and call MultiDex.install(this) to enable multidex. For more information, see the MultiDexApplication reference documentation.
Also this code may help you:
dexOptions {
javaMaxHeapSize "4g"
}
Put in your gradle(android{ ... } ).
Use the Debug.WriteLine
. This will display your message in the Output
window immediately. The only restriction is that you must run your test in Debug
mode.
[TestMethod]
public void TestMethod1()
{
Debug.WriteLine("Time {0}", DateTime.Now);
System.Threading.Thread.Sleep(30000);
Debug.WriteLine("Time {0}", DateTime.Now);
}
Output
The Question is already answered, but allow me to add from my side too.
First of all ++ means increment by one and -- means decrement by one.
Now x++ means Increment x after this line and ++x means Increment x before this line.
Check this Example
class Example {
public static void main (String args[]) {
int x=17,a,b;
a=x++;
b=++x;
System.out.println(“x=” + x +“a=” +a);
System.out.println(“x=” + x + “b=” +b);
a = x--;
b = --x;
System.out.println(“x=” + x + “a=” +a);
System.out.println(“x=” + x + “b=” +b);
}
}
It will give the following output:
x=19 a=17
x=19 b=19
x=18 a=19
x=17 b=17
Here is my use case, which requires an exceptional amount of encoding. Maybe you think it contrived, but we run this on production. Coincidently, this covers every type of encoding, so I'm posting as a tutorial.
Somebody just bought a prepaid gift card ("token") on our website. Tokens have corresponding URLs to redeem them. This customer wants to email the URL to someone else. Our web page includes a mailto
link that lets them do that.
// The order system generates some opaque token
$token = 'w%a&!e#"^2(^@azW';
// Here is a URL to redeem that token
$redeemUrl = 'https://httpbin.org/get?token=' . urlencode($token);
// Actual contents we want for the email
$subject = 'I just bought this for you';
$body = 'Please enter your shipping details here: ' . $redeemUrl;
// A URI for the email as prescribed
$mailToUri = 'mailto:?subject=' . rawurlencode($subject) . '&body=' . rawurlencode($body);
// Print an HTML element with that mailto link
echo '<a href="' . htmlspecialchars($mailToUri) . '">Email your friend</a>';
Note: the above assumes you are outputting to a text/html
document. If your output media type is text/json
then simply use $retval['url'] = $mailToUri;
because output encoding is handled by json_encode()
.
You should see:
"args": {
"token": "w%a&!e#\"^2(^@azW"
},
And of course this is the JSON representation of $token
above.
As per the documentation, you need to specify true
as the second argument if you want an associative array instead of an object from json_decode
. This would be the code:
$result = json_decode($jsondata, true);
If you want integer
keys instead of whatever the property names are:
$result = array_values(json_decode($jsondata, true));
However, with your current decode you just access it as an object:
print_r($obj->Result);
This will allow file names to have spaces (reproducible example).
# Select files of interest, here, only text files for ex.
find -type f -exec file {} \; > findresult.txt
grep ": ASCII text$" findresult.txt > textfiles.txt
# leave only the path to the file removing suffix and prefix
sed -i -e 's/:.*$//' textfiles.txt
sed -i -e 's/\.\///' textfiles.txt
#write a script that deletes the files in textfiles.txt
IFS_backup=$IFS
IFS=$(echo "\n\b")
for f in $(cat textfiles.txt);
do
rm "$f";
done
IFS=$IFS_backup
# save script as "some.sh" and run: sh some.sh
For anyone else wondering how to achieve this, here is my extended EditText
class EditTextNumeric
.
.setMaxLength(int)
- sets maximum number of digits
.setMaxValue(int)
- limit maximum integer value
.setMin(int)
- limit minimum integer value
.getValue()
- get integer value
import android.content.Context;
import android.text.InputFilter;
import android.text.InputType;
import android.widget.EditText;
public class EditTextNumeric extends EditText {
protected int max_value = Integer.MAX_VALUE;
protected int min_value = Integer.MIN_VALUE;
// constructor
public EditTextNumeric(Context context) {
super(context);
this.setInputType(InputType.TYPE_CLASS_NUMBER);
}
// checks whether the limits are set and corrects them if not within limits
@Override
protected void onTextChanged(CharSequence text, int start, int before, int after) {
if (max_value != Integer.MAX_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) > max_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(max_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
if (min_value != Integer.MIN_VALUE) {
try {
if (Integer.parseInt(this.getText().toString()) < min_value) {
// change value and keep cursor position
int selection = this.getSelectionStart();
this.setText(String.valueOf(min_value));
if (selection >= this.getText().toString().length()) {
selection = this.getText().toString().length();
}
this.setSelection(selection);
}
} catch (NumberFormatException exception) {
super.onTextChanged(text, start, before, after);
}
}
super.onTextChanged(text, start, before, after);
}
// set the max number of digits the user can enter
public void setMaxLength(int length) {
InputFilter[] FilterArray = new InputFilter[1];
FilterArray[0] = new InputFilter.LengthFilter(length);
this.setFilters(FilterArray);
}
// set the maximum integer value the user can enter.
// if exeeded, input value will become equal to the set limit
public void setMaxValue(int value) {
max_value = value;
}
// set the minimum integer value the user can enter.
// if entered value is inferior, input value will become equal to the set limit
public void setMinValue(int value) {
min_value = value;
}
// returns integer value or 0 if errorous value
public int getValue() {
try {
return Integer.parseInt(this.getText().toString());
} catch (NumberFormatException exception) {
return 0;
}
}
}
Example usage:
final EditTextNumeric input = new EditTextNumeric(this);
input.setMaxLength(5);
input.setMaxValue(total_pages);
input.setMinValue(1);
All other methods and attributes that apply to EditText
, of course work too.
For me the navigate works just NO XAMARIN SOLUTIONS. That suggestions here DIDN´T WORKS. :( Devenv.exe /resetuserdata not works for me.
My solution was: Re-create the solutions, project, folders and works. No import. Detail: my project was on the VS 2015, the error was on the VS 2017.
You can also choose to break explicitly in code:
// Assuming C#
if (condition)
{
System.Diagnostics.Debugger.Break();
}
From MSDN:
Debugger.Break: If no debugger is attached, users are asked if they want to attach a debugger. If yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit.
This is only a fallback, though. Setting a conditional breakpoint in Visual Studio, as described in other comments, is a better choice.
I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).
So I modified Stephan Muller's answer slightly:
A datalist with non-unique values:
<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
<option value="42">The answer</option>
<option value="43">The answer</option>
<option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">
When the user selects an option, the browser replaces input.value
with the value
of the datalist
option instead of the innerText
.
The following code then checks for an option
with that value
, pushes that into the hidden field and replaces the input.value
with the innerText
.
document.querySelector('#answerInput').addEventListener('input', function(e) {
var input = e.target,
list = input.getAttribute('list'),
options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');
if (options.length > 0) {
hiddenInput.value = input.value;
input.value = options[0].innerText;
}
});
As a consequence the user sees whatever the option's innerText
says, but the unique id from option.value
is available upon form submit.
Demo jsFiddle
Generally speaking, people refer to an application's presentation layer as its front end, its persistence layer (database, usually) as the back end, and anything between as middle tier. This set of ideas is often referred to as 3-tier architecture. They let you separate your application into more easily comprehensible (and testable!) chunks; you can also reuse lower-tier code more easily in higher tiers.
Which code is part of which tier is somewhat subjective; graphic designers tend to think of everything that isn't presentation as the back end, database people think of everything in front of the database as the front end, and so on.
Not all applications need to be separated out this way, though. It's certainly more work to have 3 separate sub-projects than it is to just open index.php and get cracking; depending on (1) how long you expect to have to maintain the app (2) how complex you expect the app to get, you may want to forgo the complexity.
your 8080 port is already used by another application 1/ you can try to find out which app is using it, using "netstat -aon" and stop the process; 2/ you can go to server.xml and change from port 8080 to another one (ex: 8081)
I found the AXMLPrinter2, a Java app over at the Android4Me project to work fine on the AndroidManifest.xml that I had (and prints the XML out in a nicely formatted way). http://code.google.com/p/android4me/downloads/detail?name=AXMLPrinter2.jar
One note.. it (and the code on this answer from Ribo) doesn't appear to handle every compiled XML file that I've come across. I found one where the strings were stored with one byte per character, rather than the double byte format that it assumes.
I want to add, who needs full custom header functionality
function addSearchControls(json) {
$("#tblCalls thead").append($("#tblCalls thead tr:first").clone());
$("#tblCalls thead tr:eq(1) th").each(function (index) {
// For text inputs
if (index != 1 && index != 2) {
$(this).replaceWith('<th><input type="text" placeholder=" ' + $(this).html() + ' ara"></input></th>');
var searchControl = $("#tblCalls thead tr:eq(1) th:eq(" + index + ") input");
searchControl.on("keyup", function () {
table.column(index).search(searchControl.val()).draw();
})
}
// For DatePicker inputs
else if (index == 1) {
$(this).replaceWith('<th><input type="text" id="datepicker" placeholder="' + $(this).html() + ' ara" class="tblCalls-search-date datepicker" /></th>');
$('.tblCalls-search-date').on('keyup click change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(v).draw();
});
$(".datepicker").datepicker({
dateFormat: "dd-mm-yy",
altFieldTimeOnly: false,
altFormat: "yy-mm-dd",
altTimeFormat: "h:m",
altField: "#tarih-db",
monthNames: ["Ocak", "Subat", "Mart", "Nisan", "Mayis", "Haziran", "Temmuz", "Agustos", "Eylül", "Ekim", "Kasim", "Aralik"],
dayNamesMin: ["Pa", "Pt", "Sl", "Ça", "Pe", "Cu", "Ct"],
firstDay: 1,
dateFormat: "yy-mm-dd",
showOn: "button",
showAnim: 'slideDown',
showButtonPanel: true,
autoSize: true,
buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
buttonImageOnly: false,
buttonText: "Tarih Seçiniz",
closeText: "Temizle"
});
$(document).on("click", ".ui-datepicker-close", function () {
$('.datepicker').val("");
table.columns(5).search("").draw();
});
}
// For DropDown inputs
else if (index == 2) {
$(this).replaceWith('<th><select id="filter_comparator" class="styled-select yellow rounded"><option value="select">Seç</option><option value="eq">=</option><option value="gt">>=</option><option value="lt"><=</option><option value="ne">!=</option></select><input type="text" id="filter_value"></th>');
var selectedOperator;
$('#filter_comparator').on('change', function () {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
selectedOperator = v;
if(v=="select")
table.columns(index).search('select|0').draw();
$('#filter_value').val("");
});
$('#filter_value').on('keyup click change', function () {
var keycode = (event.keyCode ? event.keyCode : event.which);
if (keycode == '13') {
var i = $(this).attr('id'); // getting column index
var v = $(this).val(); // getting search input value
table.columns(index).search(selectedOperator + '|' + v).draw();
}
});
}
})
}
Another forum provided this answer:
Ahh, figured this out. The following system properties need to be set, so that the "logging.properties" file can be picked up.
Assuming that the tomcat is located under an Eclipse project, add the following under the "Arguments" tab of its launch configuration:
-Dcatalina.base="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Dcatalina.home="${project_loc}\<apache-tomcat-5.5.23_loc>"
-Djava.util.logging.config.file="${project_loc}\<apache-tomcat-5.5.23_loc>\conf\logging.properties"
-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager
http://www.coderanch.com/t/442412/Tomcat/Tweaking-tomcat-logging-properties-file
Sqliteopenhelper's method have methods create and upgrade,create is used when any table is first time created and upgrade method will called everytime whenever table's number of column is changed.
A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.
Only the following headers are allowed cross domain:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type
any others cause a "pre-flight" request to be issued in CORS supported browsers.
Without CORS it is not possible to add X-Requested-With
to a cross domain XHR request.
If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin
header could be an option in supported browsers, although you will leave old browsers vulnerable.)
You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.
OWASP Recommend combining this with an Origin and Referer check:
This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)
However, for the reasons already discussed checking Origin can be tricky.
Written a more in depth blog post on CORS, CSRF and X-Requested-With here.
I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.
$(document).ready(function() {
var myContent = '<div id="test">Hello <span>world!</span></div>';
alert(myContent.replace(/(<([^>]+)>)/ig,""));
});
Swift
// remove left buttons (in case you added some)
self.navigationItem.leftBarButtonItems = []
// hide the default back buttons
self.navigationItem.hidesBackButton = true
I think i have the easiest approach... on pressing new in B..
Intent intent = new Intent(B.this, A.class);
intent.putExtra("NewClicked", true);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
and in A get it
if (getIntent().getBooleanExtra("NewClicked", false)) {
finish();// finish yourself and make a create a new Instance of yours.
Intent intent = new Intent(A.this,A.class);
startActivity(intent);
}
Get the number of days, then divide by 365.2425 (the mean Gregorian year) for years. Divide by 30.436875 (the mean Gregorian month) for months.
Short answer: You can't. rm
removes files blindly, with no concept of 'trash'.
Some Unix and Linux systems try to limit its destructive ability by aliasing it to rm -i
by default, but not all do.
Long answer: Depending on your filesystem, disk activity, and how long ago the deletion occured, you may be able to recover some or all of what you deleted. If you're using an EXT3 or EXT4 formatted drive, you can check out extundelete
.
In the future, use rm
with caution. Either create a del
alias that provides interactivity, or use a file manager.
One of the biggest problems with delivering live events on Internet is 'scale', and TCP doesn’t scale well. For example when you are beaming a live football match -as opposed to an on demand movie playback- the number of people watching can easily be 1000 times more. In such a scenario using TCP is a death sentence for the CDNs (content delivery networks).
There are a couple of main reasons why TCP doesn't scale well:
One of the largest tradeoffs of TCP is the variability of throughput achievable between the sender and the receiver. When streaming video over the Internet the video packets must traverse multiple routers over the Internet, each of these routers is connected with different speed connections. The TCP algorithm starts with TCP window off small, then grows until packet loss is detected, the packet loss is considered a sign of congestion and TCP responds to it by drastically reducing the window size to avoid congestion. Thus in turn reducing the effective throughput immediately. Now imagine a network with TCP transmission using 6-7 router hops to the client (a very normal scenario), if any of the intermediate router looses any packet, the TCP for that link will reduce the transmission rate. In-fact The traffic flow between routers follow an hourglass kind of a shape; always gong up and down in-between one of the intermediate routers. Rendering the effective through put much lower compared to best-effort UDP.
As you may already know TCP is an acknowledgement-based protocol. Lets for example say a sender is 50ms away (i.e. latency btw two points). This would mean time it takes for a packet to be sent to a receiver and receiver to send an acknowledgement would be 100ms; thus maximum throughput possible as compared to UDP based transmission is already halved.
The TCP doesn’t support multicasting or the new emerging standard of multicasting AMT. Which means the CDNs don’t have the opportunity to reduce network traffic by replicating the packets -when many clients are watching the same content. That itself is a big enough reason for CDNs (like Akamai or Level3) to not go with TCP for live streams.
create a global temp table with a GUID in the name dynamically. Then you can work with it in your code, via dyn sql, without worry that another process calling same sproc will use it. This is useful when you dont know what to expect from the underlying selected table each time it runs so you cannot created a temp table explicitly beforehand. ie - you need to use SELECT * INTO syntax
DECLARE @TmpGlobalTable varchar(255) = 'SomeText_' + convert(varchar(36),NEWID())
-- select @TmpGlobalTable
-- build query
SET @Sql =
'SELECT * INTO [##' + @TmpGlobalTable + '] FROM SomeTable'
EXEC (@Sql)
EXEC ('SELECT * FROM [##' + @TmpGlobalTable + '] ')
EXEC ('DROP TABLE [##' + @TmpGlobalTable + ']')
PRINT 'Dropped Table ' + @TmpGlobalTable
I use my own custom function...
public function areNull() {
if (func_num_args() == 0) return false;
$arguments = func_get_args();
foreach ($arguments as $argument):
if (is_null($argument)) return true;
endforeach;
return false;
}
$var = areNull("username", "password", "etc");
I'm sure it can easily be changed for you scenario. Basically it returns true if any of the values are NULL, so you could change it to empty or whatever.
This works for me in Visual Studio 2015.
I copy all DLL files from a folder located in a library folder on the same level as my solution folder into the targetdirectory of the project being built.
Using a relative path from my project directory and going up the folder structure two steps with..\..\lib
MySolutionFolder
....MyProject
Lib
if $(ConfigurationName) == Debug (
xcopy /Y "$(ProjectDir)..\..\lib\*.dll" "$(TargetDir)"
) ELSE (echo "Not Debug mode, no file copy from lib")
use this:
pil_image = PIL.Image.open('Image.jpg').convert('RGB')
open_cv_image = numpy.array(pil_image)
# Convert RGB to BGR
open_cv_image = open_cv_image[:, :, ::-1].copy()
I was also confused about them. See this example below:
<Window x:Class="WpfApplicationWPF.CommandsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CommandsWindow" Height="300" Width="300">
<StackPanel>
<Button Name="ButtonNew"
Click="ButtonNew_Click"
Background="{DynamicResource PinkBrush}">NEW</Button>
<Image Name="ImageNew"
Source="pack://application:,,,/images/winter.jpg"></Image>
</StackPanel>
<Window.Background>
<DynamicResource ResourceKey="PinkBrush"></DynamicResource>
</Window.Background>
</Window>
Here I have used dynamic resource for button and window and have not declared it anywhere.Upon runtime, the ResourceDictionary of the hierarchy will be checked.Since I have not defined it, I guess the default will be used.
If I add the code below to click event of Button, since they use DynamicResource, the background will be updated accordingly.
private void ButtonNew_Click(object sender, RoutedEventArgs e)
{
this.Resources.Add( "PinkBrush"
,new SolidColorBrush(SystemColors.DesktopColor)
);
}
If they had used StaticResource:
Hope I cleared some confusion.
If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->
$searchResultQuery = Users::query();
$searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
$searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null
Or with scope in model :
public function scopeNotNullOnly($query){
return $query->where('status_message', '<>', '');
}
I had some decrypted byte arrays with padding characters and other stuff I didn't need, so I did this (probably not perfect, but it works for my limited use)
var junk = String.fromCharCode.apply(null, res).split('').map(char => char.charCodeAt(0) <= 127 && char.charCodeAt(0) >= 32 ? char : '').join('');
✗
✗
✘
✘
✕
✕
✖
✖
I had a different, but similar problem with Facebook recently, and found that the scraper/debug page mentioned, simply does not appear to read any page in its entirety. My meta properties for Open Graph were further down in the head section, and the scraper would constantly inform me that the image specification was not correct, and would use a cached version regardless. I moved the Open Graph tags further up in the code, near the very top of the page, and then everything worked perfectly, every time.
CSS PLaY | cross browser fixed header/footer/centered single column layout
CSS Frames, version 2: Example 2, specified width | 456 Berea Street
One important thing is that although this sounds easy, there's going to be quite a bit of ugly code going into your CSS file to get an effect like this. Unfortunately, it really is the only option.
I followed @user2314737's advice (his answer is on page 1) and enabled "Show debug information" under "Config" that after a restart of xampp showed me that my install path had a space " " in it which wasn't allowed.
My path was D:\Program files (x86)\xampp\ so I reinstalled it to D:\xampp\ and then it worked.
You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:
Option Explicit
Sub GetUnique()
Dim rng As Range
Dim myarray, myunique
Dim i As Integer
ReDim myunique(1)
With ThisWorkbook.Sheets("Sheet1")
Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
myarray = Application.Transpose(rng)
For i = LBound(myarray) To UBound(myarray)
If IsError(Application.Match(myarray(i), myunique, 0)) Then
myunique(UBound(myunique)) = myarray(i)
ReDim Preserve myunique(UBound(myunique) + 1)
End If
Next
End With
For i = LBound(myunique) To UBound(myunique)
Debug.Print myunique(i)
Next
End Sub
This uses array instead of range.
It also uses Match
function instead of a nested For Loop
.
I didn't have the time to check the time difference though.
So I leave the testing to you.
And this seems to be a much more complete list, where I found some warnings specific to Android-Studio that I couldn't find elsewhere (e.g. SynchronizeOnNonFinalField)
https://jazzy.id.au/2008/10/30/list_of_suppresswarnings_arguments.html
Oh, now SO's guidelines contraddict SO's restrictions. On one hand, I am supposed to copy the list rather than providing only the link. But on the other hand, this would exceed the maximum allowed number of characters. So let's just hope the link won't break.
This was working for me so Try This: $ad->getcodes()->distinct('pid')->count()
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
If you want to merge changes in SubBranch to MainBranch
git checkout MainBranch
git merge SubBranch
Here is a jQuery plugin to set the heights of multiple divs to be the same. And below is the actual code of the plugin.
$.fn.equalHeights = function(px) {
$(this).each(function(){
var currentTallest = 0;
$(this).children().each(function(i){
if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
});
if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
// for ie6, set height since min-height isn't supported
if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
$(this).children().css({'min-height': currentTallest});
});
return this;
};
Okay guys another sleek option is
Application.Context.ApplicationInfo.NonLocalizedLabel
verified for hard coded android label on application element.
<application android:label="Big App"></application>
Reference: http://developer.android.com/reference/android/content/pm/PackageItemInfo.html#nonLocalizedLabel
Why involve Notepad?
Sub ReplaceStringInFile()
Dim sBuf As String
Dim sTemp As String
Dim iFileNum As Integer
Dim sFileName As String
' Edit as needed
sFileName = "C:\Temp\test.txt"
iFileNum = FreeFile
Open sFileName For Input As iFileNum
Do Until EOF(iFileNum)
Line Input #iFileNum, sBuf
sTemp = sTemp & sBuf & vbCrLf
Loop
Close iFileNum
sTemp = Replace(sTemp, "THIS", "THAT")
iFileNum = FreeFile
Open sFileName For Output As iFileNum
Print #iFileNum, sTemp
Close iFileNum
End Sub
Your method (placing script before the closing body tag)
<script>
myFunction()
</script>
</body>
</html>
is a reliable way to support old and new browsers.
os.unlink(path, *, dir_fd=None)
or
os.remove(path, *, dir_fd=None)
Both functions are semantically same. This functions removes (deletes) the file path. If path is not a file and it is directory, then exception is raised.
shutil.rmtree(path, ignore_errors=False, onerror=None)
or
os.rmdir(path, *, dir_fd=None)
In order to remove whole directory trees, shutil.rmtree()
can be used. os.rmdir
only works when the directory is empty and exists.
os.removedirs(name)
It remove every empty parent directory with self until parent which has some content
ex. os.removedirs('abc/xyz/pqr') will remove the directories by order 'abc/xyz/pqr', 'abc/xyz' and 'abc' if they are empty.
For more info check official doc: os.unlink
, os.remove
, os.rmdir
, shutil.rmtree
, os.removedirs
Try + (instancetype)appearance of UITableView:
Objective-C:
[[UITableView appearance] setSeparatorColor:[UIColor blackColor]]; // set your desired colour in place of "[UIColor blackColor]"
Swift 3.0:
UITableView.appearance().separatorColor = UIColor.black // set your desired colour in place of "UIColor.black"
Note: Change will reflect to all tables used in application.
To put it all together, this is what it should look like:
In the controller:
List<Fund> fundList = db.Funds.ToList();
ViewBag.Funds = fundList;
Then in the view:
@foreach (var item in ViewBag.Funds)
{
<span> @item.FundName </span>
}
I got this error after deleting Xcode. I fixed it by resetting the command line tools path with sudo xcode-select -r
.
Before:
navin@Radiant ~$ /usr/bin/clang
xcrun: error: active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist
Use `sudo xcode-select --switch path/to/Xcode.app` to specify the Xcode that you wish to use for command line developer tools, or use `xcode-select --install` to install the standalone command line developer tools.
See `man xcode-select` for more details.
navin@Radiant ~$ xcode-select --install
xcode-select: error: command line tools are already installed, use "Software Update" to install updates
After:
navin@Radiant ~$ /usr/bin/clang
clang: error: no input files
To check for assignability, you can use the Type.IsAssignableFrom
method:
typeof(SomeType).IsAssignableFrom(typeof(Derived))
This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.
To check for strict inheritance, you can use Type.IsSubclassOf
:
typeof(Derived).IsSubclassOf(typeof(SomeType))
try this:
public boolean verifyPwd(){
if (!(pword.equals(pwdRetypePwd.getText()))){
txtaError.setEditable(true);
txtaError.setText("*Password didn't match!");
txtaError.setForeground(Color.red);
txtaError.setEditable(false);
return false;
}
else {
return true;
}
}
if (verifyPwd()==true){
addNewUser();
}
else {
// passwords do not match
}
If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:
import requests
...
def application(environ, start_response):
cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
response_headers = [('Content-type', 'text/plain')]
response_headers.append(('Set-Cookie',cookie))
...
return [bytes(post_env),response_headers]
I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.
I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).
Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)
Check out https://github.com/131/h264-live-player on github.